Require target lra in gcc.c-torture/compile/asmgoto-6.c
[official-gcc.git] / gcc / cp / pt.cc
blob21b08a6266a57268e5d1eb13c6798697467e133e
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, bool = true);
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 gen_templ = most_general_template (templ);
10349 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10350 arglist = add_outermost_template_args (templ, arglist);
10351 arglist = coerce_template_parms (parms, arglist, templ, complain);
10352 if (arglist == error_mark_node)
10353 return error_mark_node;
10355 /* The type of the expression is NULL_TREE since the template-id could refer
10356 to an explicit or partial specialization. */
10357 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10360 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10361 not dependent. */
10363 tree
10364 finish_template_variable (tree var, tsubst_flags_t complain)
10366 tree templ = TREE_OPERAND (var, 0);
10367 tree arglist = TREE_OPERAND (var, 1);
10369 /* If the template or arguments are dependent, then we
10370 can't resolve the TEMPLATE_ID_EXPR yet. */
10371 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10372 || any_dependent_template_arguments_p (arglist))
10373 return var;
10375 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10377 if (complain & tf_error)
10379 auto_diagnostic_group d;
10380 error ("use of invalid variable template %qE", var);
10381 diagnose_constraints (location_of (var), templ, arglist);
10383 return error_mark_node;
10386 return instantiate_template (templ, arglist, complain);
10389 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10390 TARGS template args, and instantiate it if it's not dependent. */
10392 tree
10393 lookup_and_finish_template_variable (tree templ, tree targs,
10394 tsubst_flags_t complain)
10396 tree var = lookup_template_variable (templ, targs, complain);
10397 if (var == error_mark_node)
10398 return error_mark_node;
10399 /* We may be called while doing a partial substitution, but the
10400 type of the variable template may be auto, in which case we
10401 will call do_auto_deduction in mark_used (which clears tf_partial)
10402 and the auto must be properly reduced at that time for the
10403 deduction to work. */
10404 complain &= ~tf_partial;
10405 var = finish_template_variable (var, complain);
10406 mark_used (var);
10407 return var;
10410 /* If the set of template parameters PARMS contains a template parameter
10411 at the given LEVEL and INDEX, then return this parameter. Otherwise
10412 return NULL_TREE. */
10414 static tree
10415 corresponding_template_parameter_list (tree parms, int level, int index)
10417 while (TMPL_PARMS_DEPTH (parms) > level)
10418 parms = TREE_CHAIN (parms);
10420 if (TMPL_PARMS_DEPTH (parms) != level
10421 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10422 return NULL_TREE;
10424 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10427 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10428 corresponds to the template parameter PARM, or else return NULL_TREE. */
10430 static tree
10431 corresponding_template_parameter_list (tree parms, tree parm)
10433 int level, index;
10434 template_parm_level_and_index (parm, &level, &index);
10435 return corresponding_template_parameter_list (parms, level, index);
10438 /* As above, but pull out the actual parameter. */
10440 static tree
10441 corresponding_template_parameter (tree parms, tree parm)
10443 tree list = corresponding_template_parameter_list (parms, parm);
10444 if (!list)
10445 return NULL_TREE;
10447 tree t = TREE_VALUE (list);
10448 /* As in template_parm_to_arg. */
10449 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10450 t = TREE_TYPE (t);
10451 else
10452 t = DECL_INITIAL (t);
10454 gcc_assert (TEMPLATE_PARM_P (t));
10455 return t;
10458 struct pair_fn_data
10460 tree_fn_t fn;
10461 tree_fn_t any_fn;
10462 void *data;
10463 /* True when we should also visit template parameters that occur in
10464 non-deduced contexts. */
10465 bool include_nondeduced_p;
10466 hash_set<tree> *visited;
10469 /* Called from for_each_template_parm via walk_tree. */
10471 static tree
10472 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10474 tree t = *tp;
10475 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10476 tree_fn_t fn = pfd->fn;
10477 void *data = pfd->data;
10478 tree result = NULL_TREE;
10480 #define WALK_SUBTREE(NODE) \
10481 do \
10483 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10484 pfd->include_nondeduced_p, \
10485 pfd->any_fn); \
10486 if (result) goto out; \
10488 while (0)
10490 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10491 return t;
10493 if (TYPE_P (t)
10494 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10495 WALK_SUBTREE (TYPE_CONTEXT (t));
10497 switch (TREE_CODE (t))
10499 case RECORD_TYPE:
10500 if (TYPE_PTRMEMFUNC_P (t))
10501 break;
10502 /* Fall through. */
10504 case UNION_TYPE:
10505 case ENUMERAL_TYPE:
10506 if (!TYPE_TEMPLATE_INFO (t))
10507 *walk_subtrees = 0;
10508 else
10509 WALK_SUBTREE (TYPE_TI_ARGS (t));
10510 break;
10512 case INTEGER_TYPE:
10513 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10514 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10515 break;
10517 case METHOD_TYPE:
10518 /* Since we're not going to walk subtrees, we have to do this
10519 explicitly here. */
10520 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10521 /* Fall through. */
10523 case FUNCTION_TYPE:
10524 /* Check the return type. */
10525 WALK_SUBTREE (TREE_TYPE (t));
10527 /* Check the parameter types. Since default arguments are not
10528 instantiated until they are needed, the TYPE_ARG_TYPES may
10529 contain expressions that involve template parameters. But,
10530 no-one should be looking at them yet. And, once they're
10531 instantiated, they don't contain template parameters, so
10532 there's no point in looking at them then, either. */
10534 tree parm;
10536 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10537 WALK_SUBTREE (TREE_VALUE (parm));
10539 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10540 want walk_tree walking into them itself. */
10541 *walk_subtrees = 0;
10544 if (flag_noexcept_type)
10546 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10547 if (spec)
10548 WALK_SUBTREE (TREE_PURPOSE (spec));
10550 break;
10552 case TYPEOF_TYPE:
10553 case DECLTYPE_TYPE:
10554 if (pfd->include_nondeduced_p
10555 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10556 pfd->visited,
10557 pfd->include_nondeduced_p,
10558 pfd->any_fn))
10559 return error_mark_node;
10560 *walk_subtrees = false;
10561 break;
10563 case TRAIT_TYPE:
10564 if (pfd->include_nondeduced_p)
10566 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10567 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10569 *walk_subtrees = false;
10570 break;
10572 case FUNCTION_DECL:
10573 case VAR_DECL:
10574 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10575 WALK_SUBTREE (DECL_TI_ARGS (t));
10576 break;
10578 case PARM_DECL:
10579 WALK_SUBTREE (TREE_TYPE (t));
10580 break;
10582 case CONST_DECL:
10583 if (DECL_TEMPLATE_PARM_P (t))
10584 WALK_SUBTREE (DECL_INITIAL (t));
10585 if (DECL_CONTEXT (t)
10586 && pfd->include_nondeduced_p)
10587 WALK_SUBTREE (DECL_CONTEXT (t));
10588 break;
10590 case BOUND_TEMPLATE_TEMPLATE_PARM:
10591 /* Record template parameters such as `T' inside `TT<T>'. */
10592 WALK_SUBTREE (TYPE_TI_ARGS (t));
10593 /* Fall through. */
10595 case TEMPLATE_TEMPLATE_PARM:
10596 case TEMPLATE_TYPE_PARM:
10597 case TEMPLATE_PARM_INDEX:
10598 if (fn && (*fn)(t, data))
10599 return t;
10600 else if (!fn)
10601 return t;
10602 break;
10604 case TEMPLATE_DECL:
10605 /* A template template parameter is encountered. */
10606 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10607 WALK_SUBTREE (TREE_TYPE (t));
10609 /* Already substituted template template parameter */
10610 *walk_subtrees = 0;
10611 break;
10613 case TYPENAME_TYPE:
10614 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10615 partial instantiation. */
10616 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10617 *walk_subtrees = 0;
10618 break;
10620 case INDIRECT_REF:
10621 case COMPONENT_REF:
10622 /* If there's no type, then this thing must be some expression
10623 involving template parameters. */
10624 if (!fn && !TREE_TYPE (t))
10625 return error_mark_node;
10626 break;
10628 case CONSTRUCTOR:
10629 case TRAIT_EXPR:
10630 case PLUS_EXPR:
10631 case MULT_EXPR:
10632 case SCOPE_REF:
10633 /* These are non-deduced contexts. */
10634 if (!pfd->include_nondeduced_p)
10635 *walk_subtrees = 0;
10636 break;
10638 case MODOP_EXPR:
10639 case CAST_EXPR:
10640 case IMPLICIT_CONV_EXPR:
10641 case REINTERPRET_CAST_EXPR:
10642 case CONST_CAST_EXPR:
10643 case STATIC_CAST_EXPR:
10644 case DYNAMIC_CAST_EXPR:
10645 case ARROW_EXPR:
10646 case DOTSTAR_EXPR:
10647 case TYPEID_EXPR:
10648 case PSEUDO_DTOR_EXPR:
10649 if (!fn)
10650 return error_mark_node;
10651 break;
10653 default:
10654 break;
10657 #undef WALK_SUBTREE
10659 /* We didn't find any template parameters we liked. */
10660 out:
10661 return result;
10664 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10665 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10666 call FN with the parameter and the DATA.
10667 If FN returns nonzero, the iteration is terminated, and
10668 for_each_template_parm returns 1. Otherwise, the iteration
10669 continues. If FN never returns a nonzero value, the value
10670 returned by for_each_template_parm is 0. If FN is NULL, it is
10671 considered to be the function which always returns 1.
10673 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10674 parameters that occur in non-deduced contexts. When false, only
10675 visits those template parameters that can be deduced. */
10677 static tree
10678 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10679 hash_set<tree> *visited,
10680 bool include_nondeduced_p,
10681 tree_fn_t any_fn)
10683 struct pair_fn_data pfd;
10684 tree result;
10686 /* Set up. */
10687 pfd.fn = fn;
10688 pfd.any_fn = any_fn;
10689 pfd.data = data;
10690 pfd.include_nondeduced_p = include_nondeduced_p;
10692 /* Walk the tree. (Conceptually, we would like to walk without
10693 duplicates, but for_each_template_parm_r recursively calls
10694 for_each_template_parm, so we would need to reorganize a fair
10695 bit to use walk_tree_without_duplicates, so we keep our own
10696 visited list.) */
10697 if (visited)
10698 pfd.visited = visited;
10699 else
10700 pfd.visited = new hash_set<tree>;
10701 result = cp_walk_tree (&t,
10702 for_each_template_parm_r,
10703 &pfd,
10704 pfd.visited);
10706 /* Clean up. */
10707 if (!visited)
10709 delete pfd.visited;
10710 pfd.visited = 0;
10713 return result;
10716 struct find_template_parameter_info
10718 explicit find_template_parameter_info (tree ctx_parms)
10719 : ctx_parms (ctx_parms),
10720 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10723 hash_set<tree> visited;
10724 hash_set<tree> parms;
10725 tree parm_list = NULL_TREE;
10726 tree *parm_list_tail = &parm_list;
10727 tree ctx_parms;
10728 int max_depth;
10730 tree find_in (tree);
10731 tree find_in_recursive (tree);
10732 bool found (tree);
10733 unsigned num_found () { return parms.elements (); }
10736 /* Appends the declaration of T to the list in DATA. */
10738 static int
10739 keep_template_parm (tree t, void* data)
10741 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10743 /* Template parameters declared within the expression are not part of
10744 the parameter mapping. For example, in this concept:
10746 template<typename T>
10747 concept C = requires { <expr> } -> same_as<int>;
10749 the return specifier same_as<int> declares a new decltype parameter
10750 that must not be part of the parameter mapping. The same is true
10751 for generic lambda parameters, lambda template parameters, etc. */
10752 int level;
10753 int index;
10754 template_parm_level_and_index (t, &level, &index);
10755 if (level == 0 || level > ftpi->max_depth)
10756 return 0;
10758 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10759 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10760 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10761 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10763 /* This template parameter might be an argument to a cached dependent
10764 specalization that was formed earlier inside some other template, in
10765 which case the parameter is not among the ones that are in-scope.
10766 Look in CTX_PARMS to find the corresponding in-scope template
10767 parameter, and use it instead. */
10768 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10769 t = in_scope;
10771 /* Arguments like const T yield parameters like const T. This means that
10772 a template-id like X<T, const T> would yield two distinct parameters:
10773 T and const T. Adjust types to their unqualified versions. */
10774 if (TYPE_P (t))
10775 t = TYPE_MAIN_VARIANT (t);
10776 if (!ftpi->parms.add (t))
10778 /* Append T to PARM_LIST. */
10779 tree node = build_tree_list (NULL_TREE, t);
10780 *ftpi->parm_list_tail = node;
10781 ftpi->parm_list_tail = &TREE_CHAIN (node);
10784 /* Verify the parameter we found has a valid index. */
10785 if (flag_checking)
10787 tree parms = ftpi->ctx_parms;
10788 while (TMPL_PARMS_DEPTH (parms) > level)
10789 parms = TREE_CHAIN (parms);
10790 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10791 gcc_assert (index < len);
10794 return 0;
10797 /* Ensure that we recursively examine certain terms that are not normally
10798 visited in for_each_template_parm_r. */
10800 static int
10801 any_template_parm_r (tree t, void *data)
10803 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10805 #define WALK_SUBTREE(NODE) \
10806 do \
10808 for_each_template_parm (NODE, keep_template_parm, data, \
10809 &ftpi->visited, true, \
10810 any_template_parm_r); \
10812 while (0)
10814 /* A mention of a member alias/typedef is a use of all of its template
10815 arguments, including those from the enclosing class, so we don't use
10816 alias_template_specialization_p here. */
10817 if (TYPE_P (t) && typedef_variant_p (t))
10818 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10819 WALK_SUBTREE (TI_ARGS (tinfo));
10821 switch (TREE_CODE (t))
10823 case TEMPLATE_TYPE_PARM:
10824 /* Type constraints of a placeholder type may contain parameters. */
10825 if (is_auto (t))
10826 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10827 WALK_SUBTREE (constr);
10828 break;
10830 case TEMPLATE_ID_EXPR:
10831 /* Search through references to variable templates. */
10832 WALK_SUBTREE (TREE_OPERAND (t, 0));
10833 WALK_SUBTREE (TREE_OPERAND (t, 1));
10834 break;
10836 case TEMPLATE_PARM_INDEX:
10837 WALK_SUBTREE (TREE_TYPE (t));
10838 break;
10840 case TEMPLATE_DECL:
10841 /* If T is a member template that shares template parameters with
10842 ctx_parms, we need to mark all those parameters for mapping.
10843 To that end, it should suffice to just walk the DECL_CONTEXT of
10844 the template (assuming the template is not overly general). */
10845 WALK_SUBTREE (DECL_CONTEXT (t));
10846 break;
10848 case LAMBDA_EXPR:
10850 /* Look in the parms and body. */
10851 tree fn = lambda_function (t);
10852 WALK_SUBTREE (TREE_TYPE (fn));
10853 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10855 break;
10857 case IDENTIFIER_NODE:
10858 if (IDENTIFIER_CONV_OP_P (t))
10859 /* The conversion-type-id of a conversion operator may be dependent. */
10860 WALK_SUBTREE (TREE_TYPE (t));
10861 break;
10863 case CONVERT_EXPR:
10864 if (is_dummy_object (t))
10865 WALK_SUBTREE (TREE_TYPE (t));
10866 break;
10868 default:
10869 break;
10872 /* Keep walking. */
10873 return 0;
10876 /* Look through T for template parameters. */
10878 tree
10879 find_template_parameter_info::find_in (tree t)
10881 return for_each_template_parm (t, keep_template_parm, this, &visited,
10882 /*include_nondeduced*/true,
10883 any_template_parm_r);
10886 /* As above, but also recursively look into the default arguments of template
10887 parameters we found. Used for alias CTAD. */
10889 tree
10890 find_template_parameter_info::find_in_recursive (tree t)
10892 if (tree r = find_in (t))
10893 return r;
10894 /* Since newly found parms are added to the end of the list, we
10895 can just walk it until we reach the end. */
10896 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
10898 tree parm = TREE_VALUE (pl);
10899 tree list = corresponding_template_parameter_list (ctx_parms, parm);
10900 if (tree r = find_in (TREE_PURPOSE (list)))
10901 return r;
10903 return NULL_TREE;
10906 /* True if PARM was found by a previous call to find_in. PARM can be a
10907 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
10909 bool
10910 find_template_parameter_info::found (tree parm)
10912 if (TREE_CODE (parm) == TREE_LIST)
10913 parm = TREE_VALUE (parm);
10914 if (TREE_CODE (parm) == TYPE_DECL)
10915 parm = TREE_TYPE (parm);
10916 else
10917 parm = DECL_INITIAL (parm);
10918 gcc_checking_assert (TEMPLATE_PARM_P (parm));
10919 return parms.contains (parm);
10922 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10923 are the template parameters in scope. */
10925 tree
10926 find_template_parameters (tree t, tree ctx_parms)
10928 if (!ctx_parms)
10929 return NULL_TREE;
10931 find_template_parameter_info ftpi (ctx_parms);
10932 ftpi.find_in (t);
10933 return ftpi.parm_list;
10936 /* Returns true if T depends on any template parameter. */
10938 bool
10939 uses_template_parms (tree t)
10941 if (t == NULL_TREE || t == error_mark_node)
10942 return false;
10944 /* Namespaces can't depend on any template parameters. */
10945 if (TREE_CODE (t) == NAMESPACE_DECL)
10946 return false;
10948 processing_template_decl_sentinel ptds (/*reset*/false);
10949 ++processing_template_decl;
10951 if (TYPE_P (t))
10952 return dependent_type_p (t);
10953 else if (TREE_CODE (t) == TREE_VEC)
10954 return any_dependent_template_arguments_p (t);
10955 else if (TREE_CODE (t) == TREE_LIST)
10956 return (uses_template_parms (TREE_VALUE (t))
10957 || uses_template_parms (TREE_CHAIN (t)));
10958 else if (TREE_CODE (t) == TYPE_DECL)
10959 return dependent_type_p (TREE_TYPE (t));
10960 else
10961 return instantiation_dependent_expression_p (t);
10964 /* Returns true if T depends on any template parameter with level LEVEL. */
10966 bool
10967 uses_template_parms_level (tree t, int level)
10969 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10970 /*include_nondeduced_p=*/true);
10973 /* Returns true if the signature of DECL depends on any template parameter from
10974 its enclosing class. */
10976 static bool
10977 uses_outer_template_parms (tree decl)
10979 int depth;
10980 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10981 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
10982 else
10983 depth = template_class_depth (CP_DECL_CONTEXT (decl));
10984 if (depth == 0)
10985 return false;
10986 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10987 &depth, NULL, /*include_nondeduced_p=*/true))
10988 return true;
10989 if (PRIMARY_TEMPLATE_P (decl)
10990 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10992 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10993 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10995 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10996 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10997 if (TREE_CODE (parm) == PARM_DECL
10998 && for_each_template_parm (TREE_TYPE (parm),
10999 template_parm_outer_level,
11000 &depth, NULL, /*nondeduced*/true))
11001 return true;
11002 if (TREE_CODE (parm) == TEMPLATE_DECL
11003 && uses_outer_template_parms (parm))
11004 return true;
11005 if (defarg
11006 && for_each_template_parm (defarg, template_parm_outer_level,
11007 &depth, NULL, /*nondeduced*/true))
11008 return true;
11011 if (uses_outer_template_parms_in_constraints (decl))
11012 return true;
11013 return false;
11016 /* Returns true if the constraints of DECL depend on any template parameters
11017 from its enclosing scope. */
11019 bool
11020 uses_outer_template_parms_in_constraints (tree decl)
11022 tree ci = get_constraints (decl);
11023 if (ci)
11024 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11025 if (!ci)
11026 return false;
11027 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11028 if (depth == 0)
11029 return false;
11030 return for_each_template_parm (ci, template_parm_outer_level,
11031 &depth, NULL, /*nondeduced*/true);
11034 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11035 ill-formed translation unit, i.e. a variable or function that isn't
11036 usable in a constant expression. */
11038 static inline bool
11039 neglectable_inst_p (tree d)
11041 return (d && DECL_P (d)
11042 && !undeduced_auto_decl (d)
11043 && !(TREE_CODE (d) == FUNCTION_DECL
11044 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11045 : decl_maybe_constant_var_p (d)));
11048 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11049 neglectable and instantiated from within an erroneous instantiation. */
11051 static bool
11052 limit_bad_template_recursion (tree decl)
11054 struct tinst_level *lev = current_tinst_level;
11055 int errs = errorcount + sorrycount;
11056 if (errs == 0 || !neglectable_inst_p (decl))
11057 return false;
11059 /* Avoid instantiating members of an ill-formed class. */
11060 bool refuse
11061 = (DECL_CLASS_SCOPE_P (decl)
11062 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11064 if (!refuse)
11066 for (; lev; lev = lev->next)
11067 if (neglectable_inst_p (lev->maybe_get_node ()))
11068 break;
11069 refuse = (lev && errs > lev->errors);
11072 if (refuse)
11074 /* Don't warn about it not being defined. */
11075 suppress_warning (decl, OPT_Wunused);
11076 tree clone;
11077 FOR_EACH_CLONE (clone, decl)
11078 suppress_warning (clone, OPT_Wunused);
11080 return refuse;
11083 static int tinst_depth;
11084 extern int max_tinst_depth;
11085 int depth_reached;
11087 static GTY(()) struct tinst_level *last_error_tinst_level;
11089 /* We're starting to instantiate D; record the template instantiation context
11090 at LOC for diagnostics and to restore it later. */
11092 bool
11093 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11095 struct tinst_level *new_level;
11097 if (tinst_depth >= max_tinst_depth)
11099 /* Tell error.cc not to try to instantiate any templates. */
11100 at_eof = 2;
11101 fatal_error (input_location,
11102 "template instantiation depth exceeds maximum of %d"
11103 " (use %<-ftemplate-depth=%> to increase the maximum)",
11104 max_tinst_depth);
11105 return false;
11108 /* If the current instantiation caused problems, don't let it instantiate
11109 anything else. Do allow deduction substitution and decls usable in
11110 constant expressions. */
11111 if (!targs && limit_bad_template_recursion (tldcl))
11113 /* Avoid no_linkage_errors and unused function (and all other)
11114 warnings for this decl. */
11115 suppress_warning (tldcl);
11116 return false;
11119 /* When not -quiet, dump template instantiations other than functions, since
11120 announce_function will take care of those. */
11121 if (!quiet_flag && !targs
11122 && TREE_CODE (tldcl) != TREE_LIST
11123 && TREE_CODE (tldcl) != FUNCTION_DECL)
11124 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11126 new_level = tinst_level_freelist ().alloc ();
11127 new_level->tldcl = tldcl;
11128 new_level->targs = targs;
11129 new_level->locus = loc;
11130 new_level->errors = errorcount + sorrycount;
11131 new_level->next = NULL;
11132 new_level->refcount = 0;
11133 new_level->path = new_level->visible = nullptr;
11134 set_refcount_ptr (new_level->next, current_tinst_level);
11135 set_refcount_ptr (current_tinst_level, new_level);
11137 ++tinst_depth;
11138 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11139 depth_reached = tinst_depth;
11141 return true;
11144 /* We're starting substitution of TMPL<ARGS>; record the template
11145 substitution context for diagnostics and to restore it later. */
11147 bool
11148 push_tinst_level (tree tmpl, tree args)
11150 return push_tinst_level_loc (tmpl, args, input_location);
11153 /* We're starting to instantiate D; record INPUT_LOCATION and the
11154 template instantiation context for diagnostics and to restore it
11155 later. */
11157 bool
11158 push_tinst_level (tree d)
11160 return push_tinst_level_loc (d, input_location);
11163 /* Likewise, but record LOC as the program location. */
11165 bool
11166 push_tinst_level_loc (tree d, location_t loc)
11168 gcc_assert (TREE_CODE (d) != TREE_LIST);
11169 return push_tinst_level_loc (d, NULL, loc);
11172 /* We're done instantiating this template; return to the instantiation
11173 context. */
11175 void
11176 pop_tinst_level (void)
11178 /* Restore the filename and line number stashed away when we started
11179 this instantiation. */
11180 input_location = current_tinst_level->locus;
11181 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11182 --tinst_depth;
11185 /* We're instantiating a deferred template; restore the template
11186 instantiation context in which the instantiation was requested, which
11187 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11189 static tree
11190 reopen_tinst_level (struct tinst_level *level)
11192 struct tinst_level *t;
11194 tinst_depth = 0;
11195 for (t = level; t; t = t->next)
11196 ++tinst_depth;
11198 set_refcount_ptr (current_tinst_level, level);
11199 pop_tinst_level ();
11200 if (current_tinst_level)
11201 current_tinst_level->errors = errorcount+sorrycount;
11202 return level->maybe_get_node ();
11205 /* Returns the TINST_LEVEL which gives the original instantiation
11206 context. */
11208 struct tinst_level *
11209 outermost_tinst_level (void)
11211 struct tinst_level *level = current_tinst_level;
11212 if (level)
11213 while (level->next)
11214 level = level->next;
11215 return level;
11218 /* True iff T is a friend function declaration that is not itself a template
11219 and is not defined in a class template. */
11221 bool
11222 non_templated_friend_p (tree t)
11224 if (t && TREE_CODE (t) == FUNCTION_DECL
11225 && DECL_UNIQUE_FRIEND_P (t))
11227 tree ti = DECL_TEMPLATE_INFO (t);
11228 if (!ti)
11229 return true;
11230 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11231 if (DECL_FRIEND_CONTEXT (t))
11232 return false;
11233 /* Non-templated friends in a class template are still represented with a
11234 TEMPLATE_DECL; check that its primary template is the befriending
11235 class. Note that DECL_PRIMARY_TEMPLATE is null for
11236 template <class T> friend A<T>::f(); */
11237 tree tmpl = TI_TEMPLATE (ti);
11238 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11239 return (primary && primary != tmpl);
11241 else
11242 return false;
11245 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11246 vector of template arguments, as for tsubst.
11248 Returns an appropriate tsubst'd friend declaration. */
11250 static tree
11251 tsubst_friend_function (tree decl, tree args)
11253 tree new_friend;
11255 if (TREE_CODE (decl) == FUNCTION_DECL
11256 && DECL_TEMPLATE_INSTANTIATION (decl)
11257 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11258 /* This was a friend declared with an explicit template
11259 argument list, e.g.:
11261 friend void f<>(T);
11263 to indicate that f was a template instantiation, not a new
11264 function declaration. Now, we have to figure out what
11265 instantiation of what template. */
11267 tree template_id, arglist, fns;
11268 tree new_args;
11269 tree tmpl;
11270 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11272 /* Friend functions are looked up in the containing namespace scope.
11273 We must enter that scope, to avoid finding member functions of the
11274 current class with same name. */
11275 push_nested_namespace (ns);
11276 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11277 tf_warning_or_error, NULL_TREE);
11278 pop_nested_namespace (ns);
11279 arglist = tsubst (DECL_TI_ARGS (decl), args,
11280 tf_warning_or_error, NULL_TREE);
11281 template_id = lookup_template_function (fns, arglist);
11283 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11284 tmpl = determine_specialization (template_id, new_friend,
11285 &new_args,
11286 /*need_member_template=*/0,
11287 TREE_VEC_LENGTH (args),
11288 tsk_none);
11289 return instantiate_template (tmpl, new_args, tf_error);
11292 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11293 if (new_friend == error_mark_node)
11294 return error_mark_node;
11296 /* The NEW_FRIEND will look like an instantiation, to the
11297 compiler, but is not an instantiation from the point of view of
11298 the language. For example, we might have had:
11300 template <class T> struct S {
11301 template <class U> friend void f(T, U);
11304 Then, in S<int>, template <class U> void f(int, U) is not an
11305 instantiation of anything. */
11307 DECL_USE_TEMPLATE (new_friend) = 0;
11308 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11310 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11311 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11312 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11313 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11315 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11316 match in decls_match. */
11317 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11318 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11319 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11320 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11322 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11323 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11324 tsubst_each_template_parm_constraints (parms, args,
11325 tf_warning_or_error);
11329 /* The mangled name for the NEW_FRIEND is incorrect. The function
11330 is not a template instantiation and should not be mangled like
11331 one. Therefore, we forget the mangling here; we'll recompute it
11332 later if we need it. */
11333 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11335 SET_DECL_RTL (new_friend, NULL);
11336 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11339 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11341 tree old_decl;
11342 tree ns;
11344 /* We must save some information from NEW_FRIEND before calling
11345 duplicate decls since that function will free NEW_FRIEND if
11346 possible. */
11347 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11348 tree new_friend_result_template_info = NULL_TREE;
11349 bool new_friend_is_defn =
11350 (new_friend_template_info
11351 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11352 (template_for_substitution (new_friend)))
11353 != NULL_TREE));
11354 tree not_tmpl = new_friend;
11356 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11358 /* This declaration is a `primary' template. */
11359 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11361 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11362 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11364 else if (!constraints_satisfied_p (new_friend))
11365 /* Only define a constrained hidden friend when satisfied. */
11366 return error_mark_node;
11368 /* Inside pushdecl_namespace_level, we will push into the
11369 current namespace. However, the friend function should go
11370 into the namespace of the template. */
11371 ns = decl_namespace_context (new_friend);
11372 push_nested_namespace (ns);
11373 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11374 pop_nested_namespace (ns);
11376 if (old_decl == error_mark_node)
11377 return error_mark_node;
11379 if (old_decl != new_friend)
11381 /* This new friend declaration matched an existing
11382 declaration. For example, given:
11384 template <class T> void f(T);
11385 template <class U> class C {
11386 template <class T> friend void f(T) {}
11389 the friend declaration actually provides the definition
11390 of `f', once C has been instantiated for some type. So,
11391 old_decl will be the out-of-class template declaration,
11392 while new_friend is the in-class definition.
11394 But, if `f' was called before this point, the
11395 instantiation of `f' will have DECL_TI_ARGS corresponding
11396 to `T' but not to `U', references to which might appear
11397 in the definition of `f'. Previously, the most general
11398 template for an instantiation of `f' was the out-of-class
11399 version; now it is the in-class version. Therefore, we
11400 run through all specialization of `f', adding to their
11401 DECL_TI_ARGS appropriately. In particular, they need a
11402 new set of outer arguments, corresponding to the
11403 arguments for this class instantiation.
11405 The same situation can arise with something like this:
11407 friend void f(int);
11408 template <class T> class C {
11409 friend void f(T) {}
11412 when `C<int>' is instantiated. Now, `f(int)' is defined
11413 in the class. */
11415 if (!new_friend_is_defn)
11416 /* On the other hand, if the in-class declaration does
11417 *not* provide a definition, then we don't want to alter
11418 existing definitions. We can just leave everything
11419 alone. */
11421 else
11423 tree new_template = TI_TEMPLATE (new_friend_template_info);
11424 tree new_args = TI_ARGS (new_friend_template_info);
11426 /* Overwrite whatever template info was there before, if
11427 any, with the new template information pertaining to
11428 the declaration. */
11429 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11431 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11433 /* We should have called reregister_specialization in
11434 duplicate_decls. */
11435 gcc_assert (retrieve_specialization (new_template,
11436 new_args, 0)
11437 == old_decl);
11439 /* Instantiate it if the global has already been used. */
11440 if (DECL_ODR_USED (old_decl))
11441 instantiate_decl (old_decl, /*defer_ok=*/true,
11442 /*expl_inst_class_mem_p=*/false);
11444 else
11446 tree t;
11448 /* Indicate that the old function template is a partial
11449 instantiation. */
11450 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11451 = new_friend_result_template_info;
11453 gcc_assert (new_template
11454 == most_general_template (new_template));
11455 gcc_assert (new_template != old_decl);
11457 /* Reassign any specializations already in the hash table
11458 to the new more general template, and add the
11459 additional template args. */
11460 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11461 t != NULL_TREE;
11462 t = TREE_CHAIN (t))
11464 tree spec = TREE_VALUE (t);
11465 spec_entry elt;
11467 elt.tmpl = old_decl;
11468 elt.args = DECL_TI_ARGS (spec);
11469 elt.spec = NULL_TREE;
11471 decl_specializations->remove_elt (&elt);
11473 DECL_TI_ARGS (spec)
11474 = add_outermost_template_args (new_args,
11475 DECL_TI_ARGS (spec));
11477 register_specialization
11478 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11481 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11485 /* The information from NEW_FRIEND has been merged into OLD_DECL
11486 by duplicate_decls. */
11487 new_friend = old_decl;
11490 /* We've just introduced a namespace-scope function in the purview
11491 without necessarily having opened the enclosing namespace, so
11492 make sure the namespace is in the purview now too. */
11493 if (modules_p ()
11494 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11495 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11496 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11498 else
11500 tree context = DECL_CONTEXT (new_friend);
11501 bool dependent_p;
11503 /* In the code
11504 template <class T> class C {
11505 template <class U> friend void C1<U>::f (); // case 1
11506 friend void C2<T>::f (); // case 2
11508 we only need to make sure CONTEXT is a complete type for
11509 case 2. To distinguish between the two cases, we note that
11510 CONTEXT of case 1 remains dependent type after tsubst while
11511 this isn't true for case 2. */
11512 ++processing_template_decl;
11513 dependent_p = dependent_type_p (context);
11514 --processing_template_decl;
11516 if (!dependent_p
11517 && !complete_type_or_else (context, NULL_TREE))
11518 return error_mark_node;
11520 if (COMPLETE_TYPE_P (context))
11522 tree fn = new_friend;
11523 /* do_friend adds the TEMPLATE_DECL for any member friend
11524 template even if it isn't a member template, i.e.
11525 template <class T> friend A<T>::f();
11526 Look through it in that case. */
11527 if (TREE_CODE (fn) == TEMPLATE_DECL
11528 && !PRIMARY_TEMPLATE_P (fn))
11529 fn = DECL_TEMPLATE_RESULT (fn);
11530 /* Check to see that the declaration is really present, and,
11531 possibly obtain an improved declaration. */
11532 fn = check_classfn (context, fn, NULL_TREE);
11534 if (fn)
11535 new_friend = fn;
11539 return new_friend;
11542 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11543 template arguments, as for tsubst.
11545 Returns an appropriate tsubst'd friend type or error_mark_node on
11546 failure. */
11548 static tree
11549 tsubst_friend_class (tree friend_tmpl, tree args)
11551 tree tmpl;
11553 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11555 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11556 return TREE_TYPE (tmpl);
11559 tree context = CP_DECL_CONTEXT (friend_tmpl);
11560 if (TREE_CODE (context) == NAMESPACE_DECL)
11561 push_nested_namespace (context);
11562 else
11564 context = tsubst (context, args, tf_error, NULL_TREE);
11565 push_nested_class (context);
11568 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11569 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11571 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11573 /* The friend template has already been declared. Just
11574 check to see that the declarations match, and install any new
11575 default parameters. We must tsubst the default parameters,
11576 of course. We only need the innermost template parameters
11577 because that is all that redeclare_class_template will look
11578 at. */
11579 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11580 > TMPL_ARGS_DEPTH (args))
11582 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11583 args, tf_warning_or_error);
11584 tsubst_each_template_parm_constraints (parms, args,
11585 tf_warning_or_error);
11586 location_t saved_input_location = input_location;
11587 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11588 tree cons = get_constraints (friend_tmpl);
11589 ++processing_template_decl;
11590 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11591 DECL_FRIEND_CONTEXT (friend_tmpl));
11592 --processing_template_decl;
11593 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11594 input_location = saved_input_location;
11597 else
11599 /* The friend template has not already been declared. In this
11600 case, the instantiation of the template class will cause the
11601 injection of this template into the namespace scope. */
11602 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11604 if (tmpl != error_mark_node)
11606 /* The new TMPL is not an instantiation of anything, so we
11607 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11608 for the new type because that is supposed to be the
11609 corresponding template decl, i.e., TMPL. */
11610 DECL_USE_TEMPLATE (tmpl) = 0;
11611 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11612 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11613 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11614 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11616 /* Substitute into and set the constraints on the new declaration. */
11617 if (tree ci = get_constraints (friend_tmpl))
11619 ++processing_template_decl;
11620 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11621 DECL_FRIEND_CONTEXT (friend_tmpl));
11622 --processing_template_decl;
11623 set_constraints (tmpl, ci);
11624 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11625 args, tf_warning_or_error);
11628 /* Inject this template into the enclosing namspace scope. */
11629 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11633 if (TREE_CODE (context) == NAMESPACE_DECL)
11634 pop_nested_namespace (context);
11635 else
11636 pop_nested_class ();
11638 return TREE_TYPE (tmpl);
11641 /* Returns zero if TYPE cannot be completed later due to circularity.
11642 Otherwise returns one. */
11644 static int
11645 can_complete_type_without_circularity (tree type)
11647 if (type == NULL_TREE || type == error_mark_node)
11648 return 0;
11649 else if (COMPLETE_TYPE_P (type))
11650 return 1;
11651 else if (TREE_CODE (type) == ARRAY_TYPE)
11652 return can_complete_type_without_circularity (TREE_TYPE (type));
11653 else if (CLASS_TYPE_P (type)
11654 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11655 return 0;
11656 else
11657 return 1;
11660 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11661 tsubst_flags_t, tree);
11663 /* Instantiate the contract statement. */
11665 static tree
11666 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11667 tree in_decl)
11669 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11670 bool auto_p = type_uses_auto (type);
11672 tree r = copy_node (t);
11674 /* Rebuild the result variable. */
11675 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11677 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11679 tree newvar = copy_node (oldvar);
11680 TREE_TYPE (newvar) = type;
11681 DECL_CONTEXT (newvar) = decl;
11682 POSTCONDITION_IDENTIFIER (r) = newvar;
11684 /* Make sure the postcondition is valid. */
11685 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11686 if (!auto_p)
11687 if (!check_postcondition_result (decl, type, loc))
11688 return invalidate_contract (r);
11690 /* Make the variable available for lookup. */
11691 register_local_specialization (newvar, oldvar);
11694 /* Instantiate the condition. If the return type is undeduced, process
11695 the expression as if inside a template to avoid spurious type errors. */
11696 if (auto_p)
11697 ++processing_template_decl;
11698 ++processing_contract_condition;
11699 CONTRACT_CONDITION (r)
11700 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11701 --processing_contract_condition;
11702 if (auto_p)
11703 --processing_template_decl;
11705 /* And the comment. */
11706 CONTRACT_COMMENT (r)
11707 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11709 return r;
11712 /* Update T by instantiating its contract attribute. */
11714 static void
11715 tsubst_contract_attribute (tree decl, tree t, tree args,
11716 tsubst_flags_t complain, tree in_decl)
11718 /* For non-specializations, adjust the current declaration to the most general
11719 version of in_decl. Because we defer the instantiation of contracts as long
11720 as possible, they are still written in terms of the parameters (and return
11721 type) of the most general template. */
11722 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11723 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11724 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11725 local_specialization_stack specs (lss_copy);
11726 register_parameter_specializations (in_decl, decl);
11728 /* Get the contract to be instantiated. */
11729 tree contract = CONTRACT_STATEMENT (t);
11731 /* Use the complete set of template arguments for instantiation. The
11732 contract may not have been instantiated and still refer to outer levels
11733 of template parameters. */
11734 args = DECL_TI_ARGS (decl);
11736 /* For member functions, make this available for semantic analysis. */
11737 tree save_ccp = current_class_ptr;
11738 tree save_ccr = current_class_ref;
11739 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11741 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11742 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11743 inject_this_parameter (this_type, cp_type_quals (this_type));
11746 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11748 current_class_ptr = save_ccp;
11749 current_class_ref = save_ccr;
11751 /* Rebuild the attribute. */
11752 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11755 /* Rebuild the attribute list for DECL, substituting into contracts
11756 as needed. */
11758 void
11759 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11761 tree list = copy_list (DECL_ATTRIBUTES (decl));
11762 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11764 if (cxx_contract_attribute_p (attr))
11765 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11767 DECL_ATTRIBUTES (decl) = list;
11770 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11771 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11773 static tree
11774 tsubst_attribute (tree t, tree *decl_p, tree args,
11775 tsubst_flags_t complain, tree in_decl)
11777 gcc_assert (ATTR_IS_DEPENDENT (t));
11779 /* Note that contract attributes are never substituted from this function.
11780 Their instantiation is triggered by regenerate_from_template_decl when
11781 we instantiate the body of the function. */
11783 tree val = TREE_VALUE (t);
11784 if (val == NULL_TREE)
11785 /* Nothing to do. */;
11786 else if ((flag_openmp || flag_openmp_simd)
11787 && is_attribute_p ("omp declare simd",
11788 get_attribute_name (t)))
11790 tree clauses = TREE_VALUE (val);
11791 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11792 complain, in_decl);
11793 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11794 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11795 tree parms = DECL_ARGUMENTS (*decl_p);
11796 clauses
11797 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11798 if (clauses)
11799 val = build_tree_list (NULL_TREE, clauses);
11800 else
11801 val = NULL_TREE;
11803 else if (flag_openmp
11804 && is_attribute_p ("omp declare variant base",
11805 get_attribute_name (t)))
11807 ++cp_unevaluated_operand;
11808 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11809 --cp_unevaluated_operand;
11810 tree chain = TREE_CHAIN (val);
11811 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11812 tree ctx = copy_list (TREE_VALUE (val));
11813 tree simd = get_identifier ("simd");
11814 tree score = get_identifier (" score");
11815 tree condition = get_identifier ("condition");
11816 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11818 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11819 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11820 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11822 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11824 tree clauses = TREE_VALUE (t2);
11825 clauses = tsubst_omp_clauses (clauses,
11826 C_ORT_OMP_DECLARE_SIMD, args,
11827 complain, in_decl);
11828 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11829 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11830 TREE_VALUE (t2) = clauses;
11832 else
11834 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11835 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11836 if (TREE_VALUE (t3))
11838 bool allow_string
11839 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11840 && TREE_PURPOSE (t3) != score);
11841 tree v = TREE_VALUE (t3);
11842 if (TREE_CODE (v) == STRING_CST && allow_string)
11843 continue;
11844 v = tsubst_expr (v, args, complain, in_decl);
11845 v = fold_non_dependent_expr (v);
11846 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11847 || (TREE_PURPOSE (t3) == score
11848 ? TREE_CODE (v) != INTEGER_CST
11849 : !tree_fits_shwi_p (v)))
11851 location_t loc
11852 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11853 match_loc);
11854 if (TREE_PURPOSE (t3) == score)
11855 error_at (loc, "score argument must be "
11856 "constant integer expression");
11857 else if (allow_string)
11858 error_at (loc, "property must be constant "
11859 "integer expression or string "
11860 "literal");
11861 else
11862 error_at (loc, "property must be constant "
11863 "integer expression");
11864 return NULL_TREE;
11866 else if (TREE_PURPOSE (t3) == score
11867 && tree_int_cst_sgn (v) < 0)
11869 location_t loc
11870 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11871 match_loc);
11872 error_at (loc, "score argument must be "
11873 "non-negative");
11874 return NULL_TREE;
11876 TREE_VALUE (t3) = v;
11881 val = tree_cons (varid, ctx, chain);
11883 /* If the first attribute argument is an identifier, don't
11884 pass it through tsubst. Attributes like mode, format,
11885 cleanup and several target specific attributes expect it
11886 unmodified. */
11887 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11889 tree chain
11890 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11891 if (chain != TREE_CHAIN (val))
11892 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11894 else if (PACK_EXPANSION_P (val))
11896 /* An attribute pack expansion. */
11897 tree purp = TREE_PURPOSE (t);
11898 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11899 if (pack == error_mark_node)
11900 return error_mark_node;
11901 int len = TREE_VEC_LENGTH (pack);
11902 tree list = NULL_TREE;
11903 tree *q = &list;
11904 for (int i = 0; i < len; ++i)
11906 tree elt = TREE_VEC_ELT (pack, i);
11907 *q = build_tree_list (purp, elt);
11908 q = &TREE_CHAIN (*q);
11910 return list;
11912 else
11913 val = tsubst_expr (val, args, complain, in_decl);
11915 if (val == error_mark_node)
11916 return error_mark_node;
11917 if (val != TREE_VALUE (t))
11918 return build_tree_list (TREE_PURPOSE (t), val);
11919 return t;
11922 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11923 unchanged or a new TREE_LIST chain. */
11925 static tree
11926 tsubst_attributes (tree attributes, tree args,
11927 tsubst_flags_t complain, tree in_decl)
11929 tree last_dep = NULL_TREE;
11931 for (tree t = attributes; t; t = TREE_CHAIN (t))
11932 if (ATTR_IS_DEPENDENT (t))
11934 last_dep = t;
11935 attributes = copy_list (attributes);
11936 break;
11939 if (last_dep)
11940 for (tree *p = &attributes; *p; )
11942 tree t = *p;
11943 if (ATTR_IS_DEPENDENT (t))
11945 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11946 if (subst != t)
11948 *p = subst;
11949 while (*p)
11950 p = &TREE_CHAIN (*p);
11951 *p = TREE_CHAIN (t);
11952 continue;
11955 p = &TREE_CHAIN (*p);
11958 return attributes;
11961 /* Apply any attributes which had to be deferred until instantiation
11962 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11963 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11964 false on error. */
11966 static bool
11967 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11968 tree args, tsubst_flags_t complain, tree in_decl)
11970 tree t;
11971 tree *p;
11973 if (attributes == NULL_TREE)
11974 return true;
11976 if (DECL_P (*decl_p))
11978 if (TREE_TYPE (*decl_p) == error_mark_node)
11979 return false;
11980 p = &DECL_ATTRIBUTES (*decl_p);
11981 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11982 to our attributes parameter. */
11983 gcc_assert (*p == attributes);
11985 else
11987 p = &TYPE_ATTRIBUTES (*decl_p);
11988 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11989 lookup_template_class_1, and should be preserved. */
11990 gcc_assert (*p != attributes);
11991 while (*p)
11992 p = &TREE_CHAIN (*p);
11995 /* save_template_attributes puts the dependent attributes at the beginning of
11996 the list; find the non-dependent ones. */
11997 for (t = attributes; t; t = TREE_CHAIN (t))
11998 if (!ATTR_IS_DEPENDENT (t))
11999 break;
12000 tree nondep = t;
12002 /* Apply any non-dependent attributes. */
12003 *p = nondep;
12005 if (nondep == attributes)
12006 return true;
12008 /* And then any dependent ones. */
12009 tree late_attrs = NULL_TREE;
12010 tree *q = &late_attrs;
12011 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12013 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12014 if (*q == error_mark_node)
12015 return false;
12016 if (*q == t)
12018 *q = copy_node (t);
12019 TREE_CHAIN (*q) = NULL_TREE;
12021 while (*q)
12022 q = &TREE_CHAIN (*q);
12025 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12026 those attributes should have been added already when those templates were
12027 parsed, and shouldn't be added based on from which context they are
12028 first time instantiated. */
12029 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12030 auto o2 = make_temp_override (optimization_current_node,
12031 optimization_default_node);
12032 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12033 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12034 NULL);
12035 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12037 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12039 return true;
12042 /* The template TMPL is being instantiated with the template arguments TARGS.
12043 Perform the access checks that we deferred when parsing the template. */
12045 static void
12046 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12048 unsigned i;
12049 deferred_access_check *chk;
12051 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12052 return;
12054 if (vec<deferred_access_check, va_gc> *access_checks
12055 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12056 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12058 tree decl = chk->decl;
12059 tree diag_decl = chk->diag_decl;
12060 tree type_scope = TREE_TYPE (chk->binfo);
12062 if (uses_template_parms (type_scope))
12063 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12065 /* Make access check error messages point to the location
12066 of the use of the typedef. */
12067 iloc_sentinel ils (chk->loc);
12068 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12069 decl, diag_decl, tf_warning_or_error);
12073 tree
12074 instantiate_class_template (tree type)
12076 auto_timevar tv (TV_TEMPLATE_INST);
12078 tree templ, args, pattern, t, member;
12079 tree typedecl;
12080 tree pbinfo;
12081 tree base_list;
12082 unsigned int saved_maximum_field_alignment;
12083 tree fn_context;
12085 if (type == error_mark_node)
12086 return error_mark_node;
12088 if (COMPLETE_OR_OPEN_TYPE_P (type)
12089 || (uses_template_parms (type)
12090 && !TYPE_FUNCTION_SCOPE_P (type)))
12091 return type;
12093 /* Figure out which template is being instantiated. */
12094 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12095 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12097 /* Mark the type as in the process of being defined. */
12098 TYPE_BEING_DEFINED (type) = 1;
12100 /* We may be in the middle of deferred access check. Disable
12101 it now. */
12102 deferring_access_check_sentinel acs (dk_no_deferred);
12104 /* Determine what specialization of the original template to
12105 instantiate. */
12106 t = most_specialized_partial_spec (type, tf_warning_or_error);
12107 if (t == error_mark_node)
12108 return error_mark_node;
12109 else if (t)
12111 /* This TYPE is actually an instantiation of a partial
12112 specialization. We replace the innermost set of ARGS with
12113 the arguments appropriate for substitution. For example,
12114 given:
12116 template <class T> struct S {};
12117 template <class T> struct S<T*> {};
12119 and supposing that we are instantiating S<int*>, ARGS will
12120 presently be {int*} -- but we need {int}. */
12121 pattern = TREE_TYPE (TI_TEMPLATE (t));
12122 args = TI_ARGS (t);
12124 else
12126 pattern = TREE_TYPE (templ);
12127 args = CLASSTYPE_TI_ARGS (type);
12130 /* If the template we're instantiating is incomplete, then clearly
12131 there's nothing we can do. */
12132 if (!COMPLETE_TYPE_P (pattern))
12134 /* We can try again later. */
12135 TYPE_BEING_DEFINED (type) = 0;
12136 return type;
12139 /* If we've recursively instantiated too many templates, stop. */
12140 if (! push_tinst_level (type))
12141 return type;
12143 int saved_unevaluated_operand = cp_unevaluated_operand;
12144 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12146 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12147 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12148 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12149 fn_context = error_mark_node;
12150 if (!fn_context)
12151 push_to_top_level ();
12152 else
12154 cp_unevaluated_operand = 0;
12155 c_inhibit_evaluation_warnings = 0;
12158 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12160 /* Use #pragma pack from the template context. */
12161 saved_maximum_field_alignment = maximum_field_alignment;
12162 maximum_field_alignment = TYPE_PRECISION (pattern);
12164 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12166 /* Set the input location to the most specialized template definition.
12167 This is needed if tsubsting causes an error. */
12168 typedecl = TYPE_MAIN_DECL (pattern);
12169 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12170 DECL_SOURCE_LOCATION (typedecl);
12172 set_instantiating_module (TYPE_NAME (type));
12174 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12175 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12176 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12177 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12178 if (ANON_AGGR_TYPE_P (pattern))
12179 SET_ANON_AGGR_TYPE_P (type);
12180 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12182 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12183 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12184 /* Adjust visibility for template arguments. */
12185 determine_visibility (TYPE_MAIN_DECL (type));
12187 if (CLASS_TYPE_P (type))
12188 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12190 pbinfo = TYPE_BINFO (pattern);
12192 /* We should never instantiate a nested class before its enclosing
12193 class; we need to look up the nested class by name before we can
12194 instantiate it, and that lookup should instantiate the enclosing
12195 class. */
12196 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12197 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12199 base_list = NULL_TREE;
12200 /* Defer access checking while we substitute into the types named in
12201 the base-clause. */
12202 push_deferring_access_checks (dk_deferred);
12203 if (BINFO_N_BASE_BINFOS (pbinfo))
12205 tree pbase_binfo;
12206 int i;
12208 /* Substitute into each of the bases to determine the actual
12209 basetypes. */
12210 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12212 tree base;
12213 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12214 tree expanded_bases = NULL_TREE;
12215 int idx, len = 1;
12217 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12219 expanded_bases =
12220 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12221 args, tf_error, NULL_TREE);
12222 if (expanded_bases == error_mark_node)
12223 continue;
12225 len = TREE_VEC_LENGTH (expanded_bases);
12228 for (idx = 0; idx < len; idx++)
12230 if (expanded_bases)
12231 /* Extract the already-expanded base class. */
12232 base = TREE_VEC_ELT (expanded_bases, idx);
12233 else
12234 /* Substitute to figure out the base class. */
12235 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12236 NULL_TREE);
12238 if (base == error_mark_node)
12239 continue;
12241 base_list = tree_cons (access, base, base_list);
12242 if (BINFO_VIRTUAL_P (pbase_binfo))
12243 TREE_TYPE (base_list) = integer_type_node;
12247 /* The list is now in reverse order; correct that. */
12248 base_list = nreverse (base_list);
12250 /* Now call xref_basetypes to set up all the base-class
12251 information. */
12252 xref_basetypes (type, base_list);
12254 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12255 (int) ATTR_FLAG_TYPE_IN_PLACE,
12256 args, tf_error, NULL_TREE);
12257 fixup_attribute_variants (type);
12259 /* Now that our base classes are set up, enter the scope of the
12260 class, so that name lookups into base classes, etc. will work
12261 correctly. This is precisely analogous to what we do in
12262 begin_class_definition when defining an ordinary non-template
12263 class, except we also need to push the enclosing classes. */
12264 push_nested_class (type);
12266 /* Now check accessibility of the types named in its base-clause,
12267 relative to the scope of the class. */
12268 pop_to_parent_deferring_access_checks ();
12270 /* A vector to hold members marked with attribute used. */
12271 auto_vec<tree> used;
12273 /* Now members are processed in the order of declaration. */
12274 for (member = CLASSTYPE_DECL_LIST (pattern);
12275 member; member = TREE_CHAIN (member))
12277 tree t = TREE_VALUE (member);
12279 if (TREE_PURPOSE (member))
12281 if (TYPE_P (t))
12283 if (LAMBDA_TYPE_P (t))
12284 /* A closure type for a lambda in an NSDMI or default argument.
12285 Ignore it; it will be regenerated when needed. */
12286 continue;
12288 /* If the member is a class template, we've
12289 already substituted its type. */
12290 if (CLASS_TYPE_P (t)
12291 && CLASSTYPE_IS_TEMPLATE (t))
12292 continue;
12294 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12295 if (newtag == error_mark_node)
12296 continue;
12298 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12300 tree name = TYPE_IDENTIFIER (t);
12302 /* Now, install the tag. We don't use pushtag
12303 because that does too much work -- creating an
12304 implicit typedef, which we've already done. */
12305 set_identifier_type_value (name, TYPE_NAME (newtag));
12306 maybe_add_class_template_decl_list (type, newtag, false);
12307 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12308 determine_visibility (TYPE_NAME (newtag));
12311 else if (DECL_DECLARES_FUNCTION_P (t))
12313 tree r;
12315 if (TREE_CODE (t) == TEMPLATE_DECL)
12316 ++processing_template_decl;
12317 r = tsubst (t, args, tf_error, NULL_TREE);
12318 if (TREE_CODE (t) == TEMPLATE_DECL)
12319 --processing_template_decl;
12321 set_current_access_from_decl (r);
12322 finish_member_declaration (r);
12323 /* Instantiate members marked with attribute used. */
12324 if (r != error_mark_node && DECL_PRESERVE_P (r))
12325 used.safe_push (r);
12326 if (TREE_CODE (r) == FUNCTION_DECL
12327 && DECL_OMP_DECLARE_REDUCTION_P (r))
12328 cp_check_omp_declare_reduction (r);
12330 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12331 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12332 /* A closure type for a lambda in an NSDMI or default argument.
12333 Ignore it; it will be regenerated when needed. */;
12334 else
12336 /* Build new TYPE_FIELDS. */
12337 if (TREE_CODE (t) == STATIC_ASSERT)
12338 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE);
12339 else if (TREE_CODE (t) != CONST_DECL)
12341 tree r;
12342 tree vec = NULL_TREE;
12343 int len = 1;
12345 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12346 /* The file and line for this declaration, to
12347 assist in error message reporting. Since we
12348 called push_tinst_level above, we don't need to
12349 restore these. */
12350 input_location = DECL_SOURCE_LOCATION (t);
12352 if (TREE_CODE (t) == TEMPLATE_DECL)
12353 ++processing_template_decl;
12354 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12355 if (TREE_CODE (t) == TEMPLATE_DECL)
12356 --processing_template_decl;
12358 if (TREE_CODE (r) == TREE_VEC)
12360 /* A capture pack became multiple fields. */
12361 vec = r;
12362 len = TREE_VEC_LENGTH (vec);
12365 for (int i = 0; i < len; ++i)
12367 if (vec)
12368 r = TREE_VEC_ELT (vec, i);
12369 if (VAR_P (r))
12371 /* In [temp.inst]:
12373 [t]he initialization (and any associated
12374 side-effects) of a static data member does
12375 not occur unless the static data member is
12376 itself used in a way that requires the
12377 definition of the static data member to
12378 exist.
12380 Therefore, we do not substitute into the
12381 initialized for the static data member here. */
12382 finish_static_data_member_decl
12384 /*init=*/NULL_TREE,
12385 /*init_const_expr_p=*/false,
12386 /*asmspec_tree=*/NULL_TREE,
12387 /*flags=*/0);
12388 /* Instantiate members marked with attribute used. */
12389 if (r != error_mark_node && DECL_PRESERVE_P (r))
12390 used.safe_push (r);
12392 else if (TREE_CODE (r) == FIELD_DECL)
12394 /* Determine whether R has a valid type and can be
12395 completed later. If R is invalid, then its type
12396 is replaced by error_mark_node. */
12397 tree rtype = TREE_TYPE (r);
12398 if (can_complete_type_without_circularity (rtype))
12399 complete_type (rtype);
12401 if (!complete_or_array_type_p (rtype))
12403 /* If R's type couldn't be completed and
12404 it isn't a flexible array member (whose
12405 type is incomplete by definition) give
12406 an error. */
12407 cxx_incomplete_type_error (r, rtype);
12408 TREE_TYPE (r) = error_mark_node;
12410 else if (TREE_CODE (rtype) == ARRAY_TYPE
12411 && TYPE_DOMAIN (rtype) == NULL_TREE
12412 && (TREE_CODE (type) == UNION_TYPE
12413 || TREE_CODE (type) == QUAL_UNION_TYPE))
12415 error ("flexible array member %qD in union", r);
12416 TREE_TYPE (r) = error_mark_node;
12418 else if (!verify_type_context (input_location,
12419 TCTX_FIELD, rtype))
12420 TREE_TYPE (r) = error_mark_node;
12423 /* If it is a TYPE_DECL for a class-scoped
12424 ENUMERAL_TYPE, such a thing will already have
12425 been added to the field list by tsubst_enum
12426 in finish_member_declaration case above. */
12427 if (!(TREE_CODE (r) == TYPE_DECL
12428 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12429 && DECL_ARTIFICIAL (r)))
12431 set_current_access_from_decl (r);
12432 finish_member_declaration (r);
12438 else
12440 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12441 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12443 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12445 tree friend_type = t;
12446 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12448 /* template <class T> friend class C; */
12449 friend_type = tsubst_friend_class (friend_type, args);
12451 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12453 /* template <class T> friend class C::D; */
12454 friend_type = tsubst (friend_type, args,
12455 tf_warning_or_error, NULL_TREE);
12456 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12457 friend_type = TREE_TYPE (friend_type);
12459 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12460 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12462 /* This could be either
12464 friend class T::C;
12466 when dependent_type_p is false or
12468 template <class U> friend class T::C;
12470 otherwise. */
12471 /* Bump processing_template_decl in case this is something like
12472 template <class T> friend struct A<T>::B. */
12473 ++processing_template_decl;
12474 friend_type = tsubst (friend_type, args,
12475 tf_warning_or_error, NULL_TREE);
12476 --processing_template_decl;
12478 else if (uses_template_parms (friend_type))
12479 /* friend class C<T>; */
12480 friend_type = tsubst (friend_type, args,
12481 tf_warning_or_error, NULL_TREE);
12483 /* Otherwise it's
12485 friend class C;
12487 where C is already declared or
12489 friend class C<int>;
12491 We don't have to do anything in these cases. */
12493 if (friend_type != error_mark_node)
12494 make_friend_class (type, friend_type, /*complain=*/false);
12496 else
12498 /* Build new DECL_FRIENDLIST. */
12499 tree r;
12501 /* The file and line for this declaration, to
12502 assist in error message reporting. Since we
12503 called push_tinst_level above, we don't need to
12504 restore these. */
12505 input_location = DECL_SOURCE_LOCATION (t);
12507 if (TREE_CODE (t) == TEMPLATE_DECL)
12509 ++processing_template_decl;
12510 push_deferring_access_checks (dk_no_check);
12513 r = tsubst_friend_function (t, args);
12514 add_friend (type, r, /*complain=*/false);
12515 if (TREE_CODE (t) == TEMPLATE_DECL)
12517 pop_deferring_access_checks ();
12518 --processing_template_decl;
12524 if (fn_context)
12526 /* Restore these before substituting into the lambda capture
12527 initializers. */
12528 cp_unevaluated_operand = saved_unevaluated_operand;
12529 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12532 /* Set the file and line number information to whatever is given for
12533 the class itself. This puts error messages involving generated
12534 implicit functions at a predictable point, and the same point
12535 that would be used for non-template classes. */
12536 input_location = DECL_SOURCE_LOCATION (typedecl);
12538 unreverse_member_declarations (type);
12539 finish_struct_1 (type);
12540 TYPE_BEING_DEFINED (type) = 0;
12542 /* Remember if instantiating this class ran into errors, so we can avoid
12543 instantiating member functions in limit_bad_template_recursion. We set
12544 this flag even if the problem was in another instantiation triggered by
12545 this one, as that will likely also cause trouble for member functions. */
12546 if (errorcount + sorrycount > current_tinst_level->errors)
12547 CLASSTYPE_ERRONEOUS (type) = true;
12549 /* We don't instantiate default arguments for member functions. 14.7.1:
12551 The implicit instantiation of a class template specialization causes
12552 the implicit instantiation of the declarations, but not of the
12553 definitions or default arguments, of the class member functions,
12554 member classes, static data members and member templates.... */
12556 perform_instantiation_time_access_checks (pattern, args);
12557 perform_deferred_access_checks (tf_warning_or_error);
12559 /* Now that we've gone through all the members, instantiate those
12560 marked with attribute used. We must do this in the context of
12561 the class -- not the context we pushed from, as that might be
12562 inside a template and change the behaviour of mark_used. */
12563 for (tree x : used)
12564 mark_used (x);
12566 pop_nested_class ();
12567 maximum_field_alignment = saved_maximum_field_alignment;
12568 if (!fn_context)
12569 pop_from_top_level ();
12570 pop_tinst_level ();
12572 /* The vtable for a template class can be emitted in any translation
12573 unit in which the class is instantiated. When there is no key
12574 method, however, finish_struct_1 will already have added TYPE to
12575 the keyed_classes. */
12576 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12577 vec_safe_push (keyed_classes, type);
12579 return type;
12582 tree
12583 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12585 tree r;
12587 if (!t)
12588 r = t;
12589 else if (TYPE_P (t))
12590 r = tsubst (t, args, complain, in_decl);
12591 else
12593 if (!(complain & tf_warning))
12594 ++c_inhibit_evaluation_warnings;
12595 r = tsubst_expr (t, args, complain, in_decl);
12596 if (!(complain & tf_warning))
12597 --c_inhibit_evaluation_warnings;
12600 return r;
12603 /* Given a function parameter pack TMPL_PARM and some function parameters
12604 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12605 and set *SPEC_P to point at the next point in the list. */
12607 tree
12608 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12610 /* Collect all of the extra "packed" parameters into an
12611 argument pack. */
12612 tree argpack;
12613 tree spec_parm = *spec_p;
12614 int len;
12616 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12617 if (tmpl_parm
12618 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12619 break;
12621 spec_parm = *spec_p;
12622 if (len == 1 && DECL_PACK_P (spec_parm))
12624 /* The instantiation is still a parameter pack; don't wrap it in a
12625 NONTYPE_ARGUMENT_PACK. */
12626 argpack = spec_parm;
12627 spec_parm = DECL_CHAIN (spec_parm);
12629 else
12631 /* Fill in PARMVEC with all of the parameters. */
12632 tree parmvec = make_tree_vec (len);
12633 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12634 for (int i = 0; i < len; i++)
12636 tree elt = spec_parm;
12637 if (DECL_PACK_P (elt))
12638 elt = make_pack_expansion (elt);
12639 TREE_VEC_ELT (parmvec, i) = elt;
12640 spec_parm = DECL_CHAIN (spec_parm);
12643 /* Build the argument packs. */
12644 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12646 *spec_p = spec_parm;
12648 return argpack;
12651 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12652 NONTYPE_ARGUMENT_PACK. */
12654 static tree
12655 make_fnparm_pack (tree spec_parm)
12657 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12660 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12661 pack expansion with no extra args, 2 if it has extra args, or 0
12662 if it is not a pack expansion. */
12664 static int
12665 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12667 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12668 /* We're being called before this happens in tsubst_pack_expansion. */
12669 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12670 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12671 if (i >= TREE_VEC_LENGTH (vec))
12672 return 0;
12673 tree elt = TREE_VEC_ELT (vec, i);
12674 if (DECL_P (elt))
12675 /* A decl pack is itself an expansion. */
12676 elt = TREE_TYPE (elt);
12677 if (!PACK_EXPANSION_P (elt))
12678 return 0;
12679 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12680 return 2;
12681 return 1;
12685 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12687 static tree
12688 make_argument_pack_select (tree arg_pack, unsigned index)
12690 tree aps = make_node (ARGUMENT_PACK_SELECT);
12692 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12693 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12695 return aps;
12698 /* This is a subroutine of tsubst_pack_expansion.
12700 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12701 mechanism to store the (non complete list of) arguments of the
12702 substitution and return a non substituted pack expansion, in order
12703 to wait for when we have enough arguments to really perform the
12704 substitution. */
12706 static bool
12707 use_pack_expansion_extra_args_p (tree t,
12708 tree parm_packs,
12709 int arg_pack_len,
12710 bool has_empty_arg)
12712 if (has_empty_arg
12713 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12714 return true;
12716 /* If one pack has an expansion and another pack has a normal
12717 argument or if one pack has an empty argument and an another
12718 one hasn't then tsubst_pack_expansion cannot perform the
12719 substitution and need to fall back on the
12720 PACK_EXPANSION_EXTRA mechanism. */
12721 if (parm_packs == NULL_TREE)
12722 return false;
12723 else if (has_empty_arg)
12725 /* If all the actual packs are pack expansions, we can still
12726 subsitute directly. */
12727 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12729 tree a = TREE_VALUE (p);
12730 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12731 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12732 a = ARGUMENT_PACK_ARGS (a);
12733 if (TREE_VEC_LENGTH (a) == 1)
12734 a = TREE_VEC_ELT (a, 0);
12735 if (PACK_EXPANSION_P (a))
12736 continue;
12737 return true;
12739 return false;
12742 for (int i = 0 ; i < arg_pack_len; ++i)
12744 bool has_expansion_arg = false;
12745 bool has_non_expansion_arg = false;
12746 for (tree parm_pack = parm_packs;
12747 parm_pack;
12748 parm_pack = TREE_CHAIN (parm_pack))
12750 tree arg = TREE_VALUE (parm_pack);
12752 int exp = argument_pack_element_is_expansion_p (arg, i);
12753 if (exp == 2)
12754 /* We can't substitute a pack expansion with extra args into
12755 our pattern. */
12756 return true;
12757 else if (exp)
12758 has_expansion_arg = true;
12759 else
12760 has_non_expansion_arg = true;
12763 if (has_expansion_arg && has_non_expansion_arg)
12765 gcc_checking_assert (false);
12766 return true;
12769 return false;
12772 /* [temp.variadic]/6 says that:
12774 The instantiation of a pack expansion [...]
12775 produces a list E1,E2, ..., En, where N is the number of elements
12776 in the pack expansion parameters.
12778 This subroutine of tsubst_pack_expansion produces one of these Ei.
12780 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12781 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12782 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12783 INDEX is the index 'i' of the element Ei to produce. ARGS,
12784 COMPLAIN, and IN_DECL are the same parameters as for the
12785 tsubst_pack_expansion function.
12787 The function returns the resulting Ei upon successful completion,
12788 or error_mark_node.
12790 Note that this function possibly modifies the ARGS parameter, so
12791 it's the responsibility of the caller to restore it. */
12793 static tree
12794 gen_elem_of_pack_expansion_instantiation (tree pattern,
12795 tree parm_packs,
12796 unsigned index,
12797 tree args /* This parm gets
12798 modified. */,
12799 tsubst_flags_t complain,
12800 tree in_decl)
12802 tree t;
12803 bool ith_elem_is_expansion = false;
12805 /* For each parameter pack, change the substitution of the parameter
12806 pack to the ith argument in its argument pack, then expand the
12807 pattern. */
12808 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12810 tree parm = TREE_PURPOSE (pack);
12811 tree arg_pack = TREE_VALUE (pack);
12812 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12814 ith_elem_is_expansion |=
12815 argument_pack_element_is_expansion_p (arg_pack, index);
12817 /* Select the Ith argument from the pack. */
12818 if (TREE_CODE (parm) == PARM_DECL
12819 || VAR_P (parm)
12820 || TREE_CODE (parm) == FIELD_DECL)
12822 if (index == 0)
12824 aps = make_argument_pack_select (arg_pack, index);
12825 if (!mark_used (parm, complain) && !(complain & tf_error))
12826 return error_mark_node;
12827 register_local_specialization (aps, parm);
12829 else
12830 aps = retrieve_local_specialization (parm);
12832 else
12834 int idx, level;
12835 template_parm_level_and_index (parm, &level, &idx);
12837 if (index == 0)
12839 aps = make_argument_pack_select (arg_pack, index);
12840 /* Update the corresponding argument. */
12841 TMPL_ARG (args, level, idx) = aps;
12843 else
12844 /* Re-use the ARGUMENT_PACK_SELECT. */
12845 aps = TMPL_ARG (args, level, idx);
12847 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12850 /* Substitute into the PATTERN with the (possibly altered)
12851 arguments. */
12852 if (pattern == in_decl)
12853 /* Expanding a fixed parameter pack from
12854 coerce_template_parameter_pack. */
12855 t = tsubst_decl (pattern, args, complain);
12856 else if (pattern == error_mark_node)
12857 t = error_mark_node;
12858 else if (!TYPE_P (pattern))
12859 t = tsubst_expr (pattern, args, complain, in_decl);
12860 else
12862 t = tsubst (pattern, args, complain, in_decl);
12863 if (is_auto (t) && !ith_elem_is_expansion)
12864 /* When expanding the fake auto... pack expansion from add_capture, we
12865 need to mark that the expansion is no longer a pack. */
12866 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12869 /* If the Ith argument pack element is a pack expansion, then
12870 the Ith element resulting from the substituting is going to
12871 be a pack expansion as well. */
12872 if (ith_elem_is_expansion)
12873 t = make_pack_expansion (t, complain);
12875 return t;
12878 /* When the unexpanded parameter pack in a fold expression expands to an empty
12879 sequence, the value of the expression is as follows; the program is
12880 ill-formed if the operator is not listed in this table.
12882 && true
12883 || false
12884 , void() */
12886 tree
12887 expand_empty_fold (tree t, tsubst_flags_t complain)
12889 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12890 if (!FOLD_EXPR_MODIFY_P (t))
12891 switch (code)
12893 case TRUTH_ANDIF_EXPR:
12894 return boolean_true_node;
12895 case TRUTH_ORIF_EXPR:
12896 return boolean_false_node;
12897 case COMPOUND_EXPR:
12898 return void_node;
12899 default:
12900 break;
12903 if (complain & tf_error)
12904 error_at (location_of (t),
12905 "fold of empty expansion over %O", code);
12906 return error_mark_node;
12909 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12910 form an expression that combines the two terms using the
12911 operator of T. */
12913 static tree
12914 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12916 tree_code code = FOLD_EXPR_OP (t);
12918 tree lookups = templated_operator_saved_lookups (t);
12920 // Handle compound assignment operators.
12921 if (FOLD_EXPR_MODIFY_P (t))
12922 return build_x_modify_expr (input_location, left, code, right,
12923 lookups, complain);
12925 warning_sentinel s(warn_parentheses);
12926 switch (code)
12928 case COMPOUND_EXPR:
12929 return build_x_compound_expr (input_location, left, right,
12930 lookups, complain);
12931 default:
12932 return build_x_binary_op (input_location, code,
12933 left, TREE_CODE (left),
12934 right, TREE_CODE (right),
12935 lookups, /*overload=*/NULL,
12936 complain);
12940 /* Substitute ARGS into the pack of a fold expression T. */
12942 static inline tree
12943 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12945 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12948 /* Substitute ARGS into the pack of a fold expression T. */
12950 static inline tree
12951 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12953 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12956 /* Expand a PACK of arguments into a grouped as left fold.
12957 Given a pack containing elements A0, A1, ..., An and an
12958 operator @, this builds the expression:
12960 ((A0 @ A1) @ A2) ... @ An
12962 Note that PACK must not be empty.
12964 The operator is defined by the original fold expression T. */
12966 static tree
12967 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12969 tree left = TREE_VEC_ELT (pack, 0);
12970 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12972 tree right = TREE_VEC_ELT (pack, i);
12973 left = fold_expression (t, left, right, complain);
12975 return left;
12978 /* Substitute into a unary left fold expression. */
12980 static tree
12981 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12982 tree in_decl)
12984 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12985 if (pack == error_mark_node)
12986 return error_mark_node;
12987 if (PACK_EXPANSION_P (pack))
12989 tree r = copy_node (t);
12990 FOLD_EXPR_PACK (r) = pack;
12991 return r;
12993 if (TREE_VEC_LENGTH (pack) == 0)
12994 return expand_empty_fold (t, complain);
12995 else
12996 return expand_left_fold (t, pack, complain);
12999 /* Substitute into a binary left fold expression.
13001 Do ths by building a single (non-empty) vector of argumnts and
13002 building the expression from those elements. */
13004 static tree
13005 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13006 tree in_decl)
13008 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13009 if (pack == error_mark_node)
13010 return error_mark_node;
13011 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13012 if (init == error_mark_node)
13013 return error_mark_node;
13015 if (PACK_EXPANSION_P (pack))
13017 tree r = copy_node (t);
13018 FOLD_EXPR_PACK (r) = pack;
13019 FOLD_EXPR_INIT (r) = init;
13020 return r;
13023 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13024 TREE_VEC_ELT (vec, 0) = init;
13025 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13026 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13028 return expand_left_fold (t, vec, complain);
13031 /* Expand a PACK of arguments into a grouped as right fold.
13032 Given a pack containing elementns A0, A1, ..., and an
13033 operator @, this builds the expression:
13035 A0@ ... (An-2 @ (An-1 @ An))
13037 Note that PACK must not be empty.
13039 The operator is defined by the original fold expression T. */
13041 tree
13042 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13044 // Build the expression.
13045 int n = TREE_VEC_LENGTH (pack);
13046 tree right = TREE_VEC_ELT (pack, n - 1);
13047 for (--n; n != 0; --n)
13049 tree left = TREE_VEC_ELT (pack, n - 1);
13050 right = fold_expression (t, left, right, complain);
13052 return right;
13055 /* Substitute into a unary right fold expression. */
13057 static tree
13058 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13059 tree in_decl)
13061 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13062 if (pack == error_mark_node)
13063 return error_mark_node;
13064 if (PACK_EXPANSION_P (pack))
13066 tree r = copy_node (t);
13067 FOLD_EXPR_PACK (r) = pack;
13068 return r;
13070 if (TREE_VEC_LENGTH (pack) == 0)
13071 return expand_empty_fold (t, complain);
13072 else
13073 return expand_right_fold (t, pack, complain);
13076 /* Substitute into a binary right fold expression.
13078 Do ths by building a single (non-empty) vector of arguments and
13079 building the expression from those elements. */
13081 static tree
13082 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13083 tree in_decl)
13085 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13086 if (pack == error_mark_node)
13087 return error_mark_node;
13088 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13089 if (init == error_mark_node)
13090 return error_mark_node;
13092 if (PACK_EXPANSION_P (pack))
13094 tree r = copy_node (t);
13095 FOLD_EXPR_PACK (r) = pack;
13096 FOLD_EXPR_INIT (r) = init;
13097 return r;
13100 int n = TREE_VEC_LENGTH (pack);
13101 tree vec = make_tree_vec (n + 1);
13102 for (int i = 0; i < n; ++i)
13103 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13104 TREE_VEC_ELT (vec, n) = init;
13106 return expand_right_fold (t, vec, complain);
13109 /* Walk through the pattern of a pack expansion, adding everything in
13110 local_specializations to a list. */
13112 class el_data
13114 public:
13115 /* Set of variables declared within the pattern. */
13116 hash_set<tree> internal;
13117 /* Set of AST nodes that have been visited by the traversal. */
13118 hash_set<tree> visited;
13119 /* List of local_specializations used within the pattern. */
13120 tree extra;
13121 tsubst_flags_t complain;
13122 /* True iff we don't want to walk into unevaluated contexts. */
13123 bool skip_unevaluated_operands = false;
13124 /* The unevaluated contexts that we avoided walking. */
13125 auto_vec<tree> skipped_trees;
13127 el_data (tsubst_flags_t c)
13128 : extra (NULL_TREE), complain (c) {}
13130 static tree
13131 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13133 el_data &data = *reinterpret_cast<el_data*>(data_);
13134 tree *extra = &data.extra;
13135 tsubst_flags_t complain = data.complain;
13137 if (data.skip_unevaluated_operands
13138 && unevaluated_p (TREE_CODE (*tp)))
13140 data.skipped_trees.safe_push (*tp);
13141 *walk_subtrees = 0;
13142 return NULL_TREE;
13145 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13146 /* Remember local typedefs (85214). */
13147 tp = &TYPE_NAME (*tp);
13149 if (TREE_CODE (*tp) == DECL_EXPR)
13151 tree decl = DECL_EXPR_DECL (*tp);
13152 data.internal.add (decl);
13153 if (VAR_P (decl)
13154 && DECL_DECOMPOSITION_P (decl)
13155 && TREE_TYPE (decl) != error_mark_node)
13157 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13158 for (tree decl2 = DECL_CHAIN (decl);
13159 decl2
13160 && VAR_P (decl2)
13161 && DECL_DECOMPOSITION_P (decl2)
13162 && DECL_NAME (decl2)
13163 && TREE_TYPE (decl2) != error_mark_node;
13164 decl2 = DECL_CHAIN (decl2))
13166 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13167 data.internal.add (decl2);
13171 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13173 /* Since we defer implicit capture, look in the parms and body. */
13174 tree fn = lambda_function (*tp);
13175 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13176 &data.visited);
13177 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13178 &data.visited);
13180 else if (tree spec = retrieve_local_specialization (*tp))
13182 if (data.internal.contains (*tp))
13183 /* Don't mess with variables declared within the pattern. */
13184 return NULL_TREE;
13185 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13187 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13188 tree args = ARGUMENT_PACK_ARGS (spec);
13189 if (TREE_VEC_LENGTH (args) == 1)
13191 tree elt = TREE_VEC_ELT (args, 0);
13192 if (PACK_EXPANSION_P (elt))
13193 elt = PACK_EXPANSION_PATTERN (elt);
13194 if (DECL_PACK_P (elt))
13195 spec = elt;
13197 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13199 /* Handle lambda capture here, since we aren't doing any
13200 substitution now, and so tsubst_copy won't call
13201 process_outer_var_ref. */
13202 tree args = ARGUMENT_PACK_ARGS (spec);
13203 int len = TREE_VEC_LENGTH (args);
13204 for (int i = 0; i < len; ++i)
13206 tree arg = TREE_VEC_ELT (args, i);
13207 tree carg = arg;
13208 if (outer_automatic_var_p (arg))
13209 carg = process_outer_var_ref (arg, complain);
13210 if (carg != arg)
13212 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13213 proxies. */
13214 if (i == 0)
13216 spec = copy_node (spec);
13217 args = copy_node (args);
13218 ARGUMENT_PACK_ARGS (spec) = args;
13219 register_local_specialization (spec, *tp);
13221 TREE_VEC_ELT (args, i) = carg;
13226 if (outer_automatic_var_p (spec))
13227 spec = process_outer_var_ref (spec, complain);
13228 *extra = tree_cons (*tp, spec, *extra);
13230 return NULL_TREE;
13232 static tree
13233 extract_local_specs (tree pattern, tsubst_flags_t complain)
13235 el_data data (complain);
13236 /* Walk the pattern twice, ignoring unevaluated operands the first time
13237 around, so that if a local specialization appears in both an evaluated
13238 and unevaluated context we prefer to process it in the evaluated context
13239 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13240 context). */
13241 data.skip_unevaluated_operands = true;
13242 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13243 /* Now walk the unevaluated contexts we skipped the first time around. */
13244 data.skip_unevaluated_operands = false;
13245 for (tree t : data.skipped_trees)
13247 data.visited.remove (t);
13248 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13250 return data.extra;
13253 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13254 for use in PACK_EXPANSION_EXTRA_ARGS. */
13256 tree
13257 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13259 /* Make a copy of the extra arguments so that they won't get changed
13260 out from under us. */
13261 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13262 if (local_specializations)
13263 if (tree locals = extract_local_specs (pattern, complain))
13264 extra = tree_cons (NULL_TREE, extra, locals);
13265 return extra;
13268 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13269 normal template args to ARGS. */
13271 tree
13272 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13274 if (extra && TREE_CODE (extra) == TREE_LIST)
13276 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13278 /* The partial instantiation involved local declarations collected in
13279 extract_local_specs; map from the general template to our local
13280 context. */
13281 tree gen = TREE_PURPOSE (elt);
13282 tree inst = TREE_VALUE (elt);
13283 if (DECL_P (inst))
13284 if (tree local = retrieve_local_specialization (inst))
13285 inst = local;
13286 /* else inst is already a full instantiation of the pack. */
13287 register_local_specialization (inst, gen);
13289 gcc_assert (!TREE_PURPOSE (extra));
13290 extra = TREE_VALUE (extra);
13292 if (uses_template_parms (extra))
13294 /* This can happen after dependent substitution into a
13295 requires-expr or a lambda that uses constexpr if. */
13296 extra = tsubst_template_args (extra, args, complain, in_decl);
13297 args = add_outermost_template_args (args, extra);
13299 else
13300 args = add_to_template_args (extra, args);
13301 return args;
13304 /* Substitute ARGS into T, which is an pack expansion
13305 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13306 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13307 (if only a partial substitution could be performed) or
13308 ERROR_MARK_NODE if there was an error. */
13309 tree
13310 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13311 tree in_decl)
13313 tree pattern;
13314 tree pack, packs = NULL_TREE;
13315 bool unsubstituted_packs = false;
13316 int i, len = -1;
13317 tree result;
13318 bool need_local_specializations = false;
13319 int levels;
13321 gcc_assert (PACK_EXPANSION_P (t));
13322 pattern = PACK_EXPANSION_PATTERN (t);
13324 /* Add in any args remembered from an earlier partial instantiation. */
13325 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13327 levels = TMPL_ARGS_DEPTH (args);
13329 /* Determine the argument packs that will instantiate the parameter
13330 packs used in the expansion expression. While we're at it,
13331 compute the number of arguments to be expanded and make sure it
13332 is consistent. */
13333 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13334 pack = TREE_CHAIN (pack))
13336 tree parm_pack = TREE_VALUE (pack);
13337 tree arg_pack = NULL_TREE;
13338 tree orig_arg = NULL_TREE;
13339 int level = 0;
13341 if (TREE_CODE (parm_pack) == BASES)
13343 gcc_assert (parm_pack == pattern);
13344 if (BASES_DIRECT (parm_pack))
13345 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13346 args, complain,
13347 in_decl),
13348 complain);
13349 else
13350 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13351 args, complain, in_decl),
13352 complain);
13354 else if (builtin_pack_call_p (parm_pack))
13356 if (parm_pack != pattern)
13358 if (complain & tf_error)
13359 sorry ("%qE is not the entire pattern of the pack expansion",
13360 parm_pack);
13361 return error_mark_node;
13363 return expand_builtin_pack_call (parm_pack, args,
13364 complain, in_decl);
13366 else if (TREE_CODE (parm_pack) == PARM_DECL)
13368 /* We know we have correct local_specializations if this
13369 expansion is at function scope, or if we're dealing with a
13370 local parameter in a requires expression; for the latter,
13371 tsubst_requires_expr set it up appropriately. */
13372 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13373 arg_pack = retrieve_local_specialization (parm_pack);
13374 else
13375 /* We can't rely on local_specializations for a parameter
13376 name used later in a function declaration (such as in a
13377 late-specified return type). Even if it exists, it might
13378 have the wrong value for a recursive call. */
13379 need_local_specializations = true;
13381 if (!arg_pack)
13383 /* This parameter pack was used in an unevaluated context. Just
13384 make a dummy decl, since it's only used for its type. */
13385 ++cp_unevaluated_operand;
13386 arg_pack = tsubst_decl (parm_pack, args, complain);
13387 --cp_unevaluated_operand;
13388 if (arg_pack && DECL_PACK_P (arg_pack))
13389 /* Partial instantiation of the parm_pack, we can't build
13390 up an argument pack yet. */
13391 arg_pack = NULL_TREE;
13392 else
13393 arg_pack = make_fnparm_pack (arg_pack);
13395 else if (DECL_PACK_P (arg_pack))
13396 /* This argument pack isn't fully instantiated yet. */
13397 arg_pack = NULL_TREE;
13399 else if (is_capture_proxy (parm_pack))
13401 arg_pack = retrieve_local_specialization (parm_pack);
13402 if (DECL_PACK_P (arg_pack))
13403 arg_pack = NULL_TREE;
13405 else
13407 int idx;
13408 template_parm_level_and_index (parm_pack, &level, &idx);
13409 if (level <= levels)
13410 arg_pack = TMPL_ARG (args, level, idx);
13412 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13413 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13414 arg_pack = NULL_TREE;
13417 orig_arg = arg_pack;
13418 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13419 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13421 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13422 /* This can only happen if we forget to expand an argument
13423 pack somewhere else. Just return an error, silently. */
13425 result = make_tree_vec (1);
13426 TREE_VEC_ELT (result, 0) = error_mark_node;
13427 return result;
13430 if (arg_pack)
13432 int my_len =
13433 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13435 /* Don't bother trying to do a partial substitution with
13436 incomplete packs; we'll try again after deduction. */
13437 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13438 return t;
13440 if (len < 0)
13441 len = my_len;
13442 else if (len != my_len)
13444 if (!(complain & tf_error))
13445 /* Fail quietly. */;
13446 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13447 error ("mismatched argument pack lengths while expanding %qT",
13448 pattern);
13449 else
13450 error ("mismatched argument pack lengths while expanding %qE",
13451 pattern);
13452 return error_mark_node;
13455 /* Keep track of the parameter packs and their corresponding
13456 argument packs. */
13457 packs = tree_cons (parm_pack, arg_pack, packs);
13458 TREE_TYPE (packs) = orig_arg;
13460 else
13462 /* We can't substitute for this parameter pack. We use a flag as
13463 well as the missing_level counter because function parameter
13464 packs don't have a level. */
13465 gcc_assert (processing_template_decl || is_auto (parm_pack));
13466 unsubstituted_packs = true;
13470 /* If the expansion is just T..., return the matching argument pack, unless
13471 we need to call convert_from_reference on all the elements. This is an
13472 important optimization; see c++/68422. */
13473 if (!unsubstituted_packs
13474 && TREE_PURPOSE (packs) == pattern)
13476 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13478 /* If the argument pack is a single pack expansion, pull it out. */
13479 if (TREE_VEC_LENGTH (args) == 1
13480 && pack_expansion_args_count (args))
13481 return TREE_VEC_ELT (args, 0);
13483 /* Types need no adjustment, nor does sizeof..., and if we still have
13484 some pack expansion args we won't do anything yet. */
13485 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13486 || PACK_EXPANSION_SIZEOF_P (t)
13487 || pack_expansion_args_count (args))
13488 return args;
13489 /* Also optimize expression pack expansions if we can tell that the
13490 elements won't have reference type. */
13491 tree type = TREE_TYPE (pattern);
13492 if (type && !TYPE_REF_P (type)
13493 && !PACK_EXPANSION_P (type)
13494 && !WILDCARD_TYPE_P (type))
13495 return args;
13496 /* Otherwise use the normal path so we get convert_from_reference. */
13499 /* We cannot expand this expansion expression, because we don't have
13500 all of the argument packs we need. */
13501 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13503 /* We got some full packs, but we can't substitute them in until we
13504 have values for all the packs. So remember these until then. */
13506 t = make_pack_expansion (pattern, complain);
13507 PACK_EXPANSION_EXTRA_ARGS (t)
13508 = build_extra_args (pattern, args, complain);
13509 return t;
13512 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13513 type, so create our own local specializations map; the current map is
13514 either NULL or (in the case of recursive unification) might have
13515 bindings that we don't want to use or alter. */
13516 local_specialization_stack lss (need_local_specializations
13517 ? lss_blank : lss_nop);
13519 if (unsubstituted_packs)
13521 /* There were no real arguments, we're just replacing a parameter
13522 pack with another version of itself. Substitute into the
13523 pattern and return a PACK_EXPANSION_*. The caller will need to
13524 deal with that. */
13525 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13526 result = tsubst_expr (pattern, args, complain, in_decl);
13527 else
13528 result = tsubst (pattern, args, complain, in_decl);
13529 result = make_pack_expansion (result, complain);
13530 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13531 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13532 if (PACK_EXPANSION_AUTO_P (t))
13534 /* This is a fake auto... pack expansion created in add_capture with
13535 _PACKS that don't appear in the pattern. Copy one over. */
13536 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13537 pack = retrieve_local_specialization (TREE_VALUE (packs));
13538 gcc_checking_assert (DECL_PACK_P (pack));
13539 PACK_EXPANSION_PARAMETER_PACKS (result)
13540 = build_tree_list (NULL_TREE, pack);
13541 PACK_EXPANSION_AUTO_P (result) = true;
13543 return result;
13546 gcc_assert (len >= 0);
13548 /* For each argument in each argument pack, substitute into the
13549 pattern. */
13550 result = make_tree_vec (len);
13551 tree elem_args = copy_template_args (args);
13552 for (i = 0; i < len; ++i)
13554 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13556 elem_args, complain,
13557 in_decl);
13558 TREE_VEC_ELT (result, i) = t;
13559 if (t == error_mark_node)
13561 result = error_mark_node;
13562 break;
13566 /* Update ARGS to restore the substitution from parameter packs to
13567 their argument packs. */
13568 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13570 tree parm = TREE_PURPOSE (pack);
13572 if (TREE_CODE (parm) == PARM_DECL
13573 || VAR_P (parm)
13574 || TREE_CODE (parm) == FIELD_DECL)
13575 register_local_specialization (TREE_TYPE (pack), parm);
13576 else
13578 int idx, level;
13580 if (TREE_VALUE (pack) == NULL_TREE)
13581 continue;
13583 template_parm_level_and_index (parm, &level, &idx);
13585 /* Update the corresponding argument. */
13586 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13587 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13588 TREE_TYPE (pack);
13589 else
13590 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13594 /* If the dependent pack arguments were such that we end up with only a
13595 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13596 if (len == 1 && TREE_CODE (result) == TREE_VEC
13597 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13598 return TREE_VEC_ELT (result, 0);
13600 return result;
13603 /* Make an argument pack out of the TREE_VEC VEC. */
13605 static tree
13606 make_argument_pack (tree vec)
13608 tree pack;
13610 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13611 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13612 else
13614 pack = make_node (NONTYPE_ARGUMENT_PACK);
13615 TREE_CONSTANT (pack) = 1;
13617 ARGUMENT_PACK_ARGS (pack) = vec;
13618 return pack;
13621 /* Return an exact copy of template args T that can be modified
13622 independently. */
13624 static tree
13625 copy_template_args (tree t)
13627 if (t == error_mark_node)
13628 return t;
13630 int len = TREE_VEC_LENGTH (t);
13631 tree new_vec = make_tree_vec (len);
13633 for (int i = 0; i < len; ++i)
13635 tree elt = TREE_VEC_ELT (t, i);
13636 if (elt && TREE_CODE (elt) == TREE_VEC)
13637 elt = copy_template_args (elt);
13638 TREE_VEC_ELT (new_vec, i) = elt;
13641 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13642 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13644 return new_vec;
13647 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13649 tree
13650 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13651 tree in_decl)
13653 /* This flag is used only during deduction, and we don't expect to
13654 substitute such ARGUMENT_PACKs. */
13655 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13657 /* Substitute into each of the arguments. */
13658 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13659 args, complain, in_decl);
13660 if (pack_args == error_mark_node)
13661 return error_mark_node;
13663 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13664 return orig_arg;
13666 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13667 template parameter, we might be able to avoid allocating a new
13668 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13669 if the substituted result is identical to it. */
13670 if (tree parm = template_arg_to_parm (orig_arg))
13672 int level, index;
13673 template_parm_level_and_index (parm, &level, &index);
13674 if (TMPL_ARGS_DEPTH (args) >= level)
13675 if (tree arg = TMPL_ARG (args, level, index))
13676 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13677 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13679 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13680 return arg;
13684 tree new_arg;
13685 if (TYPE_P (orig_arg))
13687 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13688 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13690 else
13692 new_arg = make_node (TREE_CODE (orig_arg));
13693 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13695 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13696 return new_arg;
13699 /* Substitute ARGS into the vector or list of template arguments T. */
13701 tree
13702 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13704 if (t == error_mark_node)
13705 return error_mark_node;
13707 /* In "sizeof(X<I>)" we need to evaluate "I". */
13708 cp_evaluated ev;
13710 const int len = TREE_VEC_LENGTH (t);
13711 tree *elts = XALLOCAVEC (tree, len);
13712 int expanded_len_adjust = 0;
13714 /* True iff the substituted result is identical to T. */
13715 bool const_subst_p = true;
13717 for (int i = 0; i < len; i++)
13719 tree orig_arg = TREE_VEC_ELT (t, i);
13720 tree new_arg;
13722 if (!orig_arg)
13723 new_arg = NULL_TREE;
13724 else if (TREE_CODE (orig_arg) == TREE_VEC)
13725 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13726 else if (PACK_EXPANSION_P (orig_arg))
13728 /* Substitute into an expansion expression. */
13729 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13731 if (TREE_CODE (new_arg) == TREE_VEC)
13732 /* Add to the expanded length adjustment the number of
13733 expanded arguments. We subtract one from this
13734 measurement, because the argument pack expression
13735 itself is already counted as 1 in
13736 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13737 the argument pack is empty. */
13738 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13740 else if (ARGUMENT_PACK_P (orig_arg))
13741 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13742 else
13743 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13745 if (new_arg == error_mark_node)
13746 return error_mark_node;
13748 elts[i] = new_arg;
13749 if (new_arg != orig_arg)
13750 const_subst_p = false;
13753 if (const_subst_p)
13754 return t;
13756 tree maybe_reuse = NULL_TREE;
13758 /* If ARGS and T are both multi-level, the substituted result may be
13759 identical to ARGS. */
13760 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13761 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13762 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13763 maybe_reuse = args;
13764 /* If T appears to be a vector of generic template arguments, the
13765 substituted result may be identical to the corresponding level
13766 from ARGS. */
13767 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13769 int level, index;
13770 template_parm_level_and_index (parm, &level, &index);
13771 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13772 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13775 /* If the substituted result is identical to MAYBE_REUSE, return
13776 it and avoid allocating a new TREE_VEC, as an optimization. */
13777 if (maybe_reuse != NULL_TREE
13778 && TREE_VEC_LENGTH (maybe_reuse) == len
13779 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13780 return maybe_reuse;
13782 /* If T consists of only a pack expansion for which substitution yielded
13783 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13784 of effectively making a copy. */
13785 if (len == 1
13786 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13787 && TREE_CODE (elts[0]) == TREE_VEC)
13788 return elts[0];
13790 /* Make space for the expanded arguments coming from template
13791 argument packs. */
13792 tree r = make_tree_vec (len + expanded_len_adjust);
13793 /* T can contain TREE_VECs. That happens if T contains the
13794 arguments for a member template.
13795 In that case each TREE_VEC in T represents a level of template
13796 arguments, and T won't carry any non defaulted argument count.
13797 It will rather be the nested TREE_VECs that will carry one.
13798 In other words, T carries a non defaulted argument count only
13799 if it doesn't contain any nested TREE_VEC. */
13800 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13802 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13803 count += expanded_len_adjust;
13804 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13807 int out = 0;
13808 for (int i = 0; i < len; i++)
13810 tree orig_arg = TREE_VEC_ELT (t, i);
13811 if (orig_arg
13812 && PACK_EXPANSION_P (orig_arg)
13813 && TREE_CODE (elts[i]) == TREE_VEC)
13815 /* Now expand the template argument pack "in place". */
13816 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13817 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13819 else
13821 TREE_VEC_ELT (r, out) = elts[i];
13822 out++;
13825 gcc_assert (out == TREE_VEC_LENGTH (r));
13827 return r;
13830 /* Substitute ARGS into one level PARMS of template parameters. */
13832 static tree
13833 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13835 if (parms == error_mark_node)
13836 return error_mark_node;
13838 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13840 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13842 tree tuple = TREE_VEC_ELT (parms, i);
13844 if (tuple == error_mark_node)
13845 continue;
13847 TREE_VEC_ELT (new_vec, i) =
13848 tsubst_template_parm (tuple, args, complain);
13851 return new_vec;
13854 /* Return the result of substituting ARGS into the template parameters
13855 given by PARMS. If there are m levels of ARGS and m + n levels of
13856 PARMS, then the result will contain n levels of PARMS. For
13857 example, if PARMS is `template <class T> template <class U>
13858 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13859 result will be `template <int*, double, class V>'. */
13861 static tree
13862 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13864 tree r = NULL_TREE;
13865 tree* new_parms;
13867 /* When substituting into a template, we must set
13868 PROCESSING_TEMPLATE_DECL as the template parameters may be
13869 dependent if they are based on one-another, and the dependency
13870 predicates are short-circuit outside of templates. */
13871 ++processing_template_decl;
13873 for (new_parms = &r;
13874 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13875 new_parms = &(TREE_CHAIN (*new_parms)),
13876 parms = TREE_CHAIN (parms))
13878 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13879 args, complain);
13880 *new_parms =
13881 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13882 - TMPL_ARGS_DEPTH (args)),
13883 new_vec, NULL_TREE);
13884 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13885 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13888 --processing_template_decl;
13890 return r;
13893 /* Return the result of substituting ARGS into one template parameter
13894 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13895 parameter and which TREE_PURPOSE is the default argument of the
13896 template parameter. */
13898 static tree
13899 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13901 tree default_value, parm_decl;
13903 if (args == NULL_TREE
13904 || t == NULL_TREE
13905 || t == error_mark_node)
13906 return t;
13908 gcc_assert (TREE_CODE (t) == TREE_LIST);
13910 default_value = TREE_PURPOSE (t);
13911 parm_decl = TREE_VALUE (t);
13913 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13914 if (TREE_CODE (parm_decl) == PARM_DECL
13915 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13916 parm_decl = error_mark_node;
13917 default_value = tsubst_template_arg (default_value, args,
13918 complain, NULL_TREE);
13920 tree r = build_tree_list (default_value, parm_decl);
13921 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13922 return r;
13925 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13926 parameter in PARMS for sake of declaration matching. */
13928 static void
13929 tsubst_each_template_parm_constraints (tree parms, tree args,
13930 tsubst_flags_t complain)
13932 ++processing_template_decl;
13933 for (; parms; parms = TREE_CHAIN (parms))
13935 tree level = TREE_VALUE (parms);
13936 for (tree parm : tree_vec_range (level))
13937 TEMPLATE_PARM_CONSTRAINTS (parm)
13938 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13939 complain, NULL_TREE);
13941 --processing_template_decl;
13944 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13945 type T. If T is not an aggregate or enumeration type, it is
13946 handled as if by tsubst. IN_DECL is as for tsubst. If
13947 ENTERING_SCOPE is nonzero, T is the context for a template which
13948 we are presently tsubst'ing. Return the substituted value. */
13950 static tree
13951 tsubst_aggr_type (tree t,
13952 tree args,
13953 tsubst_flags_t complain,
13954 tree in_decl,
13955 int entering_scope)
13957 if (t == NULL_TREE)
13958 return NULL_TREE;
13960 /* Handle typedefs via tsubst so that they get consistently reused. */
13961 if (typedef_variant_p (t))
13963 t = tsubst (t, args, complain, in_decl);
13964 if (t == error_mark_node)
13965 return error_mark_node;
13967 /* The effect of entering_scope is that for a dependent specialization
13968 A<T>, lookup_template_class prefers to return A's primary template
13969 type instead of the implicit instantiation. So when entering_scope,
13970 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
13971 taking advantage of the fact that lookup_template_class links the two
13972 types by setting TYPE_CANONICAL of the latter to the former. */
13973 if (entering_scope
13974 && CLASS_TYPE_P (t)
13975 && dependent_type_p (t)
13976 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
13977 t = TYPE_CANONICAL (t);
13979 return t;
13982 switch (TREE_CODE (t))
13984 case RECORD_TYPE:
13985 case ENUMERAL_TYPE:
13986 case UNION_TYPE:
13987 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
13989 default:
13990 return tsubst (t, args, complain, in_decl);
13994 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
13995 and ENUMERAL_TYPE cases of tsubst. */
13997 static tree
13998 tsubst_aggr_type_1 (tree t,
13999 tree args,
14000 tsubst_flags_t complain,
14001 tree in_decl,
14002 int entering_scope)
14004 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14006 complain &= ~tf_qualifying_scope;
14008 /* Figure out what arguments are appropriate for the
14009 type we are trying to find. For example, given:
14011 template <class T> struct S;
14012 template <class T, class U> void f(T, U) { S<U> su; }
14014 and supposing that we are instantiating f<int, double>,
14015 then our ARGS will be {int, double}, but, when looking up
14016 S we only want {double}. */
14017 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14018 complain, in_decl);
14019 if (argvec == error_mark_node)
14020 return error_mark_node;
14022 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14023 entering_scope, complain);
14024 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14026 else
14027 /* This is not a template type, so there's nothing to do. */
14028 return t;
14031 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14032 indexed in reverse order of the parameters. */
14034 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14036 /* Return a reference to the vec* of defarg insts for FN. */
14038 static vec<tree,va_gc> *&
14039 defarg_insts_for (tree fn)
14041 if (!defarg_inst)
14042 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14043 tree_vec_map in = { { fn }, nullptr };
14044 tree_vec_map **slot
14045 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14046 if (!*slot)
14048 *slot = ggc_alloc<tree_vec_map> ();
14049 **slot = in;
14051 return (*slot)->to;
14054 /* Substitute into the default argument ARG (a default argument for
14055 FN), which has the indicated TYPE. */
14057 tree
14058 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14059 tsubst_flags_t complain)
14061 int errs = errorcount + sorrycount;
14063 /* This can happen in invalid code. */
14064 if (TREE_CODE (arg) == DEFERRED_PARSE)
14065 return arg;
14067 /* Shortcut {}. */
14068 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14069 && CONSTRUCTOR_NELTS (arg) == 0)
14070 return arg;
14072 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14073 parm = chain_index (parmnum, parm);
14074 tree parmtype = TREE_TYPE (parm);
14075 if (DECL_BY_REFERENCE (parm))
14076 parmtype = TREE_TYPE (parmtype);
14077 if (parmtype == error_mark_node)
14078 return error_mark_node;
14080 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14082 /* Remember the location of the pointer to the vec rather than the location
14083 of the particular element, in case the vec grows in tsubst_expr. */
14084 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14085 /* Index in reverse order to avoid allocating space for initial parameters
14086 that don't have default arguments. */
14087 unsigned ridx = list_length (parm);
14088 if (vec_safe_length (defs) < ridx)
14089 vec_safe_grow_cleared (defs, ridx);
14090 else if (tree inst = (*defs)[ridx - 1])
14091 return inst;
14093 /* This default argument came from a template. Instantiate the
14094 default argument here, not in tsubst. In the case of
14095 something like:
14097 template <class T>
14098 struct S {
14099 static T t();
14100 void f(T = t());
14103 we must be careful to do name lookup in the scope of S<T>,
14104 rather than in the current class. */
14105 push_to_top_level ();
14106 push_access_scope (fn);
14107 push_deferring_access_checks (dk_no_deferred);
14108 /* So in_immediate_context knows this is a default argument. */
14109 begin_scope (sk_function_parms, fn);
14110 start_lambda_scope (parm);
14112 /* The default argument expression may cause implicitly defined
14113 member functions to be synthesized, which will result in garbage
14114 collection. We must treat this situation as if we were within
14115 the body of function so as to avoid collecting live data on the
14116 stack. */
14117 ++function_depth;
14118 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14119 --function_depth;
14121 finish_lambda_scope ();
14123 /* Make sure the default argument is reasonable. */
14124 arg = check_default_argument (type, arg, complain);
14126 if (errorcount+sorrycount > errs
14127 && (complain & tf_warning_or_error))
14128 inform (input_location,
14129 " when instantiating default argument for call to %qD", fn);
14131 leave_scope ();
14132 pop_deferring_access_checks ();
14133 pop_access_scope (fn);
14134 pop_from_top_level ();
14136 if (arg != error_mark_node && !cp_unevaluated_operand)
14137 (*defs)[ridx - 1] = arg;
14139 return arg;
14142 /* Substitute into all the default arguments for FN. */
14144 static void
14145 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14147 tree arg;
14148 tree tmpl_args;
14150 tmpl_args = DECL_TI_ARGS (fn);
14152 /* If this function is not yet instantiated, we certainly don't need
14153 its default arguments. */
14154 if (uses_template_parms (tmpl_args))
14155 return;
14156 /* Don't do this again for clones. */
14157 if (DECL_CLONED_FUNCTION_P (fn))
14158 return;
14160 int i = 0;
14161 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14162 arg;
14163 arg = TREE_CHAIN (arg), ++i)
14164 if (TREE_PURPOSE (arg))
14165 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14166 TREE_VALUE (arg),
14167 TREE_PURPOSE (arg),
14168 complain);
14171 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14172 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14174 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14176 void
14177 store_explicit_specifier (tree v, tree t)
14179 if (!explicit_specifier_map)
14180 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14181 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14182 explicit_specifier_map->put (v, t);
14185 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14187 tree
14188 lookup_explicit_specifier (tree v)
14190 return *explicit_specifier_map->get (v);
14193 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14194 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14195 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14196 identical to T. */
14198 static tree
14199 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14200 tree raises, tsubst_flags_t complain)
14202 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14204 tree new_type;
14205 if (TREE_CODE (t) == FUNCTION_TYPE)
14207 new_type = build_function_type (return_type, arg_types);
14208 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14210 else
14212 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14213 /* Don't pick up extra function qualifiers from the basetype. */
14214 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14215 if (! MAYBE_CLASS_TYPE_P (r))
14217 /* [temp.deduct]
14219 Type deduction may fail for any of the following
14220 reasons:
14222 -- Attempting to create "pointer to member of T" when T
14223 is not a class type. */
14224 if (complain & tf_error)
14225 error ("creating pointer to member function of non-class type %qT",
14227 return error_mark_node;
14230 new_type = build_method_type_directly (r, return_type,
14231 TREE_CHAIN (arg_types));
14233 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14235 cp_ref_qualifier rqual = type_memfn_rqual (t);
14236 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14237 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14240 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14241 each of its formal parameters. If there is a disagreement then rebuild
14242 DECL's function type according to its formal parameter types, as part of a
14243 resolution for Core issues 1001/1322. */
14245 static void
14246 maybe_rebuild_function_decl_type (tree decl)
14248 bool function_type_needs_rebuilding = false;
14249 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14251 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14252 while (parm_type_list && parm_type_list != void_list_node)
14254 tree parm_type = TREE_VALUE (parm_type_list);
14255 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14256 if (!same_type_p (parm_type, formal_parm_type_unqual))
14258 function_type_needs_rebuilding = true;
14259 break;
14262 parm_list = DECL_CHAIN (parm_list);
14263 parm_type_list = TREE_CHAIN (parm_type_list);
14267 if (!function_type_needs_rebuilding)
14268 return;
14270 const tree fntype = TREE_TYPE (decl);
14271 tree parm_list = DECL_ARGUMENTS (decl);
14272 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14273 tree new_parm_type_list = NULL_TREE;
14274 tree *q = &new_parm_type_list;
14275 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14277 *q = copy_node (old_parm_type_list);
14278 parm_list = DECL_CHAIN (parm_list);
14279 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14280 q = &TREE_CHAIN (*q);
14282 while (old_parm_type_list && old_parm_type_list != void_list_node)
14284 *q = copy_node (old_parm_type_list);
14285 tree *new_parm_type = &TREE_VALUE (*q);
14286 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14287 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14288 *new_parm_type = formal_parm_type_unqual;
14290 parm_list = DECL_CHAIN (parm_list);
14291 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14292 q = &TREE_CHAIN (*q);
14294 if (old_parm_type_list == void_list_node)
14295 *q = void_list_node;
14297 TREE_TYPE (decl)
14298 = rebuild_function_or_method_type (fntype,
14299 TREE_TYPE (fntype), new_parm_type_list,
14300 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14303 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14305 static tree
14306 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14307 tree lambda_fntype, bool use_spec_table = true)
14309 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14310 hashval_t hash = 0;
14311 tree in_decl = t;
14313 /* Nobody should be tsubst'ing into non-template functions. */
14314 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14315 || DECL_LOCAL_DECL_P (t));
14317 if (DECL_LOCAL_DECL_P (t))
14319 if (tree spec = retrieve_local_specialization (t))
14320 return spec;
14322 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14324 /* If T is not dependent, just return it. */
14325 if (!uses_template_parms (DECL_TI_ARGS (t))
14326 && !LAMBDA_FUNCTION_P (t))
14327 return t;
14329 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14330 if (non_templated_friend_p (t))
14331 goto friend_case;
14333 /* Calculate the most general template of which R is a
14334 specialization. */
14335 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14337 /* We're substituting a lambda function under tsubst_lambda_expr but not
14338 directly from it; find the matching function we're already inside.
14339 But don't do this if T is a generic lambda with a single level of
14340 template parms, as in that case we're doing a normal instantiation. */
14341 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14342 && (!generic_lambda_fn_p (t)
14343 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14344 return enclosing_instantiation_of (t);
14346 /* Calculate the complete set of arguments used to
14347 specialize R. */
14348 if (use_spec_table)
14350 argvec = tsubst_template_args (DECL_TI_ARGS
14351 (DECL_TEMPLATE_RESULT
14352 (DECL_TI_TEMPLATE (t))),
14353 args, complain, in_decl);
14354 if (argvec == error_mark_node)
14355 return error_mark_node;
14357 /* Check to see if we already have this specialization. */
14358 if (!lambda_fntype)
14360 hash = spec_hasher::hash (gen_tmpl, argvec);
14361 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14362 /* The spec for these args might be a partial instantiation of the
14363 template, but here what we want is the FUNCTION_DECL. */
14364 return STRIP_TEMPLATE (spec);
14367 else
14368 argvec = args;
14370 else
14372 /* This special case arises when we have something like this:
14374 template <class T> struct S {
14375 friend void f<int>(int, double);
14378 Here, the DECL_TI_TEMPLATE for the friend declaration
14379 will be an IDENTIFIER_NODE. We are being called from
14380 tsubst_friend_function, and we want only to create a
14381 new decl (R) with appropriate types so that we can call
14382 determine_specialization. */
14383 friend_case:
14384 gen_tmpl = NULL_TREE;
14385 argvec = NULL_TREE;
14388 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14389 : NULL_TREE);
14390 tree ctx = closure ? closure : DECL_CONTEXT (t);
14391 bool member = ctx && TYPE_P (ctx);
14393 /* If this is a static lambda, remove the 'this' pointer added in
14394 tsubst_lambda_expr now that we know the closure type. */
14395 if (lambda_fntype && DECL_STATIC_FUNCTION_P (t))
14396 lambda_fntype = static_fn_type (lambda_fntype);
14398 if (member && !closure)
14399 ctx = tsubst_aggr_type (ctx, args,
14400 complain, t, /*entering_scope=*/1);
14402 tree type = (lambda_fntype ? lambda_fntype
14403 : tsubst (TREE_TYPE (t), args,
14404 complain | tf_fndecl_type, in_decl));
14405 if (type == error_mark_node)
14406 return error_mark_node;
14408 /* If we hit excessive deduction depth, the type is bogus even if
14409 it isn't error_mark_node, so don't build a decl. */
14410 if (excessive_deduction_depth)
14411 return error_mark_node;
14413 /* We do NOT check for matching decls pushed separately at this
14414 point, as they may not represent instantiations of this
14415 template, and in any case are considered separate under the
14416 discrete model. */
14417 tree r = copy_decl (t);
14418 DECL_USE_TEMPLATE (r) = 0;
14419 TREE_TYPE (r) = type;
14420 /* Clear out the mangled name and RTL for the instantiation. */
14421 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14422 SET_DECL_RTL (r, NULL);
14423 /* Leave DECL_INITIAL set on deleted instantiations. */
14424 if (!DECL_DELETED_FN (r))
14425 DECL_INITIAL (r) = NULL_TREE;
14426 DECL_CONTEXT (r) = ctx;
14427 set_instantiating_module (r);
14429 /* Handle explicit(dependent-expr). */
14430 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14432 tree spec = lookup_explicit_specifier (t);
14433 spec = tsubst_copy_and_build (spec, args, complain, in_decl);
14434 spec = build_explicit_specifier (spec, complain);
14435 if (spec == error_mark_node)
14436 return error_mark_node;
14437 if (instantiation_dependent_expression_p (spec))
14438 store_explicit_specifier (r, spec);
14439 else
14441 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14442 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14446 /* OpenMP UDRs have the only argument a reference to the declared
14447 type. We want to diagnose if the declared type is a reference,
14448 which is invalid, but as references to references are usually
14449 quietly merged, diagnose it here. */
14450 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14452 tree argtype
14453 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14454 argtype = tsubst (argtype, args, complain, in_decl);
14455 if (TYPE_REF_P (argtype))
14456 error_at (DECL_SOURCE_LOCATION (t),
14457 "reference type %qT in "
14458 "%<#pragma omp declare reduction%>", argtype);
14459 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14460 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14461 argtype);
14464 if (member && DECL_CONV_FN_P (r))
14465 /* Type-conversion operator. Reconstruct the name, in
14466 case it's the name of one of the template's parameters. */
14467 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14469 tree parms = DECL_ARGUMENTS (t);
14470 if (closure && !DECL_STATIC_FUNCTION_P (t))
14471 parms = DECL_CHAIN (parms);
14472 parms = tsubst (parms, args, complain, t);
14473 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14474 DECL_CONTEXT (parm) = r;
14475 if (closure && !DECL_STATIC_FUNCTION_P (t))
14477 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14478 DECL_NAME (tparm) = closure_identifier;
14479 DECL_CHAIN (tparm) = parms;
14480 parms = tparm;
14482 DECL_ARGUMENTS (r) = parms;
14483 DECL_RESULT (r) = NULL_TREE;
14485 maybe_rebuild_function_decl_type (r);
14487 TREE_STATIC (r) = 0;
14488 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14489 DECL_EXTERNAL (r) = 1;
14490 /* If this is an instantiation of a function with internal
14491 linkage, we already know what object file linkage will be
14492 assigned to the instantiation. */
14493 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14494 DECL_DEFER_OUTPUT (r) = 0;
14495 DECL_CHAIN (r) = NULL_TREE;
14496 DECL_PENDING_INLINE_INFO (r) = 0;
14497 DECL_PENDING_INLINE_P (r) = 0;
14498 DECL_SAVED_TREE (r) = NULL_TREE;
14499 DECL_STRUCT_FUNCTION (r) = NULL;
14500 TREE_USED (r) = 0;
14501 /* We'll re-clone as appropriate in instantiate_template. */
14502 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14504 /* If we aren't complaining now, return on error before we register
14505 the specialization so that we'll complain eventually. */
14506 if ((complain & tf_error) == 0
14507 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14508 && !grok_op_properties (r, /*complain=*/false))
14509 return error_mark_node;
14511 /* Associate the constraints directly with the instantiation. We
14512 don't substitute through the constraints; that's only done when
14513 they are checked. */
14514 if (tree ci = get_constraints (t))
14515 set_constraints (r, ci);
14517 if (DECL_FRIEND_CONTEXT (t))
14518 SET_DECL_FRIEND_CONTEXT (r,
14519 tsubst (DECL_FRIEND_CONTEXT (t),
14520 args, complain, in_decl));
14522 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14523 args, complain, in_decl))
14524 return error_mark_node;
14526 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14527 this in the special friend case mentioned above where
14528 GEN_TMPL is NULL. */
14529 if (gen_tmpl && !closure)
14531 DECL_TEMPLATE_INFO (r)
14532 = build_template_info (gen_tmpl, argvec);
14533 SET_DECL_IMPLICIT_INSTANTIATION (r);
14535 if (use_spec_table)
14537 tree new_r
14538 = register_specialization (r, gen_tmpl, argvec, false, hash);
14539 if (new_r != r)
14540 /* We instantiated this while substituting into
14541 the type earlier (template/friend54.C). */
14542 return new_r;
14545 /* We're not supposed to instantiate default arguments
14546 until they are called, for a template. But, for a
14547 declaration like:
14549 template <class T> void f ()
14550 { extern void g(int i = T()); }
14552 we should do the substitution when the template is
14553 instantiated. We handle the member function case in
14554 instantiate_class_template since the default arguments
14555 might refer to other members of the class. */
14556 if (!member
14557 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14558 && !uses_template_parms (argvec))
14559 tsubst_default_arguments (r, complain);
14561 else if (DECL_LOCAL_DECL_P (r))
14563 if (!cp_unevaluated_operand)
14564 register_local_specialization (r, t);
14566 else
14567 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14569 /* Copy the list of befriending classes. */
14570 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14571 *friends;
14572 friends = &TREE_CHAIN (*friends))
14574 *friends = copy_node (*friends);
14575 TREE_VALUE (*friends)
14576 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14579 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14581 maybe_retrofit_in_chrg (r);
14582 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14583 return error_mark_node;
14584 /* If this is an instantiation of a member template, clone it.
14585 If it isn't, that'll be handled by
14586 clone_constructors_and_destructors. */
14587 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14588 clone_cdtor (r, /*update_methods=*/false);
14590 else if ((complain & tf_error) != 0
14591 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14592 && !grok_op_properties (r, /*complain=*/true))
14593 return error_mark_node;
14595 /* Possibly limit visibility based on template args. */
14596 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14597 if (DECL_VISIBILITY_SPECIFIED (t))
14599 DECL_VISIBILITY_SPECIFIED (r) = 0;
14600 DECL_ATTRIBUTES (r)
14601 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14603 determine_visibility (r);
14604 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14605 && !processing_template_decl)
14606 defaulted_late_check (r);
14608 if (flag_openmp)
14609 if (tree attr = lookup_attribute ("omp declare variant base",
14610 DECL_ATTRIBUTES (r)))
14611 omp_declare_variant_finalize (r, attr);
14613 return r;
14616 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14618 static tree
14619 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14620 tree lambda_fntype, tree lambda_tparms)
14622 /* We can get here when processing a member function template,
14623 member class template, or template template parameter. */
14624 tree decl = DECL_TEMPLATE_RESULT (t);
14625 tree in_decl = t;
14626 tree spec;
14627 tree tmpl_args;
14628 tree full_args;
14629 tree r;
14630 hashval_t hash = 0;
14632 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14634 /* Template template parameter is treated here. */
14635 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14636 if (new_type == error_mark_node)
14637 r = error_mark_node;
14638 /* If we get a real template back, return it. This can happen in
14639 the context of most_specialized_partial_spec. */
14640 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14641 r = new_type;
14642 else
14643 /* The new TEMPLATE_DECL was built in
14644 reduce_template_parm_level. */
14645 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14646 return r;
14649 if (!lambda_fntype)
14651 /* We might already have an instance of this template.
14652 The ARGS are for the surrounding class type, so the
14653 full args contain the tsubst'd args for the context,
14654 plus the innermost args from the template decl. */
14655 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14656 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14657 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14658 /* Because this is a template, the arguments will still be
14659 dependent, even after substitution. If
14660 PROCESSING_TEMPLATE_DECL is not set, the dependency
14661 predicates will short-circuit. */
14662 ++processing_template_decl;
14663 full_args = tsubst_template_args (tmpl_args, args,
14664 complain, in_decl);
14665 --processing_template_decl;
14666 if (full_args == error_mark_node)
14667 return error_mark_node;
14669 /* If this is a default template template argument,
14670 tsubst might not have changed anything. */
14671 if (full_args == tmpl_args)
14672 return t;
14674 hash = spec_hasher::hash (t, full_args);
14675 spec = retrieve_specialization (t, full_args, hash);
14676 if (spec != NULL_TREE)
14678 if (TYPE_P (spec))
14679 /* Type partial instantiations are stored as the type by
14680 lookup_template_class_1, not here as the template. */
14681 spec = CLASSTYPE_TI_TEMPLATE (spec);
14682 return spec;
14686 /* Make a new template decl. It will be similar to the
14687 original, but will record the current template arguments.
14688 We also create a new function declaration, which is just
14689 like the old one, but points to this new template, rather
14690 than the old one. */
14691 r = copy_decl (t);
14692 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14693 DECL_CHAIN (r) = NULL_TREE;
14695 // Build new template info linking to the original template decl.
14696 if (!lambda_fntype)
14698 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14699 SET_DECL_IMPLICIT_INSTANTIATION (r);
14701 else
14702 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14704 /* The template parameters for this new template are all the
14705 template parameters for the old template, except the
14706 outermost level of parameters. */
14707 auto tparm_guard = make_temp_override (current_template_parms);
14708 DECL_TEMPLATE_PARMS (r)
14709 = current_template_parms
14710 = (lambda_tparms
14711 ? lambda_tparms
14712 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14713 complain));
14715 bool class_p = false;
14716 tree inner = decl;
14717 ++processing_template_decl;
14718 if (TREE_CODE (inner) == FUNCTION_DECL)
14719 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14720 else
14722 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14724 class_p = true;
14725 inner = TREE_TYPE (inner);
14727 if (class_p)
14728 inner = tsubst_aggr_type (inner, args, complain,
14729 in_decl, /*entering*/1);
14730 else
14731 inner = tsubst (inner, args, complain, in_decl);
14733 --processing_template_decl;
14734 if (inner == error_mark_node)
14735 return error_mark_node;
14737 if (class_p)
14739 /* For a partial specialization, we need to keep pointing to
14740 the primary template. */
14741 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14743 CLASSTYPE_TI_TEMPLATE (inner) = r;
14744 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14747 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14748 inner = TYPE_MAIN_DECL (inner);
14750 else if (lambda_fntype)
14752 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14753 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14755 else
14757 DECL_TI_TEMPLATE (inner) = r;
14758 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14761 DECL_TEMPLATE_RESULT (r) = inner;
14762 TREE_TYPE (r) = TREE_TYPE (inner);
14763 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14765 if (modules_p ())
14767 /* Propagate module information from the decl. */
14768 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14769 if (DECL_LANG_SPECIFIC (inner))
14770 /* If this is a constrained template, the above tsubst of
14771 inner can find the unconstrained template, which may have
14772 come from an import. This is ok, because we don't
14773 register this instantiation (see below). */
14774 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14775 || (TEMPLATE_PARMS_CONSTRAINTS
14776 (DECL_TEMPLATE_PARMS (t))));
14779 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14780 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14782 if (PRIMARY_TEMPLATE_P (t))
14783 DECL_PRIMARY_TEMPLATE (r) = r;
14785 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14786 /* Record this non-type partial instantiation. */
14787 register_specialization (r, t,
14788 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14789 false, hash);
14791 return r;
14794 /* True if FN is the op() for a lambda in an uninstantiated template. */
14796 bool
14797 lambda_fn_in_template_p (tree fn)
14799 if (!fn || !LAMBDA_FUNCTION_P (fn))
14800 return false;
14801 tree closure = DECL_CONTEXT (fn);
14802 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14805 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14806 which the above is true. */
14808 bool
14809 regenerated_lambda_fn_p (tree fn)
14811 if (!fn || !LAMBDA_FUNCTION_P (fn))
14812 return false;
14813 tree closure = DECL_CONTEXT (fn);
14814 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14815 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14818 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14819 If T is not a regenerated LAMBDA_EXPR, return T. */
14821 tree
14822 most_general_lambda (tree t)
14824 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14825 t = TI_TEMPLATE (ti);
14826 return t;
14829 /* Return the set of template arguments used to regenerate the lambda T
14830 from its most general lambda. */
14832 tree
14833 lambda_regenerating_args (tree t)
14835 if (LAMBDA_FUNCTION_P (t))
14836 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14837 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14838 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14839 return TI_ARGS (ti);
14840 else
14841 return NULL_TREE;
14844 /* We're instantiating a variable from template function TCTX. Return the
14845 corresponding current enclosing scope. We can match them up using
14846 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14847 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14848 the template definition in regenerate_decl_from_template. */
14850 static tree
14851 enclosing_instantiation_of (tree tctx)
14853 tree fn = current_function_decl;
14855 /* We shouldn't ever need to do this for other artificial functions. */
14856 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14858 for (; fn; fn = decl_function_context (fn))
14859 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14860 return fn;
14861 gcc_unreachable ();
14864 /* Substitute the ARGS into the T, which is a _DECL. Return the
14865 result of the substitution. Issue error and warning messages under
14866 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
14867 and insert into the specializations table or if we can assume it's
14868 the caller's responsibility; this is used by instantiate_template
14869 to avoid doing some redundant work. */
14871 static tree
14872 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
14873 bool use_spec_table /* = true */)
14875 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14876 location_t saved_loc;
14877 tree r = NULL_TREE;
14878 tree in_decl = t;
14879 hashval_t hash = 0;
14881 if (t == error_mark_node)
14882 return error_mark_node;
14884 /* Set the filename and linenumber to improve error-reporting. */
14885 saved_loc = input_location;
14886 input_location = DECL_SOURCE_LOCATION (t);
14888 switch (TREE_CODE (t))
14890 case TEMPLATE_DECL:
14891 r = tsubst_template_decl (t, args, complain,
14892 /*lambda_fntype=*/NULL_TREE,
14893 /*lambda_tparms=*/NULL_TREE);
14894 break;
14896 case FUNCTION_DECL:
14897 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
14898 use_spec_table);
14899 break;
14901 case PARM_DECL:
14903 tree type = NULL_TREE;
14904 int i, len = 1;
14905 tree expanded_types = NULL_TREE;
14906 tree prev_r = NULL_TREE;
14907 tree first_r = NULL_TREE;
14909 if (DECL_PACK_P (t))
14911 /* If there is a local specialization that isn't a
14912 parameter pack, it means that we're doing a "simple"
14913 substitution from inside tsubst_pack_expansion. Just
14914 return the local specialization (which will be a single
14915 parm). */
14916 tree spec = retrieve_local_specialization (t);
14917 if (spec
14918 && TREE_CODE (spec) == PARM_DECL
14919 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14920 RETURN (spec);
14922 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14923 the parameters in this function parameter pack. */
14924 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14925 complain, in_decl);
14926 if (TREE_CODE (expanded_types) == TREE_VEC)
14928 len = TREE_VEC_LENGTH (expanded_types);
14930 /* Zero-length parameter packs are boring. Just substitute
14931 into the chain. */
14932 if (len == 0 && !cp_unevaluated_operand)
14933 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14934 TREE_CHAIN (t)));
14936 else
14938 /* All we did was update the type. Make a note of that. */
14939 type = expanded_types;
14940 expanded_types = NULL_TREE;
14944 /* Loop through all of the parameters we'll build. When T is
14945 a function parameter pack, LEN is the number of expanded
14946 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14947 r = NULL_TREE;
14948 for (i = 0; i < len; ++i)
14950 prev_r = r;
14951 r = copy_node (t);
14952 if (DECL_TEMPLATE_PARM_P (t))
14953 SET_DECL_TEMPLATE_PARM_P (r);
14955 if (expanded_types)
14956 /* We're on the Ith parameter of the function parameter
14957 pack. */
14959 /* Get the Ith type. */
14960 type = TREE_VEC_ELT (expanded_types, i);
14962 /* Rename the parameter to include the index. */
14963 DECL_NAME (r)
14964 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14966 else if (!type)
14967 /* We're dealing with a normal parameter. */
14968 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14970 type = type_decays_to (type);
14971 TREE_TYPE (r) = type;
14972 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14974 if (DECL_INITIAL (r))
14976 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14977 DECL_INITIAL (r) = TREE_TYPE (r);
14978 else
14979 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14980 complain, in_decl);
14983 DECL_CONTEXT (r) = NULL_TREE;
14985 if (!DECL_TEMPLATE_PARM_P (r))
14986 DECL_ARG_TYPE (r) = type_passed_as (type);
14988 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14989 args, complain, in_decl))
14990 return error_mark_node;
14992 /* Keep track of the first new parameter we
14993 generate. That's what will be returned to the
14994 caller. */
14995 if (!first_r)
14996 first_r = r;
14998 /* Build a proper chain of parameters when substituting
14999 into a function parameter pack. */
15000 if (prev_r)
15001 DECL_CHAIN (prev_r) = r;
15004 /* If cp_unevaluated_operand is set, we're just looking for a
15005 single dummy parameter, so don't keep going. */
15006 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15007 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15008 complain, DECL_CHAIN (t));
15010 /* FIRST_R contains the start of the chain we've built. */
15011 r = first_r;
15013 break;
15015 case FIELD_DECL:
15017 tree type = NULL_TREE;
15018 tree vec = NULL_TREE;
15019 tree expanded_types = NULL_TREE;
15020 int len = 1;
15022 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15024 /* This field is a lambda capture pack. Return a TREE_VEC of
15025 the expanded fields to instantiate_class_template_1. */
15026 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15027 complain, in_decl);
15028 if (TREE_CODE (expanded_types) == TREE_VEC)
15030 len = TREE_VEC_LENGTH (expanded_types);
15031 vec = make_tree_vec (len);
15033 else
15035 /* All we did was update the type. Make a note of that. */
15036 type = expanded_types;
15037 expanded_types = NULL_TREE;
15041 for (int i = 0; i < len; ++i)
15043 r = copy_decl (t);
15044 if (expanded_types)
15046 type = TREE_VEC_ELT (expanded_types, i);
15047 DECL_NAME (r)
15048 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15050 else if (!type)
15051 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15053 if (type == error_mark_node)
15054 RETURN (error_mark_node);
15055 TREE_TYPE (r) = type;
15056 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15058 if (DECL_C_BIT_FIELD (r))
15059 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15060 number of bits. */
15061 DECL_BIT_FIELD_REPRESENTATIVE (r)
15062 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15063 complain, in_decl);
15064 if (DECL_INITIAL (t))
15066 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15067 NSDMI in perform_member_init. Still set DECL_INITIAL
15068 so that we know there is one. */
15069 DECL_INITIAL (r) = void_node;
15070 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15071 retrofit_lang_decl (r);
15072 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15074 /* We don't have to set DECL_CONTEXT here; it is set by
15075 finish_member_declaration. */
15076 DECL_CHAIN (r) = NULL_TREE;
15078 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15079 args, complain, in_decl))
15080 return error_mark_node;
15082 if (vec)
15083 TREE_VEC_ELT (vec, i) = r;
15086 if (vec)
15087 r = vec;
15089 break;
15091 case USING_DECL:
15092 /* We reach here only for member using decls. We also need to check
15093 uses_template_parms because DECL_DEPENDENT_P is not set for a
15094 using-declaration that designates a member of the current
15095 instantiation (c++/53549). */
15096 if (DECL_DEPENDENT_P (t)
15097 || uses_template_parms (USING_DECL_SCOPE (t)))
15099 /* True iff this using-decl was written as a pack expansion
15100 (and a pack appeared in its scope or name). If a pack
15101 appeared in both, we expand the packs separately and
15102 manually merge them. */
15103 bool variadic_p = false;
15105 tree scope = USING_DECL_SCOPE (t);
15106 if (PACK_EXPANSION_P (scope))
15108 scope = tsubst_pack_expansion (scope, args,
15109 complain | tf_qualifying_scope,
15110 in_decl);
15111 variadic_p = true;
15113 else
15114 scope = tsubst_scope (scope, args, complain, in_decl);
15116 tree name = DECL_NAME (t);
15117 if (IDENTIFIER_CONV_OP_P (name)
15118 && PACK_EXPANSION_P (TREE_TYPE (name)))
15120 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15121 complain, in_decl);
15122 if (name == error_mark_node)
15124 r = error_mark_node;
15125 break;
15127 for (tree& elt : tree_vec_range (name))
15128 elt = make_conv_op_name (elt);
15129 variadic_p = true;
15131 else
15132 name = tsubst_copy (name, args, complain, in_decl);
15134 int len;
15135 if (!variadic_p)
15136 len = 1;
15137 else if (TREE_CODE (scope) == TREE_VEC
15138 && TREE_CODE (name) == TREE_VEC)
15140 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15142 error ("mismatched argument pack lengths (%d vs %d)",
15143 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15144 r = error_mark_node;
15145 break;
15147 len = TREE_VEC_LENGTH (scope);
15149 else if (TREE_CODE (scope) == TREE_VEC)
15150 len = TREE_VEC_LENGTH (scope);
15151 else /* TREE_CODE (name) == TREE_VEC */
15152 len = TREE_VEC_LENGTH (name);
15154 r = make_tree_vec (len);
15155 for (int i = 0; i < len; ++i)
15157 tree escope = (TREE_CODE (scope) == TREE_VEC
15158 ? TREE_VEC_ELT (scope, i)
15159 : scope);
15160 tree ename = (TREE_CODE (name) == TREE_VEC
15161 ? TREE_VEC_ELT (name, i)
15162 : name);
15163 tree elt = do_class_using_decl (escope, ename);
15164 if (!elt)
15166 r = error_mark_node;
15167 break;
15169 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15170 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15171 TREE_VEC_ELT (r, i) = elt;
15174 if (!variadic_p && r != error_mark_node)
15175 r = TREE_VEC_ELT (r, 0);
15177 else
15179 r = copy_node (t);
15180 DECL_CHAIN (r) = NULL_TREE;
15182 break;
15184 case TYPE_DECL:
15185 case VAR_DECL:
15187 tree argvec = NULL_TREE;
15188 tree gen_tmpl = NULL_TREE;
15189 tree tmpl = NULL_TREE;
15190 tree type = NULL_TREE;
15192 if (TREE_TYPE (t) == error_mark_node)
15193 RETURN (error_mark_node);
15195 if (TREE_CODE (t) == TYPE_DECL
15196 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15198 /* If this is the canonical decl, we don't have to
15199 mess with instantiations, and often we can't (for
15200 typename, template type parms and such). Note that
15201 TYPE_NAME is not correct for the above test if
15202 we've copied the type for a typedef. */
15203 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15204 if (type == error_mark_node)
15205 RETURN (error_mark_node);
15206 r = TYPE_NAME (type);
15207 break;
15210 /* Check to see if we already have the specialization we
15211 need. */
15212 tree spec = NULL_TREE;
15213 bool local_p = false;
15214 tree ctx = DECL_CONTEXT (t);
15215 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15216 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15218 local_p = false;
15219 if (DECL_CLASS_SCOPE_P (t))
15221 ctx = tsubst_aggr_type (ctx, args,
15222 complain,
15223 in_decl, /*entering_scope=*/1);
15224 if (DECL_SELF_REFERENCE_P (t))
15225 /* The context and type of an injected-class-name are
15226 the same, so we don't need to substitute both. */
15227 type = ctx;
15228 /* If CTX is unchanged, then T is in fact the
15229 specialization we want. That situation occurs when
15230 referencing a static data member within in its own
15231 class. We can use pointer equality, rather than
15232 same_type_p, because DECL_CONTEXT is always
15233 canonical... */
15234 if (ctx == DECL_CONTEXT (t)
15235 /* ... unless T is a member template; in which
15236 case our caller can be willing to create a
15237 specialization of that template represented
15238 by T. */
15239 && !(DECL_TI_TEMPLATE (t)
15240 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15241 spec = t;
15244 if (!spec)
15246 tmpl = DECL_TI_TEMPLATE (t);
15247 if (use_spec_table)
15249 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15250 if (argvec == error_mark_node)
15251 RETURN (error_mark_node);
15252 gen_tmpl = most_general_template (tmpl);
15253 hash = spec_hasher::hash (gen_tmpl, argvec);
15254 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15256 else
15257 argvec = args;
15260 else
15262 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15263 /* Subsequent calls to pushdecl will fill this in. */
15264 ctx = NULL_TREE;
15265 /* A local variable. */
15266 local_p = true;
15267 /* Unless this is a reference to a static variable from an
15268 enclosing function, in which case we need to fill it in now. */
15269 if (TREE_STATIC (t))
15271 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15272 if (fn != current_function_decl)
15273 ctx = fn;
15275 spec = retrieve_local_specialization (t);
15277 /* If we already have the specialization we need, there is
15278 nothing more to do. */
15279 if (spec)
15281 r = spec;
15282 break;
15285 /* Create a new node for the specialization we need. */
15286 if (type == NULL_TREE)
15288 if (is_typedef_decl (t))
15289 type = DECL_ORIGINAL_TYPE (t);
15290 else
15291 type = TREE_TYPE (t);
15292 if (VAR_P (t)
15293 && VAR_HAD_UNKNOWN_BOUND (t)
15294 && type != error_mark_node)
15295 type = strip_array_domain (type);
15296 tsubst_flags_t tcomplain = complain;
15297 if (VAR_P (t))
15298 tcomplain |= tf_tst_ok;
15299 type = tsubst (type, args, tcomplain, in_decl);
15300 /* Substituting the type might have recursively instantiated this
15301 same alias (c++/86171). */
15302 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15303 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15305 r = spec;
15306 break;
15309 if (type == error_mark_node && !(complain & tf_error))
15310 RETURN (error_mark_node);
15311 r = copy_decl (t);
15312 if (VAR_P (r))
15314 DECL_INITIALIZED_P (r) = 0;
15315 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15316 if (TREE_CODE (type) == FUNCTION_TYPE)
15318 /* It may seem that this case cannot occur, since:
15320 typedef void f();
15321 void g() { f x; }
15323 declares a function, not a variable. However:
15325 typedef void f();
15326 template <typename T> void g() { T t; }
15327 template void g<f>();
15329 is an attempt to declare a variable with function
15330 type. */
15331 error ("variable %qD has function type",
15332 /* R is not yet sufficiently initialized, so we
15333 just use its name. */
15334 DECL_NAME (r));
15335 RETURN (error_mark_node);
15337 type = complete_type (type);
15338 /* Wait until cp_finish_decl to set this again, to handle
15339 circular dependency (template/instantiate6.C). */
15340 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15341 type = check_var_type (DECL_NAME (r), type,
15342 DECL_SOURCE_LOCATION (r));
15343 if (DECL_HAS_VALUE_EXPR_P (t))
15345 tree ve = DECL_VALUE_EXPR (t);
15346 /* If the DECL_VALUE_EXPR is converted to the declared type,
15347 preserve the identity so that gimplify_type_sizes works. */
15348 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15349 if (nop)
15350 ve = TREE_OPERAND (ve, 0);
15351 ve = tsubst_expr (ve, args, complain, in_decl);
15352 if (REFERENCE_REF_P (ve))
15354 gcc_assert (TYPE_REF_P (type));
15355 ve = TREE_OPERAND (ve, 0);
15357 if (nop)
15358 ve = build_nop (type, ve);
15359 else if (DECL_LANG_SPECIFIC (t)
15360 && DECL_OMP_PRIVATIZED_MEMBER (t)
15361 && TREE_CODE (ve) == COMPONENT_REF
15362 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15363 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15364 type = TREE_TYPE (ve);
15365 else
15366 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15367 == TYPE_MAIN_VARIANT (type));
15368 SET_DECL_VALUE_EXPR (r, ve);
15370 if (CP_DECL_THREAD_LOCAL_P (r)
15371 && !processing_template_decl)
15372 set_decl_tls_model (r, decl_default_tls_model (r));
15374 else if (DECL_SELF_REFERENCE_P (t))
15375 SET_DECL_SELF_REFERENCE_P (r);
15376 TREE_TYPE (r) = type;
15377 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15378 DECL_CONTEXT (r) = ctx;
15379 /* Clear out the mangled name and RTL for the instantiation. */
15380 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15381 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15382 SET_DECL_RTL (r, NULL);
15383 set_instantiating_module (r);
15385 /* The initializer must not be expanded until it is required;
15386 see [temp.inst]. */
15387 DECL_INITIAL (r) = NULL_TREE;
15388 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15389 if (VAR_P (r))
15391 if (DECL_LANG_SPECIFIC (r))
15392 SET_DECL_DEPENDENT_INIT_P (r, false);
15394 SET_DECL_MODE (r, VOIDmode);
15396 /* Possibly limit visibility based on template args. */
15397 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15398 if (DECL_VISIBILITY_SPECIFIED (t))
15400 DECL_VISIBILITY_SPECIFIED (r) = 0;
15401 DECL_ATTRIBUTES (r)
15402 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15404 determine_visibility (r);
15407 if (!local_p)
15409 /* A static data member declaration is always marked
15410 external when it is declared in-class, even if an
15411 initializer is present. We mimic the non-template
15412 processing here. */
15413 DECL_EXTERNAL (r) = 1;
15414 if (DECL_NAMESPACE_SCOPE_P (t))
15415 DECL_NOT_REALLY_EXTERN (r) = 1;
15417 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15418 SET_DECL_IMPLICIT_INSTANTIATION (r);
15419 if (use_spec_table)
15420 register_specialization (r, gen_tmpl, argvec, false, hash);
15422 else
15424 if (DECL_LANG_SPECIFIC (r))
15425 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15426 if (!cp_unevaluated_operand)
15427 register_local_specialization (r, t);
15430 DECL_CHAIN (r) = NULL_TREE;
15432 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15433 /*flags=*/0,
15434 args, complain, in_decl))
15435 return error_mark_node;
15437 /* Preserve a typedef that names a type. */
15438 if (is_typedef_decl (r) && type != error_mark_node)
15440 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15441 set_underlying_type (r);
15443 /* common_handle_aligned_attribute doesn't apply the alignment
15444 to DECL_ORIGINAL_TYPE. */
15445 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15446 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15447 TYPE_ALIGN (TREE_TYPE (t)));
15450 layout_decl (r, 0);
15452 break;
15454 default:
15455 gcc_unreachable ();
15457 #undef RETURN
15459 out:
15460 /* Restore the file and line information. */
15461 input_location = saved_loc;
15463 return r;
15466 /* Substitute into the complete parameter type list PARMS. */
15468 tree
15469 tsubst_function_parms (tree parms,
15470 tree args,
15471 tsubst_flags_t complain,
15472 tree in_decl)
15474 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15477 /* Substitute into the ARG_TYPES of a function type.
15478 If END is a TREE_CHAIN, leave it and any following types
15479 un-substituted. */
15481 static tree
15482 tsubst_arg_types (tree arg_types,
15483 tree args,
15484 tree end,
15485 tsubst_flags_t complain,
15486 tree in_decl)
15488 tree type = NULL_TREE;
15489 int len = 1;
15490 tree expanded_args = NULL_TREE;
15492 if (!arg_types || arg_types == void_list_node || arg_types == end)
15493 return arg_types;
15495 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15497 /* For a pack expansion, perform substitution on the
15498 entire expression. Later on, we'll handle the arguments
15499 one-by-one. */
15500 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15501 args, complain, in_decl);
15503 if (TREE_CODE (expanded_args) == TREE_VEC)
15504 /* So that we'll spin through the parameters, one by one. */
15505 len = TREE_VEC_LENGTH (expanded_args);
15506 else
15508 /* We only partially substituted into the parameter
15509 pack. Our type is TYPE_PACK_EXPANSION. */
15510 type = expanded_args;
15511 expanded_args = NULL_TREE;
15514 else
15515 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15517 /* Check if a substituted type is erroneous before substituting into
15518 the rest of the chain. */
15519 for (int i = 0; i < len; i++)
15521 if (expanded_args)
15522 type = TREE_VEC_ELT (expanded_args, i);
15524 if (type == error_mark_node)
15525 return error_mark_node;
15526 if (VOID_TYPE_P (type))
15528 if (complain & tf_error)
15530 error ("invalid parameter type %qT", type);
15531 if (in_decl)
15532 error ("in declaration %q+D", in_decl);
15534 return error_mark_node;
15538 /* We do not substitute into default arguments here. The standard
15539 mandates that they be instantiated only when needed, which is
15540 done in build_over_call. */
15541 tree default_arg = TREE_PURPOSE (arg_types);
15543 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15544 since the new op() won't have any associated template arguments for us
15545 to refer to later. */
15546 if (lambda_fn_in_template_p (in_decl)
15547 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15548 && DECL_LOCAL_DECL_P (in_decl)))
15549 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl);
15551 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15552 args, end, complain, in_decl);
15553 if (remaining_arg_types == error_mark_node)
15554 return error_mark_node;
15556 for (int i = len-1; i >= 0; i--)
15558 if (expanded_args)
15559 type = TREE_VEC_ELT (expanded_args, i);
15561 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15562 top-level qualifiers as required. */
15563 type = cv_unqualified (type_decays_to (type));
15565 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15567 /* We've instantiated a template before its default arguments
15568 have been parsed. This can happen for a nested template
15569 class, and is not an error unless we require the default
15570 argument in a call of this function. */
15571 remaining_arg_types
15572 = tree_cons (default_arg, type, remaining_arg_types);
15573 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15574 remaining_arg_types);
15576 else
15577 remaining_arg_types
15578 = hash_tree_cons (default_arg, type, remaining_arg_types);
15581 return remaining_arg_types;
15584 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15585 *not* handle the exception-specification for FNTYPE, because the
15586 initial substitution of explicitly provided template parameters
15587 during argument deduction forbids substitution into the
15588 exception-specification:
15590 [temp.deduct]
15592 All references in the function type of the function template to the
15593 corresponding template parameters are replaced by the specified tem-
15594 plate argument values. If a substitution in a template parameter or
15595 in the function type of the function template results in an invalid
15596 type, type deduction fails. [Note: The equivalent substitution in
15597 exception specifications is done only when the function is instanti-
15598 ated, at which point a program is ill-formed if the substitution
15599 results in an invalid type.] */
15601 static tree
15602 tsubst_function_type (tree t,
15603 tree args,
15604 tsubst_flags_t complain,
15605 tree in_decl)
15607 tree return_type;
15608 tree arg_types = NULL_TREE;
15610 /* The TYPE_CONTEXT is not used for function/method types. */
15611 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15613 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15614 failure. */
15615 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15617 if (late_return_type_p)
15619 /* Substitute the argument types. */
15620 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15621 complain, in_decl);
15622 if (arg_types == error_mark_node)
15623 return error_mark_node;
15625 tree save_ccp = current_class_ptr;
15626 tree save_ccr = current_class_ref;
15627 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15628 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15629 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15630 if (do_inject)
15632 /* DR 1207: 'this' is in scope in the trailing return type. */
15633 inject_this_parameter (this_type, cp_type_quals (this_type));
15636 /* Substitute the return type. */
15637 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15639 if (do_inject)
15641 current_class_ptr = save_ccp;
15642 current_class_ref = save_ccr;
15645 else
15646 /* Substitute the return type. */
15647 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15649 if (return_type == error_mark_node)
15650 return error_mark_node;
15651 /* DR 486 clarifies that creation of a function type with an
15652 invalid return type is a deduction failure. */
15653 if (TREE_CODE (return_type) == ARRAY_TYPE
15654 || TREE_CODE (return_type) == FUNCTION_TYPE)
15656 if (complain & tf_error)
15658 if (TREE_CODE (return_type) == ARRAY_TYPE)
15659 error ("function returning an array");
15660 else
15661 error ("function returning a function");
15663 return error_mark_node;
15666 if (!late_return_type_p)
15668 /* Substitute the argument types. */
15669 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15670 complain, in_decl);
15671 if (arg_types == error_mark_node)
15672 return error_mark_node;
15675 /* Construct a new type node and return it. */
15676 return rebuild_function_or_method_type (t, return_type, arg_types,
15677 /*raises=*/NULL_TREE, complain);
15680 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15681 ARGS into that specification, and return the substituted
15682 specification. If there is no specification, return NULL_TREE. */
15684 static tree
15685 tsubst_exception_specification (tree fntype,
15686 tree args,
15687 tsubst_flags_t complain,
15688 tree in_decl,
15689 bool defer_ok)
15691 tree specs;
15692 tree new_specs;
15694 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15695 new_specs = NULL_TREE;
15696 if (specs && TREE_PURPOSE (specs))
15698 /* A noexcept-specifier. */
15699 tree expr = TREE_PURPOSE (specs);
15700 if (TREE_CODE (expr) == INTEGER_CST)
15701 new_specs = expr;
15702 else if (defer_ok)
15704 /* Defer instantiation of noexcept-specifiers to avoid
15705 excessive instantiations (c++/49107). */
15706 new_specs = make_node (DEFERRED_NOEXCEPT);
15707 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15709 /* We already partially instantiated this member template,
15710 so combine the new args with the old. */
15711 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15712 = DEFERRED_NOEXCEPT_PATTERN (expr);
15713 DEFERRED_NOEXCEPT_ARGS (new_specs)
15714 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15716 else
15718 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15719 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15722 else
15724 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15726 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15727 args);
15728 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15730 new_specs = tsubst_copy_and_build (expr, args, complain, in_decl);
15732 new_specs = build_noexcept_spec (new_specs, complain);
15733 /* We've instantiated a template before a noexcept-specifier
15734 contained therein has been parsed. This can happen for
15735 a nested template class:
15737 struct S {
15738 template<typename> struct B { B() noexcept(...); };
15739 struct A : B<int> { ... use B() ... };
15742 where completing B<int> will trigger instantiating the
15743 noexcept, even though we only parse it at the end of S. */
15744 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15746 gcc_checking_assert (defer_ok);
15747 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15750 else if (specs)
15752 if (! TREE_VALUE (specs))
15753 new_specs = specs;
15754 else
15755 while (specs)
15757 tree spec;
15758 int i, len = 1;
15759 tree expanded_specs = NULL_TREE;
15761 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15763 /* Expand the pack expansion type. */
15764 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15765 args, complain,
15766 in_decl);
15768 if (expanded_specs == error_mark_node)
15769 return error_mark_node;
15770 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15771 len = TREE_VEC_LENGTH (expanded_specs);
15772 else
15774 /* We're substituting into a member template, so
15775 we got a TYPE_PACK_EXPANSION back. Add that
15776 expansion and move on. */
15777 gcc_assert (TREE_CODE (expanded_specs)
15778 == TYPE_PACK_EXPANSION);
15779 new_specs = add_exception_specifier (new_specs,
15780 expanded_specs,
15781 complain);
15782 specs = TREE_CHAIN (specs);
15783 continue;
15787 for (i = 0; i < len; ++i)
15789 if (expanded_specs)
15790 spec = TREE_VEC_ELT (expanded_specs, i);
15791 else
15792 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15793 if (spec == error_mark_node)
15794 return spec;
15795 new_specs = add_exception_specifier (new_specs, spec,
15796 complain);
15799 specs = TREE_CHAIN (specs);
15802 return new_specs;
15805 /* Substitute through a TREE_LIST of types or expressions, handling pack
15806 expansions. */
15808 tree
15809 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15811 if (t == void_list_node)
15812 return t;
15814 tree purpose = TREE_PURPOSE (t);
15815 tree purposevec = NULL_TREE;
15816 if (!purpose)
15818 else if (PACK_EXPANSION_P (purpose))
15820 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15821 if (TREE_CODE (purpose) == TREE_VEC)
15822 purposevec = purpose;
15824 else if (TYPE_P (purpose))
15825 purpose = tsubst (purpose, args, complain, in_decl);
15826 else
15827 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15828 if (purpose == error_mark_node || purposevec == error_mark_node)
15829 return error_mark_node;
15831 tree value = TREE_VALUE (t);
15832 tree valuevec = NULL_TREE;
15833 if (!value)
15835 else if (PACK_EXPANSION_P (value))
15837 value = tsubst_pack_expansion (value, args, complain, in_decl);
15838 if (TREE_CODE (value) == TREE_VEC)
15839 valuevec = value;
15841 else if (TYPE_P (value))
15842 value = tsubst (value, args, complain, in_decl);
15843 else
15844 value = tsubst_copy_and_build (value, args, complain, in_decl);
15845 if (value == error_mark_node || valuevec == error_mark_node)
15846 return error_mark_node;
15848 tree chain = TREE_CHAIN (t);
15849 if (!chain)
15851 else if (TREE_CODE (chain) == TREE_LIST)
15852 chain = tsubst_tree_list (chain, args, complain, in_decl);
15853 else if (TYPE_P (chain))
15854 chain = tsubst (chain, args, complain, in_decl);
15855 else
15856 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15857 if (chain == error_mark_node)
15858 return error_mark_node;
15860 if (purpose == TREE_PURPOSE (t)
15861 && value == TREE_VALUE (t)
15862 && chain == TREE_CHAIN (t))
15863 return t;
15865 int len;
15866 /* Determine the number of arguments. */
15867 if (purposevec)
15869 len = TREE_VEC_LENGTH (purposevec);
15870 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15872 else if (valuevec)
15873 len = TREE_VEC_LENGTH (valuevec);
15874 else
15875 len = 1;
15877 for (int i = len; i-- > 0; )
15879 if (purposevec)
15880 purpose = TREE_VEC_ELT (purposevec, i);
15881 if (valuevec)
15882 value = TREE_VEC_ELT (valuevec, i);
15884 if (value && TYPE_P (value))
15885 chain = hash_tree_cons (purpose, value, chain);
15886 else
15887 chain = tree_cons (purpose, value, chain);
15890 return chain;
15893 /* Take the tree structure T and replace template parameters used
15894 therein with the argument vector ARGS. IN_DECL is an associated
15895 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15896 Issue error and warning messages under control of COMPLAIN. Note
15897 that we must be relatively non-tolerant of extensions here, in
15898 order to preserve conformance; if we allow substitutions that
15899 should not be allowed, we may allow argument deductions that should
15900 not succeed, and therefore report ambiguous overload situations
15901 where there are none. In theory, we could allow the substitution,
15902 but indicate that it should have failed, and allow our caller to
15903 make sure that the right thing happens, but we don't try to do this
15904 yet.
15906 This function is used for dealing with types, decls and the like;
15907 for expressions, use tsubst_expr or tsubst_copy. */
15909 tree
15910 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15912 enum tree_code code;
15913 tree type, r = NULL_TREE;
15915 if (t == NULL_TREE || t == error_mark_node
15916 || t == integer_type_node
15917 || t == void_type_node
15918 || t == char_type_node
15919 || t == unknown_type_node
15920 || TREE_CODE (t) == NAMESPACE_DECL
15921 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15922 return t;
15924 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
15925 complain &= ~tf_tst_ok;
15927 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
15928 complain &= ~tf_qualifying_scope;
15930 if (DECL_P (t))
15931 return tsubst_decl (t, args, complain);
15933 if (args == NULL_TREE)
15934 return t;
15936 code = TREE_CODE (t);
15938 gcc_assert (code != IDENTIFIER_NODE);
15939 type = TREE_TYPE (t);
15941 gcc_assert (type != unknown_type_node);
15943 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15944 return d;
15946 /* Reuse typedefs. We need to do this to handle dependent attributes,
15947 such as attribute aligned. */
15948 if (TYPE_P (t)
15949 && typedef_variant_p (t))
15951 tree decl = TYPE_NAME (t);
15953 if (alias_template_specialization_p (t, nt_opaque))
15955 /* DECL represents an alias template and we want to
15956 instantiate it. */
15957 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15958 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15959 r = instantiate_alias_template (tmpl, gen_args, complain);
15961 else if (DECL_CLASS_SCOPE_P (decl)
15962 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15963 && uses_template_parms (DECL_CONTEXT (decl)))
15965 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15966 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15967 r = retrieve_specialization (tmpl, gen_args, 0);
15969 else if (DECL_FUNCTION_SCOPE_P (decl)
15970 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15971 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15972 r = retrieve_local_specialization (decl);
15973 else
15974 /* The typedef is from a non-template context. */
15975 return t;
15977 if (r)
15979 r = TREE_TYPE (r);
15980 r = cp_build_qualified_type
15981 (r, cp_type_quals (t) | cp_type_quals (r),
15982 complain | tf_ignore_bad_quals);
15983 return r;
15985 else
15987 /* We don't have an instantiation yet, so drop the typedef. */
15988 int quals = cp_type_quals (t);
15989 t = DECL_ORIGINAL_TYPE (decl);
15990 t = cp_build_qualified_type (t, quals,
15991 complain | tf_ignore_bad_quals);
15995 bool fndecl_type = (complain & tf_fndecl_type);
15996 complain &= ~tf_fndecl_type;
15998 if (type
15999 && code != TYPENAME_TYPE
16000 && code != TEMPLATE_TYPE_PARM
16001 && code != TEMPLATE_PARM_INDEX
16002 && code != IDENTIFIER_NODE
16003 && code != FUNCTION_TYPE
16004 && code != METHOD_TYPE)
16005 type = tsubst (type, args, complain, in_decl);
16006 if (type == error_mark_node)
16007 return error_mark_node;
16009 switch (code)
16011 case RECORD_TYPE:
16012 if (TYPE_PTRMEMFUNC_P (t))
16013 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16014 /* Fall through. */
16015 case UNION_TYPE:
16016 case ENUMERAL_TYPE:
16017 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16018 /*entering_scope=*/0);
16020 case ERROR_MARK:
16021 case IDENTIFIER_NODE:
16022 case VOID_TYPE:
16023 case OPAQUE_TYPE:
16024 case REAL_TYPE:
16025 case COMPLEX_TYPE:
16026 case VECTOR_TYPE:
16027 case BOOLEAN_TYPE:
16028 case NULLPTR_TYPE:
16029 case LANG_TYPE:
16030 return t;
16032 case INTEGER_TYPE:
16033 if (t == integer_type_node)
16034 return t;
16036 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16037 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16038 return t;
16041 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16043 max = tsubst_expr (omax, args, complain, in_decl);
16045 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16046 needed. */
16047 if (TREE_CODE (max) == NOP_EXPR
16048 && TREE_SIDE_EFFECTS (omax)
16049 && !TREE_TYPE (max))
16050 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16052 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16053 with TREE_SIDE_EFFECTS that indicates this is not an integral
16054 constant expression. */
16055 if (processing_template_decl
16056 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16058 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16059 TREE_SIDE_EFFECTS (max) = 1;
16062 return compute_array_index_type (NULL_TREE, max, complain);
16065 case TEMPLATE_TYPE_PARM:
16066 if (template_placeholder_p (t))
16068 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16069 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
16070 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16071 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16073 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16074 return make_template_placeholder (tmpl);
16075 else
16076 return t;
16078 /* Fall through. */
16079 case TEMPLATE_TEMPLATE_PARM:
16080 case BOUND_TEMPLATE_TEMPLATE_PARM:
16081 case TEMPLATE_PARM_INDEX:
16083 int idx;
16084 int level;
16085 int levels;
16086 tree arg = NULL_TREE;
16088 r = NULL_TREE;
16090 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16091 template_parm_level_and_index (t, &level, &idx);
16093 levels = TMPL_ARGS_DEPTH (args);
16094 if (level <= levels
16095 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16097 arg = TMPL_ARG (args, level, idx);
16099 /* See through ARGUMENT_PACK_SELECT arguments. */
16100 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16101 arg = argument_pack_select_arg (arg);
16104 if (arg == error_mark_node)
16105 return error_mark_node;
16106 else if (arg != NULL_TREE)
16108 if (ARGUMENT_PACK_P (arg))
16109 /* If ARG is an argument pack, we don't actually want to
16110 perform a substitution here, because substitutions
16111 for argument packs are only done
16112 element-by-element. We can get to this point when
16113 substituting the type of a non-type template
16114 parameter pack, when that type actually contains
16115 template parameter packs from an outer template, e.g.,
16117 template<typename... Types> struct A {
16118 template<Types... Values> struct B { };
16119 }; */
16120 return t;
16122 if (code == TEMPLATE_TYPE_PARM)
16124 int quals;
16126 /* When building concept checks for the purpose of
16127 deducing placeholders, we can end up with wildcards
16128 where types are expected. Adjust this to the deduced
16129 value. */
16130 if (TREE_CODE (arg) == WILDCARD_DECL)
16131 arg = TREE_TYPE (TREE_TYPE (arg));
16133 gcc_assert (TYPE_P (arg));
16135 quals = cp_type_quals (arg) | cp_type_quals (t);
16137 return cp_build_qualified_type
16138 (arg, quals, complain | tf_ignore_bad_quals);
16140 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16142 /* We are processing a type constructed from a
16143 template template parameter. */
16144 tree argvec = tsubst (TYPE_TI_ARGS (t),
16145 args, complain, in_decl);
16146 if (argvec == error_mark_node)
16147 return error_mark_node;
16149 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16150 || TREE_CODE (arg) == TEMPLATE_DECL
16151 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16153 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16154 /* Consider this code:
16156 template <template <class> class Template>
16157 struct Internal {
16158 template <class Arg> using Bind = Template<Arg>;
16161 template <template <class> class Template, class Arg>
16162 using Instantiate = Template<Arg>; //#0
16164 template <template <class> class Template,
16165 class Argument>
16166 using Bind =
16167 Instantiate<Internal<Template>::template Bind,
16168 Argument>; //#1
16170 When #1 is parsed, the
16171 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16172 parameter `Template' in #0 matches the
16173 UNBOUND_CLASS_TEMPLATE representing the argument
16174 `Internal<Template>::template Bind'; We then want
16175 to assemble the type `Bind<Argument>' that can't
16176 be fully created right now, because
16177 `Internal<Template>' not being complete, the Bind
16178 template cannot be looked up in that context. So
16179 we need to "store" `Bind<Argument>' for later
16180 when the context of Bind becomes complete. Let's
16181 store that in a TYPENAME_TYPE. */
16182 return make_typename_type (TYPE_CONTEXT (arg),
16183 build_nt (TEMPLATE_ID_EXPR,
16184 TYPE_IDENTIFIER (arg),
16185 argvec),
16186 typename_type,
16187 complain);
16189 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16190 are resolving nested-types in the signature of a
16191 member function templates. Otherwise ARG is a
16192 TEMPLATE_DECL and is the real template to be
16193 instantiated. */
16194 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16195 arg = TYPE_NAME (arg);
16197 r = lookup_template_class (arg,
16198 argvec, in_decl,
16199 DECL_CONTEXT (arg),
16200 /*entering_scope=*/0,
16201 complain);
16202 return cp_build_qualified_type
16203 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16205 else if (code == TEMPLATE_TEMPLATE_PARM)
16206 return arg;
16207 else
16208 /* TEMPLATE_PARM_INDEX. */
16209 return convert_from_reference (unshare_expr (arg));
16212 if (level == 1)
16213 /* This can happen during the attempted tsubst'ing in
16214 unify. This means that we don't yet have any information
16215 about the template parameter in question. */
16216 return t;
16218 /* Early in template argument deduction substitution, we don't
16219 want to reduce the level of 'auto', or it will be confused
16220 with a normal template parm in subsequent deduction.
16221 Similarly, don't reduce the level of template parameters to
16222 avoid mismatches when deducing their types. */
16223 if (complain & tf_partial)
16224 return t;
16226 /* If we get here, we must have been looking at a parm for a
16227 more deeply nested template. Make a new version of this
16228 template parameter, but with a lower level. */
16229 int quals;
16230 switch (code)
16232 case TEMPLATE_TYPE_PARM:
16233 case TEMPLATE_TEMPLATE_PARM:
16234 quals = cp_type_quals (t);
16235 if (quals)
16237 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16238 t = TYPE_MAIN_VARIANT (t);
16241 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16242 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16243 && (code == TEMPLATE_TYPE_PARM
16244 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16245 /* Cache lowering a type parameter or a simple template
16246 template parameter. */
16247 r = TREE_TYPE (d);
16249 if (!r)
16251 r = copy_type (t);
16252 TEMPLATE_TYPE_PARM_INDEX (r)
16253 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16254 r, levels, args, complain);
16255 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16256 TYPE_MAIN_VARIANT (r) = r;
16257 TYPE_POINTER_TO (r) = NULL_TREE;
16258 TYPE_REFERENCE_TO (r) = NULL_TREE;
16260 if (code == TEMPLATE_TYPE_PARM)
16261 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16262 /* Propagate constraints on placeholders since they are
16263 only instantiated during satisfaction. */
16264 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16266 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16267 SET_TYPE_STRUCTURAL_EQUALITY (r);
16268 else
16269 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16272 if (quals)
16273 r = cp_build_qualified_type (r, quals,
16274 complain | tf_ignore_bad_quals);
16275 break;
16277 case BOUND_TEMPLATE_TEMPLATE_PARM:
16279 tree tinfo = TYPE_TEMPLATE_INFO (t);
16280 /* We might need to substitute into the types of non-type
16281 template parameters. This also lowers the level of
16282 the ttp appropriately. */
16283 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16284 complain, in_decl);
16285 if (tmpl == error_mark_node)
16286 return error_mark_node;
16287 tree argvec = tsubst (TI_ARGS (tinfo), args,
16288 complain, in_decl);
16289 if (argvec == error_mark_node)
16290 return error_mark_node;
16291 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16292 /*entering_scope=*/false, complain);
16293 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16294 break;
16297 case TEMPLATE_PARM_INDEX:
16298 /* OK, now substitute the type of the non-type parameter. We
16299 couldn't do it earlier because it might be an auto parameter,
16300 and we wouldn't need to if we had an argument. */
16301 type = tsubst (type, args, complain, in_decl);
16302 if (type == error_mark_node)
16303 return error_mark_node;
16304 r = reduce_template_parm_level (t, type, levels, args, complain);
16305 break;
16307 default:
16308 gcc_unreachable ();
16311 return r;
16314 case TREE_LIST:
16315 return tsubst_tree_list (t, args, complain, in_decl);
16317 case TREE_BINFO:
16318 /* We should never be tsubsting a binfo. */
16319 gcc_unreachable ();
16321 case TREE_VEC:
16322 /* A vector of template arguments. */
16323 gcc_assert (!type);
16324 return tsubst_template_args (t, args, complain, in_decl);
16326 case POINTER_TYPE:
16327 case REFERENCE_TYPE:
16329 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16330 return t;
16332 /* [temp.deduct]
16334 Type deduction may fail for any of the following
16335 reasons:
16337 -- Attempting to create a pointer to reference type.
16338 -- Attempting to create a reference to a reference type or
16339 a reference to void.
16341 Core issue 106 says that creating a reference to a reference
16342 during instantiation is no longer a cause for failure. We
16343 only enforce this check in strict C++98 mode. */
16344 if ((TYPE_REF_P (type)
16345 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16346 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16348 static location_t last_loc;
16350 /* We keep track of the last time we issued this error
16351 message to avoid spewing a ton of messages during a
16352 single bad template instantiation. */
16353 if (complain & tf_error
16354 && last_loc != input_location)
16356 if (VOID_TYPE_P (type))
16357 error ("forming reference to void");
16358 else if (code == POINTER_TYPE)
16359 error ("forming pointer to reference type %qT", type);
16360 else
16361 error ("forming reference to reference type %qT", type);
16362 last_loc = input_location;
16365 return error_mark_node;
16367 else if (TREE_CODE (type) == FUNCTION_TYPE
16368 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16369 || type_memfn_rqual (type) != REF_QUAL_NONE))
16371 if (complain & tf_error)
16373 if (code == POINTER_TYPE)
16374 error ("forming pointer to qualified function type %qT",
16375 type);
16376 else
16377 error ("forming reference to qualified function type %qT",
16378 type);
16380 return error_mark_node;
16382 else if (code == POINTER_TYPE)
16384 r = build_pointer_type (type);
16385 if (TREE_CODE (type) == METHOD_TYPE)
16386 r = build_ptrmemfunc_type (r);
16388 else if (TYPE_REF_P (type))
16389 /* In C++0x, during template argument substitution, when there is an
16390 attempt to create a reference to a reference type, reference
16391 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16393 "If a template-argument for a template-parameter T names a type
16394 that is a reference to a type A, an attempt to create the type
16395 'lvalue reference to cv T' creates the type 'lvalue reference to
16396 A,' while an attempt to create the type type rvalue reference to
16397 cv T' creates the type T"
16399 r = cp_build_reference_type
16400 (TREE_TYPE (type),
16401 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16402 else
16403 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16404 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16406 if (r != error_mark_node)
16407 /* Will this ever be needed for TYPE_..._TO values? */
16408 layout_type (r);
16410 return r;
16412 case OFFSET_TYPE:
16414 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16415 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16417 /* [temp.deduct]
16419 Type deduction may fail for any of the following
16420 reasons:
16422 -- Attempting to create "pointer to member of T" when T
16423 is not a class type. */
16424 if (complain & tf_error)
16425 error ("creating pointer to member of non-class type %qT", r);
16426 return error_mark_node;
16428 if (TYPE_REF_P (type))
16430 if (complain & tf_error)
16431 error ("creating pointer to member reference type %qT", type);
16432 return error_mark_node;
16434 if (VOID_TYPE_P (type))
16436 if (complain & tf_error)
16437 error ("creating pointer to member of type void");
16438 return error_mark_node;
16440 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16441 if (TREE_CODE (type) == FUNCTION_TYPE)
16443 /* The type of the implicit object parameter gets its
16444 cv-qualifiers from the FUNCTION_TYPE. */
16445 tree memptr;
16446 tree method_type
16447 = build_memfn_type (type, r, type_memfn_quals (type),
16448 type_memfn_rqual (type));
16449 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16450 return cp_build_qualified_type (memptr, cp_type_quals (t),
16451 complain);
16453 else
16454 return cp_build_qualified_type (build_ptrmem_type (r, type),
16455 cp_type_quals (t),
16456 complain);
16458 case FUNCTION_TYPE:
16459 case METHOD_TYPE:
16461 tree fntype;
16462 tree specs;
16463 fntype = tsubst_function_type (t, args, complain, in_decl);
16464 if (fntype == error_mark_node)
16465 return error_mark_node;
16467 /* Substitute the exception specification. */
16468 specs = tsubst_exception_specification (t, args, complain, in_decl,
16469 /*defer_ok*/fndecl_type);
16470 if (specs == error_mark_node)
16471 return error_mark_node;
16472 if (specs)
16473 fntype = build_exception_variant (fntype, specs);
16474 return fntype;
16476 case ARRAY_TYPE:
16478 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16479 if (domain == error_mark_node)
16480 return error_mark_node;
16482 /* As an optimization, we avoid regenerating the array type if
16483 it will obviously be the same as T. */
16484 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16485 return t;
16487 /* These checks should match the ones in create_array_type_for_decl.
16489 [temp.deduct]
16491 The deduction may fail for any of the following reasons:
16493 -- Attempting to create an array with an element type that
16494 is void, a function type, or a reference type, or [DR337]
16495 an abstract class type. */
16496 if (VOID_TYPE_P (type)
16497 || TREE_CODE (type) == FUNCTION_TYPE
16498 || (TREE_CODE (type) == ARRAY_TYPE
16499 && TYPE_DOMAIN (type) == NULL_TREE)
16500 || TYPE_REF_P (type))
16502 if (complain & tf_error)
16503 error ("creating array of %qT", type);
16504 return error_mark_node;
16507 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16508 !(complain & tf_error)))
16509 return error_mark_node;
16511 r = build_cplus_array_type (type, domain);
16513 if (!valid_array_size_p (input_location, r, in_decl,
16514 (complain & tf_error)))
16515 return error_mark_node;
16517 if (TYPE_USER_ALIGN (t))
16519 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16520 TYPE_USER_ALIGN (r) = 1;
16523 return r;
16526 case TYPENAME_TYPE:
16528 tree ctx = TYPE_CONTEXT (t);
16529 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16531 ctx = tsubst_pack_expansion (ctx, args,
16532 complain | tf_qualifying_scope,
16533 in_decl);
16534 if (ctx == error_mark_node
16535 || TREE_VEC_LENGTH (ctx) > 1)
16536 return error_mark_node;
16537 if (TREE_VEC_LENGTH (ctx) == 0)
16539 if (complain & tf_error)
16540 error ("%qD is instantiated for an empty pack",
16541 TYPENAME_TYPE_FULLNAME (t));
16542 return error_mark_node;
16544 ctx = TREE_VEC_ELT (ctx, 0);
16546 else
16547 ctx = tsubst_aggr_type (ctx, args,
16548 complain | tf_qualifying_scope,
16549 in_decl, /*entering_scope=*/1);
16550 if (ctx == error_mark_node)
16551 return error_mark_node;
16553 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16554 complain, in_decl);
16555 if (f == error_mark_node)
16556 return error_mark_node;
16558 if (!MAYBE_CLASS_TYPE_P (ctx))
16560 if (complain & tf_error)
16561 error ("%qT is not a class, struct, or union type", ctx);
16562 return error_mark_node;
16564 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16566 /* Normally, make_typename_type does not require that the CTX
16567 have complete type in order to allow things like:
16569 template <class T> struct S { typename S<T>::X Y; };
16571 But, such constructs have already been resolved by this
16572 point, so here CTX really should have complete type, unless
16573 it's a partial instantiation. */
16574 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16575 return error_mark_node;
16578 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16579 tags. TYPENAME_TYPE should probably remember the exact tag that
16580 was written. */
16581 enum tag_types tag_type
16582 = TYPENAME_IS_CLASS_P (t) ? class_type
16583 : TYPENAME_IS_ENUM_P (t) ? enum_type
16584 : typename_type;
16585 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16586 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16587 f = make_typename_type (ctx, f, tag_type, tcomplain);
16588 if (f == error_mark_node)
16589 return f;
16590 if (TREE_CODE (f) == TYPE_DECL)
16592 complain |= tf_ignore_bad_quals;
16593 f = TREE_TYPE (f);
16596 if (TREE_CODE (f) != TYPENAME_TYPE)
16598 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16600 if (complain & tf_error)
16601 error ("%qT resolves to %qT, which is not an enumeration type",
16602 t, f);
16603 else
16604 return error_mark_node;
16606 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16608 if (complain & tf_error)
16609 error ("%qT resolves to %qT, which is not a class type",
16610 t, f);
16611 else
16612 return error_mark_node;
16616 return cp_build_qualified_type
16617 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16620 case UNBOUND_CLASS_TEMPLATE:
16622 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16623 in_decl, /*entering_scope=*/1);
16624 tree name = TYPE_IDENTIFIER (t);
16625 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16627 if (ctx == error_mark_node || name == error_mark_node)
16628 return error_mark_node;
16630 if (parm_list)
16631 parm_list = tsubst_template_parms (parm_list, args, complain);
16632 return make_unbound_class_template (ctx, name, parm_list, complain);
16635 case TYPEOF_TYPE:
16637 tree type;
16639 ++cp_unevaluated_operand;
16640 ++c_inhibit_evaluation_warnings;
16642 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16644 --cp_unevaluated_operand;
16645 --c_inhibit_evaluation_warnings;
16647 type = finish_typeof (type);
16648 return cp_build_qualified_type (type,
16649 cp_type_quals (t)
16650 | cp_type_quals (type),
16651 complain);
16654 case DECLTYPE_TYPE:
16656 tree type;
16658 ++cp_unevaluated_operand;
16659 ++c_inhibit_evaluation_warnings;
16661 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16662 complain|tf_decltype, in_decl);
16664 --cp_unevaluated_operand;
16665 --c_inhibit_evaluation_warnings;
16667 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16668 type = lambda_capture_field_type (type,
16669 false /*explicit_init*/,
16670 DECLTYPE_FOR_REF_CAPTURE (t));
16671 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16672 type = lambda_proxy_type (type);
16673 else
16675 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16676 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16677 && EXPR_P (type))
16678 /* In a template ~id could be either a complement expression
16679 or an unqualified-id naming a destructor; if instantiating
16680 it produces an expression, it's not an id-expression or
16681 member access. */
16682 id = false;
16683 type = finish_decltype_type (type, id, complain);
16685 return cp_build_qualified_type (type,
16686 cp_type_quals (t)
16687 | cp_type_quals (type),
16688 complain | tf_ignore_bad_quals);
16691 case TRAIT_TYPE:
16693 tree type1 = TRAIT_TYPE_TYPE1 (t);
16694 if (TYPE_P (type1))
16695 type1 = tsubst (type1, args, complain, in_decl);
16696 else
16697 type1 = tsubst_copy_and_build (type1, args, complain, in_decl);
16698 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16699 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16700 return cp_build_qualified_type (type,
16701 cp_type_quals (t) | cp_type_quals (type),
16702 complain | tf_ignore_bad_quals);
16705 case TYPE_ARGUMENT_PACK:
16706 case NONTYPE_ARGUMENT_PACK:
16707 return tsubst_argument_pack (t, args, complain, in_decl);
16709 case VOID_CST:
16710 case INTEGER_CST:
16711 case REAL_CST:
16712 case STRING_CST:
16713 case PLUS_EXPR:
16714 case MINUS_EXPR:
16715 case NEGATE_EXPR:
16716 case NOP_EXPR:
16717 case INDIRECT_REF:
16718 case ADDR_EXPR:
16719 case CALL_EXPR:
16720 case ARRAY_REF:
16721 case SCOPE_REF:
16722 /* We should use one of the expression tsubsts for these codes. */
16723 gcc_unreachable ();
16725 default:
16726 sorry ("use of %qs in template", get_tree_code_name (code));
16727 return error_mark_node;
16731 /* Convenience wrapper over tsubst for substituting into the LHS
16732 of the :: scope resolution operator. */
16734 static tree
16735 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16737 gcc_checking_assert (TYPE_P (t));
16738 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16741 /* OLDFNS is a lookup set of member functions from some class template, and
16742 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16743 of that class template. Return the subset of NEWFNS which are
16744 specializations of a function from OLDFNS. */
16746 static tree
16747 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16749 /* Record all member functions from the old lookup set OLDFNS into
16750 VISIBLE_SET. */
16751 hash_set<tree> visible_set;
16752 bool seen_dep_using = false;
16753 for (tree fn : lkp_range (oldfns))
16755 if (TREE_CODE (fn) == USING_DECL)
16757 /* Imprecisely handle dependent using-decl by keeping all members
16758 in the new lookup set that are defined in a base class, i.e.
16759 members that could plausibly have been introduced by this
16760 dependent using-decl.
16761 FIXME: Track which members are introduced by a dependent
16762 using-decl precisely, perhaps by performing another lookup
16763 from the substituted USING_DECL_SCOPE. */
16764 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16765 seen_dep_using = true;
16767 else
16768 visible_set.add (fn);
16771 /* Returns true iff (a less specialized version of) FN appeared in
16772 the old lookup set OLDFNS. */
16773 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16774 if (DECL_CONTEXT (fn) != newtype)
16775 /* FN is a member function from a base class, introduced via a
16776 using-decl; if it might have been introduced by a dependent
16777 using-decl then just conservatively keep it, otherwise look
16778 in the old lookup set for FN exactly. */
16779 return seen_dep_using || visible_set.contains (fn);
16780 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16781 /* FN is a member function template from the current class;
16782 look in the old lookup set for the TEMPLATE_DECL from which
16783 it was specialized. */
16784 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16785 else
16786 /* FN is a non-template member function from the current class;
16787 look in the old lookup set for the FUNCTION_DECL from which
16788 it was specialized. */
16789 return visible_set.contains (DECL_TEMPLATE_RESULT
16790 (DECL_TI_TEMPLATE (fn)));
16793 bool lookup_changed_p = false;
16794 for (tree fn : lkp_range (newfns))
16795 if (!visible_p (fn))
16797 lookup_changed_p = true;
16798 break;
16800 if (!lookup_changed_p)
16801 return newfns;
16803 /* Filter out from NEWFNS the member functions that weren't
16804 previously visible according to OLDFNS. */
16805 tree filtered_fns = NULL_TREE;
16806 unsigned filtered_size = 0;
16807 for (tree fn : lkp_range (newfns))
16808 if (visible_p (fn))
16810 filtered_fns = lookup_add (fn, filtered_fns);
16811 filtered_size++;
16813 gcc_checking_assert (seen_dep_using
16814 ? filtered_size >= visible_set.elements ()
16815 : filtered_size == visible_set.elements ());
16817 return filtered_fns;
16820 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16821 expression on the left-hand side of the "." or "->" operator. We
16822 only do the lookup if we had a dependent BASELINK. Otherwise we
16823 adjust it onto the instantiated heirarchy. */
16825 static tree
16826 tsubst_baselink (tree baselink, tree object_type,
16827 tree args, tsubst_flags_t complain, tree in_decl)
16829 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16830 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16831 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16833 tree optype = BASELINK_OPTYPE (baselink);
16834 optype = tsubst (optype, args, complain, in_decl);
16836 tree template_args = NULL_TREE;
16837 bool template_id_p = false;
16838 tree fns = BASELINK_FUNCTIONS (baselink);
16839 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16841 template_id_p = true;
16842 template_args = TREE_OPERAND (fns, 1);
16843 fns = TREE_OPERAND (fns, 0);
16844 if (template_args)
16845 template_args = tsubst_template_args (template_args, args,
16846 complain, in_decl);
16849 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16850 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16851 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16852 || optype != BASELINK_OPTYPE (baselink));
16854 if (dependent_p)
16856 tree name = OVL_NAME (fns);
16857 if (IDENTIFIER_CONV_OP_P (name))
16858 name = make_conv_op_name (optype);
16860 /* See maybe_dependent_member_ref. */
16861 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16863 if (template_id_p)
16864 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16865 template_args);
16866 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16867 /* ::template */false);
16870 if (name == complete_dtor_identifier)
16871 /* Treat as-if non-dependent below. */
16872 dependent_p = false;
16874 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16875 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16876 complain);
16877 if (maybe_incomplete)
16879 /* Filter out from the new lookup set those functions which didn't
16880 appear in the original lookup set (in a less specialized form).
16881 This is needed to preserve the consistency of member lookup
16882 performed in an incomplete-class context, within which
16883 later-declared members ought to remain invisible. */
16884 BASELINK_FUNCTIONS (baselink)
16885 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16886 binfo_type);
16887 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16890 if (!baselink)
16892 if ((complain & tf_error)
16893 && constructor_name_p (name, qualifying_scope))
16894 error ("cannot call constructor %<%T::%D%> directly",
16895 qualifying_scope, name);
16896 return error_mark_node;
16899 fns = BASELINK_FUNCTIONS (baselink);
16901 else
16903 /* We're going to overwrite pieces below, make a duplicate. */
16904 baselink = copy_node (baselink);
16906 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16908 /* The decl we found was from non-dependent scope, but we still need
16909 to update the binfos for the instantiated qualifying_scope. */
16910 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16911 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16912 ba_unique, nullptr, complain);
16916 /* If lookup found a single function, mark it as used at this point.
16917 (If lookup found multiple functions the one selected later by
16918 overload resolution will be marked as used at that point.) */
16919 if (!template_id_p && !really_overloaded_fn (fns))
16921 tree fn = OVL_FIRST (fns);
16922 bool ok = mark_used (fn, complain);
16923 if (!ok && !(complain & tf_error))
16924 return error_mark_node;
16925 if (ok && BASELINK_P (baselink))
16926 /* We might have instantiated an auto function. */
16927 TREE_TYPE (baselink) = TREE_TYPE (fn);
16930 if (BASELINK_P (baselink))
16932 /* Add back the template arguments, if present. */
16933 if (template_id_p)
16934 BASELINK_FUNCTIONS (baselink)
16935 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16937 /* Update the conversion operator type. */
16938 BASELINK_OPTYPE (baselink) = optype;
16941 if (!object_type)
16942 object_type = current_class_type;
16944 if (qualified_p || !dependent_p)
16946 baselink = adjust_result_of_qualified_name_lookup (baselink,
16947 qualifying_scope,
16948 object_type);
16949 if (!qualified_p)
16950 /* We need to call adjust_result_of_qualified_name_lookup in case the
16951 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16952 so that we still get virtual function binding. */
16953 BASELINK_QUALIFIED_P (baselink) = false;
16956 return baselink;
16959 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16960 true if the qualified-id will be a postfix-expression in-and-of
16961 itself; false if more of the postfix-expression follows the
16962 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16963 of "&". */
16965 static tree
16966 tsubst_qualified_id (tree qualified_id, tree args,
16967 tsubst_flags_t complain, tree in_decl,
16968 bool done, bool address_p)
16970 tree expr;
16971 tree scope;
16972 tree name;
16973 bool is_template;
16974 tree template_args;
16975 location_t loc = EXPR_LOCATION (qualified_id);
16977 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16979 /* Figure out what name to look up. */
16980 name = TREE_OPERAND (qualified_id, 1);
16981 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16983 is_template = true;
16984 template_args = TREE_OPERAND (name, 1);
16985 if (template_args)
16986 template_args = tsubst_template_args (template_args, args,
16987 complain, in_decl);
16988 if (template_args == error_mark_node)
16989 return error_mark_node;
16990 name = TREE_OPERAND (name, 0);
16992 else
16994 is_template = false;
16995 template_args = NULL_TREE;
16998 /* Substitute into the qualifying scope. When there are no ARGS, we
16999 are just trying to simplify a non-dependent expression. In that
17000 case the qualifying scope may be dependent, and, in any case,
17001 substituting will not help. */
17002 scope = TREE_OPERAND (qualified_id, 0);
17003 if (args)
17005 scope = tsubst_scope (scope, args, complain, in_decl);
17006 expr = tsubst_copy (name, args, complain, in_decl);
17008 else
17009 expr = name;
17011 if (dependent_scope_p (scope))
17013 if (TREE_CODE (expr) == SCOPE_REF)
17014 /* We built one in tsubst_baselink. */
17015 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17016 else
17018 if (is_template)
17019 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17020 template_args);
17021 expr = build_qualified_name (NULL_TREE, scope, expr,
17022 QUALIFIED_NAME_IS_TEMPLATE
17023 (qualified_id));
17025 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17026 return expr;
17029 if (!BASELINK_P (name) && !DECL_P (expr))
17031 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17033 /* A BIT_NOT_EXPR is used to represent a destructor. */
17034 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17036 error ("qualifying type %qT does not match destructor name ~%qT",
17037 scope, TREE_OPERAND (expr, 0));
17038 expr = error_mark_node;
17040 else
17041 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17042 LOOK_want::NORMAL, false);
17044 else
17045 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17046 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17047 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17049 if (complain & tf_error)
17051 error ("dependent-name %qE is parsed as a non-type, but "
17052 "instantiation yields a type", qualified_id);
17053 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17055 return error_mark_node;
17059 if (DECL_P (expr))
17061 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17062 scope, complain))
17063 return error_mark_node;
17064 /* Remember that there was a reference to this entity. */
17065 if (!mark_used (expr, complain) && !(complain & tf_error))
17066 return error_mark_node;
17069 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17071 if (complain & tf_error)
17072 qualified_name_lookup_error (scope,
17073 TREE_OPERAND (qualified_id, 1),
17074 expr, input_location);
17075 return error_mark_node;
17078 if (is_template)
17080 /* We may be repeating a check already done during parsing, but
17081 if it was well-formed and passed then, it will pass again
17082 now, and if it didn't, we wouldn't have got here. The case
17083 we want to catch is when we couldn't tell then, and can now,
17084 namely when templ prior to substitution was an
17085 identifier. */
17086 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17087 return error_mark_node;
17089 if (variable_template_p (expr))
17090 expr = lookup_and_finish_template_variable (expr, template_args,
17091 complain);
17092 else
17093 expr = lookup_template_function (expr, template_args);
17096 if (expr == error_mark_node && complain & tf_error)
17097 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17098 expr, input_location);
17099 else if (TYPE_P (scope))
17101 expr = (adjust_result_of_qualified_name_lookup
17102 (expr, scope, current_nonlambda_class_type ()));
17103 expr = (finish_qualified_id_expr
17104 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17105 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17106 /*template_arg_p=*/false, complain));
17109 /* Expressions do not generally have reference type. */
17110 if (TREE_CODE (expr) != SCOPE_REF
17111 /* However, if we're about to form a pointer-to-member, we just
17112 want the referenced member referenced. */
17113 && TREE_CODE (expr) != OFFSET_REF)
17114 expr = convert_from_reference (expr);
17116 if (REF_PARENTHESIZED_P (qualified_id))
17117 expr = force_paren_expr (expr);
17119 expr = maybe_wrap_with_location (expr, loc);
17121 return expr;
17124 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17125 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17126 for tsubst. */
17128 static tree
17129 tsubst_init (tree init, tree decl, tree args,
17130 tsubst_flags_t complain, tree in_decl)
17132 if (!init)
17133 return NULL_TREE;
17135 init = tsubst_expr (init, args, complain, in_decl);
17137 tree type = TREE_TYPE (decl);
17139 if (!init && type != error_mark_node)
17141 if (tree auto_node = type_uses_auto (type))
17143 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17145 if (complain & tf_error)
17146 error ("initializer for %q#D expands to an empty list "
17147 "of expressions", decl);
17148 return error_mark_node;
17151 else if (!dependent_type_p (type))
17153 /* If we had an initializer but it
17154 instantiated to nothing,
17155 value-initialize the object. This will
17156 only occur when the initializer was a
17157 pack expansion where the parameter packs
17158 used in that expansion were of length
17159 zero. */
17160 init = build_value_init (type, complain);
17161 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17162 init = get_target_expr (init, complain);
17163 if (TREE_CODE (init) == TARGET_EXPR)
17164 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17168 return init;
17171 /* If T is a reference to a dependent member of the current instantiation C and
17172 we are trying to refer to that member in a partial instantiation of C,
17173 return a SCOPE_REF; otherwise, return NULL_TREE.
17175 This can happen when forming a C++17 deduction guide, as in PR96199. */
17177 static tree
17178 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17179 tree in_decl)
17181 if (!(complain & tf_dguide))
17182 return NULL_TREE;
17184 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17185 if (!decl || !DECL_P (decl))
17186 return NULL_TREE;
17188 tree ctx = context_for_name_lookup (decl);
17189 if (!CLASS_TYPE_P (ctx))
17190 return NULL_TREE;
17192 ctx = tsubst (ctx, args, complain, in_decl);
17193 if (!dependent_scope_p (ctx))
17194 return NULL_TREE;
17196 if (TYPE_P (t))
17198 if (typedef_variant_p (t))
17199 t = strip_typedefs (t);
17200 tree decl = TYPE_NAME (t);
17201 if (decl)
17202 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17203 if (!decl)
17204 return NULL_TREE;
17205 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17206 complain);
17209 tree name = DECL_NAME (t);
17210 tree fullname = name;
17211 if (instantiates_primary_template_p (t))
17213 tree tinfo = get_template_info (t);
17214 name = DECL_NAME (TI_TEMPLATE (tinfo));
17215 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17216 targs = tsubst_template_args (targs, args, complain, in_decl);
17217 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17220 if (TREE_CODE (t) == TYPE_DECL)
17222 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17223 && TYPE_NAME (TREE_TYPE (t)) == t)
17224 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17225 scope, but it doesn't need to be rewritten again. */
17226 return NULL_TREE;
17227 tree type = build_typename_type (ctx, name, fullname, typename_type);
17228 return TYPE_NAME (type);
17230 else if (DECL_TYPE_TEMPLATE_P (t))
17231 return make_unbound_class_template (ctx, name,
17232 NULL_TREE, complain);
17233 else
17234 return build_qualified_name (NULL_TREE, ctx, fullname,
17235 TREE_CODE (t) == TEMPLATE_DECL);
17238 /* Like tsubst, but deals with expressions. This function just replaces
17239 template parms; to finish processing the resultant expression, use
17240 tsubst_copy_and_build or tsubst_expr. */
17242 static tree
17243 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17245 enum tree_code code;
17246 tree r;
17248 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17249 return t;
17251 if (TYPE_P (t))
17252 return tsubst (t, args, complain, in_decl);
17254 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17255 return d;
17257 code = TREE_CODE (t);
17259 switch (code)
17261 case PARM_DECL:
17262 r = retrieve_local_specialization (t);
17264 if (r == NULL_TREE)
17266 /* We get here for a use of 'this' in an NSDMI. */
17267 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17268 return current_class_ptr;
17270 /* This can happen for a parameter name used later in a function
17271 declaration (such as in a late-specified return type). Just
17272 make a dummy decl, since it's only used for its type. */
17273 gcc_assert (cp_unevaluated_operand);
17274 r = tsubst_decl (t, args, complain);
17275 /* Give it the template pattern as its context; its true context
17276 hasn't been instantiated yet and this is good enough for
17277 mangling. */
17278 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17281 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17282 r = argument_pack_select_arg (r);
17283 if (!mark_used (r, complain) && !(complain & tf_error))
17284 return error_mark_node;
17285 return r;
17287 case CONST_DECL:
17289 tree enum_type;
17290 tree v;
17292 if (DECL_TEMPLATE_PARM_P (t))
17293 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17294 if (!uses_template_parms (DECL_CONTEXT (t)))
17295 return t;
17297 /* Unfortunately, we cannot just call lookup_name here.
17298 Consider:
17300 template <int I> int f() {
17301 enum E { a = I };
17302 struct S { void g() { E e = a; } };
17305 When we instantiate f<7>::S::g(), say, lookup_name is not
17306 clever enough to find f<7>::a. */
17307 enum_type
17308 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17309 /*entering_scope=*/0);
17311 for (v = TYPE_VALUES (enum_type);
17312 v != NULL_TREE;
17313 v = TREE_CHAIN (v))
17314 if (TREE_PURPOSE (v) == DECL_NAME (t))
17315 return TREE_VALUE (v);
17317 /* We didn't find the name. That should never happen; if
17318 name-lookup found it during preliminary parsing, we
17319 should find it again here during instantiation. */
17320 gcc_unreachable ();
17322 return t;
17324 case FIELD_DECL:
17325 if (DECL_CONTEXT (t))
17327 tree ctx;
17329 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17330 /*entering_scope=*/1);
17331 if (ctx != DECL_CONTEXT (t))
17333 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17334 if (!r)
17336 if (complain & tf_error)
17337 error ("using invalid field %qD", t);
17338 return error_mark_node;
17340 return r;
17344 return t;
17346 case VAR_DECL:
17347 case FUNCTION_DECL:
17348 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17349 r = tsubst (t, args, complain, in_decl);
17350 else if (DECL_LOCAL_DECL_P (t))
17352 /* Local specialization will usually have been created when
17353 we instantiated the DECL_EXPR_DECL. */
17354 r = retrieve_local_specialization (t);
17355 if (!r)
17357 /* We're in a generic lambda referencing a local extern
17358 from an outer block-scope of a non-template. */
17359 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17360 r = t;
17363 else if (local_variable_p (t)
17364 && uses_template_parms (DECL_CONTEXT (t)))
17366 r = retrieve_local_specialization (t);
17367 if (r == NULL_TREE)
17369 /* First try name lookup to find the instantiation. */
17370 r = lookup_name (DECL_NAME (t));
17371 if (r)
17373 if (!VAR_P (r))
17375 /* During error-recovery we may find a non-variable,
17376 even an OVERLOAD: just bail out and avoid ICEs and
17377 duplicate diagnostics (c++/62207). */
17378 gcc_assert (seen_error ());
17379 return error_mark_node;
17381 if (!is_capture_proxy (r))
17383 /* Make sure the one we found is the one we want. */
17384 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17385 if (ctx != DECL_CONTEXT (r))
17386 r = NULL_TREE;
17390 if (r)
17391 /* OK */;
17392 else
17394 /* This can happen for a variable used in a
17395 late-specified return type of a local lambda, or for a
17396 local static or constant. Building a new VAR_DECL
17397 should be OK in all those cases. */
17398 r = tsubst_decl (t, args, complain);
17399 if (local_specializations)
17400 /* Avoid infinite recursion (79640). */
17401 register_local_specialization (r, t);
17402 if (decl_maybe_constant_var_p (r))
17404 /* We can't call cp_finish_decl, so handle the
17405 initializer by hand. */
17406 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17407 complain, in_decl);
17408 if (!processing_template_decl)
17409 init = maybe_constant_init (init);
17410 if (processing_template_decl
17411 ? potential_constant_expression (init)
17412 : reduced_constant_expression_p (init))
17413 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17414 = TREE_CONSTANT (r) = true;
17415 DECL_INITIAL (r) = init;
17416 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17417 TREE_TYPE (r)
17418 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17419 complain, adc_variable_type);
17421 gcc_assert (cp_unevaluated_operand
17422 || processing_contract_condition
17423 || TREE_STATIC (r)
17424 || decl_constant_var_p (r)
17425 || seen_error ());
17426 if (!processing_template_decl
17427 && !TREE_STATIC (r))
17428 r = process_outer_var_ref (r, complain);
17430 /* Remember this for subsequent uses. */
17431 if (local_specializations)
17432 register_local_specialization (r, t);
17434 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17435 r = argument_pack_select_arg (r);
17437 else
17438 r = t;
17439 if (!mark_used (r, complain))
17440 return error_mark_node;
17441 return r;
17443 case NAMESPACE_DECL:
17444 return t;
17446 case OVERLOAD:
17447 return t;
17449 case BASELINK:
17450 return tsubst_baselink (t, current_nonlambda_class_type (),
17451 args, complain, in_decl);
17453 case TEMPLATE_DECL:
17454 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17455 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17456 args, complain, in_decl);
17457 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17458 return tsubst (t, args, complain, in_decl);
17459 else if (DECL_CLASS_SCOPE_P (t)
17460 && uses_template_parms (DECL_CONTEXT (t)))
17462 /* Template template argument like the following example need
17463 special treatment:
17465 template <template <class> class TT> struct C {};
17466 template <class T> struct D {
17467 template <class U> struct E {};
17468 C<E> c; // #1
17470 D<int> d; // #2
17472 We are processing the template argument `E' in #1 for
17473 the template instantiation #2. Originally, `E' is a
17474 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17475 have to substitute this with one having context `D<int>'. */
17477 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
17478 in_decl, /*entering_scope=*/true);
17479 return lookup_field (context, DECL_NAME(t), 0, false);
17481 else
17482 /* Ordinary template template argument. */
17483 return t;
17485 case NON_LVALUE_EXPR:
17486 case VIEW_CONVERT_EXPR:
17488 /* Handle location wrappers by substituting the wrapped node
17489 first, *then* reusing the resulting type. Doing the type
17490 first ensures that we handle template parameters and
17491 parameter pack expansions. */
17492 if (location_wrapper_p (t))
17494 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17495 complain, in_decl);
17496 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17498 tree op = TREE_OPERAND (t, 0);
17499 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17500 if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17502 op = tsubst_copy (op, args, complain, in_decl);
17503 op = build1 (code, TREE_TYPE (op), op);
17504 REF_PARENTHESIZED_P (op) = true;
17505 return op;
17507 /* We shouldn't see any other uses of these in templates
17508 (tsubst_copy_and_build handles C++20 tparm object wrappers). */
17509 gcc_unreachable ();
17512 case CAST_EXPR:
17513 case REINTERPRET_CAST_EXPR:
17514 case CONST_CAST_EXPR:
17515 case STATIC_CAST_EXPR:
17516 case DYNAMIC_CAST_EXPR:
17517 case IMPLICIT_CONV_EXPR:
17518 CASE_CONVERT:
17520 tsubst_flags_t tcomplain = complain;
17521 if (code == CAST_EXPR)
17522 tcomplain |= tf_tst_ok;
17523 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17524 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17525 return build1 (code, type, op0);
17528 case BIT_CAST_EXPR:
17530 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17531 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17532 r = build_min (BIT_CAST_EXPR, type, op0);
17533 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17534 return r;
17537 case SIZEOF_EXPR:
17538 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17539 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17541 tree expanded, op = TREE_OPERAND (t, 0);
17542 int len = 0;
17544 if (SIZEOF_EXPR_TYPE_P (t))
17545 op = TREE_TYPE (op);
17547 ++cp_unevaluated_operand;
17548 ++c_inhibit_evaluation_warnings;
17549 /* We only want to compute the number of arguments. */
17550 if (PACK_EXPANSION_P (op))
17551 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17552 else
17553 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17554 args, complain, in_decl);
17555 --cp_unevaluated_operand;
17556 --c_inhibit_evaluation_warnings;
17558 if (TREE_CODE (expanded) == TREE_VEC)
17560 len = TREE_VEC_LENGTH (expanded);
17561 /* Set TREE_USED for the benefit of -Wunused. */
17562 for (int i = 0; i < len; i++)
17563 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17564 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17567 if (expanded == error_mark_node)
17568 return error_mark_node;
17569 else if (PACK_EXPANSION_P (expanded)
17570 || (TREE_CODE (expanded) == TREE_VEC
17571 && pack_expansion_args_count (expanded)))
17574 if (PACK_EXPANSION_P (expanded))
17575 /* OK. */;
17576 else if (TREE_VEC_LENGTH (expanded) == 1)
17577 expanded = TREE_VEC_ELT (expanded, 0);
17578 else
17579 expanded = make_argument_pack (expanded);
17581 if (TYPE_P (expanded))
17582 return cxx_sizeof_or_alignof_type (input_location,
17583 expanded, SIZEOF_EXPR,
17584 false,
17585 complain & tf_error);
17586 else
17587 return cxx_sizeof_or_alignof_expr (input_location,
17588 expanded, SIZEOF_EXPR,
17589 false,
17590 complain & tf_error);
17592 else
17593 return build_int_cst (size_type_node, len);
17595 if (SIZEOF_EXPR_TYPE_P (t))
17597 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17598 args, complain, in_decl);
17599 r = build1 (NOP_EXPR, r, error_mark_node);
17600 r = build1 (SIZEOF_EXPR,
17601 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17602 SIZEOF_EXPR_TYPE_P (r) = 1;
17603 return r;
17605 /* Fall through */
17607 case INDIRECT_REF:
17608 case NEGATE_EXPR:
17609 case TRUTH_NOT_EXPR:
17610 case BIT_NOT_EXPR:
17611 case ADDR_EXPR:
17612 case UNARY_PLUS_EXPR: /* Unary + */
17613 case ALIGNOF_EXPR:
17614 case AT_ENCODE_EXPR:
17615 case ARROW_EXPR:
17616 case THROW_EXPR:
17617 case TYPEID_EXPR:
17618 case REALPART_EXPR:
17619 case IMAGPART_EXPR:
17620 case PAREN_EXPR:
17622 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17623 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17624 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17625 if (code == ALIGNOF_EXPR)
17626 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17627 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17628 set for possible later diagnostics. */
17629 if (code == ADDR_EXPR
17630 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17631 && TREE_CODE (op0) == FUNCTION_DECL
17632 && DECL_IMMEDIATE_FUNCTION_P (op0))
17633 SET_EXPR_LOCATION (r, input_location);
17634 return r;
17637 case EXCESS_PRECISION_EXPR:
17639 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17640 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17641 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
17643 gcc_checking_assert (same_type_p (type, TREE_TYPE (op0)));
17644 return op0;
17646 return build1_loc (EXPR_LOCATION (t), code, type, op0);
17649 case COMPONENT_REF:
17651 tree object;
17652 tree name;
17654 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17655 name = TREE_OPERAND (t, 1);
17656 if (TREE_CODE (name) == BIT_NOT_EXPR)
17658 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17659 complain, in_decl);
17660 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17662 else if (TREE_CODE (name) == SCOPE_REF
17663 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17665 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17666 complain, in_decl);
17667 name = TREE_OPERAND (name, 1);
17668 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17669 complain, in_decl);
17670 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17671 name = build_qualified_name (/*type=*/NULL_TREE,
17672 base, name,
17673 /*template_p=*/false);
17675 else if (BASELINK_P (name))
17676 name = tsubst_baselink (name,
17677 non_reference (TREE_TYPE (object)),
17678 args, complain,
17679 in_decl);
17680 else
17681 name = tsubst_copy (name, args, complain, in_decl);
17682 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17685 case PLUS_EXPR:
17686 case MINUS_EXPR:
17687 case MULT_EXPR:
17688 case TRUNC_DIV_EXPR:
17689 case CEIL_DIV_EXPR:
17690 case FLOOR_DIV_EXPR:
17691 case ROUND_DIV_EXPR:
17692 case EXACT_DIV_EXPR:
17693 case BIT_AND_EXPR:
17694 case BIT_IOR_EXPR:
17695 case BIT_XOR_EXPR:
17696 case TRUNC_MOD_EXPR:
17697 case FLOOR_MOD_EXPR:
17698 case TRUTH_ANDIF_EXPR:
17699 case TRUTH_ORIF_EXPR:
17700 case TRUTH_AND_EXPR:
17701 case TRUTH_OR_EXPR:
17702 case RSHIFT_EXPR:
17703 case LSHIFT_EXPR:
17704 case EQ_EXPR:
17705 case NE_EXPR:
17706 case MAX_EXPR:
17707 case MIN_EXPR:
17708 case LE_EXPR:
17709 case GE_EXPR:
17710 case LT_EXPR:
17711 case GT_EXPR:
17712 case COMPOUND_EXPR:
17713 case DOTSTAR_EXPR:
17714 case MEMBER_REF:
17715 case PREDECREMENT_EXPR:
17716 case PREINCREMENT_EXPR:
17717 case POSTDECREMENT_EXPR:
17718 case POSTINCREMENT_EXPR:
17720 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17721 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17722 return build_nt (code, op0, op1);
17725 case SCOPE_REF:
17727 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
17728 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17729 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17730 QUALIFIED_NAME_IS_TEMPLATE (t));
17733 case ARRAY_REF:
17735 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17736 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17737 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17740 case CALL_EXPR:
17742 int n = VL_EXP_OPERAND_LENGTH (t);
17743 tree result = build_vl_exp (CALL_EXPR, n);
17744 int i;
17745 for (i = 0; i < n; i++)
17746 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17747 complain, in_decl);
17748 return result;
17751 case COND_EXPR:
17752 case MODOP_EXPR:
17753 case PSEUDO_DTOR_EXPR:
17754 case VEC_PERM_EXPR:
17756 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17757 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17758 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17759 r = build_nt (code, op0, op1, op2);
17760 copy_warning (r, t);
17761 return r;
17764 case NEW_EXPR:
17766 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17767 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17768 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17769 r = build_nt (code, op0, op1, op2);
17770 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17771 return r;
17774 case DELETE_EXPR:
17776 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17777 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17778 r = build_nt (code, op0, op1);
17779 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17780 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17781 return r;
17784 case TEMPLATE_ID_EXPR:
17786 /* Substituted template arguments */
17787 tree tmpl = TREE_OPERAND (t, 0);
17788 tree targs = TREE_OPERAND (t, 1);
17790 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17791 if (targs)
17792 targs = tsubst_template_args (targs, args, complain, in_decl);
17794 if (variable_template_p (tmpl))
17795 return lookup_template_variable (tmpl, targs, complain);
17796 else
17797 return lookup_template_function (tmpl, targs);
17800 case TREE_LIST:
17802 tree purpose, value, chain;
17804 if (t == void_list_node)
17805 return t;
17807 purpose = TREE_PURPOSE (t);
17808 if (purpose)
17809 purpose = tsubst_copy (purpose, args, complain, in_decl);
17810 value = TREE_VALUE (t);
17811 if (value)
17812 value = tsubst_copy (value, args, complain, in_decl);
17813 chain = TREE_CHAIN (t);
17814 if (chain && chain != void_type_node)
17815 chain = tsubst_copy (chain, args, complain, in_decl);
17816 if (purpose == TREE_PURPOSE (t)
17817 && value == TREE_VALUE (t)
17818 && chain == TREE_CHAIN (t))
17819 return t;
17820 return tree_cons (purpose, value, chain);
17823 case TEMPLATE_PARM_INDEX:
17824 case TYPE_DECL:
17825 return tsubst (t, args, complain, in_decl);
17827 case USING_DECL:
17828 t = DECL_NAME (t);
17829 /* Fall through. */
17830 case IDENTIFIER_NODE:
17831 if (IDENTIFIER_CONV_OP_P (t))
17833 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17834 return make_conv_op_name (new_type);
17836 else
17837 return t;
17839 case CONSTRUCTOR:
17840 /* This is handled by tsubst_copy_and_build. */
17841 gcc_unreachable ();
17843 case VA_ARG_EXPR:
17845 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17846 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17847 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17850 case CLEANUP_POINT_EXPR:
17851 /* We shouldn't have built any of these during initial template
17852 generation. Instead, they should be built during instantiation
17853 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17854 gcc_unreachable ();
17856 case OFFSET_REF:
17858 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17859 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17860 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17861 r = build2 (code, type, op0, op1);
17862 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17863 if (!mark_used (TREE_OPERAND (r, 1), complain)
17864 && !(complain & tf_error))
17865 return error_mark_node;
17866 return r;
17869 case EXPR_PACK_EXPANSION:
17870 error ("invalid use of pack expansion expression");
17871 return error_mark_node;
17873 case NONTYPE_ARGUMENT_PACK:
17874 error ("use %<...%> to expand argument pack");
17875 return error_mark_node;
17877 case VOID_CST:
17878 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17879 return t;
17881 case INTEGER_CST:
17882 case REAL_CST:
17883 case COMPLEX_CST:
17884 case VECTOR_CST:
17886 /* Instantiate any typedefs in the type. */
17887 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17888 r = fold_convert (type, t);
17889 gcc_assert (TREE_CODE (r) == code);
17890 return r;
17893 case STRING_CST:
17895 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17896 r = t;
17897 if (type != TREE_TYPE (t))
17899 r = copy_node (t);
17900 TREE_TYPE (r) = type;
17902 return r;
17905 case PTRMEM_CST:
17906 /* These can sometimes show up in a partial instantiation, but never
17907 involve template parms. */
17908 gcc_assert (!uses_template_parms (t));
17909 return t;
17911 case UNARY_LEFT_FOLD_EXPR:
17912 return tsubst_unary_left_fold (t, args, complain, in_decl);
17913 case UNARY_RIGHT_FOLD_EXPR:
17914 return tsubst_unary_right_fold (t, args, complain, in_decl);
17915 case BINARY_LEFT_FOLD_EXPR:
17916 return tsubst_binary_left_fold (t, args, complain, in_decl);
17917 case BINARY_RIGHT_FOLD_EXPR:
17918 return tsubst_binary_right_fold (t, args, complain, in_decl);
17919 case PREDICT_EXPR:
17920 return t;
17922 case DEBUG_BEGIN_STMT:
17923 /* ??? There's no point in copying it for now, but maybe some
17924 day it will contain more information, such as a pointer back
17925 to the containing function, inlined copy or so. */
17926 return t;
17928 case CO_AWAIT_EXPR:
17929 return tsubst_expr (t, args, complain, in_decl);
17931 default:
17932 /* We shouldn't get here, but keep going if !flag_checking. */
17933 if (flag_checking)
17934 gcc_unreachable ();
17935 return t;
17939 /* Helper function for tsubst_omp_clauses, used for instantiation of
17940 OMP_CLAUSE_DECL of clauses. */
17942 static tree
17943 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17944 tree in_decl, tree *iterator_cache)
17946 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17947 return decl;
17949 /* Handle OpenMP iterators. */
17950 if (TREE_CODE (decl) == TREE_LIST
17951 && TREE_PURPOSE (decl)
17952 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17954 tree ret;
17955 if (iterator_cache[0] == TREE_PURPOSE (decl))
17956 ret = iterator_cache[1];
17957 else
17959 tree *tp = &ret;
17960 begin_scope (sk_omp, NULL);
17961 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17963 *tp = copy_node (it);
17964 TREE_VEC_ELT (*tp, 0)
17965 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17966 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17967 pushdecl (TREE_VEC_ELT (*tp, 0));
17968 TREE_VEC_ELT (*tp, 1)
17969 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17970 TREE_VEC_ELT (*tp, 2)
17971 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17972 TREE_VEC_ELT (*tp, 3)
17973 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17974 TREE_CHAIN (*tp) = NULL_TREE;
17975 tp = &TREE_CHAIN (*tp);
17977 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17978 iterator_cache[0] = TREE_PURPOSE (decl);
17979 iterator_cache[1] = ret;
17981 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17982 args, complain,
17983 in_decl, NULL));
17986 /* Handle an OpenMP array section represented as a TREE_LIST (or
17987 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17988 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17989 TREE_LIST. We can handle it exactly the same as an array section
17990 (purpose, value, and a chain), even though the nomenclature
17991 (low_bound, length, etc) is different. */
17992 if (TREE_CODE (decl) == TREE_LIST)
17994 tree low_bound
17995 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl);
17996 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl);
17997 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17998 in_decl, NULL);
17999 if (TREE_PURPOSE (decl) == low_bound
18000 && TREE_VALUE (decl) == length
18001 && TREE_CHAIN (decl) == chain)
18002 return decl;
18003 tree ret = tree_cons (low_bound, length, chain);
18004 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
18005 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
18006 return ret;
18008 tree ret = tsubst_expr (decl, args, complain, in_decl);
18009 /* Undo convert_from_reference tsubst_expr could have called. */
18010 if (decl
18011 && REFERENCE_REF_P (ret)
18012 && !REFERENCE_REF_P (decl))
18013 ret = TREE_OPERAND (ret, 0);
18014 return ret;
18017 /* Like tsubst_copy, but specifically for OpenMP clauses. */
18019 static tree
18020 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
18021 tree args, tsubst_flags_t complain, tree in_decl)
18023 tree new_clauses = NULL_TREE, nc, oc;
18024 tree linear_no_step = NULL_TREE;
18025 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
18027 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
18029 nc = copy_node (oc);
18030 OMP_CLAUSE_CHAIN (nc) = new_clauses;
18031 new_clauses = nc;
18033 switch (OMP_CLAUSE_CODE (nc))
18035 case OMP_CLAUSE_LASTPRIVATE:
18036 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
18038 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
18039 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
18040 complain, in_decl);
18041 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
18042 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
18044 /* FALLTHRU */
18045 case OMP_CLAUSE_PRIVATE:
18046 case OMP_CLAUSE_SHARED:
18047 case OMP_CLAUSE_FIRSTPRIVATE:
18048 case OMP_CLAUSE_COPYIN:
18049 case OMP_CLAUSE_COPYPRIVATE:
18050 case OMP_CLAUSE_UNIFORM:
18051 case OMP_CLAUSE_DEPEND:
18052 case OMP_CLAUSE_DOACROSS:
18053 case OMP_CLAUSE_AFFINITY:
18054 case OMP_CLAUSE_FROM:
18055 case OMP_CLAUSE_TO:
18056 case OMP_CLAUSE_MAP:
18057 case OMP_CLAUSE__CACHE_:
18058 case OMP_CLAUSE_NONTEMPORAL:
18059 case OMP_CLAUSE_USE_DEVICE_PTR:
18060 case OMP_CLAUSE_USE_DEVICE_ADDR:
18061 case OMP_CLAUSE_IS_DEVICE_PTR:
18062 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18063 case OMP_CLAUSE_INCLUSIVE:
18064 case OMP_CLAUSE_EXCLUSIVE:
18065 OMP_CLAUSE_DECL (nc)
18066 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18067 in_decl, iterator_cache);
18068 break;
18069 case OMP_CLAUSE_NUM_TEAMS:
18070 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
18071 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
18072 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
18073 complain, in_decl);
18074 /* FALLTHRU */
18075 case OMP_CLAUSE_TILE:
18076 case OMP_CLAUSE_IF:
18077 case OMP_CLAUSE_NUM_THREADS:
18078 case OMP_CLAUSE_SCHEDULE:
18079 case OMP_CLAUSE_COLLAPSE:
18080 case OMP_CLAUSE_FINAL:
18081 case OMP_CLAUSE_DEVICE:
18082 case OMP_CLAUSE_DIST_SCHEDULE:
18083 case OMP_CLAUSE_THREAD_LIMIT:
18084 case OMP_CLAUSE_SAFELEN:
18085 case OMP_CLAUSE_SIMDLEN:
18086 case OMP_CLAUSE_NUM_TASKS:
18087 case OMP_CLAUSE_GRAINSIZE:
18088 case OMP_CLAUSE_PRIORITY:
18089 case OMP_CLAUSE_ORDERED:
18090 case OMP_CLAUSE_HINT:
18091 case OMP_CLAUSE_FILTER:
18092 case OMP_CLAUSE_NUM_GANGS:
18093 case OMP_CLAUSE_NUM_WORKERS:
18094 case OMP_CLAUSE_VECTOR_LENGTH:
18095 case OMP_CLAUSE_WORKER:
18096 case OMP_CLAUSE_VECTOR:
18097 case OMP_CLAUSE_ASYNC:
18098 case OMP_CLAUSE_WAIT:
18099 case OMP_CLAUSE_DETACH:
18100 OMP_CLAUSE_OPERAND (nc, 0)
18101 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
18102 break;
18103 case OMP_CLAUSE_REDUCTION:
18104 case OMP_CLAUSE_IN_REDUCTION:
18105 case OMP_CLAUSE_TASK_REDUCTION:
18106 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
18108 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
18109 if (TREE_CODE (placeholder) == SCOPE_REF)
18111 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
18112 complain, in_decl);
18113 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
18114 = build_qualified_name (NULL_TREE, scope,
18115 TREE_OPERAND (placeholder, 1),
18116 false);
18118 else
18119 gcc_assert (identifier_p (placeholder));
18121 OMP_CLAUSE_DECL (nc)
18122 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18123 in_decl, NULL);
18124 break;
18125 case OMP_CLAUSE_GANG:
18126 case OMP_CLAUSE_ALIGNED:
18127 OMP_CLAUSE_DECL (nc)
18128 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18129 in_decl, NULL);
18130 OMP_CLAUSE_OPERAND (nc, 1)
18131 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18132 break;
18133 case OMP_CLAUSE_ALLOCATE:
18134 OMP_CLAUSE_DECL (nc)
18135 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18136 in_decl, NULL);
18137 OMP_CLAUSE_OPERAND (nc, 1)
18138 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18139 OMP_CLAUSE_OPERAND (nc, 2)
18140 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
18141 break;
18142 case OMP_CLAUSE_LINEAR:
18143 OMP_CLAUSE_DECL (nc)
18144 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18145 in_decl, NULL);
18146 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
18148 gcc_assert (!linear_no_step);
18149 linear_no_step = nc;
18151 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
18152 OMP_CLAUSE_LINEAR_STEP (nc)
18153 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
18154 complain, in_decl, NULL);
18155 else
18156 OMP_CLAUSE_LINEAR_STEP (nc)
18157 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args,
18158 complain, in_decl);
18159 break;
18160 case OMP_CLAUSE_NOWAIT:
18161 case OMP_CLAUSE_DEFAULT:
18162 case OMP_CLAUSE_UNTIED:
18163 case OMP_CLAUSE_MERGEABLE:
18164 case OMP_CLAUSE_INBRANCH:
18165 case OMP_CLAUSE_NOTINBRANCH:
18166 case OMP_CLAUSE_PROC_BIND:
18167 case OMP_CLAUSE_FOR:
18168 case OMP_CLAUSE_PARALLEL:
18169 case OMP_CLAUSE_SECTIONS:
18170 case OMP_CLAUSE_TASKGROUP:
18171 case OMP_CLAUSE_NOGROUP:
18172 case OMP_CLAUSE_THREADS:
18173 case OMP_CLAUSE_SIMD:
18174 case OMP_CLAUSE_DEFAULTMAP:
18175 case OMP_CLAUSE_ORDER:
18176 case OMP_CLAUSE_BIND:
18177 case OMP_CLAUSE_INDEPENDENT:
18178 case OMP_CLAUSE_AUTO:
18179 case OMP_CLAUSE_SEQ:
18180 case OMP_CLAUSE_IF_PRESENT:
18181 case OMP_CLAUSE_FINALIZE:
18182 case OMP_CLAUSE_NOHOST:
18183 break;
18184 default:
18185 gcc_unreachable ();
18187 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18188 switch (OMP_CLAUSE_CODE (nc))
18190 case OMP_CLAUSE_SHARED:
18191 case OMP_CLAUSE_PRIVATE:
18192 case OMP_CLAUSE_FIRSTPRIVATE:
18193 case OMP_CLAUSE_LASTPRIVATE:
18194 case OMP_CLAUSE_COPYPRIVATE:
18195 case OMP_CLAUSE_LINEAR:
18196 case OMP_CLAUSE_REDUCTION:
18197 case OMP_CLAUSE_IN_REDUCTION:
18198 case OMP_CLAUSE_TASK_REDUCTION:
18199 case OMP_CLAUSE_USE_DEVICE_PTR:
18200 case OMP_CLAUSE_USE_DEVICE_ADDR:
18201 case OMP_CLAUSE_IS_DEVICE_PTR:
18202 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18203 case OMP_CLAUSE_INCLUSIVE:
18204 case OMP_CLAUSE_EXCLUSIVE:
18205 case OMP_CLAUSE_ALLOCATE:
18206 /* tsubst_expr on SCOPE_REF results in returning
18207 finish_non_static_data_member result. Undo that here. */
18208 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18209 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18210 == IDENTIFIER_NODE))
18212 tree t = OMP_CLAUSE_DECL (nc);
18213 tree v = t;
18214 while (v)
18215 switch (TREE_CODE (v))
18217 case COMPONENT_REF:
18218 case MEM_REF:
18219 case INDIRECT_REF:
18220 CASE_CONVERT:
18221 case POINTER_PLUS_EXPR:
18222 v = TREE_OPERAND (v, 0);
18223 continue;
18224 case PARM_DECL:
18225 if (DECL_CONTEXT (v) == current_function_decl
18226 && DECL_ARTIFICIAL (v)
18227 && DECL_NAME (v) == this_identifier)
18228 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18229 /* FALLTHRU */
18230 default:
18231 v = NULL_TREE;
18232 break;
18235 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18236 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18237 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18238 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18239 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18241 tree decl = OMP_CLAUSE_DECL (nc);
18242 if (VAR_P (decl))
18244 retrofit_lang_decl (decl);
18245 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18248 break;
18249 default:
18250 break;
18254 new_clauses = nreverse (new_clauses);
18255 if (ort != C_ORT_OMP_DECLARE_SIMD)
18257 new_clauses = finish_omp_clauses (new_clauses, ort);
18258 if (linear_no_step)
18259 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18260 if (nc == linear_no_step)
18262 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18263 break;
18266 return new_clauses;
18269 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18271 static tree
18272 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18273 tree in_decl)
18275 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18277 tree purpose, value, chain;
18279 if (t == NULL)
18280 return t;
18282 if (TREE_CODE (t) != TREE_LIST)
18283 return tsubst_copy_and_build (t, args, complain, in_decl);
18285 if (t == void_list_node)
18286 return t;
18288 purpose = TREE_PURPOSE (t);
18289 if (purpose)
18290 purpose = RECUR (purpose);
18291 value = TREE_VALUE (t);
18292 if (value)
18294 if (TREE_CODE (value) != LABEL_DECL)
18295 value = RECUR (value);
18296 else
18298 value = lookup_label (DECL_NAME (value));
18299 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18300 TREE_USED (value) = 1;
18303 chain = TREE_CHAIN (t);
18304 if (chain && chain != void_type_node)
18305 chain = RECUR (chain);
18306 return tree_cons (purpose, value, chain);
18307 #undef RECUR
18310 /* Used to temporarily communicate the list of #pragma omp parallel
18311 clauses to #pragma omp for instantiation if they are combined
18312 together. */
18314 static tree *omp_parallel_combined_clauses;
18316 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18317 tree *, unsigned int *);
18319 /* Substitute one OMP_FOR iterator. */
18321 static bool
18322 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18323 tree initv, tree condv, tree incrv, tree *clauses,
18324 tree args, tsubst_flags_t complain, tree in_decl)
18326 #define RECUR(NODE) \
18327 tsubst_expr ((NODE), args, complain, in_decl)
18328 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18329 bool ret = false;
18331 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18332 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18334 decl = TREE_OPERAND (init, 0);
18335 init = TREE_OPERAND (init, 1);
18336 tree decl_expr = NULL_TREE;
18337 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18338 if (range_for)
18340 bool decomp = false;
18341 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18343 tree v = DECL_VALUE_EXPR (decl);
18344 if (TREE_CODE (v) == ARRAY_REF
18345 && VAR_P (TREE_OPERAND (v, 0))
18346 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18348 tree decomp_first = NULL_TREE;
18349 unsigned decomp_cnt = 0;
18350 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18351 maybe_push_decl (d);
18352 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18353 in_decl, &decomp_first, &decomp_cnt);
18354 decomp = true;
18355 if (d == error_mark_node)
18356 decl = error_mark_node;
18357 else
18358 for (unsigned int i = 0; i < decomp_cnt; i++)
18360 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18362 tree v = build_nt (ARRAY_REF, d,
18363 size_int (decomp_cnt - i - 1),
18364 NULL_TREE, NULL_TREE);
18365 SET_DECL_VALUE_EXPR (decomp_first, v);
18366 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18368 fit_decomposition_lang_decl (decomp_first, d);
18369 decomp_first = DECL_CHAIN (decomp_first);
18373 decl = tsubst_decl (decl, args, complain);
18374 if (!decomp)
18375 maybe_push_decl (decl);
18377 else if (init && TREE_CODE (init) == DECL_EXPR)
18379 /* We need to jump through some hoops to handle declarations in the
18380 init-statement, since we might need to handle auto deduction,
18381 but we need to keep control of initialization. */
18382 decl_expr = init;
18383 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18384 decl = tsubst_decl (decl, args, complain);
18386 else
18388 if (TREE_CODE (decl) == SCOPE_REF)
18390 decl = RECUR (decl);
18391 if (TREE_CODE (decl) == COMPONENT_REF)
18393 tree v = decl;
18394 while (v)
18395 switch (TREE_CODE (v))
18397 case COMPONENT_REF:
18398 case MEM_REF:
18399 case INDIRECT_REF:
18400 CASE_CONVERT:
18401 case POINTER_PLUS_EXPR:
18402 v = TREE_OPERAND (v, 0);
18403 continue;
18404 case PARM_DECL:
18405 if (DECL_CONTEXT (v) == current_function_decl
18406 && DECL_ARTIFICIAL (v)
18407 && DECL_NAME (v) == this_identifier)
18409 decl = TREE_OPERAND (decl, 1);
18410 decl = omp_privatize_field (decl, false);
18412 /* FALLTHRU */
18413 default:
18414 v = NULL_TREE;
18415 break;
18419 else
18420 decl = RECUR (decl);
18422 if (init && TREE_CODE (init) == TREE_VEC)
18424 init = copy_node (init);
18425 TREE_VEC_ELT (init, 0)
18426 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18427 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18428 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18430 else
18431 init = RECUR (init);
18433 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18435 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18436 if (TREE_CODE (o) == TREE_LIST)
18437 TREE_VEC_ELT (orig_declv, i)
18438 = tree_cons (RECUR (TREE_PURPOSE (o)),
18439 RECUR (TREE_VALUE (o)),
18440 NULL_TREE);
18441 else
18442 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18445 if (range_for)
18447 tree this_pre_body = NULL_TREE;
18448 tree orig_init = NULL_TREE;
18449 tree orig_decl = NULL_TREE;
18450 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18451 orig_init, cond, incr);
18452 if (orig_decl)
18454 if (orig_declv == NULL_TREE)
18455 orig_declv = copy_node (declv);
18456 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18457 ret = true;
18459 else if (orig_declv)
18460 TREE_VEC_ELT (orig_declv, i) = decl;
18463 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18464 if (!range_for && auto_node && init)
18465 TREE_TYPE (decl)
18466 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18468 gcc_assert (!type_dependent_expression_p (decl));
18470 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18472 if (decl_expr)
18474 /* Declare the variable, but don't let that initialize it. */
18475 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18476 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18477 RECUR (decl_expr);
18478 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18481 if (!range_for)
18483 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18484 if (COMPARISON_CLASS_P (cond)
18485 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18487 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18488 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18489 TREE_VEC_ELT (rhs, 0)
18490 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18491 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18492 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18493 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18494 lhs, rhs);
18496 else
18497 cond = RECUR (cond);
18498 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18499 if (TREE_CODE (incr) == MODIFY_EXPR)
18501 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18502 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18503 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18504 NOP_EXPR, rhs, NULL_TREE, complain);
18506 else
18507 incr = RECUR (incr);
18508 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18509 TREE_VEC_ELT (orig_declv, i) = decl;
18511 TREE_VEC_ELT (declv, i) = decl;
18512 TREE_VEC_ELT (initv, i) = init;
18513 TREE_VEC_ELT (condv, i) = cond;
18514 TREE_VEC_ELT (incrv, i) = incr;
18515 return ret;
18518 if (decl_expr)
18520 /* Declare and initialize the variable. */
18521 RECUR (decl_expr);
18522 init = NULL_TREE;
18524 else if (init)
18526 tree *pc;
18527 int j;
18528 for (j = ((omp_parallel_combined_clauses == NULL
18529 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18531 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18533 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18534 && OMP_CLAUSE_DECL (*pc) == decl)
18535 break;
18536 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18537 && OMP_CLAUSE_DECL (*pc) == decl)
18539 if (j)
18540 break;
18541 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18542 tree c = *pc;
18543 *pc = OMP_CLAUSE_CHAIN (c);
18544 OMP_CLAUSE_CHAIN (c) = *clauses;
18545 *clauses = c;
18547 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18548 && OMP_CLAUSE_DECL (*pc) == decl)
18550 error ("iteration variable %qD should not be firstprivate",
18551 decl);
18552 *pc = OMP_CLAUSE_CHAIN (*pc);
18554 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18555 && OMP_CLAUSE_DECL (*pc) == decl)
18557 error ("iteration variable %qD should not be reduction",
18558 decl);
18559 *pc = OMP_CLAUSE_CHAIN (*pc);
18561 else
18562 pc = &OMP_CLAUSE_CHAIN (*pc);
18564 if (*pc)
18565 break;
18567 if (*pc == NULL_TREE)
18569 tree c = build_omp_clause (input_location,
18570 TREE_CODE (t) == OMP_LOOP
18571 ? OMP_CLAUSE_LASTPRIVATE
18572 : OMP_CLAUSE_PRIVATE);
18573 OMP_CLAUSE_DECL (c) = decl;
18574 c = finish_omp_clauses (c, C_ORT_OMP);
18575 if (c)
18577 OMP_CLAUSE_CHAIN (c) = *clauses;
18578 *clauses = c;
18582 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18583 if (COMPARISON_CLASS_P (cond))
18585 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18586 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18587 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18589 else
18590 cond = RECUR (cond);
18591 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18592 switch (TREE_CODE (incr))
18594 case PREINCREMENT_EXPR:
18595 case PREDECREMENT_EXPR:
18596 case POSTINCREMENT_EXPR:
18597 case POSTDECREMENT_EXPR:
18598 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18599 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18600 break;
18601 case MODIFY_EXPR:
18602 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18603 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18605 tree rhs = TREE_OPERAND (incr, 1);
18606 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18607 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18608 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18609 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18610 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18611 rhs0, rhs1));
18613 else
18614 incr = RECUR (incr);
18615 break;
18616 case MODOP_EXPR:
18617 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18618 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18620 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18621 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18622 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18623 TREE_TYPE (decl), lhs,
18624 RECUR (TREE_OPERAND (incr, 2))));
18626 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18627 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18628 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18630 tree rhs = TREE_OPERAND (incr, 2);
18631 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18632 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18633 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18634 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18635 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18636 rhs0, rhs1));
18638 else
18639 incr = RECUR (incr);
18640 break;
18641 default:
18642 incr = RECUR (incr);
18643 break;
18646 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18647 TREE_VEC_ELT (orig_declv, i) = decl;
18648 TREE_VEC_ELT (declv, i) = decl;
18649 TREE_VEC_ELT (initv, i) = init;
18650 TREE_VEC_ELT (condv, i) = cond;
18651 TREE_VEC_ELT (incrv, i) = incr;
18652 return false;
18653 #undef RECUR
18656 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18657 of OMP_TARGET's body. */
18659 static tree
18660 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18662 *walk_subtrees = 0;
18663 switch (TREE_CODE (*tp))
18665 case OMP_TEAMS:
18666 return *tp;
18667 case BIND_EXPR:
18668 case STATEMENT_LIST:
18669 *walk_subtrees = 1;
18670 break;
18671 default:
18672 break;
18674 return NULL_TREE;
18677 /* Helper function for tsubst_expr. For decomposition declaration
18678 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18679 also the corresponding decls representing the identifiers
18680 of the decomposition declaration. Return DECL if successful
18681 or error_mark_node otherwise, set *FIRST to the first decl
18682 in the list chained through DECL_CHAIN and *CNT to the number
18683 of such decls. */
18685 static tree
18686 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18687 tsubst_flags_t complain, tree in_decl, tree *first,
18688 unsigned int *cnt)
18690 tree decl2, decl3, prev = decl;
18691 *cnt = 0;
18692 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18693 for (decl2 = DECL_CHAIN (pattern_decl);
18694 decl2
18695 && VAR_P (decl2)
18696 && DECL_DECOMPOSITION_P (decl2)
18697 && DECL_NAME (decl2);
18698 decl2 = DECL_CHAIN (decl2))
18700 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18702 gcc_assert (errorcount);
18703 return error_mark_node;
18705 (*cnt)++;
18706 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18707 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18708 tree v = DECL_VALUE_EXPR (decl2);
18709 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18710 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18711 decl3 = tsubst (decl2, args, complain, in_decl);
18712 SET_DECL_VALUE_EXPR (decl2, v);
18713 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18714 if (VAR_P (decl3))
18715 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18716 else
18718 gcc_assert (errorcount);
18719 decl = error_mark_node;
18720 continue;
18722 maybe_push_decl (decl3);
18723 if (error_operand_p (decl3))
18724 decl = error_mark_node;
18725 else if (decl != error_mark_node
18726 && DECL_CHAIN (decl3) != prev
18727 && decl != prev)
18729 gcc_assert (errorcount);
18730 decl = error_mark_node;
18732 else
18733 prev = decl3;
18735 *first = prev;
18736 return decl;
18739 /* Return the proper local_specialization for init-capture pack DECL. */
18741 static tree
18742 lookup_init_capture_pack (tree decl)
18744 /* We handle normal pack captures by forwarding to the specialization of the
18745 captured parameter. We can't do that for pack init-captures; we need them
18746 to have their own local_specialization. We created the individual
18747 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18748 when we process the DECL_EXPR for the pack init-capture in the template.
18749 So, how do we find them? We don't know the capture proxy pack when
18750 building the individual resulting proxies, and we don't know the
18751 individual proxies when instantiating the pack. What we have in common is
18752 the FIELD_DECL.
18754 So...when we instantiate the FIELD_DECL, we stick the result in
18755 local_specializations. Then at the DECL_EXPR we look up that result, see
18756 how many elements it has, synthesize the names, and look them up. */
18758 tree cname = DECL_NAME (decl);
18759 tree val = DECL_VALUE_EXPR (decl);
18760 tree field = TREE_OPERAND (val, 1);
18761 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18762 tree fpack = retrieve_local_specialization (field);
18763 if (fpack == error_mark_node)
18764 return error_mark_node;
18766 int len = 1;
18767 tree vec = NULL_TREE;
18768 tree r = NULL_TREE;
18769 if (TREE_CODE (fpack) == TREE_VEC)
18771 len = TREE_VEC_LENGTH (fpack);
18772 vec = make_tree_vec (len);
18773 r = make_node (NONTYPE_ARGUMENT_PACK);
18774 ARGUMENT_PACK_ARGS (r) = vec;
18776 for (int i = 0; i < len; ++i)
18778 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18779 tree elt = lookup_name (ename);
18780 if (vec)
18781 TREE_VEC_ELT (vec, i) = elt;
18782 else
18783 r = elt;
18785 return r;
18788 /* T is an operand of a template tree being substituted. Return whether
18789 T is dependent such that we should suppress some warnings that would
18790 make sense if the substituted expression were written directly, like
18791 template <int I> bool f() { return I == 2; }
18792 We don't want to warn when instantiating f that comparing two constants
18793 always has the same value.
18795 This is a more limited concept of dependence than instantiation-dependent;
18796 here we don't care whether substitution could fail. */
18798 static bool
18799 dependent_operand_p (tree t)
18801 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18802 t = TREE_OPERAND (t, 0);
18803 ++processing_template_decl;
18804 bool r = (potential_constant_expression (t)
18805 ? value_dependent_expression_p (t)
18806 : type_dependent_expression_p (t));
18807 --processing_template_decl;
18808 return r;
18811 /* Like tsubst_copy for expressions, etc. but also does semantic
18812 processing. */
18814 tree
18815 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18817 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18818 #define RECUR(NODE) \
18819 tsubst_expr ((NODE), args, complain, in_decl)
18821 tree stmt, tmp;
18822 tree r;
18823 location_t loc;
18825 if (t == NULL_TREE || t == error_mark_node)
18826 return t;
18828 loc = input_location;
18829 if (location_t eloc = cp_expr_location (t))
18830 input_location = eloc;
18831 if (STATEMENT_CODE_P (TREE_CODE (t)))
18832 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18834 switch (TREE_CODE (t))
18836 case STATEMENT_LIST:
18838 for (tree stmt : tsi_range (t))
18839 RECUR (stmt);
18840 break;
18843 case CTOR_INITIALIZER:
18844 finish_mem_initializers (tsubst_initializer_list
18845 (TREE_OPERAND (t, 0), args));
18846 break;
18848 case RETURN_EXPR:
18849 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18850 break;
18852 case CO_RETURN_EXPR:
18853 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18854 break;
18856 case CO_YIELD_EXPR:
18857 stmt = finish_co_yield_expr (input_location,
18858 RECUR (TREE_OPERAND (t, 0)));
18859 RETURN (stmt);
18861 case CO_AWAIT_EXPR:
18862 stmt = finish_co_await_expr (input_location,
18863 RECUR (TREE_OPERAND (t, 0)));
18864 RETURN (stmt);
18866 case EXPR_STMT:
18867 tmp = RECUR (EXPR_STMT_EXPR (t));
18868 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18869 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18870 else
18871 finish_expr_stmt (tmp);
18872 break;
18874 case USING_STMT:
18875 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18876 break;
18878 case PRECONDITION_STMT:
18879 case POSTCONDITION_STMT:
18880 gcc_unreachable ();
18882 case ASSERTION_STMT:
18884 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18885 if (r != error_mark_node)
18886 add_stmt (r);
18887 RETURN (r);
18889 break;
18891 case DECL_EXPR:
18893 tree decl, pattern_decl;
18894 tree init;
18896 pattern_decl = decl = DECL_EXPR_DECL (t);
18897 if (TREE_CODE (decl) == LABEL_DECL)
18898 finish_label_decl (DECL_NAME (decl));
18899 else if (TREE_CODE (decl) == USING_DECL)
18901 tree scope = USING_DECL_SCOPE (decl);
18902 if (DECL_DEPENDENT_P (decl))
18904 scope = tsubst (scope, args, complain, in_decl);
18905 if (!MAYBE_CLASS_TYPE_P (scope)
18906 && TREE_CODE (scope) != ENUMERAL_TYPE)
18908 if (complain & tf_error)
18909 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18910 "class, namespace, or enumeration", scope);
18911 return error_mark_node;
18913 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18915 else
18917 /* This is a non-dependent using-decl, and we'll have
18918 used the names it found during template parsing. We do
18919 not want to do the lookup again, because we might not
18920 find the things we found then. */
18921 gcc_checking_assert (scope == tsubst (scope, args,
18922 complain, in_decl));
18923 /* We still need to push the bindings so that we can look up
18924 this name later. */
18925 push_using_decl_bindings (DECL_NAME (decl),
18926 USING_DECL_DECLS (decl));
18929 else if (is_capture_proxy (decl)
18930 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18932 /* We're in tsubst_lambda_expr, we've already inserted a new
18933 capture proxy, so look it up and register it. */
18934 tree inst;
18935 if (!DECL_PACK_P (decl))
18937 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18938 LOOK_want::HIDDEN_LAMBDA);
18939 gcc_assert (inst != decl && is_capture_proxy (inst));
18941 else if (is_normal_capture_proxy (decl))
18943 inst = (retrieve_local_specialization
18944 (DECL_CAPTURED_VARIABLE (decl)));
18945 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18946 || DECL_PACK_P (inst));
18948 else
18949 inst = lookup_init_capture_pack (decl);
18951 register_local_specialization (inst, decl);
18952 break;
18954 else if (DECL_PRETTY_FUNCTION_P (decl))
18955 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18956 DECL_NAME (decl),
18957 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18958 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18959 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18960 /* Don't copy the old closure; we'll create a new one in
18961 tsubst_lambda_expr. */
18962 break;
18963 else
18965 init = DECL_INITIAL (decl);
18966 decl = tsubst (decl, args, complain, in_decl);
18967 if (decl != error_mark_node)
18969 /* By marking the declaration as instantiated, we avoid
18970 trying to instantiate it. Since instantiate_decl can't
18971 handle local variables, and since we've already done
18972 all that needs to be done, that's the right thing to
18973 do. */
18974 if (VAR_P (decl))
18975 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18976 if (VAR_P (decl) && !DECL_NAME (decl)
18977 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18978 /* Anonymous aggregates are a special case. */
18979 finish_anon_union (decl);
18980 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18982 DECL_CONTEXT (decl) = current_function_decl;
18983 if (DECL_NAME (decl) == this_identifier)
18985 tree lam = DECL_CONTEXT (current_function_decl);
18986 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18987 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18989 insert_capture_proxy (decl);
18991 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18992 /* We already did a pushtag. */;
18993 else if (VAR_OR_FUNCTION_DECL_P (decl)
18994 && DECL_LOCAL_DECL_P (decl))
18996 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18997 DECL_CONTEXT (decl) = NULL_TREE;
18998 decl = pushdecl (decl);
18999 if (TREE_CODE (decl) == FUNCTION_DECL
19000 && DECL_OMP_DECLARE_REDUCTION_P (decl)
19001 && cp_check_omp_declare_reduction (decl))
19002 instantiate_body (pattern_decl, args, decl, true);
19004 else
19006 bool const_init = false;
19007 unsigned int cnt = 0;
19008 tree first = NULL_TREE, ndecl = error_mark_node;
19009 tree asmspec_tree = NULL_TREE;
19010 maybe_push_decl (decl);
19012 if (VAR_P (decl)
19013 && DECL_LANG_SPECIFIC (decl)
19014 && DECL_OMP_PRIVATIZED_MEMBER (decl))
19015 break;
19017 if (VAR_P (decl)
19018 && DECL_DECOMPOSITION_P (decl)
19019 && TREE_TYPE (pattern_decl) != error_mark_node)
19020 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
19021 complain, in_decl, &first,
19022 &cnt);
19024 init = tsubst_init (init, decl, args, complain, in_decl);
19026 if (VAR_P (decl))
19027 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
19028 (pattern_decl));
19030 if (ndecl != error_mark_node)
19031 cp_maybe_mangle_decomp (ndecl, first, cnt);
19033 /* In a non-template function, VLA type declarations are
19034 handled in grokdeclarator; for templates, handle them
19035 now. */
19036 predeclare_vla (decl);
19038 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
19040 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
19041 const char *asmspec = IDENTIFIER_POINTER (id);
19042 gcc_assert (asmspec[0] == '*');
19043 asmspec_tree
19044 = build_string (IDENTIFIER_LENGTH (id) - 1,
19045 asmspec + 1);
19046 TREE_TYPE (asmspec_tree) = char_array_type_node;
19049 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
19051 if (ndecl != error_mark_node)
19052 cp_finish_decomp (ndecl, first, cnt);
19057 break;
19060 case FOR_STMT:
19061 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
19062 RECUR (FOR_INIT_STMT (t));
19063 finish_init_stmt (stmt);
19064 tmp = RECUR (FOR_COND (t));
19065 finish_for_cond (tmp, stmt, false, 0);
19066 tmp = RECUR (FOR_EXPR (t));
19067 finish_for_expr (tmp, stmt);
19069 bool prev = note_iteration_stmt_body_start ();
19070 RECUR (FOR_BODY (t));
19071 note_iteration_stmt_body_end (prev);
19073 finish_for_stmt (stmt);
19074 break;
19076 case RANGE_FOR_STMT:
19078 /* Construct another range_for, if this is not a final
19079 substitution (for inside a generic lambda of a
19080 template). Otherwise convert to a regular for. */
19081 tree decl, expr;
19082 stmt = (processing_template_decl
19083 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
19084 : begin_for_stmt (NULL_TREE, NULL_TREE));
19085 RECUR (RANGE_FOR_INIT_STMT (t));
19086 decl = RANGE_FOR_DECL (t);
19087 decl = tsubst (decl, args, complain, in_decl);
19088 maybe_push_decl (decl);
19089 expr = RECUR (RANGE_FOR_EXPR (t));
19091 tree decomp_first = NULL_TREE;
19092 unsigned decomp_cnt = 0;
19093 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
19094 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
19095 complain, in_decl,
19096 &decomp_first, &decomp_cnt);
19098 if (processing_template_decl)
19100 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
19101 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
19102 finish_range_for_decl (stmt, decl, expr);
19103 if (decomp_first && decl != error_mark_node)
19104 cp_finish_decomp (decl, decomp_first, decomp_cnt);
19106 else
19108 unsigned short unroll = (RANGE_FOR_UNROLL (t)
19109 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
19110 stmt = cp_convert_range_for (stmt, decl, expr,
19111 decomp_first, decomp_cnt,
19112 RANGE_FOR_IVDEP (t), unroll);
19115 bool prev = note_iteration_stmt_body_start ();
19116 RECUR (RANGE_FOR_BODY (t));
19117 note_iteration_stmt_body_end (prev);
19118 finish_for_stmt (stmt);
19120 break;
19122 case WHILE_STMT:
19123 stmt = begin_while_stmt ();
19124 tmp = RECUR (WHILE_COND (t));
19125 finish_while_stmt_cond (tmp, stmt, false, 0);
19127 bool prev = note_iteration_stmt_body_start ();
19128 RECUR (WHILE_BODY (t));
19129 note_iteration_stmt_body_end (prev);
19131 finish_while_stmt (stmt);
19132 break;
19134 case DO_STMT:
19135 stmt = begin_do_stmt ();
19137 bool prev = note_iteration_stmt_body_start ();
19138 RECUR (DO_BODY (t));
19139 note_iteration_stmt_body_end (prev);
19141 finish_do_body (stmt);
19142 tmp = RECUR (DO_COND (t));
19143 finish_do_stmt (tmp, stmt, false, 0);
19144 break;
19146 case IF_STMT:
19147 stmt = begin_if_stmt ();
19148 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
19149 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
19150 if (IF_STMT_CONSTEXPR_P (t))
19151 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
19153 tree cond = IF_COND (t);
19154 bool was_dep = dependent_operand_p (cond);
19155 cond = RECUR (cond);
19156 warning_sentinel s1(warn_address, was_dep);
19157 tmp = finish_if_stmt_cond (cond, stmt);
19159 if (IF_STMT_CONSTEXPR_P (t)
19160 && instantiation_dependent_expression_p (tmp))
19162 /* We're partially instantiating a generic lambda, but the condition
19163 of the constexpr if is still dependent. Don't substitute into the
19164 branches now, just remember the template arguments. */
19165 do_poplevel (IF_SCOPE (stmt));
19166 IF_COND (stmt) = IF_COND (t);
19167 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
19168 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
19169 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
19170 add_stmt (stmt);
19171 break;
19173 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
19174 /* Don't instantiate the THEN_CLAUSE. */;
19175 else if (IF_STMT_CONSTEVAL_P (t))
19177 bool save_in_consteval_if_p = in_consteval_if_p;
19178 in_consteval_if_p = true;
19179 RECUR (THEN_CLAUSE (t));
19180 in_consteval_if_p = save_in_consteval_if_p;
19182 else
19184 tree folded = fold_non_dependent_expr (tmp, complain);
19185 bool inhibit = integer_zerop (folded);
19186 if (inhibit)
19187 ++c_inhibit_evaluation_warnings;
19188 RECUR (THEN_CLAUSE (t));
19189 if (inhibit)
19190 --c_inhibit_evaluation_warnings;
19192 finish_then_clause (stmt);
19194 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19195 /* Don't instantiate the ELSE_CLAUSE. */;
19196 else if (ELSE_CLAUSE (t))
19198 tree folded = fold_non_dependent_expr (tmp, complain);
19199 bool inhibit = integer_nonzerop (folded);
19200 begin_else_clause (stmt);
19201 if (inhibit)
19202 ++c_inhibit_evaluation_warnings;
19203 RECUR (ELSE_CLAUSE (t));
19204 if (inhibit)
19205 --c_inhibit_evaluation_warnings;
19206 finish_else_clause (stmt);
19209 finish_if_stmt (stmt);
19210 break;
19212 case BIND_EXPR:
19213 if (BIND_EXPR_BODY_BLOCK (t))
19214 stmt = begin_function_body ();
19215 else
19216 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19217 ? BCS_TRY_BLOCK : 0);
19219 RECUR (BIND_EXPR_BODY (t));
19221 if (BIND_EXPR_BODY_BLOCK (t))
19222 finish_function_body (stmt);
19223 else
19224 finish_compound_stmt (stmt);
19225 break;
19227 case BREAK_STMT:
19228 finish_break_stmt ();
19229 break;
19231 case CONTINUE_STMT:
19232 finish_continue_stmt ();
19233 break;
19235 case SWITCH_STMT:
19236 stmt = begin_switch_stmt ();
19237 tmp = RECUR (SWITCH_STMT_COND (t));
19238 finish_switch_cond (tmp, stmt);
19239 RECUR (SWITCH_STMT_BODY (t));
19240 finish_switch_stmt (stmt);
19241 break;
19243 case CASE_LABEL_EXPR:
19245 tree decl = CASE_LABEL (t);
19246 tree low = RECUR (CASE_LOW (t));
19247 tree high = RECUR (CASE_HIGH (t));
19248 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19249 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19251 tree label = CASE_LABEL (l);
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);
19257 break;
19259 case LABEL_EXPR:
19261 tree decl = LABEL_EXPR_LABEL (t);
19262 tree label;
19264 label = finish_label_stmt (DECL_NAME (decl));
19265 if (TREE_CODE (label) == LABEL_DECL)
19266 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19267 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19268 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19270 break;
19272 case GOTO_EXPR:
19273 tmp = GOTO_DESTINATION (t);
19274 if (TREE_CODE (tmp) != LABEL_DECL)
19275 /* Computed goto's must be tsubst'd into. On the other hand,
19276 non-computed gotos must not be; the identifier in question
19277 will have no binding. */
19278 tmp = RECUR (tmp);
19279 else
19280 tmp = DECL_NAME (tmp);
19281 finish_goto_stmt (tmp);
19282 break;
19284 case ASM_EXPR:
19286 tree string = RECUR (ASM_STRING (t));
19287 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19288 complain, in_decl);
19289 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19290 complain, in_decl);
19291 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19292 complain, in_decl);
19293 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19294 complain, in_decl);
19295 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19296 outputs, inputs, clobbers, labels,
19297 ASM_INLINE_P (t));
19298 tree asm_expr = tmp;
19299 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19300 asm_expr = TREE_OPERAND (asm_expr, 0);
19301 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19303 break;
19305 case TRY_BLOCK:
19306 if (CLEANUP_P (t))
19308 stmt = begin_try_block ();
19309 RECUR (TRY_STMTS (t));
19310 finish_cleanup_try_block (stmt);
19311 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19313 else
19315 tree compound_stmt = NULL_TREE;
19317 if (FN_TRY_BLOCK_P (t))
19318 stmt = begin_function_try_block (&compound_stmt);
19319 else
19320 stmt = begin_try_block ();
19322 RECUR (TRY_STMTS (t));
19324 if (FN_TRY_BLOCK_P (t))
19325 finish_function_try_block (stmt);
19326 else
19327 finish_try_block (stmt);
19329 RECUR (TRY_HANDLERS (t));
19330 if (FN_TRY_BLOCK_P (t))
19331 finish_function_handler_sequence (stmt, compound_stmt);
19332 else
19333 finish_handler_sequence (stmt);
19335 break;
19337 case HANDLER:
19339 tree decl = HANDLER_PARMS (t);
19341 if (decl)
19343 decl = tsubst (decl, args, complain, in_decl);
19344 /* Prevent instantiate_decl from trying to instantiate
19345 this variable. We've already done all that needs to be
19346 done. */
19347 if (decl != error_mark_node)
19348 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19350 stmt = begin_handler ();
19351 finish_handler_parms (decl, stmt);
19352 RECUR (HANDLER_BODY (t));
19353 finish_handler (stmt);
19355 break;
19357 case TAG_DEFN:
19358 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19359 if (CLASS_TYPE_P (tmp))
19361 /* Local classes are not independent templates; they are
19362 instantiated along with their containing function. And this
19363 way we don't have to deal with pushing out of one local class
19364 to instantiate a member of another local class. */
19365 /* Closures are handled by the LAMBDA_EXPR. */
19366 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19367 complete_type (tmp);
19368 if (dependent_type_p (tmp))
19370 /* This is a partial instantiation, try again when full. */
19371 add_stmt (build_min (TAG_DEFN, tmp));
19372 break;
19374 tree save_ccp = current_class_ptr;
19375 tree save_ccr = current_class_ref;
19376 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19377 if ((VAR_P (fld)
19378 || (TREE_CODE (fld) == FUNCTION_DECL
19379 && !DECL_ARTIFICIAL (fld)))
19380 && DECL_TEMPLATE_INSTANTIATION (fld))
19381 instantiate_decl (fld, /*defer_ok=*/false,
19382 /*expl_inst_class=*/false);
19383 else if (TREE_CODE (fld) == FIELD_DECL)
19384 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19385 current_class_ptr = save_ccp;
19386 current_class_ref = save_ccr;
19388 break;
19390 case STATIC_ASSERT:
19392 tree condition;
19394 ++c_inhibit_evaluation_warnings;
19395 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19396 complain, in_decl);
19397 --c_inhibit_evaluation_warnings;
19399 finish_static_assert (condition,
19400 STATIC_ASSERT_MESSAGE (t),
19401 STATIC_ASSERT_SOURCE_LOCATION (t),
19402 /*member_p=*/false, /*show_expr_p=*/true);
19404 break;
19406 case OACC_KERNELS:
19407 case OACC_PARALLEL:
19408 case OACC_SERIAL:
19409 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19410 in_decl);
19411 stmt = begin_omp_parallel ();
19412 RECUR (OMP_BODY (t));
19413 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19414 break;
19416 case OMP_PARALLEL:
19417 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19418 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19419 complain, in_decl);
19420 if (OMP_PARALLEL_COMBINED (t))
19421 omp_parallel_combined_clauses = &tmp;
19422 stmt = begin_omp_parallel ();
19423 RECUR (OMP_PARALLEL_BODY (t));
19424 gcc_assert (omp_parallel_combined_clauses == NULL);
19425 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19426 = OMP_PARALLEL_COMBINED (t);
19427 pop_omp_privatization_clauses (r);
19428 break;
19430 case OMP_TASK:
19431 if (OMP_TASK_BODY (t) == NULL_TREE)
19433 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19434 complain, in_decl);
19435 t = copy_node (t);
19436 OMP_TASK_CLAUSES (t) = tmp;
19437 add_stmt (t);
19438 break;
19440 r = push_omp_privatization_clauses (false);
19441 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19442 complain, in_decl);
19443 stmt = begin_omp_task ();
19444 RECUR (OMP_TASK_BODY (t));
19445 finish_omp_task (tmp, stmt);
19446 pop_omp_privatization_clauses (r);
19447 break;
19449 case OMP_FOR:
19450 case OMP_LOOP:
19451 case OMP_SIMD:
19452 case OMP_DISTRIBUTE:
19453 case OMP_TASKLOOP:
19454 case OACC_LOOP:
19456 tree clauses, body, pre_body;
19457 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19458 tree orig_declv = NULL_TREE;
19459 tree incrv = NULL_TREE;
19460 enum c_omp_region_type ort = C_ORT_OMP;
19461 bool any_range_for = false;
19462 int i;
19464 if (TREE_CODE (t) == OACC_LOOP)
19465 ort = C_ORT_ACC;
19467 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19468 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19469 in_decl);
19470 if (OMP_FOR_INIT (t) != NULL_TREE)
19472 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19473 if (OMP_FOR_ORIG_DECLS (t))
19474 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19475 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19476 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19477 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19480 keep_next_level (true);
19481 stmt = begin_omp_structured_block ();
19483 pre_body = push_stmt_list ();
19484 RECUR (OMP_FOR_PRE_BODY (t));
19485 pre_body = pop_stmt_list (pre_body);
19487 if (OMP_FOR_INIT (t) != NULL_TREE)
19488 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19489 any_range_for
19490 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19491 condv, incrv, &clauses, args,
19492 complain, in_decl);
19493 omp_parallel_combined_clauses = NULL;
19495 if (any_range_for)
19497 gcc_assert (orig_declv);
19498 body = begin_omp_structured_block ();
19499 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19500 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19501 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19502 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19503 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19504 TREE_VEC_ELT (declv, i));
19506 else
19507 body = push_stmt_list ();
19508 RECUR (OMP_FOR_BODY (t));
19509 if (any_range_for)
19510 body = finish_omp_structured_block (body);
19511 else
19512 body = pop_stmt_list (body);
19514 if (OMP_FOR_INIT (t) != NULL_TREE)
19515 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19516 orig_declv, initv, condv, incrv, body, pre_body,
19517 NULL, clauses);
19518 else
19520 t = make_node (TREE_CODE (t));
19521 TREE_TYPE (t) = void_type_node;
19522 OMP_FOR_BODY (t) = body;
19523 OMP_FOR_PRE_BODY (t) = pre_body;
19524 OMP_FOR_CLAUSES (t) = clauses;
19525 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19526 add_stmt (t);
19529 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19530 t));
19531 pop_omp_privatization_clauses (r);
19533 break;
19535 case OMP_SECTIONS:
19536 case OMP_MASKED:
19537 omp_parallel_combined_clauses = NULL;
19538 /* FALLTHRU */
19539 case OMP_SINGLE:
19540 case OMP_SCOPE:
19541 case OMP_TEAMS:
19542 case OMP_CRITICAL:
19543 case OMP_TASKGROUP:
19544 case OMP_SCAN:
19545 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19546 && OMP_TEAMS_COMBINED (t));
19547 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19548 in_decl);
19549 if (TREE_CODE (t) == OMP_TEAMS)
19551 keep_next_level (true);
19552 stmt = begin_omp_structured_block ();
19553 RECUR (OMP_BODY (t));
19554 stmt = finish_omp_structured_block (stmt);
19556 else
19558 stmt = push_stmt_list ();
19559 RECUR (OMP_BODY (t));
19560 stmt = pop_stmt_list (stmt);
19563 if (TREE_CODE (t) == OMP_CRITICAL
19564 && tmp != NULL_TREE
19565 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19567 error_at (OMP_CLAUSE_LOCATION (tmp),
19568 "%<#pragma omp critical%> with %<hint%> clause requires "
19569 "a name, except when %<omp_sync_hint_none%> is used");
19570 RETURN (error_mark_node);
19572 t = copy_node (t);
19573 OMP_BODY (t) = stmt;
19574 OMP_CLAUSES (t) = tmp;
19575 add_stmt (t);
19576 pop_omp_privatization_clauses (r);
19577 break;
19579 case OMP_DEPOBJ:
19580 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19581 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19583 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19584 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19586 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19587 args, complain, in_decl);
19588 if (tmp == NULL_TREE)
19589 tmp = error_mark_node;
19591 else
19593 kind = (enum omp_clause_depend_kind)
19594 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19595 tmp = NULL_TREE;
19597 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19599 else
19600 finish_omp_depobj (EXPR_LOCATION (t), r,
19601 OMP_CLAUSE_DEPEND_INVALID,
19602 OMP_DEPOBJ_CLAUSES (t));
19603 break;
19605 case OACC_DATA:
19606 case OMP_TARGET_DATA:
19607 case OMP_TARGET:
19608 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19609 TREE_CODE (t) == OACC_DATA
19610 ? C_ORT_ACC
19611 : TREE_CODE (t) == OMP_TARGET
19612 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19613 args, complain, in_decl);
19614 keep_next_level (true);
19615 stmt = begin_omp_structured_block ();
19617 RECUR (OMP_BODY (t));
19618 stmt = finish_omp_structured_block (stmt);
19620 t = copy_node (t);
19621 OMP_BODY (t) = stmt;
19622 OMP_CLAUSES (t) = tmp;
19624 if (TREE_CODE (t) == OMP_TARGET)
19625 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19626 &OMP_CLAUSES (t));
19628 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19630 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19631 if (teams)
19632 /* For combined target teams, ensure the num_teams and
19633 thread_limit clause expressions are evaluated on the host,
19634 before entering the target construct. */
19635 for (tree c = OMP_TEAMS_CLAUSES (teams);
19636 c; c = OMP_CLAUSE_CHAIN (c))
19637 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19638 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19639 for (int i = 0;
19640 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19641 if (OMP_CLAUSE_OPERAND (c, i)
19642 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19644 tree expr = OMP_CLAUSE_OPERAND (c, i);
19645 expr = force_target_expr (TREE_TYPE (expr), expr,
19646 tf_none);
19647 if (expr == error_mark_node)
19648 continue;
19649 tmp = TARGET_EXPR_SLOT (expr);
19650 add_stmt (expr);
19651 OMP_CLAUSE_OPERAND (c, i) = expr;
19652 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19653 OMP_CLAUSE_FIRSTPRIVATE);
19654 OMP_CLAUSE_DECL (tc) = tmp;
19655 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19656 OMP_TARGET_CLAUSES (t) = tc;
19659 add_stmt (t);
19660 break;
19662 case OACC_DECLARE:
19663 t = copy_node (t);
19664 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19665 complain, in_decl);
19666 OACC_DECLARE_CLAUSES (t) = tmp;
19667 add_stmt (t);
19668 break;
19670 case OMP_TARGET_UPDATE:
19671 case OMP_TARGET_ENTER_DATA:
19672 case OMP_TARGET_EXIT_DATA:
19673 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19674 complain, in_decl);
19675 t = copy_node (t);
19676 OMP_STANDALONE_CLAUSES (t) = tmp;
19677 add_stmt (t);
19678 break;
19680 case OACC_CACHE:
19681 case OACC_ENTER_DATA:
19682 case OACC_EXIT_DATA:
19683 case OACC_UPDATE:
19684 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19685 complain, in_decl);
19686 t = copy_node (t);
19687 OMP_STANDALONE_CLAUSES (t) = tmp;
19688 add_stmt (t);
19689 break;
19691 case OMP_ORDERED:
19692 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19693 complain, in_decl);
19694 if (OMP_BODY (t))
19696 stmt = push_stmt_list ();
19697 RECUR (OMP_BODY (t));
19698 stmt = pop_stmt_list (stmt);
19700 else
19701 stmt = NULL_TREE;
19703 t = copy_node (t);
19704 OMP_BODY (t) = stmt;
19705 OMP_ORDERED_CLAUSES (t) = tmp;
19706 add_stmt (t);
19707 break;
19709 case OMP_MASTER:
19710 omp_parallel_combined_clauses = NULL;
19711 /* FALLTHRU */
19712 case OMP_SECTION:
19713 stmt = push_stmt_list ();
19714 RECUR (OMP_BODY (t));
19715 stmt = pop_stmt_list (stmt);
19717 t = copy_node (t);
19718 OMP_BODY (t) = stmt;
19719 add_stmt (t);
19720 break;
19722 case OMP_ATOMIC:
19723 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19724 tmp = NULL_TREE;
19725 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19726 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19727 complain, in_decl);
19728 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19730 tree op1 = TREE_OPERAND (t, 1);
19731 tree rhs1 = NULL_TREE;
19732 tree r = NULL_TREE;
19733 tree lhs, rhs;
19734 if (TREE_CODE (op1) == COMPOUND_EXPR)
19736 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19737 op1 = TREE_OPERAND (op1, 1);
19739 if (TREE_CODE (op1) == COND_EXPR)
19741 gcc_assert (rhs1 == NULL_TREE);
19742 tree c = TREE_OPERAND (op1, 0);
19743 if (TREE_CODE (c) == MODIFY_EXPR)
19745 r = RECUR (TREE_OPERAND (c, 0));
19746 c = TREE_OPERAND (c, 1);
19748 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19749 rhs = RECUR (TREE_OPERAND (c, 1));
19750 lhs = RECUR (TREE_OPERAND (op1, 2));
19751 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19753 else
19755 lhs = RECUR (TREE_OPERAND (op1, 0));
19756 rhs = RECUR (TREE_OPERAND (op1, 1));
19758 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19759 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19760 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19761 OMP_ATOMIC_WEAK (t));
19763 else
19765 tree op1 = TREE_OPERAND (t, 1);
19766 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19767 tree rhs1 = NULL_TREE, r = NULL_TREE;
19768 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19769 enum tree_code opcode = NOP_EXPR;
19770 if (code == OMP_ATOMIC_READ)
19772 v = RECUR (TREE_OPERAND (op1, 0));
19773 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19775 else if (code == OMP_ATOMIC_CAPTURE_OLD
19776 || code == OMP_ATOMIC_CAPTURE_NEW)
19778 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19779 v = RECUR (TREE_OPERAND (op1, 0));
19780 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19781 if (TREE_CODE (op11) == COMPOUND_EXPR)
19783 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19784 op11 = TREE_OPERAND (op11, 1);
19786 if (TREE_CODE (op11) == COND_EXPR)
19788 gcc_assert (rhs1 == NULL_TREE);
19789 tree c = TREE_OPERAND (op11, 0);
19790 if (TREE_CODE (c) == MODIFY_EXPR)
19792 r = RECUR (TREE_OPERAND (c, 0));
19793 c = TREE_OPERAND (c, 1);
19795 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19796 rhs = RECUR (TREE_OPERAND (c, 1));
19797 lhs = RECUR (TREE_OPERAND (op11, 2));
19798 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19800 else
19802 lhs = RECUR (TREE_OPERAND (op11, 0));
19803 rhs = RECUR (TREE_OPERAND (op11, 1));
19805 opcode = TREE_CODE (op11);
19806 if (opcode == MODIFY_EXPR)
19807 opcode = NOP_EXPR;
19809 else
19811 code = OMP_ATOMIC;
19812 lhs = RECUR (TREE_OPERAND (op1, 0));
19813 rhs = RECUR (TREE_OPERAND (op1, 1));
19815 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19816 lhs1, rhs1, r, tmp,
19817 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19819 break;
19821 case TRANSACTION_EXPR:
19823 int flags = 0;
19824 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19825 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19827 if (TRANSACTION_EXPR_IS_STMT (t))
19829 tree body = TRANSACTION_EXPR_BODY (t);
19830 tree noex = NULL_TREE;
19831 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19833 noex = MUST_NOT_THROW_COND (body);
19834 if (noex == NULL_TREE)
19835 noex = boolean_true_node;
19836 body = TREE_OPERAND (body, 0);
19838 stmt = begin_transaction_stmt (input_location, NULL, flags);
19839 RECUR (body);
19840 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19842 else
19844 stmt = build_transaction_expr (EXPR_LOCATION (t),
19845 RECUR (TRANSACTION_EXPR_BODY (t)),
19846 flags, NULL_TREE);
19847 RETURN (stmt);
19850 break;
19852 case MUST_NOT_THROW_EXPR:
19854 tree op0 = RECUR (TREE_OPERAND (t, 0));
19855 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19856 RETURN (build_must_not_throw_expr (op0, cond));
19859 case EXPR_PACK_EXPANSION:
19860 error ("invalid use of pack expansion expression");
19861 RETURN (error_mark_node);
19863 case NONTYPE_ARGUMENT_PACK:
19864 error ("use %<...%> to expand argument pack");
19865 RETURN (error_mark_node);
19867 case COMPOUND_EXPR:
19868 tmp = RECUR (TREE_OPERAND (t, 0));
19869 if (tmp == NULL_TREE)
19870 /* If the first operand was a statement, we're done with it. */
19871 RETURN (RECUR (TREE_OPERAND (t, 1)));
19872 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19873 RECUR (TREE_OPERAND (t, 1)),
19874 templated_operator_saved_lookups (t),
19875 complain));
19877 case ANNOTATE_EXPR:
19878 tmp = RECUR (TREE_OPERAND (t, 0));
19879 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19880 TREE_TYPE (tmp), tmp,
19881 RECUR (TREE_OPERAND (t, 1)),
19882 RECUR (TREE_OPERAND (t, 2))));
19884 case PREDICT_EXPR:
19885 RETURN (add_stmt (copy_node (t)));
19887 default:
19888 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19890 RETURN (tsubst_copy_and_build (t, args, complain, in_decl));
19893 RETURN (NULL_TREE);
19894 out:
19895 input_location = loc;
19896 return r;
19897 #undef RECUR
19898 #undef RETURN
19901 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19902 function. For description of the body see comment above
19903 cp_parser_omp_declare_reduction_exprs. */
19905 static void
19906 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19908 if (t == NULL_TREE || t == error_mark_node)
19909 return;
19911 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19913 tree_stmt_iterator tsi;
19914 int i;
19915 tree stmts[7];
19916 memset (stmts, 0, sizeof stmts);
19917 for (i = 0, tsi = tsi_start (t);
19918 i < 7 && !tsi_end_p (tsi);
19919 i++, tsi_next (&tsi))
19920 stmts[i] = tsi_stmt (tsi);
19921 gcc_assert (tsi_end_p (tsi));
19923 if (i >= 3)
19925 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19926 && TREE_CODE (stmts[1]) == DECL_EXPR);
19927 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19928 args, complain, in_decl);
19929 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19930 args, complain, in_decl);
19931 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19932 expect to be pushing it. */
19933 DECL_CONTEXT (omp_out) = current_function_decl;
19934 DECL_CONTEXT (omp_in) = current_function_decl;
19935 keep_next_level (true);
19936 tree block = begin_omp_structured_block ();
19937 tsubst_expr (stmts[2], args, complain, in_decl);
19938 block = finish_omp_structured_block (block);
19939 block = maybe_cleanup_point_expr_void (block);
19940 add_decl_expr (omp_out);
19941 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19942 add_decl_expr (omp_in);
19943 finish_expr_stmt (block);
19945 if (i >= 6)
19947 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19948 && TREE_CODE (stmts[4]) == DECL_EXPR);
19949 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19950 args, complain, in_decl);
19951 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19952 args, complain, in_decl);
19953 DECL_CONTEXT (omp_priv) = current_function_decl;
19954 DECL_CONTEXT (omp_orig) = current_function_decl;
19955 keep_next_level (true);
19956 tree block = begin_omp_structured_block ();
19957 tsubst_expr (stmts[5], args, complain, in_decl);
19958 block = finish_omp_structured_block (block);
19959 block = maybe_cleanup_point_expr_void (block);
19960 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19961 add_decl_expr (omp_priv);
19962 add_decl_expr (omp_orig);
19963 finish_expr_stmt (block);
19964 if (i == 7)
19965 add_decl_expr (omp_orig);
19969 /* T is a postfix-expression that is not being used in a function
19970 call. Return the substituted version of T. */
19972 static tree
19973 tsubst_non_call_postfix_expression (tree t, tree args,
19974 tsubst_flags_t complain,
19975 tree in_decl)
19977 if (TREE_CODE (t) == SCOPE_REF)
19978 t = tsubst_qualified_id (t, args, complain, in_decl,
19979 /*done=*/false, /*address_p=*/false);
19980 else
19981 t = tsubst_copy_and_build (t, args, complain, in_decl);
19983 return t;
19986 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19987 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19988 dependent init-capture. EXPLICIT_P is true if the original list had
19989 explicit captures. */
19991 static void
19992 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19993 tsubst_flags_t complain)
19995 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19997 tree type = NULL_TREE;
19998 if (!init)
20000 if (complain & tf_error)
20001 error ("empty initializer in lambda init-capture");
20002 init = error_mark_node;
20004 else if (TREE_CODE (init) == TREE_LIST)
20005 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20006 if (!type)
20007 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
20008 TREE_TYPE (field) = type;
20009 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
20011 list = tree_cons (field, init, list);
20012 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
20015 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
20016 instantiation context. Instantiating a pack expansion containing a lambda
20017 might result in multiple lambdas all based on the same lambda in the
20018 template. */
20020 tree
20021 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
20023 tree oldfn = lambda_function (t);
20024 in_decl = oldfn;
20026 tree r = build_lambda_expr ();
20028 LAMBDA_EXPR_LOCATION (r)
20029 = LAMBDA_EXPR_LOCATION (t);
20030 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
20031 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
20032 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
20033 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
20034 LAMBDA_EXPR_REGEN_INFO (r)
20035 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
20036 preserve_args (args)));
20037 else
20038 LAMBDA_EXPR_REGEN_INFO (r)
20039 = build_template_info (t, preserve_args (args));
20041 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
20042 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
20044 vec<tree,va_gc>* field_packs = NULL;
20046 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
20047 cap = TREE_CHAIN (cap))
20049 tree ofield = TREE_PURPOSE (cap);
20050 tree init = TREE_VALUE (cap);
20051 if (PACK_EXPANSION_P (init))
20052 init = tsubst_pack_expansion (init, args, complain, in_decl);
20053 else
20054 init = tsubst_copy_and_build (init, args, complain, in_decl);
20056 if (init == error_mark_node)
20057 return error_mark_node;
20059 if (init && TREE_CODE (init) == TREE_LIST)
20060 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20062 if (!processing_template_decl
20063 && init && TREE_CODE (init) != TREE_VEC
20064 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
20066 /* For a VLA, simply tsubsting the field type won't work, we need to
20067 go through add_capture again. XXX do we want to do this for all
20068 captures? */
20069 tree name = (get_identifier
20070 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
20071 tree ftype = TREE_TYPE (ofield);
20072 bool by_ref = (TYPE_REF_P (ftype)
20073 || (TREE_CODE (ftype) == DECLTYPE_TYPE
20074 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
20075 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
20076 continue;
20079 if (PACK_EXPANSION_P (ofield))
20080 ofield = PACK_EXPANSION_PATTERN (ofield);
20081 tree field = tsubst_decl (ofield, args, complain);
20083 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
20085 /* Remember these for when we've pushed local_specializations. */
20086 vec_safe_push (field_packs, ofield);
20087 vec_safe_push (field_packs, field);
20090 if (field == error_mark_node)
20091 return error_mark_node;
20093 if (TREE_CODE (field) == TREE_VEC)
20095 int len = TREE_VEC_LENGTH (field);
20096 gcc_assert (TREE_CODE (init) == TREE_VEC
20097 && TREE_VEC_LENGTH (init) == len);
20098 for (int i = 0; i < len; ++i)
20099 prepend_one_capture (TREE_VEC_ELT (field, i),
20100 TREE_VEC_ELT (init, i),
20101 LAMBDA_EXPR_CAPTURE_LIST (r),
20102 LAMBDA_CAPTURE_EXPLICIT_P (cap),
20103 complain);
20105 else
20107 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
20108 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
20110 if (id_equal (DECL_NAME (field), "__this"))
20111 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
20115 tree type = begin_lambda_type (r);
20116 if (type == error_mark_node)
20117 return error_mark_node;
20119 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
20120 record_lambda_scope (r);
20121 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
20122 /* If we're pushed into another scope (PR105652), fix it. */
20123 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
20124 = TYPE_CONTEXT (TREE_TYPE (t));
20125 record_lambda_scope_discriminator (r);
20127 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
20128 determine_visibility (TYPE_NAME (type));
20130 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
20132 tree oldtmpl = (generic_lambda_fn_p (oldfn)
20133 ? DECL_TI_TEMPLATE (oldfn)
20134 : NULL_TREE);
20136 tree tparms = NULL_TREE;
20137 if (oldtmpl)
20138 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
20140 tree fntype = static_fn_type (oldfn);
20142 tree saved_ctp = current_template_parms;
20143 if (oldtmpl)
20145 ++processing_template_decl;
20146 current_template_parms = tparms;
20148 fntype = tsubst (fntype, args, complain, in_decl);
20149 if (oldtmpl)
20151 current_template_parms = saved_ctp;
20152 --processing_template_decl;
20155 if (fntype == error_mark_node)
20156 r = error_mark_node;
20157 else
20159 /* The body of a lambda-expression is not a subexpression of the
20160 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
20161 which would be skipped if cp_unevaluated_operand. */
20162 cp_evaluated ev;
20164 /* Fix the type of 'this'. */
20165 fntype = build_memfn_type (fntype, type,
20166 type_memfn_quals (fntype),
20167 type_memfn_rqual (fntype));
20168 tree inst = (oldtmpl
20169 ? tsubst_template_decl (oldtmpl, args, complain,
20170 fntype, tparms)
20171 : tsubst_function_decl (oldfn, args, complain, fntype));
20172 if (inst == error_mark_node)
20174 r = error_mark_node;
20175 goto out;
20177 finish_member_declaration (inst);
20178 record_lambda_scope_sig_discriminator (r, inst);
20180 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
20182 /* Let finish_function set this. */
20183 DECL_DECLARED_CONSTEXPR_P (fn) = false;
20185 bool nested = cfun;
20186 if (nested)
20187 push_function_context ();
20188 else
20189 /* Still increment function_depth so that we don't GC in the
20190 middle of an expression. */
20191 ++function_depth;
20193 local_specialization_stack s (lss_copy);
20195 bool save_in_consteval_if_p = in_consteval_if_p;
20196 in_consteval_if_p = false;
20198 tree body = start_lambda_function (fn, r);
20200 /* Now record them for lookup_init_capture_pack. */
20201 int fplen = vec_safe_length (field_packs);
20202 for (int i = 0; i < fplen; )
20204 tree pack = (*field_packs)[i++];
20205 tree inst = (*field_packs)[i++];
20206 register_local_specialization (inst, pack);
20208 release_tree_vector (field_packs);
20210 register_parameter_specializations (oldfn, fn);
20212 if (oldtmpl)
20214 /* We might not partially instantiate some parts of the function, so
20215 copy these flags from the original template. */
20216 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20217 current_function_returns_value = ol->returns_value;
20218 current_function_returns_null = ol->returns_null;
20219 current_function_returns_abnormally = ol->returns_abnormally;
20220 current_function_infinite_loop = ol->infinite_loop;
20223 /* [temp.deduct] A lambda-expression appearing in a function type or a
20224 template parameter is not considered part of the immediate context for
20225 the purposes of template argument deduction. */
20226 complain = tf_warning_or_error;
20228 tree saved = DECL_SAVED_TREE (oldfn);
20229 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20230 /* We already have a body block from start_lambda_function, we don't
20231 need another to confuse NRV (91217). */
20232 saved = BIND_EXPR_BODY (saved);
20234 tsubst_expr (saved, args, complain, r);
20236 finish_lambda_function (body);
20238 in_consteval_if_p = save_in_consteval_if_p;
20240 if (nested)
20241 pop_function_context ();
20242 else
20243 --function_depth;
20245 /* The capture list was built up in reverse order; fix that now. */
20246 LAMBDA_EXPR_CAPTURE_LIST (r)
20247 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20249 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20251 maybe_add_lambda_conv_op (type);
20254 out:
20255 finish_struct (type, /*attr*/NULL_TREE);
20257 insert_pending_capture_proxies ();
20259 return r;
20262 /* Subroutine of maybe_fold_fn_template_args. */
20264 static bool
20265 fold_targs_r (tree targs, tsubst_flags_t complain)
20267 int len = TREE_VEC_LENGTH (targs);
20268 for (int i = 0; i < len; ++i)
20270 tree &elt = TREE_VEC_ELT (targs, i);
20271 if (!elt || TYPE_P (elt)
20272 || TREE_CODE (elt) == TEMPLATE_DECL)
20273 continue;
20274 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20276 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20277 return false;
20279 else if (/* We can only safely preevaluate scalar prvalues. */
20280 SCALAR_TYPE_P (TREE_TYPE (elt))
20281 && !glvalue_p (elt)
20282 && !TREE_CONSTANT (elt))
20284 elt = cxx_constant_value (elt, complain);
20285 if (elt == error_mark_node)
20286 return false;
20290 return true;
20293 /* Try to do constant evaluation of any explicit template arguments in FN
20294 before overload resolution, to get any errors only once. Return true iff
20295 we didn't have any problems folding. */
20297 static bool
20298 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20300 if (processing_template_decl || fn == NULL_TREE)
20301 return true;
20302 if (fn == error_mark_node)
20303 return false;
20304 if (TREE_CODE (fn) == OFFSET_REF
20305 || TREE_CODE (fn) == COMPONENT_REF)
20306 fn = TREE_OPERAND (fn, 1);
20307 if (BASELINK_P (fn))
20308 fn = BASELINK_FUNCTIONS (fn);
20309 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20310 return true;
20311 tree targs = TREE_OPERAND (fn, 1);
20312 if (targs == NULL_TREE)
20313 return true;
20314 if (targs == error_mark_node)
20315 return false;
20316 return fold_targs_r (targs, complain);
20319 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20320 handling. */
20322 static void
20323 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20324 tree in_decl, releasing_vec &call_args)
20326 unsigned int nargs = call_expr_nargs (t);
20327 for (unsigned int i = 0; i < nargs; ++i)
20329 tree arg = CALL_EXPR_ARG (t, i);
20331 if (!PACK_EXPANSION_P (arg))
20332 vec_safe_push (call_args,
20333 tsubst_copy_and_build (arg, args, complain, in_decl));
20334 else
20336 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20337 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20338 if (TREE_CODE (arg) == TREE_VEC)
20340 unsigned int len, j;
20342 len = TREE_VEC_LENGTH (arg);
20343 for (j = 0; j < len; ++j)
20345 tree value = TREE_VEC_ELT (arg, j);
20346 if (value != NULL_TREE)
20347 value = convert_from_reference (value);
20348 vec_safe_push (call_args, value);
20351 else
20352 /* A partial substitution. Add one entry. */
20353 vec_safe_push (call_args, arg);
20358 /* Like tsubst but deals with expressions and performs semantic
20359 analysis. */
20361 tree
20362 tsubst_copy_and_build (tree t,
20363 tree args,
20364 tsubst_flags_t complain,
20365 tree in_decl)
20367 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20368 #define RECUR(NODE) \
20369 tsubst_copy_and_build (NODE, args, complain, in_decl)
20371 tree retval, op1;
20372 location_t save_loc;
20374 if (t == NULL_TREE || t == error_mark_node)
20375 return t;
20377 save_loc = input_location;
20378 if (location_t eloc = cp_expr_location (t))
20379 input_location = eloc;
20381 /* N3276 decltype magic only applies to calls at the top level or on the
20382 right side of a comma. */
20383 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20384 complain &= ~tf_decltype;
20386 switch (TREE_CODE (t))
20388 case USING_DECL:
20389 t = DECL_NAME (t);
20390 /* Fall through. */
20391 case IDENTIFIER_NODE:
20393 tree decl;
20394 cp_id_kind idk;
20395 const char *error_msg;
20397 if (IDENTIFIER_CONV_OP_P (t))
20399 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20400 t = make_conv_op_name (new_type);
20403 /* Look up the name. */
20404 decl = lookup_name (t);
20406 /* By convention, expressions use ERROR_MARK_NODE to indicate
20407 failure, not NULL_TREE. */
20408 if (decl == NULL_TREE)
20409 decl = error_mark_node;
20411 decl = finish_id_expression (t, decl, NULL_TREE,
20412 &idk,
20413 /*i_c_e_p=*/false,
20414 /*allow_i_c_e_p=*/true,
20415 /*non_i_c_e_p=*/nullptr,
20416 /*template_p=*/false,
20417 /*done=*/true,
20418 /*address_p=*/false,
20419 /*template_arg_p=*/false,
20420 &error_msg,
20421 input_location);
20422 if (error_msg)
20423 error (error_msg);
20424 if (identifier_p (decl))
20426 if (complain & tf_error)
20427 unqualified_name_lookup_error (decl);
20428 decl = error_mark_node;
20430 RETURN (decl);
20433 case TEMPLATE_ID_EXPR:
20435 tree object;
20436 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20437 complain, in_decl);
20438 tree targs = TREE_OPERAND (t, 1);
20440 if (targs)
20441 targs = tsubst_template_args (targs, args, complain, in_decl);
20442 if (targs == error_mark_node)
20443 RETURN (error_mark_node);
20445 if (TREE_CODE (templ) == SCOPE_REF)
20447 tree name = TREE_OPERAND (templ, 1);
20448 tree tid = lookup_template_function (name, targs);
20449 TREE_OPERAND (templ, 1) = tid;
20450 RETURN (templ);
20453 if (concept_definition_p (templ))
20455 tree check = build_concept_check (templ, targs, complain);
20456 if (check == error_mark_node)
20457 RETURN (error_mark_node);
20459 tree id = unpack_concept_check (check);
20461 /* If we built a function concept check, return the underlying
20462 template-id. So we can evaluate it as a function call. */
20463 if (function_concept_p (TREE_OPERAND (id, 0)))
20464 RETURN (id);
20466 RETURN (check);
20469 if (variable_template_p (templ))
20471 tree r = lookup_and_finish_template_variable (templ, targs,
20472 complain);
20473 r = convert_from_reference (r);
20474 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20475 RETURN (r);
20478 if (TREE_CODE (templ) == COMPONENT_REF)
20480 object = TREE_OPERAND (templ, 0);
20481 templ = TREE_OPERAND (templ, 1);
20483 else
20484 object = NULL_TREE;
20486 tree tid = lookup_template_function (templ, targs);
20487 protected_set_expr_location (tid, EXPR_LOCATION (t));
20489 if (object)
20490 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20491 object, tid, NULL_TREE));
20492 else if (identifier_p (templ))
20494 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20495 name lookup found nothing when parsing the template name. */
20496 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20497 RETURN (tid);
20499 else
20500 RETURN (baselink_for_fns (tid));
20503 case INDIRECT_REF:
20505 tree r = RECUR (TREE_OPERAND (t, 0));
20507 if (REFERENCE_REF_P (t))
20509 /* A type conversion to reference type will be enclosed in
20510 such an indirect ref, but the substitution of the cast
20511 will have also added such an indirect ref. */
20512 r = convert_from_reference (r);
20514 else
20515 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20516 templated_operator_saved_lookups (t),
20517 complain|decltype_flag);
20519 if (REF_PARENTHESIZED_P (t))
20520 r = force_paren_expr (r);
20522 RETURN (r);
20525 case NOP_EXPR:
20527 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20528 tree op0 = RECUR (TREE_OPERAND (t, 0));
20529 RETURN (build_nop (type, op0));
20532 case IMPLICIT_CONV_EXPR:
20534 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20535 tree expr = RECUR (TREE_OPERAND (t, 0));
20536 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20538 retval = copy_node (t);
20539 TREE_TYPE (retval) = type;
20540 TREE_OPERAND (retval, 0) = expr;
20541 RETURN (retval);
20543 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20544 /* We'll pass this to convert_nontype_argument again, we don't need
20545 to actually perform any conversion here. */
20546 RETURN (expr);
20547 int flags = LOOKUP_IMPLICIT;
20548 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20549 flags = LOOKUP_NORMAL;
20550 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20551 flags |= LOOKUP_NO_NARROWING;
20552 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20553 flags));
20556 case CONVERT_EXPR:
20558 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20559 tree op0 = RECUR (TREE_OPERAND (t, 0));
20560 if (op0 == error_mark_node)
20561 RETURN (error_mark_node);
20562 RETURN (build1 (CONVERT_EXPR, type, op0));
20565 case CAST_EXPR:
20566 case REINTERPRET_CAST_EXPR:
20567 case CONST_CAST_EXPR:
20568 case DYNAMIC_CAST_EXPR:
20569 case STATIC_CAST_EXPR:
20571 tree type;
20572 tree op, r = NULL_TREE;
20574 tsubst_flags_t tcomplain = complain;
20575 if (TREE_CODE (t) == CAST_EXPR)
20576 tcomplain |= tf_tst_ok;
20577 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20579 op = RECUR (TREE_OPERAND (t, 0));
20581 warning_sentinel s(warn_useless_cast);
20582 warning_sentinel s2(warn_ignored_qualifiers);
20583 warning_sentinel s3(warn_int_in_bool_context);
20584 switch (TREE_CODE (t))
20586 case CAST_EXPR:
20587 r = build_functional_cast (input_location, type, op, complain);
20588 break;
20589 case REINTERPRET_CAST_EXPR:
20590 r = build_reinterpret_cast (input_location, type, op, complain);
20591 break;
20592 case CONST_CAST_EXPR:
20593 r = build_const_cast (input_location, type, op, complain);
20594 break;
20595 case DYNAMIC_CAST_EXPR:
20596 r = build_dynamic_cast (input_location, type, op, complain);
20597 break;
20598 case STATIC_CAST_EXPR:
20599 r = build_static_cast (input_location, type, op, complain);
20600 if (IMPLICIT_RVALUE_P (t))
20601 set_implicit_rvalue_p (r);
20602 break;
20603 default:
20604 gcc_unreachable ();
20607 RETURN (r);
20610 case BIT_CAST_EXPR:
20612 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20613 tree op0 = RECUR (TREE_OPERAND (t, 0));
20614 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20617 case POSTDECREMENT_EXPR:
20618 case POSTINCREMENT_EXPR:
20619 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20620 args, complain, in_decl);
20621 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20622 templated_operator_saved_lookups (t),
20623 complain|decltype_flag));
20625 case PREDECREMENT_EXPR:
20626 case PREINCREMENT_EXPR:
20627 case NEGATE_EXPR:
20628 case BIT_NOT_EXPR:
20629 case ABS_EXPR:
20630 case TRUTH_NOT_EXPR:
20631 case UNARY_PLUS_EXPR: /* Unary + */
20632 case REALPART_EXPR:
20633 case IMAGPART_EXPR:
20634 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20635 RECUR (TREE_OPERAND (t, 0)),
20636 templated_operator_saved_lookups (t),
20637 complain|decltype_flag));
20639 case EXCESS_PRECISION_EXPR:
20641 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20642 tree op0 = RECUR (TREE_OPERAND (t, 0));
20643 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20644 RETURN (op0);
20645 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20646 type, op0));
20649 case FIX_TRUNC_EXPR:
20650 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20651 gcc_unreachable ();
20653 case ADDR_EXPR:
20654 op1 = TREE_OPERAND (t, 0);
20655 if (TREE_CODE (op1) == LABEL_DECL)
20656 RETURN (finish_label_address_expr (DECL_NAME (op1),
20657 EXPR_LOCATION (op1)));
20658 if (TREE_CODE (op1) == SCOPE_REF)
20659 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20660 /*done=*/true, /*address_p=*/true);
20661 else
20662 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20663 in_decl);
20664 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20665 templated_operator_saved_lookups (t),
20666 complain|decltype_flag));
20668 case PLUS_EXPR:
20669 case MINUS_EXPR:
20670 case MULT_EXPR:
20671 case TRUNC_DIV_EXPR:
20672 case CEIL_DIV_EXPR:
20673 case FLOOR_DIV_EXPR:
20674 case ROUND_DIV_EXPR:
20675 case EXACT_DIV_EXPR:
20676 case BIT_AND_EXPR:
20677 case BIT_IOR_EXPR:
20678 case BIT_XOR_EXPR:
20679 case TRUNC_MOD_EXPR:
20680 case FLOOR_MOD_EXPR:
20681 case TRUTH_ANDIF_EXPR:
20682 case TRUTH_ORIF_EXPR:
20683 case TRUTH_AND_EXPR:
20684 case TRUTH_OR_EXPR:
20685 case RSHIFT_EXPR:
20686 case LSHIFT_EXPR:
20687 case EQ_EXPR:
20688 case NE_EXPR:
20689 case MAX_EXPR:
20690 case MIN_EXPR:
20691 case LE_EXPR:
20692 case GE_EXPR:
20693 case LT_EXPR:
20694 case GT_EXPR:
20695 case SPACESHIP_EXPR:
20696 case MEMBER_REF:
20697 case DOTSTAR_EXPR:
20699 /* If either OP0 or OP1 was value- or type-dependent, suppress
20700 warnings that depend on the range of the types involved. */
20701 tree op0 = TREE_OPERAND (t, 0);
20702 tree op1 = TREE_OPERAND (t, 1);
20703 const bool was_dep = (dependent_operand_p (op0)
20704 || dependent_operand_p (op1));
20705 op0 = RECUR (op0);
20706 op1 = RECUR (op1);
20708 warning_sentinel s1(warn_type_limits, was_dep);
20709 warning_sentinel s2(warn_div_by_zero, was_dep);
20710 warning_sentinel s3(warn_logical_op, was_dep);
20711 warning_sentinel s4(warn_tautological_compare, was_dep);
20712 warning_sentinel s5(warn_address, was_dep);
20714 tree r = build_x_binary_op
20715 (input_location, TREE_CODE (t),
20716 op0,
20717 (warning_suppressed_p (TREE_OPERAND (t, 0))
20718 ? ERROR_MARK
20719 : TREE_CODE (TREE_OPERAND (t, 0))),
20720 op1,
20721 (warning_suppressed_p (TREE_OPERAND (t, 1))
20722 ? ERROR_MARK
20723 : TREE_CODE (TREE_OPERAND (t, 1))),
20724 templated_operator_saved_lookups (t),
20725 /*overload=*/NULL,
20726 complain|decltype_flag);
20727 if (EXPR_P (r))
20728 copy_warning (r, t);
20730 RETURN (r);
20733 case POINTER_PLUS_EXPR:
20735 tree op0 = RECUR (TREE_OPERAND (t, 0));
20736 if (op0 == error_mark_node)
20737 RETURN (error_mark_node);
20738 tree op1 = RECUR (TREE_OPERAND (t, 1));
20739 if (op1 == error_mark_node)
20740 RETURN (error_mark_node);
20741 RETURN (fold_build_pointer_plus (op0, op1));
20744 case SCOPE_REF:
20745 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20746 /*address_p=*/false));
20748 case BASELINK:
20749 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20750 args, complain, in_decl));
20752 case ARRAY_REF:
20753 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20754 args, complain, in_decl);
20755 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20756 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20757 == ovl_op_identifier (ARRAY_REF)))
20759 tree c = TREE_OPERAND (t, 1);
20760 releasing_vec index_exp_list;
20761 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20762 index_exp_list);
20764 tree r;
20765 if (vec_safe_length (index_exp_list) == 1
20766 && !PACK_EXPANSION_P (index_exp_list[0]))
20767 r = grok_array_decl (EXPR_LOCATION (t), op1,
20768 index_exp_list[0], NULL,
20769 complain | decltype_flag);
20770 else
20771 r = grok_array_decl (EXPR_LOCATION (t), op1,
20772 NULL_TREE, &index_exp_list,
20773 complain | decltype_flag);
20774 RETURN (r);
20776 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20777 RECUR (TREE_OPERAND (t, 1)),
20778 complain|decltype_flag));
20780 case SIZEOF_EXPR:
20781 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20782 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20783 RETURN (tsubst_copy (t, args, complain, in_decl));
20784 /* Fall through */
20786 case ALIGNOF_EXPR:
20788 tree r;
20790 op1 = TREE_OPERAND (t, 0);
20791 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20792 op1 = TREE_TYPE (op1);
20793 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20794 && ALIGNOF_EXPR_STD_P (t));
20795 if (!args)
20797 /* When there are no ARGS, we are trying to evaluate a
20798 non-dependent expression from the parser. Trying to do
20799 the substitutions may not work. */
20800 if (!TYPE_P (op1))
20801 op1 = TREE_TYPE (op1);
20803 else
20805 ++cp_unevaluated_operand;
20806 ++c_inhibit_evaluation_warnings;
20807 if (TYPE_P (op1))
20808 op1 = tsubst (op1, args, complain, in_decl);
20809 else
20810 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20811 --cp_unevaluated_operand;
20812 --c_inhibit_evaluation_warnings;
20814 if (TYPE_P (op1))
20815 r = cxx_sizeof_or_alignof_type (input_location,
20816 op1, TREE_CODE (t), std_alignof,
20817 complain & tf_error);
20818 else
20819 r = cxx_sizeof_or_alignof_expr (input_location,
20820 op1, TREE_CODE (t), std_alignof,
20821 complain & tf_error);
20822 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20824 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20826 if (!processing_template_decl && TYPE_P (op1))
20828 r = build_min (SIZEOF_EXPR, size_type_node,
20829 build1 (NOP_EXPR, op1, error_mark_node));
20830 SIZEOF_EXPR_TYPE_P (r) = 1;
20832 else
20833 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20834 TREE_SIDE_EFFECTS (r) = 0;
20835 TREE_READONLY (r) = 1;
20837 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20839 RETURN (r);
20842 case AT_ENCODE_EXPR:
20844 op1 = TREE_OPERAND (t, 0);
20845 ++cp_unevaluated_operand;
20846 ++c_inhibit_evaluation_warnings;
20847 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20848 --cp_unevaluated_operand;
20849 --c_inhibit_evaluation_warnings;
20850 RETURN (objc_build_encode_expr (op1));
20853 case NOEXCEPT_EXPR:
20854 op1 = TREE_OPERAND (t, 0);
20855 ++cp_unevaluated_operand;
20856 ++c_inhibit_evaluation_warnings;
20857 ++cp_noexcept_operand;
20858 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20859 --cp_unevaluated_operand;
20860 --c_inhibit_evaluation_warnings;
20861 --cp_noexcept_operand;
20862 RETURN (finish_noexcept_expr (op1, complain));
20864 case MODOP_EXPR:
20866 warning_sentinel s(warn_div_by_zero);
20867 tree lhs = RECUR (TREE_OPERAND (t, 0));
20868 tree rhs = RECUR (TREE_OPERAND (t, 2));
20870 tree r = build_x_modify_expr
20871 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20872 templated_operator_saved_lookups (t),
20873 complain|decltype_flag);
20874 /* TREE_NO_WARNING must be set if either the expression was
20875 parenthesized or it uses an operator such as >>= rather
20876 than plain assignment. In the former case, it was already
20877 set and must be copied. In the latter case,
20878 build_x_modify_expr sets it and it must not be reset
20879 here. */
20880 if (warning_suppressed_p (t, OPT_Wparentheses))
20881 suppress_warning (r, OPT_Wparentheses);
20883 RETURN (r);
20886 case ARROW_EXPR:
20887 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20888 args, complain, in_decl);
20889 /* Remember that there was a reference to this entity. */
20890 if (DECL_P (op1)
20891 && !mark_used (op1, complain) && !(complain & tf_error))
20892 RETURN (error_mark_node);
20893 RETURN (build_x_arrow (input_location, op1, complain));
20895 case NEW_EXPR:
20897 tree placement = RECUR (TREE_OPERAND (t, 0));
20898 tree init = RECUR (TREE_OPERAND (t, 3));
20899 vec<tree, va_gc> *placement_vec;
20900 vec<tree, va_gc> *init_vec;
20901 tree ret;
20902 location_t loc = EXPR_LOCATION (t);
20904 if (placement == NULL_TREE)
20905 placement_vec = NULL;
20906 else if (placement == error_mark_node)
20907 RETURN (error_mark_node);
20908 else
20910 placement_vec = make_tree_vector ();
20911 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20912 vec_safe_push (placement_vec, TREE_VALUE (placement));
20915 /* If there was an initializer in the original tree, but it
20916 instantiated to an empty list, then we should pass a
20917 non-NULL empty vector to tell build_new that it was an
20918 empty initializer() rather than no initializer. This can
20919 only happen when the initializer is a pack expansion whose
20920 parameter packs are of length zero. */
20921 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20922 init_vec = NULL;
20923 else if (init == error_mark_node)
20924 RETURN (error_mark_node);
20925 else
20927 init_vec = make_tree_vector ();
20928 if (init == void_node)
20929 gcc_assert (init_vec != NULL);
20930 else
20932 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20933 vec_safe_push (init_vec, TREE_VALUE (init));
20937 /* Avoid passing an enclosing decl to valid_array_size_p. */
20938 in_decl = NULL_TREE;
20940 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20941 tree op2 = RECUR (TREE_OPERAND (t, 2));
20942 ret = build_new (loc, &placement_vec, op1, op2,
20943 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20944 complain);
20946 if (placement_vec != NULL)
20947 release_tree_vector (placement_vec);
20948 if (init_vec != NULL)
20949 release_tree_vector (init_vec);
20951 RETURN (ret);
20954 case DELETE_EXPR:
20956 tree op0 = RECUR (TREE_OPERAND (t, 0));
20957 tree op1 = RECUR (TREE_OPERAND (t, 1));
20958 RETURN (delete_sanity (input_location, op0, op1,
20959 DELETE_EXPR_USE_VEC (t),
20960 DELETE_EXPR_USE_GLOBAL (t),
20961 complain));
20964 case COMPOUND_EXPR:
20966 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20967 complain & ~tf_decltype, in_decl);
20968 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20969 op0,
20970 RECUR (TREE_OPERAND (t, 1)),
20971 templated_operator_saved_lookups (t),
20972 complain|decltype_flag));
20975 case CALL_EXPR:
20977 tree function;
20978 unsigned int nargs;
20979 bool qualified_p;
20980 bool koenig_p;
20981 tree ret;
20983 function = CALL_EXPR_FN (t);
20984 /* Internal function with no arguments. */
20985 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20986 RETURN (t);
20988 /* When we parsed the expression, we determined whether or
20989 not Koenig lookup should be performed. */
20990 koenig_p = KOENIG_LOOKUP_P (t);
20991 if (function == NULL_TREE)
20993 koenig_p = false;
20994 qualified_p = false;
20996 else if (TREE_CODE (function) == SCOPE_REF)
20998 qualified_p = true;
20999 function = tsubst_qualified_id (function, args, complain, in_decl,
21000 /*done=*/false,
21001 /*address_p=*/false);
21003 else if (koenig_p
21004 && (identifier_p (function)
21005 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21006 && identifier_p (TREE_OPERAND (function, 0)))))
21008 /* Do nothing; calling tsubst_copy_and_build on an identifier
21009 would incorrectly perform unqualified lookup again.
21011 Note that we can also have an IDENTIFIER_NODE if the earlier
21012 unqualified lookup found a dependent local extern declaration
21013 (as per finish_call_expr); in that case koenig_p will be false
21014 and we do want to do the lookup again to find the substituted
21015 declaration. */
21016 qualified_p = false;
21018 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
21019 /* Use tsubst_copy to substitute through the template arguments
21020 of the template-id without performing unqualified lookup of
21021 the template name. */
21022 function = tsubst_copy (function, args, complain, in_decl);
21024 else
21026 if (TREE_CODE (function) == COMPONENT_REF)
21028 tree op = TREE_OPERAND (function, 1);
21030 qualified_p = (TREE_CODE (op) == SCOPE_REF
21031 || (BASELINK_P (op)
21032 && BASELINK_QUALIFIED_P (op)));
21034 else
21035 qualified_p = false;
21037 if (TREE_CODE (function) == ADDR_EXPR
21038 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
21039 /* Avoid error about taking the address of a constructor. */
21040 function = TREE_OPERAND (function, 0);
21042 tsubst_flags_t subcomplain = complain;
21043 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
21044 /* When KOENIG_P, we don't want to mark_used the callee before
21045 augmenting the overload set via ADL, so during this initial
21046 substitution we disable mark_used by setting tf_conv (68942). */
21047 subcomplain |= tf_conv;
21048 function = tsubst_copy_and_build (function, args, subcomplain, in_decl);
21050 if (BASELINK_P (function))
21051 qualified_p = true;
21054 nargs = call_expr_nargs (t);
21055 releasing_vec call_args;
21056 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
21057 call_args);
21059 /* Stripped-down processing for a call in a thunk. Specifically, in
21060 the thunk template for a generic lambda. */
21061 if (call_from_lambda_thunk_p (t))
21063 /* Now that we've expanded any packs, the number of call args
21064 might be different. */
21065 unsigned int cargs = call_args->length ();
21066 tree thisarg = NULL_TREE;
21067 if (TREE_CODE (function) == COMPONENT_REF)
21069 thisarg = TREE_OPERAND (function, 0);
21070 if (TREE_CODE (thisarg) == INDIRECT_REF)
21071 thisarg = TREE_OPERAND (thisarg, 0);
21072 function = TREE_OPERAND (function, 1);
21073 if (TREE_CODE (function) == BASELINK)
21074 function = BASELINK_FUNCTIONS (function);
21076 /* We aren't going to do normal overload resolution, so force the
21077 template-id to resolve. */
21078 function = resolve_nondeduced_context (function, complain);
21079 for (unsigned i = 0; i < cargs; ++i)
21081 /* In a thunk, pass through args directly, without any
21082 conversions. */
21083 tree arg = (*call_args)[i];
21084 while (TREE_CODE (arg) != PARM_DECL)
21085 arg = TREE_OPERAND (arg, 0);
21086 (*call_args)[i] = arg;
21088 if (thisarg)
21090 /* If there are no other args, just push 'this'. */
21091 if (cargs == 0)
21092 vec_safe_push (call_args, thisarg);
21093 else
21095 /* Otherwise, shift the other args over to make room. */
21096 tree last = (*call_args)[cargs - 1];
21097 vec_safe_push (call_args, last);
21098 for (int i = cargs - 1; i > 0; --i)
21099 (*call_args)[i] = (*call_args)[i - 1];
21100 (*call_args)[0] = thisarg;
21103 ret = build_call_a (function, call_args->length (),
21104 call_args->address ());
21105 /* The thunk location is not interesting. */
21106 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
21107 CALL_FROM_THUNK_P (ret) = true;
21108 if (CLASS_TYPE_P (TREE_TYPE (ret)))
21109 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
21111 RETURN (ret);
21114 /* We do not perform argument-dependent lookup if normal
21115 lookup finds a non-function, in accordance with the
21116 resolution of DR 218. */
21117 if (koenig_p
21118 && ((is_overloaded_fn (function)
21119 /* If lookup found a member function, the Koenig lookup is
21120 not appropriate, even if an unqualified-name was used
21121 to denote the function. */
21122 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
21123 || identifier_p (function)
21124 /* C++20 P0846: Lookup found nothing. */
21125 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21126 && identifier_p (TREE_OPERAND (function, 0))))
21127 /* Only do this when substitution turns a dependent call
21128 into a non-dependent call. */
21129 && type_dependent_expression_p_push (t)
21130 && !any_type_dependent_arguments_p (call_args))
21131 function = perform_koenig_lookup (function, call_args, tf_none);
21133 if (function != NULL_TREE
21134 && (identifier_p (function)
21135 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21136 && identifier_p (TREE_OPERAND (function, 0))
21137 && !any_dependent_template_arguments_p (TREE_OPERAND
21138 (function, 1))))
21139 && !any_type_dependent_arguments_p (call_args))
21141 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21142 if (template_id_p)
21143 function = TREE_OPERAND (function, 0);
21144 if (koenig_p && (complain & tf_warning_or_error))
21146 /* For backwards compatibility and good diagnostics, try
21147 the unqualified lookup again if we aren't in SFINAE
21148 context. */
21149 tree unq = tsubst_copy_and_build (function, args,
21150 complain, in_decl);
21151 if (unq == error_mark_node)
21152 RETURN (error_mark_node);
21154 if (unq != function)
21156 char const *const msg
21157 = G_("%qD was not declared in this scope, "
21158 "and no declarations were found by "
21159 "argument-dependent lookup at the point "
21160 "of instantiation");
21162 bool in_lambda = (current_class_type
21163 && LAMBDA_TYPE_P (current_class_type));
21164 /* In a lambda fn, we have to be careful to not
21165 introduce new this captures. Legacy code can't
21166 be using lambdas anyway, so it's ok to be
21167 stricter. Be strict with C++20 template-id ADL too.
21168 And be strict if we're already failing anyway. */
21169 bool strict = in_lambda || template_id_p || seen_error();
21170 bool diag = true;
21171 if (strict)
21172 error_at (cp_expr_loc_or_input_loc (t),
21173 msg, function);
21174 else
21175 diag = permerror (cp_expr_loc_or_input_loc (t),
21176 msg, function);
21177 if (diag)
21179 tree fn = unq;
21181 if (INDIRECT_REF_P (fn))
21182 fn = TREE_OPERAND (fn, 0);
21183 if (is_overloaded_fn (fn))
21184 fn = get_first_fn (fn);
21186 if (!DECL_P (fn))
21187 /* Can't say anything more. */;
21188 else if (DECL_CLASS_SCOPE_P (fn))
21190 location_t loc = cp_expr_loc_or_input_loc (t);
21191 inform (loc,
21192 "declarations in dependent base %qT are "
21193 "not found by unqualified lookup",
21194 DECL_CLASS_CONTEXT (fn));
21195 if (current_class_ptr)
21196 inform (loc,
21197 "use %<this->%D%> instead", function);
21198 else
21199 inform (loc,
21200 "use %<%T::%D%> instead",
21201 current_class_name, function);
21203 else
21204 inform (DECL_SOURCE_LOCATION (fn),
21205 "%qD declared here, later in the "
21206 "translation unit", fn);
21207 if (strict)
21208 RETURN (error_mark_node);
21211 function = unq;
21214 if (identifier_p (function))
21216 if (complain & tf_error)
21217 unqualified_name_lookup_error (function);
21218 RETURN (error_mark_node);
21222 /* Remember that there was a reference to this entity. */
21223 if (function != NULL_TREE
21224 && DECL_P (function)
21225 && !mark_used (function, complain) && !(complain & tf_error))
21226 RETURN (error_mark_node);
21228 if (!maybe_fold_fn_template_args (function, complain))
21229 return error_mark_node;
21231 /* Put back tf_decltype for the actual call. */
21232 complain |= decltype_flag;
21234 if (function == NULL_TREE)
21235 switch (CALL_EXPR_IFN (t))
21237 case IFN_LAUNDER:
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_launder%>");
21244 ret = error_mark_node;
21246 else
21247 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21248 (*call_args)[0], complain);
21249 break;
21251 case IFN_VEC_CONVERT:
21252 gcc_assert (nargs == 1);
21253 if (vec_safe_length (call_args) != 1)
21255 error_at (cp_expr_loc_or_input_loc (t),
21256 "wrong number of arguments to "
21257 "%<__builtin_convertvector%>");
21258 ret = error_mark_node;
21259 break;
21261 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21262 tsubst (TREE_TYPE (t), args,
21263 complain, in_decl),
21264 complain);
21265 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21266 RETURN (ret);
21267 break;
21269 case IFN_SHUFFLEVECTOR:
21271 ret = build_x_shufflevector (input_location, call_args,
21272 complain);
21273 if (ret != error_mark_node)
21274 RETURN (ret);
21275 break;
21278 case IFN_ASSUME:
21279 gcc_assert (nargs == 1);
21280 if (vec_safe_length (call_args) != 1)
21282 error_at (cp_expr_loc_or_input_loc (t),
21283 "wrong number of arguments to "
21284 "%<assume%> attribute");
21285 ret = error_mark_node;
21287 else
21289 tree &arg = (*call_args)[0];
21290 if (!type_dependent_expression_p (arg))
21291 arg = contextual_conv_bool (arg, tf_warning_or_error);
21292 if (error_operand_p (arg))
21294 ret = error_mark_node;
21295 break;
21297 ret = build_assume_call (EXPR_LOCATION (t), arg);
21298 RETURN (ret);
21300 break;
21302 default:
21303 /* Unsupported internal function with arguments. */
21304 gcc_unreachable ();
21306 else if (TREE_CODE (function) == OFFSET_REF
21307 || TREE_CODE (function) == DOTSTAR_EXPR
21308 || TREE_CODE (function) == MEMBER_REF)
21309 ret = build_offset_ref_call_from_tree (function, &call_args,
21310 complain);
21311 else if (TREE_CODE (function) == COMPONENT_REF)
21313 tree instance = TREE_OPERAND (function, 0);
21314 tree fn = TREE_OPERAND (function, 1);
21316 if (processing_template_decl
21317 && (type_dependent_expression_p (instance)
21318 || (!BASELINK_P (fn)
21319 && TREE_CODE (fn) != FIELD_DECL)
21320 || type_dependent_expression_p (fn)
21321 || any_type_dependent_arguments_p (call_args)))
21322 ret = build_min_nt_call_vec (function, call_args);
21323 else if (!BASELINK_P (fn))
21324 ret = finish_call_expr (function, &call_args,
21325 /*disallow_virtual=*/false,
21326 /*koenig_p=*/false,
21327 complain);
21328 else
21329 ret = (build_new_method_call
21330 (instance, fn,
21331 &call_args, NULL_TREE,
21332 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21333 /*fn_p=*/NULL,
21334 complain));
21336 else if (concept_check_p (function))
21338 /* FUNCTION is a template-id referring to a concept definition. */
21339 tree id = unpack_concept_check (function);
21340 tree tmpl = TREE_OPERAND (id, 0);
21341 tree args = TREE_OPERAND (id, 1);
21343 /* Calls to standard and variable concepts should have been
21344 previously diagnosed. */
21345 gcc_assert (function_concept_p (tmpl));
21347 /* Ensure the result is wrapped as a call expression. */
21348 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21350 else
21351 ret = finish_call_expr (function, &call_args,
21352 /*disallow_virtual=*/qualified_p,
21353 koenig_p,
21354 complain);
21356 if (ret != error_mark_node)
21358 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21359 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21360 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21361 if (op || ord || rev)
21362 if (tree call = extract_call_expr (ret))
21364 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21365 CALL_EXPR_ORDERED_ARGS (call) = ord;
21366 CALL_EXPR_REVERSE_ARGS (call) = rev;
21368 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21369 /* This also suppresses -Wredundant-move. */
21370 suppress_warning (ret, OPT_Wpessimizing_move);
21373 RETURN (ret);
21376 case COND_EXPR:
21378 tree cond = RECUR (TREE_OPERAND (t, 0));
21379 cond = mark_rvalue_use (cond);
21380 tree folded_cond = fold_non_dependent_expr (cond, complain);
21381 tree exp1, exp2;
21383 if (TREE_CODE (folded_cond) == INTEGER_CST)
21385 if (integer_zerop (folded_cond))
21387 ++c_inhibit_evaluation_warnings;
21388 exp1 = RECUR (TREE_OPERAND (t, 1));
21389 --c_inhibit_evaluation_warnings;
21390 exp2 = RECUR (TREE_OPERAND (t, 2));
21392 else
21394 exp1 = RECUR (TREE_OPERAND (t, 1));
21395 ++c_inhibit_evaluation_warnings;
21396 exp2 = RECUR (TREE_OPERAND (t, 2));
21397 --c_inhibit_evaluation_warnings;
21399 cond = folded_cond;
21401 else
21403 exp1 = RECUR (TREE_OPERAND (t, 1));
21404 exp2 = RECUR (TREE_OPERAND (t, 2));
21407 warning_sentinel s(warn_duplicated_branches);
21408 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21409 cond, exp1, exp2, complain));
21412 case PSEUDO_DTOR_EXPR:
21414 tree op0 = RECUR (TREE_OPERAND (t, 0));
21415 tree op1 = RECUR (TREE_OPERAND (t, 1));
21416 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21417 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21418 input_location));
21421 case TREE_LIST:
21422 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21424 case COMPONENT_REF:
21426 tree object;
21427 tree object_type;
21428 tree member;
21429 tree r;
21431 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21432 args, complain, in_decl);
21433 /* Remember that there was a reference to this entity. */
21434 if (DECL_P (object)
21435 && !mark_used (object, complain) && !(complain & tf_error))
21436 RETURN (error_mark_node);
21437 object_type = TREE_TYPE (object);
21439 member = TREE_OPERAND (t, 1);
21440 if (BASELINK_P (member))
21441 member = tsubst_baselink (member,
21442 non_reference (TREE_TYPE (object)),
21443 args, complain, in_decl);
21444 else
21445 member = tsubst_copy (member, args, complain, in_decl);
21446 if (member == error_mark_node)
21447 RETURN (error_mark_node);
21449 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21450 && TREE_CODE (member) == FIELD_DECL)
21452 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21453 RETURN (r);
21455 else if (TREE_CODE (member) == FIELD_DECL)
21457 r = finish_non_static_data_member (member, object, NULL_TREE,
21458 complain);
21459 if (TREE_CODE (r) == COMPONENT_REF)
21460 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21461 RETURN (r);
21463 else if (type_dependent_expression_p (object))
21464 /* We can't do much here. */;
21465 else if (!CLASS_TYPE_P (object_type))
21467 if (scalarish_type_p (object_type))
21469 tree s = NULL_TREE;
21470 tree dtor = member;
21472 if (TREE_CODE (dtor) == SCOPE_REF)
21474 s = TREE_OPERAND (dtor, 0);
21475 dtor = TREE_OPERAND (dtor, 1);
21477 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21479 dtor = TREE_OPERAND (dtor, 0);
21480 if (TYPE_P (dtor))
21481 RETURN (finish_pseudo_destructor_expr
21482 (object, s, dtor, input_location));
21486 else if (TREE_CODE (member) == SCOPE_REF
21487 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21489 /* Lookup the template functions now that we know what the
21490 scope is. */
21491 tree scope = TREE_OPERAND (member, 0);
21492 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21493 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21494 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21495 /*complain=*/false);
21496 if (BASELINK_P (member))
21498 BASELINK_FUNCTIONS (member)
21499 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21500 args);
21501 member = (adjust_result_of_qualified_name_lookup
21502 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21503 object_type));
21505 else
21507 qualified_name_lookup_error (scope, tmpl, member,
21508 input_location);
21509 RETURN (error_mark_node);
21512 else if (TREE_CODE (member) == SCOPE_REF
21513 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21514 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21516 if (complain & tf_error)
21518 if (TYPE_P (TREE_OPERAND (member, 0)))
21519 error ("%qT is not a class or namespace",
21520 TREE_OPERAND (member, 0));
21521 else
21522 error ("%qD is not a class or namespace",
21523 TREE_OPERAND (member, 0));
21525 RETURN (error_mark_node);
21528 r = finish_class_member_access_expr (object, member,
21529 /*template_p=*/false,
21530 complain);
21531 if (REF_PARENTHESIZED_P (t))
21532 r = force_paren_expr (r);
21533 RETURN (r);
21536 case THROW_EXPR:
21537 RETURN (build_throw
21538 (input_location, RECUR (TREE_OPERAND (t, 0))));
21540 case CONSTRUCTOR:
21542 vec<constructor_elt, va_gc> *n;
21543 constructor_elt *ce;
21544 unsigned HOST_WIDE_INT idx;
21545 bool process_index_p;
21546 int newlen;
21547 bool need_copy_p = false;
21548 tree r;
21550 tsubst_flags_t tcomplain = complain;
21551 if (COMPOUND_LITERAL_P (t))
21552 tcomplain |= tf_tst_ok;
21553 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21554 if (type == error_mark_node)
21555 RETURN (error_mark_node);
21557 /* We do not want to process the index of aggregate
21558 initializers as they are identifier nodes which will be
21559 looked up by digest_init. */
21560 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21562 if (null_member_pointer_value_p (t))
21564 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21565 RETURN (t);
21568 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21569 newlen = vec_safe_length (n);
21570 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21572 if (ce->index && process_index_p
21573 /* An identifier index is looked up in the type
21574 being initialized, not the current scope. */
21575 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21576 ce->index = RECUR (ce->index);
21578 if (PACK_EXPANSION_P (ce->value))
21580 /* Substitute into the pack expansion. */
21581 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21582 in_decl);
21584 if (ce->value == error_mark_node
21585 || PACK_EXPANSION_P (ce->value))
21587 else if (TREE_VEC_LENGTH (ce->value) == 1)
21588 /* Just move the argument into place. */
21589 ce->value = TREE_VEC_ELT (ce->value, 0);
21590 else
21592 /* Update the length of the final CONSTRUCTOR
21593 arguments vector, and note that we will need to
21594 copy.*/
21595 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21596 need_copy_p = true;
21599 else
21600 ce->value = RECUR (ce->value);
21603 if (need_copy_p)
21605 vec<constructor_elt, va_gc> *old_n = n;
21607 vec_alloc (n, newlen);
21608 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21610 if (TREE_CODE (ce->value) == TREE_VEC)
21612 int i, len = TREE_VEC_LENGTH (ce->value);
21613 for (i = 0; i < len; ++i)
21614 CONSTRUCTOR_APPEND_ELT (n, 0,
21615 TREE_VEC_ELT (ce->value, i));
21617 else
21618 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21622 r = build_constructor (init_list_type_node, n);
21623 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21624 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21625 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21627 if (TREE_HAS_CONSTRUCTOR (t))
21629 fcl_t cl = fcl_functional;
21630 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21631 cl = fcl_c99;
21632 RETURN (finish_compound_literal (type, r, complain, cl));
21635 TREE_TYPE (r) = type;
21636 RETURN (r);
21639 case TYPEID_EXPR:
21641 tree operand_0 = TREE_OPERAND (t, 0);
21642 if (TYPE_P (operand_0))
21644 operand_0 = tsubst (operand_0, args, complain, in_decl);
21645 RETURN (get_typeid (operand_0, complain));
21647 else
21649 operand_0 = RECUR (operand_0);
21650 RETURN (build_typeid (operand_0, complain));
21654 case VAR_DECL:
21655 if (!args)
21656 RETURN (t);
21657 /* Fall through */
21659 case PARM_DECL:
21661 tree r = tsubst_copy (t, args, complain, in_decl);
21662 /* ??? We're doing a subset of finish_id_expression here. */
21663 if (tree wrap = maybe_get_tls_wrapper_call (r))
21664 /* Replace an evaluated use of the thread_local variable with
21665 a call to its wrapper. */
21666 r = wrap;
21667 else if (outer_automatic_var_p (r))
21668 r = process_outer_var_ref (r, complain);
21670 if (!TYPE_REF_P (TREE_TYPE (t)))
21671 /* If the original type was a reference, we'll be wrapped in
21672 the appropriate INDIRECT_REF. */
21673 r = convert_from_reference (r);
21674 RETURN (r);
21677 case VA_ARG_EXPR:
21679 tree op0 = RECUR (TREE_OPERAND (t, 0));
21680 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21681 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21684 case OFFSETOF_EXPR:
21686 tree object_ptr
21687 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
21688 complain, in_decl);
21689 RETURN (finish_offsetof (object_ptr,
21690 RECUR (TREE_OPERAND (t, 0)),
21691 EXPR_LOCATION (t)));
21694 case ADDRESSOF_EXPR:
21695 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21696 RECUR (TREE_OPERAND (t, 0)), complain));
21698 case TRAIT_EXPR:
21700 tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
21701 complain, in_decl);
21702 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21703 complain, in_decl);
21704 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21705 TRAIT_EXPR_KIND (t), type1, type2));
21708 case STMT_EXPR:
21710 tree old_stmt_expr = cur_stmt_expr;
21711 tree stmt_expr = begin_stmt_expr ();
21713 cur_stmt_expr = stmt_expr;
21714 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
21715 stmt_expr = finish_stmt_expr (stmt_expr, false);
21716 cur_stmt_expr = old_stmt_expr;
21718 /* If the resulting list of expression statement is empty,
21719 fold it further into void_node. */
21720 if (empty_expr_stmt_p (stmt_expr))
21721 stmt_expr = void_node;
21723 RETURN (stmt_expr);
21726 case LAMBDA_EXPR:
21728 if (complain & tf_partial)
21730 /* We don't have a full set of template arguments yet; don't touch
21731 the lambda at all. */
21732 gcc_assert (processing_template_decl);
21733 return t;
21735 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21737 RETURN (build_lambda_object (r));
21740 case TRANSACTION_EXPR:
21741 RETURN (tsubst_expr (t, args, complain, in_decl));
21743 case PAREN_EXPR:
21744 if (REF_PARENTHESIZED_P (t))
21745 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21746 else
21747 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21749 tree op0 = RECUR (TREE_OPERAND (t, 0));
21750 RETURN (build1_loc (input_location, PAREN_EXPR,
21751 TREE_TYPE (op0), op0));
21754 case VEC_PERM_EXPR:
21756 tree op0 = RECUR (TREE_OPERAND (t, 0));
21757 tree op1 = RECUR (TREE_OPERAND (t, 1));
21758 tree op2 = RECUR (TREE_OPERAND (t, 2));
21759 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21760 complain));
21763 case REQUIRES_EXPR:
21765 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21766 RETURN (r);
21769 case RANGE_EXPR:
21770 /* No need to substitute further, a RANGE_EXPR will always be built
21771 with constant operands. */
21772 RETURN (t);
21774 case NON_LVALUE_EXPR:
21775 case VIEW_CONVERT_EXPR:
21777 tree op = RECUR (TREE_OPERAND (t, 0));
21779 if (location_wrapper_p (t))
21780 /* We need to do this here as well as in tsubst_copy so we get the
21781 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21782 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21784 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21785 if (REF_PARENTHESIZED_P (t))
21786 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21787 RETURN (finish_parenthesized_expr (op));
21789 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21790 parameter object const. */
21791 if (TREE_TYPE (op) == NULL_TREE
21792 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21794 /* The template argument is not const, presumably because
21795 it is still dependent, and so not the const template parm
21796 object. */
21797 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21798 if (TREE_CODE (op) == CONSTRUCTOR
21799 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21801 /* Don't add a wrapper to these. */
21802 op = copy_node (op);
21803 TREE_TYPE (op) = type;
21805 else
21806 /* Do add a wrapper otherwise (in particular, if op is
21807 another TEMPLATE_PARM_INDEX). */
21808 op = build1 (VIEW_CONVERT_EXPR, type, op);
21810 RETURN (op);
21813 default:
21814 /* Handle Objective-C++ constructs, if appropriate. */
21816 tree subst
21817 = objcp_tsubst_copy_and_build (t, args, complain, in_decl);
21818 if (subst)
21819 RETURN (subst);
21821 RETURN (tsubst_copy (t, args, complain, in_decl));
21824 #undef RECUR
21825 #undef RETURN
21826 out:
21827 input_location = save_loc;
21828 return retval;
21831 /* Verify that the instantiated ARGS are valid. For type arguments,
21832 make sure that the type's linkage is ok. For non-type arguments,
21833 make sure they are constants if they are integral or enumerations.
21834 Emit an error under control of COMPLAIN, and return TRUE on error. */
21836 static bool
21837 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21839 if (dependent_template_arg_p (t))
21840 return false;
21841 if (ARGUMENT_PACK_P (t))
21843 tree vec = ARGUMENT_PACK_ARGS (t);
21844 int len = TREE_VEC_LENGTH (vec);
21845 bool result = false;
21846 int i;
21848 for (i = 0; i < len; ++i)
21849 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21850 result = true;
21851 return result;
21853 else if (TYPE_P (t))
21855 /* [basic.link]: A name with no linkage (notably, the name
21856 of a class or enumeration declared in a local scope)
21857 shall not be used to declare an entity with linkage.
21858 This implies that names with no linkage cannot be used as
21859 template arguments
21861 DR 757 relaxes this restriction for C++0x. */
21862 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21863 : no_linkage_check (t, /*relaxed_p=*/false));
21865 if (nt)
21867 /* DR 488 makes use of a type with no linkage cause
21868 type deduction to fail. */
21869 if (complain & tf_error)
21871 if (TYPE_UNNAMED_P (nt))
21872 error ("%qT is/uses unnamed type", t);
21873 else
21874 error ("template argument for %qD uses local type %qT",
21875 tmpl, t);
21877 return true;
21879 /* In order to avoid all sorts of complications, we do not
21880 allow variably-modified types as template arguments. */
21881 else if (variably_modified_type_p (t, NULL_TREE))
21883 if (complain & tf_error)
21884 error ("%qT is a variably modified type", t);
21885 return true;
21888 /* Class template and alias template arguments should be OK. */
21889 else if (DECL_TYPE_TEMPLATE_P (t))
21891 /* A non-type argument of integral or enumerated type must be a
21892 constant. */
21893 else if (TREE_TYPE (t)
21894 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21895 && !REFERENCE_REF_P (t)
21896 && !TREE_CONSTANT (t))
21898 if (complain & tf_error)
21899 error ("integral expression %qE is not constant", t);
21900 return true;
21902 return false;
21905 static bool
21906 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21908 int ix, len = DECL_NTPARMS (tmpl);
21909 bool result = false;
21911 for (ix = 0; ix != len; ix++)
21913 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21914 result = true;
21916 if (result && (complain & tf_error))
21917 error (" trying to instantiate %qD", tmpl);
21918 return result;
21921 /* Call mark_used on each entity within the non-type template arguments in
21922 ARGS for an instantiation of TMPL, to ensure that each such entity is
21923 considered odr-used (and therefore marked for instantiation) regardless of
21924 whether the specialization was first formed in a template context (which
21925 inhibits mark_used).
21927 This function assumes push_to_top_level has been called beforehand. */
21929 static void
21930 mark_template_arguments_used (tree tmpl, tree args)
21932 /* It suffices to do this only when instantiating a primary template. */
21933 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21934 return;
21936 /* We already marked outer arguments when specializing the context. */
21937 args = INNERMOST_TEMPLATE_ARGS (args);
21939 for (tree arg : tree_vec_range (args))
21941 /* A (pointer/reference to) function or variable NTTP argument. */
21942 if (TREE_CODE (arg) == ADDR_EXPR
21943 || TREE_CODE (arg) == INDIRECT_REF)
21945 while (TREE_CODE (arg) == ADDR_EXPR
21946 || REFERENCE_REF_P (arg)
21947 || CONVERT_EXPR_P (arg))
21948 arg = TREE_OPERAND (arg, 0);
21949 if (VAR_OR_FUNCTION_DECL_P (arg))
21951 /* Pass tf_none to avoid duplicate diagnostics: if this call
21952 fails then an earlier call to mark_used for this argument
21953 must have also failed and emitted a diagnostic. */
21954 bool ok = mark_used (arg, tf_none);
21955 gcc_checking_assert (ok || seen_error ());
21958 /* A class NTTP argument. */
21959 else if (VAR_P (arg)
21960 && DECL_NTTP_OBJECT_P (arg))
21962 auto mark_used_r = [](tree *tp, int *, void *) {
21963 if (VAR_OR_FUNCTION_DECL_P (*tp))
21965 bool ok = mark_used (*tp, tf_none);
21966 gcc_checking_assert (ok || seen_error ());
21968 return NULL_TREE;
21970 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21971 mark_used_r, nullptr);
21976 /* We're out of SFINAE context now, so generate diagnostics for the access
21977 errors we saw earlier when instantiating D from TMPL and ARGS. */
21979 static void
21980 recheck_decl_substitution (tree d, tree tmpl, tree args)
21982 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21983 tree type = TREE_TYPE (pattern);
21984 location_t loc = input_location;
21986 push_access_scope (d);
21987 push_deferring_access_checks (dk_no_deferred);
21988 input_location = DECL_SOURCE_LOCATION (pattern);
21989 tsubst (type, args, tf_warning_or_error, d);
21990 input_location = loc;
21991 pop_deferring_access_checks ();
21992 pop_access_scope (d);
21995 /* Instantiate the indicated variable, function, or alias template TMPL with
21996 the template arguments in TARG_PTR. */
21998 tree
21999 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
22001 auto_timevar tv (TV_TEMPLATE_INST);
22003 tree targ_ptr = orig_args;
22004 tree fndecl;
22005 tree gen_tmpl;
22006 bool access_ok = true;
22008 if (tmpl == error_mark_node)
22009 return error_mark_node;
22011 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
22013 if (modules_p ())
22014 lazy_load_pendings (tmpl);
22016 /* If this function is a clone, handle it specially. */
22017 if (DECL_CLONED_FUNCTION_P (tmpl))
22019 tree spec;
22020 tree clone;
22022 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
22023 DECL_CLONED_FUNCTION. */
22024 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
22025 targ_ptr, complain);
22026 if (spec == error_mark_node)
22027 return error_mark_node;
22029 /* Look for the clone. */
22030 FOR_EACH_CLONE (clone, spec)
22031 if (DECL_NAME (clone) == DECL_NAME (tmpl))
22032 return clone;
22033 /* We should always have found the clone by now. */
22034 gcc_unreachable ();
22035 return NULL_TREE;
22038 if (targ_ptr == error_mark_node)
22039 return error_mark_node;
22041 /* Check to see if we already have this specialization. */
22042 gen_tmpl = most_general_template (tmpl);
22043 if (TMPL_ARGS_DEPTH (targ_ptr)
22044 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22045 /* targ_ptr only has the innermost template args, so add the outer ones
22046 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22047 the case of a non-dependent call within a template definition). */
22048 targ_ptr = (add_outermost_template_args
22049 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22050 targ_ptr));
22052 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
22053 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
22055 gcc_checking_assert (tmpl == gen_tmpl
22056 || ((fndecl
22057 = retrieve_specialization (tmpl, orig_args, 0))
22058 == spec)
22059 || fndecl == NULL_TREE);
22061 if (spec != NULL_TREE)
22063 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22065 if (complain & tf_error)
22066 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22067 return error_mark_node;
22069 return spec;
22072 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22073 complain))
22074 return error_mark_node;
22076 /* We are building a FUNCTION_DECL, during which the access of its
22077 parameters and return types have to be checked. However this
22078 FUNCTION_DECL which is the desired context for access checking
22079 is not built yet. We solve this chicken-and-egg problem by
22080 deferring all checks until we have the FUNCTION_DECL. */
22081 push_deferring_access_checks (dk_deferred);
22083 /* Instantiation of the function happens in the context of the function
22084 template, not the context of the overload resolution we're doing. */
22085 push_to_top_level ();
22086 /* If there are dependent arguments, e.g. because we're doing partial
22087 ordering, make sure processing_template_decl stays set. */
22088 if (uses_template_parms (targ_ptr))
22089 ++processing_template_decl;
22090 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22092 tree ctx;
22093 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22094 /* If the context of the partially instantiated template is
22095 already non-dependent, then we might as well use it. */
22096 ctx = DECL_CONTEXT (tmpl);
22097 else
22098 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22099 complain, gen_tmpl, true);
22100 push_nested_class (ctx);
22103 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22105 tree partial_ti = NULL_TREE;
22106 fndecl = NULL_TREE;
22107 if (VAR_P (pattern))
22109 /* We need to determine if we're using a partial or explicit
22110 specialization now, because the type of the variable could be
22111 different. */
22112 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22113 partial_ti = most_specialized_partial_spec (tid, complain);
22114 if (partial_ti == error_mark_node)
22115 pattern = error_mark_node;
22116 else if (partial_ti)
22118 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22119 tree partial_args = TI_ARGS (partial_ti);
22120 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22121 fndecl = tsubst_decl (partial_pat, partial_args, complain,
22122 /*use_spec_table=*/false);
22126 /* Substitute template parameters to obtain the specialization. */
22127 if (fndecl == NULL_TREE)
22128 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
22129 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22130 pop_nested_class ();
22131 pop_from_top_level ();
22133 if (fndecl == error_mark_node)
22135 pop_deferring_access_checks ();
22136 return error_mark_node;
22139 /* The DECL_TI_TEMPLATE should always be the immediate parent
22140 template, not the most general template. */
22141 DECL_TI_TEMPLATE (fndecl) = tmpl;
22142 DECL_TI_ARGS (fndecl) = targ_ptr;
22143 if (VAR_P (pattern))
22144 /* Now that we we've formed this variable template specialization,
22145 remember the result of most_specialized_partial_spec for it. */
22146 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22148 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
22149 if (fndecl == error_mark_node)
22150 return error_mark_node;
22152 set_instantiating_module (fndecl);
22154 /* Now we know the specialization, compute access previously
22155 deferred. Do no access control for inheriting constructors,
22156 as we already checked access for the inherited constructor. */
22157 if (!(flag_new_inheriting_ctors
22158 && DECL_INHERITED_CTOR (fndecl)))
22160 push_access_scope (fndecl);
22161 if (!perform_deferred_access_checks (complain))
22162 access_ok = false;
22163 pop_access_scope (fndecl);
22165 pop_deferring_access_checks ();
22167 /* If we've just instantiated the main entry point for a function,
22168 instantiate all the alternate entry points as well. We do this
22169 by cloning the instantiation of the main entry point, not by
22170 instantiating the template clones. */
22171 if (tree chain = DECL_CHAIN (gen_tmpl))
22172 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22173 clone_cdtor (fndecl, /*update_methods=*/false);
22175 if (!access_ok)
22177 if (!(complain & tf_error))
22179 /* Remember to reinstantiate when we're out of SFINAE so the user
22180 can see the errors. */
22181 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22183 return error_mark_node;
22186 return fndecl;
22189 /* Instantiate the alias template TMPL with ARGS. Also push a template
22190 instantiation level, which instantiate_template doesn't do because
22191 functions and variables have sufficient context established by the
22192 callers. */
22194 static tree
22195 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22197 if (tmpl == error_mark_node || args == error_mark_node)
22198 return error_mark_node;
22200 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22201 args, tmpl, complain);
22202 if (args == error_mark_node)
22203 return error_mark_node;
22205 /* FIXME check for satisfaction in check_instantiated_args. */
22206 if (!constraints_satisfied_p (tmpl, args))
22208 if (complain & tf_error)
22210 auto_diagnostic_group d;
22211 error ("template constraint failure for %qD", tmpl);
22212 diagnose_constraints (input_location, tmpl, args);
22214 return error_mark_node;
22217 if (!push_tinst_level (tmpl, args))
22218 return error_mark_node;
22219 tree r = instantiate_template (tmpl, args, complain);
22220 pop_tinst_level ();
22222 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22224 /* An alias template specialization can be dependent
22225 even if its underlying type is not. */
22226 TYPE_DEPENDENT_P (d) = true;
22227 TYPE_DEPENDENT_P_VALID (d) = true;
22228 /* Sometimes a dependent alias spec is equivalent to its expansion,
22229 sometimes not. So always use structural_comptypes. */
22230 SET_TYPE_STRUCTURAL_EQUALITY (d);
22233 return r;
22236 /* PARM is a template parameter pack for FN. Returns true iff
22237 PARM is used in a deducible way in the argument list of FN. */
22239 static bool
22240 pack_deducible_p (tree parm, tree fn)
22242 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22243 for (; t; t = TREE_CHAIN (t))
22245 tree type = TREE_VALUE (t);
22246 tree packs;
22247 if (!PACK_EXPANSION_P (type))
22248 continue;
22249 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22250 packs; packs = TREE_CHAIN (packs))
22251 if (template_args_equal (TREE_VALUE (packs), parm))
22253 /* The template parameter pack is used in a function parameter
22254 pack. If this is the end of the parameter list, the
22255 template parameter pack is deducible. */
22256 if (TREE_CHAIN (t) == void_list_node)
22257 return true;
22258 else
22259 /* Otherwise, not. Well, it could be deduced from
22260 a non-pack parameter, but doing so would end up with
22261 a deduction mismatch, so don't bother. */
22262 return false;
22265 /* The template parameter pack isn't used in any function parameter
22266 packs, but it might be used deeper, e.g. tuple<Args...>. */
22267 return true;
22270 /* Subroutine of fn_type_unification: check non-dependent parms for
22271 convertibility. */
22273 static int
22274 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22275 tree fn, unification_kind_t strict, int flags,
22276 struct conversion **convs, bool explain_p)
22278 /* Non-constructor methods need to leave a conversion for 'this', which
22279 isn't included in nargs here. */
22280 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22281 && !DECL_CONSTRUCTOR_P (fn));
22283 for (unsigned ia = 0;
22284 parms && parms != void_list_node && ia < nargs; )
22286 tree parm = TREE_VALUE (parms);
22288 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22289 && (!TREE_CHAIN (parms)
22290 || TREE_CHAIN (parms) == void_list_node))
22291 /* For a function parameter pack that occurs at the end of the
22292 parameter-declaration-list, the type A of each remaining
22293 argument of the call is compared with the type P of the
22294 declarator-id of the function parameter pack. */
22295 break;
22297 parms = TREE_CHAIN (parms);
22299 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22300 /* For a function parameter pack that does not occur at the
22301 end of the parameter-declaration-list, the type of the
22302 parameter pack is a non-deduced context. */
22303 continue;
22305 if (!uses_template_parms (parm))
22307 tree arg = args[ia];
22308 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22309 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22311 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22312 conv_p, explain_p))
22313 return 1;
22316 ++ia;
22319 return 0;
22322 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22323 NARGS elements of the arguments that are being used when calling
22324 it. TARGS is a vector into which the deduced template arguments
22325 are placed.
22327 Returns either a FUNCTION_DECL for the matching specialization of FN or
22328 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22329 true, diagnostics will be printed to explain why it failed.
22331 If FN is a conversion operator, or we are trying to produce a specific
22332 specialization, RETURN_TYPE is the return type desired.
22334 The EXPLICIT_TARGS are explicit template arguments provided via a
22335 template-id.
22337 The parameter STRICT is one of:
22339 DEDUCE_CALL:
22340 We are deducing arguments for a function call, as in
22341 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22342 deducing arguments for a call to the result of a conversion
22343 function template, as in [over.call.object].
22345 DEDUCE_CONV:
22346 We are deducing arguments for a conversion function, as in
22347 [temp.deduct.conv].
22349 DEDUCE_EXACT:
22350 We are deducing arguments when doing an explicit instantiation
22351 as in [temp.explicit], when determining an explicit specialization
22352 as in [temp.expl.spec], or when taking the address of a function
22353 template, as in [temp.deduct.funcaddr]. */
22355 tree
22356 fn_type_unification (tree fn,
22357 tree explicit_targs,
22358 tree targs,
22359 const tree *args,
22360 unsigned int nargs,
22361 tree return_type,
22362 unification_kind_t strict,
22363 int flags,
22364 struct conversion **convs,
22365 bool explain_p,
22366 bool decltype_p)
22368 tree parms;
22369 tree fntype;
22370 tree decl = NULL_TREE;
22371 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22372 bool ok;
22373 static int deduction_depth;
22374 /* type_unification_real will pass back any access checks from default
22375 template argument substitution. */
22376 vec<deferred_access_check, va_gc> *checks = NULL;
22377 /* We don't have all the template args yet. */
22378 bool incomplete = true;
22380 tree orig_fn = fn;
22381 if (flag_new_inheriting_ctors)
22382 fn = strip_inheriting_ctors (fn);
22384 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22385 tree r = error_mark_node;
22387 tree full_targs = targs;
22388 if (TMPL_ARGS_DEPTH (targs)
22389 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22390 full_targs = (add_outermost_template_args
22391 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22392 targs));
22394 if (decltype_p)
22395 complain |= tf_decltype;
22397 /* In C++0x, it's possible to have a function template whose type depends
22398 on itself recursively. This is most obvious with decltype, but can also
22399 occur with enumeration scope (c++/48969). So we need to catch infinite
22400 recursion and reject the substitution at deduction time; this function
22401 will return error_mark_node for any repeated substitution.
22403 This also catches excessive recursion such as when f<N> depends on
22404 f<N-1> across all integers, and returns error_mark_node for all the
22405 substitutions back up to the initial one.
22407 This is, of course, not reentrant. */
22408 if (excessive_deduction_depth)
22409 return error_mark_node;
22410 ++deduction_depth;
22412 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22414 fntype = TREE_TYPE (fn);
22415 if (explicit_targs)
22417 /* [temp.deduct]
22419 The specified template arguments must match the template
22420 parameters in kind (i.e., type, nontype, template), and there
22421 must not be more arguments than there are parameters;
22422 otherwise type deduction fails.
22424 Nontype arguments must match the types of the corresponding
22425 nontype template parameters, or must be convertible to the
22426 types of the corresponding nontype parameters as specified in
22427 _temp.arg.nontype_, otherwise type deduction fails.
22429 All references in the function type of the function template
22430 to the corresponding template parameters are replaced by the
22431 specified template argument values. If a substitution in a
22432 template parameter or in the function type of the function
22433 template results in an invalid type, type deduction fails. */
22434 int i, len = TREE_VEC_LENGTH (tparms);
22435 location_t loc = input_location;
22436 incomplete = false;
22438 if (explicit_targs == error_mark_node)
22439 goto fail;
22441 if (TMPL_ARGS_DEPTH (explicit_targs)
22442 < TMPL_ARGS_DEPTH (full_targs))
22443 explicit_targs = add_outermost_template_args (full_targs,
22444 explicit_targs);
22446 /* Adjust any explicit template arguments before entering the
22447 substitution context. */
22448 explicit_targs
22449 = (coerce_template_parms (tparms, explicit_targs, fn,
22450 complain|tf_partial,
22451 /*require_all_args=*/false));
22452 if (explicit_targs == error_mark_node)
22453 goto fail;
22455 /* Substitute the explicit args into the function type. This is
22456 necessary so that, for instance, explicitly declared function
22457 arguments can match null pointed constants. If we were given
22458 an incomplete set of explicit args, we must not do semantic
22459 processing during substitution as we could create partial
22460 instantiations. */
22461 for (i = 0; i < len; i++)
22463 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22464 bool parameter_pack = false;
22465 tree targ = TREE_VEC_ELT (explicit_targs, i);
22467 /* Dig out the actual parm. */
22468 if (TREE_CODE (parm) == TYPE_DECL
22469 || TREE_CODE (parm) == TEMPLATE_DECL)
22471 parm = TREE_TYPE (parm);
22472 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22474 else if (TREE_CODE (parm) == PARM_DECL)
22476 parm = DECL_INITIAL (parm);
22477 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22480 if (targ == NULL_TREE)
22481 /* No explicit argument for this template parameter. */
22482 incomplete = true;
22483 else if (parameter_pack && pack_deducible_p (parm, fn))
22485 /* Mark the argument pack as "incomplete". We could
22486 still deduce more arguments during unification.
22487 We remove this mark in type_unification_real. */
22488 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22489 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22490 = ARGUMENT_PACK_ARGS (targ);
22492 /* We have some incomplete argument packs. */
22493 incomplete = true;
22497 if (incomplete)
22499 if (!push_tinst_level (fn, explicit_targs))
22501 excessive_deduction_depth = true;
22502 goto fail;
22504 ++processing_template_decl;
22505 input_location = DECL_SOURCE_LOCATION (fn);
22506 /* Ignore any access checks; we'll see them again in
22507 instantiate_template and they might have the wrong
22508 access path at this point. */
22509 push_deferring_access_checks (dk_deferred);
22510 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22511 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22512 pop_deferring_access_checks ();
22513 input_location = loc;
22514 --processing_template_decl;
22515 pop_tinst_level ();
22517 if (fntype == error_mark_node)
22518 goto fail;
22521 /* Place the explicitly specified arguments in TARGS. */
22522 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22523 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22524 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22525 if (!incomplete && CHECKING_P
22526 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22527 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22528 (targs, NUM_TMPL_ARGS (explicit_targs));
22531 if (return_type && strict != DEDUCE_CALL)
22533 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22534 new_args[0] = return_type;
22535 memcpy (new_args + 1, args, nargs * sizeof (tree));
22536 args = new_args;
22537 ++nargs;
22540 if (!incomplete)
22541 goto deduced;
22543 /* Never do unification on the 'this' parameter. */
22544 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22546 if (return_type && strict == DEDUCE_CALL)
22548 /* We're deducing for a call to the result of a template conversion
22549 function. The parms we really want are in return_type. */
22550 if (INDIRECT_TYPE_P (return_type))
22551 return_type = TREE_TYPE (return_type);
22552 parms = TYPE_ARG_TYPES (return_type);
22554 else if (return_type)
22556 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22559 /* We allow incomplete unification without an error message here
22560 because the standard doesn't seem to explicitly prohibit it. Our
22561 callers must be ready to deal with unification failures in any
22562 event. */
22564 /* If we aren't explaining yet, push tinst context so we can see where
22565 any errors (e.g. from class instantiations triggered by instantiation
22566 of default template arguments) come from. If we are explaining, this
22567 context is redundant. */
22568 if (!explain_p && !push_tinst_level (fn, targs))
22570 excessive_deduction_depth = true;
22571 goto fail;
22574 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22575 full_targs, parms, args, nargs, /*subr=*/0,
22576 strict, &checks, explain_p);
22577 if (!explain_p)
22578 pop_tinst_level ();
22579 if (!ok)
22580 goto fail;
22582 /* Now that we have bindings for all of the template arguments,
22583 ensure that the arguments deduced for the template template
22584 parameters have compatible template parameter lists. We cannot
22585 check this property before we have deduced all template
22586 arguments, because the template parameter types of a template
22587 template parameter might depend on prior template parameters
22588 deduced after the template template parameter. The following
22589 ill-formed example illustrates this issue:
22591 template<typename T, template<T> class C> void f(C<5>, T);
22593 template<int N> struct X {};
22595 void g() {
22596 f(X<5>(), 5l); // error: template argument deduction fails
22599 The template parameter list of 'C' depends on the template type
22600 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22601 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22602 time that we deduce 'C'. */
22603 if (!template_template_parm_bindings_ok_p
22604 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22606 unify_inconsistent_template_template_parameters (explain_p);
22607 goto fail;
22610 deduced:
22612 /* CWG2369: Check satisfaction before non-deducible conversions. */
22613 if (!constraints_satisfied_p (fn, targs))
22615 if (explain_p)
22616 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22617 goto fail;
22620 /* DR 1391: All parameters have args, now check non-dependent parms for
22621 convertibility. We don't do this if all args were explicitly specified,
22622 as the standard says that we substitute explicit args immediately. */
22623 if (incomplete
22624 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22625 convs, explain_p))
22626 goto fail;
22628 /* All is well so far. Now, check:
22630 [temp.deduct]
22632 When all template arguments have been deduced, all uses of
22633 template parameters in nondeduced contexts are replaced with
22634 the corresponding deduced argument values. If the
22635 substitution results in an invalid type, as described above,
22636 type deduction fails. */
22637 if (!push_tinst_level (fn, targs))
22639 excessive_deduction_depth = true;
22640 goto fail;
22643 /* Also collect access checks from the instantiation. */
22644 reopen_deferring_access_checks (checks);
22646 decl = instantiate_template (fn, targs, complain);
22648 checks = get_deferred_access_checks ();
22649 pop_deferring_access_checks ();
22651 pop_tinst_level ();
22653 if (decl == error_mark_node)
22654 goto fail;
22656 /* Now perform any access checks encountered during substitution. */
22657 push_access_scope (decl);
22658 ok = perform_access_checks (checks, complain);
22659 pop_access_scope (decl);
22660 if (!ok)
22661 goto fail;
22663 /* If we're looking for an exact match, check that what we got
22664 is indeed an exact match. It might not be if some template
22665 parameters are used in non-deduced contexts. But don't check
22666 for an exact match if we have dependent template arguments;
22667 in that case we're doing partial ordering, and we already know
22668 that we have two candidates that will provide the actual type. */
22669 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22671 tree substed = TREE_TYPE (decl);
22672 unsigned int i;
22674 tree sarg
22675 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22676 if (return_type)
22677 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22678 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22679 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22681 unify_type_mismatch (explain_p, args[i],
22682 TREE_VALUE (sarg));
22683 goto fail;
22685 if ((i < nargs || sarg)
22686 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22687 doesn't contain the trailing void, and conv fns are always (). */
22688 && !DECL_CONV_FN_P (decl))
22690 unsigned nsargs = i + list_length (sarg);
22691 unify_arity (explain_p, nargs, nsargs);
22692 goto fail;
22696 /* After doing deduction with the inherited constructor, actually return an
22697 instantiation of the inheriting constructor. */
22698 if (orig_fn != fn)
22699 decl = instantiate_template (orig_fn, targs, complain);
22701 r = decl;
22703 fail:
22704 --deduction_depth;
22705 if (excessive_deduction_depth)
22707 if (deduction_depth == 0)
22708 /* Reset once we're all the way out. */
22709 excessive_deduction_depth = false;
22712 return r;
22715 /* Returns true iff PARM is a forwarding reference in the context of
22716 template argument deduction for TMPL. */
22718 static bool
22719 forwarding_reference_p (tree parm, tree tmpl)
22721 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22722 cv-unqualified template parameter ..." */
22723 if (TYPE_REF_P (parm)
22724 && TYPE_REF_IS_RVALUE (parm)
22725 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22726 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22728 parm = TREE_TYPE (parm);
22729 /* [temp.deduct.call], "... that does not represent a template parameter
22730 of a class template (during class template argument deduction)." */
22731 if (tmpl
22732 && deduction_guide_p (tmpl)
22733 && DECL_ARTIFICIAL (tmpl))
22735 /* Since the template parameters of a synthesized guide consist of
22736 the template parameters of the class template followed by those of
22737 the constructor (if any), we can tell if PARM represents a template
22738 parameter of the class template by comparing its index with the
22739 arity of the class template. */
22740 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22741 if (TEMPLATE_TYPE_IDX (parm)
22742 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22743 return false;
22745 return true;
22747 return false;
22750 /* Adjust types before performing type deduction, as described in
22751 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22752 sections are symmetric. PARM is the type of a function parameter
22753 or the return type of the conversion function. ARG is the type of
22754 the argument passed to the call, or the type of the value
22755 initialized with the result of the conversion function.
22756 ARG_EXPR is the original argument expression, which may be null. */
22758 static int
22759 maybe_adjust_types_for_deduction (tree tparms,
22760 unification_kind_t strict,
22761 tree* parm,
22762 tree* arg,
22763 tree arg_expr)
22765 int result = 0;
22767 switch (strict)
22769 case DEDUCE_CALL:
22770 break;
22772 case DEDUCE_CONV:
22773 /* [temp.deduct.conv] First remove a reference type on parm.
22774 DRs 322 & 976 affected this. */
22775 if (TYPE_REF_P (*parm))
22776 *parm = TREE_TYPE (*parm);
22778 /* Swap PARM and ARG throughout the remainder of this
22779 function; the handling is precisely symmetric since PARM
22780 will initialize ARG rather than vice versa. */
22781 std::swap (parm, arg);
22783 break;
22785 case DEDUCE_EXACT:
22786 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22787 too, but here handle it by stripping the reference from PARM
22788 rather than by adding it to ARG. */
22789 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22790 && TYPE_REF_P (*arg)
22791 && !TYPE_REF_IS_RVALUE (*arg))
22792 *parm = TREE_TYPE (*parm);
22793 /* Nothing else to do in this case. */
22794 return 0;
22796 default:
22797 gcc_unreachable ();
22800 if (!TYPE_REF_P (*parm))
22802 /* [temp.deduct.call]
22804 If P is not a reference type:
22806 --If A is an array type, the pointer type produced by the
22807 array-to-pointer standard conversion (_conv.array_) is
22808 used in place of A for type deduction; otherwise,
22810 --If A is a function type, the pointer type produced by
22811 the function-to-pointer standard conversion
22812 (_conv.func_) is used in place of A for type deduction;
22813 otherwise,
22815 --If A is a cv-qualified type, the top level
22816 cv-qualifiers of A's type are ignored for type
22817 deduction. */
22818 if (TREE_CODE (*arg) == ARRAY_TYPE)
22819 *arg = build_pointer_type (TREE_TYPE (*arg));
22820 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22821 *arg = build_pointer_type (*arg);
22822 else
22823 *arg = TYPE_MAIN_VARIANT (*arg);
22826 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22827 an lvalue, the type 'lvalue reference to A' is used in place of A for
22828 type deduction." */
22829 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22830 && (arg_expr ? lvalue_p (arg_expr)
22831 /* try_one_overload doesn't provide an arg_expr, but
22832 functions are always lvalues. */
22833 : TREE_CODE (*arg) == FUNCTION_TYPE))
22834 *arg = build_reference_type (*arg);
22836 /* [temp.deduct.call]
22838 If P is a cv-qualified type, the top level cv-qualifiers
22839 of P's type are ignored for type deduction. If P is a
22840 reference type, the type referred to by P is used for
22841 type deduction. */
22842 *parm = TYPE_MAIN_VARIANT (*parm);
22843 if (TYPE_REF_P (*parm))
22845 *parm = TREE_TYPE (*parm);
22846 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22849 return result;
22852 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22853 template which doesn't contain any deducible template parameters; check if
22854 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22855 unify_one_argument. */
22857 static int
22858 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22859 int flags, struct conversion **conv_p,
22860 bool explain_p)
22862 tree type;
22864 if (!TYPE_P (arg))
22865 type = TREE_TYPE (arg);
22866 else
22867 type = arg;
22869 if (same_type_p (parm, type))
22870 return unify_success (explain_p);
22872 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22873 if (strict == DEDUCE_CONV)
22875 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22876 return unify_success (explain_p);
22878 else if (strict == DEDUCE_CALL)
22880 bool ok = false;
22881 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22882 if (conv_p)
22883 /* Avoid recalculating this in add_function_candidate. */
22884 ok = (*conv_p
22885 = good_conversion (parm, type, conv_arg, flags, complain));
22886 else
22887 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22888 if (ok)
22889 return unify_success (explain_p);
22892 if (strict == DEDUCE_EXACT)
22893 return unify_type_mismatch (explain_p, parm, arg);
22894 else
22895 return unify_arg_conversion (explain_p, parm, type, arg);
22898 static bool uses_deducible_template_parms (tree type);
22900 /* Returns true iff the expression EXPR is one from which a template
22901 argument can be deduced. In other words, if it's an undecorated
22902 use of a template non-type parameter. */
22904 static bool
22905 deducible_expression (tree expr)
22907 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22908 while (CONVERT_EXPR_P (expr)
22909 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22910 || REFERENCE_REF_P (expr))
22911 expr = TREE_OPERAND (expr, 0);
22912 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22915 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22916 deducible way; that is, if it has a max value of <PARM> - 1. */
22918 static bool
22919 deducible_array_bound (tree domain)
22921 if (domain == NULL_TREE)
22922 return false;
22924 tree max = TYPE_MAX_VALUE (domain);
22925 if (TREE_CODE (max) != MINUS_EXPR)
22926 return false;
22928 return deducible_expression (TREE_OPERAND (max, 0));
22931 /* Returns true iff the template arguments ARGS use a template parameter
22932 in a deducible way. */
22934 static bool
22935 deducible_template_args (tree args)
22937 for (tree elt : tree_vec_range (args))
22939 bool deducible;
22940 if (ARGUMENT_PACK_P (elt))
22941 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22942 else
22944 if (PACK_EXPANSION_P (elt))
22945 elt = PACK_EXPANSION_PATTERN (elt);
22946 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22947 deducible = true;
22948 else if (TYPE_P (elt))
22949 deducible = uses_deducible_template_parms (elt);
22950 else
22951 deducible = deducible_expression (elt);
22953 if (deducible)
22954 return true;
22956 return false;
22959 /* Returns true iff TYPE contains any deducible references to template
22960 parameters, as per 14.8.2.5. */
22962 static bool
22963 uses_deducible_template_parms (tree type)
22965 if (PACK_EXPANSION_P (type))
22966 type = PACK_EXPANSION_PATTERN (type);
22968 /* T
22969 cv-list T
22970 TT<T>
22971 TT<i>
22972 TT<> */
22973 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22974 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22975 return true;
22977 /* T*
22979 T&& */
22980 if (INDIRECT_TYPE_P (type))
22981 return uses_deducible_template_parms (TREE_TYPE (type));
22983 /* T[integer-constant ]
22984 type [i] */
22985 if (TREE_CODE (type) == ARRAY_TYPE)
22986 return (uses_deducible_template_parms (TREE_TYPE (type))
22987 || deducible_array_bound (TYPE_DOMAIN (type)));
22989 /* T type ::*
22990 type T::*
22991 T T::*
22992 T (type ::*)()
22993 type (T::*)()
22994 type (type ::*)(T)
22995 type (T::*)(T)
22996 T (type ::*)(T)
22997 T (T::*)()
22998 T (T::*)(T) */
22999 if (TYPE_PTRMEM_P (type))
23000 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
23001 || (uses_deducible_template_parms
23002 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
23004 /* template-name <T> (where template-name refers to a class template)
23005 template-name <i> (where template-name refers to a class template) */
23006 if (CLASS_TYPE_P (type)
23007 && CLASSTYPE_TEMPLATE_INFO (type)
23008 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
23009 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
23010 (CLASSTYPE_TI_ARGS (type)));
23012 /* type (T)
23014 T(T) */
23015 if (FUNC_OR_METHOD_TYPE_P (type))
23017 if (uses_deducible_template_parms (TREE_TYPE (type)))
23018 return true;
23019 tree parm = TYPE_ARG_TYPES (type);
23020 if (TREE_CODE (type) == METHOD_TYPE)
23021 parm = TREE_CHAIN (parm);
23022 for (; parm; parm = TREE_CHAIN (parm))
23023 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23024 return true;
23025 if (flag_noexcept_type
23026 && TYPE_RAISES_EXCEPTIONS (type)
23027 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23028 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23029 return true;
23032 return false;
23035 /* Subroutine of type_unification_real and unify_pack_expansion to
23036 handle unification of a single P/A pair. Parameters are as
23037 for those functions. */
23039 static int
23040 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23041 int subr, unification_kind_t strict,
23042 bool explain_p)
23044 tree arg_expr = NULL_TREE;
23045 int arg_strict;
23047 if (arg == error_mark_node || parm == error_mark_node)
23048 return unify_invalid (explain_p);
23049 if (arg == unknown_type_node)
23050 /* We can't deduce anything from this, but we might get all the
23051 template args from other function args. */
23052 return unify_success (explain_p);
23054 /* Implicit conversions (Clause 4) will be performed on a function
23055 argument to convert it to the type of the corresponding function
23056 parameter if the parameter type contains no template-parameters that
23057 participate in template argument deduction. */
23058 if (strict != DEDUCE_EXACT
23059 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23060 /* For function parameters with no deducible template parameters,
23061 just return. We'll check non-dependent conversions later. */
23062 return unify_success (explain_p);
23064 switch (strict)
23066 case DEDUCE_CALL:
23067 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23068 | UNIFY_ALLOW_MORE_CV_QUAL
23069 | UNIFY_ALLOW_DERIVED);
23070 break;
23072 case DEDUCE_CONV:
23073 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23074 break;
23076 case DEDUCE_EXACT:
23077 arg_strict = UNIFY_ALLOW_NONE;
23078 break;
23080 default:
23081 gcc_unreachable ();
23084 /* We only do these transformations if this is the top-level
23085 parameter_type_list in a call or declaration matching; in other
23086 situations (nested function declarators, template argument lists) we
23087 won't be comparing a type to an expression, and we don't do any type
23088 adjustments. */
23089 if (!subr)
23091 if (!TYPE_P (arg))
23093 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23094 if (type_unknown_p (arg))
23096 /* [temp.deduct.type] A template-argument can be
23097 deduced from a pointer to function or pointer
23098 to member function argument if the set of
23099 overloaded functions does not contain function
23100 templates and at most one of a set of
23101 overloaded functions provides a unique
23102 match. */
23103 resolve_overloaded_unification (tparms, targs, parm,
23104 arg, strict,
23105 arg_strict, explain_p);
23106 /* If a unique match was not found, this is a
23107 non-deduced context, so we still succeed. */
23108 return unify_success (explain_p);
23111 arg_expr = arg;
23112 arg = unlowered_expr_type (arg);
23113 if (arg == error_mark_node)
23114 return unify_invalid (explain_p);
23117 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23118 &parm, &arg, arg_expr);
23120 else
23121 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23122 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23123 return unify_template_argument_mismatch (explain_p, parm, arg);
23125 /* For deduction from an init-list we need the actual list. */
23126 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23127 arg = arg_expr;
23128 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23131 /* for_each_template_parm callback that always returns 0. */
23133 static int
23134 zero_r (tree, void *)
23136 return 0;
23139 /* for_each_template_parm any_fn callback to handle deduction of a template
23140 type argument from the type of an array bound. */
23142 static int
23143 array_deduction_r (tree t, void *data)
23145 tree_pair_p d = (tree_pair_p)data;
23146 tree &tparms = d->purpose;
23147 tree &targs = d->value;
23149 if (TREE_CODE (t) == ARRAY_TYPE)
23150 if (tree dom = TYPE_DOMAIN (t))
23151 if (tree max = TYPE_MAX_VALUE (dom))
23153 if (TREE_CODE (max) == MINUS_EXPR)
23154 max = TREE_OPERAND (max, 0);
23155 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23156 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23157 UNIFY_ALLOW_NONE, /*explain*/false);
23160 /* Keep walking. */
23161 return 0;
23164 /* Try to deduce any not-yet-deduced template type arguments from the type of
23165 an array bound. This is handled separately from unify because 14.8.2.5 says
23166 "The type of a type parameter is only deduced from an array bound if it is
23167 not otherwise deduced." */
23169 static void
23170 try_array_deduction (tree tparms, tree targs, tree parm)
23172 tree_pair_s data = { tparms, targs };
23173 hash_set<tree> visited;
23174 for_each_template_parm (parm, zero_r, &data, &visited,
23175 /*nondeduced*/false, array_deduction_r);
23178 /* Most parms like fn_type_unification.
23180 If SUBR is 1, we're being called recursively (to unify the
23181 arguments of a function or method parameter of a function
23182 template).
23184 CHECKS is a pointer to a vector of access checks encountered while
23185 substituting default template arguments. */
23187 static int
23188 type_unification_real (tree tparms,
23189 tree full_targs,
23190 tree xparms,
23191 const tree *xargs,
23192 unsigned int xnargs,
23193 int subr,
23194 unification_kind_t strict,
23195 vec<deferred_access_check, va_gc> **checks,
23196 bool explain_p)
23198 tree parm, arg;
23199 int i;
23200 int ntparms = TREE_VEC_LENGTH (tparms);
23201 int saw_undeduced = 0;
23202 tree parms;
23203 const tree *args;
23204 unsigned int nargs;
23205 unsigned int ia;
23207 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23208 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23209 gcc_assert (ntparms > 0);
23211 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23213 /* Reset the number of non-defaulted template arguments contained
23214 in TARGS. */
23215 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23217 again:
23218 parms = xparms;
23219 args = xargs;
23220 nargs = xnargs;
23222 /* Only fn_type_unification cares about terminal void. */
23223 if (nargs && args[nargs-1] == void_type_node)
23224 --nargs;
23226 ia = 0;
23227 while (parms && parms != void_list_node
23228 && ia < nargs)
23230 parm = TREE_VALUE (parms);
23232 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23233 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23234 /* For a function parameter pack that occurs at the end of the
23235 parameter-declaration-list, the type A of each remaining
23236 argument of the call is compared with the type P of the
23237 declarator-id of the function parameter pack. */
23238 break;
23240 parms = TREE_CHAIN (parms);
23242 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23243 /* For a function parameter pack that does not occur at the
23244 end of the parameter-declaration-list, the type of the
23245 parameter pack is a non-deduced context. */
23246 continue;
23248 arg = args[ia];
23249 ++ia;
23251 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23252 explain_p))
23253 return 1;
23256 if (parms
23257 && parms != void_list_node
23258 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23260 /* Unify the remaining arguments with the pack expansion type. */
23261 tree argvec;
23262 tree parmvec = make_tree_vec (1);
23264 /* Allocate a TREE_VEC and copy in all of the arguments */
23265 argvec = make_tree_vec (nargs - ia);
23266 for (i = 0; ia < nargs; ++ia, ++i)
23267 TREE_VEC_ELT (argvec, i) = args[ia];
23269 /* Copy the parameter into parmvec. */
23270 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23271 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23272 /*subr=*/subr, explain_p))
23273 return 1;
23275 /* Advance to the end of the list of parameters. */
23276 parms = TREE_CHAIN (parms);
23279 /* Fail if we've reached the end of the parm list, and more args
23280 are present, and the parm list isn't variadic. */
23281 if (ia < nargs && parms == void_list_node)
23282 return unify_too_many_arguments (explain_p, nargs, ia);
23283 /* Fail if parms are left and they don't have default values and
23284 they aren't all deduced as empty packs (c++/57397). This is
23285 consistent with sufficient_parms_p. */
23286 if (parms && parms != void_list_node
23287 && TREE_PURPOSE (parms) == NULL_TREE)
23289 unsigned int count = nargs;
23290 tree p = parms;
23291 bool type_pack_p;
23294 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23295 if (!type_pack_p)
23296 count++;
23297 p = TREE_CHAIN (p);
23299 while (p && p != void_list_node);
23300 if (count != nargs)
23301 return unify_too_few_arguments (explain_p, ia, count,
23302 type_pack_p);
23305 if (!subr)
23307 tsubst_flags_t complain = (explain_p
23308 ? tf_warning_or_error
23309 : tf_none);
23310 bool tried_array_deduction = (cxx_dialect < cxx17);
23312 for (i = 0; i < ntparms; i++)
23314 tree targ = TREE_VEC_ELT (targs, i);
23315 tree tparm = TREE_VEC_ELT (tparms, i);
23317 /* Clear the "incomplete" flags on all argument packs now so that
23318 substituting them into later default arguments works. */
23319 if (targ && ARGUMENT_PACK_P (targ))
23321 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23322 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23325 if (targ || tparm == error_mark_node)
23326 continue;
23327 tparm = TREE_VALUE (tparm);
23329 if (TREE_CODE (tparm) == TYPE_DECL
23330 && !tried_array_deduction)
23332 try_array_deduction (tparms, targs, xparms);
23333 tried_array_deduction = true;
23334 if (TREE_VEC_ELT (targs, i))
23335 continue;
23338 /* If this is an undeduced nontype parameter that depends on
23339 a type parameter, try another pass; its type may have been
23340 deduced from a later argument than the one from which
23341 this parameter can be deduced. */
23342 if (TREE_CODE (tparm) == PARM_DECL
23343 && !is_auto (TREE_TYPE (tparm))
23344 && uses_template_parms (TREE_TYPE (tparm))
23345 && saw_undeduced < 2)
23347 saw_undeduced = 1;
23348 continue;
23351 /* Core issue #226 (C++0x) [temp.deduct]:
23353 If a template argument has not been deduced, its
23354 default template argument, if any, is used.
23356 When we are in C++98 mode, TREE_PURPOSE will either
23357 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23358 to explicitly check cxx_dialect here. */
23359 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23360 /* OK, there is a default argument. Wait until after the
23361 conversion check to do substitution. */
23362 continue;
23364 /* If the type parameter is a parameter pack, then it will
23365 be deduced to an empty parameter pack. */
23366 if (template_parameter_pack_p (tparm))
23368 tree arg;
23370 if (TREE_CODE (tparm) == PARM_DECL)
23372 arg = make_node (NONTYPE_ARGUMENT_PACK);
23373 TREE_CONSTANT (arg) = 1;
23375 else
23376 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23378 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23380 TREE_VEC_ELT (targs, i) = arg;
23381 continue;
23384 return unify_parameter_deduction_failure (explain_p, tparm);
23387 /* During partial ordering, we deduce dependent template args. */
23388 bool any_dependent_targs = false;
23390 /* Now substitute into the default template arguments. */
23391 for (i = 0; i < ntparms; i++)
23393 tree targ = TREE_VEC_ELT (targs, i);
23394 tree tparm = TREE_VEC_ELT (tparms, i);
23396 if (targ)
23398 if (!any_dependent_targs && dependent_template_arg_p (targ))
23399 any_dependent_targs = true;
23400 continue;
23402 if (tparm == error_mark_node)
23403 continue;
23405 tree parm = TREE_VALUE (tparm);
23406 tree arg = TREE_PURPOSE (tparm);
23407 reopen_deferring_access_checks (*checks);
23408 location_t save_loc = input_location;
23409 if (DECL_P (parm))
23410 input_location = DECL_SOURCE_LOCATION (parm);
23412 if (saw_undeduced == 1
23413 && TREE_CODE (parm) == PARM_DECL
23414 && !is_auto (TREE_TYPE (parm))
23415 && uses_template_parms (TREE_TYPE (parm)))
23417 /* The type of this non-type parameter depends on undeduced
23418 parameters. Don't try to use its default argument yet,
23419 since we might deduce an argument for it on the next pass,
23420 but do check whether the arguments we already have cause
23421 substitution failure, so that that happens before we try
23422 later default arguments (78489). */
23423 ++processing_template_decl;
23424 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23425 NULL_TREE);
23426 --processing_template_decl;
23427 if (type == error_mark_node)
23428 arg = error_mark_node;
23429 else
23430 arg = NULL_TREE;
23432 else
23434 /* Even if the call is happening in template context, getting
23435 here means it's non-dependent, and a default argument is
23436 considered a separate definition under [temp.decls], so we can
23437 do this substitution without processing_template_decl. This
23438 is important if the default argument contains something that
23439 might be instantiation-dependent like access (87480). */
23440 processing_template_decl_sentinel s (!any_dependent_targs);
23441 tree substed = NULL_TREE;
23442 if (saw_undeduced == 1 && !any_dependent_targs)
23444 /* First instatiate in template context, in case we still
23445 depend on undeduced template parameters. */
23446 ++processing_template_decl;
23447 substed = tsubst_template_arg (arg, full_targs, complain,
23448 NULL_TREE);
23449 --processing_template_decl;
23450 if (substed != error_mark_node
23451 && !uses_template_parms (substed))
23452 /* We replaced all the tparms, substitute again out of
23453 template context. */
23454 substed = NULL_TREE;
23456 if (!substed)
23457 substed = tsubst_template_arg (arg, full_targs, complain,
23458 NULL_TREE);
23460 if (!uses_template_parms (substed))
23461 arg = convert_template_argument (parm, substed, full_targs,
23462 complain, i, NULL_TREE);
23463 else if (saw_undeduced == 1)
23464 arg = NULL_TREE;
23465 else if (!any_dependent_targs)
23466 arg = error_mark_node;
23469 input_location = save_loc;
23470 *checks = get_deferred_access_checks ();
23471 pop_deferring_access_checks ();
23473 if (arg == error_mark_node)
23474 return 1;
23475 else if (arg)
23477 TREE_VEC_ELT (targs, i) = arg;
23478 /* The position of the first default template argument,
23479 is also the number of non-defaulted arguments in TARGS.
23480 Record that. */
23481 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23482 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23486 if (saw_undeduced++ == 1)
23487 goto again;
23490 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23491 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23493 return unify_success (explain_p);
23496 /* Subroutine of type_unification_real. Args are like the variables
23497 at the call site. ARG is an overloaded function (or template-id);
23498 we try deducing template args from each of the overloads, and if
23499 only one succeeds, we go with that. Modifies TARGS and returns
23500 true on success. */
23502 static bool
23503 resolve_overloaded_unification (tree tparms,
23504 tree targs,
23505 tree parm,
23506 tree arg,
23507 unification_kind_t strict,
23508 int sub_strict,
23509 bool explain_p)
23511 tree tempargs = copy_node (targs);
23512 int good = 0;
23513 tree goodfn = NULL_TREE;
23514 bool addr_p;
23516 if (TREE_CODE (arg) == ADDR_EXPR)
23518 arg = TREE_OPERAND (arg, 0);
23519 addr_p = true;
23521 else
23522 addr_p = false;
23524 if (TREE_CODE (arg) == COMPONENT_REF)
23525 /* Handle `&x' where `x' is some static or non-static member
23526 function name. */
23527 arg = TREE_OPERAND (arg, 1);
23529 if (TREE_CODE (arg) == OFFSET_REF)
23530 arg = TREE_OPERAND (arg, 1);
23532 /* Strip baselink information. */
23533 if (BASELINK_P (arg))
23534 arg = BASELINK_FUNCTIONS (arg);
23536 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23538 /* If we got some explicit template args, we need to plug them into
23539 the affected templates before we try to unify, in case the
23540 explicit args will completely resolve the templates in question. */
23542 int ok = 0;
23543 tree expl_subargs = TREE_OPERAND (arg, 1);
23544 arg = TREE_OPERAND (arg, 0);
23546 for (lkp_iterator iter (arg); iter; ++iter)
23548 tree fn = *iter;
23549 tree subargs, elem;
23551 if (TREE_CODE (fn) != TEMPLATE_DECL)
23552 continue;
23554 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23555 expl_subargs, NULL_TREE, tf_none);
23556 if (subargs != error_mark_node
23557 && !any_dependent_template_arguments_p (subargs))
23559 fn = instantiate_template (fn, subargs, tf_none);
23560 if (!constraints_satisfied_p (fn))
23561 continue;
23562 if (undeduced_auto_decl (fn))
23564 /* Instantiate the function to deduce its return type. */
23565 ++function_depth;
23566 instantiate_decl (fn, /*defer*/false, /*class*/false);
23567 --function_depth;
23570 if (flag_noexcept_type)
23571 maybe_instantiate_noexcept (fn, tf_none);
23573 elem = TREE_TYPE (fn);
23574 if (try_one_overload (tparms, targs, tempargs, parm,
23575 elem, strict, sub_strict, addr_p, explain_p)
23576 && (!goodfn || !same_type_p (goodfn, elem)))
23578 goodfn = elem;
23579 ++good;
23582 else if (subargs)
23583 ++ok;
23585 /* If no templates (or more than one) are fully resolved by the
23586 explicit arguments, this template-id is a non-deduced context; it
23587 could still be OK if we deduce all template arguments for the
23588 enclosing call through other arguments. */
23589 if (good != 1)
23590 good = ok;
23592 else if (!OVL_P (arg))
23593 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23594 -- but the deduction does not succeed because the expression is
23595 not just the function on its own. */
23596 return false;
23597 else
23598 for (lkp_iterator iter (arg); iter; ++iter)
23600 tree fn = *iter;
23601 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23602 strict, sub_strict, addr_p, explain_p)
23603 && (!goodfn || !decls_match (goodfn, fn)))
23605 goodfn = fn;
23606 ++good;
23610 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23611 to function or pointer to member function argument if the set of
23612 overloaded functions does not contain function templates and at most
23613 one of a set of overloaded functions provides a unique match.
23615 So if we found multiple possibilities, we return success but don't
23616 deduce anything. */
23618 if (good == 1)
23620 int i = TREE_VEC_LENGTH (targs);
23621 for (; i--; )
23622 if (TREE_VEC_ELT (tempargs, i))
23624 tree old = TREE_VEC_ELT (targs, i);
23625 tree new_ = TREE_VEC_ELT (tempargs, i);
23626 if (new_ && old && ARGUMENT_PACK_P (old)
23627 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23628 /* Don't forget explicit template arguments in a pack. */
23629 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23630 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23631 TREE_VEC_ELT (targs, i) = new_;
23634 if (good)
23635 return true;
23637 return false;
23640 /* Core DR 115: In contexts where deduction is done and fails, or in
23641 contexts where deduction is not done, if a template argument list is
23642 specified and it, along with any default template arguments, identifies
23643 a single function template specialization, then the template-id is an
23644 lvalue for the function template specialization. */
23646 tree
23647 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23649 tree expr, offset, baselink;
23650 bool addr;
23652 if (!type_unknown_p (orig_expr))
23653 return orig_expr;
23655 expr = orig_expr;
23656 addr = false;
23657 offset = NULL_TREE;
23658 baselink = NULL_TREE;
23660 if (TREE_CODE (expr) == ADDR_EXPR)
23662 expr = TREE_OPERAND (expr, 0);
23663 addr = true;
23665 if (TREE_CODE (expr) == OFFSET_REF)
23667 offset = expr;
23668 expr = TREE_OPERAND (expr, 1);
23670 if (BASELINK_P (expr))
23672 baselink = expr;
23673 expr = BASELINK_FUNCTIONS (expr);
23676 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23678 int good = 0;
23679 tree goodfn = NULL_TREE;
23681 /* If we got some explicit template args, we need to plug them into
23682 the affected templates before we try to unify, in case the
23683 explicit args will completely resolve the templates in question. */
23685 tree expl_subargs = TREE_OPERAND (expr, 1);
23686 tree arg = TREE_OPERAND (expr, 0);
23687 tree badfn = NULL_TREE;
23688 tree badargs = NULL_TREE;
23690 for (lkp_iterator iter (arg); iter; ++iter)
23692 tree fn = *iter;
23693 tree subargs, elem;
23695 if (TREE_CODE (fn) != TEMPLATE_DECL)
23696 continue;
23698 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23699 expl_subargs, NULL_TREE, tf_none);
23700 if (subargs != error_mark_node
23701 && !any_dependent_template_arguments_p (subargs))
23703 elem = instantiate_template (fn, subargs, tf_none);
23704 if (elem == error_mark_node)
23706 badfn = fn;
23707 badargs = subargs;
23709 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23710 && constraints_satisfied_p (elem))
23712 goodfn = elem;
23713 ++good;
23717 if (good == 1)
23719 mark_used (goodfn);
23720 expr = goodfn;
23721 if (baselink)
23722 expr = build_baselink (BASELINK_BINFO (baselink),
23723 BASELINK_ACCESS_BINFO (baselink),
23724 expr, BASELINK_OPTYPE (baselink));
23725 if (offset)
23727 tree base
23728 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23729 expr = build_offset_ref (base, expr, addr, complain);
23731 if (addr)
23732 expr = cp_build_addr_expr (expr, complain);
23733 return expr;
23735 else if (good == 0 && badargs && (complain & tf_error))
23736 /* There were no good options and at least one bad one, so let the
23737 user know what the problem is. */
23738 instantiate_template (badfn, badargs, complain);
23740 return orig_expr;
23743 /* As above, but error out if the expression remains overloaded. */
23745 tree
23746 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23748 exp = resolve_nondeduced_context (exp, complain);
23749 if (type_unknown_p (exp))
23751 if (complain & tf_error)
23752 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23753 return error_mark_node;
23755 return exp;
23758 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23759 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23760 different overloads deduce different arguments for a given parm.
23761 ADDR_P is true if the expression for which deduction is being
23762 performed was of the form "& fn" rather than simply "fn".
23764 Returns 1 on success. */
23766 static int
23767 try_one_overload (tree tparms,
23768 tree orig_targs,
23769 tree targs,
23770 tree parm,
23771 tree arg,
23772 unification_kind_t strict,
23773 int sub_strict,
23774 bool addr_p,
23775 bool explain_p)
23777 int nargs;
23778 tree tempargs;
23779 int i;
23781 if (arg == error_mark_node)
23782 return 0;
23784 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23785 to function or pointer to member function argument if the set of
23786 overloaded functions does not contain function templates and at most
23787 one of a set of overloaded functions provides a unique match.
23789 So if this is a template, just return success. */
23791 if (uses_template_parms (arg))
23792 return 1;
23794 if (TREE_CODE (arg) == METHOD_TYPE)
23795 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23796 else if (addr_p)
23797 arg = build_pointer_type (arg);
23799 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23800 &parm, &arg, NULL_TREE);
23802 /* We don't copy orig_targs for this because if we have already deduced
23803 some template args from previous args, unify would complain when we
23804 try to deduce a template parameter for the same argument, even though
23805 there isn't really a conflict. */
23806 nargs = TREE_VEC_LENGTH (targs);
23807 tempargs = make_tree_vec (nargs);
23809 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23810 return 0;
23812 /* First make sure we didn't deduce anything that conflicts with
23813 explicitly specified args. */
23814 for (i = nargs; i--; )
23816 tree elt = TREE_VEC_ELT (tempargs, i);
23817 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23819 if (!elt)
23820 /*NOP*/;
23821 else if (uses_template_parms (elt))
23822 /* Since we're unifying against ourselves, we will fill in
23823 template args used in the function parm list with our own
23824 template parms. Discard them. */
23825 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23826 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23828 /* Check that the argument at each index of the deduced argument pack
23829 is equivalent to the corresponding explicitly specified argument.
23830 We may have deduced more arguments than were explicitly specified,
23831 and that's OK. */
23833 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23834 that's wrong if we deduce the same argument pack from multiple
23835 function arguments: it's only incomplete the first time. */
23837 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23838 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23840 if (TREE_VEC_LENGTH (deduced_pack)
23841 < TREE_VEC_LENGTH (explicit_pack))
23842 return 0;
23844 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23845 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23846 TREE_VEC_ELT (deduced_pack, j)))
23847 return 0;
23849 else if (oldelt && !template_args_equal (oldelt, elt))
23850 return 0;
23853 for (i = nargs; i--; )
23855 tree elt = TREE_VEC_ELT (tempargs, i);
23857 if (elt)
23858 TREE_VEC_ELT (targs, i) = elt;
23861 return 1;
23864 /* PARM is a template class (perhaps with unbound template
23865 parameters). ARG is a fully instantiated type. If ARG can be
23866 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23867 TARGS are as for unify. */
23869 static tree
23870 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23871 bool explain_p)
23873 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23874 return NULL_TREE;
23875 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23876 /* Matches anything. */;
23877 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23878 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23879 return NULL_TREE;
23881 /* We need to make a new template argument vector for the call to
23882 unify. If we used TARGS, we'd clutter it up with the result of
23883 the attempted unification, even if this class didn't work out.
23884 We also don't want to commit ourselves to all the unifications
23885 we've already done, since unification is supposed to be done on
23886 an argument-by-argument basis. In other words, consider the
23887 following pathological case:
23889 template <int I, int J, int K>
23890 struct S {};
23892 template <int I, int J>
23893 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23895 template <int I, int J, int K>
23896 void f(S<I, J, K>, S<I, I, I>);
23898 void g() {
23899 S<0, 0, 0> s0;
23900 S<0, 1, 2> s2;
23902 f(s0, s2);
23905 Now, by the time we consider the unification involving `s2', we
23906 already know that we must have `f<0, 0, 0>'. But, even though
23907 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23908 because there are two ways to unify base classes of S<0, 1, 2>
23909 with S<I, I, I>. If we kept the already deduced knowledge, we
23910 would reject the possibility I=1. */
23911 targs = copy_template_args (targs);
23912 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23913 targ = NULL_TREE;
23915 int err;
23916 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23917 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23918 else
23919 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23920 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23922 return err ? NULL_TREE : arg;
23925 /* Given a template type PARM and a class type ARG, find the unique
23926 base type in ARG that is an instance of PARM. We do not examine
23927 ARG itself; only its base-classes. If there is not exactly one
23928 appropriate base class, return NULL_TREE. PARM may be the type of
23929 a partial specialization, as well as a plain template type. Used
23930 by unify. */
23932 static enum template_base_result
23933 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23934 bool explain_p, tree *result)
23936 tree rval = NULL_TREE;
23937 tree binfo;
23939 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23941 binfo = TYPE_BINFO (complete_type (arg));
23942 if (!binfo)
23944 /* The type could not be completed. */
23945 *result = NULL_TREE;
23946 return tbr_incomplete_type;
23949 /* Walk in inheritance graph order. The search order is not
23950 important, and this avoids multiple walks of virtual bases. */
23951 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23953 tree r = try_class_unification (tparms, targs, parm,
23954 BINFO_TYPE (binfo), explain_p);
23956 if (r)
23958 /* If there is more than one satisfactory baseclass, then:
23960 [temp.deduct.call]
23962 If they yield more than one possible deduced A, the type
23963 deduction fails.
23965 applies. */
23966 if (rval && !same_type_p (r, rval))
23968 /* [temp.deduct.call]/4.3: If there is a class C that is a
23969 (direct or indirect) base class of D and derived (directly or
23970 indirectly) from a class B and that would be a valid deduced
23971 A, the deduced A cannot be B or pointer to B, respectively. */
23972 if (DERIVED_FROM_P (r, rval))
23973 /* Ignore r. */
23974 continue;
23975 else if (DERIVED_FROM_P (rval, r))
23976 /* Ignore rval. */;
23977 else
23979 *result = NULL_TREE;
23980 return tbr_ambiguous_baseclass;
23984 rval = r;
23988 *result = rval;
23989 return tbr_success;
23992 /* Returns the level of DECL, which declares a template parameter. */
23994 static int
23995 template_decl_level (tree decl)
23997 switch (TREE_CODE (decl))
23999 case TYPE_DECL:
24000 case TEMPLATE_DECL:
24001 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
24003 case PARM_DECL:
24004 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
24006 default:
24007 gcc_unreachable ();
24009 return 0;
24012 /* Decide whether ARG can be unified with PARM, considering only the
24013 cv-qualifiers of each type, given STRICT as documented for unify.
24014 Returns nonzero iff the unification is OK on that basis. */
24016 static int
24017 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24019 int arg_quals = cp_type_quals (arg);
24020 int parm_quals = cp_type_quals (parm);
24022 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24023 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24025 /* Although a CVR qualifier is ignored when being applied to a
24026 substituted template parameter ([8.3.2]/1 for example), that
24027 does not allow us to unify "const T" with "int&" because both
24028 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24029 It is ok when we're allowing additional CV qualifiers
24030 at the outer level [14.8.2.1]/3,1st bullet. */
24031 if ((TYPE_REF_P (arg)
24032 || FUNC_OR_METHOD_TYPE_P (arg))
24033 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24034 return 0;
24036 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24037 && (parm_quals & TYPE_QUAL_RESTRICT))
24038 return 0;
24041 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24042 && (arg_quals & parm_quals) != parm_quals)
24043 return 0;
24045 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24046 && (parm_quals & arg_quals) != arg_quals)
24047 return 0;
24049 return 1;
24052 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24053 void
24054 template_parm_level_and_index (tree parm, int* level, int* index)
24056 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24057 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24058 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24060 *index = TEMPLATE_TYPE_IDX (parm);
24061 *level = TEMPLATE_TYPE_LEVEL (parm);
24063 else
24065 *index = TEMPLATE_PARM_IDX (parm);
24066 *level = TEMPLATE_PARM_LEVEL (parm);
24070 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24071 do { \
24072 if (unify (TP, TA, P, A, S, EP)) \
24073 return 1; \
24074 } while (0)
24076 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24077 expansion at the end of PACKED_PARMS. Returns 0 if the type
24078 deduction succeeds, 1 otherwise. STRICT is the same as in
24079 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24080 function call argument list. We'll need to adjust the arguments to make them
24081 types. SUBR tells us if this is from a recursive call to
24082 type_unification_real, or for comparing two template argument
24083 lists. */
24085 static int
24086 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24087 tree packed_args, unification_kind_t strict,
24088 bool subr, bool explain_p)
24090 tree parm
24091 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24092 tree pattern = PACK_EXPANSION_PATTERN (parm);
24093 tree pack, packs = NULL_TREE;
24094 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24096 /* Add in any args remembered from an earlier partial instantiation. */
24097 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24098 int levels = TMPL_ARGS_DEPTH (targs);
24100 packed_args = expand_template_argument_pack (packed_args);
24102 int len = TREE_VEC_LENGTH (packed_args);
24104 /* Determine the parameter packs we will be deducing from the
24105 pattern, and record their current deductions. */
24106 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24107 pack; pack = TREE_CHAIN (pack))
24109 tree parm_pack = TREE_VALUE (pack);
24110 int idx, level;
24112 /* Only template parameter packs can be deduced, not e.g. function
24113 parameter packs or __bases or __integer_pack. */
24114 if (!TEMPLATE_PARM_P (parm_pack))
24115 continue;
24117 /* Determine the index and level of this parameter pack. */
24118 template_parm_level_and_index (parm_pack, &level, &idx);
24119 if (level > levels)
24120 continue;
24122 /* Keep track of the parameter packs and their corresponding
24123 argument packs. */
24124 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24125 TREE_TYPE (packs) = make_tree_vec (len - start);
24128 /* Loop through all of the arguments that have not yet been
24129 unified and unify each with the pattern. */
24130 for (i = start; i < len; i++)
24132 tree parm;
24133 bool any_explicit = false;
24134 tree arg = TREE_VEC_ELT (packed_args, i);
24136 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24137 or the element of its argument pack at the current index if
24138 this argument was explicitly specified. */
24139 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24141 int idx, level;
24142 tree arg, pargs;
24143 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24145 arg = NULL_TREE;
24146 if (TREE_VALUE (pack)
24147 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24148 && (i - start < TREE_VEC_LENGTH (pargs)))
24150 any_explicit = true;
24151 arg = TREE_VEC_ELT (pargs, i - start);
24153 TMPL_ARG (targs, level, idx) = arg;
24156 /* If we had explicit template arguments, substitute them into the
24157 pattern before deduction. */
24158 if (any_explicit)
24160 /* Some arguments might still be unspecified or dependent. */
24161 bool dependent;
24162 ++processing_template_decl;
24163 dependent = any_dependent_template_arguments_p (targs);
24164 if (!dependent)
24165 --processing_template_decl;
24166 parm = tsubst (pattern, targs,
24167 explain_p ? tf_warning_or_error : tf_none,
24168 NULL_TREE);
24169 if (dependent)
24170 --processing_template_decl;
24171 if (parm == error_mark_node)
24172 return 1;
24174 else
24175 parm = pattern;
24177 /* Unify the pattern with the current argument. */
24178 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24179 explain_p))
24180 return 1;
24182 /* For each parameter pack, collect the deduced value. */
24183 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24185 int idx, level;
24186 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24188 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24189 TMPL_ARG (targs, level, idx);
24193 /* Verify that the results of unification with the parameter packs
24194 produce results consistent with what we've seen before, and make
24195 the deduced argument packs available. */
24196 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24198 tree old_pack = TREE_VALUE (pack);
24199 tree new_args = TREE_TYPE (pack);
24200 int i, len = TREE_VEC_LENGTH (new_args);
24201 int idx, level;
24202 bool nondeduced_p = false;
24204 /* By default keep the original deduced argument pack.
24205 If necessary, more specific code is going to update the
24206 resulting deduced argument later down in this function. */
24207 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24208 TMPL_ARG (targs, level, idx) = old_pack;
24210 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24211 actually deduce anything. */
24212 for (i = 0; i < len && !nondeduced_p; ++i)
24213 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24214 nondeduced_p = true;
24215 if (nondeduced_p)
24216 continue;
24218 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24220 /* If we had fewer function args than explicit template args,
24221 just use the explicits. */
24222 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24223 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24224 if (len < explicit_len)
24225 new_args = explicit_args;
24228 if (!old_pack)
24230 tree result;
24231 /* Build the deduced *_ARGUMENT_PACK. */
24232 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24234 result = make_node (NONTYPE_ARGUMENT_PACK);
24235 TREE_CONSTANT (result) = 1;
24237 else
24238 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24240 ARGUMENT_PACK_ARGS (result) = new_args;
24242 /* Note the deduced argument packs for this parameter
24243 pack. */
24244 TMPL_ARG (targs, level, idx) = result;
24246 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24247 && (ARGUMENT_PACK_ARGS (old_pack)
24248 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24250 /* We only had the explicitly-provided arguments before, but
24251 now we have a complete set of arguments. */
24252 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24254 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24255 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24256 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24258 else
24260 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24261 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24262 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24263 /* During template argument deduction for the aggregate deduction
24264 candidate, the number of elements in a trailing parameter pack
24265 is only deduced from the number of remaining function
24266 arguments if it is not otherwise deduced. */
24267 if (cxx_dialect >= cxx20
24268 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24269 /* FIXME This isn't set properly for partial instantiations. */
24270 && TPARMS_PRIMARY_TEMPLATE (tparms)
24271 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24272 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24273 if (!comp_template_args (old_args, new_args,
24274 &bad_old_arg, &bad_new_arg))
24275 /* Inconsistent unification of this parameter pack. */
24276 return unify_parameter_pack_inconsistent (explain_p,
24277 bad_old_arg,
24278 bad_new_arg);
24282 return unify_success (explain_p);
24285 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24286 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24287 parameters and return value are as for unify. */
24289 static int
24290 unify_array_domain (tree tparms, tree targs,
24291 tree parm_dom, tree arg_dom,
24292 bool explain_p)
24294 tree parm_max;
24295 tree arg_max;
24296 bool parm_cst;
24297 bool arg_cst;
24299 /* Our representation of array types uses "N - 1" as the
24300 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24301 not an integer constant. We cannot unify arbitrarily
24302 complex expressions, so we eliminate the MINUS_EXPRs
24303 here. */
24304 parm_max = TYPE_MAX_VALUE (parm_dom);
24305 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24306 if (!parm_cst)
24308 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24309 parm_max = TREE_OPERAND (parm_max, 0);
24311 arg_max = TYPE_MAX_VALUE (arg_dom);
24312 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24313 if (!arg_cst)
24315 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24316 trying to unify the type of a variable with the type
24317 of a template parameter. For example:
24319 template <unsigned int N>
24320 void f (char (&) [N]);
24321 int g();
24322 void h(int i) {
24323 char a[g(i)];
24324 f(a);
24327 Here, the type of the ARG will be "int [g(i)]", and
24328 may be a SAVE_EXPR, etc. */
24329 if (TREE_CODE (arg_max) != MINUS_EXPR)
24330 return unify_vla_arg (explain_p, arg_dom);
24331 arg_max = TREE_OPERAND (arg_max, 0);
24334 /* If only one of the bounds used a MINUS_EXPR, compensate
24335 by adding one to the other bound. */
24336 if (parm_cst && !arg_cst)
24337 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24338 integer_type_node,
24339 parm_max,
24340 integer_one_node);
24341 else if (arg_cst && !parm_cst)
24342 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24343 integer_type_node,
24344 arg_max,
24345 integer_one_node);
24347 return unify (tparms, targs, parm_max, arg_max,
24348 UNIFY_ALLOW_INTEGER, explain_p);
24351 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24353 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24355 static pa_kind_t
24356 pa_kind (tree t)
24358 if (PACK_EXPANSION_P (t))
24359 t = PACK_EXPANSION_PATTERN (t);
24360 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24361 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24362 || DECL_TYPE_TEMPLATE_P (t))
24363 return pa_tmpl;
24364 else if (TYPE_P (t))
24365 return pa_type;
24366 else
24367 return pa_expr;
24370 /* Deduce the value of template parameters. TPARMS is the (innermost)
24371 set of template parameters to a template. TARGS is the bindings
24372 for those template parameters, as determined thus far; TARGS may
24373 include template arguments for outer levels of template parameters
24374 as well. PARM is a parameter to a template function, or a
24375 subcomponent of that parameter; ARG is the corresponding argument.
24376 This function attempts to match PARM with ARG in a manner
24377 consistent with the existing assignments in TARGS. If more values
24378 are deduced, then TARGS is updated.
24380 Returns 0 if the type deduction succeeds, 1 otherwise. The
24381 parameter STRICT is a bitwise or of the following flags:
24383 UNIFY_ALLOW_NONE:
24384 Require an exact match between PARM and ARG.
24385 UNIFY_ALLOW_MORE_CV_QUAL:
24386 Allow the deduced ARG to be more cv-qualified (by qualification
24387 conversion) than ARG.
24388 UNIFY_ALLOW_LESS_CV_QUAL:
24389 Allow the deduced ARG to be less cv-qualified than ARG.
24390 UNIFY_ALLOW_DERIVED:
24391 Allow the deduced ARG to be a template base class of ARG,
24392 or a pointer to a template base class of the type pointed to by
24393 ARG.
24394 UNIFY_ALLOW_INTEGER:
24395 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24396 case for more information.
24397 UNIFY_ALLOW_OUTER_LEVEL:
24398 This is the outermost level of a deduction. Used to determine validity
24399 of qualification conversions. A valid qualification conversion must
24400 have const qualified pointers leading up to the inner type which
24401 requires additional CV quals, except at the outer level, where const
24402 is not required [conv.qual]. It would be normal to set this flag in
24403 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24404 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24405 This is the outermost level of a deduction, and PARM can be more CV
24406 qualified at this point.
24407 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24408 This is the outermost level of a deduction, and PARM can be less CV
24409 qualified at this point. */
24411 static int
24412 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24413 bool explain_p)
24415 int idx;
24416 tree targ;
24417 tree tparm;
24418 int strict_in = strict;
24419 tsubst_flags_t complain = (explain_p
24420 ? tf_warning_or_error
24421 : tf_none);
24423 /* I don't think this will do the right thing with respect to types.
24424 But the only case I've seen it in so far has been array bounds, where
24425 signedness is the only information lost, and I think that will be
24426 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24427 finish_id_expression_1, and are also OK. */
24428 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24429 parm = TREE_OPERAND (parm, 0);
24431 if (arg == error_mark_node)
24432 return unify_invalid (explain_p);
24433 if (arg == unknown_type_node
24434 || arg == init_list_type_node)
24435 /* We can't deduce anything from this, but we might get all the
24436 template args from other function args. */
24437 return unify_success (explain_p);
24439 if (parm == any_targ_node || arg == any_targ_node)
24440 return unify_success (explain_p);
24442 /* If PARM uses template parameters, then we can't bail out here,
24443 even if ARG == PARM, since we won't record unifications for the
24444 template parameters. We might need them if we're trying to
24445 figure out which of two things is more specialized. */
24446 if (arg == parm && !uses_template_parms (parm))
24447 return unify_success (explain_p);
24449 /* Handle init lists early, so the rest of the function can assume
24450 we're dealing with a type. */
24451 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24453 tree elttype;
24454 tree orig_parm = parm;
24456 if (!is_std_init_list (parm)
24457 && TREE_CODE (parm) != ARRAY_TYPE)
24458 /* We can only deduce from an initializer list argument if the
24459 parameter is std::initializer_list or an array; otherwise this
24460 is a non-deduced context. */
24461 return unify_success (explain_p);
24463 if (TREE_CODE (parm) == ARRAY_TYPE)
24464 elttype = TREE_TYPE (parm);
24465 else
24467 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24468 /* Deduction is defined in terms of a single type, so just punt
24469 on the (bizarre) std::initializer_list<T...>. */
24470 if (PACK_EXPANSION_P (elttype))
24471 return unify_success (explain_p);
24474 if (strict != DEDUCE_EXACT
24475 && TYPE_P (elttype)
24476 && !uses_deducible_template_parms (elttype))
24477 /* If ELTTYPE has no deducible template parms, skip deduction from
24478 the list elements. */;
24479 else
24480 for (auto &e: CONSTRUCTOR_ELTS (arg))
24482 tree elt = e.value;
24483 int elt_strict = strict;
24485 if (elt == error_mark_node)
24486 return unify_invalid (explain_p);
24488 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24490 tree type = TREE_TYPE (elt);
24491 if (type == error_mark_node)
24492 return unify_invalid (explain_p);
24493 /* It should only be possible to get here for a call. */
24494 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24495 elt_strict |= maybe_adjust_types_for_deduction
24496 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24497 elt = type;
24500 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24501 explain_p);
24504 if (TREE_CODE (parm) == ARRAY_TYPE
24505 && deducible_array_bound (TYPE_DOMAIN (parm)))
24507 /* Also deduce from the length of the initializer list. */
24508 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24509 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24510 if (idx == error_mark_node)
24511 return unify_invalid (explain_p);
24512 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24513 idx, explain_p);
24516 /* If the std::initializer_list<T> deduction worked, replace the
24517 deduced A with std::initializer_list<A>. */
24518 if (orig_parm != parm)
24520 idx = TEMPLATE_TYPE_IDX (orig_parm);
24521 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24522 targ = listify (targ);
24523 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24525 return unify_success (explain_p);
24528 /* If parm and arg aren't the same kind of thing (template, type, or
24529 expression), fail early. */
24530 if (pa_kind (parm) != pa_kind (arg))
24531 return unify_invalid (explain_p);
24533 /* Immediately reject some pairs that won't unify because of
24534 cv-qualification mismatches. */
24535 if (TREE_CODE (arg) == TREE_CODE (parm)
24536 && TYPE_P (arg)
24537 /* It is the elements of the array which hold the cv quals of an array
24538 type, and the elements might be template type parms. We'll check
24539 when we recurse. */
24540 && TREE_CODE (arg) != ARRAY_TYPE
24541 /* We check the cv-qualifiers when unifying with template type
24542 parameters below. We want to allow ARG `const T' to unify with
24543 PARM `T' for example, when computing which of two templates
24544 is more specialized, for example. */
24545 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24546 && !check_cv_quals_for_unify (strict_in, arg, parm))
24547 return unify_cv_qual_mismatch (explain_p, parm, arg);
24549 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24550 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24551 && !FUNC_OR_METHOD_TYPE_P (parm))
24552 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24553 /* PMFs recurse at the same level, so don't strip this yet. */
24554 if (!TYPE_PTRMEMFUNC_P (parm))
24555 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24556 strict &= ~UNIFY_ALLOW_DERIVED;
24557 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24558 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24560 switch (TREE_CODE (parm))
24562 case TYPENAME_TYPE:
24563 case SCOPE_REF:
24564 case UNBOUND_CLASS_TEMPLATE:
24565 /* In a type which contains a nested-name-specifier, template
24566 argument values cannot be deduced for template parameters used
24567 within the nested-name-specifier. */
24568 return unify_success (explain_p);
24570 case TEMPLATE_TYPE_PARM:
24571 case TEMPLATE_TEMPLATE_PARM:
24572 case BOUND_TEMPLATE_TEMPLATE_PARM:
24573 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24574 if (error_operand_p (tparm))
24575 return unify_invalid (explain_p);
24577 if (TEMPLATE_TYPE_LEVEL (parm)
24578 != template_decl_level (tparm))
24579 /* The PARM is not one we're trying to unify. Just check
24580 to see if it matches ARG. */
24582 if (TREE_CODE (arg) == TREE_CODE (parm)
24583 && (is_auto (parm) ? is_auto (arg)
24584 : same_type_p (parm, arg)))
24585 return unify_success (explain_p);
24586 else
24587 return unify_type_mismatch (explain_p, parm, arg);
24589 idx = TEMPLATE_TYPE_IDX (parm);
24590 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24591 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24592 if (error_operand_p (tparm))
24593 return unify_invalid (explain_p);
24595 /* Check for mixed types and values. */
24596 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24597 && TREE_CODE (tparm) != TYPE_DECL)
24598 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24599 && TREE_CODE (tparm) != TEMPLATE_DECL))
24600 gcc_unreachable ();
24602 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24604 if ((strict_in & UNIFY_ALLOW_DERIVED)
24605 && CLASS_TYPE_P (arg))
24607 /* First try to match ARG directly. */
24608 tree t = try_class_unification (tparms, targs, parm, arg,
24609 explain_p);
24610 if (!t)
24612 /* Otherwise, look for a suitable base of ARG, as below. */
24613 enum template_base_result r;
24614 r = get_template_base (tparms, targs, parm, arg,
24615 explain_p, &t);
24616 if (!t)
24617 return unify_no_common_base (explain_p, r, parm, arg);
24618 arg = t;
24621 /* ARG must be constructed from a template class or a template
24622 template parameter. */
24623 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24624 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24625 return unify_template_deduction_failure (explain_p, parm, arg);
24627 /* Deduce arguments T, i from TT<T> or TT<i>. */
24628 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24629 return 1;
24631 arg = TYPE_TI_TEMPLATE (arg);
24632 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24633 /* If the template is a template template parameter, use the
24634 TEMPLATE_TEMPLATE_PARM for matching. */
24635 arg = TREE_TYPE (arg);
24637 /* Fall through to deduce template name. */
24640 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24641 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24643 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24645 /* Simple cases: Value already set, does match or doesn't. */
24646 if (targ != NULL_TREE && template_args_equal (targ, arg))
24647 return unify_success (explain_p);
24648 else if (targ)
24649 return unify_inconsistency (explain_p, parm, targ, arg);
24651 else
24653 /* If PARM is `const T' and ARG is only `int', we don't have
24654 a match unless we are allowing additional qualification.
24655 If ARG is `const int' and PARM is just `T' that's OK;
24656 that binds `const int' to `T'. */
24657 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24658 arg, parm))
24659 return unify_cv_qual_mismatch (explain_p, parm, arg);
24661 /* Consider the case where ARG is `const volatile int' and
24662 PARM is `const T'. Then, T should be `volatile int'. */
24663 arg = cp_build_qualified_type
24664 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24665 if (arg == error_mark_node)
24666 return unify_invalid (explain_p);
24668 /* Simple cases: Value already set, does match or doesn't. */
24669 if (targ != NULL_TREE && same_type_p (targ, arg))
24670 return unify_success (explain_p);
24671 else if (targ)
24672 return unify_inconsistency (explain_p, parm, targ, arg);
24674 /* Make sure that ARG is not a variable-sized array. (Note
24675 that were talking about variable-sized arrays (like
24676 `int[n]'), rather than arrays of unknown size (like
24677 `int[]').) We'll get very confused by such a type since
24678 the bound of the array is not constant, and therefore
24679 not mangleable. Besides, such types are not allowed in
24680 ISO C++, so we can do as we please here. We do allow
24681 them for 'auto' deduction, since that isn't ABI-exposed. */
24682 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24683 return unify_vla_arg (explain_p, arg);
24685 /* Strip typedefs as in convert_template_argument. */
24686 arg = canonicalize_type_argument (arg, tf_none);
24689 /* If ARG is a parameter pack or an expansion, we cannot unify
24690 against it unless PARM is also a parameter pack. */
24691 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24692 && !template_parameter_pack_p (parm))
24693 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24695 /* If the argument deduction results is a METHOD_TYPE,
24696 then there is a problem.
24697 METHOD_TYPE doesn't map to any real C++ type the result of
24698 the deduction cannot be of that type. */
24699 if (TREE_CODE (arg) == METHOD_TYPE)
24700 return unify_method_type_error (explain_p, arg);
24702 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24703 return unify_success (explain_p);
24705 case TEMPLATE_PARM_INDEX:
24706 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24707 if (error_operand_p (tparm))
24708 return unify_invalid (explain_p);
24710 if (TEMPLATE_PARM_LEVEL (parm)
24711 != template_decl_level (tparm))
24713 /* The PARM is not one we're trying to unify. Just check
24714 to see if it matches ARG. */
24715 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24716 && cp_tree_equal (parm, arg));
24717 if (result)
24718 unify_expression_unequal (explain_p, parm, arg);
24719 return result;
24722 idx = TEMPLATE_PARM_IDX (parm);
24723 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24725 if (targ)
24727 if ((strict & UNIFY_ALLOW_INTEGER)
24728 && TREE_TYPE (targ) && TREE_TYPE (arg)
24729 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24730 /* We're deducing from an array bound, the type doesn't matter.
24731 This conversion should match the one below. */
24732 arg = fold (build_nop (TREE_TYPE (targ), arg));
24733 int x = !cp_tree_equal (targ, arg);
24734 if (x)
24735 unify_inconsistency (explain_p, parm, targ, arg);
24736 return x;
24739 /* [temp.deduct.type] If, in the declaration of a function template
24740 with a non-type template-parameter, the non-type
24741 template-parameter is used in an expression in the function
24742 parameter-list and, if the corresponding template-argument is
24743 deduced, the template-argument type shall match the type of the
24744 template-parameter exactly, except that a template-argument
24745 deduced from an array bound may be of any integral type.
24746 The non-type parameter might use already deduced type parameters. */
24747 tparm = TREE_TYPE (parm);
24748 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24749 /* We don't have enough levels of args to do any substitution. This
24750 can happen in the context of -fnew-ttp-matching. */;
24751 else
24753 ++processing_template_decl;
24754 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24755 --processing_template_decl;
24757 if (tree a = type_uses_auto (tparm))
24759 tparm = do_auto_deduction (tparm, arg, a,
24760 complain, adc_unify, targs,
24761 LOOKUP_NORMAL,
24762 TPARMS_PRIMARY_TEMPLATE (tparms));
24763 if (tparm == error_mark_node)
24764 return 1;
24768 if (!TREE_TYPE (arg)
24769 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24770 /* Template-parameter dependent expression. Just accept it for now.
24771 It will later be processed in convert_template_argument. */
24773 else if (same_type_ignoring_top_level_qualifiers_p
24774 (non_reference (TREE_TYPE (arg)),
24775 non_reference (tparm)))
24776 /* OK. Ignore top-level quals here because a class-type template
24777 parameter object is const. */;
24778 else if ((strict & UNIFY_ALLOW_INTEGER)
24779 && CP_INTEGRAL_TYPE_P (tparm))
24780 /* Convert the ARG to the type of PARM; the deduced non-type
24781 template argument must exactly match the types of the
24782 corresponding parameter. This conversion should match the
24783 one above. */
24784 arg = fold (build_nop (tparm, arg));
24785 else if (uses_template_parms (tparm))
24787 /* We haven't deduced the type of this parameter yet. */
24788 if (cxx_dialect >= cxx17
24789 /* We deduce from array bounds in try_array_deduction. */
24790 && !(strict & UNIFY_ALLOW_INTEGER)
24791 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24793 /* Deduce it from the non-type argument. As above, ignore
24794 top-level quals here too. */
24795 tree atype = cv_unqualified (TREE_TYPE (arg));
24796 RECUR_AND_CHECK_FAILURE (tparms, targs,
24797 tparm, atype,
24798 UNIFY_ALLOW_NONE, explain_p);
24799 /* Now check whether the type of this parameter is still
24800 dependent, and give up if so. */
24801 ++processing_template_decl;
24802 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24803 --processing_template_decl;
24804 if (uses_template_parms (tparm))
24805 return unify_success (explain_p);
24807 else
24808 /* Try again later. */
24809 return unify_success (explain_p);
24811 else
24812 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24814 /* If ARG is a parameter pack or an expansion, we cannot unify
24815 against it unless PARM is also a parameter pack. */
24816 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24817 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24818 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24821 bool removed_attr = false;
24822 arg = strip_typedefs_expr (arg, &removed_attr);
24824 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24825 return unify_success (explain_p);
24827 case PTRMEM_CST:
24829 /* A pointer-to-member constant can be unified only with
24830 another constant. */
24831 if (TREE_CODE (arg) != PTRMEM_CST)
24832 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24834 /* Just unify the class member. It would be useless (and possibly
24835 wrong, depending on the strict flags) to unify also
24836 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24837 arg refer to the same variable, even if through different
24838 classes. For instance:
24840 struct A { int x; };
24841 struct B : A { };
24843 Unification of &A::x and &B::x must succeed. */
24844 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24845 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24848 case POINTER_TYPE:
24850 if (!TYPE_PTR_P (arg))
24851 return unify_type_mismatch (explain_p, parm, arg);
24853 /* [temp.deduct.call]
24855 A can be another pointer or pointer to member type that can
24856 be converted to the deduced A via a qualification
24857 conversion (_conv.qual_).
24859 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24860 This will allow for additional cv-qualification of the
24861 pointed-to types if appropriate. */
24863 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24864 /* The derived-to-base conversion only persists through one
24865 level of pointers. */
24866 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24868 return unify (tparms, targs, TREE_TYPE (parm),
24869 TREE_TYPE (arg), strict, explain_p);
24872 case REFERENCE_TYPE:
24873 if (!TYPE_REF_P (arg))
24874 return unify_type_mismatch (explain_p, parm, arg);
24875 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24876 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24878 case ARRAY_TYPE:
24879 if (TREE_CODE (arg) != ARRAY_TYPE)
24880 return unify_type_mismatch (explain_p, parm, arg);
24881 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24882 != (TYPE_DOMAIN (arg) == NULL_TREE))
24883 return unify_type_mismatch (explain_p, parm, arg);
24884 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24885 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24886 if (TYPE_DOMAIN (parm) != NULL_TREE)
24887 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24888 TYPE_DOMAIN (arg), explain_p);
24889 return unify_success (explain_p);
24891 case REAL_TYPE:
24892 case COMPLEX_TYPE:
24893 case VECTOR_TYPE:
24894 case INTEGER_TYPE:
24895 case BOOLEAN_TYPE:
24896 case ENUMERAL_TYPE:
24897 case VOID_TYPE:
24898 case OPAQUE_TYPE:
24899 case NULLPTR_TYPE:
24900 if (TREE_CODE (arg) != TREE_CODE (parm))
24901 return unify_type_mismatch (explain_p, parm, arg);
24903 /* We have already checked cv-qualification at the top of the
24904 function. */
24905 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24906 return unify_type_mismatch (explain_p, parm, arg);
24908 /* As far as unification is concerned, this wins. Later checks
24909 will invalidate it if necessary. */
24910 return unify_success (explain_p);
24912 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24913 /* Type INTEGER_CST can come from ordinary constant template args. */
24914 case INTEGER_CST:
24915 while (CONVERT_EXPR_P (arg))
24916 arg = TREE_OPERAND (arg, 0);
24918 if (TREE_CODE (arg) != INTEGER_CST)
24919 return unify_template_argument_mismatch (explain_p, parm, arg);
24920 return (tree_int_cst_equal (parm, arg)
24921 ? unify_success (explain_p)
24922 : unify_template_argument_mismatch (explain_p, parm, arg));
24924 case TREE_VEC:
24926 int i, len, argslen;
24927 int parm_variadic_p = 0;
24929 if (TREE_CODE (arg) != TREE_VEC)
24930 return unify_template_argument_mismatch (explain_p, parm, arg);
24932 len = TREE_VEC_LENGTH (parm);
24933 argslen = TREE_VEC_LENGTH (arg);
24935 /* Check for pack expansions in the parameters. */
24936 for (i = 0; i < len; ++i)
24938 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24940 if (i == len - 1)
24941 /* We can unify against something with a trailing
24942 parameter pack. */
24943 parm_variadic_p = 1;
24944 else
24945 /* [temp.deduct.type]/9: If the template argument list of
24946 P contains a pack expansion that is not the last
24947 template argument, the entire template argument list
24948 is a non-deduced context. */
24949 return unify_success (explain_p);
24953 /* If we don't have enough arguments to satisfy the parameters
24954 (not counting the pack expression at the end), or we have
24955 too many arguments for a parameter list that doesn't end in
24956 a pack expression, we can't unify. */
24957 if (parm_variadic_p
24958 ? argslen < len - parm_variadic_p
24959 : argslen != len)
24960 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24962 /* Unify all of the parameters that precede the (optional)
24963 pack expression. */
24964 for (i = 0; i < len - parm_variadic_p; ++i)
24966 RECUR_AND_CHECK_FAILURE (tparms, targs,
24967 TREE_VEC_ELT (parm, i),
24968 TREE_VEC_ELT (arg, i),
24969 UNIFY_ALLOW_NONE, explain_p);
24971 if (parm_variadic_p)
24972 return unify_pack_expansion (tparms, targs, parm, arg,
24973 DEDUCE_EXACT,
24974 /*subr=*/true, explain_p);
24975 return unify_success (explain_p);
24978 case RECORD_TYPE:
24979 case UNION_TYPE:
24980 if (TREE_CODE (arg) != TREE_CODE (parm))
24981 return unify_type_mismatch (explain_p, parm, arg);
24983 if (TYPE_PTRMEMFUNC_P (parm))
24985 if (!TYPE_PTRMEMFUNC_P (arg))
24986 return unify_type_mismatch (explain_p, parm, arg);
24988 return unify (tparms, targs,
24989 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24990 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24991 strict, explain_p);
24993 else if (TYPE_PTRMEMFUNC_P (arg))
24994 return unify_type_mismatch (explain_p, parm, arg);
24996 if (CLASSTYPE_TEMPLATE_INFO (parm))
24998 tree t = NULL_TREE;
25000 if (strict_in & UNIFY_ALLOW_DERIVED)
25002 /* First, we try to unify the PARM and ARG directly. */
25003 t = try_class_unification (tparms, targs,
25004 parm, arg, explain_p);
25006 if (!t)
25008 /* Fallback to the special case allowed in
25009 [temp.deduct.call]:
25011 If P is a class, and P has the form
25012 template-id, then A can be a derived class of
25013 the deduced A. Likewise, if P is a pointer to
25014 a class of the form template-id, A can be a
25015 pointer to a derived class pointed to by the
25016 deduced A. */
25017 enum template_base_result r;
25018 r = get_template_base (tparms, targs, parm, arg,
25019 explain_p, &t);
25021 if (!t)
25023 /* Don't give the derived diagnostic if we're
25024 already dealing with the same template. */
25025 bool same_template
25026 = (CLASSTYPE_TEMPLATE_INFO (arg)
25027 && (CLASSTYPE_TI_TEMPLATE (parm)
25028 == CLASSTYPE_TI_TEMPLATE (arg)));
25029 return unify_no_common_base (explain_p && !same_template,
25030 r, parm, arg);
25034 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25035 && (CLASSTYPE_TI_TEMPLATE (parm)
25036 == CLASSTYPE_TI_TEMPLATE (arg)))
25037 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25038 Then, we should unify `int' and `U'. */
25039 t = arg;
25040 else
25041 /* There's no chance of unification succeeding. */
25042 return unify_type_mismatch (explain_p, parm, arg);
25044 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
25045 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
25047 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25048 return unify_type_mismatch (explain_p, parm, arg);
25049 return unify_success (explain_p);
25051 case METHOD_TYPE:
25052 case FUNCTION_TYPE:
25054 unsigned int nargs;
25055 tree *args;
25056 tree a;
25057 unsigned int i;
25059 if (TREE_CODE (arg) != TREE_CODE (parm))
25060 return unify_type_mismatch (explain_p, parm, arg);
25062 /* CV qualifications for methods can never be deduced, they must
25063 match exactly. We need to check them explicitly here,
25064 because type_unification_real treats them as any other
25065 cv-qualified parameter. */
25066 if (TREE_CODE (parm) == METHOD_TYPE
25067 && (!check_cv_quals_for_unify
25068 (UNIFY_ALLOW_NONE,
25069 class_of_this_parm (arg),
25070 class_of_this_parm (parm))))
25071 return unify_cv_qual_mismatch (explain_p, parm, arg);
25072 if (TREE_CODE (arg) == FUNCTION_TYPE
25073 && type_memfn_quals (parm) != type_memfn_quals (arg))
25074 return unify_cv_qual_mismatch (explain_p, parm, arg);
25075 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25076 return unify_type_mismatch (explain_p, parm, arg);
25078 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25079 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25081 nargs = list_length (TYPE_ARG_TYPES (arg));
25082 args = XALLOCAVEC (tree, nargs);
25083 for (a = TYPE_ARG_TYPES (arg), i = 0;
25084 a != NULL_TREE && a != void_list_node;
25085 a = TREE_CHAIN (a), ++i)
25086 args[i] = TREE_VALUE (a);
25087 nargs = i;
25089 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25090 args, nargs, 1, DEDUCE_EXACT,
25091 NULL, explain_p))
25092 return 1;
25094 if (flag_noexcept_type)
25096 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25097 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25098 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25099 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25100 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25101 && uses_template_parms (TREE_PURPOSE (pspec)))
25102 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25103 TREE_PURPOSE (aspec),
25104 UNIFY_ALLOW_NONE, explain_p);
25105 else
25107 bool pn = nothrow_spec_p (pspec);
25108 bool an = nothrow_spec_p (aspec);
25109 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25110 /more/ noexcept, since function pointer conversions are the
25111 reverse of qualification conversions. */
25112 if (an == pn
25113 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25114 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25115 /* OK. */;
25116 else
25117 return unify_type_mismatch (explain_p, parm, arg);
25120 if (flag_tm)
25122 /* As for noexcept. */
25123 bool pn = tx_safe_fn_type_p (parm);
25124 bool an = tx_safe_fn_type_p (arg);
25125 if (an == pn
25126 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25127 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25128 /* OK. */;
25129 else
25130 return unify_type_mismatch (explain_p, parm, arg);
25133 return 0;
25136 case OFFSET_TYPE:
25137 /* Unify a pointer to member with a pointer to member function, which
25138 deduces the type of the member as a function type. */
25139 if (TYPE_PTRMEMFUNC_P (arg))
25141 /* Check top-level cv qualifiers */
25142 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25143 return unify_cv_qual_mismatch (explain_p, parm, arg);
25145 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25146 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25147 UNIFY_ALLOW_NONE, explain_p);
25149 /* Determine the type of the function we are unifying against. */
25150 tree fntype = static_fn_type (arg);
25152 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25155 if (TREE_CODE (arg) != OFFSET_TYPE)
25156 return unify_type_mismatch (explain_p, parm, arg);
25157 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25158 TYPE_OFFSET_BASETYPE (arg),
25159 UNIFY_ALLOW_NONE, explain_p);
25160 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25161 strict, explain_p);
25163 case CONST_DECL:
25164 if (DECL_TEMPLATE_PARM_P (parm))
25165 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
25166 if (arg != scalar_constant_value (parm))
25167 return unify_template_argument_mismatch (explain_p, parm, arg);
25168 return unify_success (explain_p);
25170 case FIELD_DECL:
25171 case TEMPLATE_DECL:
25172 /* Matched cases are handled by the ARG == PARM test above. */
25173 return unify_template_argument_mismatch (explain_p, parm, arg);
25175 case VAR_DECL:
25176 /* We might get a variable as a non-type template argument in parm if the
25177 corresponding parameter is type-dependent. Make any necessary
25178 adjustments based on whether arg is a reference. */
25179 if (CONSTANT_CLASS_P (arg))
25180 parm = fold_non_dependent_expr (parm, complain);
25181 else if (REFERENCE_REF_P (arg))
25183 tree sub = TREE_OPERAND (arg, 0);
25184 STRIP_NOPS (sub);
25185 if (TREE_CODE (sub) == ADDR_EXPR)
25186 arg = TREE_OPERAND (sub, 0);
25188 /* Now use the normal expression code to check whether they match. */
25189 goto expr;
25191 case TYPE_ARGUMENT_PACK:
25192 case NONTYPE_ARGUMENT_PACK:
25193 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25194 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25196 case TYPEOF_TYPE:
25197 case DECLTYPE_TYPE:
25198 case TRAIT_TYPE:
25199 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25200 or TRAIT_TYPE nodes. */
25201 return unify_success (explain_p);
25203 case ERROR_MARK:
25204 /* Unification fails if we hit an error node. */
25205 return unify_invalid (explain_p);
25207 case INDIRECT_REF:
25208 if (REFERENCE_REF_P (parm))
25210 bool pexp = PACK_EXPANSION_P (arg);
25211 if (pexp)
25212 arg = PACK_EXPANSION_PATTERN (arg);
25213 if (REFERENCE_REF_P (arg))
25214 arg = TREE_OPERAND (arg, 0);
25215 if (pexp)
25216 arg = make_pack_expansion (arg, complain);
25217 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25218 strict, explain_p);
25220 /* FALLTHRU */
25222 default:
25223 /* An unresolved overload is a nondeduced context. */
25224 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25225 return unify_success (explain_p);
25226 gcc_assert (EXPR_P (parm)
25227 || TREE_CODE (parm) == CONSTRUCTOR
25228 || TREE_CODE (parm) == TRAIT_EXPR);
25229 expr:
25230 /* We must be looking at an expression. This can happen with
25231 something like:
25233 template <int I>
25234 void foo(S<I>, S<I + 2>);
25238 template<typename T>
25239 void foo(A<T, T{}>);
25241 This is a "non-deduced context":
25243 [deduct.type]
25245 The non-deduced contexts are:
25247 --A non-type template argument or an array bound in which
25248 a subexpression references a template parameter.
25250 In these cases, we assume deduction succeeded, but don't
25251 actually infer any unifications. */
25253 if (!uses_template_parms (parm)
25254 && !template_args_equal (parm, arg))
25255 return unify_expression_unequal (explain_p, parm, arg);
25256 else
25257 return unify_success (explain_p);
25260 #undef RECUR_AND_CHECK_FAILURE
25262 /* Note that DECL can be defined in this translation unit, if
25263 required. */
25265 static void
25266 mark_definable (tree decl)
25268 tree clone;
25269 DECL_NOT_REALLY_EXTERN (decl) = 1;
25270 FOR_EACH_CLONE (clone, decl)
25271 DECL_NOT_REALLY_EXTERN (clone) = 1;
25274 /* Called if RESULT is explicitly instantiated, or is a member of an
25275 explicitly instantiated class. */
25277 void
25278 mark_decl_instantiated (tree result, int extern_p)
25280 SET_DECL_EXPLICIT_INSTANTIATION (result);
25282 /* If this entity has already been written out, it's too late to
25283 make any modifications. */
25284 if (TREE_ASM_WRITTEN (result))
25285 return;
25287 /* consteval functions are never emitted. */
25288 if (TREE_CODE (result) == FUNCTION_DECL
25289 && DECL_IMMEDIATE_FUNCTION_P (result))
25290 return;
25292 /* For anonymous namespace we don't need to do anything. */
25293 if (decl_internal_context_p (result))
25295 gcc_assert (!TREE_PUBLIC (result));
25296 return;
25299 if (TREE_CODE (result) != FUNCTION_DECL)
25300 /* The TREE_PUBLIC flag for function declarations will have been
25301 set correctly by tsubst. */
25302 TREE_PUBLIC (result) = 1;
25304 if (extern_p)
25306 DECL_EXTERNAL (result) = 1;
25307 DECL_NOT_REALLY_EXTERN (result) = 0;
25309 else
25311 mark_definable (result);
25312 mark_needed (result);
25313 /* Always make artificials weak. */
25314 if (DECL_ARTIFICIAL (result) && flag_weak)
25315 comdat_linkage (result);
25316 /* For WIN32 we also want to put explicit instantiations in
25317 linkonce sections. */
25318 else if (TREE_PUBLIC (result))
25319 maybe_make_one_only (result);
25320 if (TREE_CODE (result) == FUNCTION_DECL
25321 && DECL_TEMPLATE_INSTANTIATED (result))
25322 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25323 since start_preparsed_function wouldn't have if we had an earlier
25324 extern explicit instantiation. */
25325 DECL_EXTERNAL (result) = 0;
25328 /* If EXTERN_P, then this function will not be emitted -- unless
25329 followed by an explicit instantiation, at which point its linkage
25330 will be adjusted. If !EXTERN_P, then this function will be
25331 emitted here. In neither circumstance do we want
25332 import_export_decl to adjust the linkage. */
25333 DECL_INTERFACE_KNOWN (result) = 1;
25336 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25337 important template arguments. If any are missing, we check whether
25338 they're important by using error_mark_node for substituting into any
25339 args that were used for partial ordering (the ones between ARGS and END)
25340 and seeing if it bubbles up. */
25342 static bool
25343 check_undeduced_parms (tree targs, tree args, tree end)
25345 bool found = false;
25346 for (tree& targ : tree_vec_range (targs))
25347 if (targ == NULL_TREE)
25349 found = true;
25350 targ = error_mark_node;
25352 if (found)
25354 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25355 if (substed == error_mark_node)
25356 return true;
25358 return false;
25361 /* Given two function templates PAT1 and PAT2, return:
25363 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25364 -1 if PAT2 is more specialized than PAT1.
25365 0 if neither is more specialized.
25367 LEN indicates the number of parameters we should consider
25368 (defaulted parameters should not be considered).
25370 The 1998 std underspecified function template partial ordering, and
25371 DR214 addresses the issue. We take pairs of arguments, one from
25372 each of the templates, and deduce them against each other. One of
25373 the templates will be more specialized if all the *other*
25374 template's arguments deduce against its arguments and at least one
25375 of its arguments *does* *not* deduce against the other template's
25376 corresponding argument. Deduction is done as for class templates.
25377 The arguments used in deduction have reference and top level cv
25378 qualifiers removed. Iff both arguments were originally reference
25379 types *and* deduction succeeds in both directions, an lvalue reference
25380 wins against an rvalue reference and otherwise the template
25381 with the more cv-qualified argument wins for that pairing (if
25382 neither is more cv-qualified, they both are equal). Unlike regular
25383 deduction, after all the arguments have been deduced in this way,
25384 we do *not* verify the deduced template argument values can be
25385 substituted into non-deduced contexts.
25387 The logic can be a bit confusing here, because we look at deduce1 and
25388 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25389 can find template arguments for pat1 to make arg1 look like arg2, that
25390 means that arg2 is at least as specialized as arg1. */
25393 more_specialized_fn (tree pat1, tree pat2, int len)
25395 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25396 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25397 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25398 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25399 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25400 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25401 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25402 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25403 tree origs1, origs2;
25404 bool lose1 = false;
25405 bool lose2 = false;
25407 /* Remove the this parameter from non-static member functions. If
25408 one is a non-static member function and the other is not a static
25409 member function, remove the first parameter from that function
25410 also. This situation occurs for operator functions where we
25411 locate both a member function (with this pointer) and non-member
25412 operator (with explicit first operand). */
25413 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25415 len--; /* LEN is the number of significant arguments for DECL1 */
25416 args1 = TREE_CHAIN (args1);
25417 if (!DECL_STATIC_FUNCTION_P (decl2))
25418 args2 = TREE_CHAIN (args2);
25420 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25422 args2 = TREE_CHAIN (args2);
25423 if (!DECL_STATIC_FUNCTION_P (decl1))
25425 len--;
25426 args1 = TREE_CHAIN (args1);
25430 /* If only one is a conversion operator, they are unordered. */
25431 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25432 return 0;
25434 /* Consider the return type for a conversion function */
25435 if (DECL_CONV_FN_P (decl1))
25437 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25438 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25439 len++;
25442 processing_template_decl++;
25444 origs1 = args1;
25445 origs2 = args2;
25447 while (len--
25448 /* Stop when an ellipsis is seen. */
25449 && args1 != NULL_TREE && args2 != NULL_TREE)
25451 tree arg1 = TREE_VALUE (args1);
25452 tree arg2 = TREE_VALUE (args2);
25453 int deduce1, deduce2;
25454 int quals1 = -1;
25455 int quals2 = -1;
25456 int ref1 = 0;
25457 int ref2 = 0;
25459 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25460 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25462 /* When both arguments are pack expansions, we need only
25463 unify the patterns themselves. */
25464 arg1 = PACK_EXPANSION_PATTERN (arg1);
25465 arg2 = PACK_EXPANSION_PATTERN (arg2);
25467 /* This is the last comparison we need to do. */
25468 len = 0;
25471 if (TYPE_REF_P (arg1))
25473 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25474 arg1 = TREE_TYPE (arg1);
25475 quals1 = cp_type_quals (arg1);
25478 if (TYPE_REF_P (arg2))
25480 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25481 arg2 = TREE_TYPE (arg2);
25482 quals2 = cp_type_quals (arg2);
25485 arg1 = TYPE_MAIN_VARIANT (arg1);
25486 arg2 = TYPE_MAIN_VARIANT (arg2);
25488 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25490 int i, len2 = remaining_arguments (args2);
25491 tree parmvec = make_tree_vec (1);
25492 tree argvec = make_tree_vec (len2);
25493 tree ta = args2;
25495 /* Setup the parameter vector, which contains only ARG1. */
25496 TREE_VEC_ELT (parmvec, 0) = arg1;
25498 /* Setup the argument vector, which contains the remaining
25499 arguments. */
25500 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25501 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25503 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25504 argvec, DEDUCE_EXACT,
25505 /*subr=*/true, /*explain_p=*/false)
25506 == 0);
25508 /* We cannot deduce in the other direction, because ARG1 is
25509 a pack expansion but ARG2 is not. */
25510 deduce2 = 0;
25512 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25514 int i, len1 = remaining_arguments (args1);
25515 tree parmvec = make_tree_vec (1);
25516 tree argvec = make_tree_vec (len1);
25517 tree ta = args1;
25519 /* Setup the parameter vector, which contains only ARG1. */
25520 TREE_VEC_ELT (parmvec, 0) = arg2;
25522 /* Setup the argument vector, which contains the remaining
25523 arguments. */
25524 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25525 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25527 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25528 argvec, DEDUCE_EXACT,
25529 /*subr=*/true, /*explain_p=*/false)
25530 == 0);
25532 /* We cannot deduce in the other direction, because ARG2 is
25533 a pack expansion but ARG1 is not.*/
25534 deduce1 = 0;
25537 else
25539 /* The normal case, where neither argument is a pack
25540 expansion. */
25541 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25542 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25543 == 0);
25544 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25545 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25546 == 0);
25549 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25550 arg2, then arg2 is not as specialized as arg1. */
25551 if (!deduce1)
25552 lose2 = true;
25553 if (!deduce2)
25554 lose1 = true;
25556 /* "If, for a given type, deduction succeeds in both directions
25557 (i.e., the types are identical after the transformations above)
25558 and both P and A were reference types (before being replaced with
25559 the type referred to above):
25560 - if the type from the argument template was an lvalue reference and
25561 the type from the parameter template was not, the argument type is
25562 considered to be more specialized than the other; otherwise,
25563 - if the type from the argument template is more cv-qualified
25564 than the type from the parameter template (as described above),
25565 the argument type is considered to be more specialized than the other;
25566 otherwise,
25567 - neither type is more specialized than the other." */
25569 if (deduce1 && deduce2)
25571 if (ref1 && ref2 && ref1 != ref2)
25573 if (ref1 > ref2)
25574 lose1 = true;
25575 else
25576 lose2 = true;
25578 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25580 if ((quals1 & quals2) == quals2)
25581 lose2 = true;
25582 if ((quals1 & quals2) == quals1)
25583 lose1 = true;
25587 if (lose1 && lose2)
25588 /* We've failed to deduce something in either direction.
25589 These must be unordered. */
25590 break;
25592 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25593 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25594 /* We have already processed all of the arguments in our
25595 handing of the pack expansion type. */
25596 len = 0;
25598 args1 = TREE_CHAIN (args1);
25599 args2 = TREE_CHAIN (args2);
25602 /* "In most cases, all template parameters must have values in order for
25603 deduction to succeed, but for partial ordering purposes a template
25604 parameter may remain without a value provided it is not used in the
25605 types being used for partial ordering."
25607 Thus, if we are missing any of the targs1 we need to substitute into
25608 origs1, then pat2 is not as specialized as pat1. This can happen when
25609 there is a nondeduced context. */
25610 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25611 lose2 = true;
25612 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25613 lose1 = true;
25615 processing_template_decl--;
25617 /* If both deductions succeed, the partial ordering selects the more
25618 constrained template. */
25619 /* P2113: If the corresponding template-parameters of the
25620 template-parameter-lists are not equivalent ([temp.over.link]) or if
25621 the function parameters that positionally correspond between the two
25622 templates are not of the same type, neither template is more
25623 specialized than the other. */
25624 if (!lose1 && !lose2
25625 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25626 DECL_TEMPLATE_PARMS (pat2))
25627 && compparms (origs1, origs2))
25629 int winner = more_constrained (decl1, decl2);
25630 if (winner > 0)
25631 lose2 = true;
25632 else if (winner < 0)
25633 lose1 = true;
25636 /* All things being equal, if the next argument is a pack expansion
25637 for one function but not for the other, prefer the
25638 non-variadic function. FIXME this is bogus; see c++/41958. */
25639 if (lose1 == lose2
25640 && args1 && TREE_VALUE (args1)
25641 && args2 && TREE_VALUE (args2))
25643 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25644 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25647 if (lose1 == lose2)
25648 return 0;
25649 else if (!lose1)
25650 return 1;
25651 else
25652 return -1;
25655 /* Determine which of two partial specializations of TMPL is more
25656 specialized.
25658 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25659 to the first partial specialization. The TREE_PURPOSE is the
25660 innermost set of template parameters for the partial
25661 specialization. PAT2 is similar, but for the second template.
25663 Return 1 if the first partial specialization is more specialized;
25664 -1 if the second is more specialized; 0 if neither is more
25665 specialized.
25667 See [temp.class.order] for information about determining which of
25668 two templates is more specialized. */
25670 static int
25671 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25673 tree targs;
25674 int winner = 0;
25675 bool any_deductions = false;
25677 tree tmpl1 = TREE_VALUE (pat1);
25678 tree tmpl2 = TREE_VALUE (pat2);
25679 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25680 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25682 /* Just like what happens for functions, if we are ordering between
25683 different template specializations, we may encounter dependent
25684 types in the arguments, and we need our dependency check functions
25685 to behave correctly. */
25686 ++processing_template_decl;
25687 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25688 if (targs)
25690 --winner;
25691 any_deductions = true;
25694 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25695 if (targs)
25697 ++winner;
25698 any_deductions = true;
25700 --processing_template_decl;
25702 /* If both deductions succeed, the partial ordering selects the more
25703 constrained template. */
25704 if (!winner && any_deductions)
25705 winner = more_constrained (tmpl1, tmpl2);
25707 /* In the case of a tie where at least one of the templates
25708 has a parameter pack at the end, the template with the most
25709 non-packed parameters wins. */
25710 if (winner == 0
25711 && any_deductions
25712 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25713 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25715 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25716 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25717 int len1 = TREE_VEC_LENGTH (args1);
25718 int len2 = TREE_VEC_LENGTH (args2);
25720 /* We don't count the pack expansion at the end. */
25721 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25722 --len1;
25723 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25724 --len2;
25726 if (len1 > len2)
25727 return 1;
25728 else if (len1 < len2)
25729 return -1;
25732 return winner;
25735 /* Return the template arguments that will produce the function signature
25736 DECL from the function template FN, with the explicit template
25737 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25738 also match. Return NULL_TREE if no satisfactory arguments could be
25739 found. */
25741 static tree
25742 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25744 int ntparms = DECL_NTPARMS (fn);
25745 tree targs = make_tree_vec (ntparms);
25746 tree decl_type = TREE_TYPE (decl);
25747 tree decl_arg_types;
25748 tree *args;
25749 unsigned int nargs, ix;
25750 tree arg;
25752 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25754 /* Never do unification on the 'this' parameter. */
25755 decl_arg_types = skip_artificial_parms_for (decl,
25756 TYPE_ARG_TYPES (decl_type));
25758 nargs = list_length (decl_arg_types);
25759 args = XALLOCAVEC (tree, nargs);
25760 for (arg = decl_arg_types, ix = 0;
25761 arg != NULL_TREE;
25762 arg = TREE_CHAIN (arg), ++ix)
25763 args[ix] = TREE_VALUE (arg);
25765 if (fn_type_unification (fn, explicit_args, targs,
25766 args, ix,
25767 (check_rettype || DECL_CONV_FN_P (fn)
25768 ? TREE_TYPE (decl_type) : NULL_TREE),
25769 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25770 /*explain_p=*/false,
25771 /*decltype*/false)
25772 == error_mark_node)
25773 return NULL_TREE;
25775 return targs;
25778 /* Return the innermost template arguments that, when applied to a partial
25779 specialization SPEC_TMPL of TMPL, yield the ARGS.
25781 For example, suppose we have:
25783 template <class T, class U> struct S {};
25784 template <class T> struct S<T*, int> {};
25786 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25787 partial specialization and the ARGS will be {double*, int}. The resulting
25788 vector will be {double}, indicating that `T' is bound to `double'. */
25790 static tree
25791 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25793 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25794 tree spec_args
25795 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25796 int i, ntparms = TREE_VEC_LENGTH (tparms);
25797 tree deduced_args;
25798 tree innermost_deduced_args;
25800 innermost_deduced_args = make_tree_vec (ntparms);
25801 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25803 deduced_args = copy_node (args);
25804 SET_TMPL_ARGS_LEVEL (deduced_args,
25805 TMPL_ARGS_DEPTH (deduced_args),
25806 innermost_deduced_args);
25808 else
25809 deduced_args = innermost_deduced_args;
25811 bool tried_array_deduction = (cxx_dialect < cxx17);
25812 again:
25813 if (unify (tparms, deduced_args,
25814 INNERMOST_TEMPLATE_ARGS (spec_args),
25815 INNERMOST_TEMPLATE_ARGS (args),
25816 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25817 return NULL_TREE;
25819 for (i = 0; i < ntparms; ++i)
25820 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25822 if (!tried_array_deduction)
25824 try_array_deduction (tparms, innermost_deduced_args,
25825 INNERMOST_TEMPLATE_ARGS (spec_args));
25826 tried_array_deduction = true;
25827 if (TREE_VEC_ELT (innermost_deduced_args, i))
25828 goto again;
25830 return NULL_TREE;
25833 if (!push_tinst_level (spec_tmpl, deduced_args))
25835 excessive_deduction_depth = true;
25836 return NULL_TREE;
25839 /* Verify that nondeduced template arguments agree with the type
25840 obtained from argument deduction.
25842 For example:
25844 struct A { typedef int X; };
25845 template <class T, class U> struct C {};
25846 template <class T> struct C<T, typename T::X> {};
25848 Then with the instantiation `C<A, int>', we can deduce that
25849 `T' is `A' but unify () does not check whether `typename T::X'
25850 is `int'. */
25851 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25853 if (spec_args != error_mark_node)
25854 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25855 INNERMOST_TEMPLATE_ARGS (spec_args),
25856 tmpl, tf_none, false);
25858 pop_tinst_level ();
25860 if (spec_args == error_mark_node
25861 /* We only need to check the innermost arguments; the other
25862 arguments will always agree. */
25863 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25864 INNERMOST_TEMPLATE_ARGS (args)))
25865 return NULL_TREE;
25867 /* Now that we have bindings for all of the template arguments,
25868 ensure that the arguments deduced for the template template
25869 parameters have compatible template parameter lists. See the use
25870 of template_template_parm_bindings_ok_p in fn_type_unification
25871 for more information. */
25872 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25873 return NULL_TREE;
25875 return deduced_args;
25878 // Compare two function templates T1 and T2 by deducing bindings
25879 // from one against the other. If both deductions succeed, compare
25880 // constraints to see which is more constrained.
25881 static int
25882 more_specialized_inst (tree t1, tree t2)
25884 int fate = 0;
25885 int count = 0;
25887 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25889 --fate;
25890 ++count;
25893 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25895 ++fate;
25896 ++count;
25899 // If both deductions succeed, then one may be more constrained.
25900 if (count == 2 && fate == 0)
25901 fate = more_constrained (t1, t2);
25903 return fate;
25906 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25907 Return the TREE_LIST node with the most specialized template, if
25908 any. If there is no most specialized template, the error_mark_node
25909 is returned.
25911 Note that this function does not look at, or modify, the
25912 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25913 returned is one of the elements of INSTANTIATIONS, callers may
25914 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25915 and retrieve it from the value returned. */
25917 tree
25918 most_specialized_instantiation (tree templates)
25920 tree fn, champ;
25922 ++processing_template_decl;
25924 champ = templates;
25925 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25927 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25928 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25929 if (fate == -1)
25930 champ = fn;
25931 else if (!fate)
25933 /* Equally specialized, move to next function. If there
25934 is no next function, nothing's most specialized. */
25935 fn = TREE_CHAIN (fn);
25936 champ = fn;
25937 if (!fn)
25938 break;
25942 if (champ)
25943 /* Now verify that champ is better than everything earlier in the
25944 instantiation list. */
25945 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25946 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25948 champ = NULL_TREE;
25949 break;
25953 processing_template_decl--;
25955 if (!champ)
25956 return error_mark_node;
25958 return champ;
25961 /* If DECL is a specialization of some template, return the most
25962 general such template. Otherwise, returns NULL_TREE.
25964 For example, given:
25966 template <class T> struct S { template <class U> void f(U); };
25968 if TMPL is `template <class U> void S<int>::f(U)' this will return
25969 the full template. This function will not trace past partial
25970 specializations, however. For example, given in addition:
25972 template <class T> struct S<T*> { template <class U> void f(U); };
25974 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25975 `template <class T> template <class U> S<T*>::f(U)'. */
25977 tree
25978 most_general_template (tree decl)
25980 if (TREE_CODE (decl) != TEMPLATE_DECL)
25982 if (tree tinfo = get_template_info (decl))
25983 decl = TI_TEMPLATE (tinfo);
25984 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25985 template friend, or a FIELD_DECL for a capture pack. */
25986 if (TREE_CODE (decl) != TEMPLATE_DECL)
25987 return NULL_TREE;
25990 /* Look for more and more general templates. */
25991 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25993 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25994 (See cp-tree.h for details.) */
25995 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25996 break;
25998 if (CLASS_TYPE_P (TREE_TYPE (decl))
25999 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
26000 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
26001 break;
26003 /* Stop if we run into an explicitly specialized class template. */
26004 if (!DECL_NAMESPACE_SCOPE_P (decl)
26005 && DECL_CONTEXT (decl)
26006 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
26007 break;
26009 decl = DECL_TI_TEMPLATE (decl);
26012 return decl;
26015 /* Return the most specialized of the template partial specializations
26016 which can produce TARGET, a specialization of some class or variable
26017 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26018 TEMPLATE_DECL node corresponding to the partial specialization, while
26019 the TI_ARGS is the set of template arguments that must be substituted
26020 into the template pattern in order to generate TARGET. The result is
26021 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26022 RECHECKING is true.
26024 If the choice of partial specialization is ambiguous, a diagnostic
26025 is issued, and the error_mark_node is returned. If there are no
26026 partial specializations matching TARGET, then NULL_TREE is
26027 returned, indicating that the primary template should be used. */
26029 tree
26030 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26031 bool rechecking /* = false */)
26033 tree tinfo = NULL_TREE;
26034 tree tmpl, args, decl;
26035 if (TYPE_P (target))
26037 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26038 tmpl = TI_TEMPLATE (tinfo);
26039 args = TI_ARGS (tinfo);
26040 decl = TYPE_NAME (target);
26042 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26044 tmpl = TREE_OPERAND (target, 0);
26045 args = TREE_OPERAND (target, 1);
26046 decl = DECL_TEMPLATE_RESULT (tmpl);
26048 else if (VAR_P (target))
26050 tinfo = DECL_TEMPLATE_INFO (target);
26051 tmpl = TI_TEMPLATE (tinfo);
26052 args = TI_ARGS (tinfo);
26053 decl = target;
26055 else
26056 gcc_unreachable ();
26058 if (!PRIMARY_TEMPLATE_P (tmpl))
26059 return NULL_TREE;
26061 if (!rechecking
26062 && tinfo
26063 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26064 return TI_PARTIAL_INFO (tinfo);
26066 tree main_tmpl = most_general_template (tmpl);
26067 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26068 if (!specs)
26069 /* There are no partial specializations of this template. */
26070 return NULL_TREE;
26072 push_access_scope_guard pas (decl);
26073 deferring_access_check_sentinel acs (dk_no_deferred);
26075 /* For determining which partial specialization to use, only the
26076 innermost args are interesting. */
26077 tree outer_args = NULL_TREE;
26078 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26080 outer_args = strip_innermost_template_args (args, 1);
26081 args = INNERMOST_TEMPLATE_ARGS (args);
26084 /* The caller hasn't called push_to_top_level yet, but we need
26085 get_partial_spec_bindings to be done in non-template context so that we'll
26086 fully resolve everything. */
26087 processing_template_decl_sentinel ptds;
26089 tree list = NULL_TREE;
26090 for (tree t = specs; t; t = TREE_CHAIN (t))
26092 const tree ospec_tmpl = TREE_VALUE (t);
26094 tree spec_tmpl;
26095 if (outer_args)
26097 /* Substitute in the template args from the enclosing class. */
26098 ++processing_template_decl;
26099 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26100 --processing_template_decl;
26101 if (spec_tmpl == error_mark_node)
26102 return error_mark_node;
26104 else
26105 spec_tmpl = ospec_tmpl;
26107 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26108 if (spec_args)
26110 if (outer_args)
26111 spec_args = add_to_template_args (outer_args, spec_args);
26113 /* Keep the candidate only if its constraints are satisfied. */
26114 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26115 list = tree_cons (spec_args, ospec_tmpl, list);
26119 if (! list)
26120 return NULL_TREE;
26122 tree champ = list;
26123 bool ambiguous_p = false;
26124 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26126 int fate = more_specialized_partial_spec (tmpl, champ, t);
26127 if (fate == 1)
26129 else
26131 if (fate == 0)
26133 t = TREE_CHAIN (t);
26134 if (! t)
26136 ambiguous_p = true;
26137 break;
26140 champ = t;
26144 if (!ambiguous_p)
26145 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26147 int fate = more_specialized_partial_spec (tmpl, champ, t);
26148 if (fate != 1)
26150 ambiguous_p = true;
26151 break;
26155 if (ambiguous_p)
26157 const char *str;
26158 char *spaces = NULL;
26159 if (!(complain & tf_error))
26160 return error_mark_node;
26161 if (TYPE_P (target))
26162 error ("ambiguous template instantiation for %q#T", target);
26163 else
26164 error ("ambiguous template instantiation for %q#D", target);
26165 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26166 for (tree t = list; t; t = TREE_CHAIN (t))
26168 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26169 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26170 "%s %#qS", spaces ? spaces : str, subst);
26171 spaces = spaces ? spaces : get_spaces (str);
26173 free (spaces);
26174 return error_mark_node;
26177 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26178 if (!rechecking && tinfo)
26179 TI_PARTIAL_INFO (tinfo) = result;
26180 return result;
26183 /* Explicitly instantiate DECL. */
26185 void
26186 do_decl_instantiation (tree decl, tree storage)
26188 tree result = NULL_TREE;
26189 int extern_p = 0;
26191 if (!decl || decl == error_mark_node)
26192 /* An error occurred, for which grokdeclarator has already issued
26193 an appropriate message. */
26194 return;
26195 else if (! DECL_LANG_SPECIFIC (decl))
26197 error ("explicit instantiation of non-template %q#D", decl);
26198 return;
26200 else if (DECL_DECLARED_CONCEPT_P (decl))
26202 if (VAR_P (decl))
26203 error ("explicit instantiation of variable concept %q#D", decl);
26204 else
26205 error ("explicit instantiation of function concept %q#D", decl);
26206 return;
26209 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26210 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26212 if (VAR_P (decl) && !var_templ)
26214 /* There is an asymmetry here in the way VAR_DECLs and
26215 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26216 the latter, the DECL we get back will be marked as a
26217 template instantiation, and the appropriate
26218 DECL_TEMPLATE_INFO will be set up. This does not happen for
26219 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26220 should handle VAR_DECLs as it currently handles
26221 FUNCTION_DECLs. */
26222 if (!DECL_CLASS_SCOPE_P (decl))
26224 error ("%qD is not a static data member of a class template", decl);
26225 return;
26227 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26228 if (!result || !VAR_P (result))
26230 error ("no matching template for %qD found", decl);
26231 return;
26233 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26235 error ("type %qT for explicit instantiation %qD does not match "
26236 "declared type %qT", TREE_TYPE (result), decl,
26237 TREE_TYPE (decl));
26238 return;
26241 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26243 error ("explicit instantiation of %q#D", decl);
26244 return;
26246 else
26247 result = decl;
26249 /* Check for various error cases. Note that if the explicit
26250 instantiation is valid the RESULT will currently be marked as an
26251 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26252 until we get here. */
26254 if (DECL_TEMPLATE_SPECIALIZATION (result))
26256 /* DR 259 [temp.spec].
26258 Both an explicit instantiation and a declaration of an explicit
26259 specialization shall not appear in a program unless the explicit
26260 instantiation follows a declaration of the explicit specialization.
26262 For a given set of template parameters, if an explicit
26263 instantiation of a template appears after a declaration of an
26264 explicit specialization for that template, the explicit
26265 instantiation has no effect. */
26266 return;
26268 else if (DECL_EXPLICIT_INSTANTIATION (result))
26270 /* [temp.spec]
26272 No program shall explicitly instantiate any template more
26273 than once.
26275 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26276 the first instantiation was `extern' and the second is not,
26277 and EXTERN_P for the opposite case. */
26278 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26279 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26280 /* If an "extern" explicit instantiation follows an ordinary
26281 explicit instantiation, the template is instantiated. */
26282 if (extern_p)
26283 return;
26285 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26287 error ("no matching template for %qD found", result);
26288 return;
26290 else if (!DECL_TEMPLATE_INFO (result))
26292 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26293 return;
26296 if (storage == NULL_TREE)
26298 else if (storage == ridpointers[(int) RID_EXTERN])
26300 if (cxx_dialect == cxx98)
26301 pedwarn (input_location, OPT_Wpedantic,
26302 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26303 "instantiations");
26304 extern_p = 1;
26306 else
26307 error ("storage class %qD applied to template instantiation", storage);
26309 check_explicit_instantiation_namespace (result);
26310 mark_decl_instantiated (result, extern_p);
26311 if (! extern_p)
26312 instantiate_decl (result, /*defer_ok=*/true,
26313 /*expl_inst_class_mem_p=*/false);
26316 static void
26317 mark_class_instantiated (tree t, int extern_p)
26319 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26320 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26321 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26322 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26323 if (! extern_p)
26325 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26326 rest_of_type_compilation (t, 1);
26330 /* Perform an explicit instantiation of template class T. STORAGE, if
26331 non-null, is the RID for extern, inline or static. COMPLAIN is
26332 nonzero if this is called from the parser, zero if called recursively,
26333 since the standard is unclear (as detailed below). */
26335 void
26336 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26338 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26340 if (tree ti = TYPE_TEMPLATE_INFO (t))
26341 error ("explicit instantiation of non-class template %qD",
26342 TI_TEMPLATE (ti));
26343 else
26344 error ("explicit instantiation of non-template type %qT", t);
26345 return;
26348 complete_type (t);
26350 if (!COMPLETE_TYPE_P (t))
26352 if (complain & tf_error)
26353 error ("explicit instantiation of %q#T before definition of template",
26355 return;
26358 /* At most one of these will be true. */
26359 bool extern_p = false;
26360 bool nomem_p = false;
26361 bool static_p = false;
26363 if (storage != NULL_TREE)
26365 if (storage == ridpointers[(int) RID_EXTERN])
26367 if (cxx_dialect == cxx98)
26368 pedwarn (input_location, OPT_Wpedantic,
26369 "ISO C++ 1998 forbids the use of %<extern%> on "
26370 "explicit instantiations");
26372 else
26373 pedwarn (input_location, OPT_Wpedantic,
26374 "ISO C++ forbids the use of %qE"
26375 " on explicit instantiations", storage);
26377 if (storage == ridpointers[(int) RID_INLINE])
26378 nomem_p = true;
26379 else if (storage == ridpointers[(int) RID_EXTERN])
26380 extern_p = true;
26381 else if (storage == ridpointers[(int) RID_STATIC])
26382 static_p = true;
26383 else
26384 error ("storage class %qD applied to template instantiation",
26385 storage);
26388 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26389 /* DR 259 [temp.spec].
26391 Both an explicit instantiation and a declaration of an explicit
26392 specialization shall not appear in a program unless the
26393 explicit instantiation follows a declaration of the explicit
26394 specialization.
26396 For a given set of template parameters, if an explicit
26397 instantiation of a template appears after a declaration of an
26398 explicit specialization for that template, the explicit
26399 instantiation has no effect. */
26400 return;
26402 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26404 /* We've already instantiated the template. */
26406 /* [temp.spec]
26408 No program shall explicitly instantiate any template more
26409 than once.
26411 If EXTERN_P then this is ok. */
26412 if (!extern_p && (complain & tf_error))
26413 permerror (input_location,
26414 "duplicate explicit instantiation of %q#T", t);
26416 return;
26419 check_explicit_instantiation_namespace (TYPE_NAME (t));
26420 mark_class_instantiated (t, extern_p);
26422 if (nomem_p)
26423 return;
26425 /* In contrast to implicit instantiation, where only the
26426 declarations, and not the definitions, of members are
26427 instantiated, we have here:
26429 [temp.explicit]
26431 An explicit instantiation that names a class template
26432 specialization is also an explicit instantiation of the same
26433 kind (declaration or definition) of each of its members (not
26434 including members inherited from base classes and members
26435 that are templates) that has not been previously explicitly
26436 specialized in the translation unit containing the explicit
26437 instantiation, provided that the associated constraints, if
26438 any, of that member are satisfied by the template arguments
26439 of the explicit instantiation. */
26440 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26441 if ((VAR_P (fld)
26442 || (TREE_CODE (fld) == FUNCTION_DECL
26443 && !static_p
26444 && user_provided_p (fld)))
26445 && DECL_TEMPLATE_INSTANTIATION (fld)
26446 && constraints_satisfied_p (fld))
26448 mark_decl_instantiated (fld, extern_p);
26449 if (! extern_p)
26450 instantiate_decl (fld, /*defer_ok=*/true,
26451 /*expl_inst_class_mem_p=*/true);
26453 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26455 tree type = TREE_TYPE (fld);
26457 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26458 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26459 do_type_instantiation (type, storage, 0);
26463 /* Given a function DECL, which is a specialization of TMPL, modify
26464 DECL to be a re-instantiation of TMPL with the same template
26465 arguments. TMPL should be the template into which tsubst'ing
26466 should occur for DECL, not the most general template.
26468 One reason for doing this is a scenario like this:
26470 template <class T>
26471 void f(const T&, int i);
26473 void g() { f(3, 7); }
26475 template <class T>
26476 void f(const T& t, const int i) { }
26478 Note that when the template is first instantiated, with
26479 instantiate_template, the resulting DECL will have no name for the
26480 first parameter, and the wrong type for the second. So, when we go
26481 to instantiate the DECL, we regenerate it. */
26483 static void
26484 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26486 /* The arguments used to instantiate DECL, from the most general
26487 template. */
26488 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26490 /* Make sure that we can see identifiers, and compute access correctly. */
26491 push_access_scope (decl);
26493 if (TREE_CODE (decl) == FUNCTION_DECL)
26495 tree specs;
26496 int args_depth;
26497 int parms_depth;
26499 /* Don't bother with this for unique friends that can't be redeclared and
26500 might change type if regenerated (PR69836). */
26501 if (DECL_UNIQUE_FRIEND_P (decl))
26502 goto done;
26504 /* Use the source location of the definition. */
26505 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26507 args_depth = TMPL_ARGS_DEPTH (args);
26508 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26509 if (args_depth > parms_depth)
26510 args = get_innermost_template_args (args, parms_depth);
26512 /* Instantiate a dynamic exception-specification. noexcept will be
26513 handled below. */
26514 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26515 if (TREE_VALUE (raises))
26517 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26518 args, tf_error, NULL_TREE,
26519 /*defer_ok*/false);
26520 if (specs && specs != error_mark_node)
26521 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26522 specs);
26525 /* Merge parameter declarations. */
26526 if (tree pattern_parm
26527 = skip_artificial_parms_for (code_pattern,
26528 DECL_ARGUMENTS (code_pattern)))
26530 tree *p = &DECL_ARGUMENTS (decl);
26531 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26532 p = &DECL_CHAIN (*p);
26533 *p = tsubst_decl (pattern_parm, args, tf_error);
26534 for (tree t = *p; t; t = DECL_CHAIN (t))
26535 DECL_CONTEXT (t) = decl;
26538 if (DECL_CONTRACTS (decl))
26540 /* If we're regenerating a specialization, the contracts will have
26541 been copied from the most general template. Replace those with
26542 the ones from the actual specialization. */
26543 tree tmpl = DECL_TI_TEMPLATE (decl);
26544 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26546 remove_contract_attributes (decl);
26547 copy_contract_attributes (decl, code_pattern);
26550 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26553 /* Merge additional specifiers from the CODE_PATTERN. */
26554 if (DECL_DECLARED_INLINE_P (code_pattern)
26555 && !DECL_DECLARED_INLINE_P (decl))
26556 DECL_DECLARED_INLINE_P (decl) = 1;
26558 maybe_instantiate_noexcept (decl, tf_error);
26560 else if (VAR_P (decl))
26562 start_lambda_scope (decl);
26563 DECL_INITIAL (decl) =
26564 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26565 tf_error, DECL_TI_TEMPLATE (decl));
26566 finish_lambda_scope ();
26567 if (VAR_HAD_UNKNOWN_BOUND (decl))
26568 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26569 tf_error, DECL_TI_TEMPLATE (decl));
26571 else
26572 gcc_unreachable ();
26574 done:
26575 pop_access_scope (decl);
26578 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26579 substituted to get DECL. */
26581 tree
26582 template_for_substitution (tree decl)
26584 tree tmpl = DECL_TI_TEMPLATE (decl);
26586 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26587 for the instantiation. This is not always the most general
26588 template. Consider, for example:
26590 template <class T>
26591 struct S { template <class U> void f();
26592 template <> void f<int>(); };
26594 and an instantiation of S<double>::f<int>. We want TD to be the
26595 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26596 while (/* An instantiation cannot have a definition, so we need a
26597 more general template. */
26598 DECL_TEMPLATE_INSTANTIATION (tmpl)
26599 /* We must also deal with friend templates. Given:
26601 template <class T> struct S {
26602 template <class U> friend void f() {};
26605 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26606 so far as the language is concerned, but that's still
26607 where we get the pattern for the instantiation from. On
26608 other hand, if the definition comes outside the class, say:
26610 template <class T> struct S {
26611 template <class U> friend void f();
26613 template <class U> friend void f() {}
26615 we don't need to look any further. That's what the check for
26616 DECL_INITIAL is for. */
26617 || (TREE_CODE (decl) == FUNCTION_DECL
26618 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26619 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26621 /* The present template, TD, should not be a definition. If it
26622 were a definition, we should be using it! Note that we
26623 cannot restructure the loop to just keep going until we find
26624 a template with a definition, since that might go too far if
26625 a specialization was declared, but not defined. */
26627 /* Fetch the more general template. */
26628 tmpl = DECL_TI_TEMPLATE (tmpl);
26631 return tmpl;
26634 /* Returns true if we need to instantiate this template instance even if we
26635 know we aren't going to emit it. */
26637 bool
26638 always_instantiate_p (tree decl)
26640 /* We always instantiate inline functions so that we can inline them. An
26641 explicit instantiation declaration prohibits implicit instantiation of
26642 non-inline functions. With high levels of optimization, we would
26643 normally inline non-inline functions -- but we're not allowed to do
26644 that for "extern template" functions. Therefore, we check
26645 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26646 return ((TREE_CODE (decl) == FUNCTION_DECL
26647 && (DECL_DECLARED_INLINE_P (decl)
26648 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26649 /* And we need to instantiate static data members so that
26650 their initializers are available in integral constant
26651 expressions. */
26652 || (VAR_P (decl)
26653 && decl_maybe_constant_var_p (decl)));
26656 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26657 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26658 error, true otherwise. */
26660 bool
26661 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26663 if (fn == error_mark_node)
26664 return false;
26666 /* Don't instantiate a noexcept-specification from template context. */
26667 if (processing_template_decl
26668 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26669 return true;
26671 tree fntype = TREE_TYPE (fn);
26672 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26674 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26675 && DECL_MAYBE_DELETED (fn))
26677 if (fn == current_function_decl)
26678 /* We're in start_preparsed_function, keep going. */
26679 return true;
26681 ++function_depth;
26682 maybe_synthesize_method (fn);
26683 --function_depth;
26684 return !DECL_DELETED_FN (fn);
26687 if (!spec || !TREE_PURPOSE (spec))
26688 return true;
26690 tree noex = TREE_PURPOSE (spec);
26691 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26692 && TREE_CODE (noex) != DEFERRED_PARSE)
26693 return true;
26695 tree orig_fn = NULL_TREE;
26696 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26697 its FUNCTION_DECL for the rest of this function -- push_access_scope
26698 doesn't accept TEMPLATE_DECLs. */
26699 if (DECL_FUNCTION_TEMPLATE_P (fn))
26701 orig_fn = fn;
26702 fn = DECL_TEMPLATE_RESULT (fn);
26705 if (DECL_CLONED_FUNCTION_P (fn))
26707 tree prime = DECL_CLONED_FUNCTION (fn);
26708 if (!maybe_instantiate_noexcept (prime, complain))
26709 return false;
26710 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26712 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26714 static hash_set<tree>* fns = new hash_set<tree>;
26715 bool added = false;
26716 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26718 spec = get_defaulted_eh_spec (fn, complain);
26719 if (spec == error_mark_node)
26720 /* This might have failed because of an unparsed DMI, so
26721 let's try again later. */
26722 return false;
26724 else if (!(added = !fns->add (fn)))
26726 /* If hash_set::add returns true, the element was already there. */
26727 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26728 DECL_SOURCE_LOCATION (fn));
26729 error_at (loc,
26730 "exception specification of %qD depends on itself",
26731 fn);
26732 spec = noexcept_false_spec;
26734 else if (push_tinst_level (fn))
26736 push_to_top_level ();
26737 push_access_scope (fn);
26738 push_deferring_access_checks (dk_no_deferred);
26739 input_location = DECL_SOURCE_LOCATION (fn);
26741 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26742 && !DECL_LOCAL_DECL_P (fn))
26744 /* If needed, set current_class_ptr for the benefit of
26745 tsubst_copy/PARM_DECL. */
26746 tree this_parm = DECL_ARGUMENTS (fn);
26747 current_class_ptr = NULL_TREE;
26748 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26749 current_class_ptr = this_parm;
26752 /* If this function is represented by a TEMPLATE_DECL, then
26753 the deferred noexcept-specification might still contain
26754 dependent types, even after substitution. And we need the
26755 dependency check functions to work in build_noexcept_spec. */
26756 if (orig_fn)
26757 ++processing_template_decl;
26759 /* Do deferred instantiation of the noexcept-specifier. */
26760 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26761 DEFERRED_NOEXCEPT_ARGS (noex),
26762 tf_warning_or_error, fn);
26764 /* Build up the noexcept-specification. */
26765 spec = build_noexcept_spec (noex, tf_warning_or_error);
26767 if (orig_fn)
26768 --processing_template_decl;
26770 pop_deferring_access_checks ();
26771 pop_access_scope (fn);
26772 pop_tinst_level ();
26773 pop_from_top_level ();
26775 else
26776 spec = noexcept_false_spec;
26778 if (added)
26779 fns->remove (fn);
26782 if (spec == error_mark_node)
26784 /* This failed with a hard error, so let's go with false. */
26785 gcc_assert (seen_error ());
26786 spec = noexcept_false_spec;
26789 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26790 if (orig_fn)
26791 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26793 return true;
26796 /* We're starting to process the function INST, an instantiation of PATTERN;
26797 add their parameters to local_specializations. */
26799 void
26800 register_parameter_specializations (tree pattern, tree inst)
26802 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26803 tree spec_parm = DECL_ARGUMENTS (inst);
26804 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26806 register_local_specialization (spec_parm, tmpl_parm);
26807 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26808 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26810 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26812 if (!DECL_PACK_P (tmpl_parm))
26814 register_local_specialization (spec_parm, tmpl_parm);
26815 spec_parm = DECL_CHAIN (spec_parm);
26817 else
26819 /* Register the (value) argument pack as a specialization of
26820 TMPL_PARM, then move on. */
26821 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26822 register_local_specialization (argpack, tmpl_parm);
26825 gcc_assert (!spec_parm);
26828 /* Instantiate the body of D using PATTERN with ARGS. We have
26829 already determined PATTERN is the correct template to use.
26830 NESTED_P is true if this is a nested function, in which case
26831 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26833 static void
26834 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26836 tree td = NULL_TREE;
26837 tree code_pattern = pattern;
26839 if (!nested_p)
26841 td = pattern;
26842 code_pattern = DECL_TEMPLATE_RESULT (td);
26844 else
26845 /* Only OMP reductions are nested. */
26846 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26848 vec<tree> omp_privatization_save;
26849 if (current_function_decl)
26850 save_omp_privatization_clauses (omp_privatization_save);
26852 bool push_to_top = maybe_push_to_top_level (d);
26854 mark_template_arguments_used (pattern, args);
26856 if (VAR_P (d))
26858 /* The variable might be a lambda's extra scope, and that
26859 lambda's visibility depends on D's. */
26860 maybe_commonize_var (d);
26861 determine_visibility (d);
26864 /* Mark D as instantiated so that recursive calls to
26865 instantiate_decl do not try to instantiate it again. */
26866 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26868 if (td)
26869 /* Regenerate the declaration in case the template has been modified
26870 by a subsequent redeclaration. */
26871 regenerate_decl_from_template (d, td, args);
26873 /* We already set the file and line above. Reset them now in case
26874 they changed as a result of calling regenerate_decl_from_template. */
26875 input_location = DECL_SOURCE_LOCATION (d);
26877 if (VAR_P (d))
26879 /* Clear out DECL_RTL; whatever was there before may not be right
26880 since we've reset the type of the declaration. */
26881 SET_DECL_RTL (d, NULL);
26882 DECL_IN_AGGR_P (d) = 0;
26884 /* The initializer is placed in DECL_INITIAL by
26885 regenerate_decl_from_template so we don't need to
26886 push/pop_access_scope again here. Pull it out so that
26887 cp_finish_decl can process it. */
26888 bool const_init = false;
26889 tree init = DECL_INITIAL (d);
26890 DECL_INITIAL (d) = NULL_TREE;
26891 DECL_INITIALIZED_P (d) = 0;
26893 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26894 initializer. That function will defer actual emission until
26895 we have a chance to determine linkage. */
26896 DECL_EXTERNAL (d) = 0;
26898 /* Enter the scope of D so that access-checking works correctly. */
26899 bool enter_context = DECL_CLASS_SCOPE_P (d);
26900 if (enter_context)
26901 push_nested_class (DECL_CONTEXT (d));
26903 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26904 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26906 if (enter_context)
26907 pop_nested_class ();
26909 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26910 synthesize_method (d);
26911 else if (TREE_CODE (d) == FUNCTION_DECL)
26913 /* Set up the list of local specializations. */
26914 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26915 tree block = NULL_TREE;
26917 /* Set up context. */
26918 if (nested_p)
26919 block = push_stmt_list ();
26920 else
26922 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26924 perform_instantiation_time_access_checks (code_pattern, args);
26927 /* Create substitution entries for the parameters. */
26928 register_parameter_specializations (code_pattern, d);
26930 /* Substitute into the body of the function. */
26931 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26932 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26933 tf_warning_or_error, d);
26934 else
26936 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26937 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26939 /* Set the current input_location to the end of the function
26940 so that finish_function knows where we are. */
26941 input_location
26942 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26944 /* Remember if we saw an infinite loop in the template. */
26945 current_function_infinite_loop
26946 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26949 /* Finish the function. */
26950 if (nested_p)
26951 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26952 else
26954 d = finish_function (/*inline_p=*/false);
26955 expand_or_defer_fn (d);
26958 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26959 cp_check_omp_declare_reduction (d);
26962 /* We're not deferring instantiation any more. */
26963 if (!nested_p)
26964 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26966 maybe_pop_from_top_level (push_to_top);
26968 if (current_function_decl)
26969 restore_omp_privatization_clauses (omp_privatization_save);
26972 /* Produce the definition of D, a _DECL generated from a template. If
26973 DEFER_OK is true, then we don't have to actually do the
26974 instantiation now; we just have to do it sometime. Normally it is
26975 an error if this is an explicit instantiation but D is undefined.
26976 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26977 instantiated class template. */
26979 tree
26980 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26982 tree tmpl = DECL_TI_TEMPLATE (d);
26983 tree gen_args;
26984 tree args;
26985 tree td;
26986 tree code_pattern;
26987 tree spec;
26988 tree gen_tmpl;
26989 bool pattern_defined;
26990 location_t saved_loc = input_location;
26991 int saved_unevaluated_operand = cp_unevaluated_operand;
26992 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26993 bool external_p;
26994 bool deleted_p;
26996 /* This function should only be used to instantiate templates for
26997 functions and static member variables. */
26998 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
27000 /* A concept is never instantiated. */
27001 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
27003 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
27005 if (modules_p ())
27006 /* We may have a pending instantiation of D itself. */
27007 lazy_load_pendings (d);
27009 /* Variables are never deferred; if instantiation is required, they
27010 are instantiated right away. That allows for better code in the
27011 case that an expression refers to the value of the variable --
27012 if the variable has a constant value the referring expression can
27013 take advantage of that fact. */
27014 if (VAR_P (d))
27015 defer_ok = false;
27017 /* Don't instantiate cloned functions. Instead, instantiate the
27018 functions they cloned. */
27019 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27020 d = DECL_CLONED_FUNCTION (d);
27022 if (DECL_TEMPLATE_INSTANTIATED (d)
27023 || TREE_TYPE (d) == error_mark_node
27024 || (TREE_CODE (d) == FUNCTION_DECL
27025 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27026 || DECL_TEMPLATE_SPECIALIZATION (d))
27027 /* D has already been instantiated or explicitly specialized, so
27028 there's nothing for us to do here.
27030 It might seem reasonable to check whether or not D is an explicit
27031 instantiation, and, if so, stop here. But when an explicit
27032 instantiation is deferred until the end of the compilation,
27033 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27034 the instantiation. */
27035 return d;
27037 /* Check to see whether we know that this template will be
27038 instantiated in some other file, as with "extern template"
27039 extension. */
27040 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27042 /* In general, we do not instantiate such templates. */
27043 if (external_p && !always_instantiate_p (d))
27044 return d;
27046 gen_tmpl = most_general_template (tmpl);
27047 gen_args = DECL_TI_ARGS (d);
27049 /* We should already have the extra args. */
27050 gcc_checking_assert (tmpl == gen_tmpl
27051 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27052 == TMPL_ARGS_DEPTH (gen_args)));
27053 /* And what's in the hash table should match D. */
27054 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27055 == d
27056 || spec == NULL_TREE);
27058 /* This needs to happen before any tsubsting. */
27059 if (! push_tinst_level (d))
27060 return d;
27062 auto_timevar tv (TV_TEMPLATE_INST);
27064 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27065 for the instantiation. */
27066 td = template_for_substitution (d);
27067 args = gen_args;
27069 if (variable_template_specialization_p (d))
27071 /* Look up an explicit specialization, if any. */
27072 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27073 if (partial_ti && partial_ti != error_mark_node)
27075 td = TI_TEMPLATE (partial_ti);
27076 args = TI_ARGS (partial_ti);
27080 code_pattern = DECL_TEMPLATE_RESULT (td);
27082 /* We should never be trying to instantiate a member of a class
27083 template or partial specialization. */
27084 gcc_assert (d != code_pattern);
27086 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27087 || DECL_TEMPLATE_SPECIALIZATION (td))
27088 /* In the case of a friend template whose definition is provided
27089 outside the class, we may have too many arguments. Drop the
27090 ones we don't need. The same is true for specializations. */
27091 args = get_innermost_template_args
27092 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27094 if (TREE_CODE (d) == FUNCTION_DECL)
27096 deleted_p = DECL_DELETED_FN (code_pattern);
27097 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27098 && DECL_INITIAL (code_pattern) != error_mark_node)
27099 || DECL_DEFAULTED_FN (code_pattern)
27100 || deleted_p);
27102 else
27104 deleted_p = false;
27105 if (DECL_CLASS_SCOPE_P (code_pattern))
27106 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27107 else
27108 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27111 /* We may be in the middle of deferred access check. Disable it now. */
27112 push_deferring_access_checks (dk_no_deferred);
27114 /* Unless an explicit instantiation directive has already determined
27115 the linkage of D, remember that a definition is available for
27116 this entity. */
27117 if (pattern_defined
27118 && !DECL_INTERFACE_KNOWN (d)
27119 && !DECL_NOT_REALLY_EXTERN (d))
27120 mark_definable (d);
27122 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27123 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27124 input_location = DECL_SOURCE_LOCATION (d);
27126 /* If D is a member of an explicitly instantiated class template,
27127 and no definition is available, treat it like an implicit
27128 instantiation. */
27129 if (!pattern_defined && expl_inst_class_mem_p
27130 && DECL_EXPLICIT_INSTANTIATION (d))
27132 /* Leave linkage flags alone on instantiations with anonymous
27133 visibility. */
27134 if (TREE_PUBLIC (d))
27136 DECL_NOT_REALLY_EXTERN (d) = 0;
27137 DECL_INTERFACE_KNOWN (d) = 0;
27139 SET_DECL_IMPLICIT_INSTANTIATION (d);
27142 /* Defer all other templates, unless we have been explicitly
27143 forbidden from doing so. */
27144 if (/* If there is no definition, we cannot instantiate the
27145 template. */
27146 ! pattern_defined
27147 /* If it's OK to postpone instantiation, do so. */
27148 || defer_ok
27149 /* If this is a static data member that will be defined
27150 elsewhere, we don't want to instantiate the entire data
27151 member, but we do want to instantiate the initializer so that
27152 we can substitute that elsewhere. */
27153 || (external_p && VAR_P (d))
27154 /* Handle here a deleted function too, avoid generating
27155 its body (c++/61080). */
27156 || deleted_p)
27158 /* The definition of the static data member is now required so
27159 we must substitute the initializer. */
27160 if (VAR_P (d)
27161 && !DECL_INITIAL (d)
27162 && DECL_INITIAL (code_pattern))
27164 tree ns;
27165 tree init;
27166 bool const_init = false;
27167 bool enter_context = DECL_CLASS_SCOPE_P (d);
27169 ns = decl_namespace_context (d);
27170 push_nested_namespace (ns);
27171 if (enter_context)
27172 push_nested_class (DECL_CONTEXT (d));
27173 init = tsubst_expr (DECL_INITIAL (code_pattern),
27174 args,
27175 tf_warning_or_error, NULL_TREE);
27176 /* If instantiating the initializer involved instantiating this
27177 again, don't call cp_finish_decl twice. */
27178 if (!DECL_INITIAL (d))
27180 /* Make sure the initializer is still constant, in case of
27181 circular dependency (template/instantiate6.C). */
27182 const_init
27183 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27184 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27185 /*asmspec_tree=*/NULL_TREE, 0);
27187 if (enter_context)
27188 pop_nested_class ();
27189 pop_nested_namespace (ns);
27192 /* We restore the source position here because it's used by
27193 add_pending_template. */
27194 input_location = saved_loc;
27196 if (at_eof && !pattern_defined
27197 && DECL_EXPLICIT_INSTANTIATION (d)
27198 && DECL_NOT_REALLY_EXTERN (d))
27199 /* [temp.explicit]
27201 The definition of a non-exported function template, a
27202 non-exported member function template, or a non-exported
27203 member function or static data member of a class template
27204 shall be present in every translation unit in which it is
27205 explicitly instantiated. */
27206 permerror (input_location, "explicit instantiation of %qD "
27207 "but no definition available", d);
27209 /* If we're in unevaluated context, we just wanted to get the
27210 constant value; this isn't an odr use, so don't queue
27211 a full instantiation. */
27212 if (!cp_unevaluated_operand
27213 /* ??? Historically, we have instantiated inline functions, even
27214 when marked as "extern template". */
27215 && !(external_p && VAR_P (d)))
27216 add_pending_template (d);
27218 else
27220 set_instantiating_module (d);
27221 if (variable_template_p (gen_tmpl))
27222 note_variable_template_instantiation (d);
27223 instantiate_body (td, args, d, false);
27226 pop_deferring_access_checks ();
27227 pop_tinst_level ();
27228 input_location = saved_loc;
27229 cp_unevaluated_operand = saved_unevaluated_operand;
27230 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
27232 return d;
27235 /* Run through the list of templates that we wish we could
27236 instantiate, and instantiate any we can. RETRIES is the
27237 number of times we retry pending template instantiation. */
27239 void
27240 instantiate_pending_templates (int retries)
27242 int reconsider;
27243 location_t saved_loc = input_location;
27245 /* Instantiating templates may trigger vtable generation. This in turn
27246 may require further template instantiations. We place a limit here
27247 to avoid infinite loop. */
27248 if (pending_templates && retries >= max_tinst_depth)
27250 tree decl = pending_templates->tinst->maybe_get_node ();
27252 fatal_error (input_location,
27253 "template instantiation depth exceeds maximum of %d"
27254 " instantiating %q+D, possibly from virtual table generation"
27255 " (use %<-ftemplate-depth=%> to increase the maximum)",
27256 max_tinst_depth, decl);
27257 if (TREE_CODE (decl) == FUNCTION_DECL)
27258 /* Pretend that we defined it. */
27259 DECL_INITIAL (decl) = error_mark_node;
27260 return;
27265 struct pending_template **t = &pending_templates;
27266 struct pending_template *last = NULL;
27267 reconsider = 0;
27268 while (*t)
27270 tree instantiation = reopen_tinst_level ((*t)->tinst);
27271 bool complete = false;
27273 if (TYPE_P (instantiation))
27275 if (!COMPLETE_TYPE_P (instantiation))
27277 instantiate_class_template (instantiation);
27278 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27279 for (tree fld = TYPE_FIELDS (instantiation);
27280 fld; fld = TREE_CHAIN (fld))
27281 if ((VAR_P (fld)
27282 || (TREE_CODE (fld) == FUNCTION_DECL
27283 && !DECL_ARTIFICIAL (fld)))
27284 && DECL_TEMPLATE_INSTANTIATION (fld))
27285 instantiate_decl (fld,
27286 /*defer_ok=*/false,
27287 /*expl_inst_class_mem_p=*/false);
27289 if (COMPLETE_TYPE_P (instantiation))
27290 reconsider = 1;
27293 complete = COMPLETE_TYPE_P (instantiation);
27295 else
27297 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27298 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27300 instantiation
27301 = instantiate_decl (instantiation,
27302 /*defer_ok=*/false,
27303 /*expl_inst_class_mem_p=*/false);
27304 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27305 reconsider = 1;
27308 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27309 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27312 if (complete)
27314 /* If INSTANTIATION has been instantiated, then we don't
27315 need to consider it again in the future. */
27316 struct pending_template *drop = *t;
27317 *t = (*t)->next;
27318 set_refcount_ptr (drop->tinst);
27319 pending_template_freelist ().free (drop);
27321 else
27323 last = *t;
27324 t = &(*t)->next;
27326 tinst_depth = 0;
27327 set_refcount_ptr (current_tinst_level);
27329 last_pending_template = last;
27331 while (reconsider);
27333 input_location = saved_loc;
27336 /* Substitute ARGVEC into T, which is a list of initializers for
27337 either base class or a non-static data member. The TREE_PURPOSEs
27338 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27339 instantiate_decl. */
27341 static tree
27342 tsubst_initializer_list (tree t, tree argvec)
27344 tree inits = NULL_TREE;
27345 tree target_ctor = error_mark_node;
27347 for (; t; t = TREE_CHAIN (t))
27349 tree decl;
27350 tree init;
27351 tree expanded_bases = NULL_TREE;
27352 tree expanded_arguments = NULL_TREE;
27353 int i, len = 1;
27355 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27357 tree expr;
27358 tree arg;
27360 /* Expand the base class expansion type into separate base
27361 classes. */
27362 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27363 tf_warning_or_error,
27364 NULL_TREE);
27365 if (expanded_bases == error_mark_node)
27366 continue;
27368 /* We'll be building separate TREE_LISTs of arguments for
27369 each base. */
27370 len = TREE_VEC_LENGTH (expanded_bases);
27371 expanded_arguments = make_tree_vec (len);
27372 for (i = 0; i < len; i++)
27373 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27375 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27376 expand each argument in the TREE_VALUE of t. */
27377 expr = make_node (EXPR_PACK_EXPANSION);
27378 PACK_EXPANSION_LOCAL_P (expr) = true;
27379 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27380 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27382 if (TREE_VALUE (t) == void_type_node)
27383 /* VOID_TYPE_NODE is used to indicate
27384 value-initialization. */
27386 for (i = 0; i < len; i++)
27387 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27389 else
27391 /* Substitute parameter packs into each argument in the
27392 TREE_LIST. */
27393 in_base_initializer = 1;
27394 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27396 tree expanded_exprs;
27398 /* Expand the argument. */
27399 tree value;
27400 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27401 value = TREE_VALUE (arg);
27402 else
27404 value = expr;
27405 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27407 expanded_exprs
27408 = tsubst_pack_expansion (value, argvec,
27409 tf_warning_or_error,
27410 NULL_TREE);
27411 if (expanded_exprs == error_mark_node)
27412 continue;
27414 /* Prepend each of the expanded expressions to the
27415 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27416 for (i = 0; i < len; i++)
27417 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27418 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27419 TREE_VEC_ELT (expanded_arguments, i)
27420 = tree_cons (NULL_TREE,
27421 TREE_VEC_ELT (expanded_exprs, j),
27422 TREE_VEC_ELT (expanded_arguments, i));
27423 else
27424 TREE_VEC_ELT (expanded_arguments, i)
27425 = tree_cons (NULL_TREE,
27426 TREE_VEC_ELT (expanded_exprs, i),
27427 TREE_VEC_ELT (expanded_arguments, i));
27429 in_base_initializer = 0;
27431 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27432 since we built them backwards. */
27433 for (i = 0; i < len; i++)
27435 TREE_VEC_ELT (expanded_arguments, i) =
27436 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27441 for (i = 0; i < len; ++i)
27443 if (expanded_bases)
27445 decl = TREE_VEC_ELT (expanded_bases, i);
27446 decl = expand_member_init (decl);
27447 init = TREE_VEC_ELT (expanded_arguments, i);
27449 else
27451 tree tmp;
27452 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27453 tf_warning_or_error, NULL_TREE);
27455 decl = expand_member_init (decl);
27456 if (decl && !DECL_P (decl))
27457 in_base_initializer = 1;
27459 init = TREE_VALUE (t);
27460 tmp = init;
27461 if (init != void_type_node)
27462 init = tsubst_expr (init, argvec,
27463 tf_warning_or_error, NULL_TREE);
27464 if (init == NULL_TREE && tmp != NULL_TREE)
27465 /* If we had an initializer but it instantiated to nothing,
27466 value-initialize the object. This will only occur when
27467 the initializer was a pack expansion where the parameter
27468 packs used in that expansion were of length zero. */
27469 init = void_type_node;
27470 in_base_initializer = 0;
27473 if (target_ctor != error_mark_node
27474 && init != error_mark_node)
27476 error ("mem-initializer for %qD follows constructor delegation",
27477 decl);
27478 return inits;
27480 /* Look for a target constructor. */
27481 if (init != error_mark_node
27482 && decl && CLASS_TYPE_P (decl)
27483 && same_type_p (decl, current_class_type))
27485 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27486 if (inits)
27488 error ("constructor delegation follows mem-initializer for %qD",
27489 TREE_PURPOSE (inits));
27490 continue;
27492 target_ctor = init;
27495 if (decl)
27497 init = build_tree_list (decl, init);
27498 /* Carry over the dummy TREE_TYPE node containing the source
27499 location. */
27500 TREE_TYPE (init) = TREE_TYPE (t);
27501 TREE_CHAIN (init) = inits;
27502 inits = init;
27506 return inits;
27509 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27510 is the instantiation (which should have been created with
27511 start_enum) and ARGS are the template arguments to use. */
27513 static void
27514 tsubst_enum (tree tag, tree newtag, tree args)
27516 tree e;
27518 if (SCOPED_ENUM_P (newtag))
27519 begin_scope (sk_scoped_enum, newtag);
27521 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27523 tree value;
27524 tree decl = TREE_VALUE (e);
27526 /* Note that in a template enum, the TREE_VALUE is the
27527 CONST_DECL, not the corresponding INTEGER_CST. */
27528 value = tsubst_expr (DECL_INITIAL (decl),
27529 args, tf_warning_or_error, NULL_TREE);
27531 /* Give this enumeration constant the correct access. */
27532 set_current_access_from_decl (decl);
27534 /* Actually build the enumerator itself. Here we're assuming that
27535 enumerators can't have dependent attributes. */
27536 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27537 DECL_ATTRIBUTES (decl),
27538 DECL_SOURCE_LOCATION (decl));
27539 /* Attribute deprecated without an argument isn't sticky: it'll
27540 melt into a tree flag, so we need to propagate the flag here,
27541 since we just created a new enumerator. */
27542 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27543 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27546 if (SCOPED_ENUM_P (newtag))
27547 finish_scope ();
27549 finish_enum_value_list (newtag);
27550 finish_enum (newtag);
27552 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27553 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27554 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27555 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27558 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27559 its type -- but without substituting the innermost set of template
27560 arguments. So, innermost set of template parameters will appear in
27561 the type. */
27563 tree
27564 get_mostly_instantiated_function_type (tree decl)
27566 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27567 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27570 /* Return truthvalue if we're processing a template different from
27571 the last one involved in diagnostics. */
27572 bool
27573 problematic_instantiation_changed (void)
27575 return current_tinst_level != last_error_tinst_level;
27578 /* Remember current template involved in diagnostics. */
27579 void
27580 record_last_problematic_instantiation (void)
27582 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27585 struct tinst_level *
27586 current_instantiation (void)
27588 return current_tinst_level;
27591 /* Return TRUE if current_function_decl is being instantiated, false
27592 otherwise. */
27594 bool
27595 instantiating_current_function_p (void)
27597 return (current_instantiation ()
27598 && (current_instantiation ()->maybe_get_node ()
27599 == current_function_decl));
27602 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27603 type. Return false for ok, true for disallowed. Issue error and
27604 inform messages under control of COMPLAIN. */
27606 static bool
27607 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27609 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27610 return false;
27611 else if (TYPE_PTR_P (type))
27612 return false;
27613 else if (TYPE_REF_P (type)
27614 && !TYPE_REF_IS_RVALUE (type))
27615 return false;
27616 else if (TYPE_PTRMEM_P (type))
27617 return false;
27618 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27620 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27622 if (complain & tf_error)
27623 error ("non-type template parameters of deduced class type only "
27624 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27625 return true;
27627 return false;
27629 else if (TREE_CODE (type) == NULLPTR_TYPE)
27630 return false;
27631 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27632 && cxx_dialect < cxx11)
27633 /* Fall through; before C++11 alias templates, a bound ttp
27634 always instantiates into a class type. */;
27635 else if (WILDCARD_TYPE_P (type))
27636 /* Any other wildcard type not already handled above is allowed. */
27637 return false;
27638 else if (TREE_CODE (type) == COMPLEX_TYPE)
27639 /* Fall through. */;
27640 else if (VOID_TYPE_P (type))
27641 /* Fall through. */;
27642 else if (cxx_dialect >= cxx20)
27644 if (dependent_type_p (type))
27645 return false;
27646 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27647 return true;
27648 if (structural_type_p (type))
27649 return false;
27650 if (complain & tf_error)
27652 auto_diagnostic_group d;
27653 error ("%qT is not a valid type for a template non-type "
27654 "parameter because it is not structural", type);
27655 structural_type_p (type, true);
27657 return true;
27659 else if (CLASS_TYPE_P (type))
27661 if (complain & tf_error)
27662 error ("non-type template parameters of class type only available "
27663 "with %<-std=c++20%> or %<-std=gnu++20%>");
27664 return true;
27667 if (complain & tf_error)
27669 if (type == error_mark_node)
27670 inform (input_location, "invalid template non-type parameter");
27671 else
27672 error ("%q#T is not a valid type for a template non-type parameter",
27673 type);
27675 return true;
27678 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27680 static bool
27681 value_dependent_noexcept_spec_p (tree type)
27683 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27684 if (tree noex = TREE_PURPOSE (spec))
27685 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27686 affect overload resolution and treating it as dependent breaks
27687 things. Same for an unparsed noexcept expression. */
27688 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27689 && TREE_CODE (noex) != DEFERRED_PARSE
27690 && value_dependent_expression_p (noex))
27691 return true;
27693 return false;
27696 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27697 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27699 static bool
27700 dependent_type_p_r (tree type)
27702 tree scope;
27704 /* [temp.dep.type]
27706 A type is dependent if it is:
27708 -- a template parameter. Template template parameters are types
27709 for us (since TYPE_P holds true for them) so we handle
27710 them here. */
27711 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27712 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27713 return true;
27714 /* -- a qualified-id with a nested-name-specifier which contains a
27715 class-name that names a dependent type or whose unqualified-id
27716 names a dependent type. */
27717 if (TREE_CODE (type) == TYPENAME_TYPE)
27718 return true;
27720 /* An alias template specialization can be dependent even if the
27721 resulting type is not. */
27722 if (dependent_alias_template_spec_p (type, nt_transparent))
27723 return true;
27725 /* -- a cv-qualified type where the cv-unqualified type is
27726 dependent.
27727 No code is necessary for this bullet; the code below handles
27728 cv-qualified types, and we don't want to strip aliases with
27729 TYPE_MAIN_VARIANT because of DR 1558. */
27730 /* -- a compound type constructed from any dependent type. */
27731 if (TYPE_PTRMEM_P (type))
27732 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27733 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27734 (type)));
27735 else if (INDIRECT_TYPE_P (type))
27736 return dependent_type_p (TREE_TYPE (type));
27737 else if (FUNC_OR_METHOD_TYPE_P (type))
27739 tree arg_type;
27741 if (dependent_type_p (TREE_TYPE (type)))
27742 return true;
27743 for (arg_type = TYPE_ARG_TYPES (type);
27744 arg_type;
27745 arg_type = TREE_CHAIN (arg_type))
27746 if (dependent_type_p (TREE_VALUE (arg_type)))
27747 return true;
27748 if (cxx_dialect >= cxx17
27749 && value_dependent_noexcept_spec_p (type))
27750 /* A value-dependent noexcept-specifier makes the type dependent. */
27751 return true;
27752 return false;
27754 /* -- an array type constructed from any dependent type or whose
27755 size is specified by a constant expression that is
27756 value-dependent.
27758 We checked for type- and value-dependence of the bounds in
27759 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27760 if (TREE_CODE (type) == ARRAY_TYPE)
27762 if (TYPE_DOMAIN (type)
27763 && dependent_type_p (TYPE_DOMAIN (type)))
27764 return true;
27765 return dependent_type_p (TREE_TYPE (type));
27768 /* -- a template-id in which either the template name is a template
27769 parameter ... */
27770 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27771 return true;
27772 /* ... or any of the template arguments is a dependent type or
27773 an expression that is type-dependent or value-dependent. */
27774 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27775 && (any_dependent_template_arguments_p
27776 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27777 return true;
27779 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27780 dependent; if the argument of the `typeof' expression is not
27781 type-dependent, then it should already been have resolved. */
27782 if (TREE_CODE (type) == TYPEOF_TYPE
27783 || TREE_CODE (type) == DECLTYPE_TYPE
27784 || TREE_CODE (type) == TRAIT_TYPE)
27785 return true;
27787 /* A template argument pack is dependent if any of its packed
27788 arguments are. */
27789 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27791 tree args = ARGUMENT_PACK_ARGS (type);
27792 for (tree arg : tree_vec_range (args))
27793 if (dependent_template_arg_p (arg))
27794 return true;
27797 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27798 be template parameters. */
27799 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27800 return true;
27802 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27803 return true;
27805 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27806 return true;
27808 /* The standard does not specifically mention types that are local
27809 to template functions or local classes, but they should be
27810 considered dependent too. For example:
27812 template <int I> void f() {
27813 enum E { a = I };
27814 S<sizeof (E)> s;
27817 The size of `E' cannot be known until the value of `I' has been
27818 determined. Therefore, `E' must be considered dependent. */
27819 scope = TYPE_CONTEXT (type);
27820 if (scope && TYPE_P (scope))
27821 return dependent_type_p (scope);
27822 /* Don't use type_dependent_expression_p here, as it can lead
27823 to infinite recursion trying to determine whether a lambda
27824 nested in a lambda is dependent (c++/47687). */
27825 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27826 && DECL_LANG_SPECIFIC (scope)
27827 && DECL_TEMPLATE_INFO (scope)
27828 && (any_dependent_template_arguments_p
27829 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27830 return true;
27832 /* Other types are non-dependent. */
27833 return false;
27836 /* Returns TRUE if TYPE is dependent, in the sense of
27837 [temp.dep.type]. Note that a NULL type is considered dependent. */
27839 bool
27840 dependent_type_p (tree type)
27842 /* If there are no template parameters in scope, then there can't be
27843 any dependent types. */
27844 if (!processing_template_decl)
27846 /* If we are not processing a template, then nobody should be
27847 providing us with a dependent type. */
27848 gcc_assert (type);
27849 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27850 return false;
27853 /* If the type is NULL, we have not computed a type for the entity
27854 in question; in that case, the type is dependent. */
27855 if (!type)
27856 return true;
27858 /* Erroneous types can be considered non-dependent. */
27859 if (type == error_mark_node)
27860 return false;
27862 /* If we have not already computed the appropriate value for TYPE,
27863 do so now. */
27864 if (!TYPE_DEPENDENT_P_VALID (type))
27866 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27867 TYPE_DEPENDENT_P_VALID (type) = 1;
27870 return TYPE_DEPENDENT_P (type);
27873 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27874 lookup. In other words, a dependent type that is not the current
27875 instantiation. */
27877 bool
27878 dependent_scope_p (tree scope)
27880 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27881 && !currently_open_class (scope));
27884 /* True if we might find more declarations in SCOPE during instantiation than
27885 we can when parsing the template. */
27887 bool
27888 dependentish_scope_p (tree scope)
27890 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27893 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27894 an unknown base of 'this' (and is therefore instantiation-dependent). */
27896 static bool
27897 unknown_base_ref_p (tree t)
27899 if (!current_class_ptr)
27900 return false;
27902 tree mem = TREE_OPERAND (t, 1);
27903 if (shared_member_p (mem))
27904 return false;
27906 tree cur = current_nonlambda_class_type ();
27907 if (!any_dependent_bases_p (cur))
27908 return false;
27910 tree ctx = TREE_OPERAND (t, 0);
27911 if (DERIVED_FROM_P (ctx, cur))
27912 return false;
27914 return true;
27917 /* T is a SCOPE_REF; return whether we need to consider it
27918 instantiation-dependent so that we can check access at instantiation
27919 time even though we know which member it resolves to. */
27921 static bool
27922 instantiation_dependent_scope_ref_p (tree t)
27924 if (DECL_P (TREE_OPERAND (t, 1))
27925 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27926 && !dependent_scope_p (TREE_OPERAND (t, 0))
27927 && !unknown_base_ref_p (t)
27928 && accessible_in_template_p (TREE_OPERAND (t, 0),
27929 TREE_OPERAND (t, 1)))
27930 return false;
27931 else
27932 return true;
27935 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27936 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27937 expression. */
27939 /* Note that this predicate is not appropriate for general expressions;
27940 only constant expressions (that satisfy potential_constant_expression)
27941 can be tested for value dependence. */
27943 bool
27944 value_dependent_expression_p (tree expression)
27946 if (!processing_template_decl || expression == NULL_TREE)
27947 return false;
27949 /* A type-dependent expression is also value-dependent. */
27950 if (type_dependent_expression_p (expression))
27951 return true;
27953 switch (TREE_CODE (expression))
27955 case BASELINK:
27956 /* A dependent member function of the current instantiation. */
27957 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27959 case FUNCTION_DECL:
27960 /* A dependent member function of the current instantiation. */
27961 if (DECL_CLASS_SCOPE_P (expression)
27962 && dependent_type_p (DECL_CONTEXT (expression)))
27963 return true;
27964 break;
27966 case IDENTIFIER_NODE:
27967 /* A name that has not been looked up -- must be dependent. */
27968 return true;
27970 case TEMPLATE_PARM_INDEX:
27971 /* A non-type template parm. */
27972 return true;
27974 case CONST_DECL:
27975 /* A non-type template parm. */
27976 if (DECL_TEMPLATE_PARM_P (expression))
27977 return true;
27978 return value_dependent_expression_p (DECL_INITIAL (expression));
27980 case VAR_DECL:
27981 /* A constant with literal type and is initialized
27982 with an expression that is value-dependent. */
27983 if (DECL_DEPENDENT_INIT_P (expression))
27984 return true;
27985 if (DECL_HAS_VALUE_EXPR_P (expression))
27987 tree value_expr = DECL_VALUE_EXPR (expression);
27988 if (value_dependent_expression_p (value_expr)
27989 /* __PRETTY_FUNCTION__ inside a template function is dependent
27990 on the name of the function. */
27991 || (DECL_PRETTY_FUNCTION_P (expression)
27992 /* It might be used in a template, but not a template
27993 function, in which case its DECL_VALUE_EXPR will be
27994 "top level". */
27995 && value_expr == error_mark_node))
27996 return true;
27998 else if (TYPE_REF_P (TREE_TYPE (expression)))
27999 /* FIXME cp_finish_decl doesn't fold reference initializers. */
28000 return true;
28001 /* We have a constexpr variable and we're processing a template. When
28002 there's lifetime extension involved (for which finish_compound_literal
28003 used to create a temporary), we'll not be able to evaluate the
28004 variable until instantiating, so pretend it's value-dependent. */
28005 else if (DECL_DECLARED_CONSTEXPR_P (expression)
28006 && !TREE_CONSTANT (expression))
28007 return true;
28008 return false;
28010 case DYNAMIC_CAST_EXPR:
28011 case STATIC_CAST_EXPR:
28012 case CONST_CAST_EXPR:
28013 case REINTERPRET_CAST_EXPR:
28014 case CAST_EXPR:
28015 case IMPLICIT_CONV_EXPR:
28016 /* These expressions are value-dependent if the type to which
28017 the cast occurs is dependent or the expression being casted
28018 is value-dependent. */
28020 tree type = TREE_TYPE (expression);
28022 if (dependent_type_p (type))
28023 return true;
28025 /* A functional cast has a list of operands. */
28026 expression = TREE_OPERAND (expression, 0);
28027 if (!expression)
28029 /* If there are no operands, it must be an expression such
28030 as "int()". This should not happen for aggregate types
28031 because it would form non-constant expressions. */
28032 gcc_assert (cxx_dialect >= cxx11
28033 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28035 return false;
28038 if (TREE_CODE (expression) == TREE_LIST)
28039 return any_value_dependent_elements_p (expression);
28041 if (TREE_CODE (type) == REFERENCE_TYPE
28042 && has_value_dependent_address (expression))
28043 return true;
28045 return value_dependent_expression_p (expression);
28048 case SIZEOF_EXPR:
28049 if (SIZEOF_EXPR_TYPE_P (expression))
28050 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28051 /* FALLTHRU */
28052 case ALIGNOF_EXPR:
28053 case TYPEID_EXPR:
28054 /* A `sizeof' expression is value-dependent if the operand is
28055 type-dependent or is a pack expansion. */
28056 expression = TREE_OPERAND (expression, 0);
28057 if (PACK_EXPANSION_P (expression))
28058 return true;
28059 else if (TYPE_P (expression))
28060 return dependent_type_p (expression);
28061 return instantiation_dependent_uneval_expression_p (expression);
28063 case AT_ENCODE_EXPR:
28064 /* An 'encode' expression is value-dependent if the operand is
28065 type-dependent. */
28066 expression = TREE_OPERAND (expression, 0);
28067 return dependent_type_p (expression);
28069 case NOEXCEPT_EXPR:
28070 expression = TREE_OPERAND (expression, 0);
28071 return instantiation_dependent_uneval_expression_p (expression);
28073 case SCOPE_REF:
28074 /* All instantiation-dependent expressions should also be considered
28075 value-dependent. */
28076 return instantiation_dependent_scope_ref_p (expression);
28078 case COMPONENT_REF:
28079 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28080 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28082 case NONTYPE_ARGUMENT_PACK:
28083 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28084 is value-dependent. */
28085 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28086 if (value_dependent_expression_p (arg))
28087 return true;
28088 return false;
28090 case TRAIT_EXPR:
28092 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28093 return true;
28095 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28096 if (!type2)
28097 return false;
28099 if (TREE_CODE (type2) != TREE_VEC)
28100 return dependent_type_p (type2);
28102 for (tree arg : tree_vec_range (type2))
28103 if (dependent_type_p (arg))
28104 return true;
28106 return false;
28109 case MODOP_EXPR:
28110 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28111 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28113 case ARRAY_REF:
28114 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28115 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28117 case ADDR_EXPR:
28119 tree op = TREE_OPERAND (expression, 0);
28120 return (value_dependent_expression_p (op)
28121 || has_value_dependent_address (op));
28124 case REQUIRES_EXPR:
28125 /* Treat all requires-expressions as value-dependent so
28126 we don't try to fold them. */
28127 return true;
28129 case TYPE_REQ:
28130 return dependent_type_p (TREE_OPERAND (expression, 0));
28132 case CALL_EXPR:
28134 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28135 return true;
28136 tree fn = get_callee_fndecl (expression);
28137 int i, nargs;
28138 nargs = call_expr_nargs (expression);
28139 for (i = 0; i < nargs; ++i)
28141 tree op = CALL_EXPR_ARG (expression, i);
28142 /* In a call to a constexpr member function, look through the
28143 implicit ADDR_EXPR on the object argument so that it doesn't
28144 cause the call to be considered value-dependent. We also
28145 look through it in potential_constant_expression. */
28146 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28147 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
28148 && TREE_CODE (op) == ADDR_EXPR)
28149 op = TREE_OPERAND (op, 0);
28150 if (value_dependent_expression_p (op))
28151 return true;
28153 return false;
28156 case TEMPLATE_ID_EXPR:
28157 return concept_definition_p (TREE_OPERAND (expression, 0))
28158 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28160 case CONSTRUCTOR:
28162 unsigned ix;
28163 tree val;
28164 if (dependent_type_p (TREE_TYPE (expression)))
28165 return true;
28166 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28167 if (value_dependent_expression_p (val))
28168 return true;
28169 return false;
28172 case STMT_EXPR:
28173 /* Treat a GNU statement expression as dependent to avoid crashing
28174 under instantiate_non_dependent_expr; it can't be constant. */
28175 return true;
28177 case NEW_EXPR:
28178 case VEC_NEW_EXPR:
28179 /* The second operand is a type, which type_dependent_expression_p
28180 (and therefore value_dependent_expression_p) doesn't want to see. */
28181 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28182 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28183 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28185 default:
28186 /* A constant expression is value-dependent if any subexpression is
28187 value-dependent. */
28188 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28190 case tcc_reference:
28191 case tcc_unary:
28192 case tcc_comparison:
28193 case tcc_binary:
28194 case tcc_expression:
28195 case tcc_vl_exp:
28197 int i, len = cp_tree_operand_length (expression);
28199 for (i = 0; i < len; i++)
28201 tree t = TREE_OPERAND (expression, i);
28203 /* In some cases, some of the operands may be missing.
28204 (For example, in the case of PREDECREMENT_EXPR, the
28205 amount to increment by may be missing.) That doesn't
28206 make the expression dependent. */
28207 if (t && value_dependent_expression_p (t))
28208 return true;
28211 break;
28212 default:
28213 break;
28215 break;
28218 /* The expression is not value-dependent. */
28219 return false;
28222 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28223 [temp.dep.expr]. Note that an expression with no type is
28224 considered dependent. Other parts of the compiler arrange for an
28225 expression with type-dependent subexpressions to have no type, so
28226 this function doesn't have to be fully recursive. */
28228 bool
28229 type_dependent_expression_p (tree expression)
28231 if (!processing_template_decl)
28232 return false;
28234 if (expression == NULL_TREE || expression == error_mark_node)
28235 return false;
28237 gcc_checking_assert (!TYPE_P (expression));
28239 STRIP_ANY_LOCATION_WRAPPER (expression);
28241 /* An unresolved name is always dependent. */
28242 if (identifier_p (expression)
28243 || TREE_CODE (expression) == USING_DECL
28244 || TREE_CODE (expression) == WILDCARD_DECL)
28245 return true;
28247 /* A lambda-expression in template context is dependent. dependent_type_p is
28248 true for a lambda in the scope of a class or function template, but that
28249 doesn't cover all template contexts, like a default template argument. */
28250 if (TREE_CODE (expression) == LAMBDA_EXPR)
28251 return true;
28253 /* A fold expression is type-dependent. */
28254 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28255 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28256 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28257 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28258 return true;
28260 /* Some expression forms are never type-dependent. */
28261 if (TREE_CODE (expression) == SIZEOF_EXPR
28262 || TREE_CODE (expression) == ALIGNOF_EXPR
28263 || TREE_CODE (expression) == AT_ENCODE_EXPR
28264 || TREE_CODE (expression) == NOEXCEPT_EXPR
28265 || TREE_CODE (expression) == TRAIT_EXPR
28266 || TREE_CODE (expression) == TYPEID_EXPR
28267 || TREE_CODE (expression) == DELETE_EXPR
28268 || TREE_CODE (expression) == VEC_DELETE_EXPR
28269 || TREE_CODE (expression) == THROW_EXPR
28270 || TREE_CODE (expression) == REQUIRES_EXPR)
28271 return false;
28273 /* The types of these expressions depends only on the type to which
28274 the cast occurs. */
28275 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28276 || TREE_CODE (expression) == STATIC_CAST_EXPR
28277 || TREE_CODE (expression) == CONST_CAST_EXPR
28278 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28279 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28280 || TREE_CODE (expression) == CAST_EXPR)
28281 return dependent_type_p (TREE_TYPE (expression));
28283 /* The types of these expressions depends only on the type created
28284 by the expression. */
28285 if (TREE_CODE (expression) == NEW_EXPR
28286 || TREE_CODE (expression) == VEC_NEW_EXPR)
28288 /* For NEW_EXPR tree nodes created inside a template, either
28289 the object type itself or a TREE_LIST may appear as the
28290 operand 1. */
28291 tree type = TREE_OPERAND (expression, 1);
28292 if (TREE_CODE (type) == TREE_LIST)
28293 /* This is an array type. We need to check array dimensions
28294 as well. */
28295 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28296 || value_dependent_expression_p
28297 (TREE_OPERAND (TREE_VALUE (type), 1));
28298 /* Array type whose dimension has to be deduced. */
28299 else if (TREE_CODE (type) == ARRAY_TYPE
28300 && TREE_OPERAND (expression, 2) == NULL_TREE)
28301 return true;
28302 else
28303 return dependent_type_p (type);
28306 if (TREE_CODE (expression) == SCOPE_REF)
28308 tree scope = TREE_OPERAND (expression, 0);
28309 tree name = TREE_OPERAND (expression, 1);
28311 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28312 contains an identifier associated by name lookup with one or more
28313 declarations declared with a dependent type, or...a
28314 nested-name-specifier or qualified-id that names a member of an
28315 unknown specialization. */
28316 return (type_dependent_expression_p (name)
28317 || dependent_scope_p (scope));
28320 if (TREE_CODE (expression) == TEMPLATE_DECL
28321 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28322 return uses_outer_template_parms (expression);
28324 if (TREE_CODE (expression) == STMT_EXPR)
28325 expression = stmt_expr_value_expr (expression);
28327 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28329 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28330 if (type_dependent_expression_p (elt.value))
28331 return true;
28332 return false;
28335 /* A static data member of the current instantiation with incomplete
28336 array type is type-dependent, as the definition and specializations
28337 can have different bounds. */
28338 if (VAR_P (expression)
28339 && DECL_CLASS_SCOPE_P (expression)
28340 && dependent_type_p (DECL_CONTEXT (expression))
28341 && VAR_HAD_UNKNOWN_BOUND (expression))
28342 return true;
28344 /* An array of unknown bound depending on a variadic parameter, eg:
28346 template<typename... Args>
28347 void foo (Args... args)
28349 int arr[] = { args... };
28352 template<int... vals>
28353 void bar ()
28355 int arr[] = { vals... };
28358 If the array has no length and has an initializer, it must be that
28359 we couldn't determine its length in cp_complete_array_type because
28360 it is dependent. */
28361 if (((VAR_P (expression) && DECL_INITIAL (expression))
28362 || COMPOUND_LITERAL_P (expression))
28363 && TREE_TYPE (expression) != NULL_TREE
28364 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28365 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28366 return true;
28368 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28369 if (BASELINK_P (expression))
28371 if (BASELINK_OPTYPE (expression)
28372 && dependent_type_p (BASELINK_OPTYPE (expression)))
28373 return true;
28374 expression = BASELINK_FUNCTIONS (expression);
28377 /* A function or variable template-id is type-dependent if it has any
28378 dependent template arguments. */
28379 if (VAR_OR_FUNCTION_DECL_P (expression)
28380 && DECL_LANG_SPECIFIC (expression)
28381 && DECL_TEMPLATE_INFO (expression))
28383 /* Consider the innermost template arguments, since those are the ones
28384 that come from the template-id; the template arguments for the
28385 enclosing class do not make it type-dependent unless they are used in
28386 the type of the decl. */
28387 if (instantiates_primary_template_p (expression)
28388 && (any_dependent_template_arguments_p
28389 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28390 return true;
28393 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28394 type-dependent. Checking this is important for functions with auto return
28395 type, which looks like a dependent type. */
28396 if (TREE_CODE (expression) == FUNCTION_DECL
28397 && !(DECL_CLASS_SCOPE_P (expression)
28398 && dependent_type_p (DECL_CONTEXT (expression)))
28399 && !(DECL_LANG_SPECIFIC (expression)
28400 && DECL_UNIQUE_FRIEND_P (expression)
28401 && (!DECL_FRIEND_CONTEXT (expression)
28402 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28403 && !DECL_LOCAL_DECL_P (expression))
28405 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28406 || undeduced_auto_decl (expression));
28407 return false;
28410 /* Otherwise, its constraints could still depend on outer template parameters
28411 from its (dependent) scope. */
28412 if (TREE_CODE (expression) == FUNCTION_DECL
28413 /* As an optimization, check this cheaper sufficient condition first.
28414 (At this point we've established that we're looking at a member of
28415 a dependent class, so it makes sense to start treating say undeduced
28416 auto as dependent.) */
28417 && !dependent_type_p (TREE_TYPE (expression))
28418 && uses_outer_template_parms_in_constraints (expression))
28419 return true;
28421 /* Always dependent, on the number of arguments if nothing else. */
28422 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28423 return true;
28425 if (TREE_TYPE (expression) == unknown_type_node)
28427 if (TREE_CODE (expression) == ADDR_EXPR)
28428 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28429 if (TREE_CODE (expression) == COMPONENT_REF
28430 || TREE_CODE (expression) == OFFSET_REF)
28432 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28433 return true;
28434 expression = TREE_OPERAND (expression, 1);
28435 if (identifier_p (expression))
28436 return false;
28438 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28439 if (TREE_CODE (expression) == SCOPE_REF)
28440 return false;
28442 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28443 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28444 || TREE_CODE (expression) == CO_YIELD_EXPR)
28445 return true;
28447 if (BASELINK_P (expression))
28449 if (BASELINK_OPTYPE (expression)
28450 && dependent_type_p (BASELINK_OPTYPE (expression)))
28451 return true;
28452 expression = BASELINK_FUNCTIONS (expression);
28455 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28457 if (any_dependent_template_arguments_p
28458 (TREE_OPERAND (expression, 1)))
28459 return true;
28460 expression = TREE_OPERAND (expression, 0);
28461 if (identifier_p (expression))
28462 return true;
28465 gcc_assert (OVL_P (expression));
28467 for (lkp_iterator iter (expression); iter; ++iter)
28468 if (type_dependent_expression_p (*iter))
28469 return true;
28471 return false;
28474 /* The type of a non-type template parm declared with a placeholder type
28475 depends on the corresponding template argument, even though
28476 placeholders are not normally considered dependent. */
28477 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28478 && is_auto (TREE_TYPE (expression)))
28479 return true;
28481 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28483 /* Dependent type attributes might not have made it from the decl to
28484 the type yet. */
28485 if (DECL_P (expression)
28486 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28487 return true;
28489 return (dependent_type_p (TREE_TYPE (expression)));
28492 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28493 type-dependent if the expression refers to a member of the current
28494 instantiation and the type of the referenced member is dependent, or the
28495 class member access expression refers to a member of an unknown
28496 specialization.
28498 This function returns true if the OBJECT in such a class member access
28499 expression is of an unknown specialization. */
28501 bool
28502 type_dependent_object_expression_p (tree object)
28504 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28505 dependent. */
28506 if (TREE_CODE (object) == IDENTIFIER_NODE)
28507 return true;
28508 tree scope = TREE_TYPE (object);
28509 return (!scope || dependent_scope_p (scope));
28512 /* walk_tree callback function for instantiation_dependent_expression_p,
28513 below. Returns non-zero if a dependent subexpression is found. */
28515 static tree
28516 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28517 void * /*data*/)
28519 if (TYPE_P (*tp))
28521 /* We don't have to worry about decltype currently because decltype
28522 of an instantiation-dependent expr is a dependent type. This
28523 might change depending on the resolution of DR 1172. */
28524 *walk_subtrees = false;
28525 return NULL_TREE;
28527 enum tree_code code = TREE_CODE (*tp);
28528 switch (code)
28530 /* Don't treat an argument list as dependent just because it has no
28531 TREE_TYPE. */
28532 case TREE_LIST:
28533 case TREE_VEC:
28534 case NONTYPE_ARGUMENT_PACK:
28535 return NULL_TREE;
28537 case TEMPLATE_PARM_INDEX:
28538 if (dependent_type_p (TREE_TYPE (*tp)))
28539 return *tp;
28540 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28541 return *tp;
28542 /* We'll check value-dependence separately. */
28543 return NULL_TREE;
28545 /* Handle expressions with type operands. */
28546 case SIZEOF_EXPR:
28547 case ALIGNOF_EXPR:
28548 case TYPEID_EXPR:
28549 case AT_ENCODE_EXPR:
28551 tree op = TREE_OPERAND (*tp, 0);
28552 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28553 op = TREE_TYPE (op);
28554 if (TYPE_P (op))
28556 if (dependent_type_p (op))
28557 return *tp;
28558 else
28560 *walk_subtrees = false;
28561 return NULL_TREE;
28564 break;
28567 case COMPONENT_REF:
28568 if (identifier_p (TREE_OPERAND (*tp, 1)))
28569 /* In a template, finish_class_member_access_expr creates a
28570 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28571 type-dependent, so that we can check access control at
28572 instantiation time (PR 42277). See also Core issue 1273. */
28573 return *tp;
28574 break;
28576 case SCOPE_REF:
28577 if (instantiation_dependent_scope_ref_p (*tp))
28578 return *tp;
28579 else
28580 break;
28582 /* Treat statement-expressions as dependent. */
28583 case BIND_EXPR:
28584 return *tp;
28586 /* Treat requires-expressions as dependent. */
28587 case REQUIRES_EXPR:
28588 return *tp;
28590 case CONSTRUCTOR:
28591 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28592 return *tp;
28593 break;
28595 case TEMPLATE_DECL:
28596 case FUNCTION_DECL:
28597 /* Before C++17, a noexcept-specifier isn't part of the function type
28598 so it doesn't affect type dependence, but we still want to consider it
28599 for instantiation dependence. */
28600 if (cxx_dialect < cxx17
28601 && DECL_DECLARES_FUNCTION_P (*tp)
28602 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28603 return *tp;
28604 break;
28606 default:
28607 break;
28610 if (type_dependent_expression_p (*tp))
28611 return *tp;
28612 else
28613 return NULL_TREE;
28616 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28617 sense defined by the ABI:
28619 "An expression is instantiation-dependent if it is type-dependent
28620 or value-dependent, or it has a subexpression that is type-dependent
28621 or value-dependent."
28623 Except don't actually check value-dependence for unevaluated expressions,
28624 because in sizeof(i) we don't care about the value of i. Checking
28625 type-dependence will in turn check value-dependence of array bounds/template
28626 arguments as needed. */
28628 bool
28629 instantiation_dependent_uneval_expression_p (tree expression)
28631 tree result;
28633 if (!processing_template_decl)
28634 return false;
28636 if (expression == error_mark_node)
28637 return false;
28639 result = cp_walk_tree_without_duplicates (&expression,
28640 instantiation_dependent_r, NULL);
28641 return result != NULL_TREE;
28644 /* As above, but also check value-dependence of the expression as a whole. */
28646 bool
28647 instantiation_dependent_expression_p (tree expression)
28649 return (instantiation_dependent_uneval_expression_p (expression)
28650 || (processing_template_decl
28651 && potential_constant_expression (expression)
28652 && value_dependent_expression_p (expression)));
28655 /* Like type_dependent_expression_p, but it also works while not processing
28656 a template definition, i.e. during substitution or mangling. */
28658 bool
28659 type_dependent_expression_p_push (tree expr)
28661 bool b;
28662 ++processing_template_decl;
28663 b = type_dependent_expression_p (expr);
28664 --processing_template_decl;
28665 return b;
28668 /* Returns TRUE if ARGS contains a type-dependent expression. */
28670 bool
28671 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28673 if (!processing_template_decl || !args)
28674 return false;
28676 for (tree arg : *args)
28677 if (type_dependent_expression_p (arg))
28678 return true;
28680 return false;
28683 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28684 expressions) contains any type-dependent expressions. */
28686 bool
28687 any_type_dependent_elements_p (const_tree list)
28689 for (; list; list = TREE_CHAIN (list))
28690 if (type_dependent_expression_p (TREE_VALUE (list)))
28691 return true;
28693 return false;
28696 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28697 expressions) contains any value-dependent expressions. */
28699 bool
28700 any_value_dependent_elements_p (const_tree list)
28702 for (; list; list = TREE_CHAIN (list))
28703 if (value_dependent_expression_p (TREE_VALUE (list)))
28704 return true;
28706 return false;
28709 /* Returns TRUE if the ARG (a template argument) is dependent. */
28711 bool
28712 dependent_template_arg_p (tree arg)
28714 if (!processing_template_decl)
28715 return false;
28717 /* Assume a template argument that was wrongly written by the user
28718 is dependent. This is consistent with what
28719 any_dependent_template_arguments_p [that calls this function]
28720 does. */
28721 if (!arg || arg == error_mark_node)
28722 return true;
28724 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28725 arg = argument_pack_select_arg (arg);
28727 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28728 return true;
28729 if (TREE_CODE (arg) == TEMPLATE_DECL)
28731 if (DECL_TEMPLATE_PARM_P (arg))
28732 return true;
28733 /* A member template of a dependent class is not necessarily
28734 type-dependent, but it is a dependent template argument because it
28735 will be a member of an unknown specialization to that template. */
28736 tree scope = CP_DECL_CONTEXT (arg);
28737 return TYPE_P (scope) && dependent_type_p (scope);
28739 else if (ARGUMENT_PACK_P (arg))
28741 tree args = ARGUMENT_PACK_ARGS (arg);
28742 for (tree arg : tree_vec_range (args))
28743 if (dependent_template_arg_p (arg))
28744 return true;
28745 return false;
28747 else if (TYPE_P (arg))
28748 return dependent_type_p (arg);
28749 else
28750 return value_dependent_expression_p (arg);
28753 /* Identify any expressions that use function parms. */
28755 static tree
28756 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28758 tree t = *tp;
28759 if (TREE_CODE (t) == PARM_DECL)
28761 *walk_subtrees = 0;
28762 return t;
28764 return NULL_TREE;
28767 /* Returns true if a type specialization formed using the template
28768 arguments ARGS needs to use structural equality. */
28770 bool
28771 any_template_arguments_need_structural_equality_p (tree args)
28773 int i;
28774 int j;
28776 if (!args)
28777 return false;
28778 if (args == error_mark_node)
28779 return true;
28781 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28783 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28784 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28786 tree arg = TREE_VEC_ELT (level, j);
28787 tree packed_args = NULL_TREE;
28788 int k, len = 1;
28790 if (ARGUMENT_PACK_P (arg))
28792 /* Look inside the argument pack. */
28793 packed_args = ARGUMENT_PACK_ARGS (arg);
28794 len = TREE_VEC_LENGTH (packed_args);
28797 for (k = 0; k < len; ++k)
28799 if (packed_args)
28800 arg = TREE_VEC_ELT (packed_args, k);
28802 if (error_operand_p (arg))
28803 return true;
28804 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28805 continue;
28806 else if (arg == any_targ_node)
28807 /* An any_targ_node argument (added by add_defaults_to_ttp)
28808 makes the corresponding specialization not canonicalizable,
28809 since template_args_equal always return true for it. We
28810 may see this when called from bind_template_template_parm. */
28811 return true;
28812 /* Checking current_function_decl because this structural
28813 comparison is only necessary for redeclaration. */
28814 else if (!current_function_decl
28815 && dependent_template_arg_p (arg)
28816 && (cp_walk_tree_without_duplicates
28817 (&arg, find_parm_usage_r, NULL)))
28818 /* The identity of a class template specialization that uses
28819 a function parameter depends on the identity of the function.
28820 And if this specialization appeared in the trailing return
28821 type thereof, we don't know the identity of the function
28822 (e.g. if it's a redeclaration or a new function) until we
28823 form its signature and go through duplicate_decls. Thus
28824 it's unsafe to decide on a canonical type now (which depends
28825 on the DECL_CONTEXT of the function parameter, which can get
28826 mutated after the fact by duplicate_decls), so just require
28827 structural equality in this case (PR52830). */
28828 return true;
28833 return false;
28836 /* Returns true if ARGS (a collection of template arguments) contains
28837 any dependent arguments. */
28839 bool
28840 any_dependent_template_arguments_p (const_tree args)
28842 if (args == error_mark_node)
28843 return true;
28844 if (!processing_template_decl || !args)
28845 return false;
28847 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28849 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28850 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28851 if (dependent_template_arg_p (arg))
28852 return true;
28855 return false;
28858 /* Returns true if ARGS contains any errors. */
28860 bool
28861 any_erroneous_template_args_p (const_tree args)
28863 int i;
28864 int j;
28866 if (args == error_mark_node)
28867 return true;
28869 if (args && TREE_CODE (args) != TREE_VEC)
28871 if (tree ti = get_template_info (args))
28872 args = TI_ARGS (ti);
28873 else
28874 args = NULL_TREE;
28877 if (!args)
28878 return false;
28880 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28882 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28883 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28884 if (error_operand_p (TREE_VEC_ELT (level, j)))
28885 return true;
28888 return false;
28891 /* Returns TRUE if the template TMPL is type-dependent. */
28893 bool
28894 dependent_template_p (tree tmpl)
28896 if (TREE_CODE (tmpl) == OVERLOAD)
28898 for (lkp_iterator iter (tmpl); iter; ++iter)
28899 if (dependent_template_p (*iter))
28900 return true;
28901 return false;
28904 /* Template template parameters are dependent. */
28905 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28906 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28907 return true;
28908 /* So are names that have not been looked up. */
28909 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28910 return true;
28911 return false;
28914 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28916 bool
28917 dependent_template_id_p (tree tmpl, tree args)
28919 return (dependent_template_p (tmpl)
28920 || any_dependent_template_arguments_p (args));
28923 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28924 are dependent. */
28926 bool
28927 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28929 int i;
28931 if (!processing_template_decl)
28932 return false;
28934 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28936 tree decl = TREE_VEC_ELT (declv, i);
28937 tree init = TREE_VEC_ELT (initv, i);
28938 tree cond = TREE_VEC_ELT (condv, i);
28939 tree incr = TREE_VEC_ELT (incrv, i);
28941 if (type_dependent_expression_p (decl)
28942 || TREE_CODE (decl) == SCOPE_REF)
28943 return true;
28945 if (init && type_dependent_expression_p (init))
28946 return true;
28948 if (cond == global_namespace)
28949 return true;
28951 if (type_dependent_expression_p (cond))
28952 return true;
28954 if (COMPARISON_CLASS_P (cond)
28955 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28956 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28957 return true;
28959 if (TREE_CODE (incr) == MODOP_EXPR)
28961 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28962 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28963 return true;
28965 else if (type_dependent_expression_p (incr))
28966 return true;
28967 else if (TREE_CODE (incr) == MODIFY_EXPR)
28969 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28970 return true;
28971 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28973 tree t = TREE_OPERAND (incr, 1);
28974 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28975 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28976 return true;
28978 /* If this loop has a class iterator with != comparison
28979 with increment other than i++/++i/i--/--i, make sure the
28980 increment is constant. */
28981 if (CLASS_TYPE_P (TREE_TYPE (decl))
28982 && TREE_CODE (cond) == NE_EXPR)
28984 if (TREE_OPERAND (t, 0) == decl)
28985 t = TREE_OPERAND (t, 1);
28986 else
28987 t = TREE_OPERAND (t, 0);
28988 if (TREE_CODE (t) != INTEGER_CST)
28989 return true;
28995 return false;
28998 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28999 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
29000 no such TYPE can be found. Note that this function peers inside
29001 uninstantiated templates and therefore should be used only in
29002 extremely limited situations. ONLY_CURRENT_P restricts this
29003 peering to the currently open classes hierarchy (which is required
29004 when comparing types). */
29006 tree
29007 resolve_typename_type (tree type, bool only_current_p)
29009 tree scope;
29010 tree name;
29011 tree decl;
29012 int quals;
29013 tree pushed_scope;
29014 tree result;
29016 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
29018 scope = TYPE_CONTEXT (type);
29019 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
29020 gcc_checking_assert (uses_template_parms (scope));
29022 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
29023 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29024 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29025 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29026 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29027 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29028 the TYPENAME_TYPE instead, we avoid messing up with a possible
29029 typedef variant case. */
29030 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29032 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29033 it first before we can figure out what NAME refers to. */
29034 if (TREE_CODE (scope) == TYPENAME_TYPE)
29036 if (TYPENAME_IS_RESOLVING_P (scope))
29037 /* Given a class template A with a dependent base with nested type C,
29038 typedef typename A::C::C C will land us here, as trying to resolve
29039 the initial A::C leads to the local C typedef, which leads back to
29040 A::C::C. So we break the recursion now. */
29041 return type;
29042 else
29043 scope = resolve_typename_type (scope, only_current_p);
29045 /* If we don't know what SCOPE refers to, then we cannot resolve the
29046 TYPENAME_TYPE. */
29047 if (!CLASS_TYPE_P (scope))
29048 return type;
29049 /* If this is a typedef, we don't want to look inside (c++/11987). */
29050 if (typedef_variant_p (type))
29051 return type;
29052 /* If SCOPE isn't the template itself, it will not have a valid
29053 TYPE_FIELDS list. */
29054 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29055 /* scope is either the template itself or a compatible instantiation
29056 like X<T>, so look up the name in the original template. */
29057 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29058 /* If scope has no fields, it can't be a current instantiation. Check this
29059 before currently_open_class to avoid infinite recursion (71515). */
29060 if (!TYPE_FIELDS (scope))
29061 return type;
29062 /* If the SCOPE is not the current instantiation, there's no reason
29063 to look inside it. */
29064 if (only_current_p && !currently_open_class (scope))
29065 return type;
29066 /* Enter the SCOPE so that name lookup will be resolved as if we
29067 were in the class definition. In particular, SCOPE will no
29068 longer be considered a dependent type. */
29069 pushed_scope = push_scope (scope);
29070 /* Look up the declaration. */
29071 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29072 tf_warning_or_error);
29074 result = NULL_TREE;
29076 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29077 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29078 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29079 if (!decl)
29080 /*nop*/;
29081 else if (identifier_p (fullname)
29082 && TREE_CODE (decl) == TYPE_DECL)
29084 result = TREE_TYPE (decl);
29085 if (result == error_mark_node)
29086 result = NULL_TREE;
29088 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29089 && DECL_CLASS_TEMPLATE_P (decl))
29091 /* Obtain the template and the arguments. */
29092 tree tmpl = TREE_OPERAND (fullname, 0);
29093 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29095 /* We get here with a plain identifier because a previous tentative
29096 parse of the nested-name-specifier as part of a ptr-operator saw
29097 ::template X<A>. The use of ::template is necessary in a
29098 ptr-operator, but wrong in a declarator-id.
29100 [temp.names]: In a qualified-id of a declarator-id, the keyword
29101 template shall not appear at the top level. */
29102 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29103 "keyword %<template%> not allowed in declarator-id");
29104 tmpl = decl;
29106 tree args = TREE_OPERAND (fullname, 1);
29107 /* Instantiate the template. */
29108 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29109 /*entering_scope=*/true,
29110 tf_error | tf_user);
29111 if (result == error_mark_node)
29112 result = NULL_TREE;
29115 /* Leave the SCOPE. */
29116 if (pushed_scope)
29117 pop_scope (pushed_scope);
29119 /* If we failed to resolve it, return the original typename. */
29120 if (!result)
29121 return type;
29123 /* If lookup found a typename type, resolve that too. */
29124 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29126 /* Ill-formed programs can cause infinite recursion here, so we
29127 must catch that. */
29128 TYPENAME_IS_RESOLVING_P (result) = 1;
29129 result = resolve_typename_type (result, only_current_p);
29130 TYPENAME_IS_RESOLVING_P (result) = 0;
29133 /* Qualify the resulting type. */
29134 quals = cp_type_quals (type);
29135 if (quals)
29136 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29138 return result;
29141 /* EXPR is an expression which is not type-dependent. Return a proxy
29142 for EXPR that can be used to compute the types of larger
29143 expressions containing EXPR. */
29145 tree
29146 build_non_dependent_expr (tree expr)
29148 tree orig_expr = expr;
29149 tree inner_expr;
29151 /* When checking, try to get a constant value for all non-dependent
29152 expressions in order to expose bugs in *_dependent_expression_p
29153 and constexpr. This can affect code generation, see PR70704, so
29154 only do this for -fchecking=2. */
29155 if (flag_checking > 1
29156 && cxx_dialect >= cxx11
29157 /* Don't do this during nsdmi parsing as it can lead to
29158 unexpected recursive instantiations. */
29159 && !parsing_nsdmi ()
29160 /* Don't do this during concept processing either and for
29161 the same reason. */
29162 && !processing_constraint_expression_p ())
29163 fold_non_dependent_expr (expr, tf_none);
29165 STRIP_ANY_LOCATION_WRAPPER (expr);
29167 /* Preserve OVERLOADs; the functions must be available to resolve
29168 types. */
29169 inner_expr = expr;
29170 if (TREE_CODE (inner_expr) == STMT_EXPR)
29171 inner_expr = stmt_expr_value_expr (inner_expr);
29172 if (TREE_CODE (inner_expr) == ADDR_EXPR)
29173 inner_expr = TREE_OPERAND (inner_expr, 0);
29174 if (TREE_CODE (inner_expr) == COMPONENT_REF)
29175 inner_expr = TREE_OPERAND (inner_expr, 1);
29176 if (is_overloaded_fn (inner_expr)
29177 || TREE_CODE (inner_expr) == OFFSET_REF)
29178 return orig_expr;
29179 /* There is no need to return a proxy for a variable, parameter
29180 or enumerator. */
29181 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
29182 || TREE_CODE (expr) == CONST_DECL)
29183 return orig_expr;
29184 /* Preserve string constants; conversions from string constants to
29185 "char *" are allowed, even though normally a "const char *"
29186 cannot be used to initialize a "char *". */
29187 if (TREE_CODE (expr) == STRING_CST)
29188 return orig_expr;
29189 /* Preserve void and arithmetic constants, as an optimization -- there is no
29190 reason to create a new node. */
29191 if (TREE_CODE (expr) == VOID_CST
29192 || TREE_CODE (expr) == INTEGER_CST
29193 || TREE_CODE (expr) == REAL_CST)
29194 return orig_expr;
29195 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
29196 There is at least one place where we want to know that a
29197 particular expression is a throw-expression: when checking a ?:
29198 expression, there are special rules if the second or third
29199 argument is a throw-expression. */
29200 if (TREE_CODE (expr) == THROW_EXPR)
29201 return orig_expr;
29203 /* Don't wrap an initializer list, we need to be able to look inside. */
29204 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
29205 return orig_expr;
29207 /* Don't wrap a dummy object, we need to be able to test for it. */
29208 if (is_dummy_object (expr))
29209 return orig_expr;
29211 if (TREE_CODE (expr) == COND_EXPR)
29212 return build3 (COND_EXPR,
29213 TREE_TYPE (expr),
29214 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
29215 (TREE_OPERAND (expr, 1)
29216 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
29217 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
29218 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
29219 if (TREE_CODE (expr) == COMPOUND_EXPR)
29220 return build2 (COMPOUND_EXPR,
29221 TREE_TYPE (expr),
29222 TREE_OPERAND (expr, 0),
29223 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
29225 /* If the type is unknown, it can't really be non-dependent */
29226 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
29228 /* Otherwise, build a NON_DEPENDENT_EXPR. */
29229 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
29230 TREE_TYPE (expr), expr);
29233 /* ARGS is a vector of expressions as arguments to a function call.
29234 Replace the arguments with equivalent non-dependent expressions.
29235 This modifies ARGS in place. */
29237 void
29238 make_args_non_dependent (vec<tree, va_gc> *args)
29240 unsigned int ix;
29241 tree arg;
29243 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
29245 tree newarg = build_non_dependent_expr (arg);
29246 if (newarg != arg)
29247 (*args)[ix] = newarg;
29251 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29252 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29253 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29255 static tree
29256 make_auto_1 (tree name, bool set_canonical, int level = -1)
29258 if (level == -1)
29259 level = current_template_depth + 1;
29260 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29261 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29262 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29263 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29264 (0, level, level, TYPE_NAME (au), NULL_TREE);
29265 if (set_canonical)
29266 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29267 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29268 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29269 if (name == decltype_auto_identifier)
29270 AUTO_IS_DECLTYPE (au) = true;
29272 return au;
29275 tree
29276 make_decltype_auto (void)
29278 return make_auto_1 (decltype_auto_identifier, true);
29281 tree
29282 make_auto (void)
29284 return make_auto_1 (auto_identifier, true);
29287 /* Return a C++17 deduction placeholder for class template TMPL.
29288 There are represented as an 'auto' with the special level 0 and
29289 CLASS_PLACEHOLDER_TEMPLATE set. */
29291 tree
29292 make_template_placeholder (tree tmpl)
29294 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29295 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29296 /* Our canonical type depends on the placeholder. */
29297 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29298 return t;
29301 /* True iff T is a C++17 class template deduction placeholder. */
29303 bool
29304 template_placeholder_p (tree t)
29306 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29309 /* Make a "constrained auto" type-specifier. This is an auto or
29310 decltype(auto) type with constraints that must be associated after
29311 deduction. The constraint is formed from the given concept CON
29312 and its optional sequence of template arguments ARGS.
29314 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29316 static tree
29317 make_constrained_placeholder_type (tree type, tree con, tree args)
29319 /* Build the constraint. */
29320 tree tmpl = DECL_TI_TEMPLATE (con);
29321 tree expr = tmpl;
29322 if (TREE_CODE (con) == FUNCTION_DECL)
29323 expr = ovl_make (tmpl);
29324 ++processing_template_decl;
29325 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29326 --processing_template_decl;
29328 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29329 = build_tree_list (current_template_parms, expr);
29331 /* Our canonical type depends on the constraint. */
29332 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29334 /* Attach the constraint to the type declaration. */
29335 return TYPE_NAME (type);
29338 /* Make a "constrained auto" type-specifier. */
29340 tree
29341 make_constrained_auto (tree con, tree args)
29343 tree type = make_auto_1 (auto_identifier, false);
29344 return make_constrained_placeholder_type (type, con, args);
29347 /* Make a "constrained decltype(auto)" type-specifier. */
29349 tree
29350 make_constrained_decltype_auto (tree con, tree args)
29352 tree type = make_auto_1 (decltype_auto_identifier, false);
29353 return make_constrained_placeholder_type (type, con, args);
29356 /* Returns true if the placeholder type constraint T has any dependent
29357 (explicit) template arguments. */
29359 static bool
29360 placeholder_type_constraint_dependent_p (tree t)
29362 tree id = unpack_concept_check (t);
29363 tree args = TREE_OPERAND (id, 1);
29364 tree first = TREE_VEC_ELT (args, 0);
29365 if (ARGUMENT_PACK_P (first))
29367 args = expand_template_argument_pack (args);
29368 first = TREE_VEC_ELT (args, 0);
29370 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29371 || is_auto (first));
29372 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29373 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29374 return true;
29375 return false;
29378 /* Build and return a concept definition. Like other templates, the
29379 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29380 the TEMPLATE_DECL. */
29382 tree
29383 finish_concept_definition (cp_expr id, tree init, tree attrs)
29385 gcc_assert (identifier_p (id));
29386 gcc_assert (processing_template_decl);
29388 location_t loc = id.get_location();
29390 /* A concept-definition shall not have associated constraints. */
29391 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29393 error_at (loc, "a concept cannot be constrained");
29394 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29397 /* A concept-definition shall appear in namespace scope. Templates
29398 aren't allowed in block scope, so we only need to check for class
29399 scope. */
29400 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29402 error_at (loc, "concept %qE not in namespace scope", *id);
29403 return error_mark_node;
29406 if (current_template_depth > 1)
29408 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29409 return error_mark_node;
29412 /* Initially build the concept declaration; its type is bool. */
29413 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29414 DECL_CONTEXT (decl) = current_scope ();
29415 DECL_INITIAL (decl) = init;
29417 if (attrs)
29418 cplus_decl_attributes (&decl, attrs, 0);
29420 set_originating_module (decl, false);
29422 /* Push the enclosing template. */
29423 return push_template_decl (decl);
29426 /* Given type ARG, return std::initializer_list<ARG>. */
29428 static tree
29429 listify (tree arg)
29431 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29433 if (std_init_list == error_mark_node
29434 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29436 gcc_rich_location richloc (input_location);
29437 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29438 error_at (&richloc,
29439 "deducing from brace-enclosed initializer list"
29440 " requires %<#include <initializer_list>%>");
29442 return error_mark_node;
29444 tree argvec = make_tree_vec (1);
29445 TREE_VEC_ELT (argvec, 0) = arg;
29447 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29448 NULL_TREE, 0, tf_warning_or_error);
29451 /* Replace auto in TYPE with std::initializer_list<auto>. */
29453 static tree
29454 listify_autos (tree type, tree auto_node)
29456 tree init_auto = listify (strip_top_quals (auto_node));
29457 tree argvec = make_tree_vec (1);
29458 TREE_VEC_ELT (argvec, 0) = init_auto;
29459 if (processing_template_decl)
29460 argvec = add_to_template_args (current_template_args (), argvec);
29461 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29464 /* Hash traits for hashing possibly constrained 'auto'
29465 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29467 struct auto_hash : default_hash_traits<tree>
29469 static inline hashval_t hash (tree);
29470 static inline bool equal (tree, tree);
29473 /* Hash the 'auto' T. */
29475 inline hashval_t
29476 auto_hash::hash (tree t)
29478 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29479 /* Matching constrained-type-specifiers denote the same template
29480 parameter, so hash the constraint. */
29481 return hash_placeholder_constraint (c);
29482 else
29483 /* But unconstrained autos are all separate, so just hash the pointer. */
29484 return iterative_hash_object (t, 0);
29487 /* Compare two 'auto's. */
29489 inline bool
29490 auto_hash::equal (tree t1, tree t2)
29492 if (t1 == t2)
29493 return true;
29495 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29496 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29498 /* Two unconstrained autos are distinct. */
29499 if (!c1 || !c2)
29500 return false;
29502 return equivalent_placeholder_constraints (c1, c2);
29505 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29506 constrained) auto, add it to the vector. */
29508 static int
29509 extract_autos_r (tree t, void *data)
29511 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29512 if (is_auto (t) && !template_placeholder_p (t))
29514 /* All the autos were built with index 0; fix that up now. */
29515 tree *p = hash.find_slot (t, INSERT);
29516 int idx;
29517 if (*p)
29518 /* If this is a repeated constrained-type-specifier, use the index we
29519 chose before. */
29520 idx = TEMPLATE_TYPE_IDX (*p);
29521 else
29523 /* Otherwise this is new, so use the current count. */
29524 *p = t;
29525 idx = hash.elements () - 1;
29527 if (idx != TEMPLATE_TYPE_IDX (t))
29529 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29530 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29531 TEMPLATE_TYPE_IDX (t) = idx;
29532 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29536 /* Always keep walking. */
29537 return 0;
29540 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29541 says they can appear anywhere in the type. */
29543 static tree
29544 extract_autos (tree type)
29546 hash_set<tree> visited;
29547 hash_table<auto_hash> hash (2);
29549 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29551 tree tree_vec = make_tree_vec (hash.elements());
29552 for (tree elt : hash)
29554 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29555 TREE_VEC_ELT (tree_vec, i)
29556 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29559 return tree_vec;
29562 /* The stem for deduction guide names. */
29563 const char *const dguide_base = "__dguide_";
29565 /* Return the name for a deduction guide for class template TMPL. */
29567 tree
29568 dguide_name (tree tmpl)
29570 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29571 tree tname = TYPE_IDENTIFIER (type);
29572 char *buf = (char *) alloca (1 + strlen (dguide_base)
29573 + IDENTIFIER_LENGTH (tname));
29574 memcpy (buf, dguide_base, strlen (dguide_base));
29575 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29576 IDENTIFIER_LENGTH (tname) + 1);
29577 tree dname = get_identifier (buf);
29578 TREE_TYPE (dname) = type;
29579 return dname;
29582 /* True if NAME is the name of a deduction guide. */
29584 bool
29585 dguide_name_p (tree name)
29587 return (TREE_CODE (name) == IDENTIFIER_NODE
29588 && TREE_TYPE (name)
29589 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29592 /* True if FN is a deduction guide. */
29594 bool
29595 deduction_guide_p (const_tree fn)
29597 if (DECL_P (fn))
29598 if (tree name = DECL_NAME (fn))
29599 return dguide_name_p (name);
29600 return false;
29603 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29605 bool
29606 copy_guide_p (const_tree fn)
29608 gcc_assert (deduction_guide_p (fn));
29609 if (!DECL_ARTIFICIAL (fn))
29610 return false;
29611 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29612 return (TREE_CHAIN (parms) == void_list_node
29613 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29616 /* True if FN is a guide generated from a constructor template. */
29618 bool
29619 template_guide_p (const_tree fn)
29621 gcc_assert (deduction_guide_p (fn));
29622 if (!DECL_ARTIFICIAL (fn))
29623 return false;
29624 tree tmpl = DECL_TI_TEMPLATE (fn);
29625 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29626 return PRIMARY_TEMPLATE_P (org);
29627 return false;
29630 /* True if FN is an aggregate initialization guide or the copy deduction
29631 guide. */
29633 bool
29634 builtin_guide_p (const_tree fn)
29636 if (!deduction_guide_p (fn))
29637 return false;
29638 if (!DECL_ARTIFICIAL (fn))
29639 /* Explicitly declared. */
29640 return false;
29641 if (DECL_ABSTRACT_ORIGIN (fn))
29642 /* Derived from a constructor. */
29643 return false;
29644 return true;
29647 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29648 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29649 template parameter types. Note that the handling of template template
29650 parameters relies on current_template_parms being set appropriately for the
29651 new template. */
29653 static tree
29654 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29655 tree tsubst_args, tsubst_flags_t complain)
29657 if (olddecl == error_mark_node)
29658 return error_mark_node;
29660 tree oldidx = get_template_parm_index (olddecl);
29662 tree newtype;
29663 if (TREE_CODE (olddecl) == TYPE_DECL
29664 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29666 tree oldtype = TREE_TYPE (olddecl);
29667 newtype = cxx_make_type (TREE_CODE (oldtype));
29668 TYPE_MAIN_VARIANT (newtype) = newtype;
29670 else
29672 newtype = TREE_TYPE (olddecl);
29673 if (type_uses_auto (newtype))
29675 // Substitute once to fix references to other template parameters.
29676 newtype = tsubst (newtype, tsubst_args,
29677 complain|tf_partial, NULL_TREE);
29678 // Now substitute again to reduce the level of the auto.
29679 newtype = tsubst (newtype, current_template_args (),
29680 complain, NULL_TREE);
29682 else
29683 newtype = tsubst (newtype, tsubst_args,
29684 complain, NULL_TREE);
29687 tree newdecl
29688 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29689 DECL_NAME (olddecl), newtype);
29690 SET_DECL_TEMPLATE_PARM_P (newdecl);
29692 tree newidx;
29693 if (TREE_CODE (olddecl) == TYPE_DECL
29694 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29696 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29697 = build_template_parm_index (index, level, level,
29698 newdecl, newtype);
29699 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29700 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29701 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29703 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29705 DECL_TEMPLATE_RESULT (newdecl)
29706 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29707 DECL_NAME (olddecl), newtype);
29708 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29709 // First create a copy (ttargs) of tsubst_args with an
29710 // additional level for the template template parameter's own
29711 // template parameters (ttparms).
29712 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29713 (DECL_TEMPLATE_PARMS (olddecl)));
29714 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29715 tree ttargs = make_tree_vec (depth + 1);
29716 for (int i = 0; i < depth; ++i)
29717 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29718 TREE_VEC_ELT (ttargs, depth)
29719 = template_parms_level_to_args (ttparms);
29720 // Substitute ttargs into ttparms to fix references to
29721 // other template parameters.
29722 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29723 complain|tf_partial);
29724 // Now substitute again with args based on tparms, to reduce
29725 // the level of the ttparms.
29726 ttargs = current_template_args ();
29727 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29728 complain);
29729 // Finally, tack the adjusted parms onto tparms.
29730 ttparms = tree_cons (size_int (level + 1), ttparms,
29731 copy_node (current_template_parms));
29732 // As with all template template parms, the parameter list captured
29733 // by this template template parm that corresponds to its own level
29734 // should be empty. This avoids infinite recursion when structurally
29735 // comparing two such rewritten template template parms (PR102479).
29736 gcc_assert (!TREE_VEC_LENGTH
29737 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29738 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29739 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29740 // All done.
29741 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29744 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29745 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29746 else
29747 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29749 else
29751 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29752 tree newconst
29753 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29754 TREE_CODE (oldconst),
29755 DECL_NAME (oldconst), newtype);
29756 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29757 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29758 SET_DECL_TEMPLATE_PARM_P (newconst);
29759 newidx = build_template_parm_index (index, level, level,
29760 newconst, newtype);
29761 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29762 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29763 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29766 return newdecl;
29769 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29770 template parameter. */
29772 static tree
29773 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29774 tree targs, unsigned targs_index, tsubst_flags_t complain)
29776 tree olddecl = TREE_VALUE (oldelt);
29777 tree newdecl = rewrite_template_parm (olddecl, index, level,
29778 targs, complain);
29779 if (newdecl == error_mark_node)
29780 return error_mark_node;
29781 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29782 targs, complain, NULL_TREE);
29783 tree list = build_tree_list (newdef, newdecl);
29784 TEMPLATE_PARM_CONSTRAINTS (list)
29785 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29786 targs, complain, NULL_TREE);
29787 int depth = TMPL_ARGS_DEPTH (targs);
29788 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29789 return list;
29792 /* Returns a C++17 class deduction guide template based on the constructor
29793 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29794 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29795 aggregate initialization guide. OUTER_ARGS are the template arguments
29796 for the enclosing scope of the class. */
29798 static tree
29799 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29801 tree tparms, targs, fparms, fargs, ci;
29802 bool memtmpl = false;
29803 bool explicit_p;
29804 location_t loc;
29805 tree fn_tmpl = NULL_TREE;
29807 if (outer_args)
29809 ++processing_template_decl;
29810 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29811 --processing_template_decl;
29814 if (!DECL_DECLARES_FUNCTION_P (ctor))
29816 if (TYPE_P (ctor))
29818 bool copy_p = TYPE_REF_P (ctor);
29819 if (copy_p)
29820 fparms = tree_cons (NULL_TREE, type, void_list_node);
29821 else
29822 fparms = void_list_node;
29824 else if (TREE_CODE (ctor) == TREE_LIST)
29825 fparms = ctor;
29826 else
29827 gcc_unreachable ();
29829 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29830 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29831 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29832 ci = NULL_TREE;
29833 fargs = NULL_TREE;
29834 loc = DECL_SOURCE_LOCATION (ctmpl);
29835 explicit_p = false;
29837 else
29839 ++processing_template_decl;
29840 bool ok = true;
29842 complain |= tf_dguide;
29844 fn_tmpl
29845 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29846 : DECL_TI_TEMPLATE (ctor));
29847 if (outer_args)
29848 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29849 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29851 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29852 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29853 fully specialized args for the enclosing class. Strip those off, as
29854 the deduction guide won't have those template parameters. */
29855 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29856 TMPL_PARMS_DEPTH (tparms));
29857 /* Discard the 'this' parameter. */
29858 fparms = FUNCTION_ARG_CHAIN (ctor);
29859 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29860 ci = get_constraints (ctor);
29861 loc = DECL_SOURCE_LOCATION (ctor);
29862 explicit_p = DECL_NONCONVERTING_P (ctor);
29864 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29866 memtmpl = true;
29868 /* For a member template constructor, we need to flatten the two
29869 template parameter lists into one, and then adjust the function
29870 signature accordingly. This gets...complicated. */
29871 tree save_parms = current_template_parms;
29873 /* For a member template we should have two levels of parms/args, one
29874 for the class and one for the constructor. We stripped
29875 specialized args for further enclosing classes above. */
29876 const int depth = 2;
29877 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29879 /* Template args for translating references to the two-level template
29880 parameters into references to the one-level template parameters we
29881 are creating. */
29882 tree tsubst_args = copy_node (targs);
29883 TMPL_ARGS_LEVEL (tsubst_args, depth)
29884 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29886 /* Template parms for the constructor template. */
29887 tree ftparms = TREE_VALUE (tparms);
29888 unsigned flen = TREE_VEC_LENGTH (ftparms);
29889 /* Template parms for the class template. */
29890 tparms = TREE_CHAIN (tparms);
29891 tree ctparms = TREE_VALUE (tparms);
29892 unsigned clen = TREE_VEC_LENGTH (ctparms);
29893 /* Template parms for the deduction guide start as a copy of the
29894 template parms for the class. We set current_template_parms for
29895 lookup_template_class_1. */
29896 current_template_parms = tparms = copy_node (tparms);
29897 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29898 for (unsigned i = 0; i < clen; ++i)
29899 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29901 /* Now we need to rewrite the constructor parms to append them to the
29902 class parms. */
29903 for (unsigned i = 0; i < flen; ++i)
29905 unsigned index = i + clen;
29906 unsigned level = 1;
29907 tree oldelt = TREE_VEC_ELT (ftparms, i);
29908 tree newelt
29909 = rewrite_tparm_list (oldelt, index, level,
29910 tsubst_args, i, complain);
29911 if (newelt == error_mark_node)
29912 ok = false;
29913 TREE_VEC_ELT (new_vec, index) = newelt;
29916 /* Now we have a final set of template parms to substitute into the
29917 function signature. */
29918 targs = template_parms_to_args (tparms);
29919 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29920 complain, ctor);
29921 if (fparms == error_mark_node)
29922 ok = false;
29923 if (ci)
29925 if (outer_args)
29926 /* FIXME: We'd like to avoid substituting outer template
29927 arguments into the constraint ahead of time, but the
29928 construction of tsubst_args assumes that outer arguments
29929 are already substituted in. */
29930 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29931 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29934 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29935 cp_unevaluated_operand. */
29936 cp_evaluated ev;
29937 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29938 current_template_parms = save_parms;
29940 else
29942 /* Substitute in the same arguments to rewrite class members into
29943 references to members of an unknown specialization. */
29944 cp_evaluated ev;
29945 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29946 fargs = tsubst (fargs, targs, complain, ctor);
29947 if (ci)
29949 if (outer_args)
29950 /* FIXME: As above. */
29951 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29952 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29956 --processing_template_decl;
29957 if (!ok)
29958 return error_mark_node;
29961 if (!memtmpl)
29963 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29964 tparms = copy_node (tparms);
29965 INNERMOST_TEMPLATE_PARMS (tparms)
29966 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29969 tree fntype = build_function_type (type, fparms);
29970 tree ded_fn = build_lang_decl_loc (loc,
29971 FUNCTION_DECL,
29972 dguide_name (type), fntype);
29973 DECL_ARGUMENTS (ded_fn) = fargs;
29974 DECL_ARTIFICIAL (ded_fn) = true;
29975 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29976 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29977 DECL_ARTIFICIAL (ded_tmpl) = true;
29978 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29979 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29980 if (DECL_P (ctor))
29981 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29982 if (ci)
29983 set_constraints (ded_tmpl, ci);
29985 return ded_tmpl;
29988 /* Add to LIST the member types for the reshaped initializer CTOR. */
29990 static tree
29991 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29993 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29994 tree idx, val; unsigned i;
29995 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29997 tree ftype = elt ? elt : TREE_TYPE (idx);
29998 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29999 && CONSTRUCTOR_BRACES_ELIDED_P (val))
30001 tree subelt = NULL_TREE;
30002 if (TREE_CODE (ftype) == ARRAY_TYPE)
30003 subelt = TREE_TYPE (ftype);
30004 list = collect_ctor_idx_types (val, list, subelt);
30005 continue;
30007 tree arg = NULL_TREE;
30008 if (i == v->length() - 1
30009 && PACK_EXPANSION_P (ftype))
30010 /* Give the trailing pack expansion parameter a default argument to
30011 match aggregate initialization behavior, even if we deduce the
30012 length of the pack separately to more than we have initializers. */
30013 arg = build_constructor (init_list_type_node, NULL);
30014 /* if ei is of array type and xi is a braced-init-list or string literal,
30015 Ti is an rvalue reference to the declared type of ei */
30016 STRIP_ANY_LOCATION_WRAPPER (val);
30017 if (TREE_CODE (ftype) == ARRAY_TYPE
30018 && (BRACE_ENCLOSED_INITIALIZER_P (val)
30019 || TREE_CODE (val) == STRING_CST))
30021 if (TREE_CODE (val) == STRING_CST)
30022 ftype = cp_build_qualified_type
30023 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30024 ftype = (cp_build_reference_type
30025 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30027 list = tree_cons (arg, ftype, list);
30030 return list;
30033 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30035 static bool
30036 is_spec_or_derived (tree etype, tree tmpl)
30038 if (!etype || !CLASS_TYPE_P (etype))
30039 return false;
30041 etype = cv_unqualified (etype);
30042 tree type = TREE_TYPE (tmpl);
30043 tree tparms = (INNERMOST_TEMPLATE_PARMS
30044 (DECL_TEMPLATE_PARMS (tmpl)));
30045 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30046 int err = unify (tparms, targs, type, etype,
30047 UNIFY_ALLOW_DERIVED, /*explain*/false);
30048 ggc_free (targs);
30049 return !err;
30052 static tree alias_ctad_tweaks (tree, tree);
30054 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30055 INIT. */
30057 static tree
30058 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30060 if (cxx_dialect < cxx20)
30061 return NULL_TREE;
30063 if (init == NULL_TREE)
30064 return NULL_TREE;
30066 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30068 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30069 tree tinfo = get_template_info (under);
30070 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30071 return alias_ctad_tweaks (tmpl, guide);
30072 return NULL_TREE;
30075 /* We might be creating a guide for a class member template, e.g.,
30077 template<typename U> struct A {
30078 template<typename T> struct B { T t; };
30081 At this point, A will have been instantiated. Below, we need to
30082 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30083 const bool member_template_p
30084 = (DECL_TEMPLATE_INFO (tmpl)
30085 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30086 tree type = TREE_TYPE (tmpl);
30087 tree template_type = (member_template_p
30088 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30089 : type);
30090 if (!CP_AGGREGATE_TYPE_P (template_type))
30091 return NULL_TREE;
30093 /* No aggregate candidate for copy-initialization. */
30094 if (args->length() == 1)
30096 tree val = (*args)[0];
30097 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30098 return NULL_TREE;
30101 /* If we encounter a problem, we just won't add the candidate. */
30102 tsubst_flags_t complain = tf_none;
30104 tree parms = NULL_TREE;
30105 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30107 init = reshape_init (template_type, init, complain);
30108 if (init == error_mark_node)
30109 return NULL_TREE;
30110 parms = collect_ctor_idx_types (init, parms);
30111 /* If we're creating a deduction guide for a member class template,
30112 we've used the original template pattern type for the reshape_init
30113 above; this is done because we want PARMS to be a template parameter
30114 type, something that can be deduced when used as a function template
30115 parameter. At this point the outer class template has already been
30116 partially instantiated (we deferred the deduction until the enclosing
30117 scope is non-dependent). Therefore we have to partially instantiate
30118 PARMS, so that its template level is properly reduced and we don't get
30119 mismatches when deducing types using the guide with PARMS. */
30120 if (member_template_p)
30122 ++processing_template_decl;
30123 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30124 --processing_template_decl;
30127 else if (TREE_CODE (init) == TREE_LIST)
30129 int len = list_length (init);
30130 for (tree field = TYPE_FIELDS (type);
30131 len;
30132 --len, field = DECL_CHAIN (field))
30134 field = next_aggregate_field (field);
30135 if (!field)
30136 return NULL_TREE;
30137 tree ftype = finish_decltype_type (field, true, complain);
30138 parms = tree_cons (NULL_TREE, ftype, parms);
30141 else
30142 /* Aggregate initialization doesn't apply to an initializer expression. */
30143 return NULL_TREE;
30145 if (parms)
30147 tree last = parms;
30148 parms = nreverse (parms);
30149 TREE_CHAIN (last) = void_list_node;
30150 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30151 return guide;
30154 return NULL_TREE;
30157 /* UGUIDES are the deduction guides for the underlying template of alias
30158 template TMPL; adjust them to be deduction guides for TMPL. */
30160 static tree
30161 alias_ctad_tweaks (tree tmpl, tree uguides)
30163 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30164 class type (9.2.8.2) where the template-name names an alias template A,
30165 the defining-type-id of A must be of the form
30167 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30169 as specified in 9.2.8.2. The guides of A are the set of functions or
30170 function templates formed as follows. For each function or function
30171 template f in the guides of the template named by the simple-template-id
30172 of the defining-type-id, the template arguments of the return type of f
30173 are deduced from the defining-type-id of A according to the process in
30174 13.10.2.5 with the exception that deduction does not fail if not all
30175 template arguments are deduced. Let g denote the result of substituting
30176 these deductions into f. If substitution succeeds, form a function or
30177 function template f' with the following properties and add it to the set
30178 of guides of A:
30180 * The function type of f' is the function type of g.
30182 * If f is a function template, f' is a function template whose template
30183 parameter list consists of all the template parameters of A (including
30184 their default template arguments) that appear in the above deductions or
30185 (recursively) in their default template arguments, followed by the
30186 template parameters of f that were not deduced (including their default
30187 template arguments), otherwise f' is not a function template.
30189 * The associated constraints (13.5.2) are the conjunction of the
30190 associated constraints of g and a constraint that is satisfied if and only
30191 if the arguments of A are deducible (see below) from the return type.
30193 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30194 be so as well.
30196 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30197 considered to be so as well.
30199 * The explicit-specifier of f' is the explicit-specifier of g (if
30200 any). */
30202 tsubst_flags_t complain = tf_warning_or_error;
30203 tree atype = TREE_TYPE (tmpl);
30204 tree aguides = NULL_TREE;
30205 tree fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30206 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30207 unsigned natparms = TREE_VEC_LENGTH (atparms);
30208 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30209 for (ovl_iterator iter (uguides); iter; ++iter)
30211 tree f = *iter;
30212 tree in_decl = f;
30213 location_t loc = DECL_SOURCE_LOCATION (f);
30214 tree ret = TREE_TYPE (TREE_TYPE (f));
30215 tree fprime = f;
30216 if (TREE_CODE (f) == TEMPLATE_DECL)
30218 processing_template_decl_sentinel ptds (/*reset*/false);
30219 ++processing_template_decl;
30221 /* Deduce template arguments for f from the type-id of A. */
30222 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30223 unsigned len = TREE_VEC_LENGTH (ftparms);
30224 tree targs = make_tree_vec (len);
30225 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30226 if (err)
30227 /* CWG2664: Discard any deductions, still build the guide. */
30228 for (unsigned i = 0; i < len; ++i)
30229 TREE_VEC_ELT (targs, i) = NULL_TREE;
30231 /* The number of parms for f' is the number of parms of A used in
30232 the deduced arguments plus non-deduced parms of f. */
30233 unsigned ndlen = 0;
30234 unsigned j;
30235 for (unsigned i = 0; i < len; ++i)
30236 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30237 ++ndlen;
30238 find_template_parameter_info ftpi (fullatparms);
30239 ftpi.find_in_recursive (targs);
30240 unsigned nusedatparms = ftpi.num_found ();
30241 unsigned nfparms = nusedatparms + ndlen;
30242 tree gtparms = make_tree_vec (nfparms);
30244 /* Set current_template_parms as in build_deduction_guide. */
30245 auto ctp = make_temp_override (current_template_parms);
30246 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
30247 TREE_VALUE (current_template_parms) = gtparms;
30249 j = 0;
30250 unsigned level = 1;
30252 /* First copy over the used parms of A. */
30253 tree atargs = make_tree_vec (natparms);
30254 for (unsigned i = 0; i < natparms; ++i)
30256 tree elt = TREE_VEC_ELT (atparms, i);
30257 if (ftpi.found (elt))
30259 unsigned index = j++;
30260 tree nelt = rewrite_tparm_list (elt, index, level,
30261 atargs, i, complain);
30262 TREE_VEC_ELT (gtparms, index) = nelt;
30265 gcc_checking_assert (j == nusedatparms);
30267 /* Adjust the deduced template args for f to refer to the A parms
30268 with their new indexes. */
30269 if (nusedatparms && nusedatparms != natparms)
30270 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30272 /* Now rewrite the non-deduced parms of f. */
30273 for (unsigned i = 0; ndlen && i < len; ++i)
30274 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30276 --ndlen;
30277 unsigned index = j++;
30278 tree oldlist = TREE_VEC_ELT (ftparms, i);
30279 tree list = rewrite_tparm_list (oldlist, index, level,
30280 targs, i, complain);
30281 TREE_VEC_ELT (gtparms, index) = list;
30283 gtparms = build_tree_list (size_one_node, gtparms);
30285 /* Substitute the deduced arguments plus the rewritten template
30286 parameters into f to get g. This covers the type, copyness,
30287 guideness, and explicit-specifier. */
30288 tree g;
30290 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30291 if cp_unevaluated_operand. */
30292 cp_evaluated ev;
30293 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
30295 if (g == error_mark_node)
30296 continue;
30297 if (nfparms == 0)
30299 /* The targs are all non-dependent, so g isn't a template. */
30300 fprime = g;
30301 ret = TREE_TYPE (TREE_TYPE (fprime));
30302 goto non_template;
30304 DECL_USE_TEMPLATE (g) = 0;
30305 fprime = build_template_decl (g, gtparms, false);
30306 DECL_TEMPLATE_RESULT (fprime) = g;
30307 TREE_TYPE (fprime) = TREE_TYPE (g);
30308 tree gtargs = template_parms_to_args (gtparms);
30309 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30310 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30312 /* Substitute the associated constraints. */
30313 tree ci = get_constraints (f);
30314 if (ci)
30315 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30316 if (ci == error_mark_node)
30317 continue;
30319 /* Add a constraint that the return type matches the instantiation of
30320 A with the same template arguments. */
30321 ret = TREE_TYPE (TREE_TYPE (fprime));
30322 if (!same_type_p (atype, ret)
30323 /* FIXME this should mean they don't compare as equivalent. */
30324 || dependent_alias_template_spec_p (atype, nt_opaque))
30326 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30327 ci = append_constraint (ci, same);
30330 if (ci)
30332 remove_constraints (fprime);
30333 set_constraints (fprime, ci);
30336 else
30338 /* For a non-template deduction guide, if the arguments of A aren't
30339 deducible from the return type, don't add the candidate. */
30340 non_template:
30341 if (!type_targs_deducible_from (tmpl, ret))
30342 continue;
30345 aguides = lookup_add (fprime, aguides);
30348 return aguides;
30351 /* True iff template arguments for TMPL can be deduced from TYPE.
30352 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30353 [over.match.class.deduct].
30355 This check is specified in terms of partial specialization, so the behavior
30356 should be parallel to that of get_partial_spec_bindings. */
30358 bool
30359 type_targs_deducible_from (tree tmpl, tree type)
30361 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30362 int len = TREE_VEC_LENGTH (tparms);
30363 tree targs = make_tree_vec (len);
30364 bool tried_array_deduction = (cxx_dialect < cxx17);
30366 /* If tmpl is a class template, this is trivial: it's deducible if TYPE is a
30367 specialization of TMPL. */
30368 if (DECL_CLASS_TEMPLATE_P (tmpl))
30369 return (CLASS_TYPE_P (type)
30370 && CLASSTYPE_TEMPLATE_INFO (type)
30371 && CLASSTYPE_TI_TEMPLATE (type) == tmpl);
30373 /* Otherwise it's an alias template. */
30374 again:
30375 if (unify (tparms, targs, TREE_TYPE (tmpl), type,
30376 UNIFY_ALLOW_NONE, false))
30377 return false;
30379 /* We don't fail on an undeduced targ the second time through (like
30380 get_partial_spec_bindings) because we're going to try defaults. */
30381 for (int i = 0; i < len; ++i)
30382 if (! TREE_VEC_ELT (targs, i))
30384 tree tparm = TREE_VEC_ELT (tparms, i);
30385 tparm = TREE_VALUE (tparm);
30387 if (!tried_array_deduction
30388 && TREE_CODE (tparm) == TYPE_DECL)
30390 try_array_deduction (tparms, targs, TREE_TYPE (tmpl));
30391 tried_array_deduction = true;
30392 if (TREE_VEC_ELT (targs, i))
30393 goto again;
30395 /* If the type parameter is a parameter pack, then it will be deduced
30396 to an empty parameter pack. This is another case that doesn't model
30397 well as partial specialization. */
30398 if (template_parameter_pack_p (tparm))
30400 tree arg;
30401 if (TREE_CODE (tparm) == PARM_DECL)
30403 arg = make_node (NONTYPE_ARGUMENT_PACK);
30404 TREE_CONSTANT (arg) = 1;
30406 else
30407 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30408 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30409 TREE_VEC_ELT (targs, i) = arg;
30413 /* Maybe add in default template args. This seems like a flaw in the
30414 specification in terms of partial specialization, since it says the
30415 partial specialization has the the template parameter list of A, but a
30416 partial specialization can't have default targs. */
30417 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30418 if (targs == error_mark_node)
30419 return false;
30421 /* I believe we don't need the template_template_parm_bindings_ok_p call
30422 because coerce_template_parms did coerce_template_template_parms. */
30424 return constraints_satisfied_p (tmpl, targs);
30427 /* Return artificial deduction guides built from the constructors of class
30428 template TMPL. */
30430 static tree
30431 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30433 tree outer_args = outer_template_args (tmpl);
30434 tree type = TREE_TYPE (most_general_template (tmpl));
30436 tree cands = NULL_TREE;
30438 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30440 /* Skip inherited constructors. */
30441 if (iter.using_p ())
30442 continue;
30444 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30445 cands = lookup_add (guide, cands);
30448 /* Add implicit default constructor deduction guide. */
30449 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30451 tree guide = build_deduction_guide (type, type, outer_args,
30452 complain);
30453 cands = lookup_add (guide, cands);
30456 /* Add copy guide. */
30458 tree gtype = build_reference_type (type);
30459 tree guide = build_deduction_guide (type, gtype, outer_args,
30460 complain);
30461 cands = lookup_add (guide, cands);
30464 return cands;
30467 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30469 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30470 aggregate candidate is added separately because it depends on the
30471 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30472 guide. */
30474 static tree
30475 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30477 tree guides = NULL_TREE;
30478 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30480 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30481 tree tinfo = get_template_info (under);
30482 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30483 complain);
30485 else
30487 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30488 dguide_name (tmpl),
30489 LOOK_want::NORMAL, /*complain*/false);
30490 if (guides == error_mark_node)
30491 guides = NULL_TREE;
30492 else
30493 any_dguides_p = true;
30496 /* Cache the deduction guides for a template. We also remember the result of
30497 lookup, and rebuild everything if it changes; should be very rare. */
30498 tree_pair_p cache = NULL;
30499 if (tree_pair_p &r
30500 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30502 cache = r;
30503 if (cache->purpose == guides)
30504 return cache->value;
30506 else
30508 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30509 cache->purpose = guides;
30512 tree cands = NULL_TREE;
30513 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30514 cands = alias_ctad_tweaks (tmpl, guides);
30515 else
30517 cands = ctor_deduction_guides_for (tmpl, complain);
30518 for (ovl_iterator it (guides); it; ++it)
30519 cands = lookup_add (*it, cands);
30522 cache->value = cands;
30523 return cands;
30526 /* Return whether TMPL is a (class template argument-) deducible template. */
30528 bool
30529 ctad_template_p (tree tmpl)
30531 /* A deducible template is either a class template or is an alias template
30532 whose defining-type-id is of the form
30534 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30536 where the nested-name-specifier (if any) is non-dependent and the
30537 template-name of the simple-template-id names a deducible template. */
30539 if (DECL_CLASS_TEMPLATE_P (tmpl)
30540 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30541 return true;
30542 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30543 return false;
30544 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30545 if (tree tinfo = get_template_info (orig))
30546 return ctad_template_p (TI_TEMPLATE (tinfo));
30547 return false;
30550 /* Deduce template arguments for the class template placeholder PTYPE for
30551 template TMPL based on the initializer INIT, and return the resulting
30552 type. */
30554 static tree
30555 do_class_deduction (tree ptype, tree tmpl, tree init,
30556 int flags, tsubst_flags_t complain)
30558 /* We should have handled this in the caller. */
30559 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30560 return ptype;
30562 /* If the class was erroneous, don't try to deduce, because that
30563 can generate a lot of diagnostic. */
30564 if (TREE_TYPE (tmpl)
30565 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30566 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30567 return ptype;
30569 /* Wait until the enclosing scope is non-dependent. */
30570 if (DECL_CLASS_SCOPE_P (tmpl)
30571 && dependent_type_p (DECL_CONTEXT (tmpl)))
30572 return ptype;
30574 /* Initializing one placeholder from another. */
30575 if (init
30576 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30577 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30578 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30579 == TEMPLATE_PARM_INDEX)))
30580 && is_auto (TREE_TYPE (init))
30581 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30582 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30584 if (!ctad_template_p (tmpl))
30586 if (complain & tf_error)
30587 error ("non-deducible template %qT used without template arguments", tmpl);
30588 return error_mark_node;
30590 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30592 if (complain & tf_error)
30594 /* Be permissive with equivalent alias templates. */
30595 tree u = get_underlying_template (tmpl);
30596 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30597 bool complained
30598 = emit_diagnostic (dk, input_location, 0,
30599 "alias template deduction only available "
30600 "with %<-std=c++20%> or %<-std=gnu++20%>");
30601 if (u == tmpl)
30602 return error_mark_node;
30603 else if (complained)
30605 inform (input_location, "use %qD directly instead", u);
30606 tmpl = u;
30609 else
30610 return error_mark_node;
30613 /* Wait until the initializer is non-dependent. */
30614 if (type_dependent_expression_p (init))
30615 return ptype;
30617 /* Don't bother with the alias rules for an equivalent template. */
30618 tmpl = get_underlying_template (tmpl);
30620 tree type = TREE_TYPE (tmpl);
30622 bool try_list_cand = false;
30623 bool list_init_p = false;
30625 releasing_vec rv_args = NULL;
30626 vec<tree,va_gc> *&args = *&rv_args;
30627 if (init == NULL_TREE)
30628 args = make_tree_vector ();
30629 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30631 list_init_p = true;
30632 try_list_cand = true;
30633 if (CONSTRUCTOR_NELTS (init) == 1
30634 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30636 /* As an exception, the first phase in 16.3.1.7 (considering the
30637 initializer list as a single argument) is omitted if the
30638 initializer list consists of a single expression of type cv U,
30639 where U is a specialization of C or a class derived from a
30640 specialization of C. */
30641 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30642 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30643 try_list_cand = false;
30645 if (try_list_cand || is_std_init_list (type))
30646 args = make_tree_vector_single (init);
30647 else
30648 args = make_tree_vector_from_ctor (init);
30650 else if (TREE_CODE (init) == TREE_LIST)
30651 args = make_tree_vector_from_list (init);
30652 else
30653 args = make_tree_vector_single (init);
30655 /* Do this now to avoid problems with erroneous args later on. */
30656 args = resolve_args (args, complain);
30657 if (args == NULL)
30658 return error_mark_node;
30660 bool any_dguides_p = false;
30661 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30662 if (cands == error_mark_node)
30663 return error_mark_node;
30665 /* Prune explicit deduction guides in copy-initialization context (but
30666 not copy-list-initialization). */
30667 bool elided = false;
30668 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30670 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30671 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30672 elided = true;
30674 if (elided)
30676 /* Found a nonconverting guide, prune the candidates. */
30677 tree pruned = NULL_TREE;
30678 for (lkp_iterator iter (cands); iter; ++iter)
30679 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30680 pruned = lookup_add (*iter, pruned);
30682 cands = pruned;
30686 if (!any_dguides_p)
30687 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30688 cands = lookup_add (guide, cands);
30690 tree fndecl = error_mark_node;
30692 /* If this is list-initialization and the class has a list guide, first
30693 try deducing from the list as a single argument, as [over.match.list]. */
30694 if (try_list_cand)
30696 tree list_cands = NULL_TREE;
30697 for (tree dg : lkp_range (cands))
30698 if (is_list_ctor (dg))
30699 list_cands = lookup_add (dg, list_cands);
30700 if (list_cands)
30701 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30702 if (fndecl == error_mark_node)
30704 /* That didn't work, now try treating the list as a sequence of
30705 arguments. */
30706 release_tree_vector (args);
30707 args = make_tree_vector_from_ctor (init);
30708 args = resolve_args (args, complain);
30709 if (args == NULL)
30710 return error_mark_node;
30714 if (elided && !cands)
30716 error ("cannot deduce template arguments for copy-initialization"
30717 " of %qT, as it has no non-explicit deduction guides or "
30718 "user-declared constructors", type);
30719 return error_mark_node;
30721 else if (!cands && fndecl == error_mark_node)
30723 error ("cannot deduce template arguments of %qT, as it has no viable "
30724 "deduction guides", type);
30725 return error_mark_node;
30728 if (fndecl == error_mark_node)
30729 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30731 if (fndecl == error_mark_node)
30733 if (complain & tf_warning_or_error)
30735 error ("class template argument deduction failed:");
30736 perform_dguide_overload_resolution (cands, args, complain);
30737 if (elided)
30738 inform (input_location, "explicit deduction guides not considered "
30739 "for copy-initialization");
30741 return error_mark_node;
30743 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30744 constructor is chosen, the initialization is ill-formed. */
30745 else if (flags & LOOKUP_ONLYCONVERTING)
30747 if (DECL_NONCONVERTING_P (fndecl))
30749 if (complain & tf_warning_or_error)
30751 // TODO: Pass down location from cp_finish_decl.
30752 error ("class template argument deduction for %qT failed: "
30753 "explicit deduction guide selected in "
30754 "copy-list-initialization", type);
30755 inform (DECL_SOURCE_LOCATION (fndecl),
30756 "explicit deduction guide declared here");
30759 return error_mark_node;
30763 /* If CTAD succeeded but the type doesn't have any explicit deduction
30764 guides, this deduction might not be what the user intended. */
30765 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30767 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30768 || global_dc->dc_warn_system_headers)
30769 && warning (OPT_Wctad_maybe_unsupported,
30770 "%qT may not intend to support class template argument "
30771 "deduction", type))
30772 inform (input_location, "add a deduction guide to suppress this "
30773 "warning");
30776 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30777 cp_type_quals (ptype));
30780 /* Return true if INIT is an unparenthesized id-expression or an
30781 unparenthesized class member access. Used for the argument of
30782 decltype(auto). */
30784 bool
30785 unparenthesized_id_or_class_member_access_p (tree init)
30787 STRIP_ANY_LOCATION_WRAPPER (init);
30789 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30790 reference type). Only the latter is an id-expression. */
30791 if (REFERENCE_REF_P (init)
30792 && !REF_PARENTHESIZED_P (init))
30793 init = TREE_OPERAND (init, 0);
30794 return (DECL_P (init)
30795 || ((TREE_CODE (init) == COMPONENT_REF
30796 || TREE_CODE (init) == SCOPE_REF)
30797 && !REF_PARENTHESIZED_P (init)));
30800 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30801 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30802 The CONTEXT determines the context in which auto deduction is performed
30803 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30805 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30806 to properly substitute the result. It's also used in the adc_unify and
30807 adc_requirement contexts to communicate the necessary template arguments
30808 to satisfaction. OUTER_TARGS is ignored in other contexts.
30810 Additionally for adc_unify contexts TMPL is the template for which TYPE
30811 is a template parameter type.
30813 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30814 scope may be appended to the list of deduced template arguments prior to
30815 determining constraint satisfaction as appropriate. */
30817 tree
30818 do_auto_deduction (tree type, tree init, tree auto_node,
30819 tsubst_flags_t complain /* = tf_warning_or_error */,
30820 auto_deduction_context context /* = adc_unspecified */,
30821 tree outer_targs /* = NULL_TREE */,
30822 int flags /* = LOOKUP_NORMAL */,
30823 tree tmpl /* = NULL_TREE */)
30825 if (type == error_mark_node || init == error_mark_node)
30826 return error_mark_node;
30828 if (init && type_dependent_expression_p (init)
30829 && context != adc_unify)
30830 /* Defining a subset of type-dependent expressions that we can deduce
30831 from ahead of time isn't worth the trouble. */
30832 return type;
30834 /* Similarly, we can't deduce from another undeduced decl. */
30835 if (init && undeduced_auto_decl (init))
30836 return type;
30838 /* We may be doing a partial substitution, but we still want to replace
30839 auto_node. */
30840 complain &= ~tf_partial;
30842 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30844 /* We don't recurse here because we can't deduce from a nested
30845 initializer_list. */
30846 if (CONSTRUCTOR_ELTS (init))
30847 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30848 elt.value = resolve_nondeduced_context (elt.value, complain);
30850 else if (init)
30851 init = resolve_nondeduced_context (init, complain);
30853 /* In C++23, we must deduce the type to int&& for code like
30854 decltype(auto) f(int&& x) { return (x); }
30856 auto&& f(int x) { return x; }
30857 so we use treat_lvalue_as_rvalue_p. But don't do it for
30858 decltype(auto) f(int x) { return x; }
30859 where we should deduce 'int' rather than 'int&&'; transmogrifying
30860 INIT to an rvalue would break that. */
30861 tree r;
30862 if (cxx_dialect >= cxx23
30863 && context == adc_return_type
30864 && (!AUTO_IS_DECLTYPE (auto_node)
30865 || !unparenthesized_id_or_class_member_access_p (init))
30866 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30867 /*return*/true)))
30868 init = r;
30870 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30871 /* C++17 class template argument deduction. */
30872 return do_class_deduction (type, ctmpl, init, flags, complain);
30874 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30875 /* Nothing we can do with this, even in deduction context. */
30876 return type;
30878 location_t loc = cp_expr_loc_or_input_loc (init);
30880 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30881 with either a new invented type template parameter U or, if the
30882 initializer is a braced-init-list (8.5.4), with
30883 std::initializer_list<U>. */
30884 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30886 if (!DIRECT_LIST_INIT_P (init))
30887 type = listify_autos (type, auto_node);
30888 else if (CONSTRUCTOR_NELTS (init) == 1)
30889 init = CONSTRUCTOR_ELT (init, 0)->value;
30890 else
30892 if (complain & tf_warning_or_error)
30894 if (permerror (loc, "direct-list-initialization of "
30895 "%<auto%> requires exactly one element"))
30896 inform (loc,
30897 "for deduction to %<std::initializer_list%>, use copy-"
30898 "list-initialization (i.e. add %<=%> before the %<{%>)");
30900 type = listify_autos (type, auto_node);
30904 if (type == error_mark_node || init == error_mark_node)
30905 return error_mark_node;
30907 tree targs;
30908 if (context == adc_decomp_type
30909 && auto_node == type
30910 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30912 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30913 and initializer has array type, deduce cv-qualified array type. */
30914 targs = make_tree_vec (1);
30915 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30917 else if (AUTO_IS_DECLTYPE (auto_node))
30919 const bool id = unparenthesized_id_or_class_member_access_p (init);
30920 tree deduced = finish_decltype_type (init, id, complain);
30921 deduced = canonicalize_type_argument (deduced, complain);
30922 if (deduced == error_mark_node)
30923 return error_mark_node;
30924 targs = make_tree_vec (1);
30925 TREE_VEC_ELT (targs, 0) = deduced;
30927 else
30929 if (error_operand_p (init))
30930 return error_mark_node;
30932 tree parms = build_tree_list (NULL_TREE, type);
30933 tree tparms;
30935 if (flag_concepts_ts)
30936 tparms = extract_autos (type);
30937 else
30939 tparms = make_tree_vec (1);
30940 TREE_VEC_ELT (tparms, 0)
30941 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30944 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30945 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30946 DEDUCE_CALL,
30947 NULL, /*explain_p=*/false);
30948 if (val > 0)
30950 if (processing_template_decl)
30951 /* Try again at instantiation time. */
30952 return type;
30953 if (type && type != error_mark_node
30954 && (complain & tf_error))
30955 /* If type is error_mark_node a diagnostic must have been
30956 emitted by now. Also, having a mention to '<type error>'
30957 in the diagnostic is not really useful to the user. */
30959 if (cfun
30960 && FNDECL_USED_AUTO (current_function_decl)
30961 && (auto_node
30962 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30963 && LAMBDA_FUNCTION_P (current_function_decl))
30964 error_at (loc, "unable to deduce lambda return type from %qE",
30965 init);
30966 else
30967 error_at (loc, "unable to deduce %qT from %qE", type, init);
30968 type_unification_real (tparms, targs, parms, &init, 1, 0,
30969 DEDUCE_CALL,
30970 NULL, /*explain_p=*/true);
30972 return error_mark_node;
30976 /* Check any placeholder constraints against the deduced type. */
30977 if (processing_template_decl && context == adc_unify)
30978 /* Constraints will be checked after deduction. */;
30979 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30981 if (processing_template_decl)
30983 gcc_checking_assert (context == adc_variable_type
30984 || context == adc_return_type
30985 || context == adc_decomp_type);
30986 gcc_checking_assert (!type_dependent_expression_p (init));
30987 /* If the constraint is dependent, we need to wait until
30988 instantiation time to resolve the placeholder. */
30989 if (placeholder_type_constraint_dependent_p (constr))
30990 return type;
30993 if (context == adc_return_type
30994 || context == adc_variable_type
30995 || context == adc_decomp_type)
30996 if (tree fn = current_function_decl)
30997 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30999 outer_targs = DECL_TEMPLATE_INFO (fn)
31000 ? DECL_TI_ARGS (fn) : NULL_TREE;
31001 if (LAMBDA_FUNCTION_P (fn))
31003 /* As in satisfy_declaration_constraints. */
31004 tree regen_args = lambda_regenerating_args (fn);
31005 if (outer_targs)
31006 outer_targs = add_to_template_args (regen_args, outer_targs);
31007 else
31008 outer_targs = regen_args;
31012 tree full_targs = outer_targs;
31013 if (context == adc_unify && tmpl)
31014 full_targs = add_outermost_template_args (tmpl, full_targs);
31015 full_targs = add_to_template_args (full_targs, targs);
31017 /* HACK: Compensate for callers not always communicating all levels of
31018 outer template arguments by filling in the outermost missing levels
31019 with dummy levels before checking satisfaction. We'll still crash
31020 if the constraint depends on a template argument belonging to one of
31021 these missing levels, but this hack otherwise allows us to handle a
31022 large subset of possible constraints (including all non-dependent
31023 constraints). */
31024 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31025 - TMPL_ARGS_DEPTH (full_targs)))
31027 tree dummy_levels = make_tree_vec (missing_levels);
31028 for (int i = 0; i < missing_levels; ++i)
31029 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31030 full_targs = add_to_template_args (dummy_levels, full_targs);
31033 if (!constraints_satisfied_p (auto_node, full_targs))
31035 if (complain & tf_warning_or_error)
31037 auto_diagnostic_group d;
31038 switch (context)
31040 case adc_unspecified:
31041 case adc_unify:
31042 error_at (loc, "placeholder constraints not satisfied");
31043 break;
31044 case adc_variable_type:
31045 case adc_decomp_type:
31046 error_at (loc, "deduced initializer does not satisfy "
31047 "placeholder constraints");
31048 break;
31049 case adc_return_type:
31050 error_at (loc, "deduced return type does not satisfy "
31051 "placeholder constraints");
31052 break;
31053 case adc_requirement:
31054 error_at (loc, "deduced expression type does not satisfy "
31055 "placeholder constraints");
31056 break;
31058 diagnose_constraints (loc, auto_node, full_targs);
31060 return error_mark_node;
31064 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31065 /* The outer template arguments are already substituted into type
31066 (but we still may have used them for constraint checking above). */;
31067 else if (context == adc_unify)
31068 targs = add_to_template_args (outer_targs, targs);
31069 else if (processing_template_decl)
31070 targs = add_to_template_args (current_template_args (), targs);
31071 return tsubst (type, targs, complain, NULL_TREE);
31074 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31075 result. */
31077 tree
31078 splice_late_return_type (tree type, tree late_return_type)
31080 if (late_return_type)
31082 gcc_assert (is_auto (type) || seen_error ());
31083 return late_return_type;
31086 if (tree auto_node = find_type_usage (type, is_auto))
31087 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31089 /* In an abbreviated function template we didn't know we were dealing
31090 with a function template when we saw the auto return type, so rebuild
31091 the return type using an auto with the correct level. */
31092 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31093 tree auto_vec = make_tree_vec (1);
31094 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31095 tree targs = add_outermost_template_args (current_template_args (),
31096 auto_vec);
31097 /* Also rebuild the constraint info in terms of the new auto. */
31098 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31099 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31100 = build_tree_list (current_template_parms,
31101 tsubst_constraint (TREE_VALUE (ci), targs,
31102 tf_none, NULL_TREE));
31103 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31104 return tsubst (type, targs, tf_none, NULL_TREE);
31106 return type;
31109 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31110 'decltype(auto)' or a deduced class template. */
31112 bool
31113 is_auto (const_tree type)
31115 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31116 && (TYPE_IDENTIFIER (type) == auto_identifier
31117 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31118 return true;
31119 else
31120 return false;
31123 /* for_each_template_parm callback for type_uses_auto. */
31126 is_auto_r (tree tp, void */*data*/)
31128 return is_auto (tp);
31131 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31132 a use of `auto'. Returns NULL_TREE otherwise. */
31134 tree
31135 type_uses_auto (tree type)
31137 if (type == NULL_TREE)
31138 return NULL_TREE;
31139 else if (flag_concepts_ts)
31141 /* The Concepts TS allows multiple autos in one type-specifier; just
31142 return the first one we find, do_auto_deduction will collect all of
31143 them. */
31144 if (uses_template_parms (type))
31145 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31146 /*visited*/NULL, /*nondeduced*/false);
31147 else
31148 return NULL_TREE;
31150 else
31151 return find_type_usage (type, is_auto);
31154 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31155 concepts are enabled, auto is acceptable in template arguments, but
31156 only when TEMPL identifies a template class. Return TRUE if any
31157 such errors were reported. */
31159 bool
31160 check_auto_in_tmpl_args (tree tmpl, tree args)
31162 if (!flag_concepts_ts)
31163 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31164 have already been rejected by the parser more generally. */
31165 return false;
31167 /* If there were previous errors, nevermind. */
31168 if (!args || TREE_CODE (args) != TREE_VEC)
31169 return false;
31171 /* If TMPL is an identifier, we're parsing and we can't tell yet
31172 whether TMPL is supposed to be a type, a function or a variable.
31173 We'll only be able to tell during template substitution, so we
31174 expect to be called again then. If concepts are enabled and we
31175 know we have a type, we're ok. */
31176 if (identifier_p (tmpl)
31177 || (DECL_P (tmpl)
31178 && (DECL_TYPE_TEMPLATE_P (tmpl)
31179 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31180 return false;
31182 /* Quickly search for any occurrences of auto; usually there won't
31183 be any, and then we'll avoid allocating the vector. */
31184 if (!type_uses_auto (args))
31185 return false;
31187 bool errors = false;
31189 tree vec = extract_autos (args);
31190 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31192 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31193 error_at (DECL_SOURCE_LOCATION (xauto),
31194 "invalid use of %qT in template argument", xauto);
31195 errors = true;
31198 return errors;
31201 /* Recursively walk over && expressions searching for EXPR. Return a reference
31202 to that expression. */
31204 static tree *find_template_requirement (tree *t, tree key)
31206 if (*t == key)
31207 return t;
31208 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31210 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31211 return p;
31212 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31213 return p;
31215 return 0;
31218 /* Convert the generic type parameters in PARM that match the types given in the
31219 range [START_IDX, END_IDX) from the current_template_parms into generic type
31220 packs. */
31222 tree
31223 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31225 tree current = current_template_parms;
31226 int depth = TMPL_PARMS_DEPTH (current);
31227 current = INNERMOST_TEMPLATE_PARMS (current);
31228 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31230 for (int i = 0; i < start_idx; ++i)
31231 TREE_VEC_ELT (replacement, i)
31232 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31234 for (int i = start_idx; i < end_idx; ++i)
31236 /* Create a distinct parameter pack type from the current parm and add it
31237 to the replacement args to tsubst below into the generic function
31238 parameter. */
31239 tree node = TREE_VEC_ELT (current, i);
31240 tree o = TREE_TYPE (TREE_VALUE (node));
31241 tree t = copy_type (o);
31242 TEMPLATE_TYPE_PARM_INDEX (t)
31243 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31244 t, 0, 0, tf_none);
31245 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31246 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31247 TYPE_MAIN_VARIANT (t) = t;
31248 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31249 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31250 TREE_VEC_ELT (replacement, i) = t;
31252 /* Replace the current template parameter with new pack. */
31253 TREE_VALUE (node) = TREE_CHAIN (t);
31255 /* Surgically adjust the associated constraint of adjusted parameter
31256 and it's corresponding contribution to the current template
31257 requirements. */
31258 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31260 tree id = unpack_concept_check (constr);
31261 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31262 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
31263 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31265 /* If there was a constraint, we also need to replace that in
31266 the template requirements, which we've already built. */
31267 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31268 reqs = find_template_requirement (reqs, constr);
31269 *reqs = fold;
31273 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31274 TREE_VEC_ELT (replacement, i)
31275 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31277 /* If there are more levels then build up the replacement with the outer
31278 template parms. */
31279 if (depth > 1)
31280 replacement = add_to_template_args (template_parms_to_args
31281 (TREE_CHAIN (current_template_parms)),
31282 replacement);
31284 return tsubst (parm, replacement, tf_none, NULL_TREE);
31287 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31288 0..N-1. */
31290 void
31291 declare_integer_pack (void)
31293 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31294 build_function_type_list (integer_type_node,
31295 integer_type_node,
31296 NULL_TREE),
31297 NULL_TREE, ECF_CONST);
31298 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31299 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31300 CP_BUILT_IN_INTEGER_PACK);
31303 /* Walk the decl or type specialization table calling FN on each
31304 entry. */
31306 void
31307 walk_specializations (bool decls_p,
31308 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31309 void *data)
31311 spec_hash_table *table = decls_p ? decl_specializations
31312 : type_specializations;
31313 spec_hash_table::iterator end (table->end ());
31314 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31315 fn (decls_p, *iter, data);
31318 /* Lookup the specialization of *ELT, in the decl or type
31319 specialization table. Return the SPEC that's already there, or
31320 NULL if nothing. */
31322 tree
31323 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31325 hash_table<spec_hasher> *specializations
31326 = decl_p ? decl_specializations : type_specializations;
31327 hashval_t hash = spec_hasher::hash (elt);
31328 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31330 if (slot)
31331 return (*slot)->spec;
31333 return NULL_TREE;
31336 /* Return flags encoding whether SPEC is on the instantiation and/or
31337 specialization lists of TMPL. */
31339 unsigned
31340 get_mergeable_specialization_flags (tree tmpl, tree decl)
31342 unsigned flags = 0;
31344 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31345 inst; inst = TREE_CHAIN (inst))
31346 if (TREE_VALUE (inst) == decl)
31348 flags |= 1;
31349 break;
31352 if (CLASS_TYPE_P (TREE_TYPE (decl))
31353 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31354 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31355 /* Only need to search if DECL is a partial specialization. */
31356 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31357 part; part = TREE_CHAIN (part))
31358 if (TREE_VALUE (part) == decl)
31360 flags |= 2;
31361 break;
31364 return flags;
31367 /* Add a new specialization described by SPEC. DECL is the
31368 maybe-template decl and FLAGS is as returned from
31369 get_mergeable_specialization_flags. */
31371 void
31372 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31373 tree decl, unsigned flags)
31375 hashval_t hash = spec_hasher::hash (elt);
31376 if (decl_p)
31378 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31380 gcc_checking_assert (!*slot);
31381 auto entry = ggc_alloc<spec_entry> ();
31382 *entry = *elt;
31383 *slot = entry;
31385 if (alias_p)
31387 elt->spec = TREE_TYPE (elt->spec);
31388 gcc_checking_assert (elt->spec);
31392 if (!decl_p || alias_p)
31394 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31396 /* We don't distinguish different constrained partial type
31397 specializations, so there could be duplicates. Everything else
31398 must be new. */
31399 if (!(flags & 2 && *slot))
31401 gcc_checking_assert (!*slot);
31403 auto entry = ggc_alloc<spec_entry> ();
31404 *entry = *elt;
31405 *slot = entry;
31409 if (flags & 1)
31410 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31411 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31413 if (flags & 2)
31415 /* A partial specialization. */
31416 tree cons = tree_cons (elt->args, decl,
31417 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31418 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31419 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31423 /* Set up the hash tables for template instantiations. */
31425 void
31426 init_template_processing (void)
31428 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31429 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31431 if (cxx_dialect >= cxx11)
31432 declare_integer_pack ();
31435 /* Print stats about the template hash tables for -fstats. */
31437 void
31438 print_template_statistics (void)
31440 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31441 "%f collisions\n", (long) decl_specializations->size (),
31442 (long) decl_specializations->elements (),
31443 decl_specializations->collisions ());
31444 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31445 "%f collisions\n", (long) type_specializations->size (),
31446 (long) type_specializations->elements (),
31447 type_specializations->collisions ());
31450 #if CHECKING_P
31452 namespace selftest {
31454 /* Verify that build_non_dependent_expr () works, for various expressions,
31455 and that location wrappers don't affect the results. */
31457 static void
31458 test_build_non_dependent_expr ()
31460 location_t loc = BUILTINS_LOCATION;
31462 /* Verify constants, without and with location wrappers. */
31463 tree int_cst = build_int_cst (integer_type_node, 42);
31464 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31466 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31467 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31468 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31470 tree string_lit = build_string (4, "foo");
31471 TREE_TYPE (string_lit) = char_array_type_node;
31472 string_lit = fix_string_type (string_lit);
31473 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31475 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31476 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31477 ASSERT_EQ (wrapped_string_lit,
31478 build_non_dependent_expr (wrapped_string_lit));
31481 /* Verify that type_dependent_expression_p () works correctly, even
31482 in the presence of location wrapper nodes. */
31484 static void
31485 test_type_dependent_expression_p ()
31487 location_t loc = BUILTINS_LOCATION;
31489 tree name = get_identifier ("foo");
31491 /* If no templates are involved, nothing is type-dependent. */
31492 gcc_assert (!processing_template_decl);
31493 ASSERT_FALSE (type_dependent_expression_p (name));
31495 ++processing_template_decl;
31497 /* Within a template, an unresolved name is always type-dependent. */
31498 ASSERT_TRUE (type_dependent_expression_p (name));
31500 /* Ensure it copes with NULL_TREE and errors. */
31501 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31502 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31504 /* A USING_DECL in a template should be type-dependent, even if wrapped
31505 with a location wrapper (PR c++/83799). */
31506 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31507 TREE_TYPE (using_decl) = integer_type_node;
31508 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31509 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31510 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31511 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31513 --processing_template_decl;
31516 /* Run all of the selftests within this file. */
31518 void
31519 cp_pt_cc_tests ()
31521 test_build_non_dependent_expr ();
31522 test_type_dependent_expression_p ();
31525 } // namespace selftest
31527 #endif /* #if CHECKING_P */
31529 #include "gt-cp-pt.h"