c++: local class in generic lambda [PR113544]
[official-gcc.git] / gcc / cp / pt.cc
blobfb2448a26e968433c7705853ce1944ae36cb8d22
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2024 Free Software Foundation, Inc.
3 Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4 Rewritten by Jason Merrill (jason@cygnus.com).
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* Known bugs or deficiencies include:
24 all methods must be provided in header files; can't use a source
25 file that contains only the method templates and "just win".
27 Fixed by: C++20 modules. */
29 #include "config.h"
30 #define INCLUDE_ALGORITHM // for std::equal
31 #include "system.h"
32 #include "coretypes.h"
33 #include "cp-tree.h"
34 #include "timevar.h"
35 #include "stringpool.h"
36 #include "varasm.h"
37 #include "attribs.h"
38 #include "stor-layout.h"
39 #include "intl.h"
40 #include "c-family/c-objc.h"
41 #include "cp-objcp-common.h"
42 #include "toplev.h"
43 #include "tree-iterator.h"
44 #include "type-utils.h"
45 #include "gimplify.h"
46 #include "gcc-rich-location.h"
47 #include "selftest.h"
48 #include "target.h"
49 #include "builtins.h"
50 #include "omp-general.h"
52 /* The type of functions taking a tree, and some additional data, and
53 returning an int. */
54 typedef int (*tree_fn_t) (tree, void*);
56 /* The PENDING_TEMPLATES is a list of templates whose instantiations
57 have been deferred, either because their definitions were not yet
58 available, or because we were putting off doing the work. */
59 struct GTY ((chain_next ("%h.next"))) pending_template
61 struct pending_template *next;
62 struct tinst_level *tinst;
65 static GTY(()) struct pending_template *pending_templates;
66 static GTY(()) struct pending_template *last_pending_template;
68 int processing_template_parmlist;
69 static int template_header_count;
71 static vec<int> inline_parm_levels;
73 static GTY(()) struct tinst_level *current_tinst_level;
75 static GTY(()) vec<tree, va_gc> *saved_access_scope;
77 /* Live only within one (recursive) call to tsubst_expr. We use
78 this to pass the statement expression node from the STMT_EXPR
79 to the EXPR_STMT that is its result. */
80 static tree cur_stmt_expr;
82 // -------------------------------------------------------------------------- //
83 // Local Specialization Stack
85 // Implementation of the RAII helper for creating new local
86 // specializations.
87 local_specialization_stack::local_specialization_stack (lss_policy policy)
88 : saved (local_specializations)
90 if (policy == lss_nop)
92 else if (policy == lss_blank || !saved)
93 local_specializations = new hash_map<tree, tree>;
94 else
95 local_specializations = new hash_map<tree, tree>(*saved);
98 local_specialization_stack::~local_specialization_stack ()
100 if (local_specializations != saved)
102 delete local_specializations;
103 local_specializations = saved;
107 /* True if we've recursed into fn_type_unification too many times. */
108 static bool excessive_deduction_depth;
110 struct spec_hasher : ggc_ptr_hash<spec_entry>
112 static hashval_t hash (tree, tree);
113 static hashval_t hash (spec_entry *);
114 static bool equal (spec_entry *, spec_entry *);
117 /* The general template is not in these tables. */
118 typedef hash_table<spec_hasher> spec_hash_table;
119 static GTY (()) spec_hash_table *decl_specializations;
120 static GTY (()) spec_hash_table *type_specializations;
122 /* Contains canonical template parameter types. The vector is indexed by
123 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
124 TREE_LIST, whose TREE_VALUEs contain the canonical template
125 parameters of various types and levels. */
126 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
128 #define UNIFY_ALLOW_NONE 0
129 #define UNIFY_ALLOW_MORE_CV_QUAL 1
130 #define UNIFY_ALLOW_LESS_CV_QUAL 2
131 #define UNIFY_ALLOW_DERIVED 4
132 #define UNIFY_ALLOW_INTEGER 8
133 #define UNIFY_ALLOW_OUTER_LEVEL 16
134 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
135 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
137 enum template_base_result {
138 tbr_incomplete_type,
139 tbr_ambiguous_baseclass,
140 tbr_success
143 static bool resolve_overloaded_unification (tree, tree, tree, tree,
144 unification_kind_t, int,
145 bool);
146 static int try_one_overload (tree, tree, tree, tree, tree,
147 unification_kind_t, int, bool, bool);
148 static int unify (tree, tree, tree, tree, int, bool);
149 static void add_pending_template (tree);
150 static tree reopen_tinst_level (struct tinst_level *);
151 static tree tsubst_initializer_list (tree, tree);
152 static tree get_partial_spec_bindings (tree, tree, tree);
153 static void tsubst_enum (tree, tree, tree);
154 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
155 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
156 struct conversion **, bool, bool);
157 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
158 tree*, tree*, tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160 unsigned int, int, unification_kind_t,
161 vec<deferred_access_check, va_gc> **,
162 bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167 tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169 hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184 tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
190 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
192 static bool check_specialization_scope (void);
193 static tree process_partial_specialization (tree);
194 static enum template_base_result get_template_base (tree, tree, tree, tree,
195 bool , tree *);
196 static tree try_class_unification (tree, tree, tree, tree, bool);
197 static bool class_nttp_const_wrapper_p (tree t);
198 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
199 tree, tree);
200 static bool template_template_parm_bindings_ok_p (tree, tree);
201 static void tsubst_default_arguments (tree, tsubst_flags_t);
202 static tree for_each_template_parm_r (tree *, int *, void *);
203 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
204 static void copy_default_args_to_explicit_spec (tree);
205 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
206 static bool dependent_template_arg_p (tree);
207 static bool dependent_type_p_r (tree);
208 static tree tsubst_stmt (tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
210 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
211 static tree tsubst_name (tree, tree, tsubst_flags_t, tree);
212 static void perform_instantiation_time_access_checks (tree, tree);
213 static tree listify (tree);
214 static tree listify_autos (tree, tree);
215 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
216 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
217 static tree get_underlying_template (tree);
218 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
219 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
220 static tree make_argument_pack (tree);
221 static tree enclosing_instantiation_of (tree tctx);
222 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
223 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
224 static void mark_template_arguments_used (tree, tree);
225 static bool uses_outer_template_parms (tree);
226 static tree alias_ctad_tweaks (tree, tree);
227 static tree inherited_ctad_tweaks (tree, tree, tsubst_flags_t);
228 static tree deduction_guides_for (tree, bool&, tsubst_flags_t);
230 /* Make the current scope suitable for access checking when we are
231 processing T. T can be FUNCTION_DECL for instantiated function
232 template, VAR_DECL for static member variable, or TYPE_DECL for
233 for a class or alias template (needed by instantiate_decl). */
235 void
236 push_access_scope (tree t)
238 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
239 || TREE_CODE (t) == TYPE_DECL);
241 if (DECL_FRIEND_CONTEXT (t))
242 push_nested_class (DECL_FRIEND_CONTEXT (t));
243 else if (DECL_IMPLICIT_TYPEDEF_P (t)
244 && CLASS_TYPE_P (TREE_TYPE (t)))
245 push_nested_class (TREE_TYPE (t));
246 else if (DECL_CLASS_SCOPE_P (t))
247 push_nested_class (DECL_CONTEXT (t));
248 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
249 /* An artificial deduction guide should have the same access as
250 the constructor. */
251 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
252 else
253 push_to_top_level ();
255 if (TREE_CODE (t) == FUNCTION_DECL)
257 vec_safe_push (saved_access_scope, current_function_decl);
258 current_function_decl = t;
262 /* Restore the scope set up by push_access_scope. T is the node we
263 are processing. */
265 void
266 pop_access_scope (tree t)
268 if (TREE_CODE (t) == FUNCTION_DECL)
269 current_function_decl = saved_access_scope->pop();
271 if (DECL_FRIEND_CONTEXT (t)
272 || (DECL_IMPLICIT_TYPEDEF_P (t)
273 && CLASS_TYPE_P (TREE_TYPE (t)))
274 || DECL_CLASS_SCOPE_P (t)
275 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
276 pop_nested_class ();
277 else
278 pop_from_top_level ();
281 /* Do any processing required when DECL (a member template
282 declaration) is finished. Returns the TEMPLATE_DECL corresponding
283 to DECL, unless it is a specialization, in which case the DECL
284 itself is returned. */
286 tree
287 finish_member_template_decl (tree decl)
289 if (decl == error_mark_node)
290 return error_mark_node;
292 gcc_assert (DECL_P (decl));
294 if (TREE_CODE (decl) == TYPE_DECL)
296 tree type;
298 type = TREE_TYPE (decl);
299 if (type == error_mark_node)
300 return error_mark_node;
301 if (MAYBE_CLASS_TYPE_P (type)
302 && CLASSTYPE_TEMPLATE_INFO (type)
303 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
305 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
306 check_member_template (tmpl);
307 return tmpl;
309 return NULL_TREE;
311 else if (TREE_CODE (decl) == FIELD_DECL)
312 error_at (DECL_SOURCE_LOCATION (decl),
313 "data member %qD cannot be a member template", decl);
314 else if (DECL_TEMPLATE_INFO (decl))
316 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
318 check_member_template (DECL_TI_TEMPLATE (decl));
319 return DECL_TI_TEMPLATE (decl);
321 else
322 return NULL_TREE;
324 else
325 error_at (DECL_SOURCE_LOCATION (decl),
326 "invalid member template declaration %qD", decl);
328 return error_mark_node;
331 /* Create a template info node. */
333 tree
334 build_template_info (tree template_decl, tree template_args)
336 tree result = make_node (TEMPLATE_INFO);
337 TI_TEMPLATE (result) = template_decl;
338 TI_ARGS (result) = template_args;
339 return result;
342 /* DECL_TEMPLATE_INFO, if applicable, or NULL_TREE. */
344 static tree
345 decl_template_info (const_tree decl)
347 /* This needs to match template_info_decl_check. */
348 if (DECL_LANG_SPECIFIC (decl))
349 switch (TREE_CODE (decl))
351 case FUNCTION_DECL:
352 if (DECL_THUNK_P (decl))
353 break;
354 gcc_fallthrough ();
355 case VAR_DECL:
356 case FIELD_DECL:
357 case TYPE_DECL:
358 case CONCEPT_DECL:
359 case TEMPLATE_DECL:
360 return DECL_TEMPLATE_INFO (decl);
362 default:
363 break;
365 return NULL_TREE;
368 /* Return the template info node corresponding to T, whatever T is. */
370 tree
371 get_template_info (const_tree t)
373 tree tinfo = NULL_TREE;
375 if (!t || t == error_mark_node)
376 return NULL;
378 if (TREE_CODE (t) == NAMESPACE_DECL
379 || TREE_CODE (t) == PARM_DECL)
380 return NULL;
382 if (DECL_P (t))
383 tinfo = decl_template_info (t);
385 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
386 t = TREE_TYPE (t);
388 if (OVERLOAD_TYPE_P (t))
389 tinfo = TYPE_TEMPLATE_INFO (t);
390 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
391 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
393 return tinfo;
396 /* Returns the template nesting level of the indicated class TYPE.
398 For example, in:
399 template <class T>
400 struct A
402 template <class U>
403 struct B {};
406 A<T>::B<U> has depth two, while A<T> has depth one.
407 Both A<T>::B<int> and A<int>::B<U> have depth one, if
408 they are instantiations, not specializations.
410 This function is guaranteed to return 0 if passed NULL_TREE so
411 that, for example, `template_class_depth (current_class_type)' is
412 always safe. */
415 template_class_depth (tree type)
417 int depth;
419 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
421 tree tinfo = get_template_info (type);
423 if (tinfo
424 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
425 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
426 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
427 ++depth;
429 if (DECL_P (type))
431 if (tree fctx = DECL_FRIEND_CONTEXT (type))
432 type = fctx;
433 else
434 type = CP_DECL_CONTEXT (type);
436 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
437 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
438 else
439 type = CP_TYPE_CONTEXT (type);
442 return depth;
445 /* Return TRUE if NODE instantiates a template that has arguments of
446 its own, be it directly a primary template or indirectly through a
447 partial specializations. */
448 static bool
449 instantiates_primary_template_p (tree node)
451 tree tinfo = get_template_info (node);
452 if (!tinfo)
453 return false;
455 tree tmpl = TI_TEMPLATE (tinfo);
456 if (PRIMARY_TEMPLATE_P (tmpl))
457 return true;
459 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
460 return false;
462 /* So now we know we have a specialization, but it could be a full
463 or a partial specialization. To tell which, compare the depth of
464 its template arguments with those of its context. */
466 tree ctxt = DECL_CONTEXT (tmpl);
467 tree ctinfo = get_template_info (ctxt);
468 if (!ctinfo)
469 return true;
471 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
472 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
475 /* Subroutine of maybe_begin_member_template_processing.
476 Returns true if processing DECL needs us to push template parms. */
478 static bool
479 inline_needs_template_parms (tree decl, bool nsdmi)
481 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
482 return false;
484 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
485 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
488 /* Subroutine of maybe_begin_member_template_processing.
489 Push the template parms in PARMS, starting from LEVELS steps into the
490 chain, and ending at the beginning, since template parms are listed
491 innermost first. */
493 static void
494 push_inline_template_parms_recursive (tree parmlist, int levels)
496 tree parms = TREE_VALUE (parmlist);
497 int i;
499 if (levels > 1)
500 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
502 ++processing_template_decl;
503 current_template_parms
504 = tree_cons (size_int (current_template_depth + 1),
505 parms, current_template_parms);
506 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
507 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
508 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
510 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
511 NULL);
512 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
514 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
516 if (error_operand_p (parm))
517 continue;
519 gcc_assert (DECL_P (parm));
521 switch (TREE_CODE (parm))
523 case TYPE_DECL:
524 case TEMPLATE_DECL:
525 pushdecl (parm);
526 break;
528 case PARM_DECL:
529 /* Push the CONST_DECL. */
530 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
531 break;
533 default:
534 gcc_unreachable ();
539 /* Restore the template parameter context for a member template, a
540 friend template defined in a class definition, or a non-template
541 member of template class. */
543 void
544 maybe_begin_member_template_processing (tree decl)
546 tree parms;
547 int levels = 0;
548 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
550 if (nsdmi)
552 tree ctx = DECL_CONTEXT (decl);
553 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
554 /* Disregard full specializations (c++/60999). */
555 && uses_template_parms (ctx)
556 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
559 if (inline_needs_template_parms (decl, nsdmi))
561 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
562 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
564 if (DECL_TEMPLATE_SPECIALIZATION (decl))
566 --levels;
567 parms = TREE_CHAIN (parms);
570 push_inline_template_parms_recursive (parms, levels);
573 /* Remember how many levels of template parameters we pushed so that
574 we can pop them later. */
575 inline_parm_levels.safe_push (levels);
578 /* Undo the effects of maybe_begin_member_template_processing. */
580 void
581 maybe_end_member_template_processing (void)
583 int i;
584 int last;
586 if (inline_parm_levels.length () == 0)
587 return;
589 last = inline_parm_levels.pop ();
590 for (i = 0; i < last; ++i)
592 --processing_template_decl;
593 current_template_parms = TREE_CHAIN (current_template_parms);
594 poplevel (0, 0, 0);
598 /* Return a new template argument vector which contains all of ARGS,
599 but has as its innermost set of arguments the EXTRA_ARGS. */
601 tree
602 add_to_template_args (tree args, tree extra_args)
604 tree new_args;
605 int extra_depth;
606 int i;
607 int j;
609 if (args == NULL_TREE || extra_args == error_mark_node)
610 return extra_args;
612 extra_depth = TMPL_ARGS_DEPTH (extra_args);
613 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
615 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
616 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
618 for (j = 1; j <= extra_depth; ++j, ++i)
619 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
621 return new_args;
624 /* Like add_to_template_args, but only the outermost ARGS are added to
625 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
626 (EXTRA_ARGS) levels are added. This function is used to combine
627 the template arguments from a partial instantiation with the
628 template arguments used to attain the full instantiation from the
629 partial instantiation.
631 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
633 tree
634 add_outermost_template_args (tree args, tree extra_args)
636 tree new_args;
638 if (!args)
639 return extra_args;
640 if (TREE_CODE (args) == TEMPLATE_DECL)
642 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
643 args = TI_ARGS (ti);
646 /* If there are more levels of EXTRA_ARGS than there are ARGS,
647 something very fishy is going on. */
648 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
650 /* If *all* the new arguments will be the EXTRA_ARGS, just return
651 them. */
652 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
653 return extra_args;
655 /* For the moment, we make ARGS look like it contains fewer levels. */
656 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
658 new_args = add_to_template_args (args, extra_args);
660 /* Now, we restore ARGS to its full dimensions. */
661 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
663 return new_args;
666 /* Return the N levels of innermost template arguments from the ARGS. */
668 tree
669 get_innermost_template_args (tree args, int n)
671 tree new_args;
672 int extra_levels;
673 int i;
675 gcc_assert (n >= 0);
677 /* If N is 1, just return the innermost set of template arguments. */
678 if (n == 1)
679 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
681 /* If we're not removing anything, just return the arguments we were
682 given. */
683 extra_levels = TMPL_ARGS_DEPTH (args) - n;
684 gcc_assert (extra_levels >= 0);
685 if (extra_levels == 0)
686 return args;
688 /* Make a new set of arguments, not containing the outer arguments. */
689 new_args = make_tree_vec (n);
690 for (i = 1; i <= n; ++i)
691 SET_TMPL_ARGS_LEVEL (new_args, i,
692 TMPL_ARGS_LEVEL (args, i + extra_levels));
694 return new_args;
697 /* The inverse of get_innermost_template_args: Return all but the innermost
698 EXTRA_LEVELS levels of template arguments from the ARGS. */
700 static tree
701 strip_innermost_template_args (tree args, int extra_levels)
703 tree new_args;
704 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
705 int i;
707 gcc_assert (n >= 0);
709 /* If N is 1, just return the outermost set of template arguments. */
710 if (n == 1)
711 return TMPL_ARGS_LEVEL (args, 1);
713 /* If we're not removing anything, just return the arguments we were
714 given. */
715 gcc_assert (extra_levels >= 0);
716 if (extra_levels == 0)
717 return args;
719 /* Make a new set of arguments, not containing the inner arguments. */
720 new_args = make_tree_vec (n);
721 for (i = 1; i <= n; ++i)
722 SET_TMPL_ARGS_LEVEL (new_args, i,
723 TMPL_ARGS_LEVEL (args, i));
725 return new_args;
728 /* We've got a template header coming up; push to a new level for storing
729 the parms. */
731 void
732 begin_template_parm_list (void)
734 /* We use a non-tag-transparent scope here, which causes pushtag to
735 put tags in this scope, rather than in the enclosing class or
736 namespace scope. This is the right thing, since we want
737 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
738 global template class, push_template_decl handles putting the
739 TEMPLATE_DECL into top-level scope. For a nested template class,
740 e.g.:
742 template <class T> struct S1 {
743 template <class T> struct S2 {};
746 pushtag contains special code to insert the TEMPLATE_DECL for S2
747 at the right scope. */
748 begin_scope (sk_template_parms, NULL);
749 ++processing_template_decl;
750 ++processing_template_parmlist;
751 note_template_header (0);
753 /* Add a dummy parameter level while we process the parameter list. */
754 current_template_parms
755 = tree_cons (size_int (current_template_depth + 1),
756 make_tree_vec (0),
757 current_template_parms);
760 /* This routine is called when a specialization is declared. If it is
761 invalid to declare a specialization here, an error is reported and
762 false is returned, otherwise this routine will return true. */
764 static bool
765 check_specialization_scope (void)
767 tree scope = current_scope ();
769 /* [temp.expl.spec]
771 An explicit specialization shall be declared in the namespace of
772 which the template is a member, or, for member templates, in the
773 namespace of which the enclosing class or enclosing class
774 template is a member. An explicit specialization of a member
775 function, member class or static data member of a class template
776 shall be declared in the namespace of which the class template
777 is a member. */
778 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
780 error ("explicit specialization in non-namespace scope %qD", scope);
781 return false;
784 /* [temp.expl.spec]
786 In an explicit specialization declaration for a member of a class
787 template or a member template that appears in namespace scope,
788 the member template and some of its enclosing class templates may
789 remain unspecialized, except that the declaration shall not
790 explicitly specialize a class member template if its enclosing
791 class templates are not explicitly specialized as well. */
792 if (current_template_parms)
794 error ("enclosing class templates are not explicitly specialized");
795 return false;
798 return true;
801 /* We've just seen template <>. */
803 bool
804 begin_specialization (void)
806 begin_scope (sk_template_spec, NULL);
807 note_template_header (1);
808 return check_specialization_scope ();
811 /* Called at then end of processing a declaration preceded by
812 template<>. */
814 void
815 end_specialization (void)
817 finish_scope ();
818 reset_specialization ();
821 /* Any template <>'s that we have seen thus far are not referring to a
822 function specialization. */
824 void
825 reset_specialization (void)
827 processing_specialization = 0;
828 template_header_count = 0;
831 /* We've just seen a template header. If SPECIALIZATION is nonzero,
832 it was of the form template <>. */
834 static void
835 note_template_header (int specialization)
837 processing_specialization = specialization;
838 template_header_count++;
841 /* We're beginning an explicit instantiation. */
843 void
844 begin_explicit_instantiation (void)
846 gcc_assert (!processing_explicit_instantiation);
847 processing_explicit_instantiation = true;
851 void
852 end_explicit_instantiation (void)
854 gcc_assert (processing_explicit_instantiation);
855 processing_explicit_instantiation = false;
858 /* An explicit specialization or partial specialization of TMPL is being
859 declared. Check that the namespace in which the specialization is
860 occurring is permissible. Returns false iff it is invalid to
861 specialize TMPL in the current namespace. */
863 static bool
864 check_specialization_namespace (tree tmpl)
866 tree tpl_ns = decl_namespace_context (tmpl);
868 /* [tmpl.expl.spec]
870 An explicit specialization shall be declared in a namespace enclosing the
871 specialized template. An explicit specialization whose declarator-id is
872 not qualified shall be declared in the nearest enclosing namespace of the
873 template, or, if the namespace is inline (7.3.1), any namespace from its
874 enclosing namespace set. */
875 if (current_scope() != DECL_CONTEXT (tmpl)
876 && !at_namespace_scope_p ())
878 error ("specialization of %qD must appear at namespace scope", tmpl);
879 return false;
882 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
883 /* Same or enclosing namespace. */
884 return true;
885 else
887 auto_diagnostic_group d;
888 if (permerror (input_location,
889 "specialization of %qD in different namespace", tmpl))
890 inform (DECL_SOURCE_LOCATION (tmpl),
891 " from definition of %q#D", tmpl);
892 return false;
896 /* SPEC is an explicit instantiation. Check that it is valid to
897 perform this explicit instantiation in the current namespace. */
899 static void
900 check_explicit_instantiation_namespace (tree spec)
902 tree ns;
904 /* DR 275: An explicit instantiation shall appear in an enclosing
905 namespace of its template. */
906 ns = decl_namespace_context (spec);
907 if (!is_nested_namespace (current_namespace, ns))
908 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
909 "(which does not enclose namespace %qD)",
910 spec, current_namespace, ns);
913 /* Returns true if TYPE is a new partial specialization that needs to be
914 set up. This may also modify TYPE to point to the correct (new or
915 existing) constrained partial specialization. */
917 static bool
918 maybe_new_partial_specialization (tree& type)
920 /* An implicit instantiation of an incomplete type implies
921 the definition of a new class template.
923 template<typename T>
924 struct S;
926 template<typename T>
927 struct S<T*>;
929 Here, S<T*> is an implicit instantiation of S whose type
930 is incomplete. */
931 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
932 return true;
934 /* It can also be the case that TYPE is a completed specialization.
935 Continuing the previous example, suppose we also declare:
937 template<typename T>
938 requires Integral<T>
939 struct S<T*>;
941 Here, S<T*> refers to the specialization S<T*> defined
942 above. However, we need to differentiate definitions because
943 we intend to define a new partial specialization. In this case,
944 we rely on the fact that the constraints are different for
945 this declaration than that above.
947 Note that we also get here for injected class names and
948 late-parsed template definitions. We must ensure that we
949 do not create new type declarations for those cases. */
950 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
952 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
953 tree args = CLASSTYPE_TI_ARGS (type);
955 /* If there are no template parameters, this cannot be a new
956 partial template specialization? */
957 if (!current_template_parms)
958 return false;
960 /* The injected-class-name is not a new partial specialization. */
961 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
962 return false;
964 /* If the constraints are not the same as those of the primary
965 then, we can probably create a new specialization. */
966 tree type_constr = current_template_constraints ();
968 if (type == TREE_TYPE (tmpl))
970 tree main_constr = get_constraints (tmpl);
971 if (equivalent_constraints (type_constr, main_constr))
972 return false;
975 /* Also, if there's a pre-existing specialization with matching
976 constraints, then this also isn't new. */
977 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
978 while (specs)
980 tree spec_tmpl = TREE_VALUE (specs);
981 tree spec_args = TREE_PURPOSE (specs);
982 tree spec_constr = get_constraints (spec_tmpl);
983 if (comp_template_args (args, spec_args)
984 && equivalent_constraints (type_constr, spec_constr))
986 type = TREE_TYPE (spec_tmpl);
987 return false;
989 specs = TREE_CHAIN (specs);
992 /* Create a new type node (and corresponding type decl)
993 for the newly declared specialization. */
994 tree t = make_class_type (TREE_CODE (type));
995 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
996 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
998 /* We only need a separate type node for storing the definition of this
999 partial specialization; uses of S<T*> are unconstrained, so all are
1000 equivalent. So keep TYPE_CANONICAL the same. */
1001 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
1003 /* Build the corresponding type decl. */
1004 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
1005 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
1006 DECL_SOURCE_LOCATION (d) = input_location;
1007 TREE_PUBLIC (d) = TREE_PUBLIC (DECL_TEMPLATE_RESULT (tmpl));
1009 set_instantiating_module (d);
1010 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
1012 type = t;
1013 return true;
1016 return false;
1019 /* The TYPE is being declared. If it is a template type, that means it
1020 is a partial specialization. Do appropriate error-checking. */
1022 tree
1023 maybe_process_partial_specialization (tree type)
1025 tree context;
1027 if (type == error_mark_node)
1028 return error_mark_node;
1030 /* A lambda that appears in specialization context is not itself a
1031 specialization. */
1032 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1033 return type;
1035 /* An injected-class-name is not a specialization. */
1036 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1037 return type;
1039 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1041 error ("name of class shadows template template parameter %qD",
1042 TYPE_NAME (type));
1043 return error_mark_node;
1046 context = TYPE_CONTEXT (type);
1048 if (TYPE_ALIAS_P (type))
1050 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1052 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1053 error ("specialization of alias template %qD",
1054 TI_TEMPLATE (tinfo));
1055 else
1056 error ("explicit specialization of non-template %qT", type);
1057 return error_mark_node;
1059 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1061 /* This is for ordinary explicit specialization and partial
1062 specialization of a template class such as:
1064 template <> class C<int>;
1068 template <class T> class C<T*>;
1070 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1072 if (maybe_new_partial_specialization (type))
1074 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1075 && !at_namespace_scope_p ())
1076 return error_mark_node;
1077 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1078 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1079 if (processing_template_decl)
1081 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1082 if (decl == error_mark_node)
1083 return error_mark_node;
1084 return TREE_TYPE (decl);
1087 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1088 error ("specialization of %qT after instantiation", type);
1089 else if (errorcount && !processing_specialization
1090 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1091 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1092 /* Trying to define a specialization either without a template<> header
1093 or in an inappropriate place. We've already given an error, so just
1094 bail now so we don't actually define the specialization. */
1095 return error_mark_node;
1097 else if (CLASS_TYPE_P (type)
1098 && !CLASSTYPE_USE_TEMPLATE (type)
1099 && CLASSTYPE_TEMPLATE_INFO (type)
1100 && context && CLASS_TYPE_P (context)
1101 && CLASSTYPE_TEMPLATE_INFO (context))
1103 /* This is for an explicit specialization of member class
1104 template according to [temp.expl.spec/18]:
1106 template <> template <class U> class C<int>::D;
1108 The context `C<int>' must be an implicit instantiation.
1109 Otherwise this is just a member class template declared
1110 earlier like:
1112 template <> class C<int> { template <class U> class D; };
1113 template <> template <class U> class C<int>::D;
1115 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1116 while in the second case, `C<int>::D' is a primary template
1117 and `C<T>::D' may not exist. */
1119 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1120 && !COMPLETE_TYPE_P (type))
1122 tree t;
1123 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1125 if (current_namespace
1126 != decl_namespace_context (tmpl))
1128 if (permerror (input_location,
1129 "specialization of %qD in different namespace",
1130 type))
1131 inform (DECL_SOURCE_LOCATION (tmpl),
1132 "from definition of %q#D", tmpl);
1135 /* Check for invalid specialization after instantiation:
1137 template <> template <> class C<int>::D<int>;
1138 template <> template <class U> class C<int>::D; */
1140 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1141 t; t = TREE_CHAIN (t))
1143 tree inst = TREE_VALUE (t);
1144 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1145 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1147 /* We already have a full specialization of this partial
1148 instantiation, or a full specialization has been
1149 looked up but not instantiated. Reassign it to the
1150 new member specialization template. */
1151 spec_entry elt;
1152 spec_entry *entry;
1154 elt.tmpl = most_general_template (tmpl);
1155 elt.args = CLASSTYPE_TI_ARGS (inst);
1156 elt.spec = inst;
1158 type_specializations->remove_elt (&elt);
1160 elt.tmpl = tmpl;
1161 CLASSTYPE_TI_ARGS (inst)
1162 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1164 spec_entry **slot
1165 = type_specializations->find_slot (&elt, INSERT);
1166 entry = ggc_alloc<spec_entry> ();
1167 *entry = elt;
1168 *slot = entry;
1170 else
1171 /* But if we've had an implicit instantiation, that's a
1172 problem ([temp.expl.spec]/6). */
1173 error ("specialization %qT after instantiation %qT",
1174 type, inst);
1177 /* Mark TYPE as a specialization. And as a result, we only
1178 have one level of template argument for the innermost
1179 class template. */
1180 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1181 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1182 CLASSTYPE_TI_ARGS (type)
1183 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1186 else if (processing_specialization)
1188 /* Someday C++0x may allow for enum template specialization. */
1189 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1190 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1191 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1192 "of %qD not allowed by ISO C++", type);
1193 else
1195 error ("explicit specialization of non-template %qT", type);
1196 return error_mark_node;
1200 return type;
1203 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1204 gone through coerce_template_parms by now. */
1206 static void
1207 verify_unstripped_args_1 (tree inner)
1209 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1211 tree arg = TREE_VEC_ELT (inner, i);
1212 if (TREE_CODE (arg) == TEMPLATE_DECL)
1213 /* OK */;
1214 else if (TYPE_P (arg))
1215 gcc_assert (strip_typedefs (arg, NULL) == arg);
1216 else if (ARGUMENT_PACK_P (arg))
1217 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1218 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1219 /* Allow typedefs on the type of a non-type argument, since a
1220 parameter can have them. */;
1221 else
1222 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1226 static void
1227 verify_unstripped_args (tree args)
1229 ++processing_template_decl;
1230 if (!any_dependent_template_arguments_p (args))
1231 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1232 --processing_template_decl;
1235 /* Retrieve the specialization (in the sense of [temp.spec] - a
1236 specialization is either an instantiation or an explicit
1237 specialization) of TMPL for the given template ARGS. If there is
1238 no such specialization, return NULL_TREE. The ARGS are a vector of
1239 arguments, or a vector of vectors of arguments, in the case of
1240 templates with more than one level of parameters.
1242 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1243 then we search for a partial specialization matching ARGS. This
1244 parameter is ignored if TMPL is not a class template.
1246 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1247 result is a NONTYPE_ARGUMENT_PACK. */
1249 static tree
1250 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1252 if (tmpl == NULL_TREE)
1253 return NULL_TREE;
1255 if (args == error_mark_node)
1256 return NULL_TREE;
1258 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1259 || TREE_CODE (tmpl) == FIELD_DECL);
1261 /* There should be as many levels of arguments as there are
1262 levels of parameters. */
1263 gcc_assert (TMPL_ARGS_DEPTH (args)
1264 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1265 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1266 : template_class_depth (DECL_CONTEXT (tmpl))));
1268 if (flag_checking)
1269 verify_unstripped_args (args);
1271 /* Lambda functions in templates aren't instantiated normally, but through
1272 tsubst_lambda_expr. */
1273 if (lambda_fn_in_template_p (tmpl))
1274 return NULL_TREE;
1276 spec_entry elt;
1277 elt.tmpl = tmpl;
1278 elt.args = args;
1279 elt.spec = NULL_TREE;
1281 spec_hash_table *specializations;
1282 if (DECL_CLASS_TEMPLATE_P (tmpl))
1283 specializations = type_specializations;
1284 else
1285 specializations = decl_specializations;
1287 if (hash == 0)
1288 hash = spec_hasher::hash (&elt);
1289 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1290 return found->spec;
1292 return NULL_TREE;
1295 /* Like retrieve_specialization, but for local declarations. */
1297 tree
1298 retrieve_local_specialization (tree tmpl)
1300 if (local_specializations == NULL)
1301 return NULL_TREE;
1303 tree *slot = local_specializations->get (tmpl);
1304 return slot ? *slot : NULL_TREE;
1307 /* Returns nonzero iff DECL is a specialization of TMPL. */
1310 is_specialization_of (tree decl, tree tmpl)
1312 tree t;
1314 if (TREE_CODE (decl) == FUNCTION_DECL)
1316 for (t = decl;
1317 t != NULL_TREE;
1318 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1319 if (t == tmpl)
1320 return 1;
1322 else
1324 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1326 for (t = TREE_TYPE (decl);
1327 t != NULL_TREE;
1328 t = CLASSTYPE_USE_TEMPLATE (t)
1329 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1330 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1331 return 1;
1334 return 0;
1337 /* Returns nonzero iff DECL is a specialization of friend declaration
1338 FRIEND_DECL according to [temp.friend]. */
1340 bool
1341 is_specialization_of_friend (tree decl, tree friend_decl)
1343 bool need_template = true;
1344 int template_depth;
1346 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1347 || TREE_CODE (decl) == TYPE_DECL);
1349 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1350 of a template class, we want to check if DECL is a specialization
1351 if this. */
1352 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1353 && DECL_CLASS_SCOPE_P (friend_decl)
1354 && DECL_TEMPLATE_INFO (friend_decl)
1355 && !DECL_USE_TEMPLATE (friend_decl))
1357 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1358 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1359 need_template = false;
1361 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1362 && !PRIMARY_TEMPLATE_P (friend_decl))
1363 need_template = false;
1365 /* There is nothing to do if this is not a template friend. */
1366 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1367 return false;
1369 if (is_specialization_of (decl, friend_decl))
1370 return true;
1372 /* [temp.friend/6]
1373 A member of a class template may be declared to be a friend of a
1374 non-template class. In this case, the corresponding member of
1375 every specialization of the class template is a friend of the
1376 class granting friendship.
1378 For example, given a template friend declaration
1380 template <class T> friend void A<T>::f();
1382 the member function below is considered a friend
1384 template <> struct A<int> {
1385 void f();
1388 For this type of template friend, TEMPLATE_DEPTH below will be
1389 nonzero. To determine if DECL is a friend of FRIEND, we first
1390 check if the enclosing class is a specialization of another. */
1392 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1393 if (template_depth
1394 && DECL_CLASS_SCOPE_P (decl)
1395 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1396 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1398 /* Next, we check the members themselves. In order to handle
1399 a few tricky cases, such as when FRIEND_DECL's are
1401 template <class T> friend void A<T>::g(T t);
1402 template <class T> template <T t> friend void A<T>::h();
1404 and DECL's are
1406 void A<int>::g(int);
1407 template <int> void A<int>::h();
1409 we need to figure out ARGS, the template arguments from
1410 the context of DECL. This is required for template substitution
1411 of `T' in the function parameter of `g' and template parameter
1412 of `h' in the above examples. Here ARGS corresponds to `int'. */
1414 tree context = DECL_CONTEXT (decl);
1415 tree args = NULL_TREE;
1416 int current_depth = 0;
1418 while (current_depth < template_depth)
1420 if (CLASSTYPE_TEMPLATE_INFO (context))
1422 if (current_depth == 0)
1423 args = TYPE_TI_ARGS (context);
1424 else
1425 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1426 current_depth++;
1428 context = TYPE_CONTEXT (context);
1431 if (TREE_CODE (decl) == FUNCTION_DECL)
1433 bool is_template;
1434 tree friend_type;
1435 tree decl_type;
1436 tree friend_args_type;
1437 tree decl_args_type;
1439 /* Make sure that both DECL and FRIEND_DECL are templates or
1440 non-templates. */
1441 is_template = DECL_TEMPLATE_INFO (decl)
1442 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1443 if (need_template ^ is_template)
1444 return false;
1445 else if (is_template)
1447 /* If both are templates, check template parameter list. */
1448 tree friend_parms
1449 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1450 args, tf_none);
1451 if (!comp_template_parms
1452 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1453 friend_parms))
1454 return false;
1456 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1458 else
1459 decl_type = TREE_TYPE (decl);
1461 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1462 tf_none, NULL_TREE);
1463 if (friend_type == error_mark_node)
1464 return false;
1466 /* Check if return types match. */
1467 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1468 return false;
1470 /* Check if function parameter types match, ignoring the
1471 `this' parameter. */
1472 friend_args_type = TYPE_ARG_TYPES (friend_type);
1473 decl_args_type = TYPE_ARG_TYPES (decl_type);
1474 if (DECL_IOBJ_MEMBER_FUNCTION_P (friend_decl))
1475 friend_args_type = TREE_CHAIN (friend_args_type);
1476 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
1477 decl_args_type = TREE_CHAIN (decl_args_type);
1479 return compparms (decl_args_type, friend_args_type);
1481 else
1483 /* DECL is a TYPE_DECL */
1484 bool is_template;
1485 tree decl_type = TREE_TYPE (decl);
1487 /* Make sure that both DECL and FRIEND_DECL are templates or
1488 non-templates. */
1489 is_template
1490 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1491 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1493 if (need_template ^ is_template)
1494 return false;
1495 else if (is_template)
1497 tree friend_parms;
1498 /* If both are templates, check the name of the two
1499 TEMPLATE_DECL's first because is_friend didn't. */
1500 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1501 != DECL_NAME (friend_decl))
1502 return false;
1504 /* Now check template parameter list. */
1505 friend_parms
1506 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1507 args, tf_none);
1508 return comp_template_parms
1509 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1510 friend_parms);
1512 else
1513 return (DECL_NAME (decl)
1514 == DECL_NAME (friend_decl));
1517 return false;
1520 /* Register the specialization SPEC as a specialization of TMPL with
1521 the indicated ARGS. IS_FRIEND indicates whether the specialization
1522 is actually just a friend declaration. ATTRLIST is the list of
1523 attributes that the specialization is declared with or NULL when
1524 it isn't. Returns SPEC, or an equivalent prior declaration, if
1525 available.
1527 We also store instantiations of field packs in the hash table, even
1528 though they are not themselves templates, to make lookup easier. */
1530 static tree
1531 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1532 hashval_t hash)
1534 tree fn;
1536 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1537 || (TREE_CODE (tmpl) == FIELD_DECL
1538 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1540 spec_entry elt;
1541 elt.tmpl = tmpl;
1542 elt.args = args;
1543 elt.spec = spec;
1545 if (hash == 0)
1546 hash = spec_hasher::hash (&elt);
1548 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1549 if (*slot)
1550 fn = (*slot)->spec;
1551 else
1552 fn = NULL_TREE;
1554 /* We can sometimes try to re-register a specialization that we've
1555 already got. In particular, regenerate_decl_from_template calls
1556 duplicate_decls which will update the specialization list. But,
1557 we'll still get called again here anyhow. It's more convenient
1558 to simply allow this than to try to prevent it. */
1559 if (fn == spec)
1560 return spec;
1561 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1563 if (DECL_TEMPLATE_INSTANTIATION (fn))
1565 if (DECL_ODR_USED (fn)
1566 || DECL_EXPLICIT_INSTANTIATION (fn))
1568 error ("specialization of %qD after instantiation",
1569 fn);
1570 return error_mark_node;
1572 else
1574 tree clone;
1575 /* This situation should occur only if the first
1576 specialization is an implicit instantiation, the
1577 second is an explicit specialization, and the
1578 implicit instantiation has not yet been used. That
1579 situation can occur if we have implicitly
1580 instantiated a member function and then specialized
1581 it later.
1583 We can also wind up here if a friend declaration that
1584 looked like an instantiation turns out to be a
1585 specialization:
1587 template <class T> void foo(T);
1588 class S { friend void foo<>(int) };
1589 template <> void foo(int);
1591 We transform the existing DECL in place so that any
1592 pointers to it become pointers to the updated
1593 declaration.
1595 If there was a definition for the template, but not
1596 for the specialization, we want this to look as if
1597 there were no definition, and vice versa. */
1598 DECL_INITIAL (fn) = NULL_TREE;
1599 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1601 /* The call to duplicate_decls will have applied
1602 [temp.expl.spec]:
1604 An explicit specialization of a function template
1605 is inline only if it is explicitly declared to be,
1606 and independently of whether its function template
1609 to the primary function; now copy the inline bits to
1610 the various clones. */
1611 FOR_EACH_CLONE (clone, fn)
1613 DECL_DECLARED_INLINE_P (clone)
1614 = DECL_DECLARED_INLINE_P (fn);
1615 DECL_SOURCE_LOCATION (clone)
1616 = DECL_SOURCE_LOCATION (fn);
1617 DECL_DELETED_FN (clone)
1618 = DECL_DELETED_FN (fn);
1620 check_specialization_namespace (tmpl);
1622 return fn;
1625 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1627 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1628 if (dd == error_mark_node)
1629 /* We've already complained in duplicate_decls. */
1630 return error_mark_node;
1632 if (dd == NULL_TREE && DECL_INITIAL (spec))
1633 /* Dup decl failed, but this is a new definition. Set the
1634 line number so any errors match this new
1635 definition. */
1636 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1638 return fn;
1641 else if (fn)
1642 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1644 /* A specialization must be declared in the same namespace as the
1645 template it is specializing. */
1646 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1647 && !check_specialization_namespace (tmpl))
1648 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1650 spec_entry *entry = ggc_alloc<spec_entry> ();
1651 gcc_assert (tmpl && args && spec);
1652 *entry = elt;
1653 *slot = entry;
1654 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1655 && PRIMARY_TEMPLATE_P (tmpl)
1656 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1657 || variable_template_p (tmpl))
1658 /* If TMPL is a forward declaration of a template function, keep a list
1659 of all specializations in case we need to reassign them to a friend
1660 template later in tsubst_friend_function.
1662 Also keep a list of all variable template instantiations so that
1663 process_partial_specialization can check whether a later partial
1664 specialization would have used it. */
1665 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1666 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1668 return spec;
1671 /* Restricts tree and type comparisons. */
1672 int comparing_specializations;
1673 int comparing_dependent_aliases;
1675 /* Whether we are comparing template arguments during partial ordering
1676 (and therefore want the comparison to look through dependent alias
1677 template specializations). */
1679 static int comparing_for_partial_ordering;
1681 /* Returns true iff two spec_entry nodes are equivalent. */
1683 bool
1684 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1686 int equal;
1688 ++comparing_specializations;
1689 ++comparing_dependent_aliases;
1690 ++processing_template_decl;
1691 equal = (e1->tmpl == e2->tmpl
1692 && comp_template_args (e1->args, e2->args));
1693 if (equal && flag_concepts
1694 /* tmpl could be a FIELD_DECL for a capture pack. */
1695 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1696 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1697 && uses_template_parms (e1->args))
1699 /* Partial specializations of a variable template can be distinguished by
1700 constraints. */
1701 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1702 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1703 equal = equivalent_constraints (c1, c2);
1705 --processing_template_decl;
1706 --comparing_dependent_aliases;
1707 --comparing_specializations;
1709 return equal;
1712 /* Returns a hash for a template TMPL and template arguments ARGS. */
1714 static hashval_t
1715 hash_tmpl_and_args (tree tmpl, tree args)
1717 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1718 return iterative_hash_template_arg (args, val);
1721 hashval_t
1722 spec_hasher::hash (tree tmpl, tree args)
1724 ++comparing_specializations;
1725 hashval_t val = hash_tmpl_and_args (tmpl, args);
1726 --comparing_specializations;
1727 return val;
1730 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1731 ignoring SPEC. */
1733 hashval_t
1734 spec_hasher::hash (spec_entry *e)
1736 return spec_hasher::hash (e->tmpl, e->args);
1739 /* Recursively calculate a hash value for a template argument ARG, for use
1740 in the hash tables of template specializations. We must be
1741 careful to (at least) skip the same entities template_args_equal
1742 does. */
1744 hashval_t
1745 iterative_hash_template_arg (tree arg, hashval_t val)
1747 if (arg == NULL_TREE)
1748 return iterative_hash_object (arg, val);
1750 if (!TYPE_P (arg))
1751 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1752 while (CONVERT_EXPR_P (arg)
1753 || TREE_CODE (arg) == NON_LVALUE_EXPR
1754 || class_nttp_const_wrapper_p (arg))
1755 arg = TREE_OPERAND (arg, 0);
1757 enum tree_code code = TREE_CODE (arg);
1759 val = iterative_hash_object (code, val);
1761 switch (code)
1763 case ARGUMENT_PACK_SELECT:
1764 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1765 preserving it in a hash table, which is bad because it will change
1766 meaning when gen_elem_of_pack_expansion_instantiation changes the
1767 ARGUMENT_PACK_SELECT_INDEX. */
1768 gcc_unreachable ();
1770 case ERROR_MARK:
1771 return val;
1773 case IDENTIFIER_NODE:
1774 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1776 case TREE_VEC:
1777 for (tree elt : tree_vec_range (arg))
1778 val = iterative_hash_template_arg (elt, val);
1779 return val;
1781 case TYPE_PACK_EXPANSION:
1782 case EXPR_PACK_EXPANSION:
1783 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1784 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1786 case TYPE_ARGUMENT_PACK:
1787 case NONTYPE_ARGUMENT_PACK:
1788 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1790 case TREE_LIST:
1791 for (; arg; arg = TREE_CHAIN (arg))
1792 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1793 return val;
1795 case OVERLOAD:
1796 for (lkp_iterator iter (arg); iter; ++iter)
1797 val = iterative_hash_template_arg (*iter, val);
1798 return val;
1800 case CONSTRUCTOR:
1802 iterative_hash_template_arg (TREE_TYPE (arg), val);
1803 for (auto &e: CONSTRUCTOR_ELTS (arg))
1805 val = iterative_hash_template_arg (e.index, val);
1806 val = iterative_hash_template_arg (e.value, val);
1808 return val;
1811 case PARM_DECL:
1812 if (!DECL_ARTIFICIAL (arg))
1814 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1815 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1817 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1819 case TARGET_EXPR:
1820 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1822 case PTRMEM_CST:
1823 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1824 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1826 case TEMPLATE_PARM_INDEX:
1827 val = iterative_hash_template_arg
1828 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1829 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1830 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1832 case TRAIT_EXPR:
1833 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1834 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1835 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1837 case BASELINK:
1838 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1839 val);
1840 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1841 val);
1843 case MODOP_EXPR:
1844 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1845 code = TREE_CODE (TREE_OPERAND (arg, 1));
1846 val = iterative_hash_object (code, val);
1847 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1849 case LAMBDA_EXPR:
1850 /* [temp.over.link] Two lambda-expressions are never considered
1851 equivalent.
1853 So just hash the closure type. */
1854 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1856 case CAST_EXPR:
1857 case IMPLICIT_CONV_EXPR:
1858 case STATIC_CAST_EXPR:
1859 case REINTERPRET_CAST_EXPR:
1860 case CONST_CAST_EXPR:
1861 case DYNAMIC_CAST_EXPR:
1862 case NEW_EXPR:
1863 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1864 /* Now hash operands as usual. */
1865 break;
1867 case CALL_EXPR:
1869 tree fn = CALL_EXPR_FN (arg);
1870 if (tree name = call_expr_dependent_name (arg))
1872 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1873 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1874 fn = name;
1876 val = iterative_hash_template_arg (fn, val);
1877 call_expr_arg_iterator ai;
1878 for (tree x = first_call_expr_arg (arg, &ai); x;
1879 x = next_call_expr_arg (&ai))
1880 val = iterative_hash_template_arg (x, val);
1881 return val;
1884 default:
1885 break;
1888 char tclass = TREE_CODE_CLASS (code);
1889 switch (tclass)
1891 case tcc_type:
1892 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1894 // We want an alias specialization that survived strip_typedefs
1895 // to hash differently from its TYPE_CANONICAL, to avoid hash
1896 // collisions that compare as different in template_args_equal.
1897 // These could be dependent specializations that strip_typedefs
1898 // left alone, or untouched specializations because
1899 // coerce_template_parms returns the unconverted template
1900 // arguments if it sees incomplete argument packs.
1901 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1902 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1905 switch (code)
1907 case DECLTYPE_TYPE:
1908 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1909 break;
1911 case TYPENAME_TYPE:
1912 if (comparing_specializations)
1914 /* Hash the components that are relevant to TYPENAME_TYPE
1915 equivalence as determined by structural_comptypes. We
1916 can only coherently do this when comparing_specializations
1917 is set, because otherwise structural_comptypes tries
1918 resolving TYPENAME_TYPE via the current instantiation. */
1919 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1920 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1921 val = iterative_hash_template_arg (context, val);
1922 val = iterative_hash_template_arg (fullname, val);
1924 break;
1926 default:
1927 if (tree canonical = TYPE_CANONICAL (arg))
1928 val = iterative_hash_object (TYPE_HASH (canonical), val);
1929 else if (tree ti = TYPE_TEMPLATE_INFO (arg))
1931 val = iterative_hash_template_arg (TI_TEMPLATE (ti), val);
1932 val = iterative_hash_template_arg (TI_ARGS (ti), val);
1934 break;
1937 return val;
1939 case tcc_declaration:
1940 case tcc_constant:
1941 return iterative_hash_expr (arg, val);
1943 default:
1944 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1945 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1946 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1947 return val;
1951 /* Unregister the specialization SPEC as a specialization of TMPL.
1952 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1953 if the SPEC was listed as a specialization of TMPL.
1955 Note that SPEC has been ggc_freed, so we can't look inside it. */
1957 bool
1958 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1960 spec_entry *entry;
1961 spec_entry elt;
1963 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1964 elt.args = TI_ARGS (tinfo);
1965 elt.spec = NULL_TREE;
1967 entry = decl_specializations->find (&elt);
1968 if (entry != NULL)
1970 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1971 gcc_assert (new_spec != NULL_TREE);
1972 entry->spec = new_spec;
1973 return 1;
1976 return 0;
1979 /* Like register_specialization, but for local declarations. We are
1980 registering SPEC, an instantiation of TMPL. */
1982 void
1983 register_local_specialization (tree spec, tree tmpl)
1985 gcc_assert (tmpl != spec);
1986 local_specializations->put (tmpl, spec);
1989 /* Registers T as a specialization of itself. This is used to preserve
1990 the references to already-parsed parameters when instantiating
1991 postconditions. */
1993 void
1994 register_local_identity (tree t)
1996 local_specializations->put (t, t);
1999 /* TYPE is a class type. Returns true if TYPE is an explicitly
2000 specialized class. */
2002 bool
2003 explicit_class_specialization_p (tree type)
2005 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2006 return false;
2007 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2010 /* Print the list of functions at FNS, going through all the overloads
2011 for each element of the list. Alternatively, FNS cannot be a
2012 TREE_LIST, in which case it will be printed together with all the
2013 overloads.
2015 MORE and *STR should respectively be FALSE and NULL when the function
2016 is called from the outside. They are used internally on recursive
2017 calls. print_candidates manages the two parameters and leaves NULL
2018 in *STR when it ends. */
2020 static void
2021 print_candidates_1 (tree fns, char **str, bool more = false)
2023 if (TREE_CODE (fns) == TREE_LIST)
2024 for (; fns; fns = TREE_CHAIN (fns))
2025 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2026 else
2027 for (lkp_iterator iter (fns); iter;)
2029 tree cand = *iter;
2030 ++iter;
2032 const char *pfx = *str;
2033 if (!pfx)
2035 if (more || iter)
2036 pfx = _("candidates are:");
2037 else
2038 pfx = _("candidate is:");
2039 *str = get_spaces (pfx);
2041 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2045 /* Print the list of candidate FNS in an error message. FNS can also
2046 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2048 void
2049 print_candidates (tree fns)
2051 char *str = NULL;
2052 print_candidates_1 (fns, &str);
2053 free (str);
2056 /* Get a (possibly) constrained template declaration for the
2057 purpose of ordering candidates. */
2058 static tree
2059 get_template_for_ordering (tree list)
2061 gcc_assert (TREE_CODE (list) == TREE_LIST);
2062 tree f = TREE_VALUE (list);
2063 if (tree ti = DECL_TEMPLATE_INFO (f))
2064 return TI_TEMPLATE (ti);
2065 return f;
2068 /* Among candidates having the same signature, return the
2069 most constrained or NULL_TREE if there is no best candidate.
2070 If the signatures of candidates vary (e.g., template
2071 specialization vs. member function), then there can be no
2072 most constrained.
2074 Note that we don't compare constraints on the functions
2075 themselves, but rather those of their templates. */
2076 static tree
2077 most_constrained_function (tree candidates)
2079 // Try to find the best candidate in a first pass.
2080 tree champ = candidates;
2081 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2083 int winner = more_constrained (get_template_for_ordering (champ),
2084 get_template_for_ordering (c));
2085 if (winner == -1)
2086 champ = c; // The candidate is more constrained
2087 else if (winner == 0)
2088 return NULL_TREE; // Neither is more constrained
2091 // Verify that the champ is better than previous candidates.
2092 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2093 if (!more_constrained (get_template_for_ordering (champ),
2094 get_template_for_ordering (c)))
2095 return NULL_TREE;
2098 return champ;
2102 /* Returns the template (one of the functions given by TEMPLATE_ID)
2103 which can be specialized to match the indicated DECL with the
2104 explicit template args given in TEMPLATE_ID. The DECL may be
2105 NULL_TREE if none is available. In that case, the functions in
2106 TEMPLATE_ID are non-members.
2108 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2109 specialization of a member template.
2111 The TEMPLATE_COUNT is the number of references to qualifying
2112 template classes that appeared in the name of the function. See
2113 check_explicit_specialization for a more accurate description.
2115 TSK indicates what kind of template declaration (if any) is being
2116 declared. TSK_TEMPLATE indicates that the declaration given by
2117 DECL, though a FUNCTION_DECL, has template parameters, and is
2118 therefore a template function.
2120 The template args (those explicitly specified and those deduced)
2121 are output in a newly created vector *TARGS_OUT.
2123 If it is impossible to determine the result, an error message is
2124 issued. The error_mark_node is returned to indicate failure. */
2126 static tree
2127 determine_specialization (tree template_id,
2128 tree decl,
2129 tree* targs_out,
2130 int need_member_template,
2131 int template_count,
2132 tmpl_spec_kind tsk)
2134 tree fns;
2135 tree targs;
2136 tree explicit_targs;
2137 tree candidates = NULL_TREE;
2139 /* A TREE_LIST of templates of which DECL may be a specialization.
2140 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2141 corresponding TREE_PURPOSE is the set of template arguments that,
2142 when used to instantiate the template, would produce a function
2143 with the signature of DECL. */
2144 tree templates = NULL_TREE;
2145 int header_count;
2146 cp_binding_level *b;
2148 *targs_out = NULL_TREE;
2150 if (template_id == error_mark_node || decl == error_mark_node)
2151 return error_mark_node;
2153 /* We shouldn't be specializing a member template of an
2154 unspecialized class template; we already gave an error in
2155 check_specialization_scope, now avoid crashing. */
2156 if (!VAR_P (decl)
2157 && template_count && DECL_CLASS_SCOPE_P (decl)
2158 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2160 gcc_assert (errorcount);
2161 return error_mark_node;
2164 fns = TREE_OPERAND (template_id, 0);
2165 explicit_targs = TREE_OPERAND (template_id, 1);
2167 if (fns == error_mark_node)
2168 return error_mark_node;
2170 /* Check for baselinks. */
2171 if (BASELINK_P (fns))
2172 fns = BASELINK_FUNCTIONS (fns);
2174 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2176 error_at (DECL_SOURCE_LOCATION (decl),
2177 "%qD is not a function template", fns);
2178 return error_mark_node;
2180 else if (VAR_P (decl) && !variable_template_p (fns))
2182 error ("%qD is not a variable template", fns);
2183 return error_mark_node;
2186 /* Count the number of template headers specified for this
2187 specialization. */
2188 header_count = 0;
2189 for (b = current_binding_level;
2190 b->kind == sk_template_parms;
2191 b = b->level_chain)
2192 ++header_count;
2194 tree orig_fns = fns;
2195 bool header_mismatch = false;
2197 if (variable_template_p (fns))
2199 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2200 targs = coerce_template_parms (parms, explicit_targs, fns,
2201 tf_warning_or_error);
2202 if (targs != error_mark_node
2203 && constraints_satisfied_p (fns, targs))
2204 templates = tree_cons (targs, fns, templates);
2206 else for (lkp_iterator iter (fns); iter; ++iter)
2208 tree fn = *iter;
2210 if (TREE_CODE (fn) == TEMPLATE_DECL)
2212 tree decl_arg_types;
2213 tree fn_arg_types;
2215 /* In case of explicit specialization, we need to check if
2216 the number of template headers appearing in the specialization
2217 is correct. This is usually done in check_explicit_specialization,
2218 but the check done there cannot be exhaustive when specializing
2219 member functions. Consider the following code:
2221 template <> void A<int>::f(int);
2222 template <> template <> void A<int>::f(int);
2224 Assuming that A<int> is not itself an explicit specialization
2225 already, the first line specializes "f" which is a non-template
2226 member function, whilst the second line specializes "f" which
2227 is a template member function. So both lines are syntactically
2228 correct, and check_explicit_specialization does not reject
2229 them.
2231 Here, we can do better, as we are matching the specialization
2232 against the declarations. We count the number of template
2233 headers, and we check if they match TEMPLATE_COUNT + 1
2234 (TEMPLATE_COUNT is the number of qualifying template classes,
2235 plus there must be another header for the member template
2236 itself).
2238 Notice that if header_count is zero, this is not a
2239 specialization but rather a template instantiation, so there
2240 is no check we can perform here. */
2241 if (header_count && header_count != template_count + 1)
2243 header_mismatch = true;
2244 continue;
2247 /* Check that the number of template arguments at the
2248 innermost level for DECL is the same as for FN. */
2249 if (current_binding_level->kind == sk_template_parms
2250 && !current_binding_level->explicit_spec_p
2251 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2252 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2253 (current_template_parms))))
2254 continue;
2256 /* DECL might be a specialization of FN. */
2257 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2258 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2260 /* For a non-static member function, we need to make sure
2261 that the const qualification is the same. Since
2262 get_bindings does not try to merge the "this" parameter,
2263 we must do the comparison explicitly. */
2264 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
2266 if (!same_type_p (TREE_VALUE (fn_arg_types),
2267 TREE_VALUE (decl_arg_types)))
2268 continue;
2270 /* And the ref-qualification. */
2271 if (type_memfn_rqual (TREE_TYPE (decl))
2272 != type_memfn_rqual (TREE_TYPE (fn)))
2273 continue;
2276 /* Skip the "this" parameter and, for constructors of
2277 classes with virtual bases, the VTT parameter. A
2278 full specialization of a constructor will have a VTT
2279 parameter, but a template never will. */
2280 decl_arg_types
2281 = skip_artificial_parms_for (decl, decl_arg_types);
2282 fn_arg_types
2283 = skip_artificial_parms_for (fn, fn_arg_types);
2285 /* Function templates cannot be specializations; there are
2286 no partial specializations of functions. Therefore, if
2287 the type of DECL does not match FN, there is no
2288 match.
2290 Note that it should never be the case that we have both
2291 candidates added here, and for regular member functions
2292 below. */
2293 if (tsk == tsk_template)
2295 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2296 current_template_parms))
2297 continue;
2298 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2299 TREE_TYPE (TREE_TYPE (fn))))
2300 continue;
2301 if (!compparms (fn_arg_types, decl_arg_types))
2302 continue;
2304 tree freq = get_constraints (fn);
2305 tree dreq = get_constraints (decl);
2306 if (!freq != !dreq)
2307 continue;
2308 if (freq)
2310 /* C++20 CA104: Substitute directly into the
2311 constraint-expression. */
2312 tree fargs = DECL_TI_ARGS (fn);
2313 tsubst_flags_t complain = tf_none;
2314 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2315 if (!cp_tree_equal (freq, dreq))
2316 continue;
2319 candidates = tree_cons (NULL_TREE, fn, candidates);
2320 continue;
2323 /* See whether this function might be a specialization of this
2324 template. Suppress access control because we might be trying
2325 to make this specialization a friend, and we have already done
2326 access control for the declaration of the specialization. */
2327 push_deferring_access_checks (dk_no_check);
2328 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2329 pop_deferring_access_checks ();
2331 if (!targs)
2332 /* We cannot deduce template arguments that when used to
2333 specialize TMPL will produce DECL. */
2334 continue;
2336 if (uses_template_parms (targs))
2337 /* We deduced something involving 'auto', which isn't a valid
2338 template argument. */
2339 continue;
2341 /* Save this template, and the arguments deduced. */
2342 templates = tree_cons (targs, fn, templates);
2344 else if (need_member_template)
2345 /* FN is an ordinary member function, and we need a
2346 specialization of a member template. */
2348 else if (TREE_CODE (fn) != FUNCTION_DECL)
2349 /* We can get IDENTIFIER_NODEs here in certain erroneous
2350 cases. */
2352 else if (!DECL_FUNCTION_MEMBER_P (fn))
2353 /* This is just an ordinary non-member function. Nothing can
2354 be a specialization of that. */
2356 else if (DECL_ARTIFICIAL (fn))
2357 /* Cannot specialize functions that are created implicitly. */
2359 else
2361 tree decl_arg_types;
2363 /* This is an ordinary member function. However, since
2364 we're here, we can assume its enclosing class is a
2365 template class. For example,
2367 template <typename T> struct S { void f(); };
2368 template <> void S<int>::f() {}
2370 Here, S<int>::f is a non-template, but S<int> is a
2371 template class. If FN has the same type as DECL, we
2372 might be in business. */
2374 if (!DECL_TEMPLATE_INFO (fn))
2375 /* Its enclosing class is an explicit specialization
2376 of a template class. This is not a candidate. */
2377 continue;
2379 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2380 TREE_TYPE (TREE_TYPE (fn))))
2381 /* The return types differ. */
2382 continue;
2384 /* Adjust the type of DECL in case FN is a static member. */
2385 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2386 if (DECL_STATIC_FUNCTION_P (fn)
2387 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2388 decl_arg_types = TREE_CHAIN (decl_arg_types);
2390 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2391 decl_arg_types))
2392 continue;
2394 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2395 && (type_memfn_rqual (TREE_TYPE (decl))
2396 != type_memfn_rqual (TREE_TYPE (fn))))
2397 continue;
2399 // If the deduced arguments do not satisfy the constraints,
2400 // this is not a candidate.
2401 if (flag_concepts && !constraints_satisfied_p (fn))
2402 continue;
2404 // Add the candidate.
2405 candidates = tree_cons (NULL_TREE, fn, candidates);
2409 if (templates && TREE_CHAIN (templates))
2411 /* We have:
2413 [temp.expl.spec]
2415 It is possible for a specialization with a given function
2416 signature to be instantiated from more than one function
2417 template. In such cases, explicit specification of the
2418 template arguments must be used to uniquely identify the
2419 function template specialization being specialized.
2421 Note that here, there's no suggestion that we're supposed to
2422 determine which of the candidate templates is most
2423 specialized. However, we, also have:
2425 [temp.func.order]
2427 Partial ordering of overloaded function template
2428 declarations is used in the following contexts to select
2429 the function template to which a function template
2430 specialization refers:
2432 -- when an explicit specialization refers to a function
2433 template.
2435 So, we do use the partial ordering rules, at least for now.
2436 This extension can only serve to make invalid programs valid,
2437 so it's safe. And, there is strong anecdotal evidence that
2438 the committee intended the partial ordering rules to apply;
2439 the EDG front end has that behavior, and John Spicer claims
2440 that the committee simply forgot to delete the wording in
2441 [temp.expl.spec]. */
2442 tree tmpl = most_specialized_instantiation (templates);
2443 if (tmpl != error_mark_node)
2445 templates = tmpl;
2446 TREE_CHAIN (templates) = NULL_TREE;
2450 // Concepts allows multiple declarations of member functions
2451 // with the same signature. Like above, we need to rely on
2452 // on the partial ordering of those candidates to determine which
2453 // is the best.
2454 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2456 if (tree cand = most_constrained_function (candidates))
2458 candidates = cand;
2459 TREE_CHAIN (cand) = NULL_TREE;
2463 if (templates == NULL_TREE && candidates == NULL_TREE)
2465 error ("template-id %qD for %q+D does not match any template "
2466 "declaration", template_id, decl);
2467 if (header_mismatch)
2468 inform (DECL_SOURCE_LOCATION (decl),
2469 "saw %d %<template<>%>, need %d for "
2470 "specializing a member function template",
2471 header_count, template_count + 1);
2472 print_candidates (orig_fns);
2473 return error_mark_node;
2475 else if ((templates && TREE_CHAIN (templates))
2476 || (candidates && TREE_CHAIN (candidates))
2477 || (templates && candidates))
2479 error ("ambiguous template specialization %qD for %q+D",
2480 template_id, decl);
2481 candidates = chainon (candidates, templates);
2482 print_candidates (candidates);
2483 return error_mark_node;
2486 /* We have one, and exactly one, match. */
2487 if (candidates)
2489 tree fn = TREE_VALUE (candidates);
2490 *targs_out = copy_node (DECL_TI_ARGS (fn));
2492 /* Propagate the candidate's constraints to the declaration. */
2493 if (tsk != tsk_template)
2494 set_constraints (decl, get_constraints (fn));
2496 /* DECL is a re-declaration or partial instantiation of a template
2497 function. */
2498 if (TREE_CODE (fn) == TEMPLATE_DECL)
2499 return fn;
2500 /* It was a specialization of an ordinary member function in a
2501 template class. */
2502 return DECL_TI_TEMPLATE (fn);
2505 /* It was a specialization of a template. */
2506 tree tmpl = TREE_VALUE (templates);
2507 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2509 /* Propagate the template's constraints to the declaration. */
2510 if (tsk != tsk_template)
2511 set_constraints (decl, get_constraints (tmpl));
2513 return tmpl;
2516 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2517 but with the default argument values filled in from those in the
2518 TMPL_TYPES. */
2520 static tree
2521 copy_default_args_to_explicit_spec_1 (tree spec_types,
2522 tree tmpl_types)
2524 tree new_spec_types;
2526 if (!spec_types)
2527 return NULL_TREE;
2529 if (spec_types == void_list_node)
2530 return void_list_node;
2532 /* Substitute into the rest of the list. */
2533 new_spec_types =
2534 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2535 TREE_CHAIN (tmpl_types));
2537 /* Add the default argument for this parameter. */
2538 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2539 TREE_VALUE (spec_types),
2540 new_spec_types);
2543 /* DECL is an explicit specialization. Replicate default arguments
2544 from the template it specializes. (That way, code like:
2546 template <class T> void f(T = 3);
2547 template <> void f(double);
2548 void g () { f (); }
2550 works, as required.) An alternative approach would be to look up
2551 the correct default arguments at the call-site, but this approach
2552 is consistent with how implicit instantiations are handled. */
2554 static void
2555 copy_default_args_to_explicit_spec (tree decl)
2557 tree tmpl;
2558 tree spec_types;
2559 tree tmpl_types;
2560 tree new_spec_types;
2561 tree old_type;
2562 tree new_type;
2563 tree t;
2564 tree object_type = NULL_TREE;
2565 tree in_charge = NULL_TREE;
2566 tree vtt = NULL_TREE;
2568 /* See if there's anything we need to do. */
2569 tmpl = DECL_TI_TEMPLATE (decl);
2570 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2571 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2572 if (TREE_PURPOSE (t))
2573 break;
2574 if (!t)
2575 return;
2577 old_type = TREE_TYPE (decl);
2578 spec_types = TYPE_ARG_TYPES (old_type);
2580 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2582 /* Remove the this pointer, but remember the object's type for
2583 CV quals. */
2584 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2585 spec_types = TREE_CHAIN (spec_types);
2586 tmpl_types = TREE_CHAIN (tmpl_types);
2588 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2590 /* DECL may contain more parameters than TMPL due to the extra
2591 in-charge parameter in constructors and destructors. */
2592 in_charge = spec_types;
2593 spec_types = TREE_CHAIN (spec_types);
2595 if (DECL_HAS_VTT_PARM_P (decl))
2597 vtt = spec_types;
2598 spec_types = TREE_CHAIN (spec_types);
2602 /* Compute the merged default arguments. */
2603 new_spec_types =
2604 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2606 /* Compute the new FUNCTION_TYPE. */
2607 if (object_type)
2609 if (vtt)
2610 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2611 TREE_VALUE (vtt),
2612 new_spec_types);
2614 if (in_charge)
2615 /* Put the in-charge parameter back. */
2616 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2617 TREE_VALUE (in_charge),
2618 new_spec_types);
2620 new_type = build_method_type_directly (object_type,
2621 TREE_TYPE (old_type),
2622 new_spec_types);
2624 else
2625 new_type = build_function_type (TREE_TYPE (old_type),
2626 new_spec_types);
2627 new_type = cp_build_type_attribute_variant (new_type,
2628 TYPE_ATTRIBUTES (old_type));
2629 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2631 TREE_TYPE (decl) = new_type;
2634 /* Return the number of template headers we expect to see for a definition
2635 or specialization of CTYPE or one of its non-template members. */
2638 num_template_headers_for_class (tree ctype)
2640 int num_templates = 0;
2642 while (ctype && CLASS_TYPE_P (ctype))
2644 /* You're supposed to have one `template <...>' for every
2645 template class, but you don't need one for a full
2646 specialization. For example:
2648 template <class T> struct S{};
2649 template <> struct S<int> { void f(); };
2650 void S<int>::f () {}
2652 is correct; there shouldn't be a `template <>' for the
2653 definition of `S<int>::f'. */
2654 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2655 /* If CTYPE does not have template information of any
2656 kind, then it is not a template, nor is it nested
2657 within a template. */
2658 break;
2659 if (explicit_class_specialization_p (ctype))
2660 break;
2661 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2662 ++num_templates;
2664 ctype = TYPE_CONTEXT (ctype);
2667 return num_templates;
2670 /* Do a simple sanity check on the template headers that precede the
2671 variable declaration DECL. */
2673 void
2674 check_template_variable (tree decl)
2676 tree ctx = CP_DECL_CONTEXT (decl);
2677 int wanted = num_template_headers_for_class (ctx);
2678 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2679 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2681 if (cxx_dialect < cxx14)
2682 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2683 "variable templates only available with "
2684 "%<-std=c++14%> or %<-std=gnu++14%>");
2686 // Namespace-scope variable templates should have a template header.
2687 ++wanted;
2689 if (template_header_count > wanted)
2691 auto_diagnostic_group d;
2692 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2693 "too many template headers for %qD "
2694 "(should be %d)",
2695 decl, wanted);
2696 if (warned && CLASS_TYPE_P (ctx)
2697 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2698 inform (DECL_SOURCE_LOCATION (decl),
2699 "members of an explicitly specialized class are defined "
2700 "without a template header");
2704 /* An explicit specialization whose declarator-id or class-head-name is not
2705 qualified shall be declared in the nearest enclosing namespace of the
2706 template, or, if the namespace is inline (7.3.1), any namespace from its
2707 enclosing namespace set.
2709 If the name declared in the explicit instantiation is an unqualified name,
2710 the explicit instantiation shall appear in the namespace where its template
2711 is declared or, if that namespace is inline (7.3.1), any namespace from its
2712 enclosing namespace set. */
2714 void
2715 check_unqualified_spec_or_inst (tree t, location_t loc)
2717 tree tmpl = most_general_template (t);
2718 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2719 && !is_nested_namespace (current_namespace,
2720 CP_DECL_CONTEXT (tmpl), true))
2722 if (processing_specialization)
2723 permerror (loc, "explicit specialization of %qD outside its "
2724 "namespace must use a nested-name-specifier", tmpl);
2725 else if (processing_explicit_instantiation
2726 && cxx_dialect >= cxx11)
2727 /* This was allowed in C++98, so only pedwarn. */
2728 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2729 "outside its namespace must use a nested-name-"
2730 "specifier", tmpl);
2734 /* Warn for a template specialization SPEC that is missing some of a set
2735 of function or type attributes that the template TEMPL is declared with.
2736 ATTRLIST is a list of additional attributes that SPEC should be taken
2737 to ultimately be declared with. */
2739 static void
2740 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2742 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2743 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2745 /* Avoid warning if the difference between the primary and
2746 the specialization is not in one of the attributes below. */
2747 const char* const blacklist[] = {
2748 "alloc_align", "alloc_size", "assume_aligned", "format",
2749 "format_arg", "malloc", "nonnull", NULL
2752 /* Put together a list of the black listed attributes that the primary
2753 template is declared with that the specialization is not, in case
2754 it's not apparent from the most recent declaration of the primary. */
2755 pretty_printer str;
2756 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2757 blacklist, &str);
2759 if (!nattrs)
2760 return;
2762 auto_diagnostic_group d;
2763 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2764 "explicit specialization %q#D may be missing attributes",
2765 spec))
2766 inform (DECL_SOURCE_LOCATION (tmpl),
2767 nattrs > 1
2768 ? G_("missing primary template attributes %s")
2769 : G_("missing primary template attribute %s"),
2770 pp_formatted_text (&str));
2773 /* Check to see if the function just declared, as indicated in
2774 DECLARATOR, and in DECL, is a specialization of a function
2775 template. We may also discover that the declaration is an explicit
2776 instantiation at this point.
2778 Returns DECL, or an equivalent declaration that should be used
2779 instead if all goes well. Issues an error message if something is
2780 amiss. Returns error_mark_node if the error is not easily
2781 recoverable.
2783 FLAGS is a bitmask consisting of the following flags:
2785 2: The function has a definition.
2786 4: The function is a friend.
2788 The TEMPLATE_COUNT is the number of references to qualifying
2789 template classes that appeared in the name of the function. For
2790 example, in
2792 template <class T> struct S { void f(); };
2793 void S<int>::f();
2795 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2796 classes are not counted in the TEMPLATE_COUNT, so that in
2798 template <class T> struct S {};
2799 template <> struct S<int> { void f(); }
2800 template <> void S<int>::f();
2802 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2803 invalid; there should be no template <>.)
2805 If the function is a specialization, it is marked as such via
2806 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2807 is set up correctly, and it is added to the list of specializations
2808 for that template. */
2810 tree
2811 check_explicit_specialization (tree declarator,
2812 tree decl,
2813 int template_count,
2814 int flags,
2815 tree attrlist)
2817 int have_def = flags & 2;
2818 int is_friend = flags & 4;
2819 bool is_concept = flags & 8;
2820 int specialization = 0;
2821 int explicit_instantiation = 0;
2822 int member_specialization = 0;
2823 tree ctype = DECL_CLASS_CONTEXT (decl);
2824 tree dname = DECL_NAME (decl);
2825 tmpl_spec_kind tsk;
2827 if (is_friend)
2829 if (!processing_specialization)
2830 tsk = tsk_none;
2831 else
2832 tsk = tsk_excessive_parms;
2834 else
2835 tsk = current_tmpl_spec_kind (template_count);
2837 switch (tsk)
2839 case tsk_none:
2840 if (processing_specialization && !VAR_P (decl))
2842 specialization = 1;
2843 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2845 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2846 || (DECL_LANG_SPECIFIC (decl)
2847 && DECL_IMPLICIT_INSTANTIATION (decl)))
2849 if (is_friend)
2850 /* This could be something like:
2852 template <class T> void f(T);
2853 class S { friend void f<>(int); } */
2854 specialization = 1;
2855 else
2857 /* This case handles bogus declarations like template <>
2858 template <class T> void f<int>(); */
2860 error_at (cp_expr_loc_or_input_loc (declarator),
2861 "template-id %qE in declaration of primary template",
2862 declarator);
2863 return decl;
2866 break;
2868 case tsk_invalid_member_spec:
2869 /* The error has already been reported in
2870 check_specialization_scope. */
2871 return error_mark_node;
2873 case tsk_invalid_expl_inst:
2874 error ("template parameter list used in explicit instantiation");
2876 /* Fall through. */
2878 case tsk_expl_inst:
2879 if (have_def)
2880 error ("definition provided for explicit instantiation");
2882 explicit_instantiation = 1;
2883 break;
2885 case tsk_excessive_parms:
2886 case tsk_insufficient_parms:
2887 if (tsk == tsk_excessive_parms)
2888 error ("too many template parameter lists in declaration of %qD",
2889 decl);
2890 else if (template_header_count)
2891 error("too few template parameter lists in declaration of %qD", decl);
2892 else
2893 error("explicit specialization of %qD must be introduced by "
2894 "%<template <>%>", decl);
2896 /* Fall through. */
2897 case tsk_expl_spec:
2898 if (is_concept)
2899 error ("explicit specialization declared %<concept%>");
2901 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2902 /* In cases like template<> constexpr bool v = true;
2903 We'll give an error in check_template_variable. */
2904 break;
2906 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2907 if (ctype)
2908 member_specialization = 1;
2909 else
2910 specialization = 1;
2911 break;
2913 case tsk_template:
2914 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2916 /* This case handles bogus declarations like template <>
2917 template <class T> void f<int>(); */
2919 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2920 error_at (cp_expr_loc_or_input_loc (declarator),
2921 "template-id %qE in declaration of primary template",
2922 declarator);
2923 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2925 /* Partial specialization of variable template. */
2926 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2927 specialization = 1;
2928 goto ok;
2930 else if (cxx_dialect < cxx14)
2931 error_at (cp_expr_loc_or_input_loc (declarator),
2932 "non-type partial specialization %qE "
2933 "is not allowed", declarator);
2934 else
2935 error_at (cp_expr_loc_or_input_loc (declarator),
2936 "non-class, non-variable partial specialization %qE "
2937 "is not allowed", declarator);
2938 return decl;
2939 ok:;
2942 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2943 /* This is a specialization of a member template, without
2944 specialization the containing class. Something like:
2946 template <class T> struct S {
2947 template <class U> void f (U);
2949 template <> template <class U> void S<int>::f(U) {}
2951 That's a specialization -- but of the entire template. */
2952 specialization = 1;
2953 break;
2955 default:
2956 gcc_unreachable ();
2959 if ((specialization || member_specialization)
2960 /* This doesn't apply to variable templates. */
2961 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2963 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2964 for (; t; t = TREE_CHAIN (t))
2965 if (TREE_PURPOSE (t))
2967 permerror (input_location,
2968 "default argument specified in explicit specialization");
2969 break;
2973 if (specialization || member_specialization || explicit_instantiation)
2975 tree tmpl = NULL_TREE;
2976 tree targs = NULL_TREE;
2977 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2978 bool found_hidden = false;
2980 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2981 if (!was_template_id)
2983 tree fns;
2985 gcc_assert (identifier_p (declarator));
2986 if (ctype)
2987 fns = dname;
2988 else
2990 /* If there is no class context, the explicit instantiation
2991 must be at namespace scope. */
2992 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2994 /* Find the namespace binding, using the declaration
2995 context. */
2996 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2997 LOOK_want::NORMAL, true);
2998 if (fns == error_mark_node)
3000 /* If lookup fails, look for a friend declaration so we can
3001 give a better diagnostic. */
3002 fns = (lookup_qualified_name
3003 (CP_DECL_CONTEXT (decl), dname,
3004 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3005 /*complain*/true));
3006 found_hidden = true;
3009 if (fns == error_mark_node || !is_overloaded_fn (fns))
3011 error ("%qD is not a template function", dname);
3012 fns = error_mark_node;
3016 declarator = lookup_template_function (fns, NULL_TREE);
3019 if (declarator == error_mark_node)
3020 return error_mark_node;
3022 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3024 if (!explicit_instantiation)
3025 /* A specialization in class scope. This is invalid,
3026 but the error will already have been flagged by
3027 check_specialization_scope. */
3028 return error_mark_node;
3029 else
3031 /* It's not valid to write an explicit instantiation in
3032 class scope, e.g.:
3034 class C { template void f(); }
3036 This case is caught by the parser. However, on
3037 something like:
3039 template class C { void f(); };
3041 (which is invalid) we can get here. The error will be
3042 issued later. */
3046 return decl;
3048 else if (ctype != NULL_TREE
3049 && (identifier_p (TREE_OPERAND (declarator, 0))))
3051 // We'll match variable templates in start_decl.
3052 if (VAR_P (decl))
3053 return decl;
3055 /* Find the list of functions in ctype that have the same
3056 name as the declared function. */
3057 tree name = TREE_OPERAND (declarator, 0);
3059 if (constructor_name_p (name, ctype))
3061 if (DECL_CONSTRUCTOR_P (decl)
3062 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3063 : !CLASSTYPE_DESTRUCTOR (ctype))
3065 /* From [temp.expl.spec]:
3067 If such an explicit specialization for the member
3068 of a class template names an implicitly-declared
3069 special member function (clause _special_), the
3070 program is ill-formed.
3072 Similar language is found in [temp.explicit]. */
3073 error ("specialization of implicitly-declared special member function");
3074 return error_mark_node;
3077 name = DECL_NAME (decl);
3080 /* For a type-conversion operator, We might be looking for
3081 `operator int' which will be a specialization of
3082 `operator T'. Grab all the conversion operators, and
3083 then select from them. */
3084 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3085 ? conv_op_identifier : name);
3087 if (fns == NULL_TREE)
3089 error ("no member function %qD declared in %qT", name, ctype);
3090 return error_mark_node;
3092 else
3093 TREE_OPERAND (declarator, 0) = fns;
3096 /* Figure out what exactly is being specialized at this point.
3097 Note that for an explicit instantiation, even one for a
3098 member function, we cannot tell a priori whether the
3099 instantiation is for a member template, or just a member
3100 function of a template class. Even if a member template is
3101 being instantiated, the member template arguments may be
3102 elided if they can be deduced from the rest of the
3103 declaration. */
3104 tmpl = determine_specialization (declarator, decl,
3105 &targs,
3106 member_specialization,
3107 template_count,
3108 tsk);
3110 if (!tmpl || tmpl == error_mark_node)
3111 /* We couldn't figure out what this declaration was
3112 specializing. */
3113 return error_mark_node;
3114 else
3116 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3118 auto_diagnostic_group d;
3119 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3120 "friend declaration %qD is not visible to "
3121 "explicit specialization", tmpl))
3122 inform (DECL_SOURCE_LOCATION (tmpl),
3123 "friend declaration here");
3126 if (!ctype && !is_friend
3127 && CP_DECL_CONTEXT (decl) == current_namespace)
3128 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3130 tree gen_tmpl = most_general_template (tmpl);
3132 if (explicit_instantiation)
3134 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3135 is done by do_decl_instantiation later. */
3137 int arg_depth = TMPL_ARGS_DEPTH (targs);
3138 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3140 if (arg_depth > parm_depth)
3142 /* If TMPL is not the most general template (for
3143 example, if TMPL is a friend template that is
3144 injected into namespace scope), then there will
3145 be too many levels of TARGS. Remove some of them
3146 here. */
3147 int i;
3148 tree new_targs;
3150 new_targs = make_tree_vec (parm_depth);
3151 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3152 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3153 = TREE_VEC_ELT (targs, i);
3154 targs = new_targs;
3157 return instantiate_template (tmpl, targs, tf_error);
3160 /* If we thought that the DECL was a member function, but it
3161 turns out to be specializing a static member function,
3162 make DECL a static member function as well. */
3163 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3164 && DECL_STATIC_FUNCTION_P (tmpl)
3165 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
3166 revert_static_member_fn (decl);
3168 /* If this is a specialization of a member template of a
3169 template class, we want to return the TEMPLATE_DECL, not
3170 the specialization of it. */
3171 if (tsk == tsk_template && !was_template_id)
3173 tree result = DECL_TEMPLATE_RESULT (tmpl);
3174 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3175 DECL_INITIAL (result) = NULL_TREE;
3176 if (have_def)
3178 tree parm;
3179 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3180 DECL_SOURCE_LOCATION (result)
3181 = DECL_SOURCE_LOCATION (decl);
3182 /* We want to use the argument list specified in the
3183 definition, not in the original declaration. */
3184 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3185 for (parm = DECL_ARGUMENTS (result); parm;
3186 parm = DECL_CHAIN (parm))
3187 DECL_CONTEXT (parm) = result;
3189 decl = register_specialization (tmpl, gen_tmpl, targs,
3190 is_friend, 0);
3191 remove_contract_attributes (result);
3192 return decl;
3195 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3196 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3198 if (was_template_id)
3199 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3201 /* Inherit default function arguments from the template
3202 DECL is specializing. */
3203 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3204 copy_default_args_to_explicit_spec (decl);
3206 /* This specialization has the same protection as the
3207 template it specializes. */
3208 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3209 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3211 /* 7.1.1-1 [dcl.stc]
3213 A storage-class-specifier shall not be specified in an
3214 explicit specialization...
3216 The parser rejects these, so unless action is taken here,
3217 explicit function specializations will always appear with
3218 global linkage.
3220 The action recommended by the C++ CWG in response to C++
3221 defect report 605 is to make the storage class and linkage
3222 of the explicit specialization match the templated function:
3224 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3226 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3228 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3229 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3231 /* A concept cannot be specialized. */
3232 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3234 error ("explicit specialization of function concept %qD",
3235 gen_tmpl);
3236 return error_mark_node;
3239 /* This specialization has the same linkage and visibility as
3240 the function template it specializes. */
3241 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3242 if (! TREE_PUBLIC (decl))
3244 DECL_INTERFACE_KNOWN (decl) = 1;
3245 DECL_NOT_REALLY_EXTERN (decl) = 1;
3247 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3248 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3250 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3251 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3255 /* If DECL is a friend declaration, declared using an
3256 unqualified name, the namespace associated with DECL may
3257 have been set incorrectly. For example, in:
3259 template <typename T> void f(T);
3260 namespace N {
3261 struct S { friend void f<int>(int); }
3264 we will have set the DECL_CONTEXT for the friend
3265 declaration to N, rather than to the global namespace. */
3266 if (DECL_NAMESPACE_SCOPE_P (decl))
3267 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3269 if (is_friend && !have_def)
3270 /* This is not really a declaration of a specialization.
3271 It's just the name of an instantiation. But, it's not
3272 a request for an instantiation, either. */
3273 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3274 else if (TREE_CODE (decl) == FUNCTION_DECL)
3275 /* A specialization is not necessarily COMDAT. */
3276 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3277 && DECL_DECLARED_INLINE_P (decl));
3278 else if (VAR_P (decl))
3279 DECL_COMDAT (decl) = false;
3281 /* If this is a full specialization, register it so that we can find
3282 it again. Partial specializations will be registered in
3283 process_partial_specialization. */
3284 if (!processing_template_decl)
3286 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3288 decl = register_specialization (decl, gen_tmpl, targs,
3289 is_friend, 0);
3292 /* If this is a specialization, splice any contracts that may have
3293 been inherited from the template, removing them. */
3294 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3295 remove_contract_attributes (decl);
3297 /* A 'structor should already have clones. */
3298 gcc_assert (decl == error_mark_node
3299 || variable_template_p (tmpl)
3300 || !(DECL_CONSTRUCTOR_P (decl)
3301 || DECL_DESTRUCTOR_P (decl))
3302 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3306 return decl;
3309 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3310 parameters. These are represented in the same format used for
3311 DECL_TEMPLATE_PARMS. */
3314 comp_template_parms (const_tree parms1, const_tree parms2)
3316 if (parms1 == parms2)
3317 return 1;
3319 tree t1 = TREE_VALUE (parms1);
3320 tree t2 = TREE_VALUE (parms2);
3321 int i;
3323 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3324 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3326 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3327 return 0;
3329 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3331 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3332 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3334 /* If either of the template parameters are invalid, assume
3335 they match for the sake of error recovery. */
3336 if (error_operand_p (parm1) || error_operand_p (parm2))
3337 return 1;
3339 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3340 return 0;
3342 if (TREE_CODE (parm1) == TYPE_DECL
3343 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm1))
3344 == TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm2))))
3345 continue;
3346 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3347 return 0;
3350 return 1;
3353 /* Returns true if two template parameters are declared with
3354 equivalent constraints. */
3356 static bool
3357 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3359 tree req1 = TREE_TYPE (parm1);
3360 tree req2 = TREE_TYPE (parm2);
3361 if (!req1 != !req2)
3362 return false;
3363 if (req1)
3364 return cp_tree_equal (req1, req2);
3365 return true;
3368 /* Returns true when two template parameters are equivalent. */
3370 static bool
3371 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3373 tree decl1 = TREE_VALUE (parm1);
3374 tree decl2 = TREE_VALUE (parm2);
3376 /* If either of the template parameters are invalid, assume
3377 they match for the sake of error recovery. */
3378 if (error_operand_p (decl1) || error_operand_p (decl2))
3379 return true;
3381 /* ... they declare parameters of the same kind. */
3382 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3383 return false;
3385 /* ... one parameter was introduced by a parameter declaration, then
3386 both are. This case arises as a result of eagerly rewriting declarations
3387 during parsing. */
3388 if (DECL_IMPLICIT_TEMPLATE_PARM_P (decl1)
3389 != DECL_IMPLICIT_TEMPLATE_PARM_P (decl2))
3390 return false;
3392 /* ... if either declares a pack, they both do. */
3393 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3394 return false;
3396 if (TREE_CODE (decl1) == PARM_DECL)
3398 /* ... if they declare non-type parameters, the types are equivalent. */
3399 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3400 return false;
3402 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3404 /* ... if they declare template template parameters, their template
3405 parameter lists are equivalent. */
3406 if (!template_heads_equivalent_p (decl1, decl2))
3407 return false;
3410 /* ... if they are declared with a qualified-concept name, they both
3411 are, and those names are equivalent. */
3412 return template_parameter_constraints_equivalent_p (parm1, parm2);
3415 /* Returns true if two template parameters lists are equivalent.
3416 Two template parameter lists are equivalent if they have the
3417 same length and their corresponding parameters are equivalent.
3419 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3420 data structure returned by DECL_TEMPLATE_PARMS.
3422 This is generally the same implementation as comp_template_parms
3423 except that it also the concept names and arguments used to
3424 introduce parameters. */
3426 static bool
3427 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3429 if (parms1 == parms2)
3430 return true;
3432 tree list1 = TREE_VALUE (parms1);
3433 tree list2 = TREE_VALUE (parms2);
3435 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3436 return 0;
3438 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3440 tree parm1 = TREE_VEC_ELT (list1, i);
3441 tree parm2 = TREE_VEC_ELT (list2, i);
3442 if (!template_parameters_equivalent_p (parm1, parm2))
3443 return false;
3446 return true;
3449 /* Return true if the requires-clause of the template parameter lists are
3450 equivalent and false otherwise. */
3451 static bool
3452 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3454 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3455 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3456 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3457 return false;
3458 if (!cp_tree_equal (req1, req2))
3459 return false;
3460 return true;
3463 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3464 Two template heads are equivalent if their template parameter
3465 lists are equivalent and their requires clauses are equivalent.
3467 In pre-C++20, this is equivalent to calling comp_template_parms
3468 for the template parameters of TMPL1 and TMPL2. */
3470 bool
3471 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3473 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3474 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3476 /* Don't change the matching rules for pre-C++20. */
3477 if (cxx_dialect < cxx20)
3478 return comp_template_parms (parms1, parms2);
3480 /* ... have the same number of template parameters, and their
3481 corresponding parameters are equivalent. */
3482 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3483 return false;
3485 /* ... if either has a requires-clause, they both do and their
3486 corresponding constraint-expressions are equivalent. */
3487 return template_requirements_equivalent_p (parms1, parms2);
3490 /* Determine whether PARM is a parameter pack. */
3492 bool
3493 template_parameter_pack_p (const_tree parm)
3495 /* Determine if we have a non-type template parameter pack. */
3496 if (TREE_CODE (parm) == PARM_DECL)
3497 return (DECL_TEMPLATE_PARM_P (parm)
3498 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3499 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3500 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3502 /* If this is a list of template parameters, we could get a
3503 TYPE_DECL or a TEMPLATE_DECL. */
3504 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3505 parm = TREE_TYPE (parm);
3507 /* Otherwise it must be a type template parameter. */
3508 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3509 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3510 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3513 /* Determine if T is a function parameter pack. */
3515 bool
3516 function_parameter_pack_p (const_tree t)
3518 if (t && TREE_CODE (t) == PARM_DECL)
3519 return DECL_PACK_P (t);
3520 return false;
3523 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3524 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3526 tree
3527 get_function_template_decl (const_tree primary_func_tmpl_inst)
3529 if (! primary_func_tmpl_inst
3530 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3531 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3532 return NULL;
3534 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3537 /* Return true iff the function parameter PARAM_DECL was expanded
3538 from the function parameter pack PACK. */
3540 bool
3541 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3543 if (DECL_ARTIFICIAL (param_decl)
3544 || !function_parameter_pack_p (pack))
3545 return false;
3547 /* The parameter pack and its pack arguments have the same
3548 DECL_PARM_INDEX. */
3549 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3552 /* Determine whether ARGS describes a variadic template args list,
3553 i.e., one that is terminated by a template argument pack. */
3555 static bool
3556 template_args_variadic_p (tree args)
3558 int nargs;
3559 tree last_parm;
3561 if (args == NULL_TREE)
3562 return false;
3564 args = INNERMOST_TEMPLATE_ARGS (args);
3565 nargs = TREE_VEC_LENGTH (args);
3567 if (nargs == 0)
3568 return false;
3570 last_parm = TREE_VEC_ELT (args, nargs - 1);
3572 return ARGUMENT_PACK_P (last_parm);
3575 /* Generate a new name for the parameter pack name NAME (an
3576 IDENTIFIER_NODE) that incorporates its */
3578 static tree
3579 make_ith_pack_parameter_name (tree name, int i)
3581 /* Munge the name to include the parameter index. */
3582 #define NUMBUF_LEN 128
3583 char numbuf[NUMBUF_LEN];
3584 char* newname;
3585 int newname_len;
3587 if (name == NULL_TREE)
3588 return name;
3589 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3590 newname_len = IDENTIFIER_LENGTH (name)
3591 + strlen (numbuf) + 2;
3592 newname = (char*)alloca (newname_len);
3593 snprintf (newname, newname_len,
3594 "%s#%i", IDENTIFIER_POINTER (name), i);
3595 return get_identifier (newname);
3598 /* Return true if T is a primary function, class or alias template
3599 specialization, not including the template pattern. */
3601 bool
3602 primary_template_specialization_p (const_tree t)
3604 if (!t)
3605 return false;
3607 if (VAR_OR_FUNCTION_DECL_P (t))
3608 return (DECL_LANG_SPECIFIC (t)
3609 && DECL_USE_TEMPLATE (t)
3610 && DECL_TEMPLATE_INFO (t)
3611 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3612 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3613 return (CLASSTYPE_TEMPLATE_INFO (t)
3614 && CLASSTYPE_USE_TEMPLATE (t)
3615 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3616 else if (alias_template_specialization_p (t, nt_transparent))
3617 return true;
3618 return false;
3621 /* Return true if PARM is a template template parameter. */
3623 bool
3624 template_template_parameter_p (const_tree parm)
3626 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3629 /* Return true iff PARM is a DECL representing a type template
3630 parameter. */
3632 bool
3633 template_type_parameter_p (const_tree parm)
3635 return (parm
3636 && (TREE_CODE (parm) == TYPE_DECL
3637 || TREE_CODE (parm) == TEMPLATE_DECL)
3638 && DECL_TEMPLATE_PARM_P (parm));
3641 /* Return the template parameters of T if T is a
3642 primary template instantiation, NULL otherwise. */
3644 tree
3645 get_primary_template_innermost_parameters (const_tree t)
3647 tree parms = NULL, template_info = NULL;
3649 if ((template_info = get_template_info (t))
3650 && primary_template_specialization_p (t))
3651 parms = INNERMOST_TEMPLATE_PARMS
3652 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3654 return parms;
3657 /* Returns the template arguments of T if T is a template instantiation,
3658 NULL otherwise. */
3660 tree
3661 get_template_innermost_arguments (const_tree t)
3663 tree args = NULL, template_info = NULL;
3665 if ((template_info = get_template_info (t))
3666 && TI_ARGS (template_info))
3667 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3669 return args;
3672 /* Return the argument pack elements of T if T is a template argument pack,
3673 NULL otherwise. */
3675 tree
3676 get_template_argument_pack_elems (const_tree t)
3678 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3679 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3680 return NULL;
3682 return ARGUMENT_PACK_ARGS (t);
3685 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3686 ARGUMENT_PACK_SELECT represents. */
3688 static tree
3689 argument_pack_select_arg (tree t)
3691 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3692 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3694 /* If the selected argument is an expansion E, that most likely means we were
3695 called from gen_elem_of_pack_expansion_instantiation during the
3696 substituting of an argument pack (of which the Ith element is a pack
3697 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3698 In this case, the Ith element resulting from this substituting is going to
3699 be a pack expansion, which pattern is the pattern of E. Let's return the
3700 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3701 resulting pack expansion from it. */
3702 if (PACK_EXPANSION_P (arg))
3704 /* Make sure we aren't throwing away arg info. */
3705 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3706 arg = PACK_EXPANSION_PATTERN (arg);
3709 return arg;
3712 /* Return a modification of ARGS that's suitable for preserving inside a hash
3713 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3714 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3716 static tree
3717 preserve_args (tree args, bool cow_p = true)
3719 if (!args)
3720 return NULL_TREE;
3722 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3724 tree t = TREE_VEC_ELT (args, i);
3725 tree r;
3726 if (!t)
3727 r = NULL_TREE;
3728 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3729 r = argument_pack_select_arg (t);
3730 else if (TREE_CODE (t) == TREE_VEC)
3731 r = preserve_args (t, cow_p);
3732 else
3733 r = t;
3734 if (r != t)
3736 if (cow_p)
3738 args = copy_template_args (args);
3739 cow_p = false;
3741 TREE_VEC_ELT (args, i) = r;
3745 return args;
3748 /* True iff FN is a function representing a built-in variadic parameter
3749 pack. */
3751 bool
3752 builtin_pack_fn_p (tree fn)
3754 if (!fn
3755 || TREE_CODE (fn) != FUNCTION_DECL
3756 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3757 return false;
3759 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3760 return true;
3762 return false;
3765 /* True iff CALL is a call to a function representing a built-in variadic
3766 parameter pack. */
3768 static bool
3769 builtin_pack_call_p (tree call)
3771 if (TREE_CODE (call) != CALL_EXPR)
3772 return false;
3773 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3776 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3778 static tree
3779 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3780 tree in_decl)
3782 tree ohi = CALL_EXPR_ARG (call, 0);
3783 tree hi = tsubst_expr (ohi, args, complain, in_decl);
3785 if (instantiation_dependent_expression_p (hi))
3787 if (hi != ohi)
3789 call = copy_node (call);
3790 CALL_EXPR_ARG (call, 0) = hi;
3792 tree ex = make_pack_expansion (call, complain);
3793 tree vec = make_tree_vec (1);
3794 TREE_VEC_ELT (vec, 0) = ex;
3795 return vec;
3797 else
3799 hi = instantiate_non_dependent_expr (hi, complain);
3800 hi = cxx_constant_value (hi, complain);
3801 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3803 /* Calculate the largest value of len that won't make the size of the vec
3804 overflow an int. The compiler will exceed resource limits long before
3805 this, but it seems a decent place to diagnose. */
3806 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3808 if (len < 0 || len > max)
3810 if ((complain & tf_error)
3811 && hi != error_mark_node)
3812 error ("argument to %<__integer_pack%> must be between 0 and %d",
3813 max);
3814 return error_mark_node;
3817 tree vec = make_tree_vec (len);
3819 for (int i = 0; i < len; ++i)
3820 TREE_VEC_ELT (vec, i) = size_int (i);
3822 return vec;
3826 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3827 CALL. */
3829 static tree
3830 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3831 tree in_decl)
3833 if (!builtin_pack_call_p (call))
3834 return NULL_TREE;
3836 tree fn = CALL_EXPR_FN (call);
3838 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3839 return expand_integer_pack (call, args, complain, in_decl);
3841 return NULL_TREE;
3844 /* Return true if the tree T has the extra args mechanism for
3845 avoiding partial instantiation. */
3847 static bool
3848 has_extra_args_mechanism_p (const_tree t)
3850 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3851 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3852 || (TREE_CODE (t) == IF_STMT
3853 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3856 /* Structure used to track the progress of find_parameter_packs_r. */
3857 struct find_parameter_pack_data
3859 /* TREE_LIST that will contain all of the parameter packs found by
3860 the traversal. */
3861 tree* parameter_packs;
3863 /* Set of AST nodes that have been visited by the traversal. */
3864 hash_set<tree> *visited;
3866 /* True iff we're making a type pack expansion. */
3867 bool type_pack_expansion_p;
3869 /* True iff we found a subtree that has the extra args mechanism. */
3870 bool found_extra_args_tree_p = false;
3873 /* Identifies all of the argument packs that occur in a template
3874 argument and appends them to the TREE_LIST inside DATA, which is a
3875 find_parameter_pack_data structure. This is a subroutine of
3876 make_pack_expansion and uses_parameter_packs. */
3877 static tree
3878 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3880 tree t = *tp;
3881 struct find_parameter_pack_data* ppd =
3882 (struct find_parameter_pack_data*)data;
3883 bool parameter_pack_p = false;
3885 #define WALK_SUBTREE(NODE) \
3886 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3887 ppd, ppd->visited) \
3889 /* Don't look through typedefs; we are interested in whether a
3890 parameter pack is actually written in the expression/type we're
3891 looking at, not the target type. */
3892 if (TYPE_P (t) && typedef_variant_p (t))
3894 /* But do look at arguments for an alias template. */
3895 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3896 cp_walk_tree (&TI_ARGS (tinfo),
3897 &find_parameter_packs_r,
3898 ppd, ppd->visited);
3899 *walk_subtrees = 0;
3900 return NULL_TREE;
3903 /* Identify whether this is a parameter pack or not. */
3904 switch (TREE_CODE (t))
3906 case TEMPLATE_PARM_INDEX:
3907 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3908 parameter_pack_p = true;
3909 break;
3911 case TEMPLATE_TYPE_PARM:
3912 t = TYPE_MAIN_VARIANT (t);
3913 /* FALLTHRU */
3914 case TEMPLATE_TEMPLATE_PARM:
3915 /* If the placeholder appears in the decl-specifier-seq of a function
3916 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3917 is a pack expansion, the invented template parameter is a template
3918 parameter pack. */
3919 if (ppd->type_pack_expansion_p && is_auto (t))
3920 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3921 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3922 parameter_pack_p = true;
3923 break;
3925 case FIELD_DECL:
3926 case PARM_DECL:
3927 if (DECL_PACK_P (t))
3929 /* We don't want to walk into the type of a PARM_DECL,
3930 because we don't want to see the type parameter pack. */
3931 *walk_subtrees = 0;
3932 parameter_pack_p = true;
3934 break;
3936 case VAR_DECL:
3937 if (DECL_PACK_P (t))
3939 /* We don't want to walk into the type of a variadic capture proxy,
3940 because we don't want to see the type parameter pack. */
3941 *walk_subtrees = 0;
3942 parameter_pack_p = true;
3944 else if (variable_template_specialization_p (t))
3946 cp_walk_tree (&DECL_TI_ARGS (t),
3947 find_parameter_packs_r,
3948 ppd, ppd->visited);
3949 *walk_subtrees = 0;
3951 break;
3953 case CALL_EXPR:
3954 if (builtin_pack_call_p (t))
3955 parameter_pack_p = true;
3956 break;
3958 case BASES:
3959 parameter_pack_p = true;
3960 break;
3961 default:
3962 /* Not a parameter pack. */
3963 break;
3966 if (parameter_pack_p)
3968 /* Add this parameter pack to the list. */
3969 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3972 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3973 ppd->found_extra_args_tree_p = true;
3975 if (TYPE_P (t))
3976 cp_walk_tree (&TYPE_CONTEXT (t),
3977 &find_parameter_packs_r, ppd, ppd->visited);
3979 /* This switch statement will return immediately if we don't find a
3980 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3981 switch (TREE_CODE (t))
3983 case BOUND_TEMPLATE_TEMPLATE_PARM:
3984 /* Check the template itself. */
3985 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3986 &find_parameter_packs_r, ppd, ppd->visited);
3987 return NULL_TREE;
3989 case DECL_EXPR:
3991 tree decl = DECL_EXPR_DECL (t);
3992 /* Ignore the declaration of a capture proxy for a parameter pack. */
3993 if (is_capture_proxy (decl))
3994 *walk_subtrees = 0;
3995 if (is_typedef_decl (decl))
3996 /* Since we stop at typedefs above, we need to look through them at
3997 the point of the DECL_EXPR. */
3998 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3999 &find_parameter_packs_r, ppd, ppd->visited);
4000 return NULL_TREE;
4003 case TEMPLATE_DECL:
4004 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4005 return NULL_TREE;
4006 cp_walk_tree (&TREE_TYPE (t),
4007 &find_parameter_packs_r, ppd, ppd->visited);
4008 return NULL_TREE;
4010 case TYPE_PACK_EXPANSION:
4011 case EXPR_PACK_EXPANSION:
4012 *walk_subtrees = 0;
4013 return NULL_TREE;
4015 case INTEGER_TYPE:
4016 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4017 ppd, ppd->visited);
4018 *walk_subtrees = 0;
4019 return NULL_TREE;
4021 case IDENTIFIER_NODE:
4022 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4023 ppd->visited);
4024 *walk_subtrees = 0;
4025 return NULL_TREE;
4027 case LAMBDA_EXPR:
4029 /* Since we defer implicit capture, look in the parms and body. */
4030 tree fn = lambda_function (t);
4031 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4032 ppd->visited);
4033 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4034 ppd->visited);
4035 return NULL_TREE;
4038 case DECLTYPE_TYPE:
4040 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4041 type_pack_expansion_p to false so that any placeholders
4042 within the expression don't get marked as parameter packs. */
4043 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4044 ppd->type_pack_expansion_p = false;
4045 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4046 ppd, ppd->visited);
4047 ppd->type_pack_expansion_p = type_pack_expansion_p;
4048 *walk_subtrees = 0;
4049 return NULL_TREE;
4052 case IF_STMT:
4053 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4054 ppd, ppd->visited);
4055 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4056 ppd, ppd->visited);
4057 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4058 ppd, ppd->visited);
4059 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4060 *walk_subtrees = 0;
4061 return NULL_TREE;
4063 case TAG_DEFN:
4064 t = TREE_TYPE (t);
4065 if (CLASS_TYPE_P (t))
4067 /* Local class, need to look through the whole definition.
4068 TYPE_BINFO might be unset for a partial instantiation. */
4069 if (TYPE_BINFO (t))
4070 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4071 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4072 ppd, ppd->visited);
4074 else
4075 /* Enum, look at the values. */
4076 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4077 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4078 &find_parameter_packs_r,
4079 ppd, ppd->visited);
4080 return NULL_TREE;
4082 case FUNCTION_TYPE:
4083 case METHOD_TYPE:
4084 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4085 break;
4087 default:
4088 return NULL_TREE;
4091 #undef WALK_SUBTREE
4093 return NULL_TREE;
4096 /* Determines if the expression or type T uses any parameter packs. */
4097 tree
4098 uses_parameter_packs (tree t)
4100 tree parameter_packs = NULL_TREE;
4101 struct find_parameter_pack_data ppd;
4102 ppd.parameter_packs = &parameter_packs;
4103 ppd.visited = new hash_set<tree>;
4104 ppd.type_pack_expansion_p = false;
4105 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4106 delete ppd.visited;
4107 return parameter_packs;
4110 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4111 representation a base-class initializer into a parameter pack
4112 expansion. If all goes well, the resulting node will be an
4113 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4114 respectively. */
4115 tree
4116 make_pack_expansion (tree arg, tsubst_flags_t complain)
4118 tree result;
4119 tree parameter_packs = NULL_TREE;
4120 bool for_types = false;
4121 struct find_parameter_pack_data ppd;
4123 if (!arg || arg == error_mark_node)
4124 return arg;
4126 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4128 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4129 class initializer. In this case, the TREE_PURPOSE will be a
4130 _TYPE node (representing the base class expansion we're
4131 initializing) and the TREE_VALUE will be a TREE_LIST
4132 containing the initialization arguments.
4134 The resulting expansion looks somewhat different from most
4135 expansions. Rather than returning just one _EXPANSION, we
4136 return a TREE_LIST whose TREE_PURPOSE is a
4137 TYPE_PACK_EXPANSION containing the bases that will be
4138 initialized. The TREE_VALUE will be identical to the
4139 original TREE_VALUE, which is a list of arguments that will
4140 be passed to each base. We do not introduce any new pack
4141 expansion nodes into the TREE_VALUE (although it is possible
4142 that some already exist), because the TREE_PURPOSE and
4143 TREE_VALUE all need to be expanded together with the same
4144 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4145 resulting TREE_PURPOSE will mention the parameter packs in
4146 both the bases and the arguments to the bases. */
4147 tree purpose;
4148 tree value;
4149 tree parameter_packs = NULL_TREE;
4151 /* Determine which parameter packs will be used by the base
4152 class expansion. */
4153 ppd.visited = new hash_set<tree>;
4154 ppd.parameter_packs = &parameter_packs;
4155 ppd.type_pack_expansion_p = false;
4156 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4157 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4158 &ppd, ppd.visited);
4160 if (parameter_packs == NULL_TREE)
4162 if (complain & tf_error)
4163 error ("base initializer expansion %qT contains no parameter packs",
4164 arg);
4165 delete ppd.visited;
4166 return error_mark_node;
4169 if (TREE_VALUE (arg) != void_type_node)
4171 /* Collect the sets of parameter packs used in each of the
4172 initialization arguments. */
4173 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4175 /* Determine which parameter packs will be expanded in this
4176 argument. */
4177 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4178 &ppd, ppd.visited);
4182 delete ppd.visited;
4184 /* Create the pack expansion type for the base type. */
4185 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4186 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4187 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4188 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4190 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4191 they will rarely be compared to anything. */
4192 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4194 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4197 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4198 for_types = true;
4200 /* Build the PACK_EXPANSION_* node. */
4201 result = for_types
4202 ? cxx_make_type (TYPE_PACK_EXPANSION)
4203 : make_node (EXPR_PACK_EXPANSION);
4204 PACK_EXPANSION_PATTERN (result) = arg;
4205 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4207 /* Propagate type and const-expression information. */
4208 TREE_TYPE (result) = TREE_TYPE (arg);
4209 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4210 /* Mark this read now, since the expansion might be length 0. */
4211 mark_exp_read (arg);
4213 else
4214 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4215 they will rarely be compared to anything. */
4216 SET_TYPE_STRUCTURAL_EQUALITY (result);
4218 /* Determine which parameter packs will be expanded. */
4219 ppd.parameter_packs = &parameter_packs;
4220 ppd.visited = new hash_set<tree>;
4221 ppd.type_pack_expansion_p = TYPE_P (arg);
4222 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4223 delete ppd.visited;
4225 /* Make sure we found some parameter packs. */
4226 if (parameter_packs == NULL_TREE)
4228 if (complain & tf_error)
4230 if (TYPE_P (arg))
4231 error ("expansion pattern %qT contains no parameter packs", arg);
4232 else
4233 error ("expansion pattern %qE contains no parameter packs", arg);
4235 return error_mark_node;
4237 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4239 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4240 if (ppd.found_extra_args_tree_p)
4241 /* If the pattern of this pack expansion contains a subtree that has
4242 the extra args mechanism for avoiding partial instantiation, then
4243 force this pack expansion to also use extra args. Otherwise
4244 partial instantiation of this pack expansion may not lower the
4245 level of some parameter packs within the pattern, which would
4246 confuse tsubst_pack_expansion later (PR101764). */
4247 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4249 return result;
4252 /* Checks T for any "bare" parameter packs, which have not yet been
4253 expanded, and issues an error if any are found. This operation can
4254 only be done on full expressions or types (e.g., an expression
4255 statement, "if" condition, etc.), because we could have expressions like:
4257 foo(f(g(h(args)))...)
4259 where "args" is a parameter pack. check_for_bare_parameter_packs
4260 should not be called for the subexpressions args, h(args),
4261 g(h(args)), or f(g(h(args))), because we would produce erroneous
4262 error messages.
4264 Returns TRUE and emits an error if there were bare parameter packs,
4265 returns FALSE otherwise. */
4266 bool
4267 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4269 tree parameter_packs = NULL_TREE;
4270 struct find_parameter_pack_data ppd;
4272 if (!processing_template_decl || !t || t == error_mark_node)
4273 return false;
4275 if (TREE_CODE (t) == TYPE_DECL)
4276 t = TREE_TYPE (t);
4278 ppd.parameter_packs = &parameter_packs;
4279 ppd.visited = new hash_set<tree>;
4280 ppd.type_pack_expansion_p = false;
4281 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4282 delete ppd.visited;
4284 if (!parameter_packs)
4285 return false;
4287 if (loc == UNKNOWN_LOCATION)
4288 loc = cp_expr_loc_or_input_loc (t);
4290 /* It's OK for a lambda to have an unexpanded parameter pack from the
4291 containing context, but do complain about unexpanded capture packs. */
4292 tree lam = current_lambda_expr ();
4293 if (lam)
4294 lam = TREE_TYPE (lam);
4296 if (lam && lam != current_class_type)
4298 /* We're in a lambda, but it isn't the innermost class.
4299 This should work, but currently doesn't. */
4300 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4301 return true;
4304 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4305 for (; parameter_packs;
4306 parameter_packs = TREE_CHAIN (parameter_packs))
4308 tree pack = TREE_VALUE (parameter_packs);
4309 if (is_capture_proxy (pack)
4310 || (TREE_CODE (pack) == PARM_DECL
4311 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4312 break;
4315 if (parameter_packs)
4317 error_at (loc, "parameter packs not expanded with %<...%>:");
4318 while (parameter_packs)
4320 tree pack = TREE_VALUE (parameter_packs);
4321 tree name = NULL_TREE;
4323 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4324 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4325 name = TYPE_NAME (pack);
4326 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4327 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4328 else if (TREE_CODE (pack) == CALL_EXPR)
4329 name = DECL_NAME (CALL_EXPR_FN (pack));
4330 else
4331 name = DECL_NAME (pack);
4333 if (name)
4334 inform (loc, " %qD", name);
4335 else
4336 inform (loc, " %s", "<anonymous>");
4338 parameter_packs = TREE_CHAIN (parameter_packs);
4341 return true;
4344 return false;
4347 /* Expand any parameter packs that occur in the template arguments in
4348 ARGS. */
4349 tree
4350 expand_template_argument_pack (tree args)
4352 if (args == error_mark_node)
4353 return error_mark_node;
4355 tree result_args = NULL_TREE;
4356 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4357 int num_result_args = -1;
4358 int non_default_args_count = -1;
4360 /* First, determine if we need to expand anything, and the number of
4361 slots we'll need. */
4362 for (in_arg = 0; in_arg < nargs; ++in_arg)
4364 tree arg = TREE_VEC_ELT (args, in_arg);
4365 if (arg == NULL_TREE)
4366 return args;
4367 if (ARGUMENT_PACK_P (arg))
4369 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4370 if (num_result_args < 0)
4371 num_result_args = in_arg + num_packed;
4372 else
4373 num_result_args += num_packed;
4375 else
4377 if (num_result_args >= 0)
4378 num_result_args++;
4382 /* If no expansion is necessary, we're done. */
4383 if (num_result_args < 0)
4384 return args;
4386 /* Expand arguments. */
4387 result_args = make_tree_vec (num_result_args);
4388 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4389 non_default_args_count =
4390 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4391 for (in_arg = 0; in_arg < nargs; ++in_arg)
4393 tree arg = TREE_VEC_ELT (args, in_arg);
4394 if (ARGUMENT_PACK_P (arg))
4396 tree packed = ARGUMENT_PACK_ARGS (arg);
4397 int i, num_packed = TREE_VEC_LENGTH (packed);
4398 for (i = 0; i < num_packed; ++i, ++out_arg)
4399 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4400 if (non_default_args_count > 0)
4401 non_default_args_count += num_packed - 1;
4403 else
4405 TREE_VEC_ELT (result_args, out_arg) = arg;
4406 ++out_arg;
4409 if (non_default_args_count >= 0)
4410 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4411 return result_args;
4414 /* Checks if DECL shadows a template parameter.
4416 [temp.local]: A template-parameter shall not be redeclared within its
4417 scope (including nested scopes).
4419 Emits an error and returns TRUE if the DECL shadows a parameter,
4420 returns FALSE otherwise. */
4422 bool
4423 check_template_shadow (tree decl)
4425 tree olddecl;
4427 /* If we're not in a template, we can't possibly shadow a template
4428 parameter. */
4429 if (!current_template_parms)
4430 return true;
4432 /* Figure out what we're shadowing. */
4433 decl = OVL_FIRST (decl);
4434 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4436 /* If there's no previous binding for this name, we're not shadowing
4437 anything, let alone a template parameter. */
4438 if (!olddecl)
4439 return true;
4441 /* If we're not shadowing a template parameter, we're done. Note
4442 that OLDDECL might be an OVERLOAD (or perhaps even an
4443 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4444 node. */
4445 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4446 return true;
4448 /* We check for decl != olddecl to avoid bogus errors for using a
4449 name inside a class. We check TPFI to avoid duplicate errors for
4450 inline member templates. */
4451 if (decl == olddecl
4452 || (DECL_TEMPLATE_PARM_P (decl)
4453 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4454 return true;
4456 /* Don't complain about the injected class name, as we've already
4457 complained about the class itself. */
4458 if (DECL_SELF_REFERENCE_P (decl))
4459 return false;
4461 if (DECL_TEMPLATE_PARM_P (decl))
4462 error ("declaration of template parameter %q+D shadows "
4463 "template parameter", decl);
4464 else
4465 error ("declaration of %q+#D shadows template parameter", decl);
4466 inform (DECL_SOURCE_LOCATION (olddecl),
4467 "template parameter %qD declared here", olddecl);
4468 return false;
4471 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4472 ORIG_LEVEL, DECL, and TYPE. */
4474 static tree
4475 build_template_parm_index (int index,
4476 int level,
4477 int orig_level,
4478 tree decl,
4479 tree type)
4481 tree t = make_node (TEMPLATE_PARM_INDEX);
4482 TEMPLATE_PARM_IDX (t) = index;
4483 TEMPLATE_PARM_LEVEL (t) = level;
4484 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4485 TEMPLATE_PARM_DECL (t) = decl;
4486 TREE_TYPE (t) = type;
4487 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4488 TREE_READONLY (t) = TREE_READONLY (decl);
4490 return t;
4493 struct ctp_hasher : ggc_ptr_hash<tree_node>
4495 static hashval_t hash (tree t)
4497 ++comparing_specializations;
4498 tree_code code = TREE_CODE (t);
4499 hashval_t val = iterative_hash_object (code, 0);
4500 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4501 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4502 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4503 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4504 --comparing_specializations;
4505 return val;
4508 static bool equal (tree t, tree u)
4510 ++comparing_specializations;
4511 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4512 --comparing_specializations;
4513 return eq;
4517 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4519 /* Find the canonical type parameter for the given template type
4520 parameter. Returns the canonical type parameter, which may be TYPE
4521 if no such parameter existed. */
4523 tree
4524 canonical_type_parameter (tree type)
4526 if (ctp_table == NULL)
4527 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4529 tree& slot = *ctp_table->find_slot (type, INSERT);
4530 if (slot == NULL_TREE)
4531 slot = type;
4532 return slot;
4535 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4536 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4537 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4538 new one is created. */
4540 static tree
4541 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4542 tsubst_flags_t complain)
4544 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4545 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4546 != TEMPLATE_PARM_LEVEL (index) - levels)
4547 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4549 tree orig_decl = TEMPLATE_PARM_DECL (index);
4551 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4552 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4553 type);
4554 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4555 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4556 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4557 DECL_ARTIFICIAL (decl) = 1;
4558 SET_DECL_TEMPLATE_PARM_P (decl);
4560 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4561 TEMPLATE_PARM_LEVEL (index) - levels,
4562 TEMPLATE_PARM_ORIG_LEVEL (index),
4563 decl, type);
4564 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4565 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4566 = TEMPLATE_PARM_PARAMETER_PACK (index);
4568 /* Template template parameters need this. */
4569 tree inner = decl;
4570 if (TREE_CODE (decl) == TEMPLATE_DECL)
4572 inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
4573 TYPE_DECL, DECL_NAME (decl), type);
4574 DECL_TEMPLATE_RESULT (decl) = inner;
4575 DECL_ARTIFICIAL (inner) = true;
4576 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
4577 args, complain);
4578 DECL_TEMPLATE_PARMS (decl) = parms;
4579 tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
4580 DECL_TEMPLATE_INFO (inner)
4581 = build_template_info (DECL_TI_TEMPLATE (orig_inner),
4582 template_parms_to_args (parms));
4585 /* Attach the TPI to the decl. */
4586 if (TREE_CODE (inner) == TYPE_DECL)
4587 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4588 else
4589 DECL_INITIAL (decl) = tpi;
4592 return TEMPLATE_PARM_DESCENDANTS (index);
4595 /* Process information from new template parameter PARM and append it
4596 to the LIST being built. This new parameter is a non-type
4597 parameter iff IS_NON_TYPE is true. This new parameter is a
4598 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4599 is in PARM_LOC. */
4601 tree
4602 process_template_parm (tree list, location_t parm_loc, tree parm,
4603 bool is_non_type, bool is_parameter_pack)
4605 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4606 tree prev = NULL_TREE;
4607 int idx = 0;
4609 if (list)
4611 prev = tree_last (list);
4613 tree p = TREE_VALUE (prev);
4614 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4615 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4616 else if (TREE_CODE (p) == PARM_DECL)
4617 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4619 ++idx;
4622 tree decl = NULL_TREE;
4623 tree defval = TREE_PURPOSE (parm);
4624 tree constr = TREE_TYPE (parm);
4626 if (is_non_type)
4628 parm = TREE_VALUE (parm);
4630 SET_DECL_TEMPLATE_PARM_P (parm);
4632 if (TREE_TYPE (parm) != error_mark_node)
4634 /* [temp.param]
4636 The top-level cv-qualifiers on the template-parameter are
4637 ignored when determining its type. */
4638 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4639 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4640 TREE_TYPE (parm) = error_mark_node;
4641 else if (uses_parameter_packs (TREE_TYPE (parm))
4642 && !is_parameter_pack
4643 /* If we're in a nested template parameter list, the template
4644 template parameter could be a parameter pack. */
4645 && processing_template_parmlist == 1)
4647 /* This template parameter is not a parameter pack, but it
4648 should be. Complain about "bare" parameter packs. */
4649 check_for_bare_parameter_packs (TREE_TYPE (parm));
4651 /* Recover by calling this a parameter pack. */
4652 is_parameter_pack = true;
4656 /* A template parameter is not modifiable. */
4657 TREE_CONSTANT (parm) = 1;
4658 TREE_READONLY (parm) = 1;
4659 decl = build_decl (parm_loc,
4660 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4661 TREE_CONSTANT (decl) = 1;
4662 TREE_READONLY (decl) = 1;
4663 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4664 = build_template_parm_index (idx, current_template_depth,
4665 current_template_depth,
4666 decl, TREE_TYPE (parm));
4668 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4669 = is_parameter_pack;
4671 else
4673 tree t;
4674 parm = TREE_VALUE (TREE_VALUE (parm));
4676 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4678 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4679 /* This is for distinguishing between real templates and template
4680 template parameters */
4681 TREE_TYPE (parm) = t;
4683 /* any_template_parm_r expects to be able to get the targs of a
4684 DECL_TEMPLATE_RESULT. */
4685 tree result = DECL_TEMPLATE_RESULT (parm);
4686 TREE_TYPE (result) = t;
4687 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4688 tree tinfo = build_template_info (parm, args);
4689 retrofit_lang_decl (result);
4690 DECL_TEMPLATE_INFO (result) = tinfo;
4692 decl = parm;
4694 else
4696 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4697 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4698 decl = build_decl (parm_loc,
4699 TYPE_DECL, parm, t);
4702 TYPE_NAME (t) = decl;
4703 TYPE_STUB_DECL (t) = decl;
4704 parm = decl;
4705 TEMPLATE_TYPE_PARM_INDEX (t)
4706 = build_template_parm_index (idx, current_template_depth,
4707 current_template_depth,
4708 decl, TREE_TYPE (parm));
4709 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4710 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4712 DECL_ARTIFICIAL (decl) = 1;
4713 SET_DECL_TEMPLATE_PARM_P (decl);
4715 if (TREE_CODE (parm) == TEMPLATE_DECL
4716 && !uses_outer_template_parms (parm))
4717 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4719 /* Build requirements for the type/template parameter.
4720 This must be done after SET_DECL_TEMPLATE_PARM_P or
4721 process_template_parm could fail. */
4722 tree reqs = finish_shorthand_constraint (parm, constr);
4724 decl = pushdecl (decl);
4725 if (!is_non_type)
4726 parm = decl;
4728 /* Build the parameter node linking the parameter declaration,
4729 its default argument (if any), and its constraints (if any). */
4730 parm = build_tree_list (defval, parm);
4731 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4733 if (prev)
4734 TREE_CHAIN (prev) = parm;
4735 else
4736 list = parm;
4738 return list;
4741 /* The end of a template parameter list has been reached. Process the
4742 tree list into a parameter vector, converting each parameter into a more
4743 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4744 as PARM_DECLs. */
4746 tree
4747 end_template_parm_list (tree parms)
4749 tree saved_parmlist = make_tree_vec (list_length (parms));
4751 /* Pop the dummy parameter level and add the real one. We do not
4752 morph the dummy parameter in place, as it might have been
4753 captured by a (nested) template-template-parm. */
4754 current_template_parms = TREE_CHAIN (current_template_parms);
4756 current_template_parms
4757 = tree_cons (size_int (current_template_depth + 1),
4758 saved_parmlist, current_template_parms);
4760 for (unsigned ix = 0; parms; ix++)
4762 tree parm = parms;
4763 parms = TREE_CHAIN (parms);
4764 TREE_CHAIN (parm) = NULL_TREE;
4766 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4769 --processing_template_parmlist;
4771 return saved_parmlist;
4774 // Explicitly indicate the end of the template parameter list. We assume
4775 // that the current template parameters have been constructed and/or
4776 // managed explicitly, as when creating new template template parameters
4777 // from a shorthand constraint.
4778 void
4779 end_template_parm_list ()
4781 --processing_template_parmlist;
4784 /* end_template_decl is called after a template declaration is seen. */
4786 void
4787 end_template_decl (void)
4789 reset_specialization ();
4791 if (! processing_template_decl)
4792 return;
4794 /* This matches the pushlevel in begin_template_parm_list. */
4795 finish_scope ();
4797 --processing_template_decl;
4798 current_template_parms = TREE_CHAIN (current_template_parms);
4801 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4802 thereof, and converts it into an argument suitable to be passed to
4803 the type substitution functions. Note that if the TREE_LIST contains
4804 an error_mark node, the returned argument is error_mark_node. */
4806 tree
4807 template_parm_to_arg (tree t)
4809 if (!t)
4810 return NULL_TREE;
4812 if (TREE_CODE (t) == TREE_LIST)
4813 t = TREE_VALUE (t);
4815 if (error_operand_p (t))
4816 return error_mark_node;
4818 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4820 if (TREE_CODE (t) == TYPE_DECL
4821 || TREE_CODE (t) == TEMPLATE_DECL)
4822 t = TREE_TYPE (t);
4823 else
4824 t = DECL_INITIAL (t);
4827 gcc_assert (TEMPLATE_PARM_P (t));
4829 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4830 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4832 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4834 /* Turn this argument into a TYPE_ARGUMENT_PACK
4835 with a single element, which expands T. */
4836 tree vec = make_tree_vec (1);
4837 if (CHECKING_P)
4838 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4840 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4842 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4843 ARGUMENT_PACK_ARGS (t) = vec;
4846 else
4848 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4850 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4851 with a single element, which expands T. */
4852 tree vec = make_tree_vec (1);
4853 if (CHECKING_P)
4854 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4856 t = convert_from_reference (t);
4857 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4859 t = make_node (NONTYPE_ARGUMENT_PACK);
4860 ARGUMENT_PACK_ARGS (t) = vec;
4862 else
4863 t = convert_from_reference (t);
4865 return t;
4868 /* If T looks like a generic template argument produced by template_parm_to_arg,
4869 return the corresponding template parameter, otherwise return NULL_TREE. */
4871 static tree
4872 template_arg_to_parm (tree t)
4874 if (t == NULL_TREE)
4875 return NULL_TREE;
4877 if (ARGUMENT_PACK_P (t))
4879 tree args = ARGUMENT_PACK_ARGS (t);
4880 if (TREE_VEC_LENGTH (args) == 1
4881 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4882 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4885 if (REFERENCE_REF_P (t))
4886 t = TREE_OPERAND (t, 0);
4888 if (TEMPLATE_PARM_P (t))
4889 return t;
4890 else
4891 return NULL_TREE;
4894 /* Given a single level of template parameters (a TREE_VEC), return it
4895 as a set of template arguments. */
4897 tree
4898 template_parms_level_to_args (tree parms)
4900 parms = copy_node (parms);
4901 TREE_TYPE (parms) = NULL_TREE;
4902 for (tree& parm : tree_vec_range (parms))
4903 parm = template_parm_to_arg (parm);
4905 if (CHECKING_P)
4906 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4908 return parms;
4911 /* Given a set of template parameters, return them as a set of template
4912 arguments. The template parameters are represented as a TREE_VEC, in
4913 the form documented in cp-tree.h for template arguments. */
4915 tree
4916 template_parms_to_args (tree parms)
4918 tree header;
4919 tree args = NULL_TREE;
4920 int length = TMPL_PARMS_DEPTH (parms);
4921 int l = length;
4923 /* If there is only one level of template parameters, we do not
4924 create a TREE_VEC of TREE_VECs. Instead, we return a single
4925 TREE_VEC containing the arguments. */
4926 if (length > 1)
4927 args = make_tree_vec (length);
4929 for (header = parms; header; header = TREE_CHAIN (header))
4931 tree a = template_parms_level_to_args (TREE_VALUE (header));
4933 if (length > 1)
4934 TREE_VEC_ELT (args, --l) = a;
4935 else
4936 args = a;
4939 return args;
4942 /* Within the declaration of a template, return the currently active
4943 template parameters as an argument TREE_VEC. */
4945 static tree
4946 current_template_args (void)
4948 return template_parms_to_args (current_template_parms);
4951 /* Return the fully generic arguments for of TMPL, i.e. what
4952 current_template_args would be while parsing it. */
4954 tree
4955 generic_targs_for (tree tmpl)
4957 if (tmpl == NULL_TREE)
4958 return NULL_TREE;
4959 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4960 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4961 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4962 template parameter, it has no TEMPLATE_INFO; for a partial
4963 specialization, it has the arguments for the primary template, and we
4964 want the arguments for the partial specialization. */;
4965 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4966 if (tree ti = get_template_info (result))
4967 return TI_ARGS (ti);
4968 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4971 /* Return the template arguments corresponding to the template parameters of
4972 DECL's enclosing scope. When DECL is a member of a partial specialization,
4973 this returns the arguments for the partial specialization as opposed to those
4974 for the primary template, which is the main difference between this function
4975 and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT. */
4977 tree
4978 outer_template_args (const_tree decl)
4980 if (TREE_CODE (decl) == TEMPLATE_DECL)
4981 decl = DECL_TEMPLATE_RESULT (decl);
4982 tree ti = get_template_info (decl);
4983 if (!ti)
4984 return NULL_TREE;
4985 tree args = TI_ARGS (ti);
4986 if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
4987 return args;
4988 if (TMPL_ARGS_DEPTH (args) == 1)
4989 return NULL_TREE;
4990 return strip_innermost_template_args (args, 1);
4993 /* Update the declared TYPE by doing any lookups which were thought to be
4994 dependent, but are not now that we know the SCOPE of the declarator. */
4996 tree
4997 maybe_update_decl_type (tree orig_type, tree scope)
4999 tree type = orig_type;
5001 if (type == NULL_TREE)
5002 return type;
5004 if (TREE_CODE (orig_type) == TYPE_DECL)
5005 type = TREE_TYPE (type);
5007 if (scope && TYPE_P (scope) && dependent_type_p (scope)
5008 && dependent_type_p (type)
5009 /* Don't bother building up the args in this case. */
5010 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5012 /* tsubst in the args corresponding to the template parameters,
5013 including auto if present. Most things will be unchanged, but
5014 make_typename_type and tsubst_qualified_id will resolve
5015 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5016 tree args = current_template_args ();
5017 tree auto_node = type_uses_auto (type);
5018 tree pushed;
5019 if (auto_node)
5021 tree auto_vec = make_tree_vec (1);
5022 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5023 args = add_to_template_args (args, auto_vec);
5025 pushed = push_scope (scope);
5026 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5027 if (pushed)
5028 pop_scope (scope);
5031 if (type == error_mark_node)
5032 return orig_type;
5034 if (TREE_CODE (orig_type) == TYPE_DECL)
5036 if (same_type_p (type, TREE_TYPE (orig_type)))
5037 type = orig_type;
5038 else
5039 type = TYPE_NAME (type);
5041 return type;
5044 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5045 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5046 the new template is a member template. */
5048 static tree
5049 build_template_decl (tree decl, tree parms, bool member_template_p)
5051 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5053 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5054 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5055 DECL_TEMPLATE_PARMS (tmpl) = parms;
5056 DECL_TEMPLATE_RESULT (tmpl) = decl;
5057 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5058 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5059 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5060 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5062 /* Propagate module information from the decl. */
5063 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5065 return tmpl;
5068 struct template_parm_data
5070 /* The level of the template parameters we are currently
5071 processing. */
5072 int level;
5074 /* The index of the specialization argument we are currently
5075 processing. */
5076 int current_arg;
5078 /* An array whose size is the number of template parameters. The
5079 elements are nonzero if the parameter has been used in any one
5080 of the arguments processed so far. */
5081 int* parms;
5083 /* An array whose size is the number of template arguments. The
5084 elements are nonzero if the argument makes use of template
5085 parameters of this level. */
5086 int* arg_uses_template_parms;
5089 /* Subroutine of push_template_decl used to see if each template
5090 parameter in a partial specialization is used in the explicit
5091 argument list. If T is of the LEVEL given in DATA (which is
5092 treated as a template_parm_data*), then DATA->PARMS is marked
5093 appropriately. */
5095 static int
5096 mark_template_parm (tree t, void* data)
5098 int level;
5099 int idx;
5100 struct template_parm_data* tpd = (struct template_parm_data*) data;
5102 template_parm_level_and_index (t, &level, &idx);
5104 if (level == tpd->level)
5106 tpd->parms[idx] = 1;
5107 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5110 /* In C++17 the type of a non-type argument is a deduced context. */
5111 if (cxx_dialect >= cxx17
5112 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5113 for_each_template_parm (TREE_TYPE (t),
5114 &mark_template_parm,
5115 data,
5116 NULL,
5117 /*include_nondeduced_p=*/false);
5119 /* Return zero so that for_each_template_parm will continue the
5120 traversal of the tree; we want to mark *every* template parm. */
5121 return 0;
5124 /* Process the partial specialization DECL. */
5126 static tree
5127 process_partial_specialization (tree decl)
5129 tree type = TREE_TYPE (decl);
5130 tree tinfo = get_template_info (decl);
5131 tree maintmpl = TI_TEMPLATE (tinfo);
5132 tree specargs = TI_ARGS (tinfo);
5133 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5134 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5135 tree inner_parms;
5136 tree inst;
5137 int nargs = TREE_VEC_LENGTH (inner_args);
5138 int ntparms;
5139 int i;
5140 bool did_error_intro = false;
5141 struct template_parm_data tpd;
5142 struct template_parm_data tpd2;
5144 gcc_assert (current_template_parms);
5146 /* A concept cannot be specialized. */
5147 if (flag_concepts && variable_concept_p (maintmpl))
5149 error ("specialization of variable concept %q#D", maintmpl);
5150 return error_mark_node;
5153 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5154 ntparms = TREE_VEC_LENGTH (inner_parms);
5156 /* We check that each of the template parameters given in the
5157 partial specialization is used in the argument list to the
5158 specialization. For example:
5160 template <class T> struct S;
5161 template <class T> struct S<T*>;
5163 The second declaration is OK because `T*' uses the template
5164 parameter T, whereas
5166 template <class T> struct S<int>;
5168 is no good. Even trickier is:
5170 template <class T>
5171 struct S1
5173 template <class U>
5174 struct S2;
5175 template <class U>
5176 struct S2<T>;
5179 The S2<T> declaration is actually invalid; it is a
5180 full-specialization. Of course,
5182 template <class U>
5183 struct S2<T (*)(U)>;
5185 or some such would have been OK. */
5186 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5187 tpd.parms = XALLOCAVEC (int, ntparms);
5188 memset (tpd.parms, 0, sizeof (int) * ntparms);
5190 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5191 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5192 for (i = 0; i < nargs; ++i)
5194 tpd.current_arg = i;
5195 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5196 &mark_template_parm,
5197 &tpd,
5198 NULL,
5199 /*include_nondeduced_p=*/false);
5201 for (i = 0; i < ntparms; ++i)
5202 if (tpd.parms[i] == 0)
5204 /* One of the template parms was not used in a deduced context in the
5205 specialization. */
5206 if (!did_error_intro)
5208 error ("template parameters not deducible in "
5209 "partial specialization:");
5210 did_error_intro = true;
5213 inform (input_location, " %qD",
5214 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5217 if (did_error_intro)
5218 return error_mark_node;
5220 /* [temp.class.spec]
5222 The argument list of the specialization shall not be identical to
5223 the implicit argument list of the primary template. */
5224 tree main_args
5225 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5226 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5227 && (!flag_concepts
5228 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5230 if (!flag_concepts)
5231 error ("partial specialization %q+D does not specialize "
5232 "any template arguments; to define the primary template, "
5233 "remove the template argument list", decl);
5234 else
5235 error ("partial specialization %q+D does not specialize any "
5236 "template arguments and is not more constrained than "
5237 "the primary template; to define the primary template, "
5238 "remove the template argument list", decl);
5239 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5242 /* A partial specialization that replaces multiple parameters of the
5243 primary template with a pack expansion is less specialized for those
5244 parameters. */
5245 if (nargs < DECL_NTPARMS (maintmpl))
5247 error ("partial specialization is not more specialized than the "
5248 "primary template because it replaces multiple parameters "
5249 "with a pack expansion");
5250 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5251 /* Avoid crash in process_partial_specialization. */
5252 return decl;
5255 else if (nargs > DECL_NTPARMS (maintmpl))
5257 error ("too many arguments for partial specialization %qT", type);
5258 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5259 /* Avoid crash below. */
5260 return decl;
5263 /* If we aren't in a dependent class, we can actually try deduction. */
5264 else if (tpd.level == 1
5265 /* FIXME we should be able to handle a partial specialization of a
5266 partial instantiation, but currently we can't (c++/41727). */
5267 && TMPL_ARGS_DEPTH (specargs) == 1
5268 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5270 auto_diagnostic_group d;
5271 if (pedwarn (input_location, 0,
5272 "partial specialization %qD is not more specialized than",
5273 decl))
5274 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5275 maintmpl);
5278 /* [temp.spec.partial]
5280 The type of a template parameter corresponding to a specialized
5281 non-type argument shall not be dependent on a parameter of the
5282 specialization.
5284 Also, we verify that pack expansions only occur at the
5285 end of the argument list. */
5286 tpd2.parms = 0;
5287 for (i = 0; i < nargs; ++i)
5289 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5290 tree arg = TREE_VEC_ELT (inner_args, i);
5291 tree packed_args = NULL_TREE;
5292 int j, len = 1;
5294 if (ARGUMENT_PACK_P (arg))
5296 /* Extract the arguments from the argument pack. We'll be
5297 iterating over these in the following loop. */
5298 packed_args = ARGUMENT_PACK_ARGS (arg);
5299 len = TREE_VEC_LENGTH (packed_args);
5302 for (j = 0; j < len; j++)
5304 if (packed_args)
5305 /* Get the Jth argument in the parameter pack. */
5306 arg = TREE_VEC_ELT (packed_args, j);
5308 if (PACK_EXPANSION_P (arg))
5310 /* Pack expansions must come at the end of the
5311 argument list. */
5312 if ((packed_args && j < len - 1)
5313 || (!packed_args && i < nargs - 1))
5315 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5316 error ("parameter pack argument %qE must be at the "
5317 "end of the template argument list", arg);
5318 else
5319 error ("parameter pack argument %qT must be at the "
5320 "end of the template argument list", arg);
5324 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5325 /* We only care about the pattern. */
5326 arg = PACK_EXPANSION_PATTERN (arg);
5328 if (/* These first two lines are the `non-type' bit. */
5329 !TYPE_P (arg)
5330 && TREE_CODE (arg) != TEMPLATE_DECL
5331 /* This next two lines are the `argument expression is not just a
5332 simple identifier' condition and also the `specialized
5333 non-type argument' bit. */
5334 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5335 && !((REFERENCE_REF_P (arg)
5336 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5337 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5339 /* Look at the corresponding template parameter,
5340 marking which template parameters its type depends
5341 upon. */
5342 tree type = TREE_TYPE (parm);
5344 if (!tpd2.parms)
5346 /* We haven't yet initialized TPD2. Do so now. */
5347 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5348 /* The number of parameters here is the number in the
5349 main template, which, as checked in the assertion
5350 above, is NARGS. */
5351 tpd2.parms = XALLOCAVEC (int, nargs);
5352 tpd2.level =
5353 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5356 /* Mark the template parameters. But this time, we're
5357 looking for the template parameters of the main
5358 template, not in the specialization. */
5359 tpd2.current_arg = i;
5360 tpd2.arg_uses_template_parms[i] = 0;
5361 memset (tpd2.parms, 0, sizeof (int) * nargs);
5362 for_each_template_parm (type,
5363 &mark_template_parm,
5364 &tpd2,
5365 NULL,
5366 /*include_nondeduced_p=*/false);
5368 if (tpd2.arg_uses_template_parms [i])
5370 /* The type depended on some template parameters.
5371 If they are fully specialized in the
5372 specialization, that's OK. */
5373 int j;
5374 int count = 0;
5375 for (j = 0; j < nargs; ++j)
5376 if (tpd2.parms[j] != 0
5377 && tpd.arg_uses_template_parms [j])
5378 ++count;
5379 if (count != 0)
5380 error_n (input_location, count,
5381 "type %qT of template argument %qE depends "
5382 "on a template parameter",
5383 "type %qT of template argument %qE depends "
5384 "on template parameters",
5385 type,
5386 arg);
5392 /* We should only get here once. */
5393 if (TREE_CODE (decl) == TYPE_DECL)
5394 gcc_assert (!COMPLETE_TYPE_P (type));
5396 // Build the template decl.
5397 tree tmpl = build_template_decl (decl, current_template_parms,
5398 DECL_MEMBER_TEMPLATE_P (maintmpl));
5399 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5400 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5401 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5403 /* Give template template parms a DECL_CONTEXT of the template
5404 for which they are a parameter. */
5405 for (i = 0; i < ntparms; ++i)
5407 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5408 if (TREE_CODE (parm) == TEMPLATE_DECL)
5409 DECL_CONTEXT (parm) = tmpl;
5412 if (VAR_P (decl))
5413 /* We didn't register this in check_explicit_specialization so we could
5414 wait until the constraints were set. */
5415 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5416 else
5417 associate_classtype_constraints (type);
5419 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5420 = tree_cons (specargs, tmpl,
5421 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5422 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5423 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5424 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5425 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5427 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5428 inst = TREE_CHAIN (inst))
5430 tree instance = TREE_VALUE (inst);
5431 if (TYPE_P (instance)
5432 ? (COMPLETE_TYPE_P (instance)
5433 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5434 : DECL_TEMPLATE_INSTANTIATION (instance))
5436 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5437 /*rechecking=*/true);
5438 tree inst_decl = (DECL_P (instance)
5439 ? instance : TYPE_NAME (instance));
5440 if (!partial_ti)
5441 /* OK */;
5442 else if (partial_ti == error_mark_node)
5443 permerror (input_location,
5444 "declaration of %qD ambiguates earlier template "
5445 "instantiation for %qD", decl, inst_decl);
5446 else if (TI_TEMPLATE (partial_ti) == tmpl)
5447 permerror (input_location,
5448 "partial specialization of %qD after instantiation "
5449 "of %qD", decl, inst_decl);
5453 return decl;
5456 /* PARM is a template parameter of some form; return the corresponding
5457 TEMPLATE_PARM_INDEX. */
5459 static tree
5460 get_template_parm_index (tree parm)
5462 if (TREE_CODE (parm) == PARM_DECL
5463 || TREE_CODE (parm) == CONST_DECL)
5464 parm = DECL_INITIAL (parm);
5465 else if (TREE_CODE (parm) == TYPE_DECL
5466 || TREE_CODE (parm) == TEMPLATE_DECL)
5467 parm = TREE_TYPE (parm);
5468 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5469 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5470 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5471 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5472 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5473 return parm;
5476 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5477 parameter packs used by the template parameter PARM. */
5479 static void
5480 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5482 /* A type parm can't refer to another parm. */
5483 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5484 return;
5485 else if (TREE_CODE (parm) == PARM_DECL)
5487 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5488 ppd, ppd->visited);
5489 return;
5492 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5494 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5495 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5497 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5498 if (template_parameter_pack_p (p))
5499 /* Any packs in the type are expanded by this parameter. */;
5500 else
5501 fixed_parameter_pack_p_1 (p, ppd);
5505 /* PARM is a template parameter pack. Return any parameter packs used in
5506 its type or the type of any of its template parameters. If there are
5507 any such packs, it will be instantiated into a fixed template parameter
5508 list by partial instantiation rather than be fully deduced. */
5510 tree
5511 fixed_parameter_pack_p (tree parm)
5513 /* This can only be true in a member template. */
5514 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5515 return NULL_TREE;
5516 /* This can only be true for a parameter pack. */
5517 if (!template_parameter_pack_p (parm))
5518 return NULL_TREE;
5519 /* A type parm can't refer to another parm. */
5520 if (TREE_CODE (parm) == TYPE_DECL)
5521 return NULL_TREE;
5523 tree parameter_packs = NULL_TREE;
5524 struct find_parameter_pack_data ppd;
5525 ppd.parameter_packs = &parameter_packs;
5526 ppd.visited = new hash_set<tree>;
5527 ppd.type_pack_expansion_p = false;
5529 fixed_parameter_pack_p_1 (parm, &ppd);
5531 delete ppd.visited;
5532 return parameter_packs;
5535 /* Check that a template declaration's use of default arguments and
5536 parameter packs is not invalid. Here, PARMS are the template
5537 parameters. IS_PRIMARY is true if DECL is the thing declared by
5538 a primary template. IS_PARTIAL is true if DECL is a partial
5539 specialization.
5541 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5542 function template declaration or a friend class template
5543 declaration. In the function case, 1 indicates a declaration, 2
5544 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5545 emitted for extraneous default arguments.
5547 Returns TRUE if there were no errors found, FALSE otherwise. */
5549 bool
5550 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5551 bool is_partial, int is_friend_decl)
5553 const char *msg;
5554 int last_level_to_check;
5555 tree parm_level;
5556 bool no_errors = true;
5558 /* [temp.param]
5560 A default template-argument shall not be specified in a
5561 function template declaration or a function template definition, nor
5562 in the template-parameter-list of the definition of a member of a
5563 class template. */
5565 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5566 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5567 /* You can't have a function template declaration in a local
5568 scope, nor you can you define a member of a class template in a
5569 local scope. */
5570 return true;
5572 if ((TREE_CODE (decl) == TYPE_DECL
5573 && TREE_TYPE (decl)
5574 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5575 || (TREE_CODE (decl) == FUNCTION_DECL
5576 && LAMBDA_FUNCTION_P (decl)))
5577 /* A lambda doesn't have an explicit declaration; don't complain
5578 about the parms of the enclosing class. */
5579 return true;
5581 if (current_class_type
5582 && !TYPE_BEING_DEFINED (current_class_type)
5583 && DECL_LANG_SPECIFIC (decl)
5584 && DECL_DECLARES_FUNCTION_P (decl)
5585 /* If this is either a friend defined in the scope of the class
5586 or a member function. */
5587 && (DECL_FUNCTION_MEMBER_P (decl)
5588 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5589 : DECL_FRIEND_CONTEXT (decl)
5590 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5591 : false)
5592 /* And, if it was a member function, it really was defined in
5593 the scope of the class. */
5594 && (!DECL_FUNCTION_MEMBER_P (decl)
5595 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5596 /* We already checked these parameters when the template was
5597 declared, so there's no need to do it again now. This function
5598 was defined in class scope, but we're processing its body now
5599 that the class is complete. */
5600 return true;
5602 /* Core issue 226 (C++0x only): the following only applies to class
5603 templates. */
5604 if (is_primary
5605 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5607 /* [temp.param]
5609 If a template-parameter has a default template-argument, all
5610 subsequent template-parameters shall have a default
5611 template-argument supplied. */
5612 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5614 tree inner_parms = TREE_VALUE (parm_level);
5615 int ntparms = TREE_VEC_LENGTH (inner_parms);
5616 int seen_def_arg_p = 0;
5617 int i;
5619 for (i = 0; i < ntparms; ++i)
5621 tree parm = TREE_VEC_ELT (inner_parms, i);
5623 if (parm == error_mark_node)
5624 continue;
5626 if (TREE_PURPOSE (parm))
5627 seen_def_arg_p = 1;
5628 else if (seen_def_arg_p
5629 && !template_parameter_pack_p (TREE_VALUE (parm)))
5631 error ("no default argument for %qD", TREE_VALUE (parm));
5632 /* For better subsequent error-recovery, we indicate that
5633 there should have been a default argument. */
5634 TREE_PURPOSE (parm) = error_mark_node;
5635 no_errors = false;
5637 else if (!is_partial
5638 && !is_friend_decl
5639 /* Don't complain about an enclosing partial
5640 specialization. */
5641 && parm_level == parms
5642 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5643 && i < ntparms - 1
5644 && template_parameter_pack_p (TREE_VALUE (parm))
5645 /* A fixed parameter pack will be partially
5646 instantiated into a fixed length list. */
5647 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5649 /* A primary class template, primary variable template
5650 (DR 2032), or alias template can only have one
5651 parameter pack, at the end of the template
5652 parameter list. */
5654 error ("parameter pack %q+D must be at the end of the"
5655 " template parameter list", TREE_VALUE (parm));
5657 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5658 = error_mark_node;
5659 no_errors = false;
5665 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5666 || is_partial
5667 || !is_primary
5668 || is_friend_decl)
5669 /* For an ordinary class template, default template arguments are
5670 allowed at the innermost level, e.g.:
5671 template <class T = int>
5672 struct S {};
5673 but, in a partial specialization, they're not allowed even
5674 there, as we have in [temp.class.spec]:
5676 The template parameter list of a specialization shall not
5677 contain default template argument values.
5679 So, for a partial specialization, or for a function template
5680 (in C++98/C++03), we look at all of them. */
5682 else
5683 /* But, for a primary class template that is not a partial
5684 specialization we look at all template parameters except the
5685 innermost ones. */
5686 parms = TREE_CHAIN (parms);
5688 /* Figure out what error message to issue. */
5689 if (is_friend_decl == 2)
5690 msg = G_("default template arguments may not be used in function template "
5691 "friend re-declaration");
5692 else if (is_friend_decl)
5693 msg = G_("default template arguments may not be used in template "
5694 "friend declarations");
5695 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5696 msg = G_("default template arguments may not be used in function templates "
5697 "without %<-std=c++11%> or %<-std=gnu++11%>");
5698 else if (is_partial)
5699 msg = G_("default template arguments may not be used in "
5700 "partial specializations");
5701 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5702 msg = G_("default argument for template parameter for class enclosing %qD");
5703 else
5704 /* Per [temp.param]/9, "A default template-argument shall not be
5705 specified in the template-parameter-lists of the definition of
5706 a member of a class template that appears outside of the member's
5707 class.", thus if we aren't handling a member of a class template
5708 there is no need to examine the parameters. */
5709 return true;
5711 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5712 /* If we're inside a class definition, there's no need to
5713 examine the parameters to the class itself. On the one
5714 hand, they will be checked when the class is defined, and,
5715 on the other, default arguments are valid in things like:
5716 template <class T = double>
5717 struct S { template <class U> void f(U); };
5718 Here the default argument for `S' has no bearing on the
5719 declaration of `f'. */
5720 last_level_to_check = template_class_depth (current_class_type) + 1;
5721 else
5722 /* Check everything. */
5723 last_level_to_check = 0;
5725 for (parm_level = parms;
5726 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5727 parm_level = TREE_CHAIN (parm_level))
5729 tree inner_parms = TREE_VALUE (parm_level);
5730 int i;
5731 int ntparms;
5733 ntparms = TREE_VEC_LENGTH (inner_parms);
5734 for (i = 0; i < ntparms; ++i)
5736 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5737 continue;
5739 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5741 if (msg)
5743 no_errors = false;
5744 if (is_friend_decl == 2)
5745 return no_errors;
5747 error (msg, decl);
5748 msg = 0;
5751 /* Clear out the default argument so that we are not
5752 confused later. */
5753 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5757 /* At this point, if we're still interested in issuing messages,
5758 they must apply to classes surrounding the object declared. */
5759 if (msg)
5760 msg = G_("default argument for template parameter for class "
5761 "enclosing %qD");
5764 return no_errors;
5767 /* Worker for push_template_decl_real, called via
5768 for_each_template_parm. DATA is really an int, indicating the
5769 level of the parameters we are interested in. If T is a template
5770 parameter of that level, return nonzero. */
5772 static int
5773 template_parm_this_level_p (tree t, void* data)
5775 int this_level = *(int *)data;
5776 int level;
5778 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5779 level = TEMPLATE_PARM_LEVEL (t);
5780 else
5781 level = TEMPLATE_TYPE_LEVEL (t);
5782 return level == this_level;
5785 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5786 DATA is really an int, indicating the innermost outer level of parameters.
5787 If T is a template parameter of that level or further out, return
5788 nonzero. */
5790 static int
5791 template_parm_outer_level (tree t, void *data)
5793 int this_level = *(int *)data;
5794 int level;
5796 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5797 level = TEMPLATE_PARM_LEVEL (t);
5798 else
5799 level = TEMPLATE_TYPE_LEVEL (t);
5800 return level <= this_level;
5803 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5804 parameters given by current_template_args, or reuses a
5805 previously existing one, if appropriate. Returns the DECL, or an
5806 equivalent one, if it is replaced via a call to duplicate_decls.
5808 If IS_FRIEND is true, DECL is a friend declaration. */
5810 tree
5811 push_template_decl (tree decl, bool is_friend)
5813 if (decl == error_mark_node || !current_template_parms)
5814 return error_mark_node;
5816 /* See if this is a partial specialization. */
5817 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5818 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5819 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5820 || (VAR_P (decl)
5821 && DECL_LANG_SPECIFIC (decl)
5822 && DECL_TEMPLATE_SPECIALIZATION (decl)
5823 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5825 /* No surprising friend functions. */
5826 gcc_checking_assert (is_friend
5827 || !(TREE_CODE (decl) == FUNCTION_DECL
5828 && DECL_UNIQUE_FRIEND_P (decl)));
5830 tree ctx;
5831 if (is_friend)
5832 /* For a friend, we want the context of the friend, not
5833 the type of which it is a friend. */
5834 ctx = CP_DECL_CONTEXT (decl);
5835 else if (CP_DECL_CONTEXT (decl)
5836 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5837 /* In the case of a virtual function, we want the class in which
5838 it is defined. */
5839 ctx = CP_DECL_CONTEXT (decl);
5840 else
5841 /* Otherwise, if we're currently defining some class, the DECL
5842 is assumed to be a member of the class. */
5843 ctx = current_scope ();
5845 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5846 ctx = NULL_TREE;
5848 if (!DECL_CONTEXT (decl))
5849 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5851 /* See if this is a primary template. */
5852 bool is_primary = false;
5853 if (is_friend && ctx
5854 && uses_template_parms_level (ctx, current_template_depth))
5855 /* A friend template that specifies a class context, i.e.
5856 template <typename T> friend void A<T>::f();
5857 is not primary. */
5859 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5860 /* Lambdas are not primary. */
5862 else
5863 is_primary = template_parm_scope_p ();
5865 /* True if the template is a member template, in the sense of
5866 [temp.mem]. */
5867 bool member_template_p = false;
5869 if (is_primary)
5871 warning (OPT_Wtemplates, "template %qD declared", decl);
5873 if (DECL_CLASS_SCOPE_P (decl))
5874 member_template_p = true;
5876 if (TREE_CODE (decl) == TYPE_DECL
5877 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5879 error ("template class without a name");
5880 return error_mark_node;
5882 else if (TREE_CODE (decl) == FUNCTION_DECL)
5884 if (member_template_p)
5886 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5887 error ("member template %qD may not have virt-specifiers", decl);
5889 if (DECL_DESTRUCTOR_P (decl))
5891 /* [temp.mem]
5893 A destructor shall not be a member template. */
5894 error_at (DECL_SOURCE_LOCATION (decl),
5895 "destructor %qD declared as member template", decl);
5896 return error_mark_node;
5898 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5899 && (!prototype_p (TREE_TYPE (decl))
5900 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5901 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5902 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5903 == void_list_node)))
5905 /* [basic.stc.dynamic.allocation]
5907 An allocation function can be a function
5908 template. ... Template allocation functions shall
5909 have two or more parameters. */
5910 error ("invalid template declaration of %qD", decl);
5911 return error_mark_node;
5914 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5915 && CLASS_TYPE_P (TREE_TYPE (decl)))
5916 /* Class template. */;
5917 else if (TREE_CODE (decl) == TYPE_DECL
5918 && TYPE_DECL_ALIAS_P (decl))
5919 /* alias-declaration */
5920 gcc_assert (!DECL_ARTIFICIAL (decl));
5921 else if (VAR_P (decl))
5922 /* C++14 variable template. */;
5923 else if (TREE_CODE (decl) == CONCEPT_DECL)
5924 /* C++20 concept definitions. */;
5925 else
5927 error ("template declaration of %q#D", decl);
5928 return error_mark_node;
5932 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5933 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5934 || (VAR_OR_FUNCTION_DECL_P (decl)
5935 && DECL_LOCAL_DECL_P (decl))));
5937 /* Check to see that the rules regarding the use of default
5938 arguments are not being violated. We check args for a friend
5939 functions when we know whether it's a definition, introducing
5940 declaration or re-declaration. */
5941 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5942 check_default_tmpl_args (decl, current_template_parms,
5943 is_primary, is_partial, is_friend);
5945 /* Ensure that there are no parameter packs in the type of this
5946 declaration that have not been expanded. */
5947 if (TREE_CODE (decl) == FUNCTION_DECL)
5949 /* Check each of the arguments individually to see if there are
5950 any bare parameter packs. */
5951 tree type = TREE_TYPE (decl);
5952 tree arg = DECL_ARGUMENTS (decl);
5953 tree argtype = TYPE_ARG_TYPES (type);
5955 while (arg && argtype)
5957 if (!DECL_PACK_P (arg)
5958 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5960 /* This is a PARM_DECL that contains unexpanded parameter
5961 packs. We have already complained about this in the
5962 check_for_bare_parameter_packs call, so just replace
5963 these types with ERROR_MARK_NODE. */
5964 TREE_TYPE (arg) = error_mark_node;
5965 TREE_VALUE (argtype) = error_mark_node;
5968 arg = DECL_CHAIN (arg);
5969 argtype = TREE_CHAIN (argtype);
5972 /* Check for bare parameter packs in the return type and the
5973 exception specifiers. */
5974 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5975 /* Errors were already issued, set return type to int
5976 as the frontend doesn't expect error_mark_node as
5977 the return type. */
5978 TREE_TYPE (type) = integer_type_node;
5979 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5980 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5982 else
5984 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5985 ? DECL_ORIGINAL_TYPE (decl)
5986 : TREE_TYPE (decl)))
5988 TREE_TYPE (decl) = error_mark_node;
5989 return error_mark_node;
5992 if (is_partial && VAR_P (decl)
5993 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5994 return error_mark_node;
5997 if (is_partial)
5998 return process_partial_specialization (decl);
6000 tree args = current_template_args ();
6001 tree tmpl = NULL_TREE;
6002 bool new_template_p = false;
6003 if (local_p)
6005 /* Does not get a template head. */
6006 tmpl = NULL_TREE;
6007 gcc_checking_assert (!is_primary);
6009 else if (!ctx
6010 || TREE_CODE (ctx) == FUNCTION_DECL
6011 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6012 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6013 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6014 && DECL_TEMPLATE_INFO (decl))))
6016 if (DECL_LANG_SPECIFIC (decl)
6017 && DECL_TEMPLATE_INFO (decl)
6018 && DECL_TI_TEMPLATE (decl))
6019 tmpl = DECL_TI_TEMPLATE (decl);
6020 /* If DECL is a TYPE_DECL for a class-template, then there won't
6021 be DECL_LANG_SPECIFIC. The information equivalent to
6022 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6023 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6024 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6025 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6027 /* Since a template declaration already existed for this
6028 class-type, we must be redeclaring it here. Make sure
6029 that the redeclaration is valid. */
6030 redeclare_class_template (TREE_TYPE (decl),
6031 current_template_parms,
6032 current_template_constraints ());
6033 /* We don't need to create a new TEMPLATE_DECL; just use the
6034 one we already had. */
6035 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6037 else
6039 tmpl = build_template_decl (decl, current_template_parms,
6040 member_template_p);
6041 new_template_p = true;
6043 if (DECL_LANG_SPECIFIC (decl)
6044 && DECL_TEMPLATE_SPECIALIZATION (decl))
6046 /* A specialization of a member template of a template
6047 class. */
6048 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6049 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6050 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6054 else
6056 tree a, t, current, parms;
6057 int i;
6058 tree tinfo = get_template_info (decl);
6060 if (!tinfo)
6062 error ("template definition of non-template %q#D", decl);
6063 return error_mark_node;
6066 tmpl = TI_TEMPLATE (tinfo);
6068 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6069 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6070 && DECL_TEMPLATE_SPECIALIZATION (decl)
6071 && DECL_MEMBER_TEMPLATE_P (tmpl))
6073 /* The declaration is a specialization of a member
6074 template, declared outside the class. Therefore, the
6075 innermost template arguments will be NULL, so we
6076 replace them with the arguments determined by the
6077 earlier call to check_explicit_specialization. */
6078 args = DECL_TI_ARGS (decl);
6080 tree new_tmpl
6081 = build_template_decl (decl, current_template_parms,
6082 member_template_p);
6083 DECL_TI_TEMPLATE (decl) = new_tmpl;
6084 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6085 DECL_TEMPLATE_INFO (new_tmpl)
6086 = build_template_info (tmpl, args);
6088 register_specialization (new_tmpl,
6089 most_general_template (tmpl),
6090 args,
6091 is_friend, 0);
6092 return decl;
6095 /* Make sure the template headers we got make sense. */
6097 parms = DECL_TEMPLATE_PARMS (tmpl);
6098 i = TMPL_PARMS_DEPTH (parms);
6099 if (TMPL_ARGS_DEPTH (args) != i)
6101 error ("expected %d levels of template parms for %q#D, got %d",
6102 i, decl, TMPL_ARGS_DEPTH (args));
6103 DECL_INTERFACE_KNOWN (decl) = 1;
6104 return error_mark_node;
6106 else
6107 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6109 a = TMPL_ARGS_LEVEL (args, i);
6110 t = INNERMOST_TEMPLATE_PARMS (parms);
6112 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6114 if (current == decl)
6115 error ("got %d template parameters for %q#D",
6116 TREE_VEC_LENGTH (a), decl);
6117 else
6118 error ("got %d template parameters for %q#T",
6119 TREE_VEC_LENGTH (a), current);
6120 error (" but %d required", TREE_VEC_LENGTH (t));
6121 /* Avoid crash in import_export_decl. */
6122 DECL_INTERFACE_KNOWN (decl) = 1;
6123 return error_mark_node;
6126 if (current == decl)
6127 current = ctx;
6128 else if (current == NULL_TREE)
6129 /* Can happen in erroneous input. */
6130 break;
6131 else
6132 current = get_containing_scope (current);
6135 /* Check that the parms are used in the appropriate qualifying scopes
6136 in the declarator. */
6137 if (!comp_template_args
6138 (TI_ARGS (tinfo),
6139 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6141 error ("template arguments to %qD do not match original "
6142 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6143 if (!uses_template_parms (TI_ARGS (tinfo)))
6144 inform (input_location, "use %<template<>%> for"
6145 " an explicit specialization");
6146 /* Avoid crash in import_export_decl. */
6147 DECL_INTERFACE_KNOWN (decl) = 1;
6148 return error_mark_node;
6151 /* Check that the constraints for each enclosing template scope are
6152 consistent with the original declarations. */
6153 if (flag_concepts)
6155 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6156 tree scope_parms = current_template_parms;
6157 if (PRIMARY_TEMPLATE_P (tmpl))
6159 decl_parms = TREE_CHAIN (decl_parms);
6160 scope_parms = TREE_CHAIN (scope_parms);
6162 while (decl_parms)
6164 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6166 error ("redeclaration of %qD with different constraints",
6167 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6168 break;
6170 decl_parms = TREE_CHAIN (decl_parms);
6171 scope_parms = TREE_CHAIN (scope_parms);
6176 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6178 if (new_template_p)
6180 /* Push template declarations for global functions and types.
6181 Note that we do not try to push a global template friend
6182 declared in a template class; such a thing may well depend on
6183 the template parameters of the class and we'll push it when
6184 instantiating the befriending class. */
6185 if (!ctx
6186 && !(is_friend && template_class_depth (current_class_type) > 0))
6188 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6189 if (pushed == error_mark_node)
6190 return error_mark_node;
6192 /* pushdecl may have found an existing template. */
6193 if (pushed != tmpl)
6195 decl = DECL_TEMPLATE_RESULT (pushed);
6196 tmpl = NULL_TREE;
6199 else if (is_friend)
6201 /* Record this decl as belonging to the current class. It's
6202 not chained onto anything else. */
6203 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6204 gcc_checking_assert (!DECL_CHAIN (tmpl));
6205 DECL_CHAIN (tmpl) = current_scope ();
6208 else if (tmpl)
6209 /* The type may have been completed, or (erroneously) changed. */
6210 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6212 if (tmpl)
6214 if (is_primary)
6216 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6218 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6220 /* Give template template parms a DECL_CONTEXT of the template
6221 for which they are a parameter. */
6222 parms = INNERMOST_TEMPLATE_PARMS (parms);
6223 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6225 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6226 if (TREE_CODE (parm) == TEMPLATE_DECL)
6227 DECL_CONTEXT (parm) = tmpl;
6230 if (TREE_CODE (decl) == TYPE_DECL
6231 && TYPE_DECL_ALIAS_P (decl))
6233 if (tree constr
6234 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6236 /* ??? Why don't we do this here for all templates? */
6237 constr = build_constraints (constr, NULL_TREE);
6238 set_constraints (decl, constr);
6243 /* The DECL_TI_ARGS of DECL contains full set of arguments
6244 referring wback to its most general template. If TMPL is a
6245 specialization, ARGS may only have the innermost set of
6246 arguments. Add the missing argument levels if necessary. */
6247 if (DECL_TEMPLATE_INFO (tmpl))
6248 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6250 tree info = build_template_info (tmpl, args);
6252 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6253 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6254 else
6256 retrofit_lang_decl (decl);
6257 DECL_TEMPLATE_INFO (decl) = info;
6261 if (flag_implicit_templates
6262 && !is_friend
6263 && TREE_PUBLIC (decl)
6264 && VAR_OR_FUNCTION_DECL_P (decl))
6265 /* Set DECL_COMDAT on template instantiations; if we force
6266 them to be emitted by explicit instantiation,
6267 mark_needed will tell cgraph to do the right thing. */
6268 DECL_COMDAT (decl) = true;
6270 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6272 return decl;
6275 /* FN is an inheriting constructor that inherits from the constructor
6276 template INHERITED; turn FN into a constructor template with a matching
6277 template header. */
6279 tree
6280 add_inherited_template_parms (tree fn, tree inherited)
6282 tree inner_parms
6283 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6284 inner_parms = copy_node (inner_parms);
6285 tree parms
6286 = tree_cons (size_int (current_template_depth + 1),
6287 inner_parms, current_template_parms);
6288 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6289 tree args = template_parms_to_args (parms);
6290 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6291 DECL_ARTIFICIAL (tmpl) = true;
6292 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6293 return tmpl;
6296 /* Called when a class template TYPE is redeclared with the indicated
6297 template PARMS, e.g.:
6299 template <class T> struct S;
6300 template <class T> struct S {}; */
6302 bool
6303 redeclare_class_template (tree type, tree parms, tree cons)
6305 tree tmpl;
6306 tree tmpl_parms;
6307 int i;
6309 if (!TYPE_TEMPLATE_INFO (type))
6311 error ("%qT is not a template type", type);
6312 return false;
6315 tmpl = TYPE_TI_TEMPLATE (type);
6316 if (!PRIMARY_TEMPLATE_P (tmpl))
6317 /* The type is nested in some template class. Nothing to worry
6318 about here; there are no new template parameters for the nested
6319 type. */
6320 return true;
6322 if (!parms)
6324 error ("template specifiers not specified in declaration of %qD",
6325 tmpl);
6326 return false;
6329 parms = INNERMOST_TEMPLATE_PARMS (parms);
6330 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6332 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6334 error_n (input_location, TREE_VEC_LENGTH (parms),
6335 "redeclared with %d template parameter",
6336 "redeclared with %d template parameters",
6337 TREE_VEC_LENGTH (parms));
6338 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6339 "previous declaration %qD used %d template parameter",
6340 "previous declaration %qD used %d template parameters",
6341 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6342 return false;
6345 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6347 tree tmpl_parm;
6348 tree parm;
6350 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6351 || TREE_VEC_ELT (parms, i) == error_mark_node)
6352 continue;
6354 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6355 if (error_operand_p (tmpl_parm))
6356 return false;
6358 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6360 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6361 TEMPLATE_DECL. */
6362 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6363 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6364 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6365 || (TREE_CODE (tmpl_parm) != PARM_DECL
6366 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6367 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6368 || (TREE_CODE (tmpl_parm) == PARM_DECL
6369 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6370 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6372 auto_diagnostic_group d;
6373 error ("template parameter %q+#D", tmpl_parm);
6374 if (DECL_P (parm))
6375 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6376 else
6377 inform (input_location, "redeclared here");
6378 return false;
6381 /* The parameters can be declared to introduce different
6382 constraints. */
6383 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6384 tree p2 = TREE_VEC_ELT (parms, i);
6385 if (!template_parameter_constraints_equivalent_p (p1, p2))
6387 auto_diagnostic_group d;
6388 error ("declaration of template parameter %q+#D with different "
6389 "constraints", parm);
6390 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6391 "original declaration appeared here");
6392 return false;
6395 /* Give each template template parm in this redeclaration a
6396 DECL_CONTEXT of the template for which they are a parameter. */
6397 if (TREE_CODE (parm) == TEMPLATE_DECL)
6399 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6400 || DECL_CONTEXT (parm) == tmpl);
6401 DECL_CONTEXT (parm) = tmpl;
6405 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6406 return false;
6408 tree ci = get_constraints (tmpl);
6409 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6410 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6412 /* Two classes with different constraints declare different entities. */
6413 if (!cp_tree_equal (req1, req2))
6415 auto_diagnostic_group d;
6416 error_at (input_location, "redeclaration of %q#D with different "
6417 "constraints", tmpl);
6418 inform (DECL_SOURCE_LOCATION (tmpl),
6419 "original declaration appeared here");
6420 return false;
6423 return true;
6426 /* The actual substitution part of instantiate_non_dependent_expr,
6427 to be used when the caller has already checked
6428 !instantiation_dependent_uneval_expression_p (expr)
6429 and cleared processing_template_decl. */
6431 tree
6432 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6434 return tsubst_expr (expr, /*args=*/NULL_TREE, complain, /*in_decl=*/NULL_TREE);
6437 /* Instantiate the non-dependent expression EXPR. */
6439 tree
6440 instantiate_non_dependent_expr (tree expr,
6441 tsubst_flags_t complain /* = tf_error */)
6443 if (expr == NULL_TREE)
6444 return NULL_TREE;
6446 if (processing_template_decl)
6448 /* The caller should have checked this already. */
6449 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6450 processing_template_decl_sentinel s;
6451 expr = instantiate_non_dependent_expr_internal (expr, complain);
6453 return expr;
6456 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6457 expression is dependent or non-constant. */
6459 tree
6460 instantiate_non_dependent_or_null (tree expr)
6462 if (expr == NULL_TREE)
6463 return NULL_TREE;
6464 if (processing_template_decl)
6466 if (!is_nondependent_constant_expression (expr))
6467 expr = NULL_TREE;
6468 else
6470 processing_template_decl_sentinel s;
6471 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6474 return expr;
6477 /* True iff T is a specialization of a variable template. */
6479 bool
6480 variable_template_specialization_p (tree t)
6482 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6483 return false;
6484 tree tmpl = DECL_TI_TEMPLATE (t);
6485 return variable_template_p (tmpl);
6488 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6489 template declaration, or a TYPE_DECL for an alias declaration. */
6491 bool
6492 alias_type_or_template_p (tree t)
6494 if (t == NULL_TREE)
6495 return false;
6496 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6497 || (TYPE_P (t)
6498 && TYPE_NAME (t)
6499 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6500 || DECL_ALIAS_TEMPLATE_P (t));
6503 /* If T is a specialization of an alias template, return it; otherwise return
6504 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6506 tree
6507 alias_template_specialization_p (const_tree t,
6508 bool transparent_typedefs)
6510 if (!TYPE_P (t))
6511 return NULL_TREE;
6513 /* It's an alias template specialization if it's an alias and its
6514 TYPE_NAME is a specialization of a primary template. */
6515 if (typedef_variant_p (t))
6517 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6518 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6519 return CONST_CAST_TREE (t);
6520 if (transparent_typedefs)
6521 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6522 (TYPE_NAME (t)),
6523 transparent_typedefs);
6526 return NULL_TREE;
6529 /* A cache of the result of complex_alias_template_p. */
6531 static GTY((deletable)) hash_map<const_tree, tree> *complex_alias_tmpl_info;
6533 /* Data structure for complex_alias_template_*. */
6535 struct uses_all_template_parms_data
6537 int level;
6538 tree *seen;
6541 /* walk_tree callback for complex_alias_template_p. */
6543 static tree
6544 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6546 tree t = *tp;
6547 auto &data = *(struct uses_all_template_parms_data*)data_;
6549 switch (TREE_CODE (t))
6551 case TEMPLATE_TYPE_PARM:
6552 case TEMPLATE_PARM_INDEX:
6553 case TEMPLATE_TEMPLATE_PARM:
6554 case BOUND_TEMPLATE_TEMPLATE_PARM:
6556 tree idx = get_template_parm_index (t);
6557 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6558 data.seen[TEMPLATE_PARM_IDX (idx)] = boolean_true_node;
6561 default:;
6564 if (!PACK_EXPANSION_P (t))
6565 return 0;
6567 /* An alias template with a pack expansion that expands a pack from the
6568 enclosing class needs to be considered complex, to avoid confusion with
6569 the same pack being used as an argument to the alias's own template
6570 parameter (91966). */
6571 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6572 pack = TREE_CHAIN (pack))
6574 tree parm_pack = TREE_VALUE (pack);
6575 if (!TEMPLATE_PARM_P (parm_pack))
6576 continue;
6577 int idx, level;
6578 template_parm_level_and_index (parm_pack, &level, &idx);
6579 if (level < data.level)
6580 return t;
6582 /* Consider the expanded packs to be used outside the expansion... */
6583 data.seen[idx] = boolean_true_node;
6586 /* ...but don't walk into the pattern. Consider PR104008:
6588 template <typename T, typename... Ts>
6589 using IsOneOf = disjunction<is_same<T, Ts>...>;
6591 where IsOneOf seemingly uses all of its template parameters in its
6592 expansion (and does not expand a pack from the enclosing class), so the
6593 alias was not marked as complex. However, if it is used like
6594 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6595 expansion. So only Ts is considered used by the pack expansion. */
6596 *walk_subtrees = false;
6598 return 0;
6601 /* An alias template is complex from a SFINAE perspective if a template-id
6602 using that alias can be ill-formed when the expansion is not, as with
6603 the void_t template.
6605 If this predicate returns true in the ordinary case, the out parameter
6606 SEEN_OUT is set to a TREE_VEC containing boolean_true_node at element I if
6607 the I'th template parameter of the alias template is used in the alias. */
6609 static bool
6610 complex_alias_template_p (const_tree tmpl, tree *seen_out)
6612 tmpl = most_general_template (tmpl);
6613 if (!PRIMARY_TEMPLATE_P (tmpl))
6614 return false;
6616 /* A renaming alias isn't complex. */
6617 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6618 return false;
6620 /* Any other constrained alias is complex. */
6621 if (get_constraints (tmpl))
6622 return true;
6624 if (!complex_alias_tmpl_info)
6625 complex_alias_tmpl_info = hash_map<const_tree, tree>::create_ggc (13);
6627 if (tree *slot = complex_alias_tmpl_info->get (tmpl))
6629 tree result = *slot;
6630 if (result == boolean_false_node)
6631 return false;
6632 if (result == boolean_true_node)
6633 return true;
6634 gcc_assert (TREE_CODE (result) == TREE_VEC);
6635 if (seen_out)
6636 *seen_out = result;
6637 return true;
6640 struct uses_all_template_parms_data data;
6641 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6642 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6643 data.level = TMPL_PARMS_DEPTH (parms);
6644 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6645 tree seen = make_tree_vec (len);
6646 data.seen = TREE_VEC_BEGIN (seen);
6647 for (int i = 0; i < len; ++i)
6648 data.seen[i] = boolean_false_node;
6650 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6652 complex_alias_tmpl_info->put (tmpl, boolean_true_node);
6653 return true;
6656 for (int i = 0; i < len; ++i)
6657 if (data.seen[i] != boolean_true_node)
6659 complex_alias_tmpl_info->put (tmpl, seen);
6660 if (seen_out)
6661 *seen_out = seen;
6662 return true;
6665 complex_alias_tmpl_info->put (tmpl, boolean_false_node);
6666 return false;
6669 /* If T is a specialization of a complex alias template with a dependent
6670 argument for an unused template parameter, return it; otherwise return
6671 NULL_TREE. If T is a typedef to such a specialization, return the
6672 specialization. */
6674 tree
6675 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6677 if (t == error_mark_node)
6678 return NULL_TREE;
6679 gcc_assert (TYPE_P (t));
6681 if (!processing_template_decl || !typedef_variant_p (t))
6682 return NULL_TREE;
6684 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6686 tree seen = NULL_TREE;
6687 if (complex_alias_template_p (TI_TEMPLATE (tinfo), &seen))
6689 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6690 if (!seen)
6692 if (any_dependent_template_arguments_p (args))
6693 return CONST_CAST_TREE (t);
6695 else
6697 gcc_assert (TREE_VEC_LENGTH (args) == TREE_VEC_LENGTH (seen));
6698 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
6699 if (TREE_VEC_ELT (seen, i) != boolean_true_node
6700 && dependent_template_arg_p (TREE_VEC_ELT (args, i)))
6701 return CONST_CAST_TREE (t);
6704 return NULL_TREE;
6708 if (transparent_typedefs)
6710 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6711 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6714 return NULL_TREE;
6717 /* Return the number of innermost template parameters in TMPL. */
6719 static int
6720 num_innermost_template_parms (const_tree tmpl)
6722 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6723 return TREE_VEC_LENGTH (parms);
6726 /* Return either TMPL or another template that it is equivalent to under DR
6727 1286: An alias that just changes the name of a template is equivalent to
6728 the other template. */
6730 static tree
6731 get_underlying_template (tree tmpl)
6733 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6734 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6736 /* Determine if the alias is equivalent to an underlying template. */
6737 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6738 /* The underlying type may have been ill-formed. Don't proceed. */
6739 if (!orig_type)
6740 break;
6741 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6742 if (!tinfo)
6743 break;
6745 tree underlying = TI_TEMPLATE (tinfo);
6746 if (!PRIMARY_TEMPLATE_P (underlying)
6747 || (num_innermost_template_parms (tmpl)
6748 != num_innermost_template_parms (underlying)))
6749 break;
6751 /* Does the alias add cv-quals? */
6752 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6753 break;
6755 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6756 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6757 break;
6759 /* Are any default template arguments equivalent? */
6760 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6761 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6762 const int nparms = TREE_VEC_LENGTH (aparms);
6763 for (int i = 0; i < nparms; ++i)
6765 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6766 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6767 if (!template_args_equal (adefarg, udefarg))
6768 goto top_break;
6771 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6772 it's appropriate to treat a less-constrained alias as equivalent. */
6773 if (!at_least_as_constrained (underlying, tmpl))
6774 break;
6776 /* Alias is equivalent. Strip it and repeat. */
6777 tmpl = underlying;
6779 top_break:;
6781 return tmpl;
6784 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6785 must be a reference-to-function or a pointer-to-function type, as specified
6786 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6787 and check that the resulting function has external linkage. */
6789 static tree
6790 convert_nontype_argument_function (tree type, tree expr,
6791 tsubst_flags_t complain)
6793 tree fns = expr;
6794 tree fn, fn_no_ptr;
6795 linkage_kind linkage;
6797 fn = instantiate_type (type, fns, tf_none);
6798 if (fn == error_mark_node)
6799 return error_mark_node;
6801 if (value_dependent_expression_p (fn))
6802 goto accept;
6804 fn_no_ptr = fn;
6805 if (REFERENCE_REF_P (fn_no_ptr))
6806 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6807 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6808 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6809 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6810 if (BASELINK_P (fn_no_ptr))
6811 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6813 /* [temp.arg.nontype]/1
6815 A template-argument for a non-type, non-template template-parameter
6816 shall be one of:
6817 [...]
6818 -- the address of an object or function with external [C++11: or
6819 internal] linkage. */
6821 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6822 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6824 if (complain & tf_error)
6826 location_t loc = cp_expr_loc_or_input_loc (expr);
6827 error_at (loc, "%qE is not a valid template argument for type %qT",
6828 expr, type);
6829 if (TYPE_PTR_P (type))
6830 inform (loc, "it must be the address of a function "
6831 "with external linkage");
6832 else
6833 inform (loc, "it must be the name of a function with "
6834 "external linkage");
6836 return NULL_TREE;
6839 linkage = decl_linkage (fn_no_ptr);
6840 if ((cxx_dialect < cxx11 && linkage != lk_external)
6841 || (cxx_dialect < cxx17 && linkage == lk_none))
6843 if (complain & tf_error)
6845 location_t loc = cp_expr_loc_or_input_loc (expr);
6846 if (cxx_dialect >= cxx11)
6847 error_at (loc, "%qE is not a valid template argument for type "
6848 "%qT because %qD has no linkage",
6849 expr, type, fn_no_ptr);
6850 else
6851 error_at (loc, "%qE is not a valid template argument for type "
6852 "%qT because %qD does not have external linkage",
6853 expr, type, fn_no_ptr);
6855 return NULL_TREE;
6858 accept:
6859 if (TYPE_REF_P (type))
6861 if (REFERENCE_REF_P (fn))
6862 fn = TREE_OPERAND (fn, 0);
6863 else
6864 fn = build_address (fn);
6866 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6867 fn = build_nop (type, fn);
6869 return fn;
6872 /* Subroutine of convert_nontype_argument.
6873 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6874 Emit an error otherwise. */
6876 static bool
6877 check_valid_ptrmem_cst_expr (tree type, tree expr,
6878 tsubst_flags_t complain)
6880 tree orig_expr = expr;
6881 STRIP_NOPS (expr);
6882 if (null_ptr_cst_p (expr))
6883 return true;
6884 if (TREE_CODE (expr) == PTRMEM_CST
6885 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6886 PTRMEM_CST_CLASS (expr)))
6887 return true;
6888 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6889 return true;
6890 if (processing_template_decl
6891 && TREE_CODE (expr) == ADDR_EXPR
6892 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6893 return true;
6894 if (complain & tf_error)
6896 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6897 error_at (loc, "%qE is not a valid template argument for type %qT",
6898 orig_expr, type);
6899 if (TREE_CODE (expr) != PTRMEM_CST)
6900 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6901 else
6902 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6904 return false;
6907 /* Returns TRUE iff the address of OP is value-dependent.
6909 14.6.2.4 [temp.dep.temp]:
6910 A non-integral non-type template-argument is dependent if its type is
6911 dependent or it has either of the following forms
6912 qualified-id
6913 & qualified-id
6914 and contains a nested-name-specifier which specifies a class-name that
6915 names a dependent type.
6917 We generalize this to just say that the address of a member of a
6918 dependent class is value-dependent; the above doesn't cover the
6919 address of a static data member named with an unqualified-id. */
6921 static bool
6922 has_value_dependent_address (tree op)
6924 STRIP_ANY_LOCATION_WRAPPER (op);
6926 /* We could use get_inner_reference here, but there's no need;
6927 this is only relevant for template non-type arguments, which
6928 can only be expressed as &id-expression. */
6929 if (DECL_P (op))
6931 tree ctx = CP_DECL_CONTEXT (op);
6933 if (TYPE_P (ctx) && dependent_type_p (ctx))
6934 return true;
6936 if (VAR_P (op)
6937 && TREE_STATIC (op)
6938 && TREE_CODE (ctx) == FUNCTION_DECL
6939 && type_dependent_expression_p (ctx))
6940 return true;
6943 return false;
6946 /* The next set of functions are used for providing helpful explanatory
6947 diagnostics for failed overload resolution. Their messages should be
6948 indented by two spaces for consistency with the messages in
6949 call.cc */
6951 static int
6952 unify_success (bool /*explain_p*/)
6954 return 0;
6957 /* Other failure functions should call this one, to provide a single function
6958 for setting a breakpoint on. */
6960 static int
6961 unify_invalid (bool /*explain_p*/)
6963 return 1;
6966 static int
6967 unify_parameter_deduction_failure (bool explain_p, tree parm)
6969 if (explain_p)
6970 inform (input_location,
6971 " couldn%'t deduce template parameter %qD", parm);
6972 return unify_invalid (explain_p);
6975 static int
6976 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6978 if (explain_p)
6979 inform (input_location,
6980 " types %qT and %qT have incompatible cv-qualifiers",
6981 parm, arg);
6982 return unify_invalid (explain_p);
6985 static int
6986 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6988 if (explain_p)
6989 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6990 return unify_invalid (explain_p);
6993 static int
6994 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6996 if (explain_p)
6997 inform (input_location,
6998 " template parameter %qD is not a parameter pack, but "
6999 "argument %qD is",
7000 parm, arg);
7001 return unify_invalid (explain_p);
7004 static int
7005 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
7007 if (explain_p)
7008 inform (input_location,
7009 " template argument %qE does not match "
7010 "pointer-to-member constant %qE",
7011 arg, parm);
7012 return unify_invalid (explain_p);
7015 static int
7016 unify_expression_unequal (bool explain_p, tree parm, tree arg)
7018 if (explain_p)
7019 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
7020 return unify_invalid (explain_p);
7023 static int
7024 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
7026 if (explain_p)
7027 inform (input_location,
7028 " inconsistent parameter pack deduction with %qT and %qT",
7029 old_arg, new_arg);
7030 return unify_invalid (explain_p);
7033 static int
7034 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
7036 if (explain_p)
7038 if (TYPE_P (parm))
7039 inform (input_location,
7040 " deduced conflicting types for parameter %qT (%qT and %qT)",
7041 parm, first, second);
7042 else
7043 inform (input_location,
7044 " deduced conflicting values for non-type parameter "
7045 "%qE (%qE and %qE)", parm, first, second);
7047 return unify_invalid (explain_p);
7050 static int
7051 unify_vla_arg (bool explain_p, tree arg)
7053 if (explain_p)
7054 inform (input_location,
7055 " variable-sized array type %qT is not "
7056 "a valid template argument",
7057 arg);
7058 return unify_invalid (explain_p);
7061 static int
7062 unify_method_type_error (bool explain_p, tree arg)
7064 if (explain_p)
7065 inform (input_location,
7066 " member function type %qT is not a valid template argument",
7067 arg);
7068 return unify_invalid (explain_p);
7071 static int
7072 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7074 if (explain_p)
7076 if (least_p)
7077 inform_n (input_location, wanted,
7078 " candidate expects at least %d argument, %d provided",
7079 " candidate expects at least %d arguments, %d provided",
7080 wanted, have);
7081 else
7082 inform_n (input_location, wanted,
7083 " candidate expects %d argument, %d provided",
7084 " candidate expects %d arguments, %d provided",
7085 wanted, have);
7087 return unify_invalid (explain_p);
7090 static int
7091 unify_too_many_arguments (bool explain_p, int have, int wanted)
7093 return unify_arity (explain_p, have, wanted);
7096 static int
7097 unify_too_few_arguments (bool explain_p, int have, int wanted,
7098 bool least_p = false)
7100 return unify_arity (explain_p, have, wanted, least_p);
7103 static int
7104 unify_arg_conversion (bool explain_p, tree to_type,
7105 tree from_type, tree arg)
7107 if (explain_p)
7108 inform (cp_expr_loc_or_input_loc (arg),
7109 " cannot convert %qE (type %qT) to type %qT",
7110 arg, from_type, to_type);
7111 return unify_invalid (explain_p);
7114 static int
7115 unify_no_common_base (bool explain_p, enum template_base_result r,
7116 tree parm, tree arg)
7118 if (explain_p)
7119 switch (r)
7121 case tbr_ambiguous_baseclass:
7122 inform (input_location, " %qT is an ambiguous base class of %qT",
7123 parm, arg);
7124 break;
7125 default:
7126 inform (input_location, " %qT is not derived from %qT", arg, parm);
7127 break;
7129 return unify_invalid (explain_p);
7132 static int
7133 unify_inconsistent_template_template_parameters (bool explain_p)
7135 if (explain_p)
7136 inform (input_location,
7137 " template parameters of a template template argument are "
7138 "inconsistent with other deduced template arguments");
7139 return unify_invalid (explain_p);
7142 static int
7143 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7145 if (explain_p)
7146 inform (input_location,
7147 " cannot deduce a template for %qT from non-template type %qT",
7148 parm, arg);
7149 return unify_invalid (explain_p);
7152 static int
7153 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7155 if (explain_p)
7156 inform (input_location,
7157 " template argument %qE does not match %qE", arg, parm);
7158 return unify_invalid (explain_p);
7161 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7162 argument for TYPE, points to an unsuitable object.
7164 Also adjust the type of the index in C++20 array subobject references. */
7166 static bool
7167 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7169 switch (TREE_CODE (expr))
7171 CASE_CONVERT:
7172 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7173 complain);
7175 case TARGET_EXPR:
7176 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7177 complain);
7179 case CONSTRUCTOR:
7181 for (auto &e: CONSTRUCTOR_ELTS (expr))
7182 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7183 return true;
7185 break;
7187 case ADDR_EXPR:
7189 tree decl = TREE_OPERAND (expr, 0);
7191 if (cxx_dialect >= cxx20)
7192 while (TREE_CODE (decl) == COMPONENT_REF
7193 || TREE_CODE (decl) == ARRAY_REF)
7195 tree &op = TREE_OPERAND (decl, 1);
7196 if (TREE_CODE (decl) == ARRAY_REF
7197 && TREE_CODE (op) == INTEGER_CST)
7198 /* Canonicalize array offsets to ptrdiff_t; how they were
7199 written doesn't matter for subobject identity. */
7200 op = fold_convert (ptrdiff_type_node, op);
7201 decl = TREE_OPERAND (decl, 0);
7204 if (!VAR_OR_FUNCTION_DECL_P (decl))
7206 if (complain & tf_error)
7207 error_at (cp_expr_loc_or_input_loc (expr),
7208 "%qE is not a valid template argument of type %qT "
7209 "because %qE is not a variable or function",
7210 expr, type, decl);
7211 return true;
7213 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7215 if (complain & tf_error)
7216 error_at (cp_expr_loc_or_input_loc (expr),
7217 "%qE is not a valid template argument of type %qT "
7218 "in C++98 because %qD does not have external linkage",
7219 expr, type, decl);
7220 return true;
7222 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7223 && decl_linkage (decl) == lk_none)
7225 if (complain & tf_error)
7226 error_at (cp_expr_loc_or_input_loc (expr),
7227 "%qE is not a valid template argument of type %qT "
7228 "because %qD has no linkage", expr, type, decl);
7229 return true;
7231 /* C++17: For a non-type template-parameter of reference or pointer
7232 type, the value of the constant expression shall not refer to (or
7233 for a pointer type, shall not be the address of):
7234 * a subobject (4.5),
7235 * a temporary object (15.2),
7236 * a string literal (5.13.5),
7237 * the result of a typeid expression (8.2.8), or
7238 * a predefined __func__ variable (11.4.1). */
7239 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl)
7240 && !DECL_NTTP_OBJECT_P (decl))
7242 gcc_checking_assert (DECL_TINFO_P (decl) || DECL_FNAME_P (decl));
7243 if (complain & tf_error)
7244 error ("the address of %qD is not a valid template argument",
7245 decl);
7246 return true;
7248 else if (cxx_dialect < cxx20
7249 && !(same_type_ignoring_top_level_qualifiers_p
7250 (strip_array_types (TREE_TYPE (type)),
7251 strip_array_types (TREE_TYPE (decl)))))
7253 if (complain & tf_error)
7254 error ("the address of the %qT subobject of %qD is not a "
7255 "valid template argument", TREE_TYPE (type), decl);
7256 return true;
7258 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7260 if (complain & tf_error)
7261 error ("the address of %qD is not a valid template argument "
7262 "because it does not have static storage duration",
7263 decl);
7264 return true;
7267 break;
7269 default:
7270 if (!INDIRECT_TYPE_P (type))
7271 /* We're only concerned about pointers and references here. */;
7272 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7273 /* Null pointer values are OK in C++11. */;
7274 else
7276 if (VAR_P (expr))
7278 if (complain & tf_error)
7279 error ("%qD is not a valid template argument "
7280 "because %qD is a variable, not the address of "
7281 "a variable", expr, expr);
7282 return true;
7284 else
7286 if (complain & tf_error)
7287 error ("%qE is not a valid template argument for %qT "
7288 "because it is not the address of a variable",
7289 expr, type);
7290 return true;
7294 return false;
7298 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7299 template argument EXPR. */
7301 static tree
7302 create_template_parm_object (tree expr, tsubst_flags_t complain)
7304 if (TREE_CODE (expr) == TARGET_EXPR)
7305 expr = TARGET_EXPR_INITIAL (expr);
7307 if (!TREE_CONSTANT (expr))
7309 if ((complain & tf_error)
7310 && require_rvalue_constant_expression (expr))
7311 cxx_constant_value (expr);
7312 return error_mark_node;
7314 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7315 return error_mark_node;
7317 /* This is no longer a compound literal. */
7318 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7320 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7323 /* The template arguments corresponding to template parameter objects of types
7324 that contain pointers to members. */
7326 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7328 /* Find or build an nttp object for (already-validated) EXPR with name
7329 NAME. */
7331 tree
7332 get_template_parm_object (tree expr, tree name)
7334 tree decl = get_global_binding (name);
7335 if (decl)
7336 return decl;
7338 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7339 decl = create_temporary_var (type);
7340 DECL_NTTP_OBJECT_P (decl) = true;
7341 DECL_CONTEXT (decl) = NULL_TREE;
7342 TREE_STATIC (decl) = true;
7343 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7344 TREE_READONLY (decl) = true;
7345 DECL_NAME (decl) = name;
7346 SET_DECL_ASSEMBLER_NAME (decl, name);
7347 comdat_linkage (decl);
7349 if (!zero_init_p (type))
7351 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7352 lower_var_init before we're done mangling. So store the original
7353 value elsewhere. */
7354 tree copy = unshare_constructor (expr);
7355 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7358 pushdecl_top_level_and_finish (decl, expr);
7360 return decl;
7363 /* Return the actual template argument corresponding to template parameter
7364 object VAR. */
7366 tree
7367 tparm_object_argument (tree var)
7369 if (zero_init_p (TREE_TYPE (var)))
7370 return DECL_INITIAL (var);
7371 return *(tparm_obj_values->get (var));
7374 /* Attempt to convert the non-type template parameter EXPR to the
7375 indicated TYPE. If the conversion is successful, return the
7376 converted value. If the conversion is unsuccessful, return
7377 NULL_TREE if we issued an error message, or error_mark_node if we
7378 did not. We issue error messages for out-and-out bad template
7379 parameters, but not simply because the conversion failed, since we
7380 might be just trying to do argument deduction. Both TYPE and EXPR
7381 must be non-dependent.
7383 The conversion follows the special rules described in
7384 [temp.arg.nontype], and it is much more strict than an implicit
7385 conversion.
7387 This function is called twice for each template argument (see
7388 lookup_template_class for a more accurate description of this
7389 problem). This means that we need to handle expressions which
7390 are not valid in a C++ source, but can be created from the
7391 first call (for instance, casts to perform conversions). These
7392 hacks can go away after we fix the double coercion problem. */
7394 static tree
7395 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7397 tree expr_type;
7398 location_t loc = cp_expr_loc_or_input_loc (expr);
7400 /* Detect immediately string literals as invalid non-type argument.
7401 This special-case is not needed for correctness (we would easily
7402 catch this later), but only to provide better diagnostic for this
7403 common user mistake. As suggested by DR 100, we do not mention
7404 linkage issues in the diagnostic as this is not the point. */
7405 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7407 if (complain & tf_error)
7408 error ("%qE is not a valid template argument for type %qT "
7409 "because string literals can never be used in this context",
7410 expr, type);
7411 return NULL_TREE;
7414 /* Add the ADDR_EXPR now for the benefit of
7415 value_dependent_expression_p. */
7416 if (TYPE_PTROBV_P (type)
7417 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7419 expr = decay_conversion (expr, complain);
7420 if (expr == error_mark_node)
7421 return error_mark_node;
7424 /* If we are in a template, EXPR may be non-dependent, but still
7425 have a syntactic, rather than semantic, form. For example, EXPR
7426 might be a SCOPE_REF, rather than the VAR_DECL to which the
7427 SCOPE_REF refers. Preserving the qualifying scope is necessary
7428 so that access checking can be performed when the template is
7429 instantiated -- but here we need the resolved form so that we can
7430 convert the argument. */
7431 bool non_dep = false;
7432 if (TYPE_REF_OBJ_P (type)
7433 && has_value_dependent_address (expr))
7434 /* If we want the address and it's value-dependent, don't fold. */;
7435 else if (processing_template_decl
7436 && !instantiation_dependent_expression_p (expr))
7437 non_dep = true;
7438 if (error_operand_p (expr))
7439 return error_mark_node;
7440 expr_type = TREE_TYPE (expr);
7442 /* If the argument is non-dependent, perform any conversions in
7443 non-dependent context as well. */
7444 processing_template_decl_sentinel s (non_dep);
7445 if (non_dep)
7446 expr = instantiate_non_dependent_expr_internal (expr, complain);
7448 bool val_dep_p = value_dependent_expression_p (expr);
7449 if (val_dep_p)
7450 expr = canonicalize_expr_argument (expr, complain);
7451 else
7452 STRIP_ANY_LOCATION_WRAPPER (expr);
7454 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7455 to a non-type argument of "nullptr". */
7456 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7457 expr = fold_simple (convert (type, expr));
7459 /* In C++11, integral or enumeration non-type template arguments can be
7460 arbitrary constant expressions. Pointer and pointer to
7461 member arguments can be general constant expressions that evaluate
7462 to a null value, but otherwise still need to be of a specific form. */
7463 if (cxx_dialect >= cxx11)
7465 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7466 /* A PTRMEM_CST is already constant, and a valid template
7467 argument for a parameter of pointer to member type, we just want
7468 to leave it in that form rather than lower it to a
7469 CONSTRUCTOR. */;
7470 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7471 || cxx_dialect >= cxx17)
7473 /* C++17: A template-argument for a non-type template-parameter shall
7474 be a converted constant expression (8.20) of the type of the
7475 template-parameter. */
7476 expr = build_converted_constant_expr (type, expr, complain);
7477 if (expr == error_mark_node)
7478 /* Make sure we return NULL_TREE only if we have really issued
7479 an error, as described above. */
7480 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7481 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7483 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7484 return expr;
7486 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7487 expr = convert_from_reference (expr);
7488 /* EXPR may have become value-dependent. */
7489 val_dep_p = value_dependent_expression_p (expr);
7491 else if (TYPE_PTR_OR_PTRMEM_P (type))
7493 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7494 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7495 : null_member_pointer_value_p (folded))
7496 expr = folded;
7500 if (TYPE_REF_P (type))
7501 expr = mark_lvalue_use (expr);
7502 else
7503 expr = mark_rvalue_use (expr);
7505 /* HACK: Due to double coercion, we can get a
7506 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7507 which is the tree that we built on the first call (see
7508 below when coercing to reference to object or to reference to
7509 function). We just strip everything and get to the arg.
7510 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7511 for examples. */
7512 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7514 /* Check this before we strip *& to avoid redundancy. */
7515 if (!mark_single_function (expr, complain))
7516 return error_mark_node;
7518 tree probe_type, probe = expr;
7519 if (REFERENCE_REF_P (probe))
7520 probe = TREE_OPERAND (probe, 0);
7521 probe_type = TREE_TYPE (probe);
7522 if (TREE_CODE (probe) == NOP_EXPR)
7524 /* ??? Maybe we could use convert_from_reference here, but we
7525 would need to relax its constraints because the NOP_EXPR
7526 could actually change the type to something more cv-qualified,
7527 and this is not folded by convert_from_reference. */
7528 tree addr = TREE_OPERAND (probe, 0);
7529 if (TYPE_REF_P (probe_type)
7530 && TREE_CODE (addr) == ADDR_EXPR
7531 && TYPE_PTR_P (TREE_TYPE (addr))
7532 && (same_type_ignoring_top_level_qualifiers_p
7533 (TREE_TYPE (probe_type),
7534 TREE_TYPE (TREE_TYPE (addr)))))
7536 expr = TREE_OPERAND (addr, 0);
7537 expr_type = TREE_TYPE (probe_type);
7542 /* [temp.arg.nontype]/5, bullet 1
7544 For a non-type template-parameter of integral or enumeration type,
7545 integral promotions (_conv.prom_) and integral conversions
7546 (_conv.integral_) are applied. */
7547 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7548 || SCALAR_FLOAT_TYPE_P (type))
7550 if (cxx_dialect < cxx11)
7552 tree t = build_converted_constant_expr (type, expr, complain);
7553 t = maybe_constant_value (t);
7554 if (t != error_mark_node)
7555 expr = t;
7558 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7559 return error_mark_node;
7561 /* Notice that there are constant expressions like '4 % 0' which
7562 do not fold into integer constants. */
7563 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7565 if (complain & tf_error)
7567 int errs = errorcount, warns = warningcount + werrorcount;
7568 if (!require_potential_constant_expression (expr))
7569 expr = error_mark_node;
7570 else
7571 expr = cxx_constant_value (expr);
7572 if (errorcount > errs || warningcount + werrorcount > warns)
7573 inform (loc, "in template argument for type %qT", type);
7574 if (expr == error_mark_node)
7575 return NULL_TREE;
7576 /* else cxx_constant_value complained but gave us
7577 a real constant, so go ahead. */
7578 if (!CONSTANT_CLASS_P (expr))
7580 /* Some assemble time constant expressions like
7581 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7582 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7583 as we can emit them into .rodata initializers of
7584 variables, yet they can't fold into an INTEGER_CST at
7585 compile time. Refuse them here. */
7586 gcc_checking_assert (reduced_constant_expression_p (expr));
7587 error_at (loc, "template argument %qE for type %qT not "
7588 "a compile-time constant", expr, type);
7589 return NULL_TREE;
7592 else
7593 return NULL_TREE;
7596 /* Avoid typedef problems. */
7597 if (TREE_TYPE (expr) != type)
7598 expr = fold_convert (type, expr);
7600 /* [temp.arg.nontype]/5, bullet 2
7602 For a non-type template-parameter of type pointer to object,
7603 qualification conversions (_conv.qual_) and the array-to-pointer
7604 conversion (_conv.array_) are applied. */
7605 else if (TYPE_PTROBV_P (type))
7607 tree decayed = expr;
7609 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7610 decay_conversion or an explicit cast. If it's a problematic cast,
7611 we'll complain about it below. */
7612 if (TREE_CODE (expr) == NOP_EXPR)
7614 tree probe = expr;
7615 STRIP_NOPS (probe);
7616 if (TREE_CODE (probe) == ADDR_EXPR
7617 && TYPE_PTR_P (TREE_TYPE (probe)))
7619 expr = probe;
7620 expr_type = TREE_TYPE (expr);
7624 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7626 A template-argument for a non-type, non-template template-parameter
7627 shall be one of: [...]
7629 -- the name of a non-type template-parameter;
7630 -- the address of an object or function with external linkage, [...]
7631 expressed as "& id-expression" where the & is optional if the name
7632 refers to a function or array, or if the corresponding
7633 template-parameter is a reference.
7635 Here, we do not care about functions, as they are invalid anyway
7636 for a parameter of type pointer-to-object. */
7638 if (val_dep_p)
7639 /* Non-type template parameters are OK. */
7641 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7642 /* Null pointer values are OK in C++11. */;
7643 else if (TREE_CODE (expr) != ADDR_EXPR
7644 && !INDIRECT_TYPE_P (expr_type))
7645 /* Other values, like integer constants, might be valid
7646 non-type arguments of some other type. */
7647 return error_mark_node;
7648 else if (invalid_tparm_referent_p (type, expr, complain))
7649 return NULL_TREE;
7651 expr = decayed;
7653 expr = perform_qualification_conversions (type, expr);
7654 if (expr == error_mark_node)
7655 return error_mark_node;
7657 /* [temp.arg.nontype]/5, bullet 3
7659 For a non-type template-parameter of type reference to object, no
7660 conversions apply. The type referred to by the reference may be more
7661 cv-qualified than the (otherwise identical) type of the
7662 template-argument. The template-parameter is bound directly to the
7663 template-argument, which must be an lvalue. */
7664 else if (TYPE_REF_OBJ_P (type))
7666 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7667 expr_type))
7668 return error_mark_node;
7670 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7672 if (complain & tf_error)
7673 error ("%qE is not a valid template argument for type %qT "
7674 "because of conflicts in cv-qualification", expr, type);
7675 return NULL_TREE;
7678 if (!lvalue_p (expr))
7680 if (complain & tf_error)
7681 error ("%qE is not a valid template argument for type %qT "
7682 "because it is not an lvalue", expr, type);
7683 return NULL_TREE;
7686 /* [temp.arg.nontype]/1
7688 A template-argument for a non-type, non-template template-parameter
7689 shall be one of: [...]
7691 -- the address of an object or function with external linkage. */
7692 if (INDIRECT_REF_P (expr)
7693 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7695 expr = TREE_OPERAND (expr, 0);
7696 if (DECL_P (expr))
7698 if (complain & tf_error)
7699 error ("%q#D is not a valid template argument for type %qT "
7700 "because a reference variable does not have a constant "
7701 "address", expr, type);
7702 return NULL_TREE;
7706 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7707 /* OK, dependent reference. We don't want to ask whether a DECL is
7708 itself value-dependent, since what we want here is its address. */;
7709 else
7711 expr = build_address (expr);
7713 if (invalid_tparm_referent_p (type, expr, complain))
7714 return NULL_TREE;
7717 if (!same_type_p (type, TREE_TYPE (expr)))
7718 expr = build_nop (type, expr);
7720 /* [temp.arg.nontype]/5, bullet 4
7722 For a non-type template-parameter of type pointer to function, only
7723 the function-to-pointer conversion (_conv.func_) is applied. If the
7724 template-argument represents a set of overloaded functions (or a
7725 pointer to such), the matching function is selected from the set
7726 (_over.over_). */
7727 else if (TYPE_PTRFN_P (type))
7729 /* If the argument is a template-id, we might not have enough
7730 context information to decay the pointer. */
7731 if (!type_unknown_p (expr_type))
7733 expr = decay_conversion (expr, complain);
7734 if (expr == error_mark_node)
7735 return error_mark_node;
7738 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7739 /* Null pointer values are OK in C++11. */
7740 return perform_qualification_conversions (type, expr);
7742 expr = convert_nontype_argument_function (type, expr, complain);
7743 if (!expr || expr == error_mark_node)
7744 return expr;
7746 /* [temp.arg.nontype]/5, bullet 5
7748 For a non-type template-parameter of type reference to function, no
7749 conversions apply. If the template-argument represents a set of
7750 overloaded functions, the matching function is selected from the set
7751 (_over.over_). */
7752 else if (TYPE_REFFN_P (type))
7754 if (TREE_CODE (expr) == ADDR_EXPR)
7756 if (complain & tf_error)
7758 error ("%qE is not a valid template argument for type %qT "
7759 "because it is a pointer", expr, type);
7760 inform (input_location, "try using %qE instead",
7761 TREE_OPERAND (expr, 0));
7763 return NULL_TREE;
7766 expr = convert_nontype_argument_function (type, expr, complain);
7767 if (!expr || expr == error_mark_node)
7768 return expr;
7770 /* [temp.arg.nontype]/5, bullet 6
7772 For a non-type template-parameter of type pointer to member function,
7773 no conversions apply. If the template-argument represents a set of
7774 overloaded member functions, the matching member function is selected
7775 from the set (_over.over_). */
7776 else if (TYPE_PTRMEMFUNC_P (type))
7778 expr = instantiate_type (type, expr, tf_none);
7779 if (expr == error_mark_node)
7780 return error_mark_node;
7782 /* [temp.arg.nontype] bullet 1 says the pointer to member
7783 expression must be a pointer-to-member constant. */
7784 if (!val_dep_p
7785 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7786 return NULL_TREE;
7788 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7789 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7790 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7791 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7793 /* [temp.arg.nontype]/5, bullet 7
7795 For a non-type template-parameter of type pointer to data member,
7796 qualification conversions (_conv.qual_) are applied. */
7797 else if (TYPE_PTRDATAMEM_P (type))
7799 /* [temp.arg.nontype] bullet 1 says the pointer to member
7800 expression must be a pointer-to-member constant. */
7801 if (!val_dep_p
7802 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7803 return NULL_TREE;
7805 expr = perform_qualification_conversions (type, expr);
7806 if (expr == error_mark_node)
7807 return expr;
7809 else if (NULLPTR_TYPE_P (type))
7811 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7813 if (complain & tf_error)
7814 error ("%qE is not a valid template argument for type %qT "
7815 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7816 return NULL_TREE;
7818 return expr;
7820 else if (CLASS_TYPE_P (type))
7822 /* Replace the argument with a reference to the corresponding template
7823 parameter object. */
7824 if (!val_dep_p)
7825 expr = create_template_parm_object (expr, complain);
7826 if (expr == error_mark_node)
7827 return NULL_TREE;
7829 /* A template non-type parameter must be one of the above. */
7830 else
7831 gcc_unreachable ();
7833 /* Sanity check: did we actually convert the argument to the
7834 right type? */
7835 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7836 (type, TREE_TYPE (expr)));
7837 return convert_from_reference (expr);
7840 /* Subroutine of coerce_template_template_parms, which returns 1 if
7841 PARM_PARM and ARG_PARM match using the rule for the template
7842 parameters of template template parameters. Both PARM and ARG are
7843 template parameters; the rest of the arguments are the same as for
7844 coerce_template_template_parms.
7846 static int
7847 coerce_template_template_parm (tree parm,
7848 tree arg,
7849 tsubst_flags_t complain,
7850 tree in_decl,
7851 tree outer_args)
7853 if (arg == NULL_TREE || error_operand_p (arg)
7854 || parm == NULL_TREE || error_operand_p (parm))
7855 return 0;
7857 if (TREE_CODE (arg) != TREE_CODE (parm))
7858 return 0;
7860 switch (TREE_CODE (parm))
7862 case TEMPLATE_DECL:
7863 /* We encounter instantiations of templates like
7864 template <template <template <class> class> class TT>
7865 class C; */
7867 if (!coerce_template_template_parms
7868 (parm, arg, complain, in_decl, outer_args))
7869 return 0;
7871 /* Fall through. */
7873 case TYPE_DECL:
7874 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7875 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7876 /* Argument is a parameter pack but parameter is not. */
7877 return 0;
7878 break;
7880 case PARM_DECL:
7881 /* The tsubst call is used to handle cases such as
7883 template <int> class C {};
7884 template <class T, template <T> class TT> class D {};
7885 D<int, C> d;
7887 i.e. the parameter list of TT depends on earlier parameters. */
7888 if (!uses_template_parms (TREE_TYPE (arg)))
7890 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7891 if (!uses_template_parms (t)
7892 && !same_type_p (t, TREE_TYPE (arg)))
7893 return 0;
7896 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7897 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7898 /* Argument is a parameter pack but parameter is not. */
7899 return 0;
7901 break;
7903 default:
7904 gcc_unreachable ();
7907 return 1;
7910 /* Coerce template argument list ARGLIST for use with template
7911 template-parameter TEMPL. */
7913 static tree
7914 coerce_template_args_for_ttp (tree templ, tree arglist,
7915 tsubst_flags_t complain)
7917 /* Consider an example where a template template parameter declared as
7919 template <class T, class U = std::allocator<T> > class TT
7921 The template parameter level of T and U are one level larger than
7922 of TT. To proper process the default argument of U, say when an
7923 instantiation `TT<int>' is seen, we need to build the full
7924 arguments containing {int} as the innermost level. Outer levels,
7925 available when not appearing as default template argument, can be
7926 obtained from the arguments of the enclosing template.
7928 Suppose that TT is later substituted with std::vector. The above
7929 instantiation is `TT<int, std::allocator<T> >' with TT at
7930 level 1, and T at level 2, while the template arguments at level 1
7931 becomes {std::vector} and the inner level 2 is {int}. */
7933 tree outer = DECL_CONTEXT (templ);
7934 if (outer)
7935 outer = generic_targs_for (outer);
7936 else if (current_template_parms)
7938 /* This is an argument of the current template, so we haven't set
7939 DECL_CONTEXT yet. We can also get here when level-lowering a
7940 bound ttp. */
7941 tree relevant_template_parms;
7943 /* Parameter levels that are greater than the level of the given
7944 template template parm are irrelevant. */
7945 relevant_template_parms = current_template_parms;
7946 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7947 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7948 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7950 outer = template_parms_to_args (relevant_template_parms);
7953 if (outer)
7954 arglist = add_to_template_args (outer, arglist);
7956 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7957 return coerce_template_parms (parmlist, arglist, templ, complain);
7960 /* A cache of template template parameters with match-all default
7961 arguments. */
7962 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7964 /* T is a bound template template-parameter. Copy its arguments into default
7965 arguments of the template template-parameter's template parameters. */
7967 static tree
7968 add_defaults_to_ttp (tree otmpl)
7970 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7971 return *c;
7973 tree ntmpl = copy_node (otmpl);
7975 tree ntype = copy_node (TREE_TYPE (otmpl));
7976 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7977 TYPE_MAIN_VARIANT (ntype) = ntype;
7978 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7979 TYPE_NAME (ntype) = ntmpl;
7980 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7982 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7983 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7984 TEMPLATE_PARM_DECL (idx) = ntmpl;
7985 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7987 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7988 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7989 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7990 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7991 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7993 tree o = TREE_VEC_ELT (vec, i);
7994 if (!template_parameter_pack_p (TREE_VALUE (o)))
7996 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7997 TREE_PURPOSE (n) = any_targ_node;
8001 tree oresult = DECL_TEMPLATE_RESULT (otmpl);
8002 tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
8003 tree gen_ntmpl;
8004 if (gen_otmpl == otmpl)
8005 gen_ntmpl = ntmpl;
8006 else
8007 gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
8009 tree nresult = copy_decl (oresult);
8010 DECL_TEMPLATE_INFO (nresult)
8011 = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
8012 DECL_TEMPLATE_RESULT (ntmpl) = nresult;
8014 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
8015 return ntmpl;
8018 /* ARG is a bound potential template template-argument, and PARGS is a list
8019 of arguments for the corresponding template template-parameter. Adjust
8020 PARGS as appropriate for application to ARG's template, and if ARG is a
8021 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
8022 arguments to the template template parameter. */
8024 static tree
8025 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
8027 ++processing_template_decl;
8028 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
8029 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8031 /* When comparing two template template-parameters in partial ordering,
8032 rewrite the one currently being used as an argument to have default
8033 arguments for all parameters. */
8034 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
8035 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
8036 if (pargs != error_mark_node)
8037 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
8038 TYPE_TI_ARGS (arg));
8040 else
8042 tree aparms
8043 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
8044 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
8046 --processing_template_decl;
8047 return pargs;
8050 /* Subroutine of unify for the case when PARM is a
8051 BOUND_TEMPLATE_TEMPLATE_PARM. */
8053 static int
8054 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
8055 bool explain_p)
8057 tree parmvec = TYPE_TI_ARGS (parm);
8058 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
8060 /* The template template parm might be variadic and the argument
8061 not, so flatten both argument lists. */
8062 parmvec = expand_template_argument_pack (parmvec);
8063 argvec = expand_template_argument_pack (argvec);
8065 if (flag_new_ttp)
8067 /* In keeping with P0522R0, adjust P's template arguments
8068 to apply to A's template; then flatten it again. */
8069 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
8070 nparmvec = expand_template_argument_pack (nparmvec);
8072 if (unify (tparms, targs, nparmvec, argvec,
8073 UNIFY_ALLOW_NONE, explain_p))
8074 return 1;
8076 /* If the P0522 adjustment eliminated a pack expansion, deduce
8077 empty packs. */
8078 if (flag_new_ttp
8079 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8080 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8081 DEDUCE_EXACT, /*sub*/true, explain_p))
8082 return 1;
8084 else
8086 /* Deduce arguments T, i from TT<T> or TT<i>.
8087 We check each element of PARMVEC and ARGVEC individually
8088 rather than the whole TREE_VEC since they can have
8089 different number of elements, which is allowed under N2555. */
8091 int len = TREE_VEC_LENGTH (parmvec);
8093 /* Check if the parameters end in a pack, making them
8094 variadic. */
8095 int parm_variadic_p = 0;
8096 if (len > 0
8097 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8098 parm_variadic_p = 1;
8100 for (int i = 0; i < len - parm_variadic_p; ++i)
8101 /* If the template argument list of P contains a pack
8102 expansion that is not the last template argument, the
8103 entire template argument list is a non-deduced
8104 context. */
8105 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8106 return unify_success (explain_p);
8108 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8109 return unify_too_few_arguments (explain_p,
8110 TREE_VEC_LENGTH (argvec), len);
8112 for (int i = 0; i < len - parm_variadic_p; ++i)
8113 if (unify (tparms, targs,
8114 TREE_VEC_ELT (parmvec, i),
8115 TREE_VEC_ELT (argvec, i),
8116 UNIFY_ALLOW_NONE, explain_p))
8117 return 1;
8119 if (parm_variadic_p
8120 && unify_pack_expansion (tparms, targs,
8121 parmvec, argvec,
8122 DEDUCE_EXACT,
8123 /*subr=*/true, explain_p))
8124 return 1;
8127 return 0;
8130 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8131 template template parameters.
8133 Consider the example:
8134 template <class T> class A;
8135 template<template <class U> class TT> class B;
8137 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8138 and OUTER_ARGS contains A. */
8140 static int
8141 coerce_template_template_parms (tree parm_tmpl,
8142 tree arg_tmpl,
8143 tsubst_flags_t complain,
8144 tree in_decl,
8145 tree outer_args)
8147 int nparms, nargs, i;
8148 tree parm, arg;
8149 int variadic_p = 0;
8151 tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
8152 tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
8153 tree gen_arg_tmpl = most_general_template (arg_tmpl);
8154 tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
8156 nparms = TREE_VEC_LENGTH (parm_parms);
8157 nargs = TREE_VEC_LENGTH (arg_parms);
8159 if (flag_new_ttp)
8161 /* P0522R0: A template template-parameter P is at least as specialized as
8162 a template template-argument A if, given the following rewrite to two
8163 function templates, the function template corresponding to P is at
8164 least as specialized as the function template corresponding to A
8165 according to the partial ordering rules for function templates
8166 ([temp.func.order]). Given an invented class template X with the
8167 template parameter list of A (including default arguments):
8169 * Each of the two function templates has the same template parameters,
8170 respectively, as P or A.
8172 * Each function template has a single function parameter whose type is
8173 a specialization of X with template arguments corresponding to the
8174 template parameters from the respective function template where, for
8175 each template parameter PP in the template parameter list of the
8176 function template, a corresponding template argument AA is formed. If
8177 PP declares a parameter pack, then AA is the pack expansion
8178 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8180 If the rewrite produces an invalid type, then P is not at least as
8181 specialized as A. */
8183 /* So coerce P's args to apply to A's parms, and then deduce between A's
8184 args and the converted args. If that succeeds, A is at least as
8185 specialized as P, so they match.*/
8186 processing_template_decl_sentinel ptds (/*reset*/false);
8187 ++processing_template_decl;
8189 tree pargs = template_parms_level_to_args (parm_parms);
8191 /* PARM and ARG might be at different template depths, and we want to
8192 pass the right additional levels of args when coercing PARGS to
8193 ARG_PARMS in case we need to do any substitution into non-type
8194 template parameter types.
8196 OUTER_ARGS are not the right outer levels in this case, as they are
8197 the args we're building up for PARM, and for the coercion we want the
8198 args for ARG. If DECL_CONTEXT isn't set for a template template
8199 parameter, we can assume that it's in the current scope. */
8200 tree ctx = DECL_CONTEXT (arg_tmpl);
8201 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8202 ctx = current_scope ();
8203 tree scope_args = NULL_TREE;
8204 if (tree tinfo = get_template_info (ctx))
8205 scope_args = TI_ARGS (tinfo);
8206 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8208 int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
8209 int scope_depth = TMPL_ARGS_DEPTH (scope_args);
8210 tree full_pargs = make_tree_vec (level + 1);
8212 /* Only use as many levels from the scope as needed
8213 (excluding the level of ARG). */
8214 for (int i = 0; i < level - 1; ++i)
8215 if (i < scope_depth)
8216 TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
8217 else
8218 TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
8220 /* Add the arguments that appear at the levels of ARG. */
8221 tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
8222 adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
8223 TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
8225 TREE_VEC_ELT (full_pargs, level) = pargs;
8226 pargs = full_pargs;
8228 else
8229 pargs = add_to_template_args (scope_args, pargs);
8231 pargs = coerce_template_parms (gen_arg_parms, pargs,
8232 NULL_TREE, tf_none);
8233 if (pargs != error_mark_node)
8235 tree targs = make_tree_vec (nargs);
8236 tree aargs = template_parms_level_to_args (arg_parms);
8237 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8238 /*explain*/false))
8239 return 1;
8243 /* Determine whether we have a parameter pack at the end of the
8244 template template parameter's template parameter list. */
8245 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8247 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8249 if (error_operand_p (parm))
8250 return 0;
8252 switch (TREE_CODE (parm))
8254 case TEMPLATE_DECL:
8255 case TYPE_DECL:
8256 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8257 variadic_p = 1;
8258 break;
8260 case PARM_DECL:
8261 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8262 variadic_p = 1;
8263 break;
8265 default:
8266 gcc_unreachable ();
8270 if (nargs != nparms
8271 && !(variadic_p && nargs >= nparms - 1))
8272 return 0;
8274 /* Check all of the template parameters except the parameter pack at
8275 the end (if any). */
8276 for (i = 0; i < nparms - variadic_p; ++i)
8278 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8279 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8280 continue;
8282 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8283 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8285 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8286 outer_args))
8287 return 0;
8291 if (variadic_p)
8293 /* Check each of the template parameters in the template
8294 argument against the template parameter pack at the end of
8295 the template template parameter. */
8296 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8297 return 0;
8299 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8301 for (; i < nargs; ++i)
8303 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8304 continue;
8306 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8308 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8309 outer_args))
8310 return 0;
8314 return 1;
8317 /* Verifies that the deduced template arguments (in TARGS) for the
8318 template template parameters (in TPARMS) represent valid bindings,
8319 by comparing the template parameter list of each template argument
8320 to the template parameter list of its corresponding template
8321 template parameter, in accordance with DR150. This
8322 routine can only be called after all template arguments have been
8323 deduced. It will return TRUE if all of the template template
8324 parameter bindings are okay, FALSE otherwise. */
8325 bool
8326 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8328 int i, ntparms = TREE_VEC_LENGTH (tparms);
8329 bool ret = true;
8331 /* We're dealing with template parms in this process. */
8332 ++processing_template_decl;
8334 targs = INNERMOST_TEMPLATE_ARGS (targs);
8336 for (i = 0; i < ntparms; ++i)
8338 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8339 tree targ = TREE_VEC_ELT (targs, i);
8341 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8343 tree packed_args = NULL_TREE;
8344 int idx, len = 1;
8346 if (ARGUMENT_PACK_P (targ))
8348 /* Look inside the argument pack. */
8349 packed_args = ARGUMENT_PACK_ARGS (targ);
8350 len = TREE_VEC_LENGTH (packed_args);
8353 for (idx = 0; idx < len; ++idx)
8355 if (packed_args)
8356 /* Extract the next argument from the argument
8357 pack. */
8358 targ = TREE_VEC_ELT (packed_args, idx);
8360 if (PACK_EXPANSION_P (targ))
8361 /* Look at the pattern of the pack expansion. */
8362 targ = PACK_EXPANSION_PATTERN (targ);
8364 /* Extract the template parameters from the template
8365 argument. */
8366 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8367 targ = TYPE_NAME (targ);
8369 /* Verify that we can coerce the template template
8370 parameters from the template argument to the template
8371 parameter. This requires an exact match. */
8372 if (TREE_CODE (targ) == TEMPLATE_DECL
8373 && !coerce_template_template_parms
8374 (tparm,
8375 targ,
8376 tf_none,
8377 tparm,
8378 targs))
8380 ret = false;
8381 goto out;
8387 out:
8389 --processing_template_decl;
8390 return ret;
8393 /* Since type attributes aren't mangled, we need to strip them from
8394 template type arguments. */
8396 tree
8397 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8399 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8400 return arg;
8401 bool removed_attributes = false;
8402 tree canon = strip_typedefs (arg, &removed_attributes);
8403 if (removed_attributes
8404 && (complain & tf_warning))
8405 warning (OPT_Wignored_attributes,
8406 "ignoring attributes on template argument %qT", arg);
8407 return canon;
8410 /* And from inside dependent non-type arguments like sizeof(Type). */
8412 static tree
8413 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8415 if (!arg || arg == error_mark_node)
8416 return arg;
8417 bool removed_attributes = false;
8418 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8419 if (removed_attributes
8420 && (complain & tf_warning))
8421 warning (OPT_Wignored_attributes,
8422 "ignoring attributes in template argument %qE", arg);
8423 return canon;
8426 /* A template declaration can be substituted for a constrained
8427 template template parameter only when the argument is no more
8428 constrained than the parameter. */
8430 static bool
8431 is_compatible_template_arg (tree parm, tree arg, tree args)
8433 tree parm_cons = get_constraints (parm);
8435 /* For now, allow constrained template template arguments
8436 and unconstrained template template parameters. */
8437 if (parm_cons == NULL_TREE)
8438 return true;
8440 /* If the template parameter is constrained, we need to rewrite its
8441 constraints in terms of the ARG's template parameters. This ensures
8442 that all of the template parameter types will have the same depth.
8444 Note that this is only valid when coerce_template_template_parm is
8445 true for the innermost template parameters of PARM and ARG. In other
8446 words, because coercion is successful, this conversion will be valid. */
8447 tree new_args = NULL_TREE;
8448 if (parm_cons)
8450 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8451 new_args = template_parms_level_to_args (aparms);
8452 new_args = add_to_template_args (args, new_args);
8453 ++processing_template_decl;
8454 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8455 tf_none, NULL_TREE);
8456 --processing_template_decl;
8457 if (parm_cons == error_mark_node)
8458 return false;
8461 return weakly_subsumes (parm_cons, arg);
8464 // Convert a placeholder argument into a binding to the original
8465 // parameter. The original parameter is saved as the TREE_TYPE of
8466 // ARG.
8467 static inline tree
8468 convert_wildcard_argument (tree parm, tree arg)
8470 TREE_TYPE (arg) = parm;
8471 return arg;
8474 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8475 because one of them is dependent. But we need to represent the
8476 conversion for the benefit of cp_tree_equal. */
8478 static tree
8479 maybe_convert_nontype_argument (tree type, tree arg, bool force)
8481 /* Auto parms get no conversion. */
8482 if (type_uses_auto (type))
8483 return arg;
8484 /* ??? Do we need to push the IMPLICIT_CONV_EXPR into the pack expansion?
8485 That would complicate other things, and it doesn't seem necessary. */
8486 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
8487 return arg;
8488 /* We don't need or want to add this conversion now if we're going to use the
8489 argument for deduction. */
8490 if (!value_dependent_expression_p (arg))
8491 force = false;
8492 else if (!force)
8493 return arg;
8495 type = cv_unqualified (type);
8496 tree argtype = TREE_TYPE (arg);
8497 if (argtype && same_type_p (type, argtype))
8498 return arg;
8500 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8501 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8502 IMPLICIT_CONV_EXPR_FORCED (arg) = force;
8503 return arg;
8506 /* Convert the indicated template ARG as necessary to match the
8507 indicated template PARM. Returns the converted ARG, or
8508 error_mark_node if the conversion was unsuccessful. Error and
8509 warning messages are issued under control of COMPLAIN. This
8510 conversion is for the Ith parameter in the parameter list. ARGS is
8511 the full set of template arguments deduced so far. */
8513 static tree
8514 convert_template_argument (tree parm,
8515 tree arg,
8516 tree args,
8517 tsubst_flags_t complain,
8518 int i,
8519 tree in_decl)
8521 tree orig_arg;
8522 tree val;
8523 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8525 if (parm == error_mark_node || error_operand_p (arg))
8526 return error_mark_node;
8528 /* Trivially convert placeholders. */
8529 if (TREE_CODE (arg) == WILDCARD_DECL)
8530 return convert_wildcard_argument (parm, arg);
8532 if (arg == any_targ_node)
8533 return arg;
8535 if (TREE_CODE (arg) == TREE_LIST
8536 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8538 /* The template argument was the name of some
8539 member function. That's usually
8540 invalid, but static members are OK. In any
8541 case, grab the underlying fields/functions
8542 and issue an error later if required. */
8543 TREE_TYPE (arg) = unknown_type_node;
8546 orig_arg = arg;
8548 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8549 requires_type = (TREE_CODE (parm) == TYPE_DECL
8550 || requires_tmpl_type);
8552 /* When determining whether an argument pack expansion is a template,
8553 look at the pattern. */
8554 if (PACK_EXPANSION_P (arg))
8555 arg = PACK_EXPANSION_PATTERN (arg);
8557 /* Deal with an injected-class-name used as a template template arg. */
8558 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8560 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8561 if (TREE_CODE (t) == TEMPLATE_DECL)
8563 if (cxx_dialect >= cxx11)
8564 /* OK under DR 1004. */;
8565 else if (complain & tf_warning_or_error)
8566 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8567 " used as template template argument", TYPE_NAME (arg));
8568 else if (flag_pedantic_errors)
8569 t = arg;
8571 arg = t;
8575 is_tmpl_type =
8576 ((TREE_CODE (arg) == TEMPLATE_DECL
8577 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8578 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8579 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8580 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8582 if (is_tmpl_type
8583 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8584 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8585 arg = TYPE_STUB_DECL (arg);
8587 is_type = TYPE_P (arg) || is_tmpl_type;
8589 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8590 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8592 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8594 if (complain & tf_error)
8595 error ("invalid use of destructor %qE as a type", orig_arg);
8596 return error_mark_node;
8599 permerror (input_location,
8600 "to refer to a type member of a template parameter, "
8601 "use %<typename %E%>", orig_arg);
8603 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8604 TREE_OPERAND (arg, 1),
8605 typename_type,
8606 complain);
8607 arg = orig_arg;
8608 is_type = 1;
8610 if (is_type != requires_type)
8612 if (in_decl)
8614 if (complain & tf_error)
8616 error ("type/value mismatch at argument %d in template "
8617 "parameter list for %qD",
8618 i + 1, in_decl);
8619 if (is_type)
8621 /* The template argument is a type, but we're expecting
8622 an expression. */
8623 inform (input_location,
8624 " expected a constant of type %qT, got %qT",
8625 TREE_TYPE (parm),
8626 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8627 /* [temp.arg]/2: "In a template-argument, an ambiguity
8628 between a type-id and an expression is resolved to a
8629 type-id, regardless of the form of the corresponding
8630 template-parameter." So give the user a clue. */
8631 if (TREE_CODE (arg) == FUNCTION_TYPE)
8632 inform (input_location, " ambiguous template argument "
8633 "for non-type template parameter is treated as "
8634 "function type");
8636 else if (requires_tmpl_type)
8637 inform (input_location,
8638 " expected a class template, got %qE", orig_arg);
8639 else
8640 inform (input_location,
8641 " expected a type, got %qE", orig_arg);
8644 return error_mark_node;
8646 if (is_tmpl_type ^ requires_tmpl_type)
8648 if (in_decl && (complain & tf_error))
8650 error ("type/value mismatch at argument %d in template "
8651 "parameter list for %qD",
8652 i + 1, in_decl);
8653 if (is_tmpl_type)
8654 inform (input_location,
8655 " expected a type, got %qT", DECL_NAME (arg));
8656 else
8657 inform (input_location,
8658 " expected a class template, got %qT", orig_arg);
8660 return error_mark_node;
8663 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8664 /* We already did the appropriate conversion when packing args. */
8665 val = orig_arg;
8666 else if (is_type)
8668 if (requires_tmpl_type)
8670 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8671 /* The number of argument required is not known yet.
8672 Just accept it for now. */
8673 val = orig_arg;
8674 else
8676 /* Strip alias templates that are equivalent to another
8677 template. */
8678 arg = get_underlying_template (arg);
8680 if (coerce_template_template_parms (parm, arg,
8681 complain, in_decl,
8682 args))
8684 val = arg;
8686 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8687 TEMPLATE_DECL. */
8688 if (val != error_mark_node)
8690 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8691 val = TREE_TYPE (val);
8692 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8693 val = make_pack_expansion (val, complain);
8696 else
8698 if (in_decl && (complain & tf_error))
8700 error ("type/value mismatch at argument %d in "
8701 "template parameter list for %qD",
8702 i + 1, in_decl);
8703 inform (input_location,
8704 " expected a template of type %qD, got %qT",
8705 parm, orig_arg);
8708 val = error_mark_node;
8711 // Check that the constraints are compatible before allowing the
8712 // substitution.
8713 if (val != error_mark_node)
8714 if (!is_compatible_template_arg (parm, arg, args))
8716 if (in_decl && (complain & tf_error))
8718 error ("constraint mismatch at argument %d in "
8719 "template parameter list for %qD",
8720 i + 1, in_decl);
8721 inform (input_location, " expected %qD but got %qD",
8722 parm, arg);
8724 val = error_mark_node;
8728 else
8729 val = orig_arg;
8730 /* We only form one instance of each template specialization.
8731 Therefore, if we use a non-canonical variant (i.e., a
8732 typedef), any future messages referring to the type will use
8733 the typedef, which is confusing if those future uses do not
8734 themselves also use the typedef. */
8735 if (TYPE_P (val))
8736 val = canonicalize_type_argument (val, complain);
8738 else
8740 tree t = TREE_TYPE (parm);
8742 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8743 > TMPL_ARGS_DEPTH (args))
8744 /* We don't have enough levels of args to do any substitution. This
8745 can happen in the context of -fnew-ttp-matching. */;
8746 else if (tree a = type_uses_auto (t))
8748 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8749 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8750 if (t == error_mark_node)
8751 return error_mark_node;
8753 else
8754 t = tsubst (t, args, complain, in_decl);
8756 /* Perform array-to-pointer and function-to-pointer conversion
8757 as per [temp.param]/10. */
8758 t = type_decays_to (t);
8760 if (invalid_nontype_parm_type_p (t, complain))
8761 return error_mark_node;
8763 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8764 this non-type template parameter, as per [temp.param]/6. */
8765 t = cv_unqualified (t);
8767 if (t != TREE_TYPE (parm))
8768 t = canonicalize_type_argument (t, complain);
8770 /* We need to handle arguments for alias or concept templates
8771 differently: we need to force building an IMPLICIT_CONV_EXPR, because
8772 these arguments are going to be substituted directly into the
8773 dependent type; they might not get another chance at
8774 convert_nontype_argument. But if the argument ends up here again for
8775 a template that isn't one of those, remove the conversion for
8776 consistency between naming the same dependent type directly or through
8777 an alias. */
8778 bool force_conv = in_decl && (DECL_ALIAS_TEMPLATE_P (in_decl)
8779 || concept_definition_p (in_decl));
8780 if (!force_conv
8781 && TREE_CODE (orig_arg) == IMPLICIT_CONV_EXPR
8782 && IMPLICIT_CONV_EXPR_FORCED (orig_arg)
8783 && same_type_p (TREE_TYPE (orig_arg), t))
8784 orig_arg = TREE_OPERAND (orig_arg, 0);
8786 if (!type_dependent_expression_p (orig_arg)
8787 && !uses_template_parms (t))
8788 /* We used to call digest_init here. However, digest_init
8789 will report errors, which we don't want when complain
8790 is zero. More importantly, digest_init will try too
8791 hard to convert things: for example, `0' should not be
8792 converted to pointer type at this point according to
8793 the standard. Accepting this is not merely an
8794 extension, since deciding whether or not these
8795 conversions can occur is part of determining which
8796 function template to call, or whether a given explicit
8797 argument specification is valid. */
8798 val = convert_nontype_argument (t, orig_arg, complain);
8799 else
8801 val = canonicalize_expr_argument (orig_arg, complain);
8802 val = maybe_convert_nontype_argument (t, val, force_conv);
8805 if (val == NULL_TREE)
8806 val = error_mark_node;
8807 else if (val == error_mark_node && (complain & tf_error))
8808 error_at (cp_expr_loc_or_input_loc (orig_arg),
8809 "could not convert template argument %qE from %qT to %qT",
8810 orig_arg, TREE_TYPE (orig_arg), t);
8812 if (INDIRECT_REF_P (val))
8814 /* Reject template arguments that are references to built-in
8815 functions with no library fallbacks. */
8816 const_tree inner = TREE_OPERAND (val, 0);
8817 const_tree innertype = TREE_TYPE (inner);
8818 if (innertype
8819 && TYPE_REF_P (innertype)
8820 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8821 && TREE_OPERAND_LENGTH (inner) > 0
8822 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8823 return error_mark_node;
8826 if (TREE_CODE (val) == SCOPE_REF)
8828 /* Strip typedefs from the SCOPE_REF. */
8829 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8830 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8831 complain);
8832 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8833 QUALIFIED_NAME_IS_TEMPLATE (val));
8837 return val;
8840 /* Coerces the remaining template arguments in INNER_ARGS (from
8841 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8842 Returns the coerced argument pack. PARM_IDX is the position of this
8843 parameter in the template parameter list. ARGS is the original
8844 template argument list. */
8845 static tree
8846 coerce_template_parameter_pack (tree parms,
8847 int parm_idx,
8848 tree args,
8849 tree inner_args,
8850 int arg_idx,
8851 tree new_args,
8852 int* lost,
8853 tree in_decl,
8854 tsubst_flags_t complain)
8856 tree parm = TREE_VEC_ELT (parms, parm_idx);
8857 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8858 tree packed_args;
8859 tree argument_pack;
8860 tree packed_parms = NULL_TREE;
8862 if (arg_idx > nargs)
8863 arg_idx = nargs;
8865 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8867 /* When the template parameter is a non-type template parameter pack
8868 or template template parameter pack whose type or template
8869 parameters use parameter packs, we know exactly how many arguments
8870 we are looking for. Build a vector of the instantiated decls for
8871 these template parameters in PACKED_PARMS. */
8872 /* We can't use make_pack_expansion here because it would interpret a
8873 _DECL as a use rather than a declaration. */
8874 tree decl = TREE_VALUE (parm);
8875 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8876 PACK_EXPANSION_PATTERN (exp) = decl;
8877 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8878 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8880 TREE_VEC_LENGTH (args)--;
8881 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8882 TREE_VEC_LENGTH (args)++;
8884 if (packed_parms == error_mark_node)
8885 return error_mark_node;
8887 /* If we're doing a partial instantiation of a member template,
8888 verify that all of the types used for the non-type
8889 template parameter pack are, in fact, valid for non-type
8890 template parameters. */
8891 if (arg_idx < nargs
8892 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8894 int j, len = TREE_VEC_LENGTH (packed_parms);
8895 for (j = 0; j < len; ++j)
8897 tree t = TREE_VEC_ELT (packed_parms, j);
8898 if (TREE_CODE (t) == PARM_DECL
8899 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8900 return error_mark_node;
8902 /* We don't know how many args we have yet, just
8903 use the unconverted ones for now. */
8904 return NULL_TREE;
8907 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8909 /* Check if we have a placeholder pack, which indicates we're
8910 in the context of a introduction list. In that case we want
8911 to match this pack to the single placeholder. */
8912 else if (arg_idx < nargs
8913 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8914 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8916 nargs = arg_idx + 1;
8917 packed_args = make_tree_vec (1);
8919 else
8920 packed_args = make_tree_vec (nargs - arg_idx);
8922 /* Convert the remaining arguments, which will be a part of the
8923 parameter pack "parm". */
8924 int first_pack_arg = arg_idx;
8925 for (; arg_idx < nargs; ++arg_idx)
8927 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8928 tree actual_parm = TREE_VALUE (parm);
8929 int pack_idx = arg_idx - first_pack_arg;
8931 if (packed_parms)
8933 /* Once we've packed as many args as we have types, stop. */
8934 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8935 break;
8936 else if (PACK_EXPANSION_P (arg))
8937 /* We don't know how many args we have yet, just
8938 use the unconverted ones for now. */
8939 return NULL_TREE;
8940 else
8941 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8944 if (arg == error_mark_node)
8946 if (complain & tf_error)
8947 error ("template argument %d is invalid", arg_idx + 1);
8949 else
8950 arg = convert_template_argument (actual_parm,
8951 arg, new_args, complain, parm_idx,
8952 in_decl);
8953 if (arg == error_mark_node)
8954 (*lost)++;
8955 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8958 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8959 && TREE_VEC_LENGTH (packed_args) > 0)
8961 if (complain & tf_error)
8962 error ("wrong number of template arguments (%d, should be %d)",
8963 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8964 return error_mark_node;
8967 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8968 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8969 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8970 else
8972 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8973 TREE_CONSTANT (argument_pack) = 1;
8976 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8977 if (CHECKING_P)
8978 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8979 TREE_VEC_LENGTH (packed_args));
8980 return argument_pack;
8983 /* Returns the number of pack expansions in the template argument vector
8984 ARGS. */
8986 static int
8987 pack_expansion_args_count (tree args)
8989 int i;
8990 int count = 0;
8991 if (args)
8992 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8994 tree elt = TREE_VEC_ELT (args, i);
8995 if (elt && PACK_EXPANSION_P (elt))
8996 ++count;
8998 return count;
9001 /* Convert all template arguments to their appropriate types, and
9002 return a vector containing the innermost resulting template
9003 arguments. If any error occurs, return error_mark_node. Error and
9004 warning messages are issued under control of COMPLAIN.
9006 If PARMS represents all template parameters levels, this function
9007 returns a vector of vectors representing all the resulting argument
9008 levels. Note that in this case, only the innermost arguments are
9009 coerced because the outermost ones are supposed to have been coerced
9010 already. Otherwise, if PARMS represents only (the innermost) vector
9011 of parameters, this function returns a vector containing just the
9012 innermost resulting arguments.
9014 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
9015 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
9016 arguments not specified in ARGS must have default arguments which
9017 we'll use to fill in ARGS. */
9019 tree
9020 coerce_template_parms (tree parms,
9021 tree args,
9022 tree in_decl,
9023 tsubst_flags_t complain,
9024 bool require_all_args /* = true */)
9026 int nparms, nargs, parm_idx, arg_idx, lost = 0;
9027 tree orig_inner_args;
9028 tree inner_args;
9030 /* When used as a boolean value, indicates whether this is a
9031 variadic template parameter list. Since it's an int, we can also
9032 subtract it from nparms to get the number of non-variadic
9033 parameters. */
9034 int variadic_p = 0;
9035 int variadic_args_p = 0;
9036 int post_variadic_parms = 0;
9038 /* Adjustment to nparms for fixed parameter packs. */
9039 int fixed_pack_adjust = 0;
9040 int fixed_packs = 0;
9041 int missing = 0;
9043 /* Likewise for parameters with default arguments. */
9044 int default_p = 0;
9046 if (args == error_mark_node)
9047 return error_mark_node;
9049 bool return_full_args = false;
9050 if (TREE_CODE (parms) == TREE_LIST)
9052 if (TMPL_PARMS_DEPTH (parms) > 1)
9054 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
9055 return_full_args = true;
9057 parms = INNERMOST_TEMPLATE_PARMS (parms);
9060 nparms = TREE_VEC_LENGTH (parms);
9062 /* Determine if there are any parameter packs or default arguments. */
9063 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
9065 tree parm = TREE_VEC_ELT (parms, parm_idx);
9066 if (variadic_p)
9067 ++post_variadic_parms;
9068 if (template_parameter_pack_p (TREE_VALUE (parm)))
9069 ++variadic_p;
9070 if (TREE_PURPOSE (parm))
9071 ++default_p;
9074 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
9075 /* If there are no parameters that follow a parameter pack, we need to
9076 expand any argument packs so that we can deduce a parameter pack from
9077 some non-packed args followed by an argument pack, as in variadic85.C.
9078 If there are such parameters, we need to leave argument packs intact
9079 so the arguments are assigned properly. This can happen when dealing
9080 with a nested class inside a partial specialization of a class
9081 template, as in variadic92.C, or when deducing a template parameter pack
9082 from a sub-declarator, as in variadic114.C. */
9083 if (!post_variadic_parms)
9084 inner_args = expand_template_argument_pack (inner_args);
9086 /* Count any pack expansion args. */
9087 variadic_args_p = pack_expansion_args_count (inner_args);
9089 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
9090 if ((nargs - variadic_args_p > nparms && !variadic_p)
9091 || (nargs < nparms - variadic_p
9092 && require_all_args
9093 && !variadic_args_p
9094 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
9095 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
9097 bad_nargs:
9098 if (complain & tf_error)
9100 if (variadic_p || default_p)
9102 nparms -= variadic_p + default_p;
9103 error ("wrong number of template arguments "
9104 "(%d, should be at least %d)", nargs, nparms);
9106 else
9107 error ("wrong number of template arguments "
9108 "(%d, should be %d)", nargs, nparms);
9110 if (in_decl)
9111 inform (DECL_SOURCE_LOCATION (in_decl),
9112 "provided for %qD", in_decl);
9115 return error_mark_node;
9117 /* We can't pass a pack expansion to a non-pack parameter of an alias
9118 template (DR 1430). */
9119 else if (in_decl
9120 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9121 || concept_definition_p (in_decl))
9122 && variadic_args_p
9123 && nargs - variadic_args_p < nparms - variadic_p)
9125 if (complain & tf_error)
9127 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9129 tree arg = TREE_VEC_ELT (inner_args, i);
9130 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9132 if (PACK_EXPANSION_P (arg)
9133 && !template_parameter_pack_p (parm))
9135 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9136 error_at (location_of (arg),
9137 "pack expansion argument for non-pack parameter "
9138 "%qD of alias template %qD", parm, in_decl);
9139 else
9140 error_at (location_of (arg),
9141 "pack expansion argument for non-pack parameter "
9142 "%qD of concept %qD", parm, in_decl);
9143 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9144 goto found;
9147 gcc_unreachable ();
9148 found:;
9150 return error_mark_node;
9153 /* We need to evaluate the template arguments, even though this
9154 template-id may be nested within a "sizeof". */
9155 cp_evaluated ev;
9157 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9158 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9159 int pack_adjust = 0;
9160 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9162 tree arg;
9163 tree parm;
9165 /* Get the Ith template parameter. */
9166 parm = TREE_VEC_ELT (parms, parm_idx);
9168 if (parm == error_mark_node)
9170 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9171 continue;
9174 /* Calculate the next argument. */
9175 if (arg_idx < nargs)
9176 arg = TREE_VEC_ELT (inner_args, arg_idx);
9177 else
9178 arg = NULL_TREE;
9180 if (template_parameter_pack_p (TREE_VALUE (parm))
9181 && (arg || require_all_args || !(complain & tf_partial))
9182 && !(arg && ARGUMENT_PACK_P (arg)))
9184 /* Some arguments will be placed in the
9185 template parameter pack PARM. */
9186 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9187 inner_args, arg_idx,
9188 new_args, &lost,
9189 in_decl, complain);
9191 if (arg == NULL_TREE)
9193 /* We don't know how many args we have yet, just use the
9194 unconverted (and still packed) ones for now. */
9195 new_inner_args = orig_inner_args;
9196 arg_idx = nargs;
9197 break;
9200 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9202 /* Store this argument. */
9203 if (arg == error_mark_node)
9205 lost++;
9206 /* We are done with all of the arguments. */
9207 arg_idx = nargs;
9208 break;
9210 else
9212 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9213 arg_idx += pack_adjust;
9214 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9216 ++fixed_packs;
9217 fixed_pack_adjust += pack_adjust;
9221 continue;
9223 else if (arg)
9225 if (PACK_EXPANSION_P (arg))
9227 /* "If every valid specialization of a variadic template
9228 requires an empty template parameter pack, the template is
9229 ill-formed, no diagnostic required." So check that the
9230 pattern works with this parameter. */
9231 tree pattern = PACK_EXPANSION_PATTERN (arg);
9232 tree conv = convert_template_argument (TREE_VALUE (parm),
9233 pattern, new_args,
9234 complain, parm_idx,
9235 in_decl);
9236 if (conv == error_mark_node)
9238 if (complain & tf_error)
9239 inform (input_location, "so any instantiation with a "
9240 "non-empty parameter pack would be ill-formed");
9241 ++lost;
9243 else if (TYPE_P (conv) && !TYPE_P (pattern))
9244 /* Recover from missing typename. */
9245 TREE_VEC_ELT (inner_args, arg_idx)
9246 = make_pack_expansion (conv, complain);
9248 /* We don't know how many args we have yet, just
9249 use the unconverted ones for now. */
9250 new_inner_args = inner_args;
9251 arg_idx = nargs;
9252 break;
9255 else if (require_all_args)
9257 /* There must be a default arg in this case. */
9258 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9259 complain, in_decl);
9260 /* The position of the first default template argument,
9261 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9262 Record that. */
9263 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9264 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9265 arg_idx - pack_adjust);
9267 else
9268 break;
9270 if (arg == error_mark_node)
9272 if (complain & tf_error)
9273 error ("template argument %d is invalid", arg_idx + 1);
9275 else if (!arg)
9277 /* This can occur if there was an error in the template
9278 parameter list itself (which we would already have
9279 reported) that we are trying to recover from, e.g., a class
9280 template with a parameter list such as
9281 template<typename..., typename> (cpp0x/variadic150.C). */
9282 ++lost;
9284 /* This can also happen with a fixed parameter pack (71834). */
9285 if (arg_idx >= nargs)
9286 ++missing;
9288 else
9289 arg = convert_template_argument (TREE_VALUE (parm),
9290 arg, new_args, complain,
9291 parm_idx, in_decl);
9293 if (arg == error_mark_node)
9294 lost++;
9296 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9299 if (missing || arg_idx < nargs - variadic_args_p)
9301 /* If we had fixed parameter packs, we didn't know how many arguments we
9302 actually needed earlier; now we do. */
9303 nparms += fixed_pack_adjust;
9304 variadic_p -= fixed_packs;
9305 goto bad_nargs;
9308 if (arg_idx < nargs)
9310 /* We had some pack expansion arguments that will only work if the packs
9311 are empty, but wait until instantiation time to complain.
9312 See variadic-ttp3.C. */
9314 /* Except that we can't provide empty packs to alias templates or
9315 concepts when there are no corresponding parameters. Basically,
9316 we can get here with this:
9318 template<typename T> concept C = true;
9320 template<typename... Args>
9321 requires C<Args...>
9322 void f();
9324 When parsing C<Args...>, we try to form a concept check of
9325 C<?, Args...>. Without the extra check for substituting an empty
9326 pack past the last parameter, we can accept the check as valid.
9328 FIXME: This may be valid for alias templates (but I doubt it).
9330 FIXME: The error could be better also. */
9331 if (in_decl && concept_definition_p (in_decl))
9333 if (complain & tf_error)
9334 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9335 "too many arguments");
9336 return error_mark_node;
9339 int len = nparms + (nargs - arg_idx);
9340 tree args = make_tree_vec (len);
9341 int i = 0;
9342 for (; i < nparms; ++i)
9343 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9344 for (; i < len; ++i, ++arg_idx)
9345 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9346 arg_idx - pack_adjust);
9347 new_inner_args = args;
9350 if (lost)
9352 gcc_assert (!(complain & tf_error) || seen_error ());
9353 return error_mark_node;
9356 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9357 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9358 TREE_VEC_LENGTH (new_inner_args));
9360 return return_full_args ? new_args : new_inner_args;
9363 /* Returns true if T is a wrapper to make a C++20 template parameter
9364 object const. */
9366 static bool
9367 class_nttp_const_wrapper_p (tree t)
9369 if (cxx_dialect < cxx20)
9370 return false;
9371 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9372 && CP_TYPE_CONST_P (TREE_TYPE (t))
9373 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9376 /* Returns 1 if template args OT and NT are equivalent. */
9379 template_args_equal (tree ot, tree nt)
9381 if (nt == ot)
9382 return 1;
9383 if (nt == NULL_TREE || ot == NULL_TREE)
9384 return false;
9385 if (nt == any_targ_node || ot == any_targ_node)
9386 return true;
9388 if (class_nttp_const_wrapper_p (nt))
9389 nt = TREE_OPERAND (nt, 0);
9390 if (class_nttp_const_wrapper_p (ot))
9391 ot = TREE_OPERAND (ot, 0);
9393 /* DR 1558: Don't treat an alias template specialization with dependent
9394 arguments as equivalent to its underlying type when used as a template
9395 argument; we need them to be distinct so that we substitute into the
9396 specialization arguments at instantiation time. And aliases can't be
9397 equivalent without being ==, so we don't need to look any deeper.
9399 During partial ordering, however, we need to treat them normally so we can
9400 order uses of the same alias with different cv-qualification (79960). */
9401 auto cso = make_temp_override (comparing_dependent_aliases);
9402 if (!comparing_for_partial_ordering)
9403 ++comparing_dependent_aliases;
9405 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9406 /* For member templates */
9407 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9408 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9409 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9410 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9411 PACK_EXPANSION_PATTERN (nt))
9412 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9413 PACK_EXPANSION_EXTRA_ARGS (nt)));
9414 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9415 return cp_tree_equal (ot, nt);
9416 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9417 gcc_unreachable ();
9418 else if (TYPE_P (nt) || TYPE_P (ot))
9420 if (!(TYPE_P (nt) && TYPE_P (ot)))
9421 return false;
9422 return same_type_p (ot, nt);
9424 else
9426 /* Try to treat a template non-type argument that has been converted
9427 to the parameter type as equivalent to one that hasn't yet. */
9428 for (enum tree_code code1 = TREE_CODE (ot);
9429 CONVERT_EXPR_CODE_P (code1)
9430 || code1 == NON_LVALUE_EXPR;
9431 code1 = TREE_CODE (ot))
9432 ot = TREE_OPERAND (ot, 0);
9434 for (enum tree_code code2 = TREE_CODE (nt);
9435 CONVERT_EXPR_CODE_P (code2)
9436 || code2 == NON_LVALUE_EXPR;
9437 code2 = TREE_CODE (nt))
9438 nt = TREE_OPERAND (nt, 0);
9440 return cp_tree_equal (ot, nt);
9444 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9445 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9446 NEWARG_PTR with the offending arguments if they are non-NULL. */
9448 bool
9449 comp_template_args (tree oldargs, tree newargs,
9450 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */)
9452 if (oldargs == newargs)
9453 return true;
9455 if (!oldargs || !newargs)
9456 return false;
9458 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9459 return false;
9461 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9463 tree nt = TREE_VEC_ELT (newargs, i);
9464 tree ot = TREE_VEC_ELT (oldargs, i);
9466 if (! template_args_equal (ot, nt))
9468 if (oldarg_ptr != NULL)
9469 *oldarg_ptr = ot;
9470 if (newarg_ptr != NULL)
9471 *newarg_ptr = nt;
9472 return false;
9475 return true;
9478 static bool
9479 comp_template_args_porder (tree oargs, tree nargs)
9481 ++comparing_for_partial_ordering;
9482 bool equal = comp_template_args (oargs, nargs);
9483 --comparing_for_partial_ordering;
9484 return equal;
9487 /* Implement a freelist interface for objects of type T.
9489 Head is a separate object, rather than a regular member, so that we
9490 can define it as a GTY deletable pointer, which is highly
9491 desirable. A data member could be declared that way, but then the
9492 containing object would implicitly get GTY((user)), which would
9493 prevent us from instantiating freelists as global objects.
9494 Although this way we can create freelist global objects, they're
9495 such thin wrappers that instantiating temporaries at every use
9496 loses nothing and saves permanent storage for the freelist object.
9498 Member functions next, anew, poison and reinit have default
9499 implementations that work for most of the types we're interested
9500 in, but if they don't work for some type, they should be explicitly
9501 specialized. See the comments before them for requirements, and
9502 the example specializations for the tree_list_freelist. */
9503 template <typename T>
9504 class freelist
9506 /* Return the next object in a chain. We could just do type
9507 punning, but if we access the object with its underlying type, we
9508 avoid strict-aliasing trouble. This needs only work between
9509 poison and reinit. */
9510 static T *&next (T *obj) { return obj->next; }
9512 /* Return a newly allocated, uninitialized or minimally-initialized
9513 object of type T. Any initialization performed by anew should
9514 either remain across the life of the object and the execution of
9515 poison, or be redone by reinit. */
9516 static T *anew () { return ggc_alloc<T> (); }
9518 /* Optionally scribble all over the bits holding the object, so that
9519 they become (mostly?) uninitialized memory. This is called while
9520 preparing to make the object part of the free list. */
9521 static void poison (T *obj) {
9522 T *p ATTRIBUTE_UNUSED = obj;
9523 T **q ATTRIBUTE_UNUSED = &next (obj);
9525 #ifdef ENABLE_GC_CHECKING
9526 /* Poison the data, to indicate the data is garbage. */
9527 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9528 memset (p, 0xa5, sizeof (*p));
9529 #endif
9530 /* Let valgrind know the object is free. */
9531 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9533 /* Let valgrind know the next portion of the object is available,
9534 but uninitialized. */
9535 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9538 /* Bring an object that underwent at least one lifecycle after anew
9539 and before the most recent free and poison, back to a usable
9540 state, reinitializing whatever is needed for it to be
9541 functionally equivalent to an object just allocated and returned
9542 by anew. This may poison or clear the next field, used by
9543 freelist housekeeping after poison was called. */
9544 static void reinit (T *obj) {
9545 T **q ATTRIBUTE_UNUSED = &next (obj);
9547 #ifdef ENABLE_GC_CHECKING
9548 memset (q, 0xa5, sizeof (*q));
9549 #endif
9550 /* Let valgrind know the entire object is available, but
9551 uninitialized. */
9552 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9555 /* Reference a GTY-deletable pointer that points to the first object
9556 in the free list proper. */
9557 T *&head;
9558 public:
9559 /* Construct a freelist object chaining objects off of HEAD. */
9560 freelist (T *&head) : head(head) {}
9562 /* Add OBJ to the free object list. The former head becomes OBJ's
9563 successor. */
9564 void free (T *obj)
9566 poison (obj);
9567 next (obj) = head;
9568 head = obj;
9571 /* Take an object from the free list, if one is available, or
9572 allocate a new one. Objects taken from the free list should be
9573 regarded as filled with garbage, except for bits that are
9574 configured to be preserved across free and alloc. */
9575 T *alloc ()
9577 if (head)
9579 T *obj = head;
9580 head = next (head);
9581 reinit (obj);
9582 return obj;
9584 else
9585 return anew ();
9589 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9590 want to allocate a TREE_LIST using the usual interface, and ensure
9591 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9592 build_tree_list logic in reinit, so this could go out of sync. */
9593 template <>
9594 inline tree &
9595 freelist<tree_node>::next (tree obj)
9597 return TREE_CHAIN (obj);
9599 template <>
9600 inline tree
9601 freelist<tree_node>::anew ()
9603 return build_tree_list (NULL, NULL);
9605 template <>
9606 inline void
9607 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9609 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9610 tree p ATTRIBUTE_UNUSED = obj;
9611 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9612 tree *q ATTRIBUTE_UNUSED = &next (obj);
9614 #ifdef ENABLE_GC_CHECKING
9615 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9617 /* Poison the data, to indicate the data is garbage. */
9618 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9619 memset (p, 0xa5, size);
9620 #endif
9621 /* Let valgrind know the object is free. */
9622 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9623 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9624 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9625 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9627 #ifdef ENABLE_GC_CHECKING
9628 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9629 /* Keep TREE_CHAIN functional. */
9630 TREE_SET_CODE (obj, TREE_LIST);
9631 #else
9632 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9633 #endif
9635 template <>
9636 inline void
9637 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9639 tree_common *c ATTRIBUTE_UNUSED = &obj->common;
9641 #ifdef ENABLE_GC_CHECKING
9642 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9643 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9644 memset (obj, 0, sizeof (tree_list));
9645 #endif
9647 /* Let valgrind know the entire object is available, but
9648 uninitialized. */
9649 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9651 #ifdef ENABLE_GC_CHECKING
9652 TREE_SET_CODE (obj, TREE_LIST);
9653 #else
9654 TREE_CHAIN (obj) = NULL_TREE;
9655 TREE_TYPE (obj) = NULL_TREE;
9656 #endif
9657 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (c, sizeof (*c)));
9660 /* Point to the first object in the TREE_LIST freelist. */
9661 static GTY((deletable)) tree tree_list_freelist_head;
9662 /* Return the/an actual TREE_LIST freelist. */
9663 static inline freelist<tree_node>
9664 tree_list_freelist ()
9666 return tree_list_freelist_head;
9669 /* Point to the first object in the tinst_level freelist. */
9670 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9671 /* Return the/an actual tinst_level freelist. */
9672 static inline freelist<tinst_level>
9673 tinst_level_freelist ()
9675 return tinst_level_freelist_head;
9678 /* Point to the first object in the pending_template freelist. */
9679 static GTY((deletable)) pending_template *pending_template_freelist_head;
9680 /* Return the/an actual pending_template freelist. */
9681 static inline freelist<pending_template>
9682 pending_template_freelist ()
9684 return pending_template_freelist_head;
9687 /* Build the TREE_LIST object out of a split list, store it
9688 permanently, and return it. */
9689 tree
9690 tinst_level::to_list ()
9692 gcc_assert (split_list_p ());
9693 tree ret = tree_list_freelist ().alloc ();
9694 TREE_PURPOSE (ret) = tldcl;
9695 TREE_VALUE (ret) = targs;
9696 tldcl = ret;
9697 targs = NULL;
9698 gcc_assert (tree_list_p ());
9699 return ret;
9702 const unsigned short tinst_level::refcount_infinity;
9704 /* Increment OBJ's refcount unless it is already infinite. */
9705 static tinst_level *
9706 inc_refcount_use (tinst_level *obj)
9708 if (obj && obj->refcount != tinst_level::refcount_infinity)
9709 ++obj->refcount;
9710 return obj;
9713 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9714 void
9715 tinst_level::free (tinst_level *obj)
9717 if (obj->tree_list_p ())
9718 tree_list_freelist ().free (obj->get_node ());
9719 tinst_level_freelist ().free (obj);
9722 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9723 OBJ's DECL and OBJ, and start over with the tinst_level object that
9724 used to be referenced by OBJ's NEXT. */
9725 static void
9726 dec_refcount_use (tinst_level *obj)
9728 while (obj
9729 && obj->refcount != tinst_level::refcount_infinity
9730 && !--obj->refcount)
9732 tinst_level *next = obj->next;
9733 tinst_level::free (obj);
9734 obj = next;
9738 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9739 and of the former PTR. Omitting the second argument is equivalent
9740 to passing (T*)NULL; this is allowed because passing the
9741 zero-valued integral constant NULL confuses type deduction and/or
9742 overload resolution. */
9743 template <typename T>
9744 static void
9745 set_refcount_ptr (T *& ptr, T *obj = NULL)
9747 T *save = ptr;
9748 ptr = inc_refcount_use (obj);
9749 dec_refcount_use (save);
9752 static void
9753 add_pending_template (tree d)
9755 tree ti = (TYPE_P (d)
9756 ? CLASSTYPE_TEMPLATE_INFO (d)
9757 : DECL_TEMPLATE_INFO (d));
9758 struct pending_template *pt;
9759 int level;
9761 if (TI_PENDING_TEMPLATE_FLAG (ti))
9762 return;
9764 /* We are called both from instantiate_decl, where we've already had a
9765 tinst_level pushed, and instantiate_template, where we haven't.
9766 Compensate. */
9767 gcc_assert (TREE_CODE (d) != TREE_LIST);
9768 level = !current_tinst_level
9769 || current_tinst_level->maybe_get_node () != d;
9771 if (level)
9772 push_tinst_level (d);
9774 pt = pending_template_freelist ().alloc ();
9775 pt->next = NULL;
9776 pt->tinst = NULL;
9777 set_refcount_ptr (pt->tinst, current_tinst_level);
9778 if (last_pending_template)
9779 last_pending_template->next = pt;
9780 else
9781 pending_templates = pt;
9783 last_pending_template = pt;
9785 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9787 if (level)
9788 pop_tinst_level ();
9792 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9793 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9794 documentation for TEMPLATE_ID_EXPR. */
9796 tree
9797 lookup_template_function (tree fns, tree arglist)
9799 if (fns == error_mark_node || arglist == error_mark_node)
9800 return error_mark_node;
9802 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9804 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9806 error ("%q#D is not a function template", fns);
9807 return error_mark_node;
9810 if (BASELINK_P (fns))
9812 fns = copy_node (fns);
9813 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9814 unknown_type_node,
9815 BASELINK_FUNCTIONS (fns),
9816 arglist);
9817 return fns;
9820 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9823 /* Within the scope of a template class S<T>, the name S gets bound
9824 (in build_self_reference) to a TYPE_DECL for the class, not a
9825 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9826 or one of its enclosing classes, and that type is a template,
9827 return the associated TEMPLATE_DECL. Otherwise, the original
9828 DECL is returned.
9830 Also handle the case when DECL is a TREE_LIST of ambiguous
9831 injected-class-names from different bases. */
9833 tree
9834 maybe_get_template_decl_from_type_decl (tree decl)
9836 if (decl == NULL_TREE)
9837 return decl;
9839 /* DR 176: A lookup that finds an injected-class-name (10.2
9840 [class.member.lookup]) can result in an ambiguity in certain cases
9841 (for example, if it is found in more than one base class). If all of
9842 the injected-class-names that are found refer to specializations of
9843 the same class template, and if the name is followed by a
9844 template-argument-list, the reference refers to the class template
9845 itself and not a specialization thereof, and is not ambiguous. */
9846 if (TREE_CODE (decl) == TREE_LIST)
9848 tree t, tmpl = NULL_TREE;
9849 for (t = decl; t; t = TREE_CHAIN (t))
9851 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9852 if (!tmpl)
9853 tmpl = elt;
9854 else if (tmpl != elt)
9855 break;
9857 if (tmpl && t == NULL_TREE)
9858 return tmpl;
9859 else
9860 return decl;
9863 return (decl != NULL_TREE
9864 && DECL_SELF_REFERENCE_P (decl)
9865 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9866 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9869 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9870 parameters, find the desired type.
9872 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9874 IN_DECL, if non-NULL, is the template declaration we are trying to
9875 instantiate.
9877 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9878 the class we are looking up.
9880 Issue error and warning messages under control of COMPLAIN.
9882 If the template class is really a local class in a template
9883 function, then the FUNCTION_CONTEXT is the function in which it is
9884 being instantiated.
9886 ??? Note that this function is currently called *twice* for each
9887 template-id: the first time from the parser, while creating the
9888 incomplete type (finish_template_type), and the second type during the
9889 real instantiation (instantiate_template_class). This is surely something
9890 that we want to avoid. It also causes some problems with argument
9891 coercion (see convert_nontype_argument for more information on this). */
9893 tree
9894 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9895 int entering_scope, tsubst_flags_t complain)
9897 auto_timevar tv (TV_TEMPLATE_INST);
9899 tree templ = NULL_TREE, parmlist;
9900 tree t;
9901 spec_entry **slot;
9902 spec_entry *entry;
9903 spec_entry elt;
9904 hashval_t hash;
9906 if (identifier_p (d1))
9908 tree value = innermost_non_namespace_value (d1);
9909 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9910 templ = value;
9911 else
9913 if (context)
9914 push_decl_namespace (context);
9915 templ = lookup_name (d1);
9916 templ = maybe_get_template_decl_from_type_decl (templ);
9917 if (context)
9918 pop_decl_namespace ();
9921 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9923 tree type = TREE_TYPE (d1);
9925 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9926 an implicit typename for the second A. Deal with it. */
9927 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9928 type = TREE_TYPE (type);
9930 if (CLASSTYPE_TEMPLATE_INFO (type))
9932 templ = CLASSTYPE_TI_TEMPLATE (type);
9933 d1 = DECL_NAME (templ);
9936 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9937 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9939 templ = TYPE_TI_TEMPLATE (d1);
9940 d1 = DECL_NAME (templ);
9942 else if (DECL_TYPE_TEMPLATE_P (d1))
9944 templ = d1;
9945 d1 = DECL_NAME (templ);
9947 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9949 templ = d1;
9950 d1 = DECL_NAME (templ);
9953 /* Issue an error message if we didn't find a template. */
9954 if (! templ)
9956 if (complain & tf_error)
9957 error ("%qT is not a template", d1);
9958 return error_mark_node;
9961 if (TREE_CODE (templ) != TEMPLATE_DECL
9962 /* Make sure it's a user visible template, if it was named by
9963 the user. */
9964 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9965 && !PRIMARY_TEMPLATE_P (templ)))
9967 if (complain & tf_error)
9969 error ("non-template type %qT used as a template", d1);
9970 if (in_decl)
9971 error ("for template declaration %q+D", in_decl);
9973 return error_mark_node;
9976 complain &= ~tf_user;
9978 /* An alias that just changes the name of a template is equivalent to the
9979 other template, so if any of the arguments are pack expansions, strip
9980 the alias to avoid problems with a pack expansion passed to a non-pack
9981 alias template parameter (DR 1430). */
9982 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9983 templ = get_underlying_template (templ);
9985 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9987 tree parm;
9988 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9989 if (arglist2 == error_mark_node
9990 || (!uses_template_parms (arglist2)
9991 && check_instantiated_args (templ, arglist2, complain)))
9992 return error_mark_node;
9994 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9995 return parm;
9997 else
9999 tree template_type = TREE_TYPE (templ);
10000 tree gen_tmpl;
10001 tree type_decl;
10002 tree found = NULL_TREE;
10003 int arg_depth;
10004 int parm_depth;
10005 int is_dependent_type;
10006 int use_partial_inst_tmpl = false;
10008 if (template_type == error_mark_node)
10009 /* An error occurred while building the template TEMPL, and a
10010 diagnostic has most certainly been emitted for that
10011 already. Let's propagate that error. */
10012 return error_mark_node;
10014 gen_tmpl = most_general_template (templ);
10015 if (modules_p ())
10016 lazy_load_pendings (gen_tmpl);
10018 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
10019 parm_depth = TMPL_PARMS_DEPTH (parmlist);
10020 arg_depth = TMPL_ARGS_DEPTH (arglist);
10022 if (arg_depth == 1 && parm_depth > 1)
10024 /* We've been given an incomplete set of template arguments.
10025 For example, given:
10027 template <class T> struct S1 {
10028 template <class U> struct S2 {};
10029 template <class U> struct S2<U*> {};
10032 we will be called with an ARGLIST of `U*', but the
10033 TEMPLATE will be `template <class T> template
10034 <class U> struct S1<T>::S2'. We must fill in the missing
10035 arguments. */
10036 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
10037 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
10038 arg_depth = TMPL_ARGS_DEPTH (arglist);
10041 /* Now we should have enough arguments. */
10042 gcc_assert (parm_depth == arg_depth);
10044 /* From here on, we're only interested in the most general
10045 template. */
10047 /* Shortcut looking up the current class scope again. */
10048 for (tree cur = current_nonlambda_class_type ();
10049 cur != NULL_TREE;
10050 cur = get_containing_scope (cur))
10052 if (!CLASS_TYPE_P (cur))
10053 continue;
10055 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
10056 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
10057 break;
10059 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
10060 && comp_template_args (arglist, TI_ARGS (ti)))
10061 return cur;
10064 /* Calculate the BOUND_ARGS. These will be the args that are
10065 actually tsubst'd into the definition to create the
10066 instantiation. */
10067 if (PRIMARY_TEMPLATE_P (gen_tmpl))
10068 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
10070 if (arglist == error_mark_node)
10071 /* We were unable to bind the arguments. */
10072 return error_mark_node;
10074 /* In the scope of a template class, explicit references to the
10075 template class refer to the type of the template, not any
10076 instantiation of it. For example, in:
10078 template <class T> class C { void f(C<T>); }
10080 the `C<T>' is just the same as `C'. Outside of the
10081 class, however, such a reference is an instantiation. */
10082 if (entering_scope
10083 || !PRIMARY_TEMPLATE_P (gen_tmpl)
10084 || currently_open_class (template_type))
10086 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10088 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10089 return template_type;
10092 /* If we already have this specialization, return it. */
10093 elt.tmpl = gen_tmpl;
10094 elt.args = arglist;
10095 elt.spec = NULL_TREE;
10096 hash = spec_hasher::hash (&elt);
10097 entry = type_specializations->find_with_hash (&elt, hash);
10099 if (entry)
10100 return entry->spec;
10102 /* If the template's constraints are not satisfied,
10103 then we cannot form a valid type.
10105 Note that the check is deferred until after the hash
10106 lookup. This prevents redundant checks on previously
10107 instantiated specializations. */
10108 if (flag_concepts
10109 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10110 && !constraints_satisfied_p (gen_tmpl, arglist))
10112 if (complain & tf_error)
10114 auto_diagnostic_group d;
10115 error ("template constraint failure for %qD", gen_tmpl);
10116 diagnose_constraints (input_location, gen_tmpl, arglist);
10118 return error_mark_node;
10121 is_dependent_type = uses_template_parms (arglist);
10123 /* If the deduced arguments are invalid, then the binding
10124 failed. */
10125 if (!is_dependent_type
10126 && check_instantiated_args (gen_tmpl,
10127 INNERMOST_TEMPLATE_ARGS (arglist),
10128 complain))
10129 return error_mark_node;
10131 if (!is_dependent_type
10132 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10133 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10134 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10135 /* This occurs when the user has tried to define a tagged type
10136 in a scope that forbids it. We emitted an error during the
10137 parse. We didn't complete the bail out then, so here we
10138 are. */
10139 return error_mark_node;
10141 context = DECL_CONTEXT (gen_tmpl);
10142 if (context && TYPE_P (context))
10144 if (!uses_template_parms (DECL_CONTEXT (templ)))
10145 /* If the context of the partially instantiated template is
10146 already non-dependent, then we might as well use it. */
10147 context = DECL_CONTEXT (templ);
10148 else
10150 context = tsubst_aggr_type (context, arglist,
10151 complain, in_decl, true);
10152 /* Try completing the enclosing context if it's not already so. */
10153 if (context != error_mark_node
10154 && !COMPLETE_TYPE_P (context))
10156 context = complete_type (context);
10157 if (COMPLETE_TYPE_P (context))
10159 /* Completion could have caused us to register the desired
10160 specialization already, so check the table again. */
10161 entry = type_specializations->find_with_hash (&elt, hash);
10162 if (entry)
10163 return entry->spec;
10168 else
10169 context = tsubst (context, arglist, complain, in_decl);
10171 if (context == error_mark_node)
10172 return error_mark_node;
10174 if (!context)
10175 context = global_namespace;
10177 /* Create the type. */
10178 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10180 /* The user referred to a specialization of an alias
10181 template represented by GEN_TMPL.
10183 [temp.alias]/2 says:
10185 When a template-id refers to the specialization of an
10186 alias template, it is equivalent to the associated
10187 type obtained by substitution of its
10188 template-arguments for the template-parameters in the
10189 type-id of the alias template. */
10191 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10192 /* Note that the call above (by indirectly calling
10193 register_specialization in tsubst_decl) registers the
10194 TYPE_DECL representing the specialization of the alias
10195 template. So next time someone substitutes ARGLIST for
10196 the template parms into the alias template (GEN_TMPL),
10197 she'll get that TYPE_DECL back. */
10199 if (t == error_mark_node)
10200 return t;
10202 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10204 if (!is_dependent_type)
10206 set_current_access_from_decl (TYPE_NAME (template_type));
10207 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10208 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10209 arglist, complain, in_decl),
10210 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10211 arglist, complain, in_decl),
10212 SCOPED_ENUM_P (template_type), NULL);
10214 if (t == error_mark_node)
10215 return t;
10217 else
10219 /* We don't want to call start_enum for this type, since
10220 the values for the enumeration constants may involve
10221 template parameters. And, no one should be interested
10222 in the enumeration constants for such a type. */
10223 t = cxx_make_type (ENUMERAL_TYPE);
10224 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10226 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10227 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10228 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10230 else if (CLASS_TYPE_P (template_type))
10232 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10233 instantiated here. */
10234 gcc_assert (!LAMBDA_TYPE_P (template_type));
10236 t = make_class_type (TREE_CODE (template_type));
10237 CLASSTYPE_DECLARED_CLASS (t)
10238 = CLASSTYPE_DECLARED_CLASS (template_type);
10239 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10241 /* A local class. Make sure the decl gets registered properly. */
10242 if (context == current_function_decl)
10243 if (pushtag (DECL_NAME (gen_tmpl), t)
10244 == error_mark_node)
10245 return error_mark_node;
10247 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10248 /* This instantiation is another name for the primary
10249 template type. Set the TYPE_CANONICAL field
10250 appropriately. */
10251 TYPE_CANONICAL (t) = template_type;
10252 else if (any_template_arguments_need_structural_equality_p (arglist))
10253 SET_TYPE_STRUCTURAL_EQUALITY (t);
10255 else
10256 gcc_unreachable ();
10258 /* If we called start_enum or pushtag above, this information
10259 will already be set up. */
10260 type_decl = TYPE_NAME (t);
10261 if (!type_decl)
10263 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10265 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10266 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10267 DECL_SOURCE_LOCATION (type_decl)
10268 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10271 set_instantiating_module (type_decl);
10272 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10273 of export flag. We want to propagate this because it might
10274 be a friend declaration that pushes a new hidden binding. */
10275 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10277 if (CLASS_TYPE_P (template_type))
10279 TREE_PRIVATE (type_decl)
10280 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10281 TREE_PROTECTED (type_decl)
10282 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10283 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10285 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10286 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10290 if (OVERLOAD_TYPE_P (t)
10291 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10293 static const char *tags[] = {"abi_tag", "may_alias"};
10295 for (unsigned ix = 0; ix != 2; ix++)
10297 tree attributes
10298 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10300 if (attributes)
10301 TYPE_ATTRIBUTES (t)
10302 = tree_cons (TREE_PURPOSE (attributes),
10303 TREE_VALUE (attributes),
10304 TYPE_ATTRIBUTES (t));
10308 /* Let's consider the explicit specialization of a member
10309 of a class template specialization that is implicitly instantiated,
10310 e.g.:
10311 template<class T>
10312 struct S
10314 template<class U> struct M {}; //#0
10317 template<>
10318 template<>
10319 struct S<int>::M<char> //#1
10321 int i;
10323 [temp.expl.spec]/4 says this is valid.
10325 In this case, when we write:
10326 S<int>::M<char> m;
10328 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10329 the one of #0.
10331 When we encounter #1, we want to store the partial instantiation
10332 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10334 For all cases other than this "explicit specialization of member of a
10335 class template", we just want to store the most general template into
10336 the CLASSTYPE_TI_TEMPLATE of M.
10338 This case of "explicit specialization of member of a class template"
10339 only happens when:
10340 1/ the enclosing class is an instantiation of, and therefore not
10341 the same as, the context of the most general template, and
10342 2/ we aren't looking at the partial instantiation itself, i.e.
10343 the innermost arguments are not the same as the innermost parms of
10344 the most general template.
10346 So it's only when 1/ and 2/ happens that we want to use the partial
10347 instantiation of the member template in lieu of its most general
10348 template. */
10350 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10351 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10352 /* the enclosing class must be an instantiation... */
10353 && CLASS_TYPE_P (context)
10354 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10356 TREE_VEC_LENGTH (arglist)--;
10357 ++processing_template_decl;
10358 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10359 tree partial_inst_args =
10360 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10361 arglist, complain, NULL_TREE);
10362 --processing_template_decl;
10363 TREE_VEC_LENGTH (arglist)++;
10364 if (partial_inst_args == error_mark_node)
10365 return error_mark_node;
10366 use_partial_inst_tmpl =
10367 /*...and we must not be looking at the partial instantiation
10368 itself. */
10369 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10370 partial_inst_args);
10373 if (!use_partial_inst_tmpl)
10374 /* This case is easy; there are no member templates involved. */
10375 found = gen_tmpl;
10376 else
10378 /* This is a full instantiation of a member template. Find
10379 the partial instantiation of which this is an instance. */
10381 /* Temporarily reduce by one the number of levels in the ARGLIST
10382 so as to avoid comparing the last set of arguments. */
10383 TREE_VEC_LENGTH (arglist)--;
10384 /* We don't use COMPLAIN in the following call because this isn't
10385 the immediate context of deduction. For instance, tf_partial
10386 could be set here as we might be at the beginning of template
10387 argument deduction when any explicitly specified template
10388 arguments are substituted into the function type. tf_partial
10389 could lead into trouble because we wouldn't find the partial
10390 instantiation that might have been created outside tf_partial
10391 context, because the levels of template parameters wouldn't
10392 match, because in a tf_partial context, tsubst doesn't reduce
10393 TEMPLATE_PARM_LEVEL. */
10394 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10395 TREE_VEC_LENGTH (arglist)++;
10396 /* FOUND is either a proper class type, or an alias
10397 template specialization. In the later case, it's a
10398 TYPE_DECL, resulting from the substituting of arguments
10399 for parameters in the TYPE_DECL of the alias template
10400 done earlier. So be careful while getting the template
10401 of FOUND. */
10402 found = (TREE_CODE (found) == TEMPLATE_DECL
10403 ? found
10404 : (TREE_CODE (found) == TYPE_DECL
10405 ? DECL_TI_TEMPLATE (found)
10406 : CLASSTYPE_TI_TEMPLATE (found)));
10408 if (DECL_CLASS_TEMPLATE_P (found)
10409 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10411 /* If this partial instantiation is specialized, we want to
10412 use it for hash table lookup. */
10413 elt.tmpl = found;
10414 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10415 hash = spec_hasher::hash (&elt);
10419 /* Build template info for the new specialization. */
10420 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10422 elt.spec = t;
10423 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10424 gcc_checking_assert (*slot == NULL);
10425 entry = ggc_alloc<spec_entry> ();
10426 *entry = elt;
10427 *slot = entry;
10429 /* Note this use of the partial instantiation so we can check it
10430 later in maybe_process_partial_specialization. */
10431 DECL_TEMPLATE_INSTANTIATIONS (found)
10432 = tree_cons (arglist, t,
10433 DECL_TEMPLATE_INSTANTIATIONS (found));
10435 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10436 && !uses_template_parms (current_nonlambda_scope ())
10437 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10438 /* Now that the type has been registered on the instantiations
10439 list, we set up the enumerators. Because the enumeration
10440 constants may involve the enumeration type itself, we make
10441 sure to register the type first, and then create the
10442 constants. That way, doing tsubst_expr for the enumeration
10443 constants won't result in recursive calls here; we'll find
10444 the instantiation and exit above. */
10445 tsubst_enum (template_type, t, arglist);
10447 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10448 /* If the type makes use of template parameters, the
10449 code that generates debugging information will crash. */
10450 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10452 /* Possibly limit visibility based on template args. */
10453 TREE_PUBLIC (type_decl) = 1;
10454 determine_visibility (type_decl);
10456 inherit_targ_abi_tags (t);
10458 return t;
10462 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10464 tree
10465 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10467 if (flag_concepts && variable_concept_p (templ))
10468 return build_concept_check (templ, arglist, tf_none);
10470 tree gen_templ = most_general_template (templ);
10471 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10472 arglist = add_outermost_template_args (templ, arglist);
10473 arglist = coerce_template_parms (parms, arglist, templ, complain);
10474 if (arglist == error_mark_node)
10475 return error_mark_node;
10477 /* The type of the expression is NULL_TREE since the template-id could refer
10478 to an explicit or partial specialization. */
10479 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10482 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10483 not dependent. */
10485 tree
10486 finish_template_variable (tree var, tsubst_flags_t complain)
10488 tree templ = TREE_OPERAND (var, 0);
10489 tree arglist = TREE_OPERAND (var, 1);
10491 /* If the template or arguments are dependent, then we
10492 can't resolve the TEMPLATE_ID_EXPR yet. */
10493 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10494 || any_dependent_template_arguments_p (arglist))
10495 return var;
10497 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10499 if (complain & tf_error)
10501 auto_diagnostic_group d;
10502 error ("use of invalid variable template %qE", var);
10503 diagnose_constraints (location_of (var), templ, arglist);
10505 return error_mark_node;
10508 return instantiate_template (templ, arglist, complain);
10511 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10512 TARGS template args, and instantiate it if it's not dependent. */
10514 tree
10515 lookup_and_finish_template_variable (tree templ, tree targs,
10516 tsubst_flags_t complain)
10518 tree var = lookup_template_variable (templ, targs, complain);
10519 if (var == error_mark_node)
10520 return error_mark_node;
10521 var = finish_template_variable (var, complain);
10522 mark_used (var);
10523 return var;
10526 /* If the set of template parameters PARMS contains a template parameter
10527 at the given LEVEL and INDEX, then return this parameter. Otherwise
10528 return NULL_TREE. */
10530 static tree
10531 corresponding_template_parameter_list (tree parms, int level, int index)
10533 while (TMPL_PARMS_DEPTH (parms) > level)
10534 parms = TREE_CHAIN (parms);
10536 if (TMPL_PARMS_DEPTH (parms) != level
10537 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10538 return NULL_TREE;
10540 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10543 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10544 corresponds to the template parameter PARM, or else return NULL_TREE. */
10546 static tree
10547 corresponding_template_parameter_list (tree parms, tree parm)
10549 int level, index;
10550 template_parm_level_and_index (parm, &level, &index);
10551 return corresponding_template_parameter_list (parms, level, index);
10554 /* As above, but pull out the actual parameter. */
10556 static tree
10557 corresponding_template_parameter (tree parms, tree parm)
10559 tree list = corresponding_template_parameter_list (parms, parm);
10560 if (!list)
10561 return NULL_TREE;
10563 tree t = TREE_VALUE (list);
10564 /* As in template_parm_to_arg. */
10565 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10566 t = TREE_TYPE (t);
10567 else
10568 t = DECL_INITIAL (t);
10570 gcc_assert (TEMPLATE_PARM_P (t));
10571 return t;
10574 struct pair_fn_data
10576 tree_fn_t fn;
10577 tree_fn_t any_fn;
10578 void *data;
10579 /* True when we should also visit template parameters that occur in
10580 non-deduced contexts. */
10581 bool include_nondeduced_p;
10582 hash_set<tree> *visited;
10585 /* Called from for_each_template_parm via walk_tree. */
10587 static tree
10588 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10590 tree t = *tp;
10591 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10592 tree_fn_t fn = pfd->fn;
10593 void *data = pfd->data;
10594 tree result = NULL_TREE;
10596 #define WALK_SUBTREE(NODE) \
10597 do \
10599 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10600 pfd->include_nondeduced_p, \
10601 pfd->any_fn); \
10602 if (result) goto out; \
10604 while (0)
10606 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10607 return t;
10609 if (TYPE_P (t)
10610 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10611 WALK_SUBTREE (TYPE_CONTEXT (t));
10613 switch (TREE_CODE (t))
10615 case RECORD_TYPE:
10616 if (TYPE_PTRMEMFUNC_P (t))
10617 break;
10618 /* Fall through. */
10620 case UNION_TYPE:
10621 case ENUMERAL_TYPE:
10622 if (!TYPE_TEMPLATE_INFO (t))
10623 *walk_subtrees = 0;
10624 else
10625 WALK_SUBTREE (TYPE_TI_ARGS (t));
10626 break;
10628 case INTEGER_TYPE:
10629 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10630 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10631 break;
10633 case METHOD_TYPE:
10634 /* Since we're not going to walk subtrees, we have to do this
10635 explicitly here. */
10636 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10637 /* Fall through. */
10639 case FUNCTION_TYPE:
10640 /* Check the return type. */
10641 WALK_SUBTREE (TREE_TYPE (t));
10643 /* Check the parameter types. Since default arguments are not
10644 instantiated until they are needed, the TYPE_ARG_TYPES may
10645 contain expressions that involve template parameters. But,
10646 no-one should be looking at them yet. And, once they're
10647 instantiated, they don't contain template parameters, so
10648 there's no point in looking at them then, either. */
10650 tree parm;
10652 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10653 WALK_SUBTREE (TREE_VALUE (parm));
10655 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10656 want walk_tree walking into them itself. */
10657 *walk_subtrees = 0;
10660 if (flag_noexcept_type)
10662 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10663 if (spec)
10664 WALK_SUBTREE (TREE_PURPOSE (spec));
10666 break;
10668 case TYPEOF_TYPE:
10669 case DECLTYPE_TYPE:
10670 if (pfd->include_nondeduced_p
10671 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10672 pfd->visited,
10673 pfd->include_nondeduced_p,
10674 pfd->any_fn))
10675 return error_mark_node;
10676 *walk_subtrees = false;
10677 break;
10679 case TRAIT_TYPE:
10680 if (pfd->include_nondeduced_p)
10682 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10683 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10685 *walk_subtrees = false;
10686 break;
10688 case FUNCTION_DECL:
10689 case VAR_DECL:
10690 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10691 WALK_SUBTREE (DECL_TI_ARGS (t));
10692 break;
10694 case PARM_DECL:
10695 WALK_SUBTREE (TREE_TYPE (t));
10696 break;
10698 case CONST_DECL:
10699 if (DECL_TEMPLATE_PARM_P (t))
10700 WALK_SUBTREE (DECL_INITIAL (t));
10701 if (DECL_CONTEXT (t)
10702 && pfd->include_nondeduced_p)
10703 WALK_SUBTREE (DECL_CONTEXT (t));
10704 break;
10706 case BOUND_TEMPLATE_TEMPLATE_PARM:
10707 /* Record template parameters such as `T' inside `TT<T>'. */
10708 WALK_SUBTREE (TYPE_TI_ARGS (t));
10709 /* Fall through. */
10711 case TEMPLATE_TEMPLATE_PARM:
10712 case TEMPLATE_TYPE_PARM:
10713 case TEMPLATE_PARM_INDEX:
10714 if (fn && (*fn)(t, data))
10715 return t;
10716 else if (!fn)
10717 return t;
10718 break;
10720 case TEMPLATE_DECL:
10721 /* A template template parameter is encountered. */
10722 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10723 WALK_SUBTREE (TREE_TYPE (t));
10725 /* Already substituted template template parameter */
10726 *walk_subtrees = 0;
10727 break;
10729 case TYPENAME_TYPE:
10730 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10731 partial instantiation. */
10732 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10733 *walk_subtrees = 0;
10734 break;
10736 case INDIRECT_REF:
10737 case COMPONENT_REF:
10738 /* If there's no type, then this thing must be some expression
10739 involving template parameters. */
10740 if (!fn && !TREE_TYPE (t))
10741 return error_mark_node;
10742 break;
10744 case CONSTRUCTOR:
10745 case TRAIT_EXPR:
10746 case PLUS_EXPR:
10747 case MULT_EXPR:
10748 case SCOPE_REF:
10749 /* These are non-deduced contexts. */
10750 if (!pfd->include_nondeduced_p)
10751 *walk_subtrees = 0;
10752 break;
10754 case MODOP_EXPR:
10755 case CAST_EXPR:
10756 case IMPLICIT_CONV_EXPR:
10757 case REINTERPRET_CAST_EXPR:
10758 case CONST_CAST_EXPR:
10759 case STATIC_CAST_EXPR:
10760 case DYNAMIC_CAST_EXPR:
10761 case ARROW_EXPR:
10762 case DOTSTAR_EXPR:
10763 case TYPEID_EXPR:
10764 case PSEUDO_DTOR_EXPR:
10765 if (!fn)
10766 return error_mark_node;
10767 break;
10769 default:
10770 break;
10773 #undef WALK_SUBTREE
10775 /* We didn't find any template parameters we liked. */
10776 out:
10777 return result;
10780 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10781 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10782 call FN with the parameter and the DATA.
10783 If FN returns nonzero, the iteration is terminated, and
10784 for_each_template_parm returns 1. Otherwise, the iteration
10785 continues. If FN never returns a nonzero value, the value
10786 returned by for_each_template_parm is 0. If FN is NULL, it is
10787 considered to be the function which always returns 1.
10789 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10790 parameters that occur in non-deduced contexts. When false, only
10791 visits those template parameters that can be deduced. */
10793 static tree
10794 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10795 hash_set<tree> *visited,
10796 bool include_nondeduced_p,
10797 tree_fn_t any_fn)
10799 struct pair_fn_data pfd;
10800 tree result;
10802 /* Set up. */
10803 pfd.fn = fn;
10804 pfd.any_fn = any_fn;
10805 pfd.data = data;
10806 pfd.include_nondeduced_p = include_nondeduced_p;
10808 /* Walk the tree. (Conceptually, we would like to walk without
10809 duplicates, but for_each_template_parm_r recursively calls
10810 for_each_template_parm, so we would need to reorganize a fair
10811 bit to use walk_tree_without_duplicates, so we keep our own
10812 visited list.) */
10813 if (visited)
10814 pfd.visited = visited;
10815 else
10816 pfd.visited = new hash_set<tree>;
10817 result = cp_walk_tree (&t,
10818 for_each_template_parm_r,
10819 &pfd,
10820 pfd.visited);
10822 /* Clean up. */
10823 if (!visited)
10825 delete pfd.visited;
10826 pfd.visited = 0;
10829 return result;
10832 struct find_template_parameter_info
10834 explicit find_template_parameter_info (tree ctx_parms)
10835 : ctx_parms (ctx_parms),
10836 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10839 hash_set<tree> visited;
10840 hash_set<tree> parms;
10841 tree parm_list = NULL_TREE;
10842 tree *parm_list_tail = &parm_list;
10843 tree ctx_parms;
10844 int max_depth;
10846 tree find_in (tree);
10847 tree find_in_recursive (tree);
10848 bool found (tree);
10849 unsigned num_found () { return parms.elements (); }
10852 /* Appends the declaration of T to the list in DATA. */
10854 static int
10855 keep_template_parm (tree t, void* data)
10857 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10859 /* Template parameters declared within the expression are not part of
10860 the parameter mapping. For example, in this concept:
10862 template<typename T>
10863 concept C = requires { <expr> } -> same_as<int>;
10865 the return specifier same_as<int> declares a new decltype parameter
10866 that must not be part of the parameter mapping. The same is true
10867 for generic lambda parameters, lambda template parameters, etc. */
10868 int level;
10869 int index;
10870 template_parm_level_and_index (t, &level, &index);
10871 if (level == 0 || level > ftpi->max_depth)
10872 return 0;
10874 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10875 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10876 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10877 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10879 /* This template parameter might be an argument to a cached dependent
10880 specalization that was formed earlier inside some other template, in
10881 which case the parameter is not among the ones that are in-scope.
10882 Look in CTX_PARMS to find the corresponding in-scope template
10883 parameter, and use it instead. */
10884 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10885 t = in_scope;
10887 /* Arguments like const T yield parameters like const T. This means that
10888 a template-id like X<T, const T> would yield two distinct parameters:
10889 T and const T. Adjust types to their unqualified versions. */
10890 if (TYPE_P (t))
10891 t = TYPE_MAIN_VARIANT (t);
10892 if (!ftpi->parms.add (t))
10894 /* Append T to PARM_LIST. */
10895 tree node = build_tree_list (NULL_TREE, t);
10896 *ftpi->parm_list_tail = node;
10897 ftpi->parm_list_tail = &TREE_CHAIN (node);
10900 /* Verify the parameter we found has a valid index. */
10901 if (flag_checking)
10903 tree parms = ftpi->ctx_parms;
10904 while (TMPL_PARMS_DEPTH (parms) > level)
10905 parms = TREE_CHAIN (parms);
10906 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10907 gcc_assert (index < len);
10910 return 0;
10913 /* Ensure that we recursively examine certain terms that are not normally
10914 visited in for_each_template_parm_r. */
10916 static int
10917 any_template_parm_r (tree t, void *data)
10919 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10921 #define WALK_SUBTREE(NODE) \
10922 do \
10924 for_each_template_parm (NODE, keep_template_parm, data, \
10925 &ftpi->visited, true, \
10926 any_template_parm_r); \
10928 while (0)
10930 /* A mention of a member alias/typedef is a use of all of its template
10931 arguments, including those from the enclosing class, so we don't use
10932 alias_template_specialization_p here. */
10933 if (TYPE_P (t) && typedef_variant_p (t))
10934 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10935 WALK_SUBTREE (TI_ARGS (tinfo));
10937 switch (TREE_CODE (t))
10939 case TEMPLATE_TYPE_PARM:
10940 /* Type constraints of a placeholder type may contain parameters. */
10941 if (is_auto (t))
10942 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10943 WALK_SUBTREE (constr);
10944 break;
10946 case TEMPLATE_ID_EXPR:
10947 /* Search through references to variable templates. */
10948 WALK_SUBTREE (TREE_OPERAND (t, 0));
10949 WALK_SUBTREE (TREE_OPERAND (t, 1));
10950 break;
10952 case TEMPLATE_PARM_INDEX:
10953 WALK_SUBTREE (TREE_TYPE (t));
10954 break;
10956 case TEMPLATE_DECL:
10957 /* If T is a member template that shares template parameters with
10958 ctx_parms, we need to mark all those parameters for mapping.
10959 To that end, it should suffice to just walk the DECL_CONTEXT of
10960 the template (assuming the template is not overly general). */
10961 WALK_SUBTREE (DECL_CONTEXT (t));
10962 break;
10964 case LAMBDA_EXPR:
10966 /* Look in the parms and body. */
10967 tree fn = lambda_function (t);
10968 WALK_SUBTREE (TREE_TYPE (fn));
10969 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10971 break;
10973 case IDENTIFIER_NODE:
10974 if (IDENTIFIER_CONV_OP_P (t))
10975 /* The conversion-type-id of a conversion operator may be dependent. */
10976 WALK_SUBTREE (TREE_TYPE (t));
10977 break;
10979 case CONVERT_EXPR:
10980 if (is_dummy_object (t))
10981 WALK_SUBTREE (TREE_TYPE (t));
10982 break;
10984 default:
10985 break;
10988 /* Keep walking. */
10989 return 0;
10992 /* Look through T for template parameters. */
10994 tree
10995 find_template_parameter_info::find_in (tree t)
10997 return for_each_template_parm (t, keep_template_parm, this, &visited,
10998 /*include_nondeduced*/true,
10999 any_template_parm_r);
11002 /* As above, but also recursively look into the default arguments of template
11003 parameters we found. Used for alias CTAD. */
11005 tree
11006 find_template_parameter_info::find_in_recursive (tree t)
11008 if (tree r = find_in (t))
11009 return r;
11010 /* Since newly found parms are added to the end of the list, we
11011 can just walk it until we reach the end. */
11012 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
11014 tree parm = TREE_VALUE (pl);
11015 tree list = corresponding_template_parameter_list (ctx_parms, parm);
11016 if (tree r = find_in (TREE_PURPOSE (list)))
11017 return r;
11019 return NULL_TREE;
11022 /* True if PARM was found by a previous call to find_in. PARM can be a
11023 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
11025 bool
11026 find_template_parameter_info::found (tree parm)
11028 if (TREE_CODE (parm) == TREE_LIST)
11029 parm = TREE_VALUE (parm);
11030 if (TREE_CODE (parm) == TYPE_DECL)
11031 parm = TREE_TYPE (parm);
11032 else
11033 parm = DECL_INITIAL (parm);
11034 gcc_checking_assert (TEMPLATE_PARM_P (parm));
11035 return parms.contains (parm);
11038 /* Returns a list of unique template parameters found within T, where CTX_PARMS
11039 are the template parameters in scope. */
11041 tree
11042 find_template_parameters (tree t, tree ctx_parms)
11044 if (!ctx_parms)
11045 return NULL_TREE;
11047 find_template_parameter_info ftpi (ctx_parms);
11048 ftpi.find_in (t);
11049 return ftpi.parm_list;
11052 /* Returns true if T depends on any template parameter. */
11054 bool
11055 uses_template_parms (tree t)
11057 if (t == NULL_TREE || t == error_mark_node)
11058 return false;
11060 /* Namespaces can't depend on any template parameters. */
11061 if (TREE_CODE (t) == NAMESPACE_DECL)
11062 return false;
11064 processing_template_decl_sentinel ptds (/*reset*/false);
11065 ++processing_template_decl;
11067 if (TYPE_P (t))
11068 return dependent_type_p (t);
11069 else if (TREE_CODE (t) == TREE_VEC)
11070 return any_dependent_template_arguments_p (t);
11071 else if (TREE_CODE (t) == TREE_LIST)
11072 return (uses_template_parms (TREE_VALUE (t))
11073 || uses_template_parms (TREE_CHAIN (t)));
11074 else if (TREE_CODE (t) == TYPE_DECL)
11075 return dependent_type_p (TREE_TYPE (t));
11076 else
11077 return instantiation_dependent_expression_p (t);
11080 /* Returns true if T depends on any template parameter with level LEVEL. */
11082 bool
11083 uses_template_parms_level (tree t, int level)
11085 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
11086 /*include_nondeduced_p=*/true);
11089 /* Returns true if the signature of DECL depends on any template parameter from
11090 its enclosing class. */
11092 static bool
11093 uses_outer_template_parms (tree decl)
11095 int depth;
11096 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11097 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
11098 else
11099 depth = template_class_depth (CP_DECL_CONTEXT (decl));
11100 if (depth == 0)
11101 return false;
11102 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
11103 &depth, NULL, /*include_nondeduced_p=*/true))
11104 return true;
11105 if (PRIMARY_TEMPLATE_P (decl)
11106 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11108 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
11109 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
11111 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
11112 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11113 if (TREE_CODE (parm) == PARM_DECL
11114 && for_each_template_parm (TREE_TYPE (parm),
11115 template_parm_outer_level,
11116 &depth, NULL, /*nondeduced*/true))
11117 return true;
11118 if (TREE_CODE (parm) == TEMPLATE_DECL
11119 && uses_outer_template_parms (parm))
11120 return true;
11121 if (defarg
11122 && for_each_template_parm (defarg, template_parm_outer_level,
11123 &depth, NULL, /*nondeduced*/true))
11124 return true;
11127 if (uses_outer_template_parms_in_constraints (decl))
11128 return true;
11129 return false;
11132 /* Returns true if the constraints of DECL depend on any template parameters
11133 from its enclosing scope. */
11135 bool
11136 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
11138 tree ci = get_constraints (decl);
11139 if (ci)
11140 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11141 if (!ci)
11142 return false;
11143 if (!ctx)
11145 if (tree fc = DECL_FRIEND_CONTEXT (decl))
11146 ctx = fc;
11147 else
11148 ctx = CP_DECL_CONTEXT (decl);
11150 int depth = template_class_depth (ctx);
11151 if (depth == 0)
11152 return false;
11153 return for_each_template_parm (ci, template_parm_outer_level,
11154 &depth, NULL, /*nondeduced*/true);
11157 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11158 ill-formed translation unit, i.e. a variable or function that isn't
11159 usable in a constant expression. */
11161 static inline bool
11162 neglectable_inst_p (tree d)
11164 return (d && DECL_P (d)
11165 && !undeduced_auto_decl (d)
11166 && !(TREE_CODE (d) == FUNCTION_DECL
11167 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11168 : decl_maybe_constant_var_p (d)));
11171 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11172 neglectable and instantiated from within an erroneous instantiation. */
11174 static bool
11175 limit_bad_template_recursion (tree decl)
11177 struct tinst_level *lev = current_tinst_level;
11178 int errs = errorcount + sorrycount;
11179 if (errs == 0 || !neglectable_inst_p (decl))
11180 return false;
11182 /* Avoid instantiating members of an ill-formed class. */
11183 bool refuse
11184 = (DECL_CLASS_SCOPE_P (decl)
11185 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11187 if (!refuse)
11189 for (; lev; lev = lev->next)
11190 if (neglectable_inst_p (lev->maybe_get_node ()))
11191 break;
11192 refuse = (lev && errs > lev->errors);
11195 if (refuse)
11197 /* Don't warn about it not being defined. */
11198 suppress_warning (decl, OPT_Wunused);
11199 tree clone;
11200 FOR_EACH_CLONE (clone, decl)
11201 suppress_warning (clone, OPT_Wunused);
11203 return refuse;
11206 static int tinst_depth;
11207 extern int max_tinst_depth;
11208 int depth_reached;
11210 static GTY(()) struct tinst_level *last_error_tinst_level;
11212 /* We're starting to instantiate D; record the template instantiation context
11213 at LOC for diagnostics and to restore it later. */
11215 bool
11216 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11218 struct tinst_level *new_level;
11220 if (tinst_depth >= max_tinst_depth)
11222 /* Tell error.cc not to try to instantiate any templates. */
11223 at_eof = 3;
11224 fatal_error (input_location,
11225 "template instantiation depth exceeds maximum of %d"
11226 " (use %<-ftemplate-depth=%> to increase the maximum)",
11227 max_tinst_depth);
11228 return false;
11231 /* If the current instantiation caused problems, don't let it instantiate
11232 anything else. Do allow deduction substitution and decls usable in
11233 constant expressions. */
11234 if (!targs && limit_bad_template_recursion (tldcl))
11236 /* Avoid no_linkage_errors and unused function (and all other)
11237 warnings for this decl. */
11238 suppress_warning (tldcl);
11239 return false;
11242 /* When not -quiet, dump template instantiations other than functions, since
11243 announce_function will take care of those. */
11244 if (!quiet_flag && !targs
11245 && TREE_CODE (tldcl) != TREE_LIST
11246 && TREE_CODE (tldcl) != FUNCTION_DECL)
11247 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11249 new_level = tinst_level_freelist ().alloc ();
11250 new_level->tldcl = tldcl;
11251 new_level->targs = targs;
11252 new_level->locus = loc;
11253 new_level->errors = errorcount + sorrycount;
11254 new_level->next = NULL;
11255 new_level->refcount = 0;
11256 new_level->path = new_level->visible = nullptr;
11257 set_refcount_ptr (new_level->next, current_tinst_level);
11258 set_refcount_ptr (current_tinst_level, new_level);
11260 ++tinst_depth;
11261 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11262 depth_reached = tinst_depth;
11264 return true;
11267 /* We're starting substitution of TMPL<ARGS>; record the template
11268 substitution context for diagnostics and to restore it later. */
11270 bool
11271 push_tinst_level (tree tmpl, tree args)
11273 return push_tinst_level_loc (tmpl, args, input_location);
11276 /* We're starting to instantiate D; record INPUT_LOCATION and the
11277 template instantiation context for diagnostics and to restore it
11278 later. */
11280 bool
11281 push_tinst_level (tree d)
11283 return push_tinst_level_loc (d, input_location);
11286 /* Likewise, but record LOC as the program location. */
11288 bool
11289 push_tinst_level_loc (tree d, location_t loc)
11291 gcc_assert (TREE_CODE (d) != TREE_LIST);
11292 return push_tinst_level_loc (d, NULL, loc);
11295 /* We're done instantiating this template; return to the instantiation
11296 context. */
11298 void
11299 pop_tinst_level (void)
11301 /* Restore the filename and line number stashed away when we started
11302 this instantiation. */
11303 input_location = current_tinst_level->locus;
11304 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11305 --tinst_depth;
11308 /* We're instantiating a deferred template; restore the template
11309 instantiation context in which the instantiation was requested, which
11310 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11312 static tree
11313 reopen_tinst_level (struct tinst_level *level)
11315 struct tinst_level *t;
11317 tinst_depth = 0;
11318 for (t = level; t; t = t->next)
11319 ++tinst_depth;
11321 set_refcount_ptr (current_tinst_level, level);
11322 pop_tinst_level ();
11323 if (current_tinst_level)
11324 current_tinst_level->errors = errorcount+sorrycount;
11325 return level->maybe_get_node ();
11328 /* Returns the TINST_LEVEL which gives the original instantiation
11329 context. */
11331 struct tinst_level *
11332 outermost_tinst_level (void)
11334 struct tinst_level *level = current_tinst_level;
11335 if (level)
11336 while (level->next)
11337 level = level->next;
11338 return level;
11341 /* True iff T is a friend function declaration that is not itself a template
11342 and is not defined in a class template. */
11344 bool
11345 non_templated_friend_p (tree t)
11347 if (t && TREE_CODE (t) == FUNCTION_DECL
11348 && DECL_UNIQUE_FRIEND_P (t))
11350 tree ti = DECL_TEMPLATE_INFO (t);
11351 if (!ti)
11352 return true;
11353 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11354 if (DECL_FRIEND_CONTEXT (t))
11355 return false;
11356 /* Non-templated friends in a class template are still represented with a
11357 TEMPLATE_DECL; check that its primary template is the befriending
11358 class. Note that DECL_PRIMARY_TEMPLATE is null for
11359 template <class T> friend A<T>::f(); */
11360 tree tmpl = TI_TEMPLATE (ti);
11361 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11362 return (primary && primary != tmpl);
11364 else
11365 return false;
11368 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11369 vector of template arguments, as for tsubst.
11371 Returns an appropriate tsubst'd friend declaration. */
11373 static tree
11374 tsubst_friend_function (tree decl, tree args)
11376 tree new_friend;
11378 if (TREE_CODE (decl) == FUNCTION_DECL
11379 && DECL_TEMPLATE_INSTANTIATION (decl)
11380 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11381 /* This was a friend declared with an explicit template
11382 argument list, e.g.:
11384 friend void f<>(T);
11386 to indicate that f was a template instantiation, not a new
11387 function declaration. Now, we have to figure out what
11388 instantiation of what template. */
11390 tree template_id, arglist, fns;
11391 tree new_args;
11392 tree tmpl;
11393 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11395 /* Friend functions are looked up in the containing namespace scope.
11396 We must enter that scope, to avoid finding member functions of the
11397 current class with same name. */
11398 push_nested_namespace (ns);
11399 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11400 tf_warning_or_error, NULL_TREE);
11401 pop_nested_namespace (ns);
11402 arglist = tsubst (DECL_TI_ARGS (decl), args,
11403 tf_warning_or_error, NULL_TREE);
11404 template_id = lookup_template_function (fns, arglist);
11406 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11407 tmpl = determine_specialization (template_id, new_friend,
11408 &new_args,
11409 /*need_member_template=*/0,
11410 TREE_VEC_LENGTH (args),
11411 tsk_none);
11412 return instantiate_template (tmpl, new_args, tf_error);
11415 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11416 if (new_friend == error_mark_node)
11417 return error_mark_node;
11419 /* The NEW_FRIEND will look like an instantiation, to the
11420 compiler, but is not an instantiation from the point of view of
11421 the language. For example, we might have had:
11423 template <class T> struct S {
11424 template <class U> friend void f(T, U);
11427 Then, in S<int>, template <class U> void f(int, U) is not an
11428 instantiation of anything. */
11430 DECL_USE_TEMPLATE (new_friend) = 0;
11431 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11433 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11434 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11435 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11436 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11438 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11439 match in decls_match. */
11440 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11441 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11442 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11443 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11445 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11446 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11447 tsubst_each_template_parm_constraints (parms, args,
11448 tf_warning_or_error);
11452 /* The mangled name for the NEW_FRIEND is incorrect. The function
11453 is not a template instantiation and should not be mangled like
11454 one. Therefore, we forget the mangling here; we'll recompute it
11455 later if we need it. */
11456 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11458 SET_DECL_RTL (new_friend, NULL);
11459 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11462 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11464 tree old_decl;
11465 tree ns;
11467 /* We must save some information from NEW_FRIEND before calling
11468 duplicate decls since that function will free NEW_FRIEND if
11469 possible. */
11470 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11471 tree new_friend_result_template_info = NULL_TREE;
11472 bool new_friend_is_defn =
11473 (new_friend_template_info
11474 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11475 (template_for_substitution (new_friend)))
11476 != NULL_TREE));
11477 tree not_tmpl = new_friend;
11479 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11481 /* This declaration is a `primary' template. */
11482 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11484 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11485 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11488 /* Inside pushdecl_namespace_level, we will push into the
11489 current namespace. However, the friend function should go
11490 into the namespace of the template. */
11491 ns = decl_namespace_context (new_friend);
11492 push_nested_namespace (ns);
11493 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11494 pop_nested_namespace (ns);
11496 if (old_decl == error_mark_node)
11497 return error_mark_node;
11499 if (old_decl != new_friend)
11501 /* This new friend declaration matched an existing
11502 declaration. For example, given:
11504 template <class T> void f(T);
11505 template <class U> class C {
11506 template <class T> friend void f(T) {}
11509 the friend declaration actually provides the definition
11510 of `f', once C has been instantiated for some type. So,
11511 old_decl will be the out-of-class template declaration,
11512 while new_friend is the in-class definition.
11514 But, if `f' was called before this point, the
11515 instantiation of `f' will have DECL_TI_ARGS corresponding
11516 to `T' but not to `U', references to which might appear
11517 in the definition of `f'. Previously, the most general
11518 template for an instantiation of `f' was the out-of-class
11519 version; now it is the in-class version. Therefore, we
11520 run through all specialization of `f', adding to their
11521 DECL_TI_ARGS appropriately. In particular, they need a
11522 new set of outer arguments, corresponding to the
11523 arguments for this class instantiation.
11525 The same situation can arise with something like this:
11527 friend void f(int);
11528 template <class T> class C {
11529 friend void f(T) {}
11532 when `C<int>' is instantiated. Now, `f(int)' is defined
11533 in the class. */
11535 if (!new_friend_is_defn)
11536 /* On the other hand, if the in-class declaration does
11537 *not* provide a definition, then we don't want to alter
11538 existing definitions. We can just leave everything
11539 alone. */
11541 else
11543 tree new_template = TI_TEMPLATE (new_friend_template_info);
11544 tree new_args = TI_ARGS (new_friend_template_info);
11546 /* Overwrite whatever template info was there before, if
11547 any, with the new template information pertaining to
11548 the declaration. */
11549 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11551 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11553 /* We should have called reregister_specialization in
11554 duplicate_decls. */
11555 gcc_assert (retrieve_specialization (new_template,
11556 new_args, 0)
11557 == old_decl);
11559 /* Instantiate it if the global has already been used. */
11560 if (DECL_ODR_USED (old_decl))
11561 instantiate_decl (old_decl, /*defer_ok=*/true,
11562 /*expl_inst_class_mem_p=*/false);
11564 else
11566 tree t;
11568 /* Indicate that the old function template is a partial
11569 instantiation. */
11570 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11571 = new_friend_result_template_info;
11573 gcc_assert (new_template
11574 == most_general_template (new_template));
11575 gcc_assert (new_template != old_decl);
11577 /* Reassign any specializations already in the hash table
11578 to the new more general template, and add the
11579 additional template args. */
11580 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11581 t != NULL_TREE;
11582 t = TREE_CHAIN (t))
11584 tree spec = TREE_VALUE (t);
11585 spec_entry elt;
11587 elt.tmpl = old_decl;
11588 elt.args = DECL_TI_ARGS (spec);
11589 elt.spec = NULL_TREE;
11591 decl_specializations->remove_elt (&elt);
11593 DECL_TI_ARGS (spec)
11594 = add_outermost_template_args (new_args,
11595 DECL_TI_ARGS (spec));
11597 register_specialization
11598 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11601 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11605 /* The information from NEW_FRIEND has been merged into OLD_DECL
11606 by duplicate_decls. */
11607 new_friend = old_decl;
11610 /* We've just introduced a namespace-scope function in the purview
11611 without necessarily having opened the enclosing namespace, so
11612 make sure the namespace is in the purview now too. */
11613 if (modules_p ()
11614 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11615 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11616 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11618 else
11620 tree context = DECL_CONTEXT (new_friend);
11621 bool dependent_p;
11623 /* In the code
11624 template <class T> class C {
11625 template <class U> friend void C1<U>::f (); // case 1
11626 friend void C2<T>::f (); // case 2
11628 we only need to make sure CONTEXT is a complete type for
11629 case 2. To distinguish between the two cases, we note that
11630 CONTEXT of case 1 remains dependent type after tsubst while
11631 this isn't true for case 2. */
11632 ++processing_template_decl;
11633 dependent_p = dependent_type_p (context);
11634 --processing_template_decl;
11636 if (!dependent_p
11637 && !complete_type_or_else (context, NULL_TREE))
11638 return error_mark_node;
11640 if (COMPLETE_TYPE_P (context))
11642 tree fn = new_friend;
11643 /* do_friend adds the TEMPLATE_DECL for any member friend
11644 template even if it isn't a member template, i.e.
11645 template <class T> friend A<T>::f();
11646 Look through it in that case. */
11647 if (TREE_CODE (fn) == TEMPLATE_DECL
11648 && !PRIMARY_TEMPLATE_P (fn))
11649 fn = DECL_TEMPLATE_RESULT (fn);
11650 /* Check to see that the declaration is really present, and,
11651 possibly obtain an improved declaration. */
11652 fn = check_classfn (context, fn, NULL_TREE);
11654 if (fn)
11655 new_friend = fn;
11659 return new_friend;
11662 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11663 template arguments, as for tsubst.
11665 Returns an appropriate tsubst'd friend type or error_mark_node on
11666 failure. */
11668 static tree
11669 tsubst_friend_class (tree friend_tmpl, tree args)
11671 tree tmpl;
11673 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11675 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11676 return TREE_TYPE (tmpl);
11679 tree context = CP_DECL_CONTEXT (friend_tmpl);
11680 if (TREE_CODE (context) == NAMESPACE_DECL)
11681 push_nested_namespace (context);
11682 else
11684 context = tsubst (context, args, tf_error, NULL_TREE);
11685 push_nested_class (context);
11688 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11689 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11691 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11693 /* The friend template has already been declared. Just
11694 check to see that the declarations match, and install any new
11695 default parameters. We must tsubst the default parameters,
11696 of course. We only need the innermost template parameters
11697 because that is all that redeclare_class_template will look
11698 at. */
11699 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11700 > TMPL_ARGS_DEPTH (args))
11702 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11703 args, tf_warning_or_error);
11704 tsubst_each_template_parm_constraints (parms, args,
11705 tf_warning_or_error);
11706 location_t saved_input_location = input_location;
11707 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11708 tree cons = get_constraints (friend_tmpl);
11709 ++processing_template_decl;
11710 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11711 DECL_FRIEND_CONTEXT (friend_tmpl));
11712 --processing_template_decl;
11713 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11714 input_location = saved_input_location;
11717 else
11719 /* The friend template has not already been declared. In this
11720 case, the instantiation of the template class will cause the
11721 injection of this template into the namespace scope. */
11722 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11724 if (tmpl != error_mark_node)
11726 /* The new TMPL is not an instantiation of anything, so we
11727 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11728 for the new type because that is supposed to be the
11729 corresponding template decl, i.e., TMPL. */
11730 DECL_USE_TEMPLATE (tmpl) = 0;
11731 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11732 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11733 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11734 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11736 /* Substitute into and set the constraints on the new declaration. */
11737 if (tree ci = get_constraints (friend_tmpl))
11739 ++processing_template_decl;
11740 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11741 DECL_FRIEND_CONTEXT (friend_tmpl));
11742 --processing_template_decl;
11743 set_constraints (tmpl, ci);
11744 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11745 args, tf_warning_or_error);
11748 /* Inject this template into the enclosing namspace scope. */
11749 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11753 if (TREE_CODE (context) == NAMESPACE_DECL)
11754 pop_nested_namespace (context);
11755 else
11756 pop_nested_class ();
11758 return TREE_TYPE (tmpl);
11761 /* Returns zero if TYPE cannot be completed later due to circularity.
11762 Otherwise returns one. */
11764 static int
11765 can_complete_type_without_circularity (tree type)
11767 if (type == NULL_TREE || type == error_mark_node)
11768 return 0;
11769 else if (COMPLETE_TYPE_P (type))
11770 return 1;
11771 else if (TREE_CODE (type) == ARRAY_TYPE)
11772 return can_complete_type_without_circularity (TREE_TYPE (type));
11773 else if (CLASS_TYPE_P (type)
11774 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11775 return 0;
11776 else
11777 return 1;
11780 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11781 tsubst_flags_t, tree);
11783 /* Instantiate the contract statement. */
11785 static tree
11786 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11787 tree in_decl)
11789 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11790 bool auto_p = type_uses_auto (type);
11792 tree r = copy_node (t);
11794 /* Rebuild the result variable. */
11795 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11797 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11799 tree newvar = copy_node (oldvar);
11800 TREE_TYPE (newvar) = type;
11801 DECL_CONTEXT (newvar) = decl;
11802 POSTCONDITION_IDENTIFIER (r) = newvar;
11804 /* Make sure the postcondition is valid. */
11805 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11806 if (!auto_p)
11807 if (!check_postcondition_result (decl, type, loc))
11808 return invalidate_contract (r);
11810 /* Make the variable available for lookup. */
11811 register_local_specialization (newvar, oldvar);
11814 /* Instantiate the condition. If the return type is undeduced, process
11815 the expression as if inside a template to avoid spurious type errors. */
11816 if (auto_p)
11817 ++processing_template_decl;
11818 ++processing_contract_condition;
11819 CONTRACT_CONDITION (r)
11820 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11821 --processing_contract_condition;
11822 if (auto_p)
11823 --processing_template_decl;
11825 /* And the comment. */
11826 CONTRACT_COMMENT (r)
11827 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11829 return r;
11832 /* Update T by instantiating its contract attribute. */
11834 static void
11835 tsubst_contract_attribute (tree decl, tree t, tree args,
11836 tsubst_flags_t complain, tree in_decl)
11838 /* For non-specializations, adjust the current declaration to the most general
11839 version of in_decl. Because we defer the instantiation of contracts as long
11840 as possible, they are still written in terms of the parameters (and return
11841 type) of the most general template. */
11842 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11843 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11844 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11845 local_specialization_stack specs (lss_copy);
11846 register_parameter_specializations (in_decl, decl);
11848 /* Get the contract to be instantiated. */
11849 tree contract = CONTRACT_STATEMENT (t);
11851 /* Use the complete set of template arguments for instantiation. The
11852 contract may not have been instantiated and still refer to outer levels
11853 of template parameters. */
11854 args = DECL_TI_ARGS (decl);
11856 /* For member functions, make this available for semantic analysis. */
11857 tree save_ccp = current_class_ptr;
11858 tree save_ccr = current_class_ref;
11859 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
11861 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11862 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11863 inject_this_parameter (this_type, cp_type_quals (this_type));
11866 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11868 current_class_ptr = save_ccp;
11869 current_class_ref = save_ccr;
11871 /* Rebuild the attribute. */
11872 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11875 /* Rebuild the attribute list for DECL, substituting into contracts
11876 as needed. */
11878 void
11879 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11881 tree list = copy_list (DECL_ATTRIBUTES (decl));
11882 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11884 if (cxx_contract_attribute_p (attr))
11885 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11887 DECL_ATTRIBUTES (decl) = list;
11890 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11891 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11893 static tree
11894 tsubst_attribute (tree t, tree *decl_p, tree args,
11895 tsubst_flags_t complain, tree in_decl)
11897 gcc_assert (ATTR_IS_DEPENDENT (t));
11899 /* Note that contract attributes are never substituted from this function.
11900 Their instantiation is triggered by regenerate_from_template_decl when
11901 we instantiate the body of the function. */
11903 tree val = TREE_VALUE (t);
11904 if (val == NULL_TREE)
11905 /* Nothing to do. */;
11906 else if ((flag_openmp || flag_openmp_simd)
11907 && is_attribute_p ("omp declare simd",
11908 get_attribute_name (t)))
11910 tree clauses = TREE_VALUE (val);
11911 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11912 complain, in_decl);
11913 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11914 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11915 tree parms = DECL_ARGUMENTS (*decl_p);
11916 clauses
11917 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11918 if (clauses)
11919 val = build_tree_list (NULL_TREE, clauses);
11920 else
11921 val = NULL_TREE;
11923 else if (flag_openmp
11924 && is_attribute_p ("omp declare variant base",
11925 get_attribute_name (t)))
11927 ++cp_unevaluated_operand;
11928 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11929 --cp_unevaluated_operand;
11930 tree chain = TREE_CHAIN (val);
11931 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11932 tree ctx = copy_list (TREE_VALUE (val));
11933 for (tree tss = ctx; tss; tss = TREE_CHAIN (tss))
11935 enum omp_tss_code set = OMP_TSS_CODE (tss);
11936 tree selectors = NULL_TREE;
11937 for (tree ts = OMP_TSS_TRAIT_SELECTORS (tss); ts;
11938 ts = TREE_CHAIN (ts))
11940 tree properties = NULL_TREE;
11941 tree scoreval = NULL_TREE;
11942 /* FIXME: The body of this loop should really be dispatching
11943 according to omp_ts_map[OMP_TS_CODE (TS)].tp_type instead
11944 of having hard-wired knowledge of specific selectors. */
11945 if (OMP_TS_CODE (ts) == OMP_TRAIT_CONSTRUCT_SIMD
11946 && set == OMP_TRAIT_SET_CONSTRUCT)
11948 tree clauses = OMP_TS_PROPERTIES (ts);
11949 clauses = tsubst_omp_clauses (clauses,
11950 C_ORT_OMP_DECLARE_SIMD, args,
11951 complain, in_decl);
11952 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11953 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11954 properties = clauses;
11956 else
11958 tree v = OMP_TS_SCORE (ts);
11959 if (v)
11961 v = tsubst_expr (v, args, complain, in_decl);
11962 v = fold_non_dependent_expr (v);
11963 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11964 || TREE_CODE (v) != INTEGER_CST)
11966 location_t loc
11967 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
11968 match_loc);
11969 error_at (loc, "score argument must be "
11970 "constant integer expression");
11971 return NULL_TREE;
11973 else if (tree_int_cst_sgn (v) < 0)
11975 location_t loc
11976 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
11977 match_loc);
11978 error_at (loc, "score argument must be "
11979 "non-negative");
11980 return NULL_TREE;
11982 scoreval = v;
11984 properties = copy_list (OMP_TS_PROPERTIES (ts));
11985 for (tree p = properties; p; p = TREE_CHAIN (p))
11986 if (OMP_TP_NAME (p) == OMP_TP_NAMELIST_NODE)
11987 continue;
11988 else if (OMP_TP_VALUE (p))
11990 bool allow_string
11991 = (OMP_TS_CODE (ts) != OMP_TRAIT_USER_CONDITION
11992 || set != OMP_TRAIT_SET_USER);
11993 tree v = OMP_TP_VALUE (p);
11994 if (TREE_CODE (v) == STRING_CST && allow_string)
11995 continue;
11996 v = tsubst_expr (v, args, complain, in_decl);
11997 v = fold_non_dependent_expr (v);
11998 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11999 || !tree_fits_shwi_p (v))
12001 location_t loc
12002 = cp_expr_loc_or_loc (OMP_TP_VALUE (p),
12003 match_loc);
12004 if (allow_string)
12005 error_at (loc, "property must be constant "
12006 "integer expression or string "
12007 "literal");
12008 else
12009 error_at (loc, "property must be constant "
12010 "integer expression");
12011 return NULL_TREE;
12013 OMP_TP_VALUE (p) = v;
12016 selectors = make_trait_selector (OMP_TS_CODE (ts), scoreval,
12017 properties, selectors);
12019 OMP_TSS_TRAIT_SELECTORS (tss) = nreverse (selectors);
12021 val = tree_cons (varid, ctx, chain);
12023 /* If the first attribute argument is an identifier, don't
12024 pass it through tsubst. Attributes like mode, format,
12025 cleanup and several target specific attributes expect it
12026 unmodified. */
12027 else if (attribute_takes_identifier_p (get_attribute_name (t)))
12029 tree chain
12030 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
12031 if (chain != TREE_CHAIN (val))
12032 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
12034 else if (PACK_EXPANSION_P (val))
12036 /* An attribute pack expansion. */
12037 tree purp = TREE_PURPOSE (t);
12038 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
12039 if (pack == error_mark_node)
12040 return error_mark_node;
12041 int len = TREE_VEC_LENGTH (pack);
12042 tree list = NULL_TREE;
12043 tree *q = &list;
12044 for (int i = 0; i < len; ++i)
12046 tree elt = TREE_VEC_ELT (pack, i);
12047 *q = build_tree_list (purp, elt);
12048 q = &TREE_CHAIN (*q);
12050 return list;
12052 else
12053 val = tsubst_expr (val, args, complain, in_decl);
12055 if (val == error_mark_node)
12056 return error_mark_node;
12057 if (val != TREE_VALUE (t))
12058 return build_tree_list (TREE_PURPOSE (t), val);
12059 return t;
12062 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
12063 unchanged or a new TREE_LIST chain. */
12065 static tree
12066 tsubst_attributes (tree attributes, tree args,
12067 tsubst_flags_t complain, tree in_decl)
12069 tree last_dep = NULL_TREE;
12071 for (tree t = attributes; t; t = TREE_CHAIN (t))
12072 if (ATTR_IS_DEPENDENT (t))
12074 last_dep = t;
12075 attributes = copy_list (attributes);
12076 break;
12079 if (last_dep)
12080 for (tree *p = &attributes; *p; )
12082 tree t = *p;
12083 if (ATTR_IS_DEPENDENT (t))
12085 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
12086 if (subst != t)
12088 *p = subst;
12089 while (*p)
12090 p = &TREE_CHAIN (*p);
12091 *p = TREE_CHAIN (t);
12092 continue;
12095 p = &TREE_CHAIN (*p);
12098 return attributes;
12101 /* Apply any attributes which had to be deferred until instantiation
12102 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
12103 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
12104 false on error. */
12106 static bool
12107 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
12108 tree args, tsubst_flags_t complain, tree in_decl)
12110 tree t;
12111 tree *p;
12113 if (attributes == NULL_TREE)
12114 return true;
12116 if (DECL_P (*decl_p))
12118 if (TREE_TYPE (*decl_p) == error_mark_node)
12119 return false;
12120 p = &DECL_ATTRIBUTES (*decl_p);
12121 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
12122 to our attributes parameter. */
12123 gcc_assert (*p == attributes);
12125 else
12127 p = &TYPE_ATTRIBUTES (*decl_p);
12128 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
12129 lookup_template_class_1, and should be preserved. */
12130 gcc_assert (*p != attributes);
12131 while (*p)
12132 p = &TREE_CHAIN (*p);
12135 /* save_template_attributes puts the dependent attributes at the beginning of
12136 the list; find the non-dependent ones. */
12137 for (t = attributes; t; t = TREE_CHAIN (t))
12138 if (!ATTR_IS_DEPENDENT (t))
12139 break;
12140 tree nondep = t;
12142 /* Apply any non-dependent attributes. */
12143 *p = nondep;
12145 if (nondep == attributes)
12146 return true;
12148 /* And then any dependent ones. */
12149 tree late_attrs = NULL_TREE;
12150 tree *q = &late_attrs;
12151 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12153 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12154 if (*q == error_mark_node)
12155 return false;
12156 if (*q == t)
12158 *q = copy_node (t);
12159 TREE_CHAIN (*q) = NULL_TREE;
12161 while (*q)
12162 q = &TREE_CHAIN (*q);
12165 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12166 those attributes should have been added already when those templates were
12167 parsed, and shouldn't be added based on from which context they are
12168 first time instantiated. */
12169 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12170 auto o2 = make_temp_override (optimization_current_node,
12171 optimization_default_node);
12172 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12173 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12174 NULL);
12175 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12177 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12179 return true;
12182 /* The template TMPL is being instantiated with the template arguments TARGS.
12183 Perform the access checks that we deferred when parsing the template. */
12185 static void
12186 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12188 unsigned i;
12189 deferred_access_check *chk;
12191 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12192 return;
12194 if (vec<deferred_access_check, va_gc> *access_checks
12195 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12196 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12198 tree decl = chk->decl;
12199 tree diag_decl = chk->diag_decl;
12200 tree type_scope = TREE_TYPE (chk->binfo);
12202 if (uses_template_parms (type_scope))
12203 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12205 /* Make access check error messages point to the location
12206 of the use of the typedef. */
12207 iloc_sentinel ils (chk->loc);
12208 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12209 decl, diag_decl, tf_warning_or_error);
12213 tree
12214 instantiate_class_template (tree type)
12216 auto_timevar tv (TV_TEMPLATE_INST);
12218 tree templ, args, pattern, t, member;
12219 tree typedecl;
12220 tree pbinfo;
12221 tree base_list;
12222 unsigned int saved_maximum_field_alignment;
12223 tree fn_context;
12225 if (type == error_mark_node)
12226 return error_mark_node;
12228 if (COMPLETE_OR_OPEN_TYPE_P (type)
12229 || uses_template_parms (type))
12230 return type;
12232 /* Figure out which template is being instantiated. */
12233 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12234 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12236 /* Mark the type as in the process of being defined. */
12237 TYPE_BEING_DEFINED (type) = 1;
12239 /* We may be in the middle of deferred access check. Disable
12240 it now. */
12241 deferring_access_check_sentinel acs (dk_no_deferred);
12243 /* Determine what specialization of the original template to
12244 instantiate. */
12245 t = most_specialized_partial_spec (type, tf_warning_or_error);
12246 if (t == error_mark_node)
12247 return error_mark_node;
12248 else if (t)
12250 /* This TYPE is actually an instantiation of a partial
12251 specialization. We replace the innermost set of ARGS with
12252 the arguments appropriate for substitution. For example,
12253 given:
12255 template <class T> struct S {};
12256 template <class T> struct S<T*> {};
12258 and supposing that we are instantiating S<int*>, ARGS will
12259 presently be {int*} -- but we need {int}. */
12260 pattern = TREE_TYPE (TI_TEMPLATE (t));
12261 args = TI_ARGS (t);
12263 else
12265 pattern = TREE_TYPE (templ);
12266 args = CLASSTYPE_TI_ARGS (type);
12269 /* If the template we're instantiating is incomplete, then clearly
12270 there's nothing we can do. */
12271 if (!COMPLETE_TYPE_P (pattern))
12273 /* We can try again later. */
12274 TYPE_BEING_DEFINED (type) = 0;
12275 return type;
12278 /* If we've recursively instantiated too many templates, stop. */
12279 if (! push_tinst_level (type))
12280 return type;
12282 int saved_unevaluated_operand = cp_unevaluated_operand;
12283 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12285 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12286 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12287 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12288 fn_context = error_mark_node;
12289 if (!fn_context)
12290 push_to_top_level ();
12291 else
12293 cp_unevaluated_operand = 0;
12294 c_inhibit_evaluation_warnings = 0;
12297 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12299 /* Use #pragma pack from the template context. */
12300 saved_maximum_field_alignment = maximum_field_alignment;
12301 maximum_field_alignment = TYPE_PRECISION (pattern);
12303 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12305 /* Set the input location to the most specialized template definition.
12306 This is needed if tsubsting causes an error. */
12307 typedecl = TYPE_MAIN_DECL (pattern);
12308 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12309 DECL_SOURCE_LOCATION (typedecl);
12311 set_instantiating_module (TYPE_NAME (type));
12313 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12314 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12315 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12316 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12317 if (ANON_AGGR_TYPE_P (pattern))
12318 SET_ANON_AGGR_TYPE_P (type);
12319 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12321 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12322 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12323 /* Adjust visibility for template arguments. */
12324 determine_visibility (TYPE_MAIN_DECL (type));
12326 if (CLASS_TYPE_P (type))
12327 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12329 pbinfo = TYPE_BINFO (pattern);
12331 /* We should never instantiate a nested class before its enclosing
12332 class; we need to look up the nested class by name before we can
12333 instantiate it, and that lookup should instantiate the enclosing
12334 class. */
12335 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12336 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12338 base_list = NULL_TREE;
12339 /* Defer access checking while we substitute into the types named in
12340 the base-clause. */
12341 push_deferring_access_checks (dk_deferred);
12342 if (BINFO_N_BASE_BINFOS (pbinfo))
12344 tree pbase_binfo;
12345 int i;
12347 /* Substitute into each of the bases to determine the actual
12348 basetypes. */
12349 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12351 tree base;
12352 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12353 tree expanded_bases = NULL_TREE;
12354 int idx, len = 1;
12356 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12358 expanded_bases =
12359 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12360 args, tf_error, NULL_TREE);
12361 if (expanded_bases == error_mark_node)
12362 continue;
12364 len = TREE_VEC_LENGTH (expanded_bases);
12367 for (idx = 0; idx < len; idx++)
12369 if (expanded_bases)
12370 /* Extract the already-expanded base class. */
12371 base = TREE_VEC_ELT (expanded_bases, idx);
12372 else
12373 /* Substitute to figure out the base class. */
12374 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12375 NULL_TREE);
12377 if (base == error_mark_node)
12378 continue;
12380 base_list = tree_cons (access, base, base_list);
12381 if (BINFO_VIRTUAL_P (pbase_binfo))
12382 TREE_TYPE (base_list) = integer_type_node;
12386 /* The list is now in reverse order; correct that. */
12387 base_list = nreverse (base_list);
12389 /* Now call xref_basetypes to set up all the base-class
12390 information. */
12391 xref_basetypes (type, base_list);
12393 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12394 (int) ATTR_FLAG_TYPE_IN_PLACE,
12395 args, tf_error, NULL_TREE);
12396 fixup_attribute_variants (type);
12398 /* Now that our base classes are set up, enter the scope of the
12399 class, so that name lookups into base classes, etc. will work
12400 correctly. This is precisely analogous to what we do in
12401 begin_class_definition when defining an ordinary non-template
12402 class, except we also need to push the enclosing classes. */
12403 push_nested_class (type);
12405 /* Now check accessibility of the types named in its base-clause,
12406 relative to the scope of the class. */
12407 pop_to_parent_deferring_access_checks ();
12409 /* A vector to hold members marked with attribute used. */
12410 auto_vec<tree> used;
12412 /* Now members are processed in the order of declaration. */
12413 for (member = CLASSTYPE_DECL_LIST (pattern);
12414 member; member = TREE_CHAIN (member))
12416 tree t = TREE_VALUE (member);
12418 if (TREE_PURPOSE (member))
12420 if (TYPE_P (t))
12422 if (LAMBDA_TYPE_P (t))
12423 /* A closure type for a lambda in an NSDMI or default argument.
12424 Ignore it; it will be regenerated when needed. */
12425 continue;
12427 /* If the member is a class template, we've
12428 already substituted its type. */
12429 if (CLASS_TYPE_P (t)
12430 && CLASSTYPE_IS_TEMPLATE (t))
12431 continue;
12433 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12434 if (newtag == error_mark_node)
12435 continue;
12437 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12439 tree name = TYPE_IDENTIFIER (t);
12441 /* Now, install the tag. We don't use pushtag
12442 because that does too much work -- creating an
12443 implicit typedef, which we've already done. */
12444 set_identifier_type_value (name, TYPE_NAME (newtag));
12445 maybe_add_class_template_decl_list (type, newtag, false);
12446 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12447 determine_visibility (TYPE_NAME (newtag));
12450 else if (DECL_DECLARES_FUNCTION_P (t))
12452 tree r;
12454 if (TREE_CODE (t) == TEMPLATE_DECL)
12455 ++processing_template_decl;
12456 r = tsubst (t, args, tf_error, NULL_TREE);
12457 if (TREE_CODE (t) == TEMPLATE_DECL)
12458 --processing_template_decl;
12460 set_current_access_from_decl (r);
12461 finish_member_declaration (r);
12462 /* Instantiate members marked with attribute used. */
12463 if (r != error_mark_node && DECL_PRESERVE_P (r))
12464 used.safe_push (r);
12465 if (TREE_CODE (r) == FUNCTION_DECL
12466 && DECL_OMP_DECLARE_REDUCTION_P (r))
12467 cp_check_omp_declare_reduction (r);
12469 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12470 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12471 /* A closure type for a lambda in an NSDMI or default argument.
12472 Ignore it; it will be regenerated when needed. */;
12473 else
12475 /* Build new TYPE_FIELDS. */
12476 if (TREE_CODE (t) == STATIC_ASSERT)
12477 tsubst_stmt (t, args, tf_warning_or_error, NULL_TREE);
12478 else if (TREE_CODE (t) != CONST_DECL)
12480 tree r;
12481 tree vec = NULL_TREE;
12482 int len = 1;
12484 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12485 /* The file and line for this declaration, to
12486 assist in error message reporting. Since we
12487 called push_tinst_level above, we don't need to
12488 restore these. */
12489 input_location = DECL_SOURCE_LOCATION (t);
12491 if (TREE_CODE (t) == TEMPLATE_DECL)
12492 ++processing_template_decl;
12493 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12494 if (TREE_CODE (t) == TEMPLATE_DECL)
12495 --processing_template_decl;
12497 if (TREE_CODE (r) == TREE_VEC)
12499 /* A capture pack became multiple fields. */
12500 vec = r;
12501 len = TREE_VEC_LENGTH (vec);
12504 for (int i = 0; i < len; ++i)
12506 if (vec)
12507 r = TREE_VEC_ELT (vec, i);
12508 if (VAR_P (r))
12510 /* In [temp.inst]:
12512 [t]he initialization (and any associated
12513 side-effects) of a static data member does
12514 not occur unless the static data member is
12515 itself used in a way that requires the
12516 definition of the static data member to
12517 exist.
12519 Therefore, we do not substitute into the
12520 initialized for the static data member here. */
12521 finish_static_data_member_decl
12523 /*init=*/NULL_TREE,
12524 /*init_const_expr_p=*/false,
12525 /*asmspec_tree=*/NULL_TREE,
12526 /*flags=*/0);
12527 /* Instantiate members marked with attribute used. */
12528 if (r != error_mark_node && DECL_PRESERVE_P (r))
12529 used.safe_push (r);
12531 else if (TREE_CODE (r) == FIELD_DECL)
12533 /* Determine whether R has a valid type and can be
12534 completed later. If R is invalid, then its type
12535 is replaced by error_mark_node. */
12536 tree rtype = TREE_TYPE (r);
12537 if (can_complete_type_without_circularity (rtype))
12538 complete_type (rtype);
12540 if (!complete_or_array_type_p (rtype))
12542 /* If R's type couldn't be completed and
12543 it isn't a flexible array member (whose
12544 type is incomplete by definition) give
12545 an error. */
12546 cxx_incomplete_type_error (r, rtype);
12547 TREE_TYPE (r) = error_mark_node;
12549 else if (TREE_CODE (rtype) == ARRAY_TYPE
12550 && TYPE_DOMAIN (rtype) == NULL_TREE
12551 && (TREE_CODE (type) == UNION_TYPE
12552 || TREE_CODE (type) == QUAL_UNION_TYPE))
12554 error ("flexible array member %qD in union", r);
12555 TREE_TYPE (r) = error_mark_node;
12557 else if (!verify_type_context (input_location,
12558 TCTX_FIELD, rtype))
12559 TREE_TYPE (r) = error_mark_node;
12562 /* If it is a TYPE_DECL for a class-scoped
12563 ENUMERAL_TYPE, such a thing will already have
12564 been added to the field list by tsubst_enum
12565 in finish_member_declaration case above. */
12566 if (!(TREE_CODE (r) == TYPE_DECL
12567 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12568 && DECL_ARTIFICIAL (r)))
12570 set_current_access_from_decl (r);
12571 finish_member_declaration (r);
12577 else
12579 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12580 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12582 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12584 tree friend_type = t;
12585 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12587 /* template <class T> friend class C; */
12588 friend_type = tsubst_friend_class (friend_type, args);
12590 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12592 /* template <class T> friend class C::D; */
12593 friend_type = tsubst (friend_type, args,
12594 tf_warning_or_error, NULL_TREE);
12595 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12596 friend_type = TREE_TYPE (friend_type);
12598 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12599 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12601 /* This could be either
12603 friend class T::C;
12605 when dependent_type_p is false or
12607 template <class U> friend class T::C;
12609 otherwise. */
12610 /* Bump processing_template_decl in case this is something like
12611 template <class T> friend struct A<T>::B. */
12612 ++processing_template_decl;
12613 friend_type = tsubst (friend_type, args,
12614 tf_warning_or_error, NULL_TREE);
12615 --processing_template_decl;
12617 else if (uses_template_parms (friend_type))
12618 /* friend class C<T>; */
12619 friend_type = tsubst (friend_type, args,
12620 tf_warning_or_error, NULL_TREE);
12622 /* Otherwise it's
12624 friend class C;
12626 where C is already declared or
12628 friend class C<int>;
12630 We don't have to do anything in these cases. */
12632 if (friend_type != error_mark_node)
12633 make_friend_class (type, friend_type, /*complain=*/false);
12635 else
12637 /* Build new DECL_FRIENDLIST. */
12638 tree r;
12640 /* The file and line for this declaration, to
12641 assist in error message reporting. Since we
12642 called push_tinst_level above, we don't need to
12643 restore these. */
12644 input_location = DECL_SOURCE_LOCATION (t);
12646 if (TREE_CODE (t) == TEMPLATE_DECL)
12648 ++processing_template_decl;
12649 push_deferring_access_checks (dk_no_check);
12652 r = tsubst_friend_function (t, args);
12653 add_friend (type, r, /*complain=*/false);
12654 if (TREE_CODE (t) == TEMPLATE_DECL)
12656 pop_deferring_access_checks ();
12657 --processing_template_decl;
12663 if (fn_context)
12665 /* Restore these before substituting into the lambda capture
12666 initializers. */
12667 cp_unevaluated_operand = saved_unevaluated_operand;
12668 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12671 /* Set the file and line number information to whatever is given for
12672 the class itself. This puts error messages involving generated
12673 implicit functions at a predictable point, and the same point
12674 that would be used for non-template classes. */
12675 input_location = DECL_SOURCE_LOCATION (typedecl);
12677 unreverse_member_declarations (type);
12678 finish_struct_1 (type);
12679 TYPE_BEING_DEFINED (type) = 0;
12681 /* Remember if instantiating this class ran into errors, so we can avoid
12682 instantiating member functions in limit_bad_template_recursion. We set
12683 this flag even if the problem was in another instantiation triggered by
12684 this one, as that will likely also cause trouble for member functions. */
12685 if (errorcount + sorrycount > current_tinst_level->errors)
12686 CLASSTYPE_ERRONEOUS (type) = true;
12688 /* We don't instantiate default arguments for member functions. 14.7.1:
12690 The implicit instantiation of a class template specialization causes
12691 the implicit instantiation of the declarations, but not of the
12692 definitions or default arguments, of the class member functions,
12693 member classes, static data members and member templates.... */
12695 perform_instantiation_time_access_checks (pattern, args);
12696 perform_deferred_access_checks (tf_warning_or_error);
12698 /* Now that we've gone through all the members, instantiate those
12699 marked with attribute used. We must do this in the context of
12700 the class -- not the context we pushed from, as that might be
12701 inside a template and change the behaviour of mark_used. */
12702 for (tree x : used)
12703 mark_used (x);
12705 pop_nested_class ();
12706 maximum_field_alignment = saved_maximum_field_alignment;
12707 if (!fn_context)
12708 pop_from_top_level ();
12709 pop_tinst_level ();
12711 /* The vtable for a template class can be emitted in any translation
12712 unit in which the class is instantiated. When there is no key
12713 method, however, finish_struct_1 will already have added TYPE to
12714 the keyed_classes. */
12715 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12716 vec_safe_push (keyed_classes, type);
12718 return type;
12721 tree
12722 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12724 tree r;
12726 if (!t)
12727 r = t;
12728 else if (TYPE_P (t))
12729 r = tsubst (t, args, complain, in_decl);
12730 else
12732 if (!(complain & tf_warning))
12733 ++c_inhibit_evaluation_warnings;
12734 r = tsubst_expr (t, args, complain, in_decl);
12735 if (!(complain & tf_warning))
12736 --c_inhibit_evaluation_warnings;
12739 return r;
12742 /* Given a function parameter pack TMPL_PARM and some function parameters
12743 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12744 and set *SPEC_P to point at the next point in the list. */
12746 tree
12747 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12749 /* Collect all of the extra "packed" parameters into an
12750 argument pack. */
12751 tree argpack;
12752 tree spec_parm = *spec_p;
12753 int len;
12755 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12756 if (tmpl_parm
12757 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12758 break;
12760 spec_parm = *spec_p;
12761 if (len == 1 && DECL_PACK_P (spec_parm))
12763 /* The instantiation is still a parameter pack; don't wrap it in a
12764 NONTYPE_ARGUMENT_PACK. */
12765 argpack = spec_parm;
12766 spec_parm = DECL_CHAIN (spec_parm);
12768 else
12770 /* Fill in PARMVEC with all of the parameters. */
12771 tree parmvec = make_tree_vec (len);
12772 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12773 for (int i = 0; i < len; i++)
12775 tree elt = spec_parm;
12776 if (DECL_PACK_P (elt))
12777 elt = make_pack_expansion (elt);
12778 TREE_VEC_ELT (parmvec, i) = elt;
12779 spec_parm = DECL_CHAIN (spec_parm);
12782 /* Build the argument packs. */
12783 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12785 *spec_p = spec_parm;
12787 return argpack;
12790 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12791 NONTYPE_ARGUMENT_PACK. */
12793 static tree
12794 make_fnparm_pack (tree spec_parm)
12796 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12799 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12800 pack expansion with no extra args, 2 if it has extra args, or 0
12801 if it is not a pack expansion. */
12803 static int
12804 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12806 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12807 /* We're being called before this happens in tsubst_pack_expansion. */
12808 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12809 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12810 if (i >= TREE_VEC_LENGTH (vec))
12811 return 0;
12812 tree elt = TREE_VEC_ELT (vec, i);
12813 if (DECL_P (elt))
12814 /* A decl pack is itself an expansion. */
12815 elt = TREE_TYPE (elt);
12816 if (!PACK_EXPANSION_P (elt))
12817 return 0;
12818 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12819 return 2;
12820 return 1;
12824 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12826 static tree
12827 make_argument_pack_select (tree arg_pack, unsigned index)
12829 tree aps = make_node (ARGUMENT_PACK_SELECT);
12831 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12832 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12834 return aps;
12837 /* This is a subroutine of tsubst_pack_expansion.
12839 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12840 mechanism to store the (non complete list of) arguments of the
12841 substitution and return a non substituted pack expansion, in order
12842 to wait for when we have enough arguments to really perform the
12843 substitution. */
12845 static bool
12846 use_pack_expansion_extra_args_p (tree t,
12847 tree parm_packs,
12848 int arg_pack_len,
12849 bool has_empty_arg)
12851 if (has_empty_arg
12852 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12853 return true;
12855 /* If one pack has an expansion and another pack has a normal
12856 argument or if one pack has an empty argument and an another
12857 one hasn't then tsubst_pack_expansion cannot perform the
12858 substitution and need to fall back on the
12859 PACK_EXPANSION_EXTRA mechanism. */
12860 if (parm_packs == NULL_TREE)
12861 return false;
12862 else if (has_empty_arg)
12864 /* If all the actual packs are pack expansions, we can still
12865 subsitute directly. */
12866 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12868 tree a = TREE_VALUE (p);
12869 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12870 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12871 a = ARGUMENT_PACK_ARGS (a);
12872 if (TREE_VEC_LENGTH (a) == 1)
12873 a = TREE_VEC_ELT (a, 0);
12874 if (PACK_EXPANSION_P (a))
12875 continue;
12876 return true;
12878 return false;
12881 for (int i = 0 ; i < arg_pack_len; ++i)
12883 bool has_expansion_arg = false;
12884 bool has_non_expansion_arg = false;
12885 for (tree parm_pack = parm_packs;
12886 parm_pack;
12887 parm_pack = TREE_CHAIN (parm_pack))
12889 tree arg = TREE_VALUE (parm_pack);
12891 int exp = argument_pack_element_is_expansion_p (arg, i);
12892 if (exp == 2)
12893 /* We can't substitute a pack expansion with extra args into
12894 our pattern. */
12895 return true;
12896 else if (exp)
12897 has_expansion_arg = true;
12898 else
12899 has_non_expansion_arg = true;
12902 if (has_expansion_arg && has_non_expansion_arg)
12904 gcc_checking_assert (false);
12905 return true;
12908 return false;
12911 /* [temp.variadic]/6 says that:
12913 The instantiation of a pack expansion [...]
12914 produces a list E1,E2, ..., En, where N is the number of elements
12915 in the pack expansion parameters.
12917 This subroutine of tsubst_pack_expansion produces one of these Ei.
12919 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12920 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12921 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12922 INDEX is the index 'i' of the element Ei to produce. ARGS,
12923 COMPLAIN, and IN_DECL are the same parameters as for the
12924 tsubst_pack_expansion function.
12926 The function returns the resulting Ei upon successful completion,
12927 or error_mark_node.
12929 Note that this function possibly modifies the ARGS parameter, so
12930 it's the responsibility of the caller to restore it. */
12932 static tree
12933 gen_elem_of_pack_expansion_instantiation (tree pattern,
12934 tree parm_packs,
12935 unsigned index,
12936 tree args /* This parm gets
12937 modified. */,
12938 tsubst_flags_t complain,
12939 tree in_decl)
12941 tree t;
12942 bool ith_elem_is_expansion = false;
12944 /* For each parameter pack, change the substitution of the parameter
12945 pack to the ith argument in its argument pack, then expand the
12946 pattern. */
12947 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12949 tree parm = TREE_PURPOSE (pack);
12950 tree arg_pack = TREE_VALUE (pack);
12951 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12953 ith_elem_is_expansion |=
12954 argument_pack_element_is_expansion_p (arg_pack, index);
12956 /* Select the Ith argument from the pack. */
12957 if (TREE_CODE (parm) == PARM_DECL
12958 || VAR_P (parm)
12959 || TREE_CODE (parm) == FIELD_DECL)
12961 if (index == 0)
12963 aps = make_argument_pack_select (arg_pack, index);
12964 if (!mark_used (parm, complain) && !(complain & tf_error))
12965 return error_mark_node;
12966 register_local_specialization (aps, parm);
12968 else
12969 aps = retrieve_local_specialization (parm);
12971 else
12973 int idx, level;
12974 template_parm_level_and_index (parm, &level, &idx);
12976 if (index == 0)
12978 aps = make_argument_pack_select (arg_pack, index);
12979 /* Update the corresponding argument. */
12980 TMPL_ARG (args, level, idx) = aps;
12982 else
12983 /* Re-use the ARGUMENT_PACK_SELECT. */
12984 aps = TMPL_ARG (args, level, idx);
12986 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12989 /* Substitute into the PATTERN with the (possibly altered)
12990 arguments. */
12991 if (pattern == in_decl)
12992 /* Expanding a fixed parameter pack from
12993 coerce_template_parameter_pack. */
12994 t = tsubst_decl (pattern, args, complain);
12995 else if (pattern == error_mark_node)
12996 t = error_mark_node;
12997 else if (!TYPE_P (pattern))
12998 t = tsubst_expr (pattern, args, complain, in_decl);
12999 else
13001 t = tsubst (pattern, args, complain, in_decl);
13002 if (is_auto (t) && !ith_elem_is_expansion)
13003 /* When expanding the fake auto... pack expansion from add_capture, we
13004 need to mark that the expansion is no longer a pack. */
13005 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
13008 /* If the Ith argument pack element is a pack expansion, then
13009 the Ith element resulting from the substituting is going to
13010 be a pack expansion as well. */
13011 if (ith_elem_is_expansion)
13012 t = make_pack_expansion (t, complain);
13014 return t;
13017 /* When the unexpanded parameter pack in a fold expression expands to an empty
13018 sequence, the value of the expression is as follows; the program is
13019 ill-formed if the operator is not listed in this table.
13021 && true
13022 || false
13023 , void() */
13025 tree
13026 expand_empty_fold (tree t, tsubst_flags_t complain)
13028 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
13029 if (!FOLD_EXPR_MODIFY_P (t))
13030 switch (code)
13032 case TRUTH_ANDIF_EXPR:
13033 return boolean_true_node;
13034 case TRUTH_ORIF_EXPR:
13035 return boolean_false_node;
13036 case COMPOUND_EXPR:
13037 return void_node;
13038 default:
13039 break;
13042 if (complain & tf_error)
13043 error_at (location_of (t),
13044 "fold of empty expansion over %O", code);
13045 return error_mark_node;
13048 /* Given a fold-expression T and a current LEFT and RIGHT operand,
13049 form an expression that combines the two terms using the
13050 operator of T. */
13052 static tree
13053 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
13055 tree_code code = FOLD_EXPR_OP (t);
13057 tree lookups = templated_operator_saved_lookups (t);
13059 // Handle compound assignment operators.
13060 if (FOLD_EXPR_MODIFY_P (t))
13061 return build_x_modify_expr (input_location, left, code, right,
13062 lookups, complain);
13064 warning_sentinel s(warn_parentheses);
13065 switch (code)
13067 case COMPOUND_EXPR:
13068 return build_x_compound_expr (input_location, left, right,
13069 lookups, complain);
13070 default:
13071 return build_x_binary_op (input_location, code,
13072 left, TREE_CODE (left),
13073 right, TREE_CODE (right),
13074 lookups, /*overload=*/NULL,
13075 complain);
13079 /* Substitute ARGS into the pack of a fold expression T. */
13081 static inline tree
13082 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13084 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
13087 /* Substitute ARGS into the pack of a fold expression T. */
13089 static inline tree
13090 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13092 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
13095 /* Expand a PACK of arguments into a grouped as left fold.
13096 Given a pack containing elements A0, A1, ..., An and an
13097 operator @, this builds the expression:
13099 ((A0 @ A1) @ A2) ... @ An
13101 Note that PACK must not be empty.
13103 The operator is defined by the original fold expression T. */
13105 static tree
13106 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
13108 tree left = TREE_VEC_ELT (pack, 0);
13109 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
13111 tree right = TREE_VEC_ELT (pack, i);
13112 left = fold_expression (t, left, right, complain);
13114 return left;
13117 /* Substitute into a unary left fold expression. */
13119 static tree
13120 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
13121 tree in_decl)
13123 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13124 if (pack == error_mark_node)
13125 return error_mark_node;
13126 if (PACK_EXPANSION_P (pack))
13128 tree r = copy_node (t);
13129 FOLD_EXPR_PACK (r) = pack;
13130 return r;
13132 if (TREE_VEC_LENGTH (pack) == 0)
13133 return expand_empty_fold (t, complain);
13134 else
13135 return expand_left_fold (t, pack, complain);
13138 /* Substitute into a binary left fold expression.
13140 Do ths by building a single (non-empty) vector of argumnts and
13141 building the expression from those elements. */
13143 static tree
13144 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13145 tree in_decl)
13147 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13148 if (pack == error_mark_node)
13149 return error_mark_node;
13150 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13151 if (init == error_mark_node)
13152 return error_mark_node;
13154 if (PACK_EXPANSION_P (pack))
13156 tree r = copy_node (t);
13157 FOLD_EXPR_PACK (r) = pack;
13158 FOLD_EXPR_INIT (r) = init;
13159 return r;
13162 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13163 TREE_VEC_ELT (vec, 0) = init;
13164 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13165 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13167 return expand_left_fold (t, vec, complain);
13170 /* Expand a PACK of arguments into a grouped as right fold.
13171 Given a pack containing elementns A0, A1, ..., and an
13172 operator @, this builds the expression:
13174 A0@ ... (An-2 @ (An-1 @ An))
13176 Note that PACK must not be empty.
13178 The operator is defined by the original fold expression T. */
13180 tree
13181 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13183 // Build the expression.
13184 int n = TREE_VEC_LENGTH (pack);
13185 tree right = TREE_VEC_ELT (pack, n - 1);
13186 for (--n; n != 0; --n)
13188 tree left = TREE_VEC_ELT (pack, n - 1);
13189 right = fold_expression (t, left, right, complain);
13191 return right;
13194 /* Substitute into a unary right fold expression. */
13196 static tree
13197 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13198 tree in_decl)
13200 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13201 if (pack == error_mark_node)
13202 return error_mark_node;
13203 if (PACK_EXPANSION_P (pack))
13205 tree r = copy_node (t);
13206 FOLD_EXPR_PACK (r) = pack;
13207 return r;
13209 if (TREE_VEC_LENGTH (pack) == 0)
13210 return expand_empty_fold (t, complain);
13211 else
13212 return expand_right_fold (t, pack, complain);
13215 /* Substitute into a binary right fold expression.
13217 Do ths by building a single (non-empty) vector of arguments and
13218 building the expression from those elements. */
13220 static tree
13221 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13222 tree in_decl)
13224 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13225 if (pack == error_mark_node)
13226 return error_mark_node;
13227 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13228 if (init == error_mark_node)
13229 return error_mark_node;
13231 if (PACK_EXPANSION_P (pack))
13233 tree r = copy_node (t);
13234 FOLD_EXPR_PACK (r) = pack;
13235 FOLD_EXPR_INIT (r) = init;
13236 return r;
13239 int n = TREE_VEC_LENGTH (pack);
13240 tree vec = make_tree_vec (n + 1);
13241 for (int i = 0; i < n; ++i)
13242 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13243 TREE_VEC_ELT (vec, n) = init;
13245 return expand_right_fold (t, vec, complain);
13248 /* Walk through the pattern of a pack expansion, adding everything in
13249 local_specializations to a list. */
13251 class el_data
13253 public:
13254 /* Set of variables declared within the pattern. */
13255 hash_set<tree> internal;
13256 /* Set of AST nodes that have been visited by the traversal. */
13257 hash_set<tree> visited;
13258 /* List of local_specializations used within the pattern. */
13259 tree extra;
13260 tsubst_flags_t complain;
13261 /* True iff we don't want to walk into unevaluated contexts. */
13262 bool skip_unevaluated_operands = false;
13263 /* The unevaluated contexts that we avoided walking. */
13264 auto_vec<tree> skipped_trees;
13266 el_data (tsubst_flags_t c)
13267 : extra (NULL_TREE), complain (c) {}
13269 static tree
13270 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13272 el_data &data = *reinterpret_cast<el_data*>(data_);
13273 tree *extra = &data.extra;
13274 tsubst_flags_t complain = data.complain;
13276 if (data.skip_unevaluated_operands
13277 && unevaluated_p (TREE_CODE (*tp)))
13279 data.skipped_trees.safe_push (*tp);
13280 *walk_subtrees = 0;
13281 return NULL_TREE;
13284 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13285 /* Remember local typedefs (85214). */
13286 tp = &TYPE_NAME (*tp);
13288 if (TREE_CODE (*tp) == DECL_EXPR)
13290 tree decl = DECL_EXPR_DECL (*tp);
13291 data.internal.add (decl);
13292 if (VAR_P (decl)
13293 && DECL_DECOMPOSITION_P (decl)
13294 && TREE_TYPE (decl) != error_mark_node)
13296 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13297 for (tree decl2 = DECL_CHAIN (decl);
13298 decl2
13299 && VAR_P (decl2)
13300 && DECL_DECOMPOSITION_P (decl2)
13301 && DECL_NAME (decl2)
13302 && TREE_TYPE (decl2) != error_mark_node;
13303 decl2 = DECL_CHAIN (decl2))
13305 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13306 data.internal.add (decl2);
13310 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13312 /* Since we defer implicit capture, look in the parms and body. */
13313 tree fn = lambda_function (*tp);
13314 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13315 &data.visited);
13316 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13317 &data.visited);
13319 else if (tree spec = retrieve_local_specialization (*tp))
13321 if (data.internal.contains (*tp))
13322 /* Don't mess with variables declared within the pattern. */
13323 return NULL_TREE;
13324 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13326 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13327 tree args = ARGUMENT_PACK_ARGS (spec);
13328 if (TREE_VEC_LENGTH (args) == 1)
13330 tree elt = TREE_VEC_ELT (args, 0);
13331 if (PACK_EXPANSION_P (elt))
13332 elt = PACK_EXPANSION_PATTERN (elt);
13333 if (DECL_PACK_P (elt))
13334 spec = elt;
13336 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13338 /* Handle lambda capture here, since we aren't doing any
13339 substitution now, and so tsubst_copy won't call
13340 process_outer_var_ref. */
13341 tree args = ARGUMENT_PACK_ARGS (spec);
13342 int len = TREE_VEC_LENGTH (args);
13343 for (int i = 0; i < len; ++i)
13345 tree arg = TREE_VEC_ELT (args, i);
13346 tree carg = arg;
13347 if (outer_automatic_var_p (arg))
13348 carg = process_outer_var_ref (arg, complain);
13349 if (carg != arg)
13351 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13352 proxies. */
13353 if (i == 0)
13355 spec = copy_node (spec);
13356 args = copy_node (args);
13357 ARGUMENT_PACK_ARGS (spec) = args;
13358 register_local_specialization (spec, *tp);
13360 TREE_VEC_ELT (args, i) = carg;
13365 if (outer_automatic_var_p (spec))
13366 spec = process_outer_var_ref (spec, complain);
13367 *extra = tree_cons (*tp, spec, *extra);
13369 return NULL_TREE;
13371 static tree
13372 extract_local_specs (tree pattern, tsubst_flags_t complain)
13374 el_data data (complain);
13375 /* Walk the pattern twice, ignoring unevaluated operands the first time
13376 around, so that if a local specialization appears in both an evaluated
13377 and unevaluated context we prefer to process it in the evaluated context
13378 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13379 context). */
13380 data.skip_unevaluated_operands = true;
13381 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13382 /* Now walk the unevaluated contexts we skipped the first time around. */
13383 data.skip_unevaluated_operands = false;
13384 for (tree t : data.skipped_trees)
13386 data.visited.remove (t);
13387 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13389 return data.extra;
13392 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13393 for use in PACK_EXPANSION_EXTRA_ARGS. */
13395 tree
13396 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13398 /* Make a copy of the extra arguments so that they won't get changed
13399 out from under us. */
13400 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13401 if (local_specializations)
13402 if (tree locals = extract_local_specs (pattern, complain))
13403 extra = tree_cons (NULL_TREE, extra, locals);
13404 return extra;
13407 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13408 normal template args to ARGS. */
13410 tree
13411 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13413 if (extra && TREE_CODE (extra) == TREE_LIST)
13415 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13417 /* The partial instantiation involved local declarations collected in
13418 extract_local_specs; map from the general template to our local
13419 context. */
13420 tree gen = TREE_PURPOSE (elt);
13421 tree inst = TREE_VALUE (elt);
13422 if (DECL_P (inst))
13423 if (tree local = retrieve_local_specialization (inst))
13424 inst = local;
13425 /* else inst is already a full instantiation of the pack. */
13426 register_local_specialization (inst, gen);
13428 gcc_assert (!TREE_PURPOSE (extra));
13429 extra = TREE_VALUE (extra);
13431 if (uses_template_parms (extra))
13433 /* This can happen after dependent substitution into a
13434 requires-expr or a lambda that uses constexpr if. */
13435 extra = tsubst_template_args (extra, args, complain, in_decl);
13436 args = add_outermost_template_args (args, extra);
13438 else
13439 args = add_to_template_args (extra, args);
13440 return args;
13443 /* Substitute ARGS into T, which is an pack expansion
13444 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13445 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13446 (if only a partial substitution could be performed) or
13447 ERROR_MARK_NODE if there was an error. */
13448 tree
13449 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13450 tree in_decl)
13452 tree pattern;
13453 tree pack, packs = NULL_TREE;
13454 bool unsubstituted_packs = false;
13455 int i, len = -1;
13456 tree result;
13457 bool need_local_specializations = false;
13458 int levels;
13460 gcc_assert (PACK_EXPANSION_P (t));
13461 pattern = PACK_EXPANSION_PATTERN (t);
13463 /* Add in any args remembered from an earlier partial instantiation. */
13464 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13466 levels = TMPL_ARGS_DEPTH (args);
13468 /* Determine the argument packs that will instantiate the parameter
13469 packs used in the expansion expression. While we're at it,
13470 compute the number of arguments to be expanded and make sure it
13471 is consistent. */
13472 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13473 pack = TREE_CHAIN (pack))
13475 tree parm_pack = TREE_VALUE (pack);
13476 tree arg_pack = NULL_TREE;
13477 tree orig_arg = NULL_TREE;
13478 int level = 0;
13480 if (TREE_CODE (parm_pack) == BASES)
13482 gcc_assert (parm_pack == pattern);
13483 tree type = tsubst (BASES_TYPE (parm_pack), args, complain, in_decl);
13484 if (BASES_DIRECT (parm_pack))
13485 return calculate_direct_bases (type, complain);
13486 else
13487 return calculate_bases (type, complain);
13489 else if (builtin_pack_call_p (parm_pack))
13491 if (parm_pack != pattern)
13493 if (complain & tf_error)
13494 sorry ("%qE is not the entire pattern of the pack expansion",
13495 parm_pack);
13496 return error_mark_node;
13498 return expand_builtin_pack_call (parm_pack, args,
13499 complain, in_decl);
13501 else if (TREE_CODE (parm_pack) == PARM_DECL)
13503 /* We know we have correct local_specializations if this
13504 expansion is at function scope, or if we're dealing with a
13505 local parameter in a requires expression; for the latter,
13506 tsubst_requires_expr set it up appropriately. */
13507 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13508 arg_pack = retrieve_local_specialization (parm_pack);
13509 else
13510 /* We can't rely on local_specializations for a parameter
13511 name used later in a function declaration (such as in a
13512 late-specified return type). Even if it exists, it might
13513 have the wrong value for a recursive call. */
13514 need_local_specializations = true;
13516 if (!arg_pack)
13518 /* This parameter pack was used in an unevaluated context. Just
13519 make a dummy decl, since it's only used for its type. */
13520 ++cp_unevaluated_operand;
13521 arg_pack = tsubst_decl (parm_pack, args, complain);
13522 --cp_unevaluated_operand;
13523 if (arg_pack && DECL_PACK_P (arg_pack))
13524 /* Partial instantiation of the parm_pack, we can't build
13525 up an argument pack yet. */
13526 arg_pack = NULL_TREE;
13527 else
13528 arg_pack = make_fnparm_pack (arg_pack);
13530 else if (DECL_PACK_P (arg_pack))
13531 /* This argument pack isn't fully instantiated yet. */
13532 arg_pack = NULL_TREE;
13534 else if (is_capture_proxy (parm_pack))
13536 arg_pack = retrieve_local_specialization (parm_pack);
13537 if (DECL_PACK_P (arg_pack))
13538 arg_pack = NULL_TREE;
13540 else
13542 int idx;
13543 template_parm_level_and_index (parm_pack, &level, &idx);
13544 if (level <= levels)
13545 arg_pack = TMPL_ARG (args, level, idx);
13547 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13548 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13549 arg_pack = NULL_TREE;
13552 orig_arg = arg_pack;
13553 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13554 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13556 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13557 /* This can only happen if we forget to expand an argument
13558 pack somewhere else. Just return an error, silently. */
13560 result = make_tree_vec (1);
13561 TREE_VEC_ELT (result, 0) = error_mark_node;
13562 return result;
13565 if (arg_pack)
13567 int my_len =
13568 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13570 /* Don't bother trying to do a partial substitution with
13571 incomplete packs; we'll try again after deduction. */
13572 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13573 return t;
13575 if (len < 0)
13576 len = my_len;
13577 else if (len != my_len)
13579 if (!(complain & tf_error))
13580 /* Fail quietly. */;
13581 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13582 error ("mismatched argument pack lengths while expanding %qT",
13583 pattern);
13584 else
13585 error ("mismatched argument pack lengths while expanding %qE",
13586 pattern);
13587 return error_mark_node;
13590 /* Keep track of the parameter packs and their corresponding
13591 argument packs. */
13592 packs = tree_cons (parm_pack, arg_pack, packs);
13593 TREE_TYPE (packs) = orig_arg;
13595 else
13597 /* We can't substitute for this parameter pack. We use a flag as
13598 well as the missing_level counter because function parameter
13599 packs don't have a level. */
13600 gcc_assert (processing_template_decl || is_auto (parm_pack));
13601 unsubstituted_packs = true;
13605 /* If the expansion is just T..., return the matching argument pack, unless
13606 we need to call convert_from_reference on all the elements. This is an
13607 important optimization; see c++/68422. */
13608 if (!unsubstituted_packs
13609 && TREE_PURPOSE (packs) == pattern)
13611 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13613 /* If the argument pack is a single pack expansion, pull it out. */
13614 if (TREE_VEC_LENGTH (args) == 1
13615 && pack_expansion_args_count (args))
13617 tree arg = TREE_VEC_ELT (args, 0);
13618 if (PACK_EXPANSION_SIZEOF_P (t)
13619 && !TEMPLATE_PARM_P (PACK_EXPANSION_PATTERN (arg)))
13620 /* Except if this isn't a simple sizeof...(T) which gets sZ
13621 mangling, keep the TREE_VEC to get sP mangling. */;
13622 else
13623 return TREE_VEC_ELT (args, 0);
13626 /* Types need no adjustment, nor does sizeof..., and if we still have
13627 some pack expansion args we won't do anything yet. */
13628 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13629 || PACK_EXPANSION_SIZEOF_P (t)
13630 || pack_expansion_args_count (args))
13631 return args;
13632 /* Also optimize expression pack expansions if we can tell that the
13633 elements won't have reference type. */
13634 tree type = TREE_TYPE (pattern);
13635 if (type && !TYPE_REF_P (type)
13636 && !PACK_EXPANSION_P (type)
13637 && !WILDCARD_TYPE_P (type))
13638 return args;
13639 /* Otherwise use the normal path so we get convert_from_reference. */
13642 /* We cannot expand this expansion expression, because we don't have
13643 all of the argument packs we need. */
13644 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13646 /* We got some full packs, but we can't substitute them in until we
13647 have values for all the packs. So remember these until then. */
13649 t = make_pack_expansion (pattern, complain);
13650 PACK_EXPANSION_EXTRA_ARGS (t)
13651 = build_extra_args (pattern, args, complain);
13652 return t;
13655 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13656 type, so create our own local specializations map; the current map is
13657 either NULL or (in the case of recursive unification) might have
13658 bindings that we don't want to use or alter. */
13659 local_specialization_stack lss (need_local_specializations
13660 ? lss_blank : lss_nop);
13662 if (unsubstituted_packs)
13664 /* There were no real arguments, we're just replacing a parameter
13665 pack with another version of itself. Substitute into the
13666 pattern and return a PACK_EXPANSION_*. The caller will need to
13667 deal with that. */
13668 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13669 result = tsubst_expr (pattern, args, complain, in_decl);
13670 else
13671 result = tsubst (pattern, args, complain, in_decl);
13672 result = make_pack_expansion (result, complain);
13673 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13674 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13675 if (PACK_EXPANSION_AUTO_P (t))
13677 /* This is a fake auto... pack expansion created in add_capture with
13678 _PACKS that don't appear in the pattern. Copy one over. */
13679 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13680 pack = retrieve_local_specialization (TREE_VALUE (packs));
13681 gcc_checking_assert (DECL_PACK_P (pack));
13682 PACK_EXPANSION_PARAMETER_PACKS (result)
13683 = build_tree_list (NULL_TREE, pack);
13684 PACK_EXPANSION_AUTO_P (result) = true;
13686 return result;
13689 gcc_assert (len >= 0);
13691 /* For each argument in each argument pack, substitute into the
13692 pattern. */
13693 result = make_tree_vec (len);
13694 tree elem_args = copy_template_args (args);
13695 for (i = 0; i < len; ++i)
13697 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13699 elem_args, complain,
13700 in_decl);
13701 TREE_VEC_ELT (result, i) = t;
13702 if (t == error_mark_node)
13704 result = error_mark_node;
13705 break;
13709 /* Update ARGS to restore the substitution from parameter packs to
13710 their argument packs. */
13711 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13713 tree parm = TREE_PURPOSE (pack);
13715 if (TREE_CODE (parm) == PARM_DECL
13716 || VAR_P (parm)
13717 || TREE_CODE (parm) == FIELD_DECL)
13718 register_local_specialization (TREE_TYPE (pack), parm);
13719 else
13721 int idx, level;
13723 if (TREE_VALUE (pack) == NULL_TREE)
13724 continue;
13726 template_parm_level_and_index (parm, &level, &idx);
13728 /* Update the corresponding argument. */
13729 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13730 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13731 TREE_TYPE (pack);
13732 else
13733 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13737 /* If the dependent pack arguments were such that we end up with only a
13738 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13739 if (len == 1 && TREE_CODE (result) == TREE_VEC
13740 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13741 return TREE_VEC_ELT (result, 0);
13743 return result;
13746 /* Make an argument pack out of the TREE_VEC VEC. */
13748 static tree
13749 make_argument_pack (tree vec)
13751 tree pack;
13753 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13754 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13755 else
13757 pack = make_node (NONTYPE_ARGUMENT_PACK);
13758 TREE_CONSTANT (pack) = 1;
13760 ARGUMENT_PACK_ARGS (pack) = vec;
13761 return pack;
13764 /* Return an exact copy of template args T that can be modified
13765 independently. */
13767 static tree
13768 copy_template_args (tree t)
13770 if (t == error_mark_node)
13771 return t;
13773 int len = TREE_VEC_LENGTH (t);
13774 tree new_vec = make_tree_vec (len);
13776 for (int i = 0; i < len; ++i)
13778 tree elt = TREE_VEC_ELT (t, i);
13779 if (elt && TREE_CODE (elt) == TREE_VEC)
13780 elt = copy_template_args (elt);
13781 TREE_VEC_ELT (new_vec, i) = elt;
13784 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13785 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13787 return new_vec;
13790 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13792 tree
13793 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13794 tree in_decl)
13796 /* This flag is used only during deduction, and we don't expect to
13797 substitute such ARGUMENT_PACKs. */
13798 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13800 /* Substitute into each of the arguments. */
13801 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13802 args, complain, in_decl);
13803 if (pack_args == error_mark_node)
13804 return error_mark_node;
13806 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13807 return orig_arg;
13809 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13810 template parameter, we might be able to avoid allocating a new
13811 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13812 if the substituted result is identical to it. */
13813 if (tree parm = template_arg_to_parm (orig_arg))
13815 int level, index;
13816 template_parm_level_and_index (parm, &level, &index);
13817 if (TMPL_ARGS_DEPTH (args) >= level)
13818 if (tree arg = TMPL_ARG (args, level, index))
13819 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13820 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13822 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13823 return arg;
13827 tree new_arg;
13828 if (TYPE_P (orig_arg))
13830 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13831 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13833 else
13835 new_arg = make_node (TREE_CODE (orig_arg));
13836 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13838 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13839 return new_arg;
13842 /* Substitute ARGS into the vector or list of template arguments T. */
13844 tree
13845 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13847 if (t == error_mark_node)
13848 return error_mark_node;
13850 /* In "sizeof(X<I>)" we need to evaluate "I". */
13851 cp_evaluated ev;
13853 const int len = TREE_VEC_LENGTH (t);
13854 tree *elts = XALLOCAVEC (tree, len);
13855 int expanded_len_adjust = 0;
13857 /* True iff the substituted result is identical to T. */
13858 bool const_subst_p = true;
13860 for (int i = 0; i < len; i++)
13862 tree orig_arg = TREE_VEC_ELT (t, i);
13863 tree new_arg;
13865 if (!orig_arg)
13866 new_arg = NULL_TREE;
13867 else if (TREE_CODE (orig_arg) == TREE_VEC)
13868 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13869 else if (PACK_EXPANSION_P (orig_arg))
13871 /* Substitute into an expansion expression. */
13872 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13874 if (TREE_CODE (new_arg) == TREE_VEC)
13875 /* Add to the expanded length adjustment the number of
13876 expanded arguments. We subtract one from this
13877 measurement, because the argument pack expression
13878 itself is already counted as 1 in
13879 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13880 the argument pack is empty. */
13881 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13883 else if (ARGUMENT_PACK_P (orig_arg))
13884 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13885 else
13886 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13888 if (new_arg == error_mark_node)
13889 return error_mark_node;
13891 elts[i] = new_arg;
13892 if (new_arg != orig_arg)
13893 const_subst_p = false;
13896 if (const_subst_p)
13897 return t;
13899 tree maybe_reuse = NULL_TREE;
13901 /* If ARGS and T are both multi-level, the substituted result may be
13902 identical to ARGS. */
13903 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13904 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13905 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13906 maybe_reuse = args;
13907 /* If T appears to be a vector of generic template arguments, the
13908 substituted result may be identical to the corresponding level
13909 from ARGS. */
13910 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13912 int level, index;
13913 template_parm_level_and_index (parm, &level, &index);
13914 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13915 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13918 /* If the substituted result is identical to MAYBE_REUSE, return
13919 it and avoid allocating a new TREE_VEC, as an optimization. */
13920 if (maybe_reuse != NULL_TREE
13921 && TREE_VEC_LENGTH (maybe_reuse) == len
13922 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13923 return maybe_reuse;
13925 /* If T consists of only a pack expansion for which substitution yielded
13926 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13927 of effectively making a copy. */
13928 if (len == 1
13929 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13930 && TREE_CODE (elts[0]) == TREE_VEC)
13931 return elts[0];
13933 /* Make space for the expanded arguments coming from template
13934 argument packs. */
13935 tree r = make_tree_vec (len + expanded_len_adjust);
13936 /* T can contain TREE_VECs. That happens if T contains the
13937 arguments for a member template.
13938 In that case each TREE_VEC in T represents a level of template
13939 arguments, and T won't carry any non defaulted argument count.
13940 It will rather be the nested TREE_VECs that will carry one.
13941 In other words, T carries a non defaulted argument count only
13942 if it doesn't contain any nested TREE_VEC. */
13943 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13945 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13946 count += expanded_len_adjust;
13947 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13950 int out = 0;
13951 for (int i = 0; i < len; i++)
13953 tree orig_arg = TREE_VEC_ELT (t, i);
13954 if (orig_arg
13955 && PACK_EXPANSION_P (orig_arg)
13956 && TREE_CODE (elts[i]) == TREE_VEC)
13958 /* Now expand the template argument pack "in place". */
13959 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13960 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13962 else
13964 TREE_VEC_ELT (r, out) = elts[i];
13965 out++;
13968 gcc_assert (out == TREE_VEC_LENGTH (r));
13970 return r;
13973 /* Substitute ARGS into one level PARMS of template parameters. */
13975 static tree
13976 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13978 if (parms == error_mark_node)
13979 return error_mark_node;
13981 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13983 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13985 tree tuple = TREE_VEC_ELT (parms, i);
13987 if (tuple == error_mark_node)
13988 continue;
13990 TREE_VEC_ELT (new_vec, i) =
13991 tsubst_template_parm (tuple, args, complain);
13994 return new_vec;
13997 /* Return the result of substituting ARGS into the template parameters
13998 given by PARMS. If there are m levels of ARGS and m + n levels of
13999 PARMS, then the result will contain n levels of PARMS. For
14000 example, if PARMS is `template <class T> template <class U>
14001 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
14002 result will be `template <int*, double, class V>'. */
14004 static tree
14005 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
14007 tree r = NULL_TREE;
14008 tree* new_parms;
14010 /* When substituting into a template, we must set
14011 PROCESSING_TEMPLATE_DECL as the template parameters may be
14012 dependent if they are based on one-another, and the dependency
14013 predicates are short-circuit outside of templates. */
14014 ++processing_template_decl;
14016 for (new_parms = &r;
14017 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
14018 new_parms = &(TREE_CHAIN (*new_parms)),
14019 parms = TREE_CHAIN (parms))
14021 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
14022 args, complain);
14023 *new_parms =
14024 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
14025 - TMPL_ARGS_DEPTH (args)),
14026 new_vec, NULL_TREE);
14027 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
14028 = TEMPLATE_PARMS_CONSTRAINTS (parms);
14031 --processing_template_decl;
14033 return r;
14036 /* Return the result of substituting ARGS into one template parameter
14037 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
14038 parameter and which TREE_PURPOSE is the default argument of the
14039 template parameter. */
14041 static tree
14042 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
14044 tree default_value, parm_decl;
14046 if (args == NULL_TREE
14047 || t == NULL_TREE
14048 || t == error_mark_node)
14049 return t;
14051 gcc_assert (TREE_CODE (t) == TREE_LIST);
14053 default_value = TREE_PURPOSE (t);
14054 parm_decl = TREE_VALUE (t);
14056 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
14057 if (TREE_CODE (parm_decl) == PARM_DECL
14058 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
14059 parm_decl = error_mark_node;
14060 default_value = tsubst_template_arg (default_value, args,
14061 complain, NULL_TREE);
14063 tree r = build_tree_list (default_value, parm_decl);
14064 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
14065 return r;
14068 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
14069 parameter in PARMS for sake of declaration matching. */
14071 static void
14072 tsubst_each_template_parm_constraints (tree parms, tree args,
14073 tsubst_flags_t complain)
14075 ++processing_template_decl;
14076 for (; parms; parms = TREE_CHAIN (parms))
14078 tree level = TREE_VALUE (parms);
14079 for (tree parm : tree_vec_range (level))
14080 TEMPLATE_PARM_CONSTRAINTS (parm)
14081 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
14082 complain, NULL_TREE);
14084 --processing_template_decl;
14087 /* Substitute the ARGS into the indicated aggregate (or enumeration)
14088 type T. If T is not an aggregate or enumeration type, it is
14089 handled as if by tsubst. IN_DECL is as for tsubst. If
14090 ENTERING_SCOPE is nonzero, T is the context for a template which
14091 we are presently tsubst'ing. Return the substituted value. */
14093 static tree
14094 tsubst_aggr_type (tree t,
14095 tree args,
14096 tsubst_flags_t complain,
14097 tree in_decl,
14098 int entering_scope)
14100 if (t == NULL_TREE)
14101 return NULL_TREE;
14103 /* Handle typedefs via tsubst so that they get consistently reused. */
14104 if (typedef_variant_p (t))
14106 t = tsubst (t, args, complain, in_decl);
14107 if (t == error_mark_node)
14108 return error_mark_node;
14110 /* The effect of entering_scope is that for a dependent specialization
14111 A<T>, lookup_template_class prefers to return A's primary template
14112 type instead of the implicit instantiation. So when entering_scope,
14113 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
14114 taking advantage of the fact that lookup_template_class links the two
14115 types by setting TYPE_CANONICAL of the latter to the former. */
14116 if (entering_scope
14117 && CLASS_TYPE_P (t)
14118 && dependent_type_p (t)
14119 && TYPE_TEMPLATE_INFO (t)
14120 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
14121 t = TYPE_CANONICAL (t);
14123 return t;
14126 switch (TREE_CODE (t))
14128 case RECORD_TYPE:
14129 case ENUMERAL_TYPE:
14130 case UNION_TYPE:
14131 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
14133 default:
14134 return tsubst (t, args, complain, in_decl);
14138 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
14139 and ENUMERAL_TYPE cases of tsubst. */
14141 static tree
14142 tsubst_aggr_type_1 (tree t,
14143 tree args,
14144 tsubst_flags_t complain,
14145 tree in_decl,
14146 int entering_scope)
14148 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14150 complain &= ~tf_qualifying_scope;
14152 /* Figure out what arguments are appropriate for the
14153 type we are trying to find. For example, given:
14155 template <class T> struct S;
14156 template <class T, class U> void f(T, U) { S<U> su; }
14158 and supposing that we are instantiating f<int, double>,
14159 then our ARGS will be {int, double}, but, when looking up
14160 S we only want {double}. */
14161 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14162 complain, in_decl);
14163 if (argvec == error_mark_node)
14164 return error_mark_node;
14166 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14167 entering_scope, complain);
14168 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14170 else
14171 /* This is not a template type, so there's nothing to do. */
14172 return t;
14175 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14176 indexed in reverse order of the parameters. */
14178 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14180 /* Return a reference to the vec* of defarg insts for FN. */
14182 static vec<tree,va_gc> *&
14183 defarg_insts_for (tree fn)
14185 if (!defarg_inst)
14186 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14187 tree_vec_map in = { { fn }, nullptr };
14188 tree_vec_map **slot
14189 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14190 if (!*slot)
14192 *slot = ggc_alloc<tree_vec_map> ();
14193 **slot = in;
14195 return (*slot)->to;
14198 /* Substitute into the default argument ARG (a default argument for
14199 FN), which has the indicated TYPE. */
14201 tree
14202 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14203 tsubst_flags_t complain)
14205 int errs = errorcount + sorrycount;
14207 /* This can happen in invalid code. */
14208 if (TREE_CODE (arg) == DEFERRED_PARSE)
14209 return arg;
14211 /* Shortcut {}. */
14212 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14213 && CONSTRUCTOR_NELTS (arg) == 0)
14214 return arg;
14216 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14217 parm = chain_index (parmnum, parm);
14218 tree parmtype = TREE_TYPE (parm);
14219 if (DECL_BY_REFERENCE (parm))
14220 parmtype = TREE_TYPE (parmtype);
14221 if (parmtype == error_mark_node)
14222 return error_mark_node;
14224 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14226 /* Remember the location of the pointer to the vec rather than the location
14227 of the particular element, in case the vec grows in tsubst_expr. */
14228 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14229 /* Index in reverse order to avoid allocating space for initial parameters
14230 that don't have default arguments. */
14231 unsigned ridx = list_length (parm);
14232 if (vec_safe_length (defs) < ridx)
14233 vec_safe_grow_cleared (defs, ridx);
14234 else if (tree inst = (*defs)[ridx - 1])
14235 return inst;
14237 /* This default argument came from a template. Instantiate the
14238 default argument here, not in tsubst. In the case of
14239 something like:
14241 template <class T>
14242 struct S {
14243 static T t();
14244 void f(T = t());
14247 we must be careful to do name lookup in the scope of S<T>,
14248 rather than in the current class. */
14249 push_to_top_level ();
14250 push_access_scope (fn);
14251 push_deferring_access_checks (dk_no_deferred);
14252 /* So in_immediate_context knows this is a default argument. */
14253 begin_scope (sk_function_parms, fn);
14254 start_lambda_scope (parm);
14256 /* The default argument expression may cause implicitly defined
14257 member functions to be synthesized, which will result in garbage
14258 collection. We must treat this situation as if we were within
14259 the body of function so as to avoid collecting live data on the
14260 stack. */
14261 ++function_depth;
14262 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14263 --function_depth;
14265 finish_lambda_scope ();
14267 /* Make sure the default argument is reasonable. */
14268 arg = check_default_argument (type, arg, complain);
14270 if (errorcount+sorrycount > errs
14271 && (complain & tf_warning_or_error))
14272 inform (input_location,
14273 " when instantiating default argument for call to %qD", fn);
14275 leave_scope ();
14276 pop_deferring_access_checks ();
14277 pop_access_scope (fn);
14278 pop_from_top_level ();
14280 if (arg != error_mark_node && !cp_unevaluated_operand)
14281 (*defs)[ridx - 1] = arg;
14283 return arg;
14286 /* Substitute into all the default arguments for FN. */
14288 static void
14289 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14291 tree arg;
14292 tree tmpl_args;
14294 tmpl_args = DECL_TI_ARGS (fn);
14296 /* If this function is not yet instantiated, we certainly don't need
14297 its default arguments. */
14298 if (uses_template_parms (tmpl_args))
14299 return;
14300 /* Don't do this again for clones. */
14301 if (DECL_CLONED_FUNCTION_P (fn))
14302 return;
14304 int i = 0;
14305 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14306 arg;
14307 arg = TREE_CHAIN (arg), ++i)
14308 if (TREE_PURPOSE (arg))
14309 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14310 TREE_VALUE (arg),
14311 TREE_PURPOSE (arg),
14312 complain);
14315 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14316 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14318 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14320 void
14321 store_explicit_specifier (tree v, tree t)
14323 if (!explicit_specifier_map)
14324 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14325 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14326 explicit_specifier_map->put (v, t);
14329 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14331 tree
14332 lookup_explicit_specifier (tree v)
14334 return *explicit_specifier_map->get (v);
14337 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14338 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14339 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14340 identical to T. */
14342 static tree
14343 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14344 tree raises, tsubst_flags_t complain)
14346 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14348 tree new_type;
14349 if (TREE_CODE (t) == FUNCTION_TYPE)
14351 new_type = build_function_type (return_type, arg_types);
14352 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14354 else
14356 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14357 /* Don't pick up extra function qualifiers from the basetype. */
14358 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14359 if (! MAYBE_CLASS_TYPE_P (r))
14361 /* [temp.deduct]
14363 Type deduction may fail for any of the following
14364 reasons:
14366 -- Attempting to create "pointer to member of T" when T
14367 is not a class type. */
14368 if (complain & tf_error)
14369 error ("creating pointer to member function of non-class type %qT",
14371 return error_mark_node;
14374 new_type = build_method_type_directly (r, return_type,
14375 TREE_CHAIN (arg_types));
14377 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14379 cp_ref_qualifier rqual = type_memfn_rqual (t);
14380 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14381 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14384 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14385 each of its formal parameters. If there is a disagreement then rebuild
14386 DECL's function type according to its formal parameter types, as part of a
14387 resolution for Core issues 1001/1322. */
14389 static void
14390 maybe_rebuild_function_decl_type (tree decl)
14392 bool function_type_needs_rebuilding = false;
14393 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14395 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14396 while (parm_type_list && parm_type_list != void_list_node)
14398 tree parm_type = TREE_VALUE (parm_type_list);
14399 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14400 if (!same_type_p (parm_type, formal_parm_type_unqual))
14402 function_type_needs_rebuilding = true;
14403 break;
14406 parm_list = DECL_CHAIN (parm_list);
14407 parm_type_list = TREE_CHAIN (parm_type_list);
14411 if (!function_type_needs_rebuilding)
14412 return;
14414 const tree fntype = TREE_TYPE (decl);
14415 tree parm_list = DECL_ARGUMENTS (decl);
14416 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14417 tree new_parm_type_list = NULL_TREE;
14418 tree *q = &new_parm_type_list;
14419 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14421 *q = copy_node (old_parm_type_list);
14422 parm_list = DECL_CHAIN (parm_list);
14423 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14424 q = &TREE_CHAIN (*q);
14426 while (old_parm_type_list && old_parm_type_list != void_list_node)
14428 *q = copy_node (old_parm_type_list);
14429 tree *new_parm_type = &TREE_VALUE (*q);
14430 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14431 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14432 *new_parm_type = formal_parm_type_unqual;
14434 parm_list = DECL_CHAIN (parm_list);
14435 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14436 q = &TREE_CHAIN (*q);
14438 if (old_parm_type_list == void_list_node)
14439 *q = void_list_node;
14441 TREE_TYPE (decl)
14442 = rebuild_function_or_method_type (fntype,
14443 TREE_TYPE (fntype), new_parm_type_list,
14444 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14447 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14449 static tree
14450 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14451 tree lambda_fntype, bool use_spec_table = true)
14453 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14454 hashval_t hash = 0;
14455 tree in_decl = t;
14457 /* Nobody should be tsubst'ing into non-template functions. */
14458 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14459 || DECL_LOCAL_DECL_P (t));
14461 if (DECL_LOCAL_DECL_P (t))
14463 if (tree spec = retrieve_local_specialization (t))
14464 return spec;
14466 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14468 /* If T is not dependent, just return it. */
14469 if (!uses_template_parms (DECL_TI_ARGS (t))
14470 && !LAMBDA_FUNCTION_P (t))
14471 return t;
14473 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14474 if (non_templated_friend_p (t))
14475 goto friend_case;
14477 /* Calculate the most general template of which R is a
14478 specialization. */
14479 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14481 /* We're substituting a lambda function under tsubst_lambda_expr but not
14482 directly from it; find the matching function we're already inside.
14483 But don't do this if T is a generic lambda with a single level of
14484 template parms, as in that case we're doing a normal instantiation. */
14485 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14486 && (!generic_lambda_fn_p (t)
14487 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14488 return enclosing_instantiation_of (t);
14490 /* Calculate the complete set of arguments used to
14491 specialize R. */
14492 if (use_spec_table && !lambda_fntype)
14494 argvec = tsubst_template_args (DECL_TI_ARGS
14495 (DECL_TEMPLATE_RESULT
14496 (DECL_TI_TEMPLATE (t))),
14497 args, complain, in_decl);
14498 if (argvec == error_mark_node)
14499 return error_mark_node;
14501 /* Check to see if we already have this specialization. */
14502 hash = spec_hasher::hash (gen_tmpl, argvec);
14503 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14504 /* The spec for these args might be a partial instantiation of the
14505 template, but here what we want is the FUNCTION_DECL. */
14506 return STRIP_TEMPLATE (spec);
14508 else
14509 argvec = args;
14511 else
14513 /* This special case arises when we have something like this:
14515 template <class T> struct S {
14516 friend void f<int>(int, double);
14519 Here, the DECL_TI_TEMPLATE for the friend declaration
14520 will be an IDENTIFIER_NODE. We are being called from
14521 tsubst_friend_function, and we want only to create a
14522 new decl (R) with appropriate types so that we can call
14523 determine_specialization. */
14524 friend_case:
14525 gen_tmpl = NULL_TREE;
14526 argvec = NULL_TREE;
14529 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14530 : NULL_TREE);
14531 tree ctx = closure ? closure : DECL_CONTEXT (t);
14532 bool member = ctx && TYPE_P (ctx);
14534 /* If this is a static or xobj lambda, remove the 'this' pointer added in
14535 tsubst_lambda_expr now that we know the closure type. */
14536 if (lambda_fntype && !DECL_IOBJ_MEMBER_FUNCTION_P (t))
14537 lambda_fntype = static_fn_type (lambda_fntype);
14539 if (member && !closure)
14540 ctx = tsubst_aggr_type (ctx, args,
14541 complain, t, /*entering_scope=*/1);
14543 tree type = (lambda_fntype ? lambda_fntype
14544 : tsubst (TREE_TYPE (t), args,
14545 complain | tf_fndecl_type, in_decl));
14546 if (type == error_mark_node)
14547 return error_mark_node;
14549 /* If we hit excessive deduction depth, the type is bogus even if
14550 it isn't error_mark_node, so don't build a decl. */
14551 if (excessive_deduction_depth)
14552 return error_mark_node;
14554 /* We do NOT check for matching decls pushed separately at this
14555 point, as they may not represent instantiations of this
14556 template, and in any case are considered separate under the
14557 discrete model. */
14558 tree r = copy_decl (t);
14559 DECL_USE_TEMPLATE (r) = 0;
14560 TREE_TYPE (r) = type;
14561 /* Clear out the mangled name and RTL for the instantiation. */
14562 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14563 SET_DECL_RTL (r, NULL);
14564 /* Leave DECL_INITIAL set on deleted instantiations. */
14565 if (!DECL_DELETED_FN (r))
14566 DECL_INITIAL (r) = NULL_TREE;
14567 DECL_CONTEXT (r) = ctx;
14568 set_instantiating_module (r);
14570 /* Handle explicit(dependent-expr). */
14571 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14573 tree spec = lookup_explicit_specifier (t);
14574 spec = tsubst_expr (spec, args, complain, in_decl);
14575 spec = build_explicit_specifier (spec, complain);
14576 if (spec == error_mark_node)
14577 return error_mark_node;
14578 if (instantiation_dependent_expression_p (spec))
14579 store_explicit_specifier (r, spec);
14580 else
14582 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14583 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14587 /* OpenMP UDRs have the only argument a reference to the declared
14588 type. We want to diagnose if the declared type is a reference,
14589 which is invalid, but as references to references are usually
14590 quietly merged, diagnose it here. */
14591 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14593 tree argtype
14594 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14595 argtype = tsubst (argtype, args, complain, in_decl);
14596 if (TYPE_REF_P (argtype))
14597 error_at (DECL_SOURCE_LOCATION (t),
14598 "reference type %qT in "
14599 "%<#pragma omp declare reduction%>", argtype);
14600 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14601 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14602 argtype);
14605 if (member && DECL_CONV_FN_P (r))
14606 /* Type-conversion operator. Reconstruct the name, in
14607 case it's the name of one of the template's parameters. */
14608 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14610 tree parms = DECL_ARGUMENTS (t);
14611 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14612 parms = DECL_CHAIN (parms);
14613 parms = tsubst (parms, args, complain, t);
14614 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14615 DECL_CONTEXT (parm) = r;
14616 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14618 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14619 DECL_NAME (tparm) = closure_identifier;
14620 DECL_CHAIN (tparm) = parms;
14621 parms = tparm;
14623 DECL_ARGUMENTS (r) = parms;
14624 DECL_RESULT (r) = NULL_TREE;
14626 maybe_rebuild_function_decl_type (r);
14628 TREE_STATIC (r) = 0;
14629 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14630 DECL_EXTERNAL (r) = 1;
14631 /* If this is an instantiation of a function with internal
14632 linkage, we already know what object file linkage will be
14633 assigned to the instantiation. */
14634 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14635 DECL_DEFER_OUTPUT (r) = 0;
14636 DECL_CHAIN (r) = NULL_TREE;
14637 DECL_PENDING_INLINE_INFO (r) = 0;
14638 DECL_PENDING_INLINE_P (r) = 0;
14639 DECL_SAVED_TREE (r) = NULL_TREE;
14640 DECL_STRUCT_FUNCTION (r) = NULL;
14641 TREE_USED (r) = 0;
14642 /* We'll re-clone as appropriate in instantiate_template. */
14643 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14645 /* If we aren't complaining now, return on error before we register
14646 the specialization so that we'll complain eventually. */
14647 if ((complain & tf_error) == 0
14648 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14649 && !grok_op_properties (r, /*complain=*/false))
14650 return error_mark_node;
14652 /* If we are looking at an xobj lambda, we might need to check the type of
14653 its xobj parameter. */
14654 if (LAMBDA_FUNCTION_P (r) && DECL_XOBJ_MEMBER_FUNCTION_P (r))
14656 tree closure_obj = DECL_CONTEXT (r);
14657 tree lambda_expr = CLASSTYPE_LAMBDA_EXPR (closure_obj);
14658 tree obj_param = TREE_TYPE (DECL_ARGUMENTS (r));
14660 if (!(LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) != CPLD_NONE
14661 || LAMBDA_EXPR_CAPTURE_LIST (lambda_expr)))
14662 /* If a lambda has an empty capture clause, an xobj parameter of
14663 unrelated type is not an error. */;
14664 else if (dependent_type_p (obj_param))
14665 /* If we are coming from tsubst_lambda_expr we might not have
14666 substituted into our xobj parameter yet. We can't error out until
14667 we know what the type really is so do nothing...
14668 ...but if we are instantiating the call op for real and we don't
14669 have a real type then something has gone incredibly wrong. */
14670 gcc_assert (lambda_fntype);
14671 else
14673 /* We have a lambda with captures, and know the type of the xobj
14674 parameter, time to check it. */
14675 tree obj_param_type = TYPE_MAIN_VARIANT (non_reference (obj_param));
14676 if (!same_or_base_type_p (closure_obj, obj_param_type))
14678 /* This error does not emit when the lambda's call operator
14679 template is instantiated by taking its address, such as in
14680 the following case:
14682 auto f = [x = 0](this auto&&){};
14683 int (*fp)(int&) = &decltype(f)::operator();
14685 It only emits when explicitly calling the call operator with
14686 an explicit template parameter:
14688 template<typename T>
14689 struct S : T {
14690 using T::operator();
14691 operator int() const {return {};}
14694 auto s = S{[x = 0](this auto&&) {}};
14695 s.operator()<int>();
14697 This is due to resolve_address_of_overloaded_function being
14698 deficient at reporting candidates when overload resolution
14699 fails.
14701 This diagnostic will be active in the first case if/when
14702 resolve_address_of_overloaded_function is fixed to properly
14703 emit candidates upon failure to resolve to an overload. */
14704 if (complain & tf_error)
14705 error ("a lambda with captures may not have an explicit "
14706 "object parameter of an unrelated type");
14707 return error_mark_node;
14712 /* Associate the constraints directly with the instantiation. We
14713 don't substitute through the constraints; that's only done when
14714 they are checked. */
14715 if (tree ci = get_constraints (t))
14716 set_constraints (r, ci);
14718 if (DECL_FRIEND_CONTEXT (t))
14719 SET_DECL_FRIEND_CONTEXT (r,
14720 tsubst (DECL_FRIEND_CONTEXT (t),
14721 args, complain, in_decl));
14723 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14724 args, complain, in_decl))
14725 return error_mark_node;
14727 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14728 this in the special friend case mentioned above where
14729 GEN_TMPL is NULL. */
14730 if (gen_tmpl && !closure)
14732 DECL_TEMPLATE_INFO (r)
14733 = build_template_info (gen_tmpl, argvec);
14734 SET_DECL_IMPLICIT_INSTANTIATION (r);
14736 if (use_spec_table)
14738 tree new_r
14739 = register_specialization (r, gen_tmpl, argvec, false, hash);
14740 if (new_r != r)
14741 /* We instantiated this while substituting into
14742 the type earlier (template/friend54.C). */
14743 return new_r;
14746 /* We're not supposed to instantiate default arguments
14747 until they are called, for a template. But, for a
14748 declaration like:
14750 template <class T> void f ()
14751 { extern void g(int i = T()); }
14753 we should do the substitution when the template is
14754 instantiated. We handle the member function case in
14755 instantiate_class_template since the default arguments
14756 might refer to other members of the class. */
14757 if (!member
14758 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14759 && !uses_template_parms (argvec))
14760 tsubst_default_arguments (r, complain);
14762 else if (DECL_LOCAL_DECL_P (r))
14764 if (!cp_unevaluated_operand)
14765 register_local_specialization (r, t);
14767 else
14768 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14770 /* Copy the list of befriending classes. */
14771 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14772 *friends;
14773 friends = &TREE_CHAIN (*friends))
14775 *friends = copy_node (*friends);
14776 TREE_VALUE (*friends)
14777 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14780 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14782 maybe_retrofit_in_chrg (r);
14783 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14784 return error_mark_node;
14785 /* If this is an instantiation of a member template, clone it.
14786 If it isn't, that'll be handled by
14787 clone_constructors_and_destructors. */
14788 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14789 clone_cdtor (r, /*update_methods=*/false);
14791 else if ((complain & tf_error) != 0
14792 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14793 && !grok_op_properties (r, /*complain=*/true))
14794 return error_mark_node;
14796 /* Possibly limit visibility based on template args. */
14797 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14798 if (DECL_VISIBILITY_SPECIFIED (t))
14800 DECL_VISIBILITY_SPECIFIED (r) = 0;
14801 DECL_ATTRIBUTES (r)
14802 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14804 determine_visibility (r);
14805 if (DECL_SECTION_NAME (t))
14806 set_decl_section_name (r, t);
14807 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14808 && !processing_template_decl)
14809 defaulted_late_check (r);
14811 if (flag_openmp)
14812 if (tree attr = lookup_attribute ("omp declare variant base",
14813 DECL_ATTRIBUTES (r)))
14814 omp_declare_variant_finalize (r, attr);
14816 return r;
14819 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14821 static tree
14822 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14823 tree lambda_fntype, tree lambda_tparms)
14825 /* We can get here when processing a member function template,
14826 member class template, or template template parameter. */
14827 tree decl = DECL_TEMPLATE_RESULT (t);
14828 tree in_decl = t;
14829 tree spec;
14830 tree tmpl_args;
14831 tree full_args = NULL_TREE;
14832 tree r;
14833 hashval_t hash = 0;
14835 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14837 /* Template template parameter is treated here. */
14838 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14839 if (new_type == error_mark_node)
14840 r = error_mark_node;
14841 /* If we get a real template back, return it. This can happen in
14842 the context of most_specialized_partial_spec. */
14843 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14844 r = new_type;
14845 else
14846 /* The new TEMPLATE_DECL was built in
14847 reduce_template_parm_level. */
14848 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14849 return r;
14852 if (!lambda_fntype)
14854 /* We might already have an instance of this template.
14855 The ARGS are for the surrounding class type, so the
14856 full args contain the tsubst'd args for the context,
14857 plus the innermost args from the template decl. */
14858 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14859 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14860 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14861 /* Because this is a template, the arguments will still be
14862 dependent, even after substitution. If
14863 PROCESSING_TEMPLATE_DECL is not set, the dependency
14864 predicates will short-circuit. */
14865 ++processing_template_decl;
14866 full_args = tsubst_template_args (tmpl_args, args,
14867 complain, in_decl);
14868 --processing_template_decl;
14869 if (full_args == error_mark_node)
14870 return error_mark_node;
14872 /* If this is a default template template argument,
14873 tsubst might not have changed anything. */
14874 if (full_args == tmpl_args)
14875 return t;
14877 hash = spec_hasher::hash (t, full_args);
14878 spec = retrieve_specialization (t, full_args, hash);
14879 if (spec != NULL_TREE)
14881 if (TYPE_P (spec))
14882 /* Type partial instantiations are stored as the type by
14883 lookup_template_class_1, not here as the template. */
14884 spec = CLASSTYPE_TI_TEMPLATE (spec);
14885 else if (TREE_CODE (spec) != TEMPLATE_DECL)
14886 spec = DECL_TI_TEMPLATE (spec);
14887 return spec;
14891 /* Make a new template decl. It will be similar to the
14892 original, but will record the current template arguments.
14893 We also create a new function declaration, which is just
14894 like the old one, but points to this new template, rather
14895 than the old one. */
14896 r = copy_decl (t);
14897 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14898 DECL_CHAIN (r) = NULL_TREE;
14900 // Build new template info linking to the original template decl.
14901 if (!lambda_fntype)
14903 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14904 SET_DECL_IMPLICIT_INSTANTIATION (r);
14906 else
14907 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14909 /* The template parameters for this new template are all the
14910 template parameters for the old template, except the
14911 outermost level of parameters. */
14912 auto tparm_guard = make_temp_override (current_template_parms);
14913 DECL_TEMPLATE_PARMS (r)
14914 = current_template_parms
14915 = (lambda_tparms
14916 ? lambda_tparms
14917 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14918 complain));
14920 bool class_p = false;
14921 tree inner = decl;
14922 ++processing_template_decl;
14923 if (TREE_CODE (inner) == FUNCTION_DECL)
14924 inner = tsubst_function_decl (inner, args, complain, lambda_fntype,
14925 /*use_spec_table=*/false);
14926 else
14928 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14930 class_p = true;
14931 inner = TREE_TYPE (inner);
14933 if (class_p)
14934 inner = tsubst_aggr_type (inner, args, complain,
14935 in_decl, /*entering*/1);
14936 else
14937 inner = tsubst_decl (inner, args, complain, /*use_spec_table=*/false);
14939 --processing_template_decl;
14940 if (inner == error_mark_node)
14941 return error_mark_node;
14943 if (class_p)
14945 /* For a partial specialization, we need to keep pointing to
14946 the primary template. */
14947 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14949 CLASSTYPE_TI_TEMPLATE (inner) = r;
14950 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14953 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14954 inner = TYPE_MAIN_DECL (inner);
14956 else if (lambda_fntype)
14958 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14959 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14961 else
14963 DECL_TI_TEMPLATE (inner) = r;
14964 /* Set DECL_TI_ARGS to the full set of template arguments,
14965 which tsubst_function_decl / tsubst_decl didn't do due to
14966 use_spec_table=false. */
14967 DECL_TI_ARGS (inner) = full_args;
14968 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14971 DECL_TEMPLATE_RESULT (r) = inner;
14972 TREE_TYPE (r) = TREE_TYPE (inner);
14973 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14975 if (modules_p ())
14977 /* Propagate module information from the decl. */
14978 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14979 if (DECL_LANG_SPECIFIC (inner))
14980 /* If this is a constrained template, the above tsubst of
14981 inner can find the unconstrained template, which may have
14982 come from an import. This is ok, because we don't
14983 register this instantiation (see below). */
14984 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14985 || (TEMPLATE_PARMS_CONSTRAINTS
14986 (DECL_TEMPLATE_PARMS (t))));
14989 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14990 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14992 if (PRIMARY_TEMPLATE_P (t))
14993 DECL_PRIMARY_TEMPLATE (r) = r;
14995 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (r) = false;
14997 if (!lambda_fntype && !class_p)
14999 /* Record this non-type partial instantiation. */
15000 /* FIXME we'd like to always register the TEMPLATE_DECL, or always
15001 the DECL_TEMPLATE_RESULT, but it seems the modules code relies
15002 on this current behavior. */
15003 if (TREE_CODE (inner) == FUNCTION_DECL)
15004 register_specialization (r, t, full_args, false, hash);
15005 else
15006 register_specialization (inner, t, full_args, false, hash);
15009 return r;
15012 /* True if FN is the op() for a lambda in an uninstantiated template. */
15014 bool
15015 lambda_fn_in_template_p (tree fn)
15017 if (!fn || !LAMBDA_FUNCTION_P (fn))
15018 return false;
15019 tree closure = DECL_CONTEXT (fn);
15020 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
15023 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
15024 which the above is true. */
15026 bool
15027 regenerated_lambda_fn_p (tree fn)
15029 if (!fn || !LAMBDA_FUNCTION_P (fn))
15030 return false;
15031 tree closure = DECL_CONTEXT (fn);
15032 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
15033 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
15036 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
15037 If T is not a regenerated LAMBDA_EXPR, return T. */
15039 tree
15040 most_general_lambda (tree t)
15042 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15043 t = TI_TEMPLATE (ti);
15044 return t;
15047 /* Return the set of template arguments used to regenerate the lambda T
15048 from its most general lambda. */
15050 tree
15051 lambda_regenerating_args (tree t)
15053 if (LAMBDA_FUNCTION_P (t))
15054 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
15055 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
15056 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15057 return TI_ARGS (ti);
15058 else
15059 return NULL_TREE;
15062 /* We're instantiating a variable from template function TCTX. Return the
15063 corresponding current enclosing scope. We can match them up using
15064 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
15065 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
15066 the template definition in regenerate_decl_from_template. */
15068 static tree
15069 enclosing_instantiation_of (tree tctx)
15071 tree fn = current_function_decl;
15073 /* We shouldn't ever need to do this for other artificial functions. */
15074 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
15076 for (; fn; fn = decl_function_context (fn))
15077 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
15078 return fn;
15079 gcc_unreachable ();
15082 /* Substitute the ARGS into the T, which is a _DECL. Return the
15083 result of the substitution. Issue error and warning messages under
15084 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
15085 and insert into the specializations table or if we can assume it's
15086 the caller's responsibility; this is used by instantiate_template
15087 to avoid doing some redundant work. */
15089 static tree
15090 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
15091 bool use_spec_table /* = true */)
15093 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
15094 location_t saved_loc;
15095 tree r = NULL_TREE;
15096 tree in_decl = t;
15097 hashval_t hash = 0;
15099 if (t == error_mark_node)
15100 return error_mark_node;
15102 /* Set the filename and linenumber to improve error-reporting. */
15103 saved_loc = input_location;
15104 input_location = DECL_SOURCE_LOCATION (t);
15106 switch (TREE_CODE (t))
15108 case TEMPLATE_DECL:
15109 r = tsubst_template_decl (t, args, complain,
15110 /*lambda_fntype=*/NULL_TREE,
15111 /*lambda_tparms=*/NULL_TREE);
15112 break;
15114 case FUNCTION_DECL:
15115 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
15116 use_spec_table);
15117 break;
15119 case PARM_DECL:
15121 tree type = NULL_TREE;
15122 int i, len = 1;
15123 tree expanded_types = NULL_TREE;
15124 tree prev_r = NULL_TREE;
15125 tree first_r = NULL_TREE;
15127 if (DECL_PACK_P (t))
15129 /* If there is a local specialization that isn't a
15130 parameter pack, it means that we're doing a "simple"
15131 substitution from inside tsubst_pack_expansion. Just
15132 return the local specialization (which will be a single
15133 parm). */
15134 tree spec = retrieve_local_specialization (t);
15135 if (spec
15136 && TREE_CODE (spec) == PARM_DECL
15137 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
15138 RETURN (spec);
15140 /* Expand the TYPE_PACK_EXPANSION that provides the types for
15141 the parameters in this function parameter pack. */
15142 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15143 complain, in_decl);
15144 if (TREE_CODE (expanded_types) == TREE_VEC)
15146 len = TREE_VEC_LENGTH (expanded_types);
15148 /* Zero-length parameter packs are boring. Just substitute
15149 into the chain. */
15150 if (len == 0 && !cp_unevaluated_operand)
15151 RETURN (tsubst (TREE_CHAIN (t), args, complain,
15152 TREE_CHAIN (t)));
15154 else
15156 /* All we did was update the type. Make a note of that. */
15157 type = expanded_types;
15158 expanded_types = NULL_TREE;
15162 /* Loop through all of the parameters we'll build. When T is
15163 a function parameter pack, LEN is the number of expanded
15164 types in EXPANDED_TYPES; otherwise, LEN is 1. */
15165 r = NULL_TREE;
15166 for (i = 0; i < len; ++i)
15168 prev_r = r;
15169 r = copy_node (t);
15170 if (DECL_TEMPLATE_PARM_P (t))
15171 SET_DECL_TEMPLATE_PARM_P (r);
15173 if (expanded_types)
15174 /* We're on the Ith parameter of the function parameter
15175 pack. */
15177 /* Get the Ith type. */
15178 type = TREE_VEC_ELT (expanded_types, i);
15180 /* Rename the parameter to include the index. */
15181 DECL_NAME (r)
15182 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15184 else if (!type)
15185 /* We're dealing with a normal parameter. */
15186 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15188 type = type_decays_to (type);
15189 TREE_TYPE (r) = type;
15190 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15192 if (DECL_INITIAL (r))
15194 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
15195 DECL_INITIAL (r) = TREE_TYPE (r);
15196 else
15197 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
15198 complain, in_decl);
15201 DECL_CONTEXT (r) = NULL_TREE;
15203 if (!DECL_TEMPLATE_PARM_P (r))
15204 DECL_ARG_TYPE (r) = type_passed_as (type);
15206 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15207 args, complain, in_decl))
15208 return error_mark_node;
15210 /* Keep track of the first new parameter we
15211 generate. That's what will be returned to the
15212 caller. */
15213 if (!first_r)
15214 first_r = r;
15216 /* Build a proper chain of parameters when substituting
15217 into a function parameter pack. */
15218 if (prev_r)
15219 DECL_CHAIN (prev_r) = r;
15222 /* If cp_unevaluated_operand is set, we're just looking for a
15223 single dummy parameter, so don't keep going. */
15224 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15225 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15226 complain, DECL_CHAIN (t));
15228 /* FIRST_R contains the start of the chain we've built. */
15229 r = first_r;
15231 break;
15233 case FIELD_DECL:
15235 tree type = NULL_TREE;
15236 tree vec = NULL_TREE;
15237 tree expanded_types = NULL_TREE;
15238 int len = 1;
15240 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15242 /* This field is a lambda capture pack. Return a TREE_VEC of
15243 the expanded fields to instantiate_class_template_1. */
15244 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15245 complain, in_decl);
15246 if (TREE_CODE (expanded_types) == TREE_VEC)
15248 len = TREE_VEC_LENGTH (expanded_types);
15249 vec = make_tree_vec (len);
15251 else
15253 /* All we did was update the type. Make a note of that. */
15254 type = expanded_types;
15255 expanded_types = NULL_TREE;
15259 for (int i = 0; i < len; ++i)
15261 r = copy_decl (t);
15262 if (expanded_types)
15264 type = TREE_VEC_ELT (expanded_types, i);
15265 DECL_NAME (r)
15266 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15268 else if (!type)
15269 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15271 if (type == error_mark_node)
15272 RETURN (error_mark_node);
15273 TREE_TYPE (r) = type;
15274 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15276 if (DECL_C_BIT_FIELD (r))
15277 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15278 number of bits. */
15279 DECL_BIT_FIELD_REPRESENTATIVE (r)
15280 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15281 complain, in_decl);
15282 if (DECL_INITIAL (t))
15284 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15285 NSDMI in perform_member_init. Still set DECL_INITIAL
15286 so that we know there is one. */
15287 DECL_INITIAL (r) = void_node;
15288 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15289 retrofit_lang_decl (r);
15290 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15292 /* We don't have to set DECL_CONTEXT here; it is set by
15293 finish_member_declaration. */
15294 DECL_CHAIN (r) = NULL_TREE;
15296 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15297 args, complain, in_decl))
15298 return error_mark_node;
15300 if (vec)
15301 TREE_VEC_ELT (vec, i) = r;
15304 if (vec)
15305 r = vec;
15307 break;
15309 case USING_DECL:
15310 /* We reach here only for member using decls. We also need to check
15311 uses_template_parms because DECL_DEPENDENT_P is not set for a
15312 using-declaration that designates a member of the current
15313 instantiation (c++/53549). */
15314 if (DECL_DEPENDENT_P (t)
15315 || uses_template_parms (USING_DECL_SCOPE (t)))
15317 /* True iff this using-decl was written as a pack expansion
15318 (and a pack appeared in its scope or name). If a pack
15319 appeared in both, we expand the packs separately and
15320 manually merge them. */
15321 bool variadic_p = false;
15323 tree scope = USING_DECL_SCOPE (t);
15324 if (PACK_EXPANSION_P (scope))
15326 scope = tsubst_pack_expansion (scope, args,
15327 complain | tf_qualifying_scope,
15328 in_decl);
15329 variadic_p = true;
15331 else
15332 scope = tsubst_scope (scope, args, complain, in_decl);
15334 tree name = DECL_NAME (t);
15335 if (IDENTIFIER_CONV_OP_P (name)
15336 && PACK_EXPANSION_P (TREE_TYPE (name)))
15338 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15339 complain, in_decl);
15340 if (name == error_mark_node)
15342 r = error_mark_node;
15343 break;
15345 for (tree& elt : tree_vec_range (name))
15346 elt = make_conv_op_name (elt);
15347 variadic_p = true;
15349 else
15350 name = tsubst_name (name, args, complain, in_decl);
15352 int len;
15353 if (!variadic_p)
15354 len = 1;
15355 else if (TREE_CODE (scope) == TREE_VEC
15356 && TREE_CODE (name) == TREE_VEC)
15358 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15360 error ("mismatched argument pack lengths (%d vs %d)",
15361 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15362 r = error_mark_node;
15363 break;
15365 len = TREE_VEC_LENGTH (scope);
15367 else if (TREE_CODE (scope) == TREE_VEC)
15368 len = TREE_VEC_LENGTH (scope);
15369 else /* TREE_CODE (name) == TREE_VEC */
15370 len = TREE_VEC_LENGTH (name);
15372 r = make_tree_vec (len);
15373 for (int i = 0; i < len; ++i)
15375 tree escope = (TREE_CODE (scope) == TREE_VEC
15376 ? TREE_VEC_ELT (scope, i)
15377 : scope);
15378 tree ename = (TREE_CODE (name) == TREE_VEC
15379 ? TREE_VEC_ELT (name, i)
15380 : name);
15381 tree elt = do_class_using_decl (escope, ename);
15382 if (!elt)
15384 r = error_mark_node;
15385 break;
15387 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15388 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15389 TREE_VEC_ELT (r, i) = elt;
15392 if (!variadic_p && r != error_mark_node)
15393 r = TREE_VEC_ELT (r, 0);
15395 else
15397 r = copy_node (t);
15398 DECL_CHAIN (r) = NULL_TREE;
15400 break;
15402 case TYPE_DECL:
15403 case VAR_DECL:
15405 tree argvec = NULL_TREE;
15406 tree gen_tmpl = NULL_TREE;
15407 tree tmpl = NULL_TREE;
15408 tree type = NULL_TREE;
15410 if (TREE_TYPE (t) == error_mark_node)
15411 RETURN (error_mark_node);
15413 if (TREE_CODE (t) == TYPE_DECL
15414 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15416 /* If this is the canonical decl, we don't have to
15417 mess with instantiations, and often we can't (for
15418 typename, template type parms and such). Note that
15419 TYPE_NAME is not correct for the above test if
15420 we've copied the type for a typedef. */
15421 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15422 if (type == error_mark_node)
15423 RETURN (error_mark_node);
15424 r = TYPE_NAME (type);
15425 break;
15428 /* Check to see if we already have the specialization we
15429 need. */
15430 tree spec = NULL_TREE;
15431 bool local_p = false;
15432 tree ctx = DECL_CONTEXT (t);
15433 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15434 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15436 local_p = false;
15437 if (DECL_CLASS_SCOPE_P (t))
15439 ctx = tsubst_aggr_type (ctx, args,
15440 complain,
15441 in_decl, /*entering_scope=*/1);
15442 if (DECL_SELF_REFERENCE_P (t))
15443 /* The context and type of an injected-class-name are
15444 the same, so we don't need to substitute both. */
15445 type = ctx;
15446 /* If CTX is unchanged, then T is in fact the
15447 specialization we want. That situation occurs when
15448 referencing a static data member within in its own
15449 class. We can use pointer equality, rather than
15450 same_type_p, because DECL_CONTEXT is always
15451 canonical... */
15452 if (ctx == DECL_CONTEXT (t)
15453 /* ... unless T is a member template; in which
15454 case our caller can be willing to create a
15455 specialization of that template represented
15456 by T. */
15457 && !(DECL_TI_TEMPLATE (t)
15458 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15459 spec = t;
15462 if (!spec)
15464 tmpl = DECL_TI_TEMPLATE (t);
15465 if (use_spec_table)
15467 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15468 if (argvec == error_mark_node)
15469 RETURN (error_mark_node);
15470 gen_tmpl = most_general_template (tmpl);
15471 hash = spec_hasher::hash (gen_tmpl, argvec);
15472 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15474 else
15475 argvec = args;
15478 else
15480 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15481 /* Subsequent calls to pushdecl will fill this in. */
15482 ctx = NULL_TREE;
15483 /* A local variable. */
15484 local_p = true;
15485 /* Unless this is a reference to a static variable from an
15486 enclosing function, in which case we need to fill it in now. */
15487 if (TREE_STATIC (t))
15489 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15490 if (fn != current_function_decl)
15491 ctx = fn;
15493 spec = retrieve_local_specialization (t);
15495 /* If we already have the specialization we need, there is
15496 nothing more to do. */
15497 if (spec)
15499 r = spec;
15500 break;
15503 /* Create a new node for the specialization we need. */
15504 if (type == NULL_TREE)
15506 if (is_typedef_decl (t))
15507 type = DECL_ORIGINAL_TYPE (t);
15508 else
15509 type = TREE_TYPE (t);
15510 if (VAR_P (t)
15511 && VAR_HAD_UNKNOWN_BOUND (t)
15512 && type != error_mark_node)
15513 type = strip_array_domain (type);
15514 tsubst_flags_t tcomplain = complain;
15515 if (VAR_P (t))
15516 tcomplain |= tf_tst_ok;
15517 type = tsubst (type, args, tcomplain, in_decl);
15518 /* Substituting the type might have recursively instantiated this
15519 same alias (c++/86171). */
15520 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15521 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15523 r = spec;
15524 break;
15527 if (type == error_mark_node && !(complain & tf_error))
15528 RETURN (error_mark_node);
15529 r = copy_decl (t);
15530 if (VAR_P (r))
15532 DECL_INITIALIZED_P (r) = 0;
15533 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15534 if (TREE_CODE (type) == FUNCTION_TYPE)
15536 /* It may seem that this case cannot occur, since:
15538 typedef void f();
15539 void g() { f x; }
15541 declares a function, not a variable. However:
15543 typedef void f();
15544 template <typename T> void g() { T t; }
15545 template void g<f>();
15547 is an attempt to declare a variable with function
15548 type. */
15549 error ("variable %qD has function type",
15550 /* R is not yet sufficiently initialized, so we
15551 just use its name. */
15552 DECL_NAME (r));
15553 RETURN (error_mark_node);
15555 type = complete_type (type);
15556 /* Wait until cp_finish_decl to set this again, to handle
15557 circular dependency (template/instantiate6.C). */
15558 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15559 type = check_var_type (DECL_NAME (r), type,
15560 DECL_SOURCE_LOCATION (r));
15561 if (DECL_HAS_VALUE_EXPR_P (t))
15563 tree ve = DECL_VALUE_EXPR (t);
15564 /* If the DECL_VALUE_EXPR is converted to the declared type,
15565 preserve the identity so that gimplify_type_sizes works. */
15566 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15567 if (nop)
15568 ve = TREE_OPERAND (ve, 0);
15569 ve = tsubst_expr (ve, args, complain, in_decl);
15570 if (REFERENCE_REF_P (ve))
15572 gcc_assert (TYPE_REF_P (type));
15573 ve = TREE_OPERAND (ve, 0);
15575 if (nop)
15576 ve = build_nop (type, ve);
15577 else if (DECL_LANG_SPECIFIC (t)
15578 && DECL_OMP_PRIVATIZED_MEMBER (t)
15579 && TREE_CODE (ve) == COMPONENT_REF
15580 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15581 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15582 type = TREE_TYPE (ve);
15583 else
15584 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15585 == TYPE_MAIN_VARIANT (type));
15586 SET_DECL_VALUE_EXPR (r, ve);
15588 if (CP_DECL_THREAD_LOCAL_P (r)
15589 && !processing_template_decl)
15590 set_decl_tls_model (r, decl_default_tls_model (r));
15592 else if (DECL_SELF_REFERENCE_P (t))
15593 SET_DECL_SELF_REFERENCE_P (r);
15594 TREE_TYPE (r) = type;
15595 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15596 DECL_CONTEXT (r) = ctx;
15597 /* Clear out the mangled name and RTL for the instantiation. */
15598 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15599 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15600 SET_DECL_RTL (r, NULL);
15601 set_instantiating_module (r);
15603 /* The initializer must not be expanded until it is required;
15604 see [temp.inst]. */
15605 DECL_INITIAL (r) = NULL_TREE;
15606 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15607 if (VAR_P (r))
15609 if (DECL_LANG_SPECIFIC (r))
15610 SET_DECL_DEPENDENT_INIT_P (r, false);
15612 SET_DECL_MODE (r, VOIDmode);
15614 /* Possibly limit visibility based on template args. */
15615 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15616 if (DECL_VISIBILITY_SPECIFIED (t))
15618 DECL_VISIBILITY_SPECIFIED (r) = 0;
15619 DECL_ATTRIBUTES (r)
15620 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15622 determine_visibility (r);
15623 if ((!local_p || TREE_STATIC (t)) && DECL_SECTION_NAME (t))
15624 set_decl_section_name (r, t);
15627 if (!local_p)
15629 /* A static data member declaration is always marked
15630 external when it is declared in-class, even if an
15631 initializer is present. We mimic the non-template
15632 processing here. */
15633 DECL_EXTERNAL (r) = 1;
15634 if (DECL_NAMESPACE_SCOPE_P (t))
15635 DECL_NOT_REALLY_EXTERN (r) = 1;
15637 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15638 SET_DECL_IMPLICIT_INSTANTIATION (r);
15639 if (use_spec_table)
15640 register_specialization (r, gen_tmpl, argvec, false, hash);
15642 else
15644 if (DECL_LANG_SPECIFIC (r))
15645 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15646 if (!cp_unevaluated_operand)
15647 register_local_specialization (r, t);
15650 DECL_CHAIN (r) = NULL_TREE;
15652 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15653 /*flags=*/0,
15654 args, complain, in_decl))
15655 return error_mark_node;
15657 /* Preserve a typedef that names a type. */
15658 if (is_typedef_decl (r) && type != error_mark_node)
15660 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15661 set_underlying_type (r);
15663 /* common_handle_aligned_attribute doesn't apply the alignment
15664 to DECL_ORIGINAL_TYPE. */
15665 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15666 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15667 TYPE_ALIGN (TREE_TYPE (t)));
15670 layout_decl (r, 0);
15672 break;
15674 default:
15675 gcc_unreachable ();
15677 #undef RETURN
15679 out:
15680 /* Restore the file and line information. */
15681 input_location = saved_loc;
15683 return r;
15686 /* Substitute into the complete parameter type list PARMS. */
15688 tree
15689 tsubst_function_parms (tree parms,
15690 tree args,
15691 tsubst_flags_t complain,
15692 tree in_decl)
15694 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15697 /* Substitute into the ARG_TYPES of a function type.
15698 If END is a TREE_CHAIN, leave it and any following types
15699 un-substituted. */
15701 static tree
15702 tsubst_arg_types (tree arg_types,
15703 tree args,
15704 tree end,
15705 tsubst_flags_t complain,
15706 tree in_decl)
15708 tree type = NULL_TREE;
15709 int len = 1;
15710 tree expanded_args = NULL_TREE;
15712 if (!arg_types || arg_types == void_list_node || arg_types == end)
15713 return arg_types;
15715 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15717 /* For a pack expansion, perform substitution on the
15718 entire expression. Later on, we'll handle the arguments
15719 one-by-one. */
15720 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15721 args, complain, in_decl);
15723 if (TREE_CODE (expanded_args) == TREE_VEC)
15724 /* So that we'll spin through the parameters, one by one. */
15725 len = TREE_VEC_LENGTH (expanded_args);
15726 else
15728 /* We only partially substituted into the parameter
15729 pack. Our type is TYPE_PACK_EXPANSION. */
15730 type = expanded_args;
15731 expanded_args = NULL_TREE;
15734 else
15735 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15737 /* Check if a substituted type is erroneous before substituting into
15738 the rest of the chain. */
15739 for (int i = 0; i < len; i++)
15741 if (expanded_args)
15742 type = TREE_VEC_ELT (expanded_args, i);
15744 if (type == error_mark_node)
15745 return error_mark_node;
15746 if (VOID_TYPE_P (type))
15748 if (complain & tf_error)
15750 error ("invalid parameter type %qT", type);
15751 if (in_decl)
15752 error ("in declaration %q+D", in_decl);
15754 return error_mark_node;
15758 /* We do not substitute into default arguments here. The standard
15759 mandates that they be instantiated only when needed, which is
15760 done in build_over_call. */
15761 tree default_arg = TREE_PURPOSE (arg_types);
15763 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15764 since the new op() won't have any associated template arguments for us
15765 to refer to later. */
15766 if (lambda_fn_in_template_p (in_decl)
15767 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15768 && DECL_LOCAL_DECL_P (in_decl)))
15769 default_arg = tsubst_expr (default_arg, args, complain, in_decl);
15771 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15772 args, end, complain, in_decl);
15773 if (remaining_arg_types == error_mark_node)
15774 return error_mark_node;
15776 for (int i = len-1; i >= 0; i--)
15778 if (expanded_args)
15779 type = TREE_VEC_ELT (expanded_args, i);
15781 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15782 top-level qualifiers as required. */
15783 type = cv_unqualified (type_decays_to (type));
15785 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15787 /* We've instantiated a template before its default arguments
15788 have been parsed. This can happen for a nested template
15789 class, and is not an error unless we require the default
15790 argument in a call of this function. */
15791 remaining_arg_types
15792 = tree_cons (default_arg, type, remaining_arg_types);
15793 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15794 remaining_arg_types);
15796 else
15797 remaining_arg_types
15798 = hash_tree_cons (default_arg, type, remaining_arg_types);
15801 return remaining_arg_types;
15804 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15805 *not* handle the exception-specification for FNTYPE, because the
15806 initial substitution of explicitly provided template parameters
15807 during argument deduction forbids substitution into the
15808 exception-specification:
15810 [temp.deduct]
15812 All references in the function type of the function template to the
15813 corresponding template parameters are replaced by the specified tem-
15814 plate argument values. If a substitution in a template parameter or
15815 in the function type of the function template results in an invalid
15816 type, type deduction fails. [Note: The equivalent substitution in
15817 exception specifications is done only when the function is instanti-
15818 ated, at which point a program is ill-formed if the substitution
15819 results in an invalid type.] */
15821 static tree
15822 tsubst_function_type (tree t,
15823 tree args,
15824 tsubst_flags_t complain,
15825 tree in_decl)
15827 tree return_type;
15828 tree arg_types = NULL_TREE;
15830 /* The TYPE_CONTEXT is not used for function/method types. */
15831 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15833 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15834 failure. */
15835 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15837 if (late_return_type_p)
15839 /* Substitute the argument types. */
15840 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15841 complain, in_decl);
15842 if (arg_types == error_mark_node)
15843 return error_mark_node;
15845 tree save_ccp = current_class_ptr;
15846 tree save_ccr = current_class_ref;
15847 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15848 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15849 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15850 if (do_inject)
15852 /* DR 1207: 'this' is in scope in the trailing return type. */
15853 inject_this_parameter (this_type, cp_type_quals (this_type));
15856 /* Substitute the return type. */
15857 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15859 if (do_inject)
15861 current_class_ptr = save_ccp;
15862 current_class_ref = save_ccr;
15865 else
15866 /* Substitute the return type. */
15867 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15869 if (return_type == error_mark_node)
15870 return error_mark_node;
15871 /* DR 486 clarifies that creation of a function type with an
15872 invalid return type is a deduction failure. */
15873 if (TREE_CODE (return_type) == ARRAY_TYPE
15874 || TREE_CODE (return_type) == FUNCTION_TYPE)
15876 if (complain & tf_error)
15878 if (TREE_CODE (return_type) == ARRAY_TYPE)
15879 error ("function returning an array");
15880 else
15881 error ("function returning a function");
15883 return error_mark_node;
15886 if (!late_return_type_p)
15888 /* Substitute the argument types. */
15889 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15890 complain, in_decl);
15891 if (arg_types == error_mark_node)
15892 return error_mark_node;
15895 /* Construct a new type node and return it. */
15896 return rebuild_function_or_method_type (t, return_type, arg_types,
15897 /*raises=*/NULL_TREE, complain);
15900 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15901 ARGS into that specification, and return the substituted
15902 specification. If there is no specification, return NULL_TREE. */
15904 static tree
15905 tsubst_exception_specification (tree fntype,
15906 tree args,
15907 tsubst_flags_t complain,
15908 tree in_decl,
15909 bool defer_ok)
15911 tree specs;
15912 tree new_specs;
15914 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15915 new_specs = NULL_TREE;
15916 if (specs && TREE_PURPOSE (specs))
15918 /* A noexcept-specifier. */
15919 tree expr = TREE_PURPOSE (specs);
15920 if (TREE_CODE (expr) == INTEGER_CST)
15921 new_specs = expr;
15922 else if (defer_ok)
15924 /* Defer instantiation of noexcept-specifiers to avoid
15925 excessive instantiations (c++/49107). */
15926 new_specs = make_node (DEFERRED_NOEXCEPT);
15927 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15929 /* We already partially instantiated this member template,
15930 so combine the new args with the old. */
15931 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15932 = DEFERRED_NOEXCEPT_PATTERN (expr);
15933 DEFERRED_NOEXCEPT_ARGS (new_specs)
15934 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15936 else
15938 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15939 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15942 else
15944 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15946 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15947 args);
15948 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15950 new_specs = tsubst_expr (expr, args, complain, in_decl);
15952 new_specs = build_noexcept_spec (new_specs, complain);
15953 /* We've instantiated a template before a noexcept-specifier
15954 contained therein has been parsed. This can happen for
15955 a nested template class:
15957 struct S {
15958 template<typename> struct B { B() noexcept(...); };
15959 struct A : B<int> { ... use B() ... };
15962 where completing B<int> will trigger instantiating the
15963 noexcept, even though we only parse it at the end of S. */
15964 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15966 gcc_checking_assert (defer_ok);
15967 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15970 else if (specs)
15972 if (! TREE_VALUE (specs))
15973 new_specs = specs;
15974 else
15975 while (specs)
15977 tree spec;
15978 int i, len = 1;
15979 tree expanded_specs = NULL_TREE;
15981 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15983 /* Expand the pack expansion type. */
15984 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15985 args, complain,
15986 in_decl);
15988 if (expanded_specs == error_mark_node)
15989 return error_mark_node;
15990 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15991 len = TREE_VEC_LENGTH (expanded_specs);
15992 else
15994 /* We're substituting into a member template, so
15995 we got a TYPE_PACK_EXPANSION back. Add that
15996 expansion and move on. */
15997 gcc_assert (TREE_CODE (expanded_specs)
15998 == TYPE_PACK_EXPANSION);
15999 new_specs = add_exception_specifier (new_specs,
16000 expanded_specs,
16001 complain);
16002 specs = TREE_CHAIN (specs);
16003 continue;
16007 for (i = 0; i < len; ++i)
16009 if (expanded_specs)
16010 spec = TREE_VEC_ELT (expanded_specs, i);
16011 else
16012 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
16013 if (spec == error_mark_node)
16014 return spec;
16015 new_specs = add_exception_specifier (new_specs, spec,
16016 complain);
16019 specs = TREE_CHAIN (specs);
16022 return new_specs;
16025 /* Substitute through a TREE_LIST of types or expressions, handling pack
16026 expansions. */
16028 tree
16029 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16031 if (t == void_list_node)
16032 return t;
16034 tree purpose = TREE_PURPOSE (t);
16035 tree purposevec = NULL_TREE;
16036 if (!purpose)
16038 else if (PACK_EXPANSION_P (purpose))
16040 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
16041 if (TREE_CODE (purpose) == TREE_VEC)
16042 purposevec = purpose;
16044 else if (TYPE_P (purpose))
16045 purpose = tsubst (purpose, args, complain, in_decl);
16046 else
16047 purpose = tsubst_expr (purpose, args, complain, in_decl);
16048 if (purpose == error_mark_node || purposevec == error_mark_node)
16049 return error_mark_node;
16051 tree value = TREE_VALUE (t);
16052 tree valuevec = NULL_TREE;
16053 if (!value)
16055 else if (PACK_EXPANSION_P (value))
16057 value = tsubst_pack_expansion (value, args, complain, in_decl);
16058 if (TREE_CODE (value) == TREE_VEC)
16059 valuevec = value;
16061 else if (TYPE_P (value))
16062 value = tsubst (value, args, complain, in_decl);
16063 else
16064 value = tsubst_expr (value, args, complain, in_decl);
16065 if (value == error_mark_node || valuevec == error_mark_node)
16066 return error_mark_node;
16068 tree chain = TREE_CHAIN (t);
16069 if (!chain)
16071 else if (TREE_CODE (chain) == TREE_LIST)
16072 chain = tsubst_tree_list (chain, args, complain, in_decl);
16073 else if (TYPE_P (chain))
16074 chain = tsubst (chain, args, complain, in_decl);
16075 else
16076 chain = tsubst_expr (chain, args, complain, in_decl);
16077 if (chain == error_mark_node)
16078 return error_mark_node;
16080 if (purpose == TREE_PURPOSE (t)
16081 && value == TREE_VALUE (t)
16082 && chain == TREE_CHAIN (t))
16083 return t;
16085 int len;
16086 /* Determine the number of arguments. */
16087 if (purposevec)
16089 len = TREE_VEC_LENGTH (purposevec);
16090 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
16092 else if (valuevec)
16093 len = TREE_VEC_LENGTH (valuevec);
16094 else
16095 len = 1;
16097 for (int i = len; i-- > 0; )
16099 if (purposevec)
16100 purpose = TREE_VEC_ELT (purposevec, i);
16101 if (valuevec)
16102 value = TREE_VEC_ELT (valuevec, i);
16104 if (value && TYPE_P (value))
16105 chain = hash_tree_cons (purpose, value, chain);
16106 else
16107 chain = tree_cons (purpose, value, chain);
16110 return chain;
16113 /* Take the tree structure T and replace template parameters used
16114 therein with the argument vector ARGS. IN_DECL is an associated
16115 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
16116 Issue error and warning messages under control of COMPLAIN. Note
16117 that we must be relatively non-tolerant of extensions here, in
16118 order to preserve conformance; if we allow substitutions that
16119 should not be allowed, we may allow argument deductions that should
16120 not succeed, and therefore report ambiguous overload situations
16121 where there are none. In theory, we could allow the substitution,
16122 but indicate that it should have failed, and allow our caller to
16123 make sure that the right thing happens, but we don't try to do this
16124 yet.
16126 This function is used for dealing with types, decls and the like;
16127 for expressions, use tsubst_expr or tsubst_copy. */
16129 tree
16130 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16132 enum tree_code code;
16133 tree type, r = NULL_TREE;
16135 if (t == NULL_TREE || t == error_mark_node
16136 || t == integer_type_node
16137 || t == void_type_node
16138 || t == char_type_node
16139 || t == unknown_type_node
16140 || TREE_CODE (t) == NAMESPACE_DECL
16141 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
16142 return t;
16144 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
16145 complain &= ~tf_tst_ok;
16147 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
16148 complain &= ~tf_qualifying_scope;
16150 if (DECL_P (t))
16151 return tsubst_decl (t, args, complain);
16153 if (args == NULL_TREE)
16154 return t;
16156 code = TREE_CODE (t);
16158 gcc_assert (code != IDENTIFIER_NODE);
16159 type = TREE_TYPE (t);
16161 gcc_assert (type != unknown_type_node);
16163 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
16164 return d;
16166 /* Reuse typedefs. We need to do this to handle dependent attributes,
16167 such as attribute aligned. */
16168 if (TYPE_P (t)
16169 && typedef_variant_p (t))
16171 tree decl = TYPE_NAME (t);
16173 if (alias_template_specialization_p (t, nt_opaque))
16175 /* DECL represents an alias template and we want to
16176 instantiate it. */
16177 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16178 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16179 r = instantiate_alias_template (tmpl, gen_args, complain);
16181 else if (DECL_CLASS_SCOPE_P (decl)
16182 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
16183 && uses_template_parms (DECL_CONTEXT (decl)))
16185 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16186 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16187 r = retrieve_specialization (tmpl, gen_args, 0);
16189 else if (DECL_FUNCTION_SCOPE_P (decl)
16190 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
16191 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
16192 r = retrieve_local_specialization (decl);
16193 else
16194 /* The typedef is from a non-template context. */
16195 return t;
16197 if (r)
16199 r = TREE_TYPE (r);
16200 r = cp_build_qualified_type
16201 (r, cp_type_quals (t) | cp_type_quals (r),
16202 complain | tf_ignore_bad_quals);
16203 return r;
16205 else
16207 /* We don't have an instantiation yet, so drop the typedef. */
16208 int quals = cp_type_quals (t);
16209 t = DECL_ORIGINAL_TYPE (decl);
16210 t = cp_build_qualified_type (t, quals,
16211 complain | tf_ignore_bad_quals);
16215 bool fndecl_type = (complain & tf_fndecl_type);
16216 complain &= ~tf_fndecl_type;
16218 if (type
16219 && code != TYPENAME_TYPE
16220 && code != TEMPLATE_TYPE_PARM
16221 && code != TEMPLATE_PARM_INDEX
16222 && code != IDENTIFIER_NODE
16223 && code != FUNCTION_TYPE
16224 && code != METHOD_TYPE)
16225 type = tsubst (type, args, complain, in_decl);
16226 if (type == error_mark_node)
16227 return error_mark_node;
16229 switch (code)
16231 case RECORD_TYPE:
16232 if (TYPE_PTRMEMFUNC_P (t))
16233 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16234 /* Fall through. */
16235 case UNION_TYPE:
16236 case ENUMERAL_TYPE:
16237 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16238 /*entering_scope=*/0);
16240 case ERROR_MARK:
16241 case IDENTIFIER_NODE:
16242 case VOID_TYPE:
16243 case OPAQUE_TYPE:
16244 case REAL_TYPE:
16245 case COMPLEX_TYPE:
16246 case VECTOR_TYPE:
16247 case BOOLEAN_TYPE:
16248 case NULLPTR_TYPE:
16249 case LANG_TYPE:
16250 return t;
16252 case INTEGER_TYPE:
16253 if (t == integer_type_node)
16254 return t;
16256 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16257 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16258 return t;
16261 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16263 max = tsubst_expr (omax, args, complain, in_decl);
16265 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16266 needed. */
16267 if (TREE_CODE (max) == NOP_EXPR
16268 && TREE_SIDE_EFFECTS (omax)
16269 && !TREE_TYPE (max))
16270 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16272 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16273 with TREE_SIDE_EFFECTS that indicates this is not an integral
16274 constant expression. */
16275 if (processing_template_decl
16276 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16278 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16279 TREE_SIDE_EFFECTS (max) = 1;
16282 return compute_array_index_type (NULL_TREE, max, complain);
16285 case TEMPLATE_TYPE_PARM:
16286 if (template_placeholder_p (t))
16288 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16289 tmpl = tsubst_expr (tmpl, args, complain, in_decl);
16290 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16291 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16293 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16294 return make_template_placeholder (tmpl);
16295 else
16296 return t;
16298 /* Fall through. */
16299 case TEMPLATE_TEMPLATE_PARM:
16300 case BOUND_TEMPLATE_TEMPLATE_PARM:
16301 case TEMPLATE_PARM_INDEX:
16303 int idx;
16304 int level;
16305 int levels;
16306 tree arg = NULL_TREE;
16308 r = NULL_TREE;
16310 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16311 template_parm_level_and_index (t, &level, &idx);
16313 levels = TMPL_ARGS_DEPTH (args);
16314 if (level <= levels
16315 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16317 arg = TMPL_ARG (args, level, idx);
16319 /* See through ARGUMENT_PACK_SELECT arguments. */
16320 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16321 arg = argument_pack_select_arg (arg);
16324 if (arg == error_mark_node)
16325 return error_mark_node;
16326 else if (arg != NULL_TREE)
16328 if (ARGUMENT_PACK_P (arg))
16329 /* If ARG is an argument pack, we don't actually want to
16330 perform a substitution here, because substitutions
16331 for argument packs are only done
16332 element-by-element. We can get to this point when
16333 substituting the type of a non-type template
16334 parameter pack, when that type actually contains
16335 template parameter packs from an outer template, e.g.,
16337 template<typename... Types> struct A {
16338 template<Types... Values> struct B { };
16339 }; */
16340 return t;
16342 if (code == TEMPLATE_TYPE_PARM)
16344 int quals;
16346 /* When building concept checks for the purpose of
16347 deducing placeholders, we can end up with wildcards
16348 where types are expected. Adjust this to the deduced
16349 value. */
16350 if (TREE_CODE (arg) == WILDCARD_DECL)
16351 arg = TREE_TYPE (TREE_TYPE (arg));
16353 gcc_assert (TYPE_P (arg));
16355 quals = cp_type_quals (arg) | cp_type_quals (t);
16357 return cp_build_qualified_type
16358 (arg, quals, complain | tf_ignore_bad_quals);
16360 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16362 /* We are processing a type constructed from a
16363 template template parameter. */
16364 tree argvec = tsubst (TYPE_TI_ARGS (t),
16365 args, complain, in_decl);
16366 if (argvec == error_mark_node)
16367 return error_mark_node;
16369 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16370 || TREE_CODE (arg) == TEMPLATE_DECL
16371 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16373 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16374 /* Consider this code:
16376 template <template <class> class Template>
16377 struct Internal {
16378 template <class Arg> using Bind = Template<Arg>;
16381 template <template <class> class Template, class Arg>
16382 using Instantiate = Template<Arg>; //#0
16384 template <template <class> class Template,
16385 class Argument>
16386 using Bind =
16387 Instantiate<Internal<Template>::template Bind,
16388 Argument>; //#1
16390 When #1 is parsed, the
16391 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16392 parameter `Template' in #0 matches the
16393 UNBOUND_CLASS_TEMPLATE representing the argument
16394 `Internal<Template>::template Bind'; We then want
16395 to assemble the type `Bind<Argument>' that can't
16396 be fully created right now, because
16397 `Internal<Template>' not being complete, the Bind
16398 template cannot be looked up in that context. So
16399 we need to "store" `Bind<Argument>' for later
16400 when the context of Bind becomes complete. Let's
16401 store that in a TYPENAME_TYPE. */
16402 return make_typename_type (TYPE_CONTEXT (arg),
16403 build_nt (TEMPLATE_ID_EXPR,
16404 TYPE_IDENTIFIER (arg),
16405 argvec),
16406 typename_type,
16407 complain);
16409 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16410 are resolving nested-types in the signature of a
16411 member function templates. Otherwise ARG is a
16412 TEMPLATE_DECL and is the real template to be
16413 instantiated. */
16414 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16415 arg = TYPE_NAME (arg);
16417 r = lookup_template_class (arg,
16418 argvec, in_decl,
16419 DECL_CONTEXT (arg),
16420 /*entering_scope=*/0,
16421 complain);
16422 return cp_build_qualified_type
16423 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16425 else if (code == TEMPLATE_TEMPLATE_PARM)
16426 return arg;
16427 else
16428 /* TEMPLATE_PARM_INDEX. */
16429 return convert_from_reference (unshare_expr (arg));
16432 if (level == 1)
16433 /* This can happen during the attempted tsubst'ing in
16434 unify. This means that we don't yet have any information
16435 about the template parameter in question. */
16436 return t;
16438 /* Early in template argument deduction substitution, we don't
16439 want to reduce the level of 'auto', or it will be confused
16440 with a normal template parm in subsequent deduction.
16441 Similarly, don't reduce the level of template parameters to
16442 avoid mismatches when deducing their types. */
16443 if (complain & tf_partial)
16444 return t;
16446 /* If we get here, we must have been looking at a parm for a
16447 more deeply nested template. Make a new version of this
16448 template parameter, but with a lower level. */
16449 int quals;
16450 switch (code)
16452 case TEMPLATE_TYPE_PARM:
16453 case TEMPLATE_TEMPLATE_PARM:
16454 quals = cp_type_quals (t);
16455 if (quals)
16457 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16458 t = TYPE_MAIN_VARIANT (t);
16461 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16462 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16463 && (code == TEMPLATE_TYPE_PARM
16464 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16465 /* Cache lowering a type parameter or a simple template
16466 template parameter. */
16467 r = TREE_TYPE (d);
16469 if (!r)
16471 r = copy_type (t);
16472 TEMPLATE_TYPE_PARM_INDEX (r)
16473 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16474 r, levels, args, complain);
16475 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16476 TYPE_MAIN_VARIANT (r) = r;
16477 TYPE_POINTER_TO (r) = NULL_TREE;
16478 TYPE_REFERENCE_TO (r) = NULL_TREE;
16480 if (code == TEMPLATE_TYPE_PARM)
16481 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16482 /* Propagate constraints on placeholders since they are
16483 only instantiated during satisfaction. */
16484 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16486 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16487 SET_TYPE_STRUCTURAL_EQUALITY (r);
16488 else
16489 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16492 if (quals)
16493 r = cp_build_qualified_type (r, quals,
16494 complain | tf_ignore_bad_quals);
16495 break;
16497 case BOUND_TEMPLATE_TEMPLATE_PARM:
16499 tree tinfo = TYPE_TEMPLATE_INFO (t);
16500 /* We might need to substitute into the types of non-type
16501 template parameters. This also lowers the level of
16502 the ttp appropriately. */
16503 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16504 complain, in_decl);
16505 if (tmpl == error_mark_node)
16506 return error_mark_node;
16507 tree argvec = tsubst (TI_ARGS (tinfo), args,
16508 complain, in_decl);
16509 if (argvec == error_mark_node)
16510 return error_mark_node;
16511 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16512 /*entering_scope=*/false, complain);
16513 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16514 break;
16517 case TEMPLATE_PARM_INDEX:
16518 /* OK, now substitute the type of the non-type parameter. We
16519 couldn't do it earlier because it might be an auto parameter,
16520 and we wouldn't need to if we had an argument. */
16521 type = tsubst (type, args, complain, in_decl);
16522 if (type == error_mark_node)
16523 return error_mark_node;
16524 r = reduce_template_parm_level (t, type, levels, args, complain);
16525 break;
16527 default:
16528 gcc_unreachable ();
16531 return r;
16534 case TREE_LIST:
16535 return tsubst_tree_list (t, args, complain, in_decl);
16537 case TREE_BINFO:
16538 /* We should never be tsubsting a binfo. */
16539 gcc_unreachable ();
16541 case TREE_VEC:
16542 /* A vector of template arguments. */
16543 gcc_assert (!type);
16544 return tsubst_template_args (t, args, complain, in_decl);
16546 case POINTER_TYPE:
16547 case REFERENCE_TYPE:
16549 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16550 return t;
16552 /* [temp.deduct]
16554 Type deduction may fail for any of the following
16555 reasons:
16557 -- Attempting to create a pointer to reference type.
16558 -- Attempting to create a reference to a reference type or
16559 a reference to void.
16561 Core issue 106 says that creating a reference to a reference
16562 during instantiation is no longer a cause for failure. We
16563 only enforce this check in strict C++98 mode. */
16564 if ((TYPE_REF_P (type)
16565 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16566 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16568 static location_t last_loc;
16570 /* We keep track of the last time we issued this error
16571 message to avoid spewing a ton of messages during a
16572 single bad template instantiation. */
16573 if (complain & tf_error
16574 && last_loc != input_location)
16576 if (VOID_TYPE_P (type))
16577 error ("forming reference to void");
16578 else if (code == POINTER_TYPE)
16579 error ("forming pointer to reference type %qT", type);
16580 else
16581 error ("forming reference to reference type %qT", type);
16582 last_loc = input_location;
16585 return error_mark_node;
16587 else if (TREE_CODE (type) == FUNCTION_TYPE
16588 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16589 || type_memfn_rqual (type) != REF_QUAL_NONE))
16591 if (complain & tf_error)
16593 if (code == POINTER_TYPE)
16594 error ("forming pointer to qualified function type %qT",
16595 type);
16596 else
16597 error ("forming reference to qualified function type %qT",
16598 type);
16600 return error_mark_node;
16602 else if (code == POINTER_TYPE)
16604 r = build_pointer_type (type);
16605 if (TREE_CODE (type) == METHOD_TYPE)
16606 r = build_ptrmemfunc_type (r);
16608 else if (TYPE_REF_P (type))
16609 /* In C++0x, during template argument substitution, when there is an
16610 attempt to create a reference to a reference type, reference
16611 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16613 "If a template-argument for a template-parameter T names a type
16614 that is a reference to a type A, an attempt to create the type
16615 'lvalue reference to cv T' creates the type 'lvalue reference to
16616 A,' while an attempt to create the type type rvalue reference to
16617 cv T' creates the type T"
16619 r = cp_build_reference_type
16620 (TREE_TYPE (type),
16621 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16622 else
16623 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16624 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16626 if (r != error_mark_node)
16627 /* Will this ever be needed for TYPE_..._TO values? */
16628 layout_type (r);
16630 return r;
16632 case OFFSET_TYPE:
16634 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16635 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16637 /* [temp.deduct]
16639 Type deduction may fail for any of the following
16640 reasons:
16642 -- Attempting to create "pointer to member of T" when T
16643 is not a class type. */
16644 if (complain & tf_error)
16645 error ("creating pointer to member of non-class type %qT", r);
16646 return error_mark_node;
16648 if (TYPE_REF_P (type))
16650 if (complain & tf_error)
16651 error ("creating pointer to member reference type %qT", type);
16652 return error_mark_node;
16654 if (VOID_TYPE_P (type))
16656 if (complain & tf_error)
16657 error ("creating pointer to member of type void");
16658 return error_mark_node;
16660 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16661 if (TREE_CODE (type) == FUNCTION_TYPE)
16663 /* The type of the implicit object parameter gets its
16664 cv-qualifiers from the FUNCTION_TYPE. */
16665 tree memptr;
16666 tree method_type
16667 = build_memfn_type (type, r, type_memfn_quals (type),
16668 type_memfn_rqual (type));
16669 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16670 return cp_build_qualified_type (memptr, cp_type_quals (t),
16671 complain);
16673 else
16674 return cp_build_qualified_type (build_ptrmem_type (r, type),
16675 cp_type_quals (t),
16676 complain);
16678 case FUNCTION_TYPE:
16679 case METHOD_TYPE:
16681 tree fntype;
16682 tree specs;
16683 fntype = tsubst_function_type (t, args, complain, in_decl);
16684 if (fntype == error_mark_node)
16685 return error_mark_node;
16687 /* Substitute the exception specification. */
16688 specs = tsubst_exception_specification (t, args, complain, in_decl,
16689 /*defer_ok*/fndecl_type);
16690 if (specs == error_mark_node)
16691 return error_mark_node;
16692 if (specs)
16693 fntype = build_exception_variant (fntype, specs);
16694 return fntype;
16696 case ARRAY_TYPE:
16698 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16699 if (domain == error_mark_node)
16700 return error_mark_node;
16702 /* As an optimization, we avoid regenerating the array type if
16703 it will obviously be the same as T. */
16704 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16705 return t;
16707 /* These checks should match the ones in create_array_type_for_decl.
16709 [temp.deduct]
16711 The deduction may fail for any of the following reasons:
16713 -- Attempting to create an array with an element type that
16714 is void, a function type, or a reference type, or [DR337]
16715 an abstract class type. */
16716 if (VOID_TYPE_P (type)
16717 || TREE_CODE (type) == FUNCTION_TYPE
16718 || (TREE_CODE (type) == ARRAY_TYPE
16719 && TYPE_DOMAIN (type) == NULL_TREE)
16720 || TYPE_REF_P (type))
16722 if (complain & tf_error)
16723 error ("creating array of %qT", type);
16724 return error_mark_node;
16727 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16728 !(complain & tf_error)))
16729 return error_mark_node;
16731 r = build_cplus_array_type (type, domain);
16733 if (!valid_array_size_p (input_location, r, in_decl,
16734 (complain & tf_error)))
16735 return error_mark_node;
16737 if (TYPE_USER_ALIGN (t))
16739 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16740 TYPE_USER_ALIGN (r) = 1;
16743 return r;
16746 case TYPENAME_TYPE:
16748 tree ctx = TYPE_CONTEXT (t);
16749 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16751 ctx = tsubst_pack_expansion (ctx, args,
16752 complain | tf_qualifying_scope,
16753 in_decl);
16754 if (ctx == error_mark_node
16755 || TREE_VEC_LENGTH (ctx) > 1)
16756 return error_mark_node;
16757 if (TREE_VEC_LENGTH (ctx) == 0)
16759 if (complain & tf_error)
16760 error ("%qD is instantiated for an empty pack",
16761 TYPENAME_TYPE_FULLNAME (t));
16762 return error_mark_node;
16764 ctx = TREE_VEC_ELT (ctx, 0);
16766 else
16767 ctx = tsubst_aggr_type (ctx, args,
16768 complain | tf_qualifying_scope,
16769 in_decl, /*entering_scope=*/1);
16770 if (ctx == error_mark_node)
16771 return error_mark_node;
16773 tree f = tsubst_name (TYPENAME_TYPE_FULLNAME (t), args,
16774 complain, in_decl);
16775 if (f == error_mark_node)
16776 return error_mark_node;
16778 if (!MAYBE_CLASS_TYPE_P (ctx))
16780 if (complain & tf_error)
16781 error ("%qT is not a class, struct, or union type", ctx);
16782 return error_mark_node;
16784 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16786 /* Normally, make_typename_type does not require that the CTX
16787 have complete type in order to allow things like:
16789 template <class T> struct S { typename S<T>::X Y; };
16791 But, such constructs have already been resolved by this
16792 point, so here CTX really should have complete type, unless
16793 it's a partial instantiation. */
16794 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16795 return error_mark_node;
16798 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16799 tags. TYPENAME_TYPE should probably remember the exact tag that
16800 was written. */
16801 enum tag_types tag_type
16802 = TYPENAME_IS_CLASS_P (t) ? class_type
16803 : TYPENAME_IS_ENUM_P (t) ? enum_type
16804 : typename_type;
16805 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16806 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16807 f = make_typename_type (ctx, f, tag_type, tcomplain);
16808 if (f == error_mark_node)
16809 return f;
16810 if (TREE_CODE (f) == TYPE_DECL)
16812 complain |= tf_ignore_bad_quals;
16813 f = TREE_TYPE (f);
16816 if (TREE_CODE (f) != TYPENAME_TYPE)
16818 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16820 if (complain & tf_error)
16821 error ("%qT resolves to %qT, which is not an enumeration type",
16822 t, f);
16823 else
16824 return error_mark_node;
16826 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16828 if (complain & tf_error)
16829 error ("%qT resolves to %qT, which is not a class type",
16830 t, f);
16831 else
16832 return error_mark_node;
16836 return cp_build_qualified_type
16837 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16840 case UNBOUND_CLASS_TEMPLATE:
16842 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16843 in_decl, /*entering_scope=*/1);
16844 tree name = TYPE_IDENTIFIER (t);
16845 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16847 if (ctx == error_mark_node || name == error_mark_node)
16848 return error_mark_node;
16850 if (parm_list)
16851 parm_list = tsubst_template_parms (parm_list, args, complain);
16852 return make_unbound_class_template (ctx, name, parm_list, complain);
16855 case TYPEOF_TYPE:
16857 tree type;
16859 ++cp_unevaluated_operand;
16860 ++c_inhibit_evaluation_warnings;
16862 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16864 --cp_unevaluated_operand;
16865 --c_inhibit_evaluation_warnings;
16867 type = finish_typeof (type);
16868 return cp_build_qualified_type (type,
16869 cp_type_quals (t)
16870 | cp_type_quals (type),
16871 complain);
16874 case DECLTYPE_TYPE:
16876 tree type;
16878 ++cp_unevaluated_operand;
16879 ++c_inhibit_evaluation_warnings;
16881 type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
16882 complain|tf_decltype, in_decl);
16884 --cp_unevaluated_operand;
16885 --c_inhibit_evaluation_warnings;
16887 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16888 type = lambda_capture_field_type (type,
16889 false /*explicit_init*/,
16890 DECLTYPE_FOR_REF_CAPTURE (t));
16891 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16892 type = lambda_proxy_type (type);
16893 else
16895 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16896 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16897 && EXPR_P (type))
16898 /* In a template ~id could be either a complement expression
16899 or an unqualified-id naming a destructor; if instantiating
16900 it produces an expression, it's not an id-expression or
16901 member access. */
16902 id = false;
16903 type = finish_decltype_type (type, id, complain);
16905 return cp_build_qualified_type (type,
16906 cp_type_quals (t)
16907 | cp_type_quals (type),
16908 complain | tf_ignore_bad_quals);
16911 case TRAIT_TYPE:
16913 tree type1 = TRAIT_TYPE_TYPE1 (t);
16914 if (TYPE_P (type1))
16915 type1 = tsubst (type1, args, complain, in_decl);
16916 else
16917 type1 = tsubst_expr (type1, args, complain, in_decl);
16918 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16919 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16920 return cp_build_qualified_type (type,
16921 cp_type_quals (t) | cp_type_quals (type),
16922 complain | tf_ignore_bad_quals);
16925 case TYPE_ARGUMENT_PACK:
16926 case NONTYPE_ARGUMENT_PACK:
16927 return tsubst_argument_pack (t, args, complain, in_decl);
16929 case VOID_CST:
16930 case INTEGER_CST:
16931 case REAL_CST:
16932 case STRING_CST:
16933 case PLUS_EXPR:
16934 case MINUS_EXPR:
16935 case NEGATE_EXPR:
16936 case NOP_EXPR:
16937 case INDIRECT_REF:
16938 case ADDR_EXPR:
16939 case CALL_EXPR:
16940 case ARRAY_REF:
16941 case SCOPE_REF:
16942 case OMP_ARRAY_SECTION:
16943 /* We should use one of the expression tsubsts for these codes. */
16944 gcc_unreachable ();
16946 default:
16947 sorry ("use of %qs in template", get_tree_code_name (code));
16948 return error_mark_node;
16952 /* Convenience wrapper over tsubst for substituting into the LHS
16953 of the :: scope resolution operator. */
16955 static tree
16956 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16958 gcc_checking_assert (TYPE_P (t));
16959 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16962 /* Convenience wrapper over tsubst for substituting into an id-expression
16963 without resolving its terminal name. */
16965 static tree
16966 tsubst_name (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16968 return tsubst_expr (t, args, complain | tf_no_name_lookup, in_decl);
16971 /* OLDFNS is a lookup set of member functions from some class template, and
16972 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16973 of that class template. Return the subset of NEWFNS which are
16974 specializations of a function from OLDFNS. */
16976 static tree
16977 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16979 /* Record all member functions from the old lookup set OLDFNS into
16980 VISIBLE_SET. */
16981 hash_set<tree> visible_set;
16982 bool seen_dep_using = false;
16983 for (tree fn : lkp_range (oldfns))
16985 if (TREE_CODE (fn) == USING_DECL)
16987 /* Imprecisely handle dependent using-decl by keeping all members
16988 in the new lookup set that are defined in a base class, i.e.
16989 members that could plausibly have been introduced by this
16990 dependent using-decl.
16991 FIXME: Track which members are introduced by a dependent
16992 using-decl precisely, perhaps by performing another lookup
16993 from the substituted USING_DECL_SCOPE. */
16994 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16995 seen_dep_using = true;
16997 else
16998 visible_set.add (fn);
17001 /* Returns true iff (a less specialized version of) FN appeared in
17002 the old lookup set OLDFNS. */
17003 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
17004 if (DECL_CONTEXT (fn) != newtype)
17005 /* FN is a member function from a base class, introduced via a
17006 using-decl; if it might have been introduced by a dependent
17007 using-decl then just conservatively keep it, otherwise look
17008 in the old lookup set for FN exactly. */
17009 return seen_dep_using || visible_set.contains (fn);
17010 else if (TREE_CODE (fn) == TEMPLATE_DECL)
17011 /* FN is a member function template from the current class;
17012 look in the old lookup set for the TEMPLATE_DECL from which
17013 it was specialized. */
17014 return visible_set.contains (DECL_TI_TEMPLATE (fn));
17015 else
17016 /* FN is a non-template member function from the current class;
17017 look in the old lookup set for the FUNCTION_DECL from which
17018 it was specialized. */
17019 return visible_set.contains (DECL_TEMPLATE_RESULT
17020 (DECL_TI_TEMPLATE (fn)));
17023 bool lookup_changed_p = false;
17024 for (tree fn : lkp_range (newfns))
17025 if (!visible_p (fn))
17027 lookup_changed_p = true;
17028 break;
17030 if (!lookup_changed_p)
17031 return newfns;
17033 /* Filter out from NEWFNS the member functions that weren't
17034 previously visible according to OLDFNS. */
17035 tree filtered_fns = NULL_TREE;
17036 unsigned filtered_size = 0;
17037 for (tree fn : lkp_range (newfns))
17038 if (visible_p (fn))
17040 filtered_fns = lookup_add (fn, filtered_fns);
17041 filtered_size++;
17043 gcc_checking_assert (seen_dep_using
17044 ? filtered_size >= visible_set.elements ()
17045 : filtered_size == visible_set.elements ());
17047 return filtered_fns;
17050 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
17051 expression on the left-hand side of the "." or "->" operator. We
17052 only do the lookup if we had a dependent BASELINK. Otherwise we
17053 adjust it onto the instantiated heirarchy. */
17055 static tree
17056 tsubst_baselink (tree baselink, tree object_type,
17057 tree args, tsubst_flags_t complain, tree in_decl)
17059 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
17060 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
17061 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
17063 tree optype = BASELINK_OPTYPE (baselink);
17064 optype = tsubst (optype, args, complain, in_decl);
17066 tree template_args = NULL_TREE;
17067 bool template_id_p = false;
17068 tree fns = BASELINK_FUNCTIONS (baselink);
17069 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
17071 template_id_p = true;
17072 template_args = TREE_OPERAND (fns, 1);
17073 fns = TREE_OPERAND (fns, 0);
17074 if (template_args)
17075 template_args = tsubst_template_args (template_args, args,
17076 complain, in_decl);
17079 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
17080 binfo_type = tsubst (binfo_type, args, complain, in_decl);
17081 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
17082 || optype != BASELINK_OPTYPE (baselink));
17084 if (dependent_p)
17086 tree name = OVL_NAME (fns);
17087 if (IDENTIFIER_CONV_OP_P (name))
17088 name = make_conv_op_name (optype);
17090 /* See maybe_dependent_member_ref. */
17091 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
17093 if (template_id_p)
17094 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
17095 template_args);
17096 return build_qualified_name (NULL_TREE, qualifying_scope, name,
17097 /* ::template */false);
17100 if (name == complete_dtor_identifier)
17101 /* Treat as-if non-dependent below. */
17102 dependent_p = false;
17104 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
17105 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
17106 complain);
17107 if (maybe_incomplete)
17109 /* Filter out from the new lookup set those functions which didn't
17110 appear in the original lookup set (in a less specialized form).
17111 This is needed to preserve the consistency of member lookup
17112 performed in an incomplete-class context, within which
17113 later-declared members ought to remain invisible. */
17114 BASELINK_FUNCTIONS (baselink)
17115 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
17116 binfo_type);
17117 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
17120 if (!baselink)
17122 if ((complain & tf_error)
17123 && constructor_name_p (name, qualifying_scope))
17124 error ("cannot call constructor %<%T::%D%> directly",
17125 qualifying_scope, name);
17126 return error_mark_node;
17129 fns = BASELINK_FUNCTIONS (baselink);
17131 else
17133 /* We're going to overwrite pieces below, make a duplicate. */
17134 baselink = copy_node (baselink);
17136 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
17138 /* The decl we found was from non-dependent scope, but we still need
17139 to update the binfos for the instantiated qualifying_scope. */
17140 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
17141 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
17142 ba_unique, nullptr, complain);
17146 /* If lookup found a single function, mark it as used at this point.
17147 (If lookup found multiple functions the one selected later by
17148 overload resolution will be marked as used at that point.) */
17149 if (!template_id_p && !really_overloaded_fn (fns))
17151 tree fn = OVL_FIRST (fns);
17152 bool ok = mark_used (fn, complain);
17153 if (!ok && !(complain & tf_error))
17154 return error_mark_node;
17155 if (ok && BASELINK_P (baselink))
17156 /* We might have instantiated an auto function. */
17157 TREE_TYPE (baselink) = TREE_TYPE (fn);
17160 if (BASELINK_P (baselink))
17162 /* Add back the template arguments, if present. */
17163 if (template_id_p)
17164 BASELINK_FUNCTIONS (baselink)
17165 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
17167 /* Update the conversion operator type. */
17168 BASELINK_OPTYPE (baselink) = optype;
17171 if (!object_type)
17172 object_type = current_class_type;
17174 if (qualified_p || !dependent_p)
17176 baselink = adjust_result_of_qualified_name_lookup (baselink,
17177 qualifying_scope,
17178 object_type);
17179 if (!qualified_p)
17180 /* We need to call adjust_result_of_qualified_name_lookup in case the
17181 destructor names a base class, but we unset BASELINK_QUALIFIED_P
17182 so that we still get virtual function binding. */
17183 BASELINK_QUALIFIED_P (baselink) = false;
17186 return baselink;
17189 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
17190 true if the qualified-id will be a postfix-expression in-and-of
17191 itself; false if more of the postfix-expression follows the
17192 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
17193 of "&". */
17195 static tree
17196 tsubst_qualified_id (tree qualified_id, tree args,
17197 tsubst_flags_t complain, tree in_decl,
17198 bool done, bool address_p)
17200 tree expr;
17201 tree scope;
17202 tree name;
17203 bool is_template;
17204 tree template_args;
17205 location_t loc = EXPR_LOCATION (qualified_id);
17207 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
17209 /* Figure out what name to look up. */
17210 name = TREE_OPERAND (qualified_id, 1);
17211 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
17213 is_template = true;
17214 template_args = TREE_OPERAND (name, 1);
17215 if (template_args)
17216 template_args = tsubst_template_args (template_args, args,
17217 complain, in_decl);
17218 if (template_args == error_mark_node)
17219 return error_mark_node;
17220 name = TREE_OPERAND (name, 0);
17222 else
17224 is_template = false;
17225 template_args = NULL_TREE;
17228 /* Substitute into the qualifying scope. When there are no ARGS, we
17229 are just trying to simplify a non-dependent expression. In that
17230 case the qualifying scope may be dependent, and, in any case,
17231 substituting will not help. */
17232 scope = TREE_OPERAND (qualified_id, 0);
17233 if (args)
17235 scope = tsubst_scope (scope, args, complain, in_decl);
17236 expr = tsubst_name (name, args, complain, in_decl);
17238 else
17239 expr = name;
17241 if (dependent_scope_p (scope))
17243 if (TREE_CODE (expr) == SCOPE_REF)
17244 /* We built one in tsubst_baselink. */
17245 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17246 else
17248 if (is_template)
17249 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17250 template_args);
17251 expr = build_qualified_name (NULL_TREE, scope, expr,
17252 QUALIFIED_NAME_IS_TEMPLATE
17253 (qualified_id));
17255 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17256 return expr;
17259 if (!BASELINK_P (name) && !DECL_P (expr))
17261 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17263 /* A BIT_NOT_EXPR is used to represent a destructor. */
17264 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17266 error ("qualifying type %qT does not match destructor name ~%qT",
17267 scope, TREE_OPERAND (expr, 0));
17268 expr = error_mark_node;
17270 else
17271 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17272 LOOK_want::NORMAL, false);
17274 else
17275 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17276 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17277 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17279 if (complain & tf_error)
17281 error ("dependent-name %qE is parsed as a non-type, but "
17282 "instantiation yields a type", qualified_id);
17283 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17285 return error_mark_node;
17289 if (DECL_P (expr))
17291 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17292 scope, complain))
17293 return error_mark_node;
17294 /* Remember that there was a reference to this entity. */
17295 if (!mark_used (expr, complain) && !(complain & tf_error))
17296 return error_mark_node;
17299 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17301 if (complain & tf_error)
17302 qualified_name_lookup_error (scope,
17303 TREE_OPERAND (qualified_id, 1),
17304 expr, input_location);
17305 return error_mark_node;
17308 if (is_template)
17310 /* We may be repeating a check already done during parsing, but
17311 if it was well-formed and passed then, it will pass again
17312 now, and if it didn't, we wouldn't have got here. The case
17313 we want to catch is when we couldn't tell then, and can now,
17314 namely when templ prior to substitution was an
17315 identifier. */
17316 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17317 return error_mark_node;
17319 if (variable_template_p (expr))
17320 expr = lookup_and_finish_template_variable (expr, template_args,
17321 complain);
17322 else
17323 expr = lookup_template_function (expr, template_args);
17326 if (expr == error_mark_node && complain & tf_error)
17327 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17328 expr, input_location);
17329 else if (TYPE_P (scope))
17331 expr = (adjust_result_of_qualified_name_lookup
17332 (expr, scope, current_nonlambda_class_type ()));
17333 expr = (finish_qualified_id_expr
17334 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17335 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17336 /*template_arg_p=*/false, complain));
17339 /* Expressions do not generally have reference type. */
17340 if (TREE_CODE (expr) != SCOPE_REF
17341 /* However, if we're about to form a pointer-to-member, we just
17342 want the referenced member referenced. */
17343 && TREE_CODE (expr) != OFFSET_REF)
17344 expr = convert_from_reference (expr);
17346 if (REF_PARENTHESIZED_P (qualified_id))
17347 expr = force_paren_expr (expr);
17349 expr = maybe_wrap_with_location (expr, loc);
17351 return expr;
17354 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17355 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17356 for tsubst. */
17358 static tree
17359 tsubst_init (tree init, tree decl, tree args,
17360 tsubst_flags_t complain, tree in_decl)
17362 if (!init)
17363 return NULL_TREE;
17365 init = tsubst_expr (init, args, complain, in_decl);
17367 tree type = TREE_TYPE (decl);
17369 if (!init && type != error_mark_node)
17371 if (tree auto_node = type_uses_auto (type))
17373 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17375 if (complain & tf_error)
17376 error ("initializer for %q#D expands to an empty list "
17377 "of expressions", decl);
17378 return error_mark_node;
17381 else if (!dependent_type_p (type))
17383 /* If we had an initializer but it
17384 instantiated to nothing,
17385 value-initialize the object. This will
17386 only occur when the initializer was a
17387 pack expansion where the parameter packs
17388 used in that expansion were of length
17389 zero. */
17390 init = build_value_init (type, complain);
17391 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17392 init = get_target_expr (init, complain);
17393 if (TREE_CODE (init) == TARGET_EXPR)
17394 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17398 return init;
17401 /* If T is a reference to a dependent member of the current instantiation C and
17402 we are trying to refer to that member in a partial instantiation of C,
17403 return a SCOPE_REF; otherwise, return NULL_TREE.
17405 This can happen when forming a C++17 deduction guide, as in PR96199. */
17407 static tree
17408 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17409 tree in_decl)
17411 if (!(complain & tf_dguide))
17412 return NULL_TREE;
17414 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17415 if (!decl || !DECL_P (decl))
17416 return NULL_TREE;
17418 tree ctx = context_for_name_lookup (decl);
17419 if (!CLASS_TYPE_P (ctx))
17420 return NULL_TREE;
17422 ctx = tsubst (ctx, args, complain, in_decl);
17423 if (!dependent_scope_p (ctx))
17424 return NULL_TREE;
17426 if (TYPE_P (t))
17428 if (typedef_variant_p (t))
17429 t = strip_typedefs (t);
17430 tree decl = TYPE_NAME (t);
17431 if (decl)
17432 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17433 if (!decl)
17434 return NULL_TREE;
17435 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17436 complain);
17439 tree name = DECL_NAME (t);
17440 tree fullname = name;
17441 if (instantiates_primary_template_p (t))
17443 tree tinfo = get_template_info (t);
17444 name = DECL_NAME (TI_TEMPLATE (tinfo));
17445 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17446 targs = tsubst_template_args (targs, args, complain, in_decl);
17447 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17450 if (TREE_CODE (t) == TYPE_DECL)
17452 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17453 && TYPE_NAME (TREE_TYPE (t)) == t)
17454 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17455 scope, but it doesn't need to be rewritten again. */
17456 return NULL_TREE;
17457 tree type = build_typename_type (ctx, name, fullname, typename_type);
17458 return TYPE_NAME (type);
17460 else if (DECL_TYPE_TEMPLATE_P (t))
17461 return make_unbound_class_template (ctx, name,
17462 NULL_TREE, complain);
17463 else
17464 return build_qualified_name (NULL_TREE, ctx, fullname,
17465 TREE_CODE (t) == TEMPLATE_DECL);
17468 /* Helper function for tsubst_omp_clauses, used for instantiation of
17469 OMP_CLAUSE_DECL of clauses. */
17471 static tree
17472 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17473 tree in_decl, tree *iterator_cache)
17475 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17476 return decl;
17478 /* Handle OpenMP iterators. */
17479 if (TREE_CODE (decl) == TREE_LIST
17480 && TREE_PURPOSE (decl)
17481 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17483 tree ret;
17484 if (iterator_cache[0] == TREE_PURPOSE (decl))
17485 ret = iterator_cache[1];
17486 else
17488 tree *tp = &ret;
17489 begin_scope (sk_omp, NULL);
17490 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17492 *tp = copy_node (it);
17493 TREE_VEC_ELT (*tp, 0)
17494 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17495 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17496 pushdecl (TREE_VEC_ELT (*tp, 0));
17497 TREE_VEC_ELT (*tp, 1)
17498 = tsubst_stmt (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17499 TREE_VEC_ELT (*tp, 2)
17500 = tsubst_stmt (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17501 TREE_VEC_ELT (*tp, 3)
17502 = tsubst_stmt (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17503 TREE_CHAIN (*tp) = NULL_TREE;
17504 tp = &TREE_CHAIN (*tp);
17506 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17507 iterator_cache[0] = TREE_PURPOSE (decl);
17508 iterator_cache[1] = ret;
17510 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17511 args, complain,
17512 in_decl, NULL));
17515 /* Handle an OpenMP array section represented as a TREE_LIST (or
17516 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17517 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17518 TREE_LIST. We can handle it exactly the same as an array section
17519 (purpose, value, and a chain), even though the nomenclature
17520 (low_bound, length, etc) is different. */
17521 if (TREE_CODE (decl) == TREE_LIST)
17523 tree low_bound
17524 = tsubst_stmt (TREE_PURPOSE (decl), args, complain, in_decl);
17525 tree length = tsubst_stmt (TREE_VALUE (decl), args, complain, in_decl);
17526 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17527 in_decl, NULL);
17528 if (TREE_PURPOSE (decl) == low_bound
17529 && TREE_VALUE (decl) == length
17530 && TREE_CHAIN (decl) == chain)
17531 return decl;
17532 tree ret = tree_cons (low_bound, length, chain);
17533 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17534 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17535 return ret;
17537 else if (TREE_CODE (decl) == OMP_ARRAY_SECTION)
17539 tree low_bound
17540 = tsubst_stmt (TREE_OPERAND (decl, 1), args, complain, in_decl);
17541 tree length = tsubst_stmt (TREE_OPERAND (decl, 2), args, complain,
17542 in_decl);
17543 tree base = tsubst_omp_clause_decl (TREE_OPERAND (decl, 0), args,
17544 complain, in_decl, NULL);
17545 if (TREE_OPERAND (decl, 0) == base
17546 && TREE_OPERAND (decl, 1) == low_bound
17547 && TREE_OPERAND (decl, 2) == length)
17548 return decl;
17549 return build3 (OMP_ARRAY_SECTION, TREE_TYPE (base), base, low_bound,
17550 length);
17552 tree ret = tsubst_stmt (decl, args, complain, in_decl);
17553 /* Undo convert_from_reference tsubst_expr could have called. */
17554 if (decl
17555 && REFERENCE_REF_P (ret)
17556 && !REFERENCE_REF_P (decl))
17557 ret = TREE_OPERAND (ret, 0);
17558 return ret;
17561 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17563 static tree
17564 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17565 tree args, tsubst_flags_t complain, tree in_decl)
17567 tree new_clauses = NULL_TREE, nc, oc;
17568 tree linear_no_step = NULL_TREE;
17569 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17571 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17573 nc = copy_node (oc);
17574 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17575 new_clauses = nc;
17577 switch (OMP_CLAUSE_CODE (nc))
17579 case OMP_CLAUSE_LASTPRIVATE:
17580 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17582 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17583 tsubst_stmt (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
17584 complain, in_decl);
17585 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17586 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17588 /* FALLTHRU */
17589 case OMP_CLAUSE_PRIVATE:
17590 case OMP_CLAUSE_SHARED:
17591 case OMP_CLAUSE_FIRSTPRIVATE:
17592 case OMP_CLAUSE_COPYIN:
17593 case OMP_CLAUSE_COPYPRIVATE:
17594 case OMP_CLAUSE_UNIFORM:
17595 case OMP_CLAUSE_DEPEND:
17596 case OMP_CLAUSE_DOACROSS:
17597 case OMP_CLAUSE_AFFINITY:
17598 case OMP_CLAUSE_FROM:
17599 case OMP_CLAUSE_TO:
17600 case OMP_CLAUSE_MAP:
17601 case OMP_CLAUSE__CACHE_:
17602 case OMP_CLAUSE_NONTEMPORAL:
17603 case OMP_CLAUSE_USE_DEVICE_PTR:
17604 case OMP_CLAUSE_USE_DEVICE_ADDR:
17605 case OMP_CLAUSE_IS_DEVICE_PTR:
17606 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17607 case OMP_CLAUSE_INCLUSIVE:
17608 case OMP_CLAUSE_EXCLUSIVE:
17609 OMP_CLAUSE_DECL (nc)
17610 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17611 in_decl, iterator_cache);
17612 break;
17613 case OMP_CLAUSE_NUM_TEAMS:
17614 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17615 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17616 = tsubst_stmt (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17617 complain, in_decl);
17618 /* FALLTHRU */
17619 case OMP_CLAUSE_TILE:
17620 case OMP_CLAUSE_IF:
17621 case OMP_CLAUSE_SELF:
17622 case OMP_CLAUSE_NUM_THREADS:
17623 case OMP_CLAUSE_SCHEDULE:
17624 case OMP_CLAUSE_COLLAPSE:
17625 case OMP_CLAUSE_FINAL:
17626 case OMP_CLAUSE_DEVICE:
17627 case OMP_CLAUSE_DIST_SCHEDULE:
17628 case OMP_CLAUSE_THREAD_LIMIT:
17629 case OMP_CLAUSE_SAFELEN:
17630 case OMP_CLAUSE_SIMDLEN:
17631 case OMP_CLAUSE_NUM_TASKS:
17632 case OMP_CLAUSE_GRAINSIZE:
17633 case OMP_CLAUSE_PRIORITY:
17634 case OMP_CLAUSE_ORDERED:
17635 case OMP_CLAUSE_HINT:
17636 case OMP_CLAUSE_FILTER:
17637 case OMP_CLAUSE_NUM_GANGS:
17638 case OMP_CLAUSE_NUM_WORKERS:
17639 case OMP_CLAUSE_VECTOR_LENGTH:
17640 case OMP_CLAUSE_WORKER:
17641 case OMP_CLAUSE_VECTOR:
17642 case OMP_CLAUSE_ASYNC:
17643 case OMP_CLAUSE_WAIT:
17644 case OMP_CLAUSE_DETACH:
17645 OMP_CLAUSE_OPERAND (nc, 0)
17646 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
17647 break;
17648 case OMP_CLAUSE_REDUCTION:
17649 case OMP_CLAUSE_IN_REDUCTION:
17650 case OMP_CLAUSE_TASK_REDUCTION:
17651 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17653 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17654 if (TREE_CODE (placeholder) == SCOPE_REF)
17656 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17657 complain, in_decl);
17658 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17659 = build_qualified_name (NULL_TREE, scope,
17660 TREE_OPERAND (placeholder, 1),
17661 false);
17663 else
17664 gcc_assert (identifier_p (placeholder));
17666 OMP_CLAUSE_DECL (nc)
17667 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17668 in_decl, NULL);
17669 break;
17670 case OMP_CLAUSE_GANG:
17671 case OMP_CLAUSE_ALIGNED:
17672 OMP_CLAUSE_DECL (nc)
17673 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17674 in_decl, NULL);
17675 OMP_CLAUSE_OPERAND (nc, 1)
17676 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17677 break;
17678 case OMP_CLAUSE_ALLOCATE:
17679 OMP_CLAUSE_DECL (nc)
17680 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17681 in_decl, NULL);
17682 OMP_CLAUSE_OPERAND (nc, 1)
17683 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17684 OMP_CLAUSE_OPERAND (nc, 2)
17685 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
17686 break;
17687 case OMP_CLAUSE_LINEAR:
17688 OMP_CLAUSE_DECL (nc)
17689 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17690 in_decl, NULL);
17691 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17693 gcc_assert (!linear_no_step);
17694 linear_no_step = nc;
17696 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17697 OMP_CLAUSE_LINEAR_STEP (nc)
17698 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17699 complain, in_decl, NULL);
17700 else
17701 OMP_CLAUSE_LINEAR_STEP (nc)
17702 = tsubst_stmt (OMP_CLAUSE_LINEAR_STEP (oc), args,
17703 complain, in_decl);
17704 break;
17705 case OMP_CLAUSE_NOWAIT:
17706 case OMP_CLAUSE_DEFAULT:
17707 case OMP_CLAUSE_UNTIED:
17708 case OMP_CLAUSE_MERGEABLE:
17709 case OMP_CLAUSE_INBRANCH:
17710 case OMP_CLAUSE_NOTINBRANCH:
17711 case OMP_CLAUSE_PROC_BIND:
17712 case OMP_CLAUSE_FOR:
17713 case OMP_CLAUSE_PARALLEL:
17714 case OMP_CLAUSE_SECTIONS:
17715 case OMP_CLAUSE_TASKGROUP:
17716 case OMP_CLAUSE_NOGROUP:
17717 case OMP_CLAUSE_THREADS:
17718 case OMP_CLAUSE_SIMD:
17719 case OMP_CLAUSE_DEFAULTMAP:
17720 case OMP_CLAUSE_ORDER:
17721 case OMP_CLAUSE_BIND:
17722 case OMP_CLAUSE_INDEPENDENT:
17723 case OMP_CLAUSE_AUTO:
17724 case OMP_CLAUSE_SEQ:
17725 case OMP_CLAUSE_IF_PRESENT:
17726 case OMP_CLAUSE_FINALIZE:
17727 case OMP_CLAUSE_NOHOST:
17728 break;
17729 default:
17730 gcc_unreachable ();
17732 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17733 switch (OMP_CLAUSE_CODE (nc))
17735 case OMP_CLAUSE_SHARED:
17736 case OMP_CLAUSE_PRIVATE:
17737 case OMP_CLAUSE_FIRSTPRIVATE:
17738 case OMP_CLAUSE_LASTPRIVATE:
17739 case OMP_CLAUSE_COPYPRIVATE:
17740 case OMP_CLAUSE_LINEAR:
17741 case OMP_CLAUSE_REDUCTION:
17742 case OMP_CLAUSE_IN_REDUCTION:
17743 case OMP_CLAUSE_TASK_REDUCTION:
17744 case OMP_CLAUSE_USE_DEVICE_PTR:
17745 case OMP_CLAUSE_USE_DEVICE_ADDR:
17746 case OMP_CLAUSE_IS_DEVICE_PTR:
17747 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17748 case OMP_CLAUSE_INCLUSIVE:
17749 case OMP_CLAUSE_EXCLUSIVE:
17750 case OMP_CLAUSE_ALLOCATE:
17751 /* tsubst_expr on SCOPE_REF results in returning
17752 finish_non_static_data_member result. Undo that here. */
17753 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17754 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17755 == IDENTIFIER_NODE))
17757 tree t = OMP_CLAUSE_DECL (nc);
17758 tree v = t;
17759 while (v)
17760 switch (TREE_CODE (v))
17762 case COMPONENT_REF:
17763 case MEM_REF:
17764 case INDIRECT_REF:
17765 CASE_CONVERT:
17766 case POINTER_PLUS_EXPR:
17767 v = TREE_OPERAND (v, 0);
17768 continue;
17769 case PARM_DECL:
17770 if (DECL_CONTEXT (v) == current_function_decl
17771 && DECL_ARTIFICIAL (v)
17772 && DECL_NAME (v) == this_identifier)
17773 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17774 /* FALLTHRU */
17775 default:
17776 v = NULL_TREE;
17777 break;
17780 else if (VAR_P (OMP_CLAUSE_DECL (oc))
17781 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17782 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17783 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17784 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17786 tree decl = OMP_CLAUSE_DECL (nc);
17787 if (VAR_P (decl))
17789 retrofit_lang_decl (decl);
17790 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17793 break;
17794 default:
17795 break;
17799 new_clauses = nreverse (new_clauses);
17800 if (ort != C_ORT_OMP_DECLARE_SIMD)
17802 new_clauses = finish_omp_clauses (new_clauses, ort);
17803 if (linear_no_step)
17804 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17805 if (nc == linear_no_step)
17807 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17808 break;
17811 return new_clauses;
17814 /* Like tsubst_expr, but unshare TREE_LIST nodes. */
17816 static tree
17817 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17818 tree in_decl)
17820 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17822 tree purpose, value, chain;
17824 if (t == NULL)
17825 return t;
17827 if (TREE_CODE (t) != TREE_LIST)
17828 return tsubst_expr (t, args, complain, in_decl);
17830 if (t == void_list_node)
17831 return t;
17833 purpose = TREE_PURPOSE (t);
17834 if (purpose)
17835 purpose = RECUR (purpose);
17836 value = TREE_VALUE (t);
17837 if (value)
17839 if (TREE_CODE (value) != LABEL_DECL)
17840 value = RECUR (value);
17841 else
17843 value = lookup_label (DECL_NAME (value));
17844 gcc_assert (TREE_CODE (value) == LABEL_DECL);
17845 TREE_USED (value) = 1;
17848 chain = TREE_CHAIN (t);
17849 if (chain && chain != void_type_node)
17850 chain = RECUR (chain);
17851 return tree_cons (purpose, value, chain);
17852 #undef RECUR
17855 /* Used to temporarily communicate the list of #pragma omp parallel
17856 clauses to #pragma omp for instantiation if they are combined
17857 together. */
17859 static tree *omp_parallel_combined_clauses;
17861 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17862 cp_decomp *);
17864 /* Substitute one OMP_FOR iterator. */
17866 static bool
17867 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17868 tree initv, tree condv, tree incrv, tree *clauses,
17869 tree args, tsubst_flags_t complain, tree in_decl)
17871 #define RECUR(NODE) \
17872 tsubst_stmt ((NODE), args, complain, in_decl)
17873 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17874 bool ret = false;
17876 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17877 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17879 decl = TREE_OPERAND (init, 0);
17880 init = TREE_OPERAND (init, 1);
17881 tree decl_expr = NULL_TREE;
17882 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17883 if (range_for)
17885 bool decomp = false;
17886 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17888 tree v = DECL_VALUE_EXPR (decl);
17889 if (TREE_CODE (v) == ARRAY_REF
17890 && VAR_P (TREE_OPERAND (v, 0))
17891 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17893 cp_decomp decomp_d = { NULL_TREE, 0 };
17894 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17895 maybe_push_decl (d);
17896 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17897 in_decl, &decomp_d);
17898 decomp = true;
17899 if (d == error_mark_node)
17900 decl = error_mark_node;
17901 else
17902 for (unsigned int i = 0; i < decomp_d.count; i++)
17904 if (!DECL_HAS_VALUE_EXPR_P (decomp_d.decl))
17906 tree v = build_nt (ARRAY_REF, d,
17907 size_int (decomp_d.count - i - 1),
17908 NULL_TREE, NULL_TREE);
17909 SET_DECL_VALUE_EXPR (decomp_d.decl, v);
17910 DECL_HAS_VALUE_EXPR_P (decomp_d.decl) = 1;
17912 fit_decomposition_lang_decl (decomp_d.decl, d);
17913 decomp_d.decl = DECL_CHAIN (decomp_d.decl);
17917 decl = tsubst_decl (decl, args, complain);
17918 if (!decomp)
17919 maybe_push_decl (decl);
17921 else if (init && TREE_CODE (init) == DECL_EXPR)
17923 /* We need to jump through some hoops to handle declarations in the
17924 init-statement, since we might need to handle auto deduction,
17925 but we need to keep control of initialization. */
17926 decl_expr = init;
17927 init = DECL_INITIAL (DECL_EXPR_DECL (init));
17928 decl = tsubst_decl (decl, args, complain);
17930 else
17932 if (TREE_CODE (decl) == SCOPE_REF)
17934 decl = RECUR (decl);
17935 if (TREE_CODE (decl) == COMPONENT_REF)
17937 tree v = decl;
17938 while (v)
17939 switch (TREE_CODE (v))
17941 case COMPONENT_REF:
17942 case MEM_REF:
17943 case INDIRECT_REF:
17944 CASE_CONVERT:
17945 case POINTER_PLUS_EXPR:
17946 v = TREE_OPERAND (v, 0);
17947 continue;
17948 case PARM_DECL:
17949 if (DECL_CONTEXT (v) == current_function_decl
17950 && DECL_ARTIFICIAL (v)
17951 && DECL_NAME (v) == this_identifier)
17953 decl = TREE_OPERAND (decl, 1);
17954 decl = omp_privatize_field (decl, false);
17956 /* FALLTHRU */
17957 default:
17958 v = NULL_TREE;
17959 break;
17963 else
17964 decl = RECUR (decl);
17966 if (init && TREE_CODE (init) == TREE_VEC)
17968 init = copy_node (init);
17969 TREE_VEC_ELT (init, 0)
17970 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17971 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17972 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17974 else
17975 init = RECUR (init);
17977 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17979 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17980 if (TREE_CODE (o) == TREE_LIST)
17981 TREE_VEC_ELT (orig_declv, i)
17982 = tree_cons (RECUR (TREE_PURPOSE (o)),
17983 RECUR (TREE_VALUE (o)),
17984 NULL_TREE);
17985 else
17986 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17989 if (range_for)
17991 tree this_pre_body = NULL_TREE;
17992 tree orig_init = NULL_TREE;
17993 tree orig_decl = NULL_TREE;
17994 tree init_sl = NULL_TREE;
17995 cp_convert_omp_range_for (this_pre_body, init_sl, decl, orig_decl, init,
17996 orig_init, cond, incr);
17997 if (orig_decl)
17999 if (orig_declv == NULL_TREE)
18000 orig_declv = copy_node (declv);
18001 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18002 ret = true;
18004 else if (orig_declv)
18005 TREE_VEC_ELT (orig_declv, i) = decl;
18008 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18009 if (!range_for && auto_node && init)
18010 TREE_TYPE (decl)
18011 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18013 gcc_assert (!type_dependent_expression_p (decl));
18015 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18017 if (decl_expr)
18019 /* Declare the variable, but don't let that initialize it. */
18020 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18021 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18022 RECUR (decl_expr);
18023 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18026 if (!range_for)
18028 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18029 if (COMPARISON_CLASS_P (cond)
18030 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18032 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18033 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18034 TREE_VEC_ELT (rhs, 0)
18035 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18036 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18037 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18038 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18039 lhs, rhs);
18041 else
18042 cond = RECUR (cond);
18043 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18044 if (TREE_CODE (incr) == MODIFY_EXPR)
18046 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18047 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18048 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18049 NOP_EXPR, rhs, NULL_TREE, complain);
18051 else
18052 incr = RECUR (incr);
18053 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18054 TREE_VEC_ELT (orig_declv, i) = decl;
18056 TREE_VEC_ELT (declv, i) = decl;
18057 TREE_VEC_ELT (initv, i) = init;
18058 TREE_VEC_ELT (condv, i) = cond;
18059 TREE_VEC_ELT (incrv, i) = incr;
18060 return ret;
18063 if (decl_expr)
18065 /* Declare and initialize the variable. */
18066 RECUR (decl_expr);
18067 init = NULL_TREE;
18069 else if (init)
18071 tree *pc;
18072 int j;
18073 for (j = ((omp_parallel_combined_clauses == NULL
18074 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18076 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18078 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18079 && OMP_CLAUSE_DECL (*pc) == decl)
18080 break;
18081 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18082 && OMP_CLAUSE_DECL (*pc) == decl)
18084 if (j)
18085 break;
18086 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18087 tree c = *pc;
18088 *pc = OMP_CLAUSE_CHAIN (c);
18089 OMP_CLAUSE_CHAIN (c) = *clauses;
18090 *clauses = c;
18092 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18093 && OMP_CLAUSE_DECL (*pc) == decl)
18095 error ("iteration variable %qD should not be firstprivate",
18096 decl);
18097 *pc = OMP_CLAUSE_CHAIN (*pc);
18099 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18100 && OMP_CLAUSE_DECL (*pc) == decl)
18102 error ("iteration variable %qD should not be reduction",
18103 decl);
18104 *pc = OMP_CLAUSE_CHAIN (*pc);
18106 else
18107 pc = &OMP_CLAUSE_CHAIN (*pc);
18109 if (*pc)
18110 break;
18112 if (*pc == NULL_TREE)
18114 tree c = build_omp_clause (input_location,
18115 TREE_CODE (t) == OMP_LOOP
18116 ? OMP_CLAUSE_LASTPRIVATE
18117 : OMP_CLAUSE_PRIVATE);
18118 OMP_CLAUSE_DECL (c) = decl;
18119 c = finish_omp_clauses (c, C_ORT_OMP);
18120 if (c)
18122 OMP_CLAUSE_CHAIN (c) = *clauses;
18123 *clauses = c;
18127 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18128 if (COMPARISON_CLASS_P (cond))
18130 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18131 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18132 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18134 else
18135 cond = RECUR (cond);
18136 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18137 switch (TREE_CODE (incr))
18139 case PREINCREMENT_EXPR:
18140 case PREDECREMENT_EXPR:
18141 case POSTINCREMENT_EXPR:
18142 case POSTDECREMENT_EXPR:
18143 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18144 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18145 break;
18146 case MODIFY_EXPR:
18147 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18148 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18150 tree rhs = TREE_OPERAND (incr, 1);
18151 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18152 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18153 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18154 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18155 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18156 rhs0, rhs1));
18158 else
18159 incr = RECUR (incr);
18160 break;
18161 case MODOP_EXPR:
18162 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18163 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18165 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18166 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18167 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18168 TREE_TYPE (decl), lhs,
18169 RECUR (TREE_OPERAND (incr, 2))));
18171 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18172 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18173 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18175 tree rhs = TREE_OPERAND (incr, 2);
18176 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18177 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18178 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18179 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18180 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18181 rhs0, rhs1));
18183 else
18184 incr = RECUR (incr);
18185 break;
18186 default:
18187 incr = RECUR (incr);
18188 break;
18191 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18192 TREE_VEC_ELT (orig_declv, i) = decl;
18193 TREE_VEC_ELT (declv, i) = decl;
18194 TREE_VEC_ELT (initv, i) = init;
18195 TREE_VEC_ELT (condv, i) = cond;
18196 TREE_VEC_ELT (incrv, i) = incr;
18197 return false;
18198 #undef RECUR
18201 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18202 of OMP_TARGET's body. */
18204 static tree
18205 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18207 *walk_subtrees = 0;
18208 switch (TREE_CODE (*tp))
18210 case OMP_TEAMS:
18211 return *tp;
18212 case BIND_EXPR:
18213 case STATEMENT_LIST:
18214 *walk_subtrees = 1;
18215 break;
18216 default:
18217 break;
18219 return NULL_TREE;
18222 /* Helper function for tsubst_expr. For decomposition declaration
18223 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18224 also the corresponding decls representing the identifiers
18225 of the decomposition declaration. Return DECL if successful
18226 or error_mark_node otherwise, set *FIRST to the first decl
18227 in the list chained through DECL_CHAIN and *CNT to the number
18228 of such decls. */
18230 static tree
18231 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18232 tsubst_flags_t complain, tree in_decl, cp_decomp *decomp)
18234 tree decl2, decl3, prev = decl;
18235 decomp->count = 0;
18236 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18237 for (decl2 = DECL_CHAIN (pattern_decl);
18238 decl2
18239 && VAR_P (decl2)
18240 && DECL_DECOMPOSITION_P (decl2)
18241 && DECL_NAME (decl2);
18242 decl2 = DECL_CHAIN (decl2))
18244 if (TREE_TYPE (decl2) == error_mark_node && decomp->count == 0)
18246 gcc_assert (errorcount);
18247 return error_mark_node;
18249 decomp->count++;
18250 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18251 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18252 tree v = DECL_VALUE_EXPR (decl2);
18253 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18254 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18255 decl3 = tsubst (decl2, args, complain, in_decl);
18256 SET_DECL_VALUE_EXPR (decl2, v);
18257 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18258 if (VAR_P (decl3))
18259 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18260 else
18262 gcc_assert (errorcount);
18263 decl = error_mark_node;
18264 continue;
18266 maybe_push_decl (decl3);
18267 if (error_operand_p (decl3))
18268 decl = error_mark_node;
18269 else if (decl != error_mark_node
18270 && DECL_CHAIN (decl3) != prev
18271 && decl != prev)
18273 gcc_assert (errorcount);
18274 decl = error_mark_node;
18276 else
18277 prev = decl3;
18279 decomp->decl = prev;
18280 return decl;
18283 /* Return the proper local_specialization for init-capture pack DECL. */
18285 static tree
18286 lookup_init_capture_pack (tree decl)
18288 /* We handle normal pack captures by forwarding to the specialization of the
18289 captured parameter. We can't do that for pack init-captures; we need them
18290 to have their own local_specialization. We created the individual
18291 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18292 when we process the DECL_EXPR for the pack init-capture in the template.
18293 So, how do we find them? We don't know the capture proxy pack when
18294 building the individual resulting proxies, and we don't know the
18295 individual proxies when instantiating the pack. What we have in common is
18296 the FIELD_DECL.
18298 So...when we instantiate the FIELD_DECL, we stick the result in
18299 local_specializations. Then at the DECL_EXPR we look up that result, see
18300 how many elements it has, synthesize the names, and look them up. */
18302 tree cname = DECL_NAME (decl);
18303 tree val = DECL_VALUE_EXPR (decl);
18304 tree field = TREE_OPERAND (val, 1);
18305 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18306 tree fpack = retrieve_local_specialization (field);
18307 if (fpack == error_mark_node)
18308 return error_mark_node;
18310 int len = 1;
18311 tree vec = NULL_TREE;
18312 tree r = NULL_TREE;
18313 if (TREE_CODE (fpack) == TREE_VEC)
18315 len = TREE_VEC_LENGTH (fpack);
18316 vec = make_tree_vec (len);
18317 r = make_node (NONTYPE_ARGUMENT_PACK);
18318 ARGUMENT_PACK_ARGS (r) = vec;
18320 for (int i = 0; i < len; ++i)
18322 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18323 tree elt = lookup_name (ename);
18324 if (vec)
18325 TREE_VEC_ELT (vec, i) = elt;
18326 else
18327 r = elt;
18329 return r;
18332 /* T is an operand of a template tree being substituted. Return whether
18333 T is dependent such that we should suppress some warnings that would
18334 make sense if the substituted expression were written directly, like
18335 template <int I> bool f() { return I == 2; }
18336 We don't want to warn when instantiating f that comparing two constants
18337 always has the same value.
18339 This is a more limited concept of dependence than instantiation-dependent;
18340 here we don't care whether substitution could fail. */
18342 static bool
18343 dependent_operand_p (tree t)
18345 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18346 t = TREE_OPERAND (t, 0);
18347 ++processing_template_decl;
18348 bool r = (potential_constant_expression (t)
18349 ? value_dependent_expression_p (t)
18350 : type_dependent_expression_p (t));
18351 --processing_template_decl;
18352 return r;
18355 /* A superset of tsubst_expr that also handles statement trees. */
18357 static tree
18358 tsubst_stmt (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18360 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18361 #define RECUR(NODE) \
18362 tsubst_stmt ((NODE), args, complain, in_decl)
18364 tree stmt, tmp;
18365 tree r;
18366 location_t loc;
18368 if (t == NULL_TREE || t == error_mark_node)
18369 return t;
18371 loc = input_location;
18372 if (location_t eloc = cp_expr_location (t))
18373 input_location = eloc;
18374 if (STATEMENT_CODE_P (TREE_CODE (t)))
18375 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18377 switch (TREE_CODE (t))
18379 case STATEMENT_LIST:
18381 for (tree stmt : tsi_range (t))
18382 RECUR (stmt);
18383 break;
18386 case CTOR_INITIALIZER:
18387 finish_mem_initializers (tsubst_initializer_list
18388 (TREE_OPERAND (t, 0), args));
18389 break;
18391 case RETURN_EXPR:
18392 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18393 break;
18395 case CO_RETURN_EXPR:
18396 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18397 break;
18399 case EXPR_STMT:
18400 tmp = RECUR (EXPR_STMT_EXPR (t));
18401 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18402 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18403 else
18404 finish_expr_stmt (tmp);
18405 break;
18407 case USING_STMT:
18408 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18409 break;
18411 case PRECONDITION_STMT:
18412 case POSTCONDITION_STMT:
18413 gcc_unreachable ();
18415 case ASSERTION_STMT:
18417 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18418 if (r != error_mark_node)
18419 add_stmt (r);
18420 RETURN (r);
18422 break;
18424 case DECL_EXPR:
18426 tree decl, pattern_decl;
18427 tree init;
18429 pattern_decl = decl = DECL_EXPR_DECL (t);
18430 if (TREE_CODE (decl) == LABEL_DECL)
18431 finish_label_decl (DECL_NAME (decl));
18432 else if (TREE_CODE (decl) == USING_DECL)
18434 tree scope = USING_DECL_SCOPE (decl);
18435 if (DECL_DEPENDENT_P (decl))
18437 scope = tsubst (scope, args, complain, in_decl);
18438 if (!MAYBE_CLASS_TYPE_P (scope)
18439 && TREE_CODE (scope) != ENUMERAL_TYPE)
18441 if (complain & tf_error)
18442 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18443 "class, namespace, or enumeration", scope);
18444 return error_mark_node;
18446 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18448 else
18450 /* This is a non-dependent using-decl, and we'll have
18451 used the names it found during template parsing. We do
18452 not want to do the lookup again, because we might not
18453 find the things we found then. */
18454 gcc_checking_assert (scope == tsubst (scope, args,
18455 complain, in_decl));
18456 /* We still need to push the bindings so that we can look up
18457 this name later. */
18458 push_using_decl_bindings (DECL_NAME (decl),
18459 USING_DECL_DECLS (decl));
18462 else if (is_capture_proxy (decl)
18463 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18465 /* We're in tsubst_lambda_expr, we've already inserted a new
18466 capture proxy, so look it up and register it. */
18467 tree inst;
18468 if (!DECL_PACK_P (decl))
18470 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18471 LOOK_want::HIDDEN_LAMBDA);
18472 gcc_assert (inst != decl && is_capture_proxy (inst));
18474 else if (is_normal_capture_proxy (decl))
18476 inst = (retrieve_local_specialization
18477 (DECL_CAPTURED_VARIABLE (decl)));
18478 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18479 || DECL_PACK_P (inst));
18481 else
18482 inst = lookup_init_capture_pack (decl);
18484 register_local_specialization (inst, decl);
18485 break;
18487 else if (DECL_PRETTY_FUNCTION_P (decl))
18488 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18489 DECL_NAME (decl),
18490 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18491 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18492 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18493 /* Don't copy the old closure; we'll create a new one in
18494 tsubst_lambda_expr. */
18495 break;
18496 else
18498 init = DECL_INITIAL (decl);
18499 decl = tsubst (decl, args, complain, in_decl);
18500 if (decl != error_mark_node)
18502 /* By marking the declaration as instantiated, we avoid
18503 trying to instantiate it. Since instantiate_decl can't
18504 handle local variables, and since we've already done
18505 all that needs to be done, that's the right thing to
18506 do. */
18507 if (VAR_P (decl))
18508 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18509 if (VAR_P (decl) && !DECL_NAME (decl)
18510 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18511 /* Anonymous aggregates are a special case. */
18512 finish_anon_union (decl);
18513 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18515 DECL_CONTEXT (decl) = current_function_decl;
18516 if (DECL_NAME (decl) == this_identifier)
18518 tree lam = DECL_CONTEXT (current_function_decl);
18519 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18520 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18522 insert_capture_proxy (decl);
18524 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18525 /* We already did a pushtag. */;
18526 else if (VAR_OR_FUNCTION_DECL_P (decl)
18527 && DECL_LOCAL_DECL_P (decl))
18529 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18530 DECL_CONTEXT (decl) = NULL_TREE;
18531 decl = pushdecl (decl);
18532 if (TREE_CODE (decl) == FUNCTION_DECL
18533 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18534 && cp_check_omp_declare_reduction (decl))
18535 instantiate_body (pattern_decl, args, decl, true);
18537 else
18539 bool const_init = false;
18540 cp_decomp decomp_d, *decomp = NULL;
18541 tree ndecl = error_mark_node;
18542 tree asmspec_tree = NULL_TREE;
18543 maybe_push_decl (decl);
18545 if (VAR_P (decl)
18546 && DECL_LANG_SPECIFIC (decl)
18547 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18548 break;
18550 if (VAR_P (decl)
18551 && DECL_DECOMPOSITION_P (decl)
18552 && TREE_TYPE (pattern_decl) != error_mark_node)
18554 decomp = &decomp_d;
18555 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18556 complain, in_decl, decomp);
18559 init = tsubst_init (init, decl, args, complain, in_decl);
18561 if (VAR_P (decl))
18562 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18563 (pattern_decl));
18565 /* In a non-template function, VLA type declarations are
18566 handled in grokdeclarator; for templates, handle them
18567 now. */
18568 predeclare_vla (decl);
18570 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18572 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18573 const char *asmspec = IDENTIFIER_POINTER (id);
18574 gcc_assert (asmspec[0] == '*');
18575 asmspec_tree
18576 = build_string (IDENTIFIER_LENGTH (id) - 1,
18577 asmspec + 1);
18578 TREE_TYPE (asmspec_tree) = char_array_type_node;
18581 cp_finish_decl (decl, init, const_init, asmspec_tree, 0,
18582 decomp);
18584 if (ndecl != error_mark_node)
18585 cp_finish_decomp (ndecl, decomp);
18590 break;
18593 case FOR_STMT:
18594 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18595 RECUR (FOR_INIT_STMT (t));
18596 finish_init_stmt (stmt);
18597 tmp = RECUR (FOR_COND (t));
18598 finish_for_cond (tmp, stmt, false, 0, false);
18599 tmp = RECUR (FOR_EXPR (t));
18600 finish_for_expr (tmp, stmt);
18602 bool prev = note_iteration_stmt_body_start ();
18603 RECUR (FOR_BODY (t));
18604 note_iteration_stmt_body_end (prev);
18606 finish_for_stmt (stmt);
18607 break;
18609 case RANGE_FOR_STMT:
18611 /* Construct another range_for, if this is not a final
18612 substitution (for inside a generic lambda of a
18613 template). Otherwise convert to a regular for. */
18614 tree decl, expr;
18615 stmt = (processing_template_decl
18616 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18617 : begin_for_stmt (NULL_TREE, NULL_TREE));
18618 RECUR (RANGE_FOR_INIT_STMT (t));
18619 decl = RANGE_FOR_DECL (t);
18620 decl = tsubst (decl, args, complain, in_decl);
18621 maybe_push_decl (decl);
18622 expr = RECUR (RANGE_FOR_EXPR (t));
18624 cp_decomp decomp_d, *decomp = NULL;
18625 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18627 decomp = &decomp_d;
18628 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18629 complain, in_decl, decomp);
18632 tree unroll = RECUR (RANGE_FOR_UNROLL (t));
18633 if (unroll)
18634 unroll
18635 = cp_check_pragma_unroll (EXPR_LOCATION (RANGE_FOR_UNROLL (t)),
18636 unroll);
18637 if (processing_template_decl)
18639 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18640 RANGE_FOR_UNROLL (stmt) = unroll;
18641 RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
18642 finish_range_for_decl (stmt, decl, expr);
18643 if (decomp && decl != error_mark_node)
18644 cp_finish_decomp (decl, decomp);
18646 else
18647 stmt = cp_convert_range_for (stmt, decl, expr, decomp,
18648 RANGE_FOR_IVDEP (t), unroll,
18649 RANGE_FOR_NOVECTOR (t));
18651 bool prev = note_iteration_stmt_body_start ();
18652 RECUR (RANGE_FOR_BODY (t));
18653 note_iteration_stmt_body_end (prev);
18654 finish_for_stmt (stmt);
18656 break;
18658 case WHILE_STMT:
18659 stmt = begin_while_stmt ();
18660 tmp = RECUR (WHILE_COND (t));
18661 finish_while_stmt_cond (tmp, stmt, false, 0, false);
18663 bool prev = note_iteration_stmt_body_start ();
18664 RECUR (WHILE_BODY (t));
18665 note_iteration_stmt_body_end (prev);
18667 finish_while_stmt (stmt);
18668 break;
18670 case DO_STMT:
18671 stmt = begin_do_stmt ();
18673 bool prev = note_iteration_stmt_body_start ();
18674 RECUR (DO_BODY (t));
18675 note_iteration_stmt_body_end (prev);
18677 finish_do_body (stmt);
18678 tmp = RECUR (DO_COND (t));
18679 finish_do_stmt (tmp, stmt, false, 0, false);
18680 break;
18682 case IF_STMT:
18683 stmt = begin_if_stmt ();
18684 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18685 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18686 if (IF_STMT_CONSTEXPR_P (t))
18687 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18689 tree cond = IF_COND (t);
18690 bool was_dep = dependent_operand_p (cond);
18691 cond = RECUR (cond);
18692 warning_sentinel s1(warn_address, was_dep);
18693 tmp = finish_if_stmt_cond (cond, stmt);
18695 if (IF_STMT_CONSTEXPR_P (t)
18696 && instantiation_dependent_expression_p (tmp))
18698 /* We're partially instantiating a generic lambda, but the condition
18699 of the constexpr if is still dependent. Don't substitute into the
18700 branches now, just remember the template arguments. */
18701 do_poplevel (IF_SCOPE (stmt));
18702 IF_COND (stmt) = IF_COND (t);
18703 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18704 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18705 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18706 add_stmt (stmt);
18707 break;
18709 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18710 /* Don't instantiate the THEN_CLAUSE. */;
18711 else if (IF_STMT_CONSTEVAL_P (t))
18713 bool save_in_consteval_if_p = in_consteval_if_p;
18714 in_consteval_if_p = true;
18715 RECUR (THEN_CLAUSE (t));
18716 in_consteval_if_p = save_in_consteval_if_p;
18718 else
18720 tree folded = fold_non_dependent_expr (tmp, complain);
18721 bool inhibit = integer_zerop (folded);
18722 if (inhibit)
18723 ++c_inhibit_evaluation_warnings;
18724 RECUR (THEN_CLAUSE (t));
18725 if (inhibit)
18726 --c_inhibit_evaluation_warnings;
18728 finish_then_clause (stmt);
18730 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18731 /* Don't instantiate the ELSE_CLAUSE. */;
18732 else if (ELSE_CLAUSE (t))
18734 tree folded = fold_non_dependent_expr (tmp, complain);
18735 bool inhibit = integer_nonzerop (folded);
18736 begin_else_clause (stmt);
18737 if (inhibit)
18738 ++c_inhibit_evaluation_warnings;
18739 RECUR (ELSE_CLAUSE (t));
18740 if (inhibit)
18741 --c_inhibit_evaluation_warnings;
18742 finish_else_clause (stmt);
18745 finish_if_stmt (stmt);
18746 break;
18748 case BIND_EXPR:
18749 if (BIND_EXPR_BODY_BLOCK (t))
18750 stmt = begin_function_body ();
18751 else
18752 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18753 ? BCS_TRY_BLOCK : 0);
18755 RECUR (BIND_EXPR_BODY (t));
18757 if (BIND_EXPR_BODY_BLOCK (t))
18758 finish_function_body (stmt);
18759 else
18760 finish_compound_stmt (stmt);
18761 break;
18763 case BREAK_STMT:
18764 finish_break_stmt ();
18765 break;
18767 case CONTINUE_STMT:
18768 finish_continue_stmt ();
18769 break;
18771 case SWITCH_STMT:
18772 stmt = begin_switch_stmt ();
18773 tmp = RECUR (SWITCH_STMT_COND (t));
18774 finish_switch_cond (tmp, stmt);
18775 RECUR (SWITCH_STMT_BODY (t));
18776 finish_switch_stmt (stmt);
18777 break;
18779 case CASE_LABEL_EXPR:
18781 tree decl = CASE_LABEL (t);
18782 tree low = RECUR (CASE_LOW (t));
18783 tree high = RECUR (CASE_HIGH (t));
18784 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18785 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18787 tree label = CASE_LABEL (l);
18788 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18789 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18790 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18793 break;
18795 case LABEL_EXPR:
18797 tree decl = LABEL_EXPR_LABEL (t);
18798 tree label;
18800 label = finish_label_stmt (DECL_NAME (decl));
18801 if (TREE_CODE (label) == LABEL_DECL)
18802 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18803 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18804 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18806 break;
18808 case GOTO_EXPR:
18809 tmp = GOTO_DESTINATION (t);
18810 if (TREE_CODE (tmp) != LABEL_DECL)
18811 /* Computed goto's must be tsubst'd into. On the other hand,
18812 non-computed gotos must not be; the identifier in question
18813 will have no binding. */
18814 tmp = RECUR (tmp);
18815 else
18816 tmp = DECL_NAME (tmp);
18817 finish_goto_stmt (tmp);
18818 break;
18820 case ASM_EXPR:
18822 tree string = RECUR (ASM_STRING (t));
18823 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18824 complain, in_decl);
18825 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18826 complain, in_decl);
18827 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18828 complain, in_decl);
18829 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18830 complain, in_decl);
18831 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18832 outputs, inputs, clobbers, labels,
18833 ASM_INLINE_P (t));
18834 tree asm_expr = tmp;
18835 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18836 asm_expr = TREE_OPERAND (asm_expr, 0);
18837 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18839 break;
18841 case TRY_BLOCK:
18842 if (CLEANUP_P (t))
18844 stmt = begin_try_block ();
18845 RECUR (TRY_STMTS (t));
18846 finish_cleanup_try_block (stmt);
18847 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18849 else
18851 tree compound_stmt = NULL_TREE;
18853 if (FN_TRY_BLOCK_P (t))
18854 stmt = begin_function_try_block (&compound_stmt);
18855 else
18856 stmt = begin_try_block ();
18858 RECUR (TRY_STMTS (t));
18860 if (FN_TRY_BLOCK_P (t))
18861 finish_function_try_block (stmt);
18862 else
18863 finish_try_block (stmt);
18865 RECUR (TRY_HANDLERS (t));
18866 if (FN_TRY_BLOCK_P (t))
18867 finish_function_handler_sequence (stmt, compound_stmt);
18868 else
18869 finish_handler_sequence (stmt);
18871 break;
18873 case HANDLER:
18875 tree decl = HANDLER_PARMS (t);
18877 if (decl)
18879 decl = tsubst (decl, args, complain, in_decl);
18880 /* Prevent instantiate_decl from trying to instantiate
18881 this variable. We've already done all that needs to be
18882 done. */
18883 if (decl != error_mark_node)
18884 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18886 stmt = begin_handler ();
18887 finish_handler_parms (decl, stmt);
18888 RECUR (HANDLER_BODY (t));
18889 finish_handler (stmt);
18891 break;
18893 case TAG_DEFN:
18894 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18895 if (dependent_type_p (tmp))
18896 /* This is a partial instantiation, try again when full. */
18897 add_stmt (build_min (TAG_DEFN, tmp));
18898 else if (CLASS_TYPE_P (tmp))
18900 /* Local classes are not independent templates; they are
18901 instantiated along with their containing function. And this
18902 way we don't have to deal with pushing out of one local class
18903 to instantiate a member of another local class. */
18904 /* Closures are handled by the LAMBDA_EXPR. */
18905 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18906 complete_type (tmp);
18907 tree save_ccp = current_class_ptr;
18908 tree save_ccr = current_class_ref;
18909 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18910 if ((VAR_P (fld)
18911 || (TREE_CODE (fld) == FUNCTION_DECL
18912 && !DECL_ARTIFICIAL (fld)))
18913 && DECL_TEMPLATE_INSTANTIATION (fld))
18914 instantiate_decl (fld, /*defer_ok=*/false,
18915 /*expl_inst_class=*/false);
18916 else if (TREE_CODE (fld) == FIELD_DECL)
18917 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
18918 current_class_ptr = save_ccp;
18919 current_class_ref = save_ccr;
18921 break;
18923 case STATIC_ASSERT:
18925 tree condition, message;
18927 ++c_inhibit_evaluation_warnings;
18928 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
18929 complain, in_decl);
18930 message = tsubst_expr (STATIC_ASSERT_MESSAGE (t), args,
18931 complain, in_decl);
18932 if (TREE_CODE (STATIC_ASSERT_MESSAGE (t)) != STRING_CST
18933 && TREE_CODE (message) == STRING_CST)
18934 message = build1_loc (STATIC_ASSERT_SOURCE_LOCATION (t),
18935 PAREN_EXPR, TREE_TYPE (message), message);
18936 --c_inhibit_evaluation_warnings;
18938 finish_static_assert (condition, message,
18939 STATIC_ASSERT_SOURCE_LOCATION (t),
18940 /*member_p=*/false, /*show_expr_p=*/true);
18942 break;
18944 case OACC_KERNELS:
18945 case OACC_PARALLEL:
18946 case OACC_SERIAL:
18947 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC_TARGET, args,
18948 complain, in_decl);
18949 stmt = begin_omp_parallel ();
18950 RECUR (OMP_BODY (t));
18951 finish_omp_construct (TREE_CODE (t), stmt, tmp);
18952 break;
18954 case OMP_PARALLEL:
18955 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18956 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18957 complain, in_decl);
18958 if (OMP_PARALLEL_COMBINED (t))
18959 omp_parallel_combined_clauses = &tmp;
18960 stmt = begin_omp_parallel ();
18961 RECUR (OMP_PARALLEL_BODY (t));
18962 gcc_assert (omp_parallel_combined_clauses == NULL);
18963 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18964 = OMP_PARALLEL_COMBINED (t);
18965 pop_omp_privatization_clauses (r);
18966 break;
18968 case OMP_TASK:
18969 if (OMP_TASK_BODY (t) == NULL_TREE)
18971 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18972 complain, in_decl);
18973 t = copy_node (t);
18974 OMP_TASK_CLAUSES (t) = tmp;
18975 add_stmt (t);
18976 break;
18978 r = push_omp_privatization_clauses (false);
18979 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18980 complain, in_decl);
18981 stmt = begin_omp_task ();
18982 RECUR (OMP_TASK_BODY (t));
18983 finish_omp_task (tmp, stmt);
18984 pop_omp_privatization_clauses (r);
18985 break;
18987 case OMP_FOR:
18988 case OMP_LOOP:
18989 case OMP_SIMD:
18990 case OMP_DISTRIBUTE:
18991 case OMP_TASKLOOP:
18992 case OACC_LOOP:
18994 tree clauses, body, pre_body;
18995 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18996 tree orig_declv = NULL_TREE;
18997 tree incrv = NULL_TREE;
18998 enum c_omp_region_type ort = C_ORT_OMP;
18999 bool any_range_for = false;
19000 int i;
19002 if (TREE_CODE (t) == OACC_LOOP)
19003 ort = C_ORT_ACC;
19005 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19006 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19007 in_decl);
19008 if (OMP_FOR_INIT (t) != NULL_TREE)
19010 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19011 if (OMP_FOR_ORIG_DECLS (t))
19012 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19013 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19014 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19015 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19018 keep_next_level (true);
19019 stmt = begin_omp_structured_block ();
19021 pre_body = push_stmt_list ();
19022 RECUR (OMP_FOR_PRE_BODY (t));
19023 pre_body = pop_stmt_list (pre_body);
19025 if (OMP_FOR_INIT (t) != NULL_TREE)
19026 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19027 any_range_for
19028 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19029 condv, incrv, &clauses, args,
19030 complain, in_decl);
19031 omp_parallel_combined_clauses = NULL;
19033 if (any_range_for)
19035 gcc_assert (orig_declv);
19036 body = begin_omp_structured_block ();
19037 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19038 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19039 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19040 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19041 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19042 TREE_VEC_ELT (declv, i));
19044 else
19045 body = push_stmt_list ();
19046 RECUR (OMP_FOR_BODY (t));
19047 if (any_range_for)
19048 body = finish_omp_structured_block (body);
19049 else
19050 body = pop_stmt_list (body);
19052 if (OMP_FOR_INIT (t) != NULL_TREE)
19053 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19054 orig_declv, initv, condv, incrv, body, pre_body,
19055 NULL, clauses);
19056 else
19058 t = make_node (TREE_CODE (t));
19059 TREE_TYPE (t) = void_type_node;
19060 OMP_FOR_BODY (t) = body;
19061 OMP_FOR_PRE_BODY (t) = pre_body;
19062 OMP_FOR_CLAUSES (t) = clauses;
19063 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19064 add_stmt (t);
19067 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19068 t));
19069 pop_omp_privatization_clauses (r);
19071 break;
19073 case OMP_SECTIONS:
19074 case OMP_MASKED:
19075 omp_parallel_combined_clauses = NULL;
19076 /* FALLTHRU */
19077 case OMP_SINGLE:
19078 case OMP_SCOPE:
19079 case OMP_TEAMS:
19080 case OMP_CRITICAL:
19081 case OMP_TASKGROUP:
19082 case OMP_SCAN:
19083 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19084 && OMP_TEAMS_COMBINED (t));
19085 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19086 in_decl);
19087 if (TREE_CODE (t) == OMP_TEAMS)
19089 keep_next_level (true);
19090 stmt = begin_omp_structured_block ();
19091 RECUR (OMP_BODY (t));
19092 stmt = finish_omp_structured_block (stmt);
19094 else
19096 stmt = push_stmt_list ();
19097 RECUR (OMP_BODY (t));
19098 stmt = pop_stmt_list (stmt);
19101 if (TREE_CODE (t) == OMP_CRITICAL
19102 && tmp != NULL_TREE
19103 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19105 error_at (OMP_CLAUSE_LOCATION (tmp),
19106 "%<#pragma omp critical%> with %<hint%> clause requires "
19107 "a name, except when %<omp_sync_hint_none%> is used");
19108 RETURN (error_mark_node);
19110 t = copy_node (t);
19111 OMP_BODY (t) = stmt;
19112 OMP_CLAUSES (t) = tmp;
19113 add_stmt (t);
19114 pop_omp_privatization_clauses (r);
19115 break;
19117 case OMP_DEPOBJ:
19118 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19119 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19121 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19122 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19124 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19125 args, complain, in_decl);
19126 if (tmp == NULL_TREE)
19127 tmp = error_mark_node;
19129 else
19131 kind = (enum omp_clause_depend_kind)
19132 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19133 tmp = NULL_TREE;
19135 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19137 else
19138 finish_omp_depobj (EXPR_LOCATION (t), r,
19139 OMP_CLAUSE_DEPEND_INVALID,
19140 OMP_DEPOBJ_CLAUSES (t));
19141 break;
19143 case OACC_DATA:
19144 case OMP_TARGET_DATA:
19145 case OMP_TARGET:
19146 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19147 TREE_CODE (t) == OACC_DATA
19148 ? C_ORT_ACC
19149 : TREE_CODE (t) == OMP_TARGET
19150 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19151 args, complain, in_decl);
19152 keep_next_level (true);
19153 stmt = begin_omp_structured_block ();
19155 RECUR (OMP_BODY (t));
19156 stmt = finish_omp_structured_block (stmt);
19158 t = copy_node (t);
19159 OMP_BODY (t) = stmt;
19160 OMP_CLAUSES (t) = tmp;
19162 if (TREE_CODE (t) == OMP_TARGET)
19163 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19164 &OMP_CLAUSES (t));
19166 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19168 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19169 if (teams)
19170 /* For combined target teams, ensure the num_teams and
19171 thread_limit clause expressions are evaluated on the host,
19172 before entering the target construct. */
19173 for (tree c = OMP_TEAMS_CLAUSES (teams);
19174 c; c = OMP_CLAUSE_CHAIN (c))
19175 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19176 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19177 for (int i = 0;
19178 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19179 if (OMP_CLAUSE_OPERAND (c, i)
19180 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19182 tree expr = OMP_CLAUSE_OPERAND (c, i);
19183 expr = force_target_expr (TREE_TYPE (expr), expr,
19184 tf_none);
19185 if (expr == error_mark_node)
19186 continue;
19187 tmp = TARGET_EXPR_SLOT (expr);
19188 add_stmt (expr);
19189 OMP_CLAUSE_OPERAND (c, i) = expr;
19190 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19191 OMP_CLAUSE_FIRSTPRIVATE);
19192 OMP_CLAUSE_DECL (tc) = tmp;
19193 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19194 OMP_TARGET_CLAUSES (t) = tc;
19197 add_stmt (t);
19198 break;
19200 case OACC_DECLARE:
19201 t = copy_node (t);
19202 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19203 complain, in_decl);
19204 OACC_DECLARE_CLAUSES (t) = tmp;
19205 add_stmt (t);
19206 break;
19208 case OMP_TARGET_UPDATE:
19209 case OMP_TARGET_ENTER_DATA:
19210 case OMP_TARGET_EXIT_DATA:
19211 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19212 complain, in_decl);
19213 t = copy_node (t);
19214 OMP_STANDALONE_CLAUSES (t) = tmp;
19215 add_stmt (t);
19216 break;
19218 case OACC_CACHE:
19219 case OACC_ENTER_DATA:
19220 case OACC_EXIT_DATA:
19221 case OACC_UPDATE:
19222 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19223 complain, in_decl);
19224 t = copy_node (t);
19225 OMP_STANDALONE_CLAUSES (t) = tmp;
19226 add_stmt (t);
19227 break;
19229 case OMP_ORDERED:
19230 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19231 complain, in_decl);
19232 if (OMP_BODY (t))
19234 stmt = push_stmt_list ();
19235 RECUR (OMP_BODY (t));
19236 stmt = pop_stmt_list (stmt);
19238 else
19239 stmt = NULL_TREE;
19241 t = copy_node (t);
19242 OMP_BODY (t) = stmt;
19243 OMP_ORDERED_CLAUSES (t) = tmp;
19244 add_stmt (t);
19245 break;
19247 case OMP_MASTER:
19248 case OMP_STRUCTURED_BLOCK:
19249 omp_parallel_combined_clauses = NULL;
19250 /* FALLTHRU */
19251 case OMP_SECTION:
19252 stmt = push_stmt_list ();
19253 RECUR (OMP_BODY (t));
19254 stmt = pop_stmt_list (stmt);
19256 t = copy_node (t);
19257 OMP_BODY (t) = stmt;
19258 add_stmt (t);
19259 break;
19261 case OMP_ATOMIC:
19262 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19263 tmp = NULL_TREE;
19264 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19265 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19266 complain, in_decl);
19267 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19269 tree op1 = TREE_OPERAND (t, 1);
19270 tree rhs1 = NULL_TREE;
19271 tree r = NULL_TREE;
19272 tree lhs, rhs;
19273 if (TREE_CODE (op1) == COMPOUND_EXPR)
19275 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19276 op1 = TREE_OPERAND (op1, 1);
19278 if (TREE_CODE (op1) == COND_EXPR)
19280 gcc_assert (rhs1 == NULL_TREE);
19281 tree c = TREE_OPERAND (op1, 0);
19282 if (TREE_CODE (c) == MODIFY_EXPR)
19284 r = RECUR (TREE_OPERAND (c, 0));
19285 c = TREE_OPERAND (c, 1);
19287 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19288 rhs = RECUR (TREE_OPERAND (c, 1));
19289 lhs = RECUR (TREE_OPERAND (op1, 2));
19290 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19292 else
19294 lhs = RECUR (TREE_OPERAND (op1, 0));
19295 rhs = RECUR (TREE_OPERAND (op1, 1));
19297 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19298 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19299 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19300 OMP_ATOMIC_WEAK (t));
19302 else
19304 tree op1 = TREE_OPERAND (t, 1);
19305 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19306 tree rhs1 = NULL_TREE, r = NULL_TREE;
19307 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19308 enum tree_code opcode = NOP_EXPR;
19309 if (code == OMP_ATOMIC_READ)
19311 v = RECUR (TREE_OPERAND (op1, 0));
19312 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19314 else if (code == OMP_ATOMIC_CAPTURE_OLD
19315 || code == OMP_ATOMIC_CAPTURE_NEW)
19317 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19318 v = RECUR (TREE_OPERAND (op1, 0));
19319 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19320 if (TREE_CODE (op11) == COMPOUND_EXPR)
19322 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19323 op11 = TREE_OPERAND (op11, 1);
19325 if (TREE_CODE (op11) == COND_EXPR)
19327 gcc_assert (rhs1 == NULL_TREE);
19328 tree c = TREE_OPERAND (op11, 0);
19329 if (TREE_CODE (c) == MODIFY_EXPR)
19331 r = RECUR (TREE_OPERAND (c, 0));
19332 c = TREE_OPERAND (c, 1);
19334 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19335 rhs = RECUR (TREE_OPERAND (c, 1));
19336 lhs = RECUR (TREE_OPERAND (op11, 2));
19337 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19339 else
19341 lhs = RECUR (TREE_OPERAND (op11, 0));
19342 rhs = RECUR (TREE_OPERAND (op11, 1));
19344 opcode = TREE_CODE (op11);
19345 if (opcode == MODIFY_EXPR)
19346 opcode = NOP_EXPR;
19348 else
19350 code = OMP_ATOMIC;
19351 lhs = RECUR (TREE_OPERAND (op1, 0));
19352 rhs = RECUR (TREE_OPERAND (op1, 1));
19354 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19355 lhs1, rhs1, r, tmp,
19356 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19358 break;
19360 case TRANSACTION_EXPR:
19362 int flags = 0;
19363 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19364 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19366 if (TRANSACTION_EXPR_IS_STMT (t))
19368 tree body = TRANSACTION_EXPR_BODY (t);
19369 tree noex = NULL_TREE;
19370 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19372 noex = MUST_NOT_THROW_COND (body);
19373 if (noex == NULL_TREE)
19374 noex = boolean_true_node;
19375 body = TREE_OPERAND (body, 0);
19377 stmt = begin_transaction_stmt (input_location, NULL, flags);
19378 RECUR (body);
19379 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19381 else
19383 stmt = build_transaction_expr (EXPR_LOCATION (t),
19384 RECUR (TRANSACTION_EXPR_BODY (t)),
19385 flags, NULL_TREE);
19386 RETURN (stmt);
19389 break;
19391 case MUST_NOT_THROW_EXPR:
19393 tree op0 = RECUR (TREE_OPERAND (t, 0));
19394 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19395 RETURN (build_must_not_throw_expr (op0, cond));
19398 case EXPR_PACK_EXPANSION:
19399 error ("invalid use of pack expansion expression");
19400 RETURN (error_mark_node);
19402 case NONTYPE_ARGUMENT_PACK:
19403 error ("use %<...%> to expand argument pack");
19404 RETURN (error_mark_node);
19406 case COMPOUND_EXPR:
19407 tmp = RECUR (TREE_OPERAND (t, 0));
19408 if (tmp == NULL_TREE)
19409 /* If the first operand was a statement, we're done with it. */
19410 RETURN (RECUR (TREE_OPERAND (t, 1)));
19411 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19412 RECUR (TREE_OPERAND (t, 1)),
19413 templated_operator_saved_lookups (t),
19414 complain));
19416 case PREDICT_EXPR:
19417 RETURN (add_stmt (copy_node (t)));
19419 default:
19420 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19422 RETURN (tsubst_expr (t, args, complain, in_decl));
19425 RETURN (NULL_TREE);
19426 out:
19427 input_location = loc;
19428 return r;
19429 #undef RECUR
19430 #undef RETURN
19433 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19434 function. For description of the body see comment above
19435 cp_parser_omp_declare_reduction_exprs. */
19437 static void
19438 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19440 if (t == NULL_TREE || t == error_mark_node)
19441 return;
19443 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19445 tree_stmt_iterator tsi;
19446 int i;
19447 tree stmts[7];
19448 memset (stmts, 0, sizeof stmts);
19449 for (i = 0, tsi = tsi_start (t);
19450 i < 7 && !tsi_end_p (tsi);
19451 i++, tsi_next (&tsi))
19452 stmts[i] = tsi_stmt (tsi);
19453 gcc_assert (tsi_end_p (tsi));
19455 if (i >= 3)
19457 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19458 && TREE_CODE (stmts[1]) == DECL_EXPR);
19459 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19460 args, complain, in_decl);
19461 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19462 args, complain, in_decl);
19463 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19464 expect to be pushing it. */
19465 DECL_CONTEXT (omp_out) = current_function_decl;
19466 DECL_CONTEXT (omp_in) = current_function_decl;
19467 keep_next_level (true);
19468 tree block = begin_omp_structured_block ();
19469 tsubst_stmt (stmts[2], args, complain, in_decl);
19470 block = finish_omp_structured_block (block);
19471 block = maybe_cleanup_point_expr_void (block);
19472 add_decl_expr (omp_out);
19473 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19474 add_decl_expr (omp_in);
19475 finish_expr_stmt (block);
19477 if (i >= 6)
19479 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19480 && TREE_CODE (stmts[4]) == DECL_EXPR);
19481 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19482 args, complain, in_decl);
19483 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19484 args, complain, in_decl);
19485 DECL_CONTEXT (omp_priv) = current_function_decl;
19486 DECL_CONTEXT (omp_orig) = current_function_decl;
19487 keep_next_level (true);
19488 tree block = begin_omp_structured_block ();
19489 tsubst_stmt (stmts[5], args, complain, in_decl);
19490 block = finish_omp_structured_block (block);
19491 block = maybe_cleanup_point_expr_void (block);
19492 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19493 add_decl_expr (omp_priv);
19494 add_decl_expr (omp_orig);
19495 finish_expr_stmt (block);
19496 if (i == 7)
19497 add_decl_expr (omp_orig);
19501 /* T is a postfix-expression that is not being used in a function
19502 call. Return the substituted version of T. */
19504 static tree
19505 tsubst_non_call_postfix_expression (tree t, tree args,
19506 tsubst_flags_t complain,
19507 tree in_decl)
19509 if (TREE_CODE (t) == SCOPE_REF)
19510 t = tsubst_qualified_id (t, args, complain, in_decl,
19511 /*done=*/false, /*address_p=*/false);
19512 else
19513 t = tsubst_expr (t, args, complain, in_decl);
19515 return t;
19518 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19519 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19520 dependent init-capture. EXPLICIT_P is true if the original list had
19521 explicit captures. */
19523 static void
19524 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19525 tsubst_flags_t complain)
19527 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19529 tree type = NULL_TREE;
19530 if (!init)
19532 if (complain & tf_error)
19533 error ("empty initializer in lambda init-capture");
19534 init = error_mark_node;
19536 else if (TREE_CODE (init) == TREE_LIST)
19537 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19538 if (!type)
19539 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19540 TREE_TYPE (field) = type;
19541 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19543 list = tree_cons (field, init, list);
19544 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19547 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19548 instantiation context. Instantiating a pack expansion containing a lambda
19549 might result in multiple lambdas all based on the same lambda in the
19550 template. */
19552 tree
19553 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19555 tree oldfn = lambda_function (t);
19556 in_decl = oldfn;
19558 tree r = build_lambda_expr ();
19560 LAMBDA_EXPR_LOCATION (r)
19561 = LAMBDA_EXPR_LOCATION (t);
19562 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19563 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19564 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19565 LAMBDA_EXPR_REGEN_INFO (r)
19566 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19567 preserve_args (args)));
19568 else
19569 LAMBDA_EXPR_REGEN_INFO (r)
19570 = build_template_info (t, preserve_args (args));
19572 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19573 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19575 vec<tree,va_gc>* field_packs = NULL;
19576 unsigned name_independent_cnt = 0;
19577 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19578 cap = TREE_CHAIN (cap))
19580 tree ofield = TREE_PURPOSE (cap);
19581 tree init = TREE_VALUE (cap);
19582 if (PACK_EXPANSION_P (init))
19583 init = tsubst_pack_expansion (init, args, complain, in_decl);
19584 else
19585 init = tsubst_expr (init, args, complain, in_decl);
19587 if (init == error_mark_node)
19588 return error_mark_node;
19590 if (init && TREE_CODE (init) == TREE_LIST)
19591 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19593 if (!processing_template_decl
19594 && init && TREE_CODE (init) != TREE_VEC
19595 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19597 /* For a VLA, simply tsubsting the field type won't work, we need to
19598 go through add_capture again. XXX do we want to do this for all
19599 captures? */
19600 tree name = (get_identifier
19601 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19602 tree ftype = TREE_TYPE (ofield);
19603 bool by_ref = (TYPE_REF_P (ftype)
19604 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19605 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19606 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield),
19607 &name_independent_cnt);
19608 continue;
19611 if (PACK_EXPANSION_P (ofield))
19612 ofield = PACK_EXPANSION_PATTERN (ofield);
19613 tree field = tsubst_decl (ofield, args, complain);
19615 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19617 /* Remember these for when we've pushed local_specializations. */
19618 vec_safe_push (field_packs, ofield);
19619 vec_safe_push (field_packs, field);
19622 if (field == error_mark_node)
19623 return error_mark_node;
19625 if (TREE_CODE (field) == TREE_VEC)
19627 int len = TREE_VEC_LENGTH (field);
19628 gcc_assert (TREE_CODE (init) == TREE_VEC
19629 && TREE_VEC_LENGTH (init) == len);
19630 for (int i = 0; i < len; ++i)
19631 prepend_one_capture (TREE_VEC_ELT (field, i),
19632 TREE_VEC_ELT (init, i),
19633 LAMBDA_EXPR_CAPTURE_LIST (r),
19634 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19635 complain);
19637 else
19639 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19640 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19642 if (id_equal (DECL_NAME (field), "__this"))
19643 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19647 tree type = begin_lambda_type (r);
19648 if (type == error_mark_node)
19649 return error_mark_node;
19651 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
19652 record_lambda_scope (r);
19653 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19654 /* If we're pushed into another scope (PR105652), fix it. */
19655 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19656 = TYPE_CONTEXT (TREE_TYPE (t));
19657 record_lambda_scope_discriminator (r);
19659 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19660 determine_visibility (TYPE_NAME (type));
19662 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19664 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19665 ? DECL_TI_TEMPLATE (oldfn)
19666 : NULL_TREE);
19668 tree tparms = NULL_TREE;
19669 if (oldtmpl)
19670 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
19672 tree fntype = static_fn_type (oldfn);
19674 tree saved_ctp = current_template_parms;
19675 if (oldtmpl)
19677 ++processing_template_decl;
19678 current_template_parms = tparms;
19680 fntype = tsubst (fntype, args, complain, in_decl);
19681 if (oldtmpl)
19683 current_template_parms = saved_ctp;
19684 --processing_template_decl;
19687 if (fntype == error_mark_node)
19688 r = error_mark_node;
19689 else
19691 /* The body of a lambda-expression is not a subexpression of the
19692 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19693 which would be skipped if cp_unevaluated_operand. */
19694 cp_evaluated ev;
19696 /* Fix the type of 'this'.
19697 For static and xobj member functions we use this to transport the
19698 lambda's closure type. It appears that in the regular case the
19699 object parameter is still pulled off, and then re-added again anyway.
19700 So perhaps we could do something better here? */
19701 fntype = build_memfn_type (fntype, type,
19702 type_memfn_quals (fntype),
19703 type_memfn_rqual (fntype));
19704 tree inst = (oldtmpl
19705 ? tsubst_template_decl (oldtmpl, args, complain,
19706 fntype, tparms)
19707 : tsubst_function_decl (oldfn, args, complain, fntype));
19708 if (inst == error_mark_node)
19710 r = error_mark_node;
19711 goto out;
19713 finish_member_declaration (inst);
19714 record_lambda_scope_sig_discriminator (r, inst);
19716 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
19718 /* Let finish_function set this. */
19719 DECL_DECLARED_CONSTEXPR_P (fn) = false;
19721 bool nested = cfun;
19722 if (nested)
19723 push_function_context ();
19724 else
19725 /* Still increment function_depth so that we don't GC in the
19726 middle of an expression. */
19727 ++function_depth;
19729 local_specialization_stack s (lss_copy);
19731 bool save_in_consteval_if_p = in_consteval_if_p;
19732 in_consteval_if_p = false;
19734 tree body = start_lambda_function (fn, r);
19736 /* Now record them for lookup_init_capture_pack. */
19737 int fplen = vec_safe_length (field_packs);
19738 for (int i = 0; i < fplen; )
19740 tree pack = (*field_packs)[i++];
19741 tree inst = (*field_packs)[i++];
19742 register_local_specialization (inst, pack);
19744 release_tree_vector (field_packs);
19746 register_parameter_specializations (oldfn, fn);
19748 if (oldtmpl)
19750 /* We might not partially instantiate some parts of the function, so
19751 copy these flags from the original template. */
19752 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19753 current_function_returns_value = ol->returns_value;
19754 current_function_returns_null = ol->returns_null;
19755 current_function_returns_abnormally = ol->returns_abnormally;
19756 current_function_infinite_loop = ol->infinite_loop;
19759 /* [temp.deduct] A lambda-expression appearing in a function type or a
19760 template parameter is not considered part of the immediate context for
19761 the purposes of template argument deduction. */
19762 complain = tf_warning_or_error;
19764 tree saved = DECL_SAVED_TREE (oldfn);
19765 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19766 /* We already have a body block from start_lambda_function, we don't
19767 need another to confuse NRV (91217). */
19768 saved = BIND_EXPR_BODY (saved);
19770 tsubst_stmt (saved, args, complain, r);
19772 finish_lambda_function (body);
19774 in_consteval_if_p = save_in_consteval_if_p;
19776 if (nested)
19777 pop_function_context ();
19778 else
19779 --function_depth;
19781 /* The capture list was built up in reverse order; fix that now. */
19782 LAMBDA_EXPR_CAPTURE_LIST (r)
19783 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19785 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19787 maybe_add_lambda_conv_op (type);
19790 out:
19791 finish_struct (type, /*attr*/NULL_TREE);
19793 insert_pending_capture_proxies ();
19795 return r;
19798 /* Subroutine of maybe_fold_fn_template_args. */
19800 static bool
19801 fold_targs_r (tree targs, tsubst_flags_t complain)
19803 int len = TREE_VEC_LENGTH (targs);
19804 for (int i = 0; i < len; ++i)
19806 tree &elt = TREE_VEC_ELT (targs, i);
19807 if (!elt || TYPE_P (elt)
19808 || TREE_CODE (elt) == TEMPLATE_DECL)
19809 continue;
19810 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
19812 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
19813 return false;
19815 else if (/* We can only safely preevaluate scalar prvalues. */
19816 SCALAR_TYPE_P (TREE_TYPE (elt))
19817 && !glvalue_p (elt)
19818 && !TREE_CONSTANT (elt))
19820 elt = cxx_constant_value (elt, complain);
19821 if (elt == error_mark_node)
19822 return false;
19826 return true;
19829 /* Try to do constant evaluation of any explicit template arguments in FN
19830 before overload resolution, to get any errors only once. Return true iff
19831 we didn't have any problems folding. */
19833 static bool
19834 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
19836 if (processing_template_decl || fn == NULL_TREE)
19837 return true;
19838 if (fn == error_mark_node)
19839 return false;
19840 if (TREE_CODE (fn) == OFFSET_REF
19841 || TREE_CODE (fn) == COMPONENT_REF)
19842 fn = TREE_OPERAND (fn, 1);
19843 if (BASELINK_P (fn))
19844 fn = BASELINK_FUNCTIONS (fn);
19845 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
19846 return true;
19847 tree targs = TREE_OPERAND (fn, 1);
19848 if (targs == NULL_TREE)
19849 return true;
19850 if (targs == error_mark_node)
19851 return false;
19852 return fold_targs_r (targs, complain);
19855 /* Helper function for tsubst_expr CALL_EXPR and ARRAY_REF handling. */
19857 static void
19858 tsubst_call_args (tree t, tree args, tsubst_flags_t complain,
19859 tree in_decl, releasing_vec &call_args)
19861 unsigned int nargs = call_expr_nargs (t);
19862 for (unsigned int i = 0; i < nargs; ++i)
19864 tree arg = CALL_EXPR_ARG (t, i);
19866 if (!PACK_EXPANSION_P (arg))
19867 vec_safe_push (call_args, tsubst_expr (arg, args, complain, in_decl));
19868 else
19870 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
19871 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19872 if (TREE_CODE (arg) == TREE_VEC)
19874 unsigned int len, j;
19876 len = TREE_VEC_LENGTH (arg);
19877 for (j = 0; j < len; ++j)
19879 tree value = TREE_VEC_ELT (arg, j);
19880 if (value != NULL_TREE)
19881 value = convert_from_reference (value);
19882 vec_safe_push (call_args, value);
19885 else
19886 /* A partial substitution. Add one entry. */
19887 vec_safe_push (call_args, arg);
19892 /* Like tsubst but deals with expressions and performs semantic
19893 analysis. */
19895 tree
19896 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19898 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19899 #define RECUR(NODE) \
19900 tsubst_expr (NODE, args, complain, in_decl)
19902 tree retval, op1;
19903 location_t save_loc;
19905 if (t == NULL_TREE || t == error_mark_node)
19906 return t;
19908 save_loc = input_location;
19909 if (location_t eloc = cp_expr_location (t))
19910 input_location = eloc;
19912 /* N3276 decltype magic only applies to calls at the top level or on the
19913 right side of a comma. */
19914 tsubst_flags_t decltype_flag = (complain & tf_decltype);
19915 complain &= ~tf_decltype;
19917 /* This flag only applies to id-expressions at the top level, and
19918 controls resolution thereof. */
19919 tsubst_flags_t no_name_lookup_flag = (complain & tf_no_name_lookup);
19920 complain &= ~tf_no_name_lookup;
19922 if (!no_name_lookup_flag)
19923 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
19924 return d;
19926 switch (TREE_CODE (t))
19928 case USING_DECL:
19929 t = DECL_NAME (t);
19930 /* Fall through. */
19931 case IDENTIFIER_NODE:
19933 tree decl;
19934 cp_id_kind idk;
19935 const char *error_msg;
19937 if (IDENTIFIER_CONV_OP_P (t))
19939 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19940 t = make_conv_op_name (new_type);
19943 if (no_name_lookup_flag)
19944 RETURN (t);
19946 /* Look up the name. */
19947 decl = lookup_name (t);
19949 /* By convention, expressions use ERROR_MARK_NODE to indicate
19950 failure, not NULL_TREE. */
19951 if (decl == NULL_TREE)
19952 decl = error_mark_node;
19954 decl = finish_id_expression (t, decl, NULL_TREE,
19955 &idk,
19956 /*i_c_e_p=*/false,
19957 /*allow_i_c_e_p=*/true,
19958 /*non_i_c_e_p=*/nullptr,
19959 /*template_p=*/false,
19960 /*done=*/true,
19961 /*address_p=*/false,
19962 /*template_arg_p=*/false,
19963 &error_msg,
19964 input_location);
19965 if (error_msg)
19966 error (error_msg);
19967 if (identifier_p (decl))
19969 if (complain & tf_error)
19970 unqualified_name_lookup_error (decl);
19971 decl = error_mark_node;
19973 RETURN (decl);
19976 case TEMPLATE_ID_EXPR:
19978 tree object;
19979 tree templ = TREE_OPERAND (t, 0);
19980 tree targs = TREE_OPERAND (t, 1);
19982 if (no_name_lookup_flag)
19983 templ = tsubst_name (templ, args, complain, in_decl);
19984 else
19985 templ = tsubst_expr (templ, args, complain, in_decl);
19987 if (targs)
19988 targs = tsubst_template_args (targs, args, complain, in_decl);
19989 if (targs == error_mark_node)
19990 RETURN (error_mark_node);
19992 if (TREE_CODE (templ) == SCOPE_REF)
19994 tree name = TREE_OPERAND (templ, 1);
19995 tree tid = lookup_template_function (name, targs);
19996 TREE_OPERAND (templ, 1) = tid;
19997 RETURN (templ);
20000 if (concept_definition_p (templ))
20002 tree check = build_concept_check (templ, targs, complain);
20003 if (check == error_mark_node)
20004 RETURN (error_mark_node);
20006 tree id = unpack_concept_check (check);
20008 /* If we built a function concept check, return the underlying
20009 template-id. So we can evaluate it as a function call. */
20010 if (function_concept_p (TREE_OPERAND (id, 0)))
20011 RETURN (id);
20013 RETURN (check);
20016 if (variable_template_p (templ))
20018 if (no_name_lookup_flag)
20019 RETURN (lookup_template_variable (templ, targs, complain));
20021 tree r = lookup_and_finish_template_variable (templ, targs,
20022 complain);
20023 r = convert_from_reference (r);
20024 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20025 RETURN (r);
20028 if (TREE_CODE (templ) == COMPONENT_REF)
20030 object = TREE_OPERAND (templ, 0);
20031 templ = TREE_OPERAND (templ, 1);
20033 else
20034 object = NULL_TREE;
20036 tree tid = lookup_template_function (templ, targs);
20037 protected_set_expr_location (tid, EXPR_LOCATION (t));
20039 if (object)
20040 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20041 object, tid, NULL_TREE));
20042 else if (no_name_lookup_flag)
20043 RETURN (tid);
20044 else if (identifier_p (templ))
20046 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20047 name lookup found nothing when parsing the template name. */
20048 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20049 RETURN (tid);
20051 else
20052 RETURN (baselink_for_fns (tid));
20055 case INDIRECT_REF:
20057 tree r = RECUR (TREE_OPERAND (t, 0));
20059 if (REFERENCE_REF_P (t))
20061 /* A type conversion to reference type will be enclosed in
20062 such an indirect ref, but the substitution of the cast
20063 will have also added such an indirect ref. */
20064 r = convert_from_reference (r);
20066 else
20067 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20068 templated_operator_saved_lookups (t),
20069 complain|decltype_flag);
20071 if (REF_PARENTHESIZED_P (t))
20072 r = force_paren_expr (r);
20074 RETURN (r);
20077 case NOP_EXPR:
20079 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20080 tree op0 = RECUR (TREE_OPERAND (t, 0));
20081 RETURN (build_nop (type, op0));
20084 case IMPLICIT_CONV_EXPR:
20086 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20087 tree expr = RECUR (TREE_OPERAND (t, 0));
20088 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20090 retval = copy_node (t);
20091 TREE_TYPE (retval) = type;
20092 TREE_OPERAND (retval, 0) = expr;
20093 RETURN (retval);
20095 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20097 tree r = convert_nontype_argument (type, expr, complain);
20098 if (r == NULL_TREE)
20099 r = error_mark_node;
20100 RETURN (r);
20102 int flags = LOOKUP_IMPLICIT;
20103 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20104 flags = LOOKUP_NORMAL;
20105 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20106 flags |= LOOKUP_NO_NARROWING;
20107 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20108 flags));
20111 case CONVERT_EXPR:
20113 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20114 tree op0 = RECUR (TREE_OPERAND (t, 0));
20115 if (op0 == error_mark_node)
20116 RETURN (error_mark_node);
20117 RETURN (build1 (CONVERT_EXPR, type, op0));
20120 case CAST_EXPR:
20121 case REINTERPRET_CAST_EXPR:
20122 case CONST_CAST_EXPR:
20123 case DYNAMIC_CAST_EXPR:
20124 case STATIC_CAST_EXPR:
20126 tree type;
20127 tree op, r = NULL_TREE;
20129 tsubst_flags_t tcomplain = complain;
20130 if (TREE_CODE (t) == CAST_EXPR)
20131 tcomplain |= tf_tst_ok;
20132 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20134 op = RECUR (TREE_OPERAND (t, 0));
20136 warning_sentinel s(warn_useless_cast);
20137 warning_sentinel s2(warn_ignored_qualifiers);
20138 warning_sentinel s3(warn_int_in_bool_context);
20139 switch (TREE_CODE (t))
20141 case CAST_EXPR:
20142 r = build_functional_cast (input_location, type, op, complain);
20143 break;
20144 case REINTERPRET_CAST_EXPR:
20145 r = build_reinterpret_cast (input_location, type, op, complain);
20146 break;
20147 case CONST_CAST_EXPR:
20148 r = build_const_cast (input_location, type, op, complain);
20149 break;
20150 case DYNAMIC_CAST_EXPR:
20151 r = build_dynamic_cast (input_location, type, op, complain);
20152 break;
20153 case STATIC_CAST_EXPR:
20154 r = build_static_cast (input_location, type, op, complain);
20155 if (IMPLICIT_RVALUE_P (t))
20156 set_implicit_rvalue_p (r);
20157 break;
20158 default:
20159 gcc_unreachable ();
20162 RETURN (r);
20165 case BIT_CAST_EXPR:
20167 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20168 tree op0 = RECUR (TREE_OPERAND (t, 0));
20169 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20172 case POSTDECREMENT_EXPR:
20173 case POSTINCREMENT_EXPR:
20174 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20175 args, complain, in_decl);
20176 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20177 templated_operator_saved_lookups (t),
20178 complain|decltype_flag));
20180 case BIT_NOT_EXPR:
20181 if (identifier_p (TREE_OPERAND (t, 0)))
20183 gcc_checking_assert (no_name_lookup_flag);
20184 RETURN (t);
20186 else if (TYPE_P (TREE_OPERAND (t, 0)))
20188 gcc_checking_assert (no_name_lookup_flag);
20189 tree op0 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
20190 RETURN (build_min_nt_loc (EXPR_LOCATION (t), BIT_NOT_EXPR, op0));
20192 /* Fall through. */
20193 case PREDECREMENT_EXPR:
20194 case PREINCREMENT_EXPR:
20195 case NEGATE_EXPR:
20196 case ABS_EXPR:
20197 case TRUTH_NOT_EXPR:
20198 case UNARY_PLUS_EXPR: /* Unary + */
20199 case REALPART_EXPR:
20200 case IMAGPART_EXPR:
20201 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20202 RECUR (TREE_OPERAND (t, 0)),
20203 templated_operator_saved_lookups (t),
20204 complain|decltype_flag));
20206 case EXCESS_PRECISION_EXPR:
20208 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20209 tree op0 = RECUR (TREE_OPERAND (t, 0));
20210 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20211 RETURN (op0);
20212 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20213 type, op0));
20216 case FIX_TRUNC_EXPR:
20217 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20218 gcc_unreachable ();
20220 case ADDR_EXPR:
20221 op1 = TREE_OPERAND (t, 0);
20222 if (TREE_CODE (op1) == LABEL_DECL)
20223 RETURN (finish_label_address_expr (DECL_NAME (op1),
20224 EXPR_LOCATION (op1)));
20225 if (TREE_CODE (op1) == SCOPE_REF)
20226 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20227 /*done=*/true, /*address_p=*/true);
20228 else
20229 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20230 in_decl);
20231 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20232 templated_operator_saved_lookups (t),
20233 complain|decltype_flag));
20235 case PLUS_EXPR:
20236 case MINUS_EXPR:
20237 case MULT_EXPR:
20238 case TRUNC_DIV_EXPR:
20239 case CEIL_DIV_EXPR:
20240 case FLOOR_DIV_EXPR:
20241 case ROUND_DIV_EXPR:
20242 case EXACT_DIV_EXPR:
20243 case BIT_AND_EXPR:
20244 case BIT_IOR_EXPR:
20245 case BIT_XOR_EXPR:
20246 case TRUNC_MOD_EXPR:
20247 case FLOOR_MOD_EXPR:
20248 case TRUTH_ANDIF_EXPR:
20249 case TRUTH_ORIF_EXPR:
20250 case TRUTH_AND_EXPR:
20251 case TRUTH_OR_EXPR:
20252 case RSHIFT_EXPR:
20253 case LSHIFT_EXPR:
20254 case EQ_EXPR:
20255 case NE_EXPR:
20256 case MAX_EXPR:
20257 case MIN_EXPR:
20258 case LE_EXPR:
20259 case GE_EXPR:
20260 case LT_EXPR:
20261 case GT_EXPR:
20262 case SPACESHIP_EXPR:
20263 case MEMBER_REF:
20264 case DOTSTAR_EXPR:
20266 /* If either OP0 or OP1 was value- or type-dependent, suppress
20267 warnings that depend on the range of the types involved. */
20268 tree op0 = TREE_OPERAND (t, 0);
20269 tree op1 = TREE_OPERAND (t, 1);
20270 const bool was_dep = (dependent_operand_p (op0)
20271 || dependent_operand_p (op1));
20272 op0 = RECUR (op0);
20273 op1 = RECUR (op1);
20275 warning_sentinel s1(warn_type_limits, was_dep);
20276 warning_sentinel s2(warn_div_by_zero, was_dep);
20277 warning_sentinel s3(warn_logical_op, was_dep);
20278 warning_sentinel s4(warn_tautological_compare, was_dep);
20279 warning_sentinel s5(warn_address, was_dep);
20281 tree r = build_x_binary_op
20282 (input_location, TREE_CODE (t),
20283 op0,
20284 (warning_suppressed_p (TREE_OPERAND (t, 0))
20285 ? ERROR_MARK
20286 : TREE_CODE (TREE_OPERAND (t, 0))),
20287 op1,
20288 (warning_suppressed_p (TREE_OPERAND (t, 1))
20289 ? ERROR_MARK
20290 : TREE_CODE (TREE_OPERAND (t, 1))),
20291 templated_operator_saved_lookups (t),
20292 /*overload=*/NULL,
20293 complain|decltype_flag);
20294 if (EXPR_P (r))
20295 copy_warning (r, t);
20297 RETURN (r);
20300 case POINTER_PLUS_EXPR:
20302 tree op0 = RECUR (TREE_OPERAND (t, 0));
20303 if (op0 == error_mark_node)
20304 RETURN (error_mark_node);
20305 tree op1 = RECUR (TREE_OPERAND (t, 1));
20306 if (op1 == error_mark_node)
20307 RETURN (error_mark_node);
20308 RETURN (fold_build_pointer_plus (op0, op1));
20311 case SCOPE_REF:
20312 if (no_name_lookup_flag)
20314 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
20315 tree op1 = tsubst_name (TREE_OPERAND (t, 1), args, complain, in_decl);
20316 RETURN (build_qualified_name (/*type=*/NULL_TREE, op0, op1,
20317 QUALIFIED_NAME_IS_TEMPLATE (t)));
20319 else
20320 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20321 /*address_p=*/false));
20323 case BASELINK:
20324 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20325 args, complain, in_decl));
20327 case ARRAY_REF:
20328 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20329 args, complain, in_decl);
20330 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20331 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20332 == ovl_op_identifier (ARRAY_REF)))
20334 tree c = TREE_OPERAND (t, 1);
20335 releasing_vec index_exp_list;
20336 tsubst_call_args (c, args, complain, in_decl, index_exp_list);
20338 tree r;
20339 if (vec_safe_length (index_exp_list) == 1
20340 && !PACK_EXPANSION_P (index_exp_list[0]))
20341 r = grok_array_decl (EXPR_LOCATION (t), op1,
20342 index_exp_list[0], NULL,
20343 complain | decltype_flag);
20344 else
20345 r = grok_array_decl (EXPR_LOCATION (t), op1,
20346 NULL_TREE, &index_exp_list,
20347 complain | decltype_flag);
20348 RETURN (r);
20350 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20351 RECUR (TREE_OPERAND (t, 1)),
20352 complain|decltype_flag));
20354 case OMP_ARRAY_SECTION:
20356 tree op0 = RECUR (TREE_OPERAND (t, 0));
20357 tree op1 = NULL_TREE, op2 = NULL_TREE;
20358 if (op0 == error_mark_node)
20359 RETURN (error_mark_node);
20360 if (TREE_OPERAND (t, 1))
20362 op1 = RECUR (TREE_OPERAND (t, 1));
20363 if (op1 == error_mark_node)
20364 RETURN (error_mark_node);
20366 if (TREE_OPERAND (t, 2))
20368 op2 = RECUR (TREE_OPERAND (t, 2));
20369 if (op2 == error_mark_node)
20370 RETURN (error_mark_node);
20372 RETURN (build_omp_array_section (EXPR_LOCATION (t), op0, op1, op2));
20375 case SIZEOF_EXPR:
20376 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20377 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20379 tree expanded, op = TREE_OPERAND (t, 0);
20380 int len = 0;
20382 if (SIZEOF_EXPR_TYPE_P (t))
20383 op = TREE_TYPE (op);
20385 ++cp_unevaluated_operand;
20386 ++c_inhibit_evaluation_warnings;
20387 /* We only want to compute the number of arguments. */
20388 if (PACK_EXPANSION_P (op))
20389 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
20390 else
20391 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
20392 args, complain, in_decl);
20393 --cp_unevaluated_operand;
20394 --c_inhibit_evaluation_warnings;
20396 if (TREE_CODE (expanded) == TREE_VEC)
20398 len = TREE_VEC_LENGTH (expanded);
20399 /* Set TREE_USED for the benefit of -Wunused. */
20400 for (int i = 0; i < len; i++)
20401 if (DECL_P (TREE_VEC_ELT (expanded, i)))
20402 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
20405 if (expanded == error_mark_node)
20406 RETURN (error_mark_node);
20407 else if (PACK_EXPANSION_P (expanded)
20408 || (TREE_CODE (expanded) == TREE_VEC
20409 && pack_expansion_args_count (expanded)))
20412 if (PACK_EXPANSION_P (expanded))
20413 /* OK. */;
20414 else
20415 expanded = make_argument_pack (expanded);
20417 if (TYPE_P (expanded))
20418 RETURN (cxx_sizeof_or_alignof_type (input_location,
20419 expanded, SIZEOF_EXPR,
20420 false,
20421 complain & tf_error));
20422 else
20423 RETURN (cxx_sizeof_or_alignof_expr (input_location,
20424 expanded, SIZEOF_EXPR,
20425 false,
20426 complain & tf_error));
20428 else
20429 RETURN (build_int_cst (size_type_node, len));
20431 /* Fall through */
20433 case ALIGNOF_EXPR:
20435 tree r;
20437 op1 = TREE_OPERAND (t, 0);
20438 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20439 op1 = TREE_TYPE (op1);
20440 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20441 && ALIGNOF_EXPR_STD_P (t));
20442 if (!args)
20444 /* When there are no ARGS, we are trying to evaluate a
20445 non-dependent expression from the parser. Trying to do
20446 the substitutions may not work. */
20447 if (!TYPE_P (op1))
20448 op1 = TREE_TYPE (op1);
20450 else
20452 ++cp_unevaluated_operand;
20453 ++c_inhibit_evaluation_warnings;
20454 if (TYPE_P (op1))
20455 op1 = tsubst (op1, args, complain, in_decl);
20456 else
20457 op1 = tsubst_expr (op1, args, complain, in_decl);
20458 --cp_unevaluated_operand;
20459 --c_inhibit_evaluation_warnings;
20461 if (TYPE_P (op1))
20462 r = cxx_sizeof_or_alignof_type (input_location,
20463 op1, TREE_CODE (t), std_alignof,
20464 complain & tf_error);
20465 else
20466 r = cxx_sizeof_or_alignof_expr (input_location,
20467 op1, TREE_CODE (t), std_alignof,
20468 complain & tf_error);
20469 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20471 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20473 if (!processing_template_decl && TYPE_P (op1))
20475 r = build_min (SIZEOF_EXPR, size_type_node,
20476 build1 (NOP_EXPR, op1, error_mark_node));
20477 SIZEOF_EXPR_TYPE_P (r) = 1;
20479 else
20480 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20481 TREE_SIDE_EFFECTS (r) = 0;
20482 TREE_READONLY (r) = 1;
20484 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20486 RETURN (r);
20489 case AT_ENCODE_EXPR:
20491 op1 = TREE_OPERAND (t, 0);
20492 ++cp_unevaluated_operand;
20493 ++c_inhibit_evaluation_warnings;
20494 op1 = tsubst (op1, args, complain, in_decl);
20495 --cp_unevaluated_operand;
20496 --c_inhibit_evaluation_warnings;
20497 RETURN (objc_build_encode_expr (op1));
20500 case NOEXCEPT_EXPR:
20501 op1 = TREE_OPERAND (t, 0);
20502 ++cp_unevaluated_operand;
20503 ++c_inhibit_evaluation_warnings;
20504 ++cp_noexcept_operand;
20505 op1 = tsubst_expr (op1, args, complain, in_decl);
20506 --cp_unevaluated_operand;
20507 --c_inhibit_evaluation_warnings;
20508 --cp_noexcept_operand;
20509 RETURN (finish_noexcept_expr (op1, complain));
20511 case MODOP_EXPR:
20513 warning_sentinel s(warn_div_by_zero);
20514 tree lhs = RECUR (TREE_OPERAND (t, 0));
20515 tree rhs = RECUR (TREE_OPERAND (t, 2));
20517 tree r = build_x_modify_expr
20518 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20519 templated_operator_saved_lookups (t),
20520 complain|decltype_flag);
20521 /* TREE_NO_WARNING must be set if either the expression was
20522 parenthesized or it uses an operator such as >>= rather
20523 than plain assignment. In the former case, it was already
20524 set and must be copied. In the latter case,
20525 build_x_modify_expr sets it and it must not be reset
20526 here. */
20527 if (warning_suppressed_p (t, OPT_Wparentheses))
20528 suppress_warning (STRIP_REFERENCE_REF (r), OPT_Wparentheses);
20530 RETURN (r);
20533 case ARROW_EXPR:
20534 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20535 args, complain, in_decl);
20536 /* Remember that there was a reference to this entity. */
20537 if (DECL_P (op1)
20538 && !mark_used (op1, complain) && !(complain & tf_error))
20539 RETURN (error_mark_node);
20540 RETURN (build_x_arrow (input_location, op1, complain));
20542 case NEW_EXPR:
20544 tree placement = RECUR (TREE_OPERAND (t, 0));
20545 tree init = RECUR (TREE_OPERAND (t, 3));
20546 vec<tree, va_gc> *placement_vec;
20547 vec<tree, va_gc> *init_vec;
20548 tree ret;
20549 location_t loc = EXPR_LOCATION (t);
20551 if (placement == NULL_TREE)
20552 placement_vec = NULL;
20553 else if (placement == error_mark_node)
20554 RETURN (error_mark_node);
20555 else
20557 placement_vec = make_tree_vector ();
20558 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20559 vec_safe_push (placement_vec, TREE_VALUE (placement));
20562 /* If there was an initializer in the original tree, but it
20563 instantiated to an empty list, then we should pass a
20564 non-NULL empty vector to tell build_new that it was an
20565 empty initializer() rather than no initializer. This can
20566 only happen when the initializer is a pack expansion whose
20567 parameter packs are of length zero. */
20568 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20569 init_vec = NULL;
20570 else if (init == error_mark_node)
20571 RETURN (error_mark_node);
20572 else
20574 init_vec = make_tree_vector ();
20575 if (init == void_node)
20576 gcc_assert (init_vec != NULL);
20577 else
20579 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20580 vec_safe_push (init_vec, TREE_VALUE (init));
20584 /* Avoid passing an enclosing decl to valid_array_size_p. */
20585 in_decl = NULL_TREE;
20587 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20588 tree op2 = RECUR (TREE_OPERAND (t, 2));
20589 ret = build_new (loc, &placement_vec, op1, op2,
20590 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20591 complain);
20593 if (placement_vec != NULL)
20594 release_tree_vector (placement_vec);
20595 if (init_vec != NULL)
20596 release_tree_vector (init_vec);
20598 RETURN (ret);
20601 case DELETE_EXPR:
20603 tree op0 = RECUR (TREE_OPERAND (t, 0));
20604 tree op1 = RECUR (TREE_OPERAND (t, 1));
20605 RETURN (delete_sanity (input_location, op0, op1,
20606 DELETE_EXPR_USE_VEC (t),
20607 DELETE_EXPR_USE_GLOBAL (t),
20608 complain));
20611 case COMPOUND_EXPR:
20613 tree op0 = tsubst_expr (TREE_OPERAND (t, 0), args,
20614 complain & ~tf_decltype, in_decl);
20615 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20616 op0,
20617 RECUR (TREE_OPERAND (t, 1)),
20618 templated_operator_saved_lookups (t),
20619 complain|decltype_flag));
20622 case CALL_EXPR:
20624 tree function;
20625 unsigned int nargs;
20626 bool qualified_p;
20627 bool koenig_p;
20628 tree ret;
20630 function = CALL_EXPR_FN (t);
20631 /* Internal function with no arguments. */
20632 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20633 RETURN (t);
20635 /* When we parsed the expression, we determined whether or
20636 not Koenig lookup should be performed. */
20637 koenig_p = KOENIG_LOOKUP_P (t);
20638 if (function == NULL_TREE)
20640 koenig_p = false;
20641 qualified_p = false;
20643 else if (TREE_CODE (function) == SCOPE_REF)
20645 qualified_p = true;
20646 function = tsubst_qualified_id (function, args, complain, in_decl,
20647 /*done=*/false,
20648 /*address_p=*/false);
20650 else if (CALL_EXPR_STATIC_CHAIN (t)
20651 && TREE_CODE (function) == FUNCTION_DECL
20652 && fndecl_built_in_p (function, BUILT_IN_CLASSIFY_TYPE))
20654 tree type = tsubst (CALL_EXPR_STATIC_CHAIN (t), args, complain,
20655 in_decl);
20656 if (dependent_type_p (type))
20658 ret = build_vl_exp (CALL_EXPR, 4);
20659 CALL_EXPR_FN (ret) = function;
20660 CALL_EXPR_STATIC_CHAIN (ret) = type;
20661 CALL_EXPR_ARG (ret, 0)
20662 = build_min (SIZEOF_EXPR, size_type_node, type);
20663 TREE_TYPE (ret) = integer_type_node;
20665 else
20666 ret = build_int_cst (integer_type_node, type_to_class (type));
20667 RETURN (ret);
20669 else if (koenig_p
20670 && (identifier_p (function)
20671 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20672 && identifier_p (TREE_OPERAND (function, 0)))))
20674 /* Do nothing; calling tsubst_expr on an identifier
20675 would incorrectly perform unqualified lookup again.
20677 Note that we can also have an IDENTIFIER_NODE if the earlier
20678 unqualified lookup found a dependent local extern declaration
20679 (as per finish_call_expr); in that case koenig_p will be false
20680 and we do want to do the lookup again to find the substituted
20681 declaration. */
20682 qualified_p = false;
20684 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20685 function = tsubst_name (function, args, complain, in_decl);
20687 else
20689 if (TREE_CODE (function) == COMPONENT_REF)
20691 tree op = TREE_OPERAND (function, 1);
20693 qualified_p = (TREE_CODE (op) == SCOPE_REF
20694 || (BASELINK_P (op)
20695 && BASELINK_QUALIFIED_P (op)));
20697 else
20698 qualified_p = false;
20700 if (TREE_CODE (function) == ADDR_EXPR
20701 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20702 /* Avoid error about taking the address of a constructor. */
20703 function = TREE_OPERAND (function, 0);
20705 tsubst_flags_t subcomplain = complain;
20706 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20707 /* When KOENIG_P, we don't want to mark_used the callee before
20708 augmenting the overload set via ADL, so during this initial
20709 substitution we disable mark_used by setting tf_conv (68942). */
20710 subcomplain |= tf_conv;
20711 function = tsubst_expr (function, args, subcomplain, in_decl);
20713 if (BASELINK_P (function))
20714 qualified_p = true;
20717 nargs = call_expr_nargs (t);
20718 releasing_vec call_args;
20719 tsubst_call_args (t, args, complain, in_decl, call_args);
20721 /* Stripped-down processing for a call in a thunk. Specifically, in
20722 the thunk template for a generic lambda. */
20723 if (call_from_lambda_thunk_p (t))
20725 /* Now that we've expanded any packs, the number of call args
20726 might be different. */
20727 unsigned int cargs = call_args->length ();
20728 tree thisarg = NULL_TREE;
20729 if (TREE_CODE (function) == COMPONENT_REF)
20731 thisarg = TREE_OPERAND (function, 0);
20732 if (TREE_CODE (thisarg) == INDIRECT_REF)
20733 thisarg = TREE_OPERAND (thisarg, 0);
20734 function = TREE_OPERAND (function, 1);
20735 if (TREE_CODE (function) == BASELINK)
20736 function = BASELINK_FUNCTIONS (function);
20738 /* We aren't going to do normal overload resolution, so force the
20739 template-id to resolve. */
20740 function = resolve_nondeduced_context (function, complain);
20741 for (unsigned i = 0; i < cargs; ++i)
20743 /* In a thunk, pass through args directly, without any
20744 conversions. */
20745 tree arg = (*call_args)[i];
20746 while (TREE_CODE (arg) != PARM_DECL)
20747 arg = TREE_OPERAND (arg, 0);
20748 (*call_args)[i] = arg;
20750 if (thisarg)
20752 /* If there are no other args, just push 'this'. */
20753 if (cargs == 0)
20754 vec_safe_push (call_args, thisarg);
20755 else
20757 /* Otherwise, shift the other args over to make room. */
20758 tree last = (*call_args)[cargs - 1];
20759 vec_safe_push (call_args, last);
20760 for (int i = cargs - 1; i > 0; --i)
20761 (*call_args)[i] = (*call_args)[i - 1];
20762 (*call_args)[0] = thisarg;
20765 ret = build_call_a (function, call_args->length (),
20766 call_args->address ());
20767 /* The thunk location is not interesting. */
20768 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20769 CALL_FROM_THUNK_P (ret) = true;
20770 if (CLASS_TYPE_P (TREE_TYPE (ret)))
20771 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20773 RETURN (ret);
20776 /* We do not perform argument-dependent lookup if normal
20777 lookup finds a non-function, in accordance with the
20778 resolution of DR 218. */
20779 if (koenig_p
20780 && ((is_overloaded_fn (function)
20781 /* If lookup found a member function, the Koenig lookup is
20782 not appropriate, even if an unqualified-name was used
20783 to denote the function. */
20784 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20785 || identifier_p (function)
20786 /* C++20 P0846: Lookup found nothing. */
20787 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20788 && identifier_p (TREE_OPERAND (function, 0))))
20789 /* Only do this when substitution turns a dependent call
20790 into a non-dependent call. */
20791 && type_dependent_expression_p_push (t)
20792 && !any_type_dependent_arguments_p (call_args))
20793 function = perform_koenig_lookup (function, call_args, tf_none);
20795 if (function != NULL_TREE
20796 && (identifier_p (function)
20797 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20798 && identifier_p (TREE_OPERAND (function, 0))
20799 && !any_dependent_template_arguments_p (TREE_OPERAND
20800 (function, 1))))
20801 && !any_type_dependent_arguments_p (call_args))
20803 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20804 if (template_id_p)
20805 function = TREE_OPERAND (function, 0);
20806 if (koenig_p && (complain & tf_warning_or_error))
20808 /* For backwards compatibility and good diagnostics, try
20809 the unqualified lookup again if we aren't in SFINAE
20810 context. */
20811 tree unq = tsubst_expr (function, args, complain, in_decl);
20812 if (unq == error_mark_node)
20813 RETURN (error_mark_node);
20815 if (unq != function)
20817 char const *const msg
20818 = G_("%qD was not declared in this scope, "
20819 "and no declarations were found by "
20820 "argument-dependent lookup at the point "
20821 "of instantiation");
20823 bool in_lambda = (current_class_type
20824 && LAMBDA_TYPE_P (current_class_type));
20825 /* In a lambda fn, we have to be careful to not
20826 introduce new this captures. Legacy code can't
20827 be using lambdas anyway, so it's ok to be
20828 stricter. Be strict with C++20 template-id ADL too.
20829 And be strict if we're already failing anyway. */
20830 bool strict = in_lambda || template_id_p || seen_error();
20831 bool diag = true;
20832 if (strict)
20833 error_at (cp_expr_loc_or_input_loc (t),
20834 msg, function);
20835 else
20836 diag = permerror (cp_expr_loc_or_input_loc (t),
20837 msg, function);
20838 if (diag)
20840 tree fn = unq;
20842 if (INDIRECT_REF_P (fn))
20843 fn = TREE_OPERAND (fn, 0);
20844 if (is_overloaded_fn (fn))
20845 fn = get_first_fn (fn);
20847 if (!DECL_P (fn))
20848 /* Can't say anything more. */;
20849 else if (DECL_CLASS_SCOPE_P (fn))
20851 location_t loc = cp_expr_loc_or_input_loc (t);
20852 inform (loc,
20853 "declarations in dependent base %qT are "
20854 "not found by unqualified lookup",
20855 DECL_CLASS_CONTEXT (fn));
20856 if (current_class_ptr)
20857 inform (loc,
20858 "use %<this->%D%> instead", function);
20859 else
20860 inform (loc,
20861 "use %<%T::%D%> instead",
20862 current_class_name, function);
20864 else
20865 inform (DECL_SOURCE_LOCATION (fn),
20866 "%qD declared here, later in the "
20867 "translation unit", fn);
20868 if (strict)
20869 RETURN (error_mark_node);
20872 function = unq;
20875 if (identifier_p (function))
20877 if (complain & tf_error)
20878 unqualified_name_lookup_error (function);
20879 RETURN (error_mark_node);
20883 /* Remember that there was a reference to this entity. */
20884 if (function != NULL_TREE
20885 && DECL_P (function)
20886 && !mark_used (function, complain) && !(complain & tf_error))
20887 RETURN (error_mark_node);
20889 if (!maybe_fold_fn_template_args (function, complain))
20890 return error_mark_node;
20892 /* Put back tf_decltype for the actual call. */
20893 complain |= decltype_flag;
20895 if (function == NULL_TREE)
20896 switch (CALL_EXPR_IFN (t))
20898 case IFN_LAUNDER:
20899 gcc_assert (nargs == 1);
20900 if (vec_safe_length (call_args) != 1)
20902 error_at (cp_expr_loc_or_input_loc (t),
20903 "wrong number of arguments to "
20904 "%<__builtin_launder%>");
20905 ret = error_mark_node;
20907 else
20908 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20909 (*call_args)[0], complain);
20910 break;
20912 case IFN_VEC_CONVERT:
20913 gcc_assert (nargs == 1);
20914 if (vec_safe_length (call_args) != 1)
20916 error_at (cp_expr_loc_or_input_loc (t),
20917 "wrong number of arguments to "
20918 "%<__builtin_convertvector%>");
20919 ret = error_mark_node;
20920 break;
20922 ret = cp_build_vec_convert ((*call_args)[0], input_location,
20923 tsubst (TREE_TYPE (t), args,
20924 complain, in_decl),
20925 complain);
20926 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20927 RETURN (ret);
20928 break;
20930 case IFN_SHUFFLEVECTOR:
20932 ret = build_x_shufflevector (input_location, call_args,
20933 complain);
20934 if (ret != error_mark_node)
20935 RETURN (ret);
20936 break;
20939 case IFN_ASSUME:
20940 gcc_assert (nargs == 1);
20941 if (vec_safe_length (call_args) != 1)
20943 error_at (cp_expr_loc_or_input_loc (t),
20944 "wrong number of arguments to "
20945 "%<assume%> attribute");
20946 ret = error_mark_node;
20948 else
20950 tree &arg = (*call_args)[0];
20951 if (!type_dependent_expression_p (arg))
20952 arg = contextual_conv_bool (arg, tf_warning_or_error);
20953 if (error_operand_p (arg))
20955 ret = error_mark_node;
20956 break;
20958 ret = build_assume_call (EXPR_LOCATION (t), arg);
20959 RETURN (ret);
20961 break;
20963 default:
20964 /* Unsupported internal function with arguments. */
20965 gcc_unreachable ();
20967 else if (TREE_CODE (function) == OFFSET_REF
20968 || TREE_CODE (function) == DOTSTAR_EXPR
20969 || TREE_CODE (function) == MEMBER_REF)
20970 ret = build_offset_ref_call_from_tree (function, &call_args,
20971 complain);
20972 else if (concept_check_p (function))
20974 /* FUNCTION is a template-id referring to a concept definition. */
20975 tree id = unpack_concept_check (function);
20976 tree tmpl = TREE_OPERAND (id, 0);
20977 tree args = TREE_OPERAND (id, 1);
20979 /* Calls to standard and variable concepts should have been
20980 previously diagnosed. */
20981 gcc_assert (function_concept_p (tmpl));
20983 /* Ensure the result is wrapped as a call expression. */
20984 ret = build_concept_check (tmpl, args, tf_warning_or_error);
20986 else
20987 ret = finish_call_expr (function, &call_args,
20988 /*disallow_virtual=*/qualified_p,
20989 koenig_p,
20990 complain);
20992 if (ret != error_mark_node)
20994 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20995 bool ord = CALL_EXPR_ORDERED_ARGS (t);
20996 bool rev = CALL_EXPR_REVERSE_ARGS (t);
20997 if (op || ord || rev)
20998 if (tree call = extract_call_expr (ret))
21000 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21001 CALL_EXPR_ORDERED_ARGS (call) = ord;
21002 CALL_EXPR_REVERSE_ARGS (call) = rev;
21004 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21005 /* This also suppresses -Wredundant-move. */
21006 suppress_warning (ret, OPT_Wpessimizing_move);
21009 RETURN (ret);
21012 case COND_EXPR:
21014 tree cond = RECUR (TREE_OPERAND (t, 0));
21015 cond = mark_rvalue_use (cond);
21016 tree folded_cond = fold_non_dependent_expr (cond, complain);
21017 tree exp1, exp2;
21019 if (TREE_CODE (folded_cond) == INTEGER_CST)
21021 if (integer_zerop (folded_cond))
21023 ++c_inhibit_evaluation_warnings;
21024 exp1 = RECUR (TREE_OPERAND (t, 1));
21025 --c_inhibit_evaluation_warnings;
21026 exp2 = RECUR (TREE_OPERAND (t, 2));
21028 else
21030 exp1 = RECUR (TREE_OPERAND (t, 1));
21031 ++c_inhibit_evaluation_warnings;
21032 exp2 = RECUR (TREE_OPERAND (t, 2));
21033 --c_inhibit_evaluation_warnings;
21035 cond = folded_cond;
21037 else
21039 exp1 = RECUR (TREE_OPERAND (t, 1));
21040 exp2 = RECUR (TREE_OPERAND (t, 2));
21043 warning_sentinel s(warn_duplicated_branches);
21044 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21045 cond, exp1, exp2, complain));
21048 case PSEUDO_DTOR_EXPR:
21050 tree op0 = RECUR (TREE_OPERAND (t, 0));
21051 tree op1 = RECUR (TREE_OPERAND (t, 1));
21052 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21053 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21054 input_location));
21057 case TREE_LIST:
21058 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21060 case COMPONENT_REF:
21062 tree object;
21063 tree object_type;
21064 tree member;
21065 tree r;
21067 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21068 args, complain, in_decl);
21069 /* Remember that there was a reference to this entity. */
21070 if (DECL_P (object)
21071 && !mark_used (object, complain) && !(complain & tf_error))
21072 RETURN (error_mark_node);
21073 object_type = TREE_TYPE (object);
21075 member = TREE_OPERAND (t, 1);
21076 if (BASELINK_P (member))
21077 member = tsubst_baselink (member,
21078 non_reference (TREE_TYPE (object)),
21079 args, complain, in_decl);
21080 else
21081 member = tsubst_name (member, args, complain, in_decl);
21082 if (member == error_mark_node)
21083 RETURN (error_mark_node);
21085 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21086 && TREE_CODE (member) == FIELD_DECL)
21088 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21089 RETURN (r);
21091 else if (TREE_CODE (member) == FIELD_DECL)
21093 r = finish_non_static_data_member (member, object, NULL_TREE,
21094 complain);
21095 if (TREE_CODE (r) == COMPONENT_REF)
21096 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21097 RETURN (r);
21099 else if (type_dependent_expression_p (object))
21100 /* We can't do much here. */;
21101 else if (!CLASS_TYPE_P (object_type))
21103 if (scalarish_type_p (object_type))
21105 tree s = NULL_TREE;
21106 tree dtor = member;
21108 if (TREE_CODE (dtor) == SCOPE_REF)
21110 s = TREE_OPERAND (dtor, 0);
21111 dtor = TREE_OPERAND (dtor, 1);
21113 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21115 dtor = TREE_OPERAND (dtor, 0);
21116 if (TYPE_P (dtor))
21117 RETURN (finish_pseudo_destructor_expr
21118 (object, s, dtor, input_location));
21122 else if (TREE_CODE (member) == SCOPE_REF
21123 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21125 /* Lookup the template functions now that we know what the
21126 scope is. */
21127 tree scope = TREE_OPERAND (member, 0);
21128 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21129 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21130 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21131 /*complain=*/false);
21132 if (BASELINK_P (member))
21134 BASELINK_FUNCTIONS (member)
21135 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21136 args);
21137 member = (adjust_result_of_qualified_name_lookup
21138 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21139 object_type));
21141 else
21143 qualified_name_lookup_error (scope, tmpl, member,
21144 input_location);
21145 RETURN (error_mark_node);
21148 else if (TREE_CODE (member) == SCOPE_REF
21149 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21150 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21152 if (complain & tf_error)
21154 if (TYPE_P (TREE_OPERAND (member, 0)))
21155 error ("%qT is not a class or namespace",
21156 TREE_OPERAND (member, 0));
21157 else
21158 error ("%qD is not a class or namespace",
21159 TREE_OPERAND (member, 0));
21161 RETURN (error_mark_node);
21164 r = finish_class_member_access_expr (object, member,
21165 /*template_p=*/false,
21166 complain);
21167 if (REF_PARENTHESIZED_P (t))
21168 r = force_paren_expr (r);
21169 RETURN (r);
21172 case THROW_EXPR:
21173 RETURN (build_throw
21174 (input_location, RECUR (TREE_OPERAND (t, 0))));
21176 case CONSTRUCTOR:
21178 vec<constructor_elt, va_gc> *n;
21179 constructor_elt *ce;
21180 unsigned HOST_WIDE_INT idx;
21181 bool process_index_p;
21182 int newlen;
21183 bool need_copy_p = false;
21184 tree r;
21186 tsubst_flags_t tcomplain = complain;
21187 if (COMPOUND_LITERAL_P (t))
21188 tcomplain |= tf_tst_ok;
21189 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21190 if (type == error_mark_node)
21191 RETURN (error_mark_node);
21193 /* We do not want to process the index of aggregate
21194 initializers as they are identifier nodes which will be
21195 looked up by digest_init. */
21196 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21198 if (null_member_pointer_value_p (t))
21200 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21201 RETURN (t);
21204 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21205 newlen = vec_safe_length (n);
21206 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21208 if (ce->index && process_index_p
21209 /* An identifier index is looked up in the type
21210 being initialized, not the current scope. */
21211 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21212 ce->index = RECUR (ce->index);
21214 if (PACK_EXPANSION_P (ce->value))
21216 /* Substitute into the pack expansion. */
21217 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21218 in_decl);
21220 if (ce->value == error_mark_node
21221 || PACK_EXPANSION_P (ce->value))
21223 else if (TREE_VEC_LENGTH (ce->value) == 1)
21224 /* Just move the argument into place. */
21225 ce->value = TREE_VEC_ELT (ce->value, 0);
21226 else
21228 /* Update the length of the final CONSTRUCTOR
21229 arguments vector, and note that we will need to
21230 copy.*/
21231 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21232 need_copy_p = true;
21235 else
21236 ce->value = RECUR (ce->value);
21239 if (need_copy_p)
21241 vec<constructor_elt, va_gc> *old_n = n;
21243 vec_alloc (n, newlen);
21244 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21246 if (TREE_CODE (ce->value) == TREE_VEC)
21248 int i, len = TREE_VEC_LENGTH (ce->value);
21249 for (i = 0; i < len; ++i)
21250 CONSTRUCTOR_APPEND_ELT (n, 0,
21251 TREE_VEC_ELT (ce->value, i));
21253 else
21254 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21258 r = build_constructor (init_list_type_node, n);
21259 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21260 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21261 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21263 if (TREE_HAS_CONSTRUCTOR (t))
21265 fcl_t cl = fcl_functional;
21266 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21267 cl = fcl_c99;
21268 RETURN (finish_compound_literal (type, r, complain, cl));
21271 TREE_TYPE (r) = type;
21272 RETURN (r);
21275 case TYPEID_EXPR:
21277 tree operand_0 = TREE_OPERAND (t, 0);
21278 if (TYPE_P (operand_0))
21280 operand_0 = tsubst (operand_0, args, complain, in_decl);
21281 RETURN (get_typeid (operand_0, complain));
21283 else
21285 operand_0 = RECUR (operand_0);
21286 RETURN (build_typeid (operand_0, complain));
21290 case FUNCTION_DECL:
21291 case PARM_DECL:
21292 case VAR_DECL:
21293 if (!args)
21294 RETURN (t);
21295 tree r;
21296 if (VAR_OR_FUNCTION_DECL_P (t)
21297 && DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
21298 r = tsubst_decl (t, args, complain);
21299 else if (VAR_OR_FUNCTION_DECL_P (t) && DECL_LOCAL_DECL_P (t))
21301 /* Local specialization will usually have been created when
21302 we instantiated the DECL_EXPR_DECL. */
21303 r = retrieve_local_specialization (t);
21304 if (!r)
21306 /* We're in a generic lambda referencing a local extern
21307 from an outer block-scope of a non-template. */
21308 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
21309 r = t;
21312 else if (local_variable_p (t)
21313 && ((r = retrieve_local_specialization (t))
21314 || TREE_CODE (t) == PARM_DECL
21315 || uses_template_parms (DECL_CONTEXT (t))))
21317 if (r == NULL_TREE && TREE_CODE (t) == PARM_DECL)
21319 /* We get here for a use of 'this' in an NSDMI. */
21320 if (DECL_NAME (t) == this_identifier && current_class_ptr)
21321 RETURN (current_class_ptr);
21323 /* This can happen for a parameter name used later in a function
21324 declaration (such as in a late-specified return type). Just
21325 make a dummy decl, since it's only used for its type. */
21326 gcc_assert (cp_unevaluated_operand);
21327 r = tsubst_decl (t, args, complain);
21328 /* Give it the template pattern as its context; its true context
21329 hasn't been instantiated yet and this is good enough for
21330 mangling. */
21331 DECL_CONTEXT (r) = DECL_CONTEXT (t);
21333 else if (r == NULL_TREE)
21335 /* First try name lookup to find the instantiation. */
21336 r = lookup_name (DECL_NAME (t));
21337 if (r)
21339 if (!VAR_P (r))
21341 /* During error-recovery we may find a non-variable,
21342 even an OVERLOAD: just bail out and avoid ICEs and
21343 duplicate diagnostics (c++/62207). */
21344 gcc_assert (seen_error ());
21345 RETURN (error_mark_node);
21347 if (!is_capture_proxy (r))
21349 /* Make sure the one we found is the one we want. */
21350 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
21351 if (ctx != DECL_CONTEXT (r))
21352 r = NULL_TREE;
21356 if (r)
21357 /* OK */;
21358 else
21360 /* This can happen for a variable used in a
21361 late-specified return type of a local lambda, or for a
21362 local static or constant. Building a new VAR_DECL
21363 should be OK in all those cases. */
21364 r = tsubst_decl (t, args, complain);
21365 if (local_specializations)
21366 /* Avoid infinite recursion (79640). */
21367 register_local_specialization (r, t);
21368 if (decl_maybe_constant_var_p (r))
21370 /* We can't call cp_finish_decl, so handle the
21371 initializer by hand. */
21372 tree init = tsubst_init (DECL_INITIAL (t), r, args,
21373 complain, in_decl);
21374 if (!processing_template_decl)
21375 init = maybe_constant_init (init);
21376 if (processing_template_decl
21377 ? potential_constant_expression (init)
21378 : reduced_constant_expression_p (init))
21379 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
21380 = TREE_CONSTANT (r) = true;
21381 DECL_INITIAL (r) = init;
21382 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
21383 TREE_TYPE (r)
21384 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
21385 complain, adc_variable_type);
21387 gcc_assert (cp_unevaluated_operand
21388 || processing_contract_condition
21389 || TREE_STATIC (r)
21390 || decl_constant_var_p (r)
21391 || seen_error ());
21392 if (!processing_template_decl
21393 && !TREE_STATIC (r))
21394 r = process_outer_var_ref (r, complain);
21396 /* Remember this for subsequent uses. */
21397 if (local_specializations)
21398 register_local_specialization (r, t);
21400 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
21401 r = argument_pack_select_arg (r);
21403 else
21404 r = t;
21405 if (!mark_used (r, complain))
21406 RETURN (error_mark_node);
21408 if (!no_name_lookup_flag
21409 && (TREE_CODE (t) == PARM_DECL || TREE_CODE (t) == VAR_DECL))
21411 /* ??? We're doing a subset of finish_id_expression here. */
21412 if (tree wrap = maybe_get_tls_wrapper_call (r))
21413 /* Replace an evaluated use of the thread_local variable with
21414 a call to its wrapper. */
21415 r = wrap;
21416 else if (outer_automatic_var_p (r))
21417 r = process_outer_var_ref (r, complain);
21419 if (!TYPE_REF_P (TREE_TYPE (t)))
21420 /* If the original type was a reference, we'll be wrapped in
21421 the appropriate INDIRECT_REF. */
21422 r = convert_from_reference (r);
21424 RETURN (r);
21426 case CONST_DECL:
21428 tree enum_type;
21429 tree v;
21431 if (DECL_TEMPLATE_PARM_P (t))
21432 RETURN (RECUR (DECL_INITIAL (t)));
21433 if (!uses_template_parms (DECL_CONTEXT (t)))
21434 RETURN (t);
21436 /* Unfortunately, we cannot just call lookup_name here.
21437 Consider:
21439 template <int I> int f() {
21440 enum E { a = I };
21441 struct S { void g() { E e = a; } };
21444 When we instantiate f<7>::S::g(), say, lookup_name is not
21445 clever enough to find f<7>::a. */
21446 enum_type
21447 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21448 /*entering_scope=*/0);
21450 for (v = TYPE_VALUES (enum_type);
21451 v != NULL_TREE;
21452 v = TREE_CHAIN (v))
21453 if (TREE_PURPOSE (v) == DECL_NAME (t))
21454 RETURN (TREE_VALUE (v));
21456 /* We didn't find the name. That should never happen; if
21457 name-lookup found it during preliminary parsing, we
21458 should find it again here during instantiation. */
21459 gcc_unreachable ();
21460 RETURN (t);
21463 case FIELD_DECL:
21464 if (DECL_CONTEXT (t))
21466 tree ctx;
21468 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21469 /*entering_scope=*/1);
21470 if (ctx != DECL_CONTEXT (t))
21472 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
21473 if (!r)
21475 if (complain & tf_error)
21476 error ("using invalid field %qD", t);
21477 RETURN (error_mark_node);
21479 RETURN (r);
21482 RETURN (t);
21484 case NAMESPACE_DECL:
21485 case OVERLOAD:
21486 RETURN (t);
21488 case TEMPLATE_DECL:
21489 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
21490 RETURN (tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
21491 args, complain, in_decl));
21492 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
21493 RETURN (tsubst (t, args, complain, in_decl));
21494 else if (DECL_CLASS_SCOPE_P (t)
21495 && uses_template_parms (DECL_CONTEXT (t)))
21497 /* Template template argument like the following example need
21498 special treatment:
21500 template <template <class> class TT> struct C {};
21501 template <class T> struct D {
21502 template <class U> struct E {};
21503 C<E> c; // #1
21505 D<int> d; // #2
21507 We are processing the template argument `E' in #1 for
21508 the template instantiation #2. Originally, `E' is a
21509 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
21510 have to substitute this with one having context `D<int>'. */
21512 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
21513 in_decl, /*entering_scope=*/true);
21514 RETURN (lookup_field (context, DECL_NAME(t), 0, false));
21516 else
21517 /* Ordinary template template argument. */
21518 RETURN (t);
21520 case TEMPLATE_PARM_INDEX:
21521 case TYPE_DECL:
21522 RETURN (tsubst (t, args, complain, in_decl));
21524 case CLEANUP_POINT_EXPR:
21525 /* We shouldn't have built any of these during initial template
21526 generation. Instead, they should be built during instantiation
21527 in response to the saved STMT_IS_FULL_EXPR_P setting. */
21528 gcc_unreachable ();
21530 case OFFSET_REF:
21532 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21533 tree op0 = RECUR (TREE_OPERAND (t, 0));
21534 tree op1 = RECUR (TREE_OPERAND (t, 1));
21535 r = build2 (OFFSET_REF, type, op0, op1);
21536 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
21537 if (!mark_used (TREE_OPERAND (r, 1), complain)
21538 && !(complain & tf_error))
21539 RETURN (error_mark_node);
21540 RETURN (r);
21543 case EXPR_PACK_EXPANSION:
21544 error ("invalid use of pack expansion expression");
21545 RETURN (error_mark_node);
21547 case NONTYPE_ARGUMENT_PACK:
21548 error ("use %<...%> to expand argument pack");
21549 RETURN (error_mark_node);
21551 case VOID_CST:
21552 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
21553 RETURN (t);
21555 case INTEGER_CST:
21556 case REAL_CST:
21557 case COMPLEX_CST:
21558 case VECTOR_CST:
21560 /* Instantiate any typedefs in the type. */
21561 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21562 r = fold_convert (type, t);
21563 gcc_assert (TREE_CODE (r) == TREE_CODE (t));
21564 RETURN (r);
21567 case STRING_CST:
21569 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21570 r = t;
21571 if (type != TREE_TYPE (t))
21573 r = copy_node (t);
21574 TREE_TYPE (r) = type;
21576 RETURN (r);
21579 case PTRMEM_CST:
21580 /* These can sometimes show up in a partial instantiation, but never
21581 involve template parms. */
21582 gcc_assert (!uses_template_parms (t));
21583 RETURN (t);
21585 case UNARY_LEFT_FOLD_EXPR:
21586 RETURN (tsubst_unary_left_fold (t, args, complain, in_decl));
21587 case UNARY_RIGHT_FOLD_EXPR:
21588 RETURN (tsubst_unary_right_fold (t, args, complain, in_decl));
21589 case BINARY_LEFT_FOLD_EXPR:
21590 RETURN (tsubst_binary_left_fold (t, args, complain, in_decl));
21591 case BINARY_RIGHT_FOLD_EXPR:
21592 RETURN (tsubst_binary_right_fold (t, args, complain, in_decl));
21593 case PREDICT_EXPR:
21594 RETURN (t);
21596 case DEBUG_BEGIN_STMT:
21597 /* ??? There's no point in copying it for now, but maybe some
21598 day it will contain more information, such as a pointer back
21599 to the containing function, inlined copy or so. */
21600 RETURN (t);
21602 case CO_YIELD_EXPR:
21603 RETURN (finish_co_yield_expr (input_location,
21604 RECUR (TREE_OPERAND (t, 0))));
21606 case CO_AWAIT_EXPR:
21607 RETURN (finish_co_await_expr (input_location,
21608 RECUR (TREE_OPERAND (t, 0))));
21610 case VA_ARG_EXPR:
21612 tree op0 = RECUR (TREE_OPERAND (t, 0));
21613 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21614 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21617 case OFFSETOF_EXPR:
21619 tree object_ptr
21620 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
21621 RETURN (finish_offsetof (object_ptr,
21622 RECUR (TREE_OPERAND (t, 0)),
21623 EXPR_LOCATION (t)));
21626 case ADDRESSOF_EXPR:
21627 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21628 RECUR (TREE_OPERAND (t, 0)), complain));
21630 case TRAIT_EXPR:
21632 tree type1 = TRAIT_EXPR_TYPE1 (t);
21633 if (TYPE_P (type1))
21634 type1 = tsubst (type1, args, complain, in_decl);
21635 else
21636 type1 = tsubst_expr (type1, args, complain, in_decl);
21637 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21638 complain, in_decl);
21639 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21640 TRAIT_EXPR_KIND (t), type1, type2));
21643 case STMT_EXPR:
21645 tree old_stmt_expr = cur_stmt_expr;
21646 tree stmt_expr = begin_stmt_expr ();
21648 cur_stmt_expr = stmt_expr;
21649 tsubst_stmt (STMT_EXPR_STMT (t), args, complain, in_decl);
21650 stmt_expr = finish_stmt_expr (stmt_expr, false);
21651 cur_stmt_expr = old_stmt_expr;
21653 /* If the resulting list of expression statement is empty,
21654 fold it further into void_node. */
21655 if (empty_expr_stmt_p (stmt_expr))
21656 stmt_expr = void_node;
21658 RETURN (stmt_expr);
21661 case LAMBDA_EXPR:
21663 if (complain & tf_partial)
21665 /* We don't have a full set of template arguments yet; don't touch
21666 the lambda at all. */
21667 gcc_assert (processing_template_decl);
21668 return t;
21670 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21672 RETURN (build_lambda_object (r));
21675 case TRANSACTION_EXPR:
21676 gcc_checking_assert (!TRANSACTION_EXPR_IS_STMT (t));
21677 RETURN (tsubst_stmt (t, args, complain, in_decl));
21679 case PAREN_EXPR:
21680 if (REF_PARENTHESIZED_P (t))
21681 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21682 else
21683 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21685 tree op0 = RECUR (TREE_OPERAND (t, 0));
21686 RETURN (build1_loc (input_location, PAREN_EXPR,
21687 TREE_TYPE (op0), op0));
21690 case VEC_PERM_EXPR:
21692 tree op0 = RECUR (TREE_OPERAND (t, 0));
21693 tree op1 = RECUR (TREE_OPERAND (t, 1));
21694 tree op2 = RECUR (TREE_OPERAND (t, 2));
21695 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21696 complain));
21699 case REQUIRES_EXPR:
21701 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21702 RETURN (r);
21705 case RANGE_EXPR:
21706 /* No need to substitute further, a RANGE_EXPR will always be built
21707 with constant operands. */
21708 RETURN (t);
21710 case NON_LVALUE_EXPR:
21711 case VIEW_CONVERT_EXPR:
21713 tree op = RECUR (TREE_OPERAND (t, 0));
21715 if (location_wrapper_p (t))
21716 /* We need to do this here as well as in tsubst_copy so we get the
21717 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21718 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21720 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21721 if (REF_PARENTHESIZED_P (t))
21722 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21723 RETURN (finish_parenthesized_expr (op));
21725 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21726 parameter object const. */
21727 if (TREE_TYPE (op) == NULL_TREE
21728 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21730 /* The template argument is not const, presumably because
21731 it is still dependent, and so not the const template parm
21732 object. */
21733 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21734 if (TREE_CODE (op) == CONSTRUCTOR
21735 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21737 /* Don't add a wrapper to these. */
21738 op = copy_node (op);
21739 TREE_TYPE (op) = type;
21741 else
21742 /* Do add a wrapper otherwise (in particular, if op is
21743 another TEMPLATE_PARM_INDEX). */
21744 op = build1 (VIEW_CONVERT_EXPR, type, op);
21746 RETURN (op);
21749 case ANNOTATE_EXPR:
21751 op1 = RECUR (TREE_OPERAND (t, 0));
21752 tree op2 = RECUR (TREE_OPERAND (t, 1));
21753 tree op3 = RECUR (TREE_OPERAND (t, 2));
21754 if (TREE_CODE (op2) == INTEGER_CST
21755 && wi::to_widest (op2) == (int) annot_expr_unroll_kind)
21756 op3 = cp_check_pragma_unroll (EXPR_LOCATION (TREE_OPERAND (t, 2)),
21757 op3);
21758 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
21759 TREE_TYPE (op1), op1, op2, op3));
21762 default:
21763 /* Handle Objective-C++ constructs, if appropriate. */
21764 if (tree subst = objcp_tsubst_expr (t, args, complain, in_decl))
21765 RETURN (subst);
21767 /* We shouldn't get here, but keep going if !flag_checking. */
21768 if (flag_checking)
21769 gcc_unreachable ();
21770 RETURN (t);
21773 #undef RECUR
21774 #undef RETURN
21775 out:
21776 input_location = save_loc;
21777 return retval;
21780 /* Verify that the instantiated ARGS are valid. For type arguments,
21781 make sure that the type's linkage is ok. For non-type arguments,
21782 make sure they are constants if they are integral or enumerations.
21783 Emit an error under control of COMPLAIN, and return TRUE on error. */
21785 static bool
21786 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21788 if (dependent_template_arg_p (t))
21789 return false;
21790 if (ARGUMENT_PACK_P (t))
21792 tree vec = ARGUMENT_PACK_ARGS (t);
21793 int len = TREE_VEC_LENGTH (vec);
21794 bool result = false;
21795 int i;
21797 for (i = 0; i < len; ++i)
21798 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21799 result = true;
21800 return result;
21802 else if (TYPE_P (t))
21804 /* [basic.link]: A name with no linkage (notably, the name
21805 of a class or enumeration declared in a local scope)
21806 shall not be used to declare an entity with linkage.
21807 This implies that names with no linkage cannot be used as
21808 template arguments
21810 DR 757 relaxes this restriction for C++0x. */
21811 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21812 : no_linkage_check (t, /*relaxed_p=*/false));
21814 if (nt)
21816 /* DR 488 makes use of a type with no linkage cause
21817 type deduction to fail. */
21818 if (complain & tf_error)
21820 if (TYPE_UNNAMED_P (nt))
21821 error ("%qT is/uses unnamed type", t);
21822 else
21823 error ("template argument for %qD uses local type %qT",
21824 tmpl, t);
21826 return true;
21828 /* In order to avoid all sorts of complications, we do not
21829 allow variably-modified types as template arguments. */
21830 else if (variably_modified_type_p (t, NULL_TREE))
21832 if (complain & tf_error)
21833 error ("%qT is a variably modified type", t);
21834 return true;
21837 /* Class template and alias template arguments should be OK. */
21838 else if (DECL_TYPE_TEMPLATE_P (t))
21840 /* A non-type argument of integral or enumerated type must be a
21841 constant. */
21842 else if (TREE_TYPE (t)
21843 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21844 && !REFERENCE_REF_P (t)
21845 && !TREE_CONSTANT (t))
21847 if (complain & tf_error)
21848 error ("integral expression %qE is not constant", t);
21849 return true;
21851 return false;
21854 static bool
21855 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21857 int ix, len = DECL_NTPARMS (tmpl);
21858 bool result = false;
21860 for (ix = 0; ix != len; ix++)
21862 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21863 result = true;
21865 if (result && (complain & tf_error))
21866 error (" trying to instantiate %qD", tmpl);
21867 return result;
21870 /* Call mark_used on each entity within the non-type template arguments in
21871 ARGS for an instantiation of TMPL, to ensure that each such entity is
21872 considered odr-used (and therefore marked for instantiation) regardless of
21873 whether the specialization was first formed in a template context (which
21874 inhibits mark_used).
21876 This function assumes push_to_top_level has been called beforehand. */
21878 static void
21879 mark_template_arguments_used (tree tmpl, tree args)
21881 /* It suffices to do this only when instantiating a primary template. */
21882 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21883 return;
21885 /* We already marked outer arguments when specializing the context. */
21886 args = INNERMOST_TEMPLATE_ARGS (args);
21888 for (tree arg : tree_vec_range (args))
21890 /* A (pointer/reference to) function or variable NTTP argument. */
21891 if (TREE_CODE (arg) == ADDR_EXPR
21892 || TREE_CODE (arg) == INDIRECT_REF)
21894 while (TREE_CODE (arg) == ADDR_EXPR
21895 || REFERENCE_REF_P (arg)
21896 || CONVERT_EXPR_P (arg))
21897 arg = TREE_OPERAND (arg, 0);
21898 if (VAR_OR_FUNCTION_DECL_P (arg))
21900 /* Pass tf_none to avoid duplicate diagnostics: if this call
21901 fails then an earlier call to mark_used for this argument
21902 must have also failed and emitted a diagnostic. */
21903 bool ok = mark_used (arg, tf_none);
21904 gcc_checking_assert (ok || seen_error ());
21907 /* A class NTTP argument. */
21908 else if (VAR_P (arg)
21909 && DECL_NTTP_OBJECT_P (arg))
21911 auto mark_used_r = [](tree *tp, int *, void *) {
21912 if (VAR_OR_FUNCTION_DECL_P (*tp))
21914 bool ok = mark_used (*tp, tf_none);
21915 gcc_checking_assert (ok || seen_error ());
21917 return NULL_TREE;
21919 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21920 mark_used_r, nullptr);
21925 /* We're out of SFINAE context now, so generate diagnostics for the access
21926 errors we saw earlier when instantiating D from TMPL and ARGS. */
21928 static void
21929 recheck_decl_substitution (tree d, tree tmpl, tree args)
21931 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21932 tree type = TREE_TYPE (pattern);
21933 location_t loc = input_location;
21935 push_access_scope (d);
21936 push_deferring_access_checks (dk_no_deferred);
21937 input_location = DECL_SOURCE_LOCATION (pattern);
21938 tsubst (type, args, tf_warning_or_error, d);
21939 input_location = loc;
21940 pop_deferring_access_checks ();
21941 pop_access_scope (d);
21944 /* Instantiate the indicated variable, function, or alias template TMPL with
21945 the template arguments in TARG_PTR. */
21947 tree
21948 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21950 auto_timevar tv (TV_TEMPLATE_INST);
21952 tree targ_ptr = orig_args;
21953 tree fndecl;
21954 tree gen_tmpl;
21955 bool access_ok = true;
21957 if (tmpl == error_mark_node)
21958 return error_mark_node;
21960 /* The other flags are not relevant anymore here, especially tf_partial
21961 shouldn't be set. For instance, we may be called while doing a partial
21962 substitution of a template variable, but the type of the variable
21963 template may be auto, in which case we will call do_auto_deduction
21964 in mark_used (which clears tf_partial) and the auto must be properly
21965 reduced at that time for the deduction to work. */
21966 complain &= tf_warning_or_error;
21968 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21970 if (modules_p ())
21971 lazy_load_pendings (tmpl);
21973 /* If this function is a clone, handle it specially. */
21974 if (DECL_CLONED_FUNCTION_P (tmpl))
21976 tree spec;
21977 tree clone;
21979 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21980 DECL_CLONED_FUNCTION. */
21981 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21982 targ_ptr, complain);
21983 if (spec == error_mark_node)
21984 return error_mark_node;
21986 /* Look for the clone. */
21987 FOR_EACH_CLONE (clone, spec)
21988 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21989 return clone;
21990 /* We should always have found the clone by now. */
21991 gcc_unreachable ();
21992 return NULL_TREE;
21995 if (targ_ptr == error_mark_node)
21996 return error_mark_node;
21998 /* Check to see if we already have this specialization. */
21999 gen_tmpl = most_general_template (tmpl);
22000 if (TMPL_ARGS_DEPTH (targ_ptr)
22001 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22002 /* targ_ptr only has the innermost template args, so add the outer ones
22003 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22004 the case of a non-dependent call within a template definition). */
22005 targ_ptr = (add_outermost_template_args
22006 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22007 targ_ptr));
22009 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
22010 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
22012 gcc_checking_assert (tmpl == gen_tmpl
22013 || ((fndecl
22014 = retrieve_specialization (tmpl, orig_args, 0))
22015 == spec)
22016 || fndecl == NULL_TREE);
22018 if (spec != NULL_TREE)
22020 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22022 if (complain & tf_error)
22023 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22024 return error_mark_node;
22026 return spec;
22029 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22030 complain))
22031 return error_mark_node;
22033 /* We are building a FUNCTION_DECL, during which the access of its
22034 parameters and return types have to be checked. However this
22035 FUNCTION_DECL which is the desired context for access checking
22036 is not built yet. We solve this chicken-and-egg problem by
22037 deferring all checks until we have the FUNCTION_DECL. */
22038 push_deferring_access_checks (dk_deferred);
22040 /* Instantiation of the function happens in the context of the function
22041 template, not the context of the overload resolution we're doing. */
22042 push_to_top_level ();
22043 /* If there are dependent arguments, e.g. because we're doing partial
22044 ordering, make sure processing_template_decl stays set. */
22045 if (uses_template_parms (targ_ptr))
22046 ++processing_template_decl;
22047 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22049 tree ctx;
22050 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22051 /* If the context of the partially instantiated template is
22052 already non-dependent, then we might as well use it. */
22053 ctx = DECL_CONTEXT (tmpl);
22054 else
22055 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22056 complain, gen_tmpl, true);
22057 push_nested_class (ctx);
22060 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22062 tree partial_ti = NULL_TREE;
22063 fndecl = NULL_TREE;
22064 if (VAR_P (pattern))
22066 /* We need to determine if we're using a partial or explicit
22067 specialization now, because the type of the variable could be
22068 different. */
22069 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22070 partial_ti = most_specialized_partial_spec (tid, complain);
22071 if (partial_ti == error_mark_node)
22072 pattern = error_mark_node;
22073 else if (partial_ti)
22075 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22076 tree partial_args = TI_ARGS (partial_ti);
22077 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22078 fndecl = tsubst_decl (partial_pat, partial_args, complain,
22079 /*use_spec_table=*/false);
22083 /* Substitute template parameters to obtain the specialization. */
22084 if (fndecl == NULL_TREE)
22085 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
22086 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22087 pop_nested_class ();
22088 pop_from_top_level ();
22090 if (fndecl == error_mark_node)
22092 pop_deferring_access_checks ();
22093 return error_mark_node;
22096 /* The DECL_TI_TEMPLATE should always be the immediate parent
22097 template, not the most general template. */
22098 DECL_TI_TEMPLATE (fndecl) = tmpl;
22099 DECL_TI_ARGS (fndecl) = targ_ptr;
22100 if (VAR_P (pattern))
22101 /* Now that we we've formed this variable template specialization,
22102 remember the result of most_specialized_partial_spec for it. */
22103 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22105 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
22106 if (fndecl == error_mark_node)
22107 return error_mark_node;
22109 set_instantiating_module (fndecl);
22111 /* Now we know the specialization, compute access previously
22112 deferred. Do no access control for inheriting constructors,
22113 as we already checked access for the inherited constructor. */
22114 if (!(flag_new_inheriting_ctors
22115 && DECL_INHERITED_CTOR (fndecl)))
22117 push_access_scope (fndecl);
22118 if (!perform_deferred_access_checks (complain))
22119 access_ok = false;
22120 pop_access_scope (fndecl);
22122 pop_deferring_access_checks ();
22124 /* If we've just instantiated the main entry point for a function,
22125 instantiate all the alternate entry points as well. We do this
22126 by cloning the instantiation of the main entry point, not by
22127 instantiating the template clones. */
22128 if (tree chain = DECL_CHAIN (gen_tmpl))
22129 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22130 clone_cdtor (fndecl, /*update_methods=*/false);
22132 if (!access_ok)
22134 if (!(complain & tf_error))
22136 /* Remember to reinstantiate when we're out of SFINAE so the user
22137 can see the errors. */
22138 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22140 return error_mark_node;
22143 return fndecl;
22146 /* Instantiate the alias template TMPL with ARGS. Also push a template
22147 instantiation level, which instantiate_template doesn't do because
22148 functions and variables have sufficient context established by the
22149 callers. */
22151 static tree
22152 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22154 if (tmpl == error_mark_node || args == error_mark_node)
22155 return error_mark_node;
22157 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22158 args, tmpl, complain);
22159 if (args == error_mark_node)
22160 return error_mark_node;
22162 /* FIXME check for satisfaction in check_instantiated_args. */
22163 if (!constraints_satisfied_p (tmpl, args))
22165 if (complain & tf_error)
22167 auto_diagnostic_group d;
22168 error ("template constraint failure for %qD", tmpl);
22169 diagnose_constraints (input_location, tmpl, args);
22171 return error_mark_node;
22174 if (!push_tinst_level (tmpl, args))
22175 return error_mark_node;
22176 tree r = instantiate_template (tmpl, args, complain);
22177 pop_tinst_level ();
22179 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22181 /* An alias template specialization can be dependent
22182 even if its underlying type is not. */
22183 TYPE_DEPENDENT_P (d) = true;
22184 TYPE_DEPENDENT_P_VALID (d) = true;
22185 /* Sometimes a dependent alias spec is equivalent to its expansion,
22186 sometimes not. So always use structural_comptypes. */
22187 SET_TYPE_STRUCTURAL_EQUALITY (d);
22190 return r;
22193 /* PARM is a template parameter pack for FN. Returns true iff
22194 PARM is used in a deducible way in the argument list of FN. */
22196 static bool
22197 pack_deducible_p (tree parm, tree fn)
22199 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22200 for (; t; t = TREE_CHAIN (t))
22202 tree type = TREE_VALUE (t);
22203 tree packs;
22204 if (!PACK_EXPANSION_P (type))
22205 continue;
22206 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22207 packs; packs = TREE_CHAIN (packs))
22208 if (template_args_equal (TREE_VALUE (packs), parm))
22210 /* The template parameter pack is used in a function parameter
22211 pack. If this is the end of the parameter list, the
22212 template parameter pack is deducible. */
22213 if (TREE_CHAIN (t) == void_list_node)
22214 return true;
22215 else
22216 /* Otherwise, not. Well, it could be deduced from
22217 a non-pack parameter, but doing so would end up with
22218 a deduction mismatch, so don't bother. */
22219 return false;
22222 /* The template parameter pack isn't used in any function parameter
22223 packs, but it might be used deeper, e.g. tuple<Args...>. */
22224 return true;
22227 /* Subroutine of fn_type_unification: check non-dependent parms for
22228 convertibility. */
22230 static int
22231 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22232 tree fn, unification_kind_t strict, int flags,
22233 struct conversion **convs, bool explain_p,
22234 bool noninst_only_p)
22236 /* Non-constructor methods need to leave a conversion for 'this', which
22237 isn't included in nargs here. */
22238 unsigned offset = (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
22239 && !DECL_CONSTRUCTOR_P (fn));
22241 for (unsigned ia = 0;
22242 parms && parms != void_list_node && ia < nargs; )
22244 tree parm = TREE_VALUE (parms);
22246 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22247 && (!TREE_CHAIN (parms)
22248 || TREE_CHAIN (parms) == void_list_node))
22249 /* For a function parameter pack that occurs at the end of the
22250 parameter-declaration-list, the type A of each remaining
22251 argument of the call is compared with the type P of the
22252 declarator-id of the function parameter pack. */
22253 break;
22255 parms = TREE_CHAIN (parms);
22257 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22258 /* For a function parameter pack that does not occur at the
22259 end of the parameter-declaration-list, the type of the
22260 parameter pack is a non-deduced context. */
22261 continue;
22263 if (!uses_template_parms (parm))
22265 tree arg = args[ia];
22266 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22267 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22269 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22270 conv_p, explain_p, noninst_only_p))
22271 return 1;
22274 ++ia;
22277 return 0;
22280 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22281 NARGS elements of the arguments that are being used when calling
22282 it. TARGS is a vector into which the deduced template arguments
22283 are placed.
22285 Returns either a FUNCTION_DECL for the matching specialization of FN or
22286 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22287 true, diagnostics will be printed to explain why it failed.
22289 If FN is a conversion operator, or we are trying to produce a specific
22290 specialization, RETURN_TYPE is the return type desired.
22292 The EXPLICIT_TARGS are explicit template arguments provided via a
22293 template-id.
22295 The parameter STRICT is one of:
22297 DEDUCE_CALL:
22298 We are deducing arguments for a function call, as in
22299 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22300 deducing arguments for a call to the result of a conversion
22301 function template, as in [over.call.object].
22303 DEDUCE_CONV:
22304 We are deducing arguments for a conversion function, as in
22305 [temp.deduct.conv].
22307 DEDUCE_EXACT:
22308 We are deducing arguments when doing an explicit instantiation
22309 as in [temp.explicit], when determining an explicit specialization
22310 as in [temp.expl.spec], or when taking the address of a function
22311 template, as in [temp.deduct.funcaddr]. */
22313 tree
22314 fn_type_unification (tree fn,
22315 tree explicit_targs,
22316 tree targs,
22317 const tree *args,
22318 unsigned int nargs,
22319 tree return_type,
22320 unification_kind_t strict,
22321 int flags,
22322 struct conversion **convs,
22323 bool explain_p,
22324 bool decltype_p)
22326 tree parms;
22327 tree fntype;
22328 tree decl = NULL_TREE;
22329 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22330 bool ok;
22331 static int deduction_depth;
22332 /* type_unification_real will pass back any access checks from default
22333 template argument substitution. */
22334 vec<deferred_access_check, va_gc> *checks = NULL;
22335 /* We don't have all the template args yet. */
22336 bool incomplete = true;
22338 tree orig_fn = fn;
22339 if (flag_new_inheriting_ctors)
22340 fn = strip_inheriting_ctors (fn);
22342 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22343 tree r = error_mark_node;
22345 tree full_targs = targs;
22346 if (TMPL_ARGS_DEPTH (targs)
22347 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22348 full_targs = (add_outermost_template_args
22349 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22350 targs));
22352 if (decltype_p)
22353 complain |= tf_decltype;
22355 /* In C++0x, it's possible to have a function template whose type depends
22356 on itself recursively. This is most obvious with decltype, but can also
22357 occur with enumeration scope (c++/48969). So we need to catch infinite
22358 recursion and reject the substitution at deduction time; this function
22359 will return error_mark_node for any repeated substitution.
22361 This also catches excessive recursion such as when f<N> depends on
22362 f<N-1> across all integers, and returns error_mark_node for all the
22363 substitutions back up to the initial one.
22365 This is, of course, not reentrant. */
22366 if (excessive_deduction_depth)
22367 return error_mark_node;
22368 ++deduction_depth;
22370 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22372 fntype = TREE_TYPE (fn);
22373 if (explicit_targs)
22375 /* [temp.deduct]
22377 The specified template arguments must match the template
22378 parameters in kind (i.e., type, nontype, template), and there
22379 must not be more arguments than there are parameters;
22380 otherwise type deduction fails.
22382 Nontype arguments must match the types of the corresponding
22383 nontype template parameters, or must be convertible to the
22384 types of the corresponding nontype parameters as specified in
22385 _temp.arg.nontype_, otherwise type deduction fails.
22387 All references in the function type of the function template
22388 to the corresponding template parameters are replaced by the
22389 specified template argument values. If a substitution in a
22390 template parameter or in the function type of the function
22391 template results in an invalid type, type deduction fails. */
22392 int i, len = TREE_VEC_LENGTH (tparms);
22393 location_t loc = input_location;
22394 incomplete = false;
22396 if (explicit_targs == error_mark_node)
22397 goto fail;
22399 if (TMPL_ARGS_DEPTH (explicit_targs)
22400 < TMPL_ARGS_DEPTH (full_targs))
22401 explicit_targs = add_outermost_template_args (full_targs,
22402 explicit_targs);
22404 /* Adjust any explicit template arguments before entering the
22405 substitution context. */
22406 explicit_targs
22407 = (coerce_template_parms (tparms, explicit_targs, fn,
22408 complain|tf_partial,
22409 /*require_all_args=*/false));
22410 if (explicit_targs == error_mark_node)
22411 goto fail;
22413 /* Substitute the explicit args into the function type. This is
22414 necessary so that, for instance, explicitly declared function
22415 arguments can match null pointed constants. If we were given
22416 an incomplete set of explicit args, we must not do semantic
22417 processing during substitution as we could create partial
22418 instantiations. */
22419 for (i = 0; i < len; i++)
22421 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22422 bool parameter_pack = false;
22423 tree targ = TREE_VEC_ELT (explicit_targs, i);
22425 /* Dig out the actual parm. */
22426 if (TREE_CODE (parm) == TYPE_DECL
22427 || TREE_CODE (parm) == TEMPLATE_DECL)
22429 parm = TREE_TYPE (parm);
22430 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22432 else if (TREE_CODE (parm) == PARM_DECL)
22434 parm = DECL_INITIAL (parm);
22435 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22438 if (targ == NULL_TREE)
22439 /* No explicit argument for this template parameter. */
22440 incomplete = true;
22441 else if (parameter_pack && pack_deducible_p (parm, fn))
22443 /* Mark the argument pack as "incomplete". We could
22444 still deduce more arguments during unification.
22445 We remove this mark in type_unification_real. */
22446 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22447 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22448 = ARGUMENT_PACK_ARGS (targ);
22450 /* We have some incomplete argument packs. */
22451 incomplete = true;
22455 if (incomplete)
22457 if (!push_tinst_level (fn, explicit_targs))
22459 excessive_deduction_depth = true;
22460 goto fail;
22462 ++processing_template_decl;
22463 input_location = DECL_SOURCE_LOCATION (fn);
22464 /* Ignore any access checks; we'll see them again in
22465 instantiate_template and they might have the wrong
22466 access path at this point. */
22467 push_deferring_access_checks (dk_deferred);
22468 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22469 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22470 pop_deferring_access_checks ();
22471 input_location = loc;
22472 --processing_template_decl;
22473 pop_tinst_level ();
22475 if (fntype == error_mark_node)
22476 goto fail;
22479 /* Place the explicitly specified arguments in TARGS. */
22480 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22481 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22482 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22483 if (!incomplete && CHECKING_P
22484 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22485 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22486 (targs, NUM_TMPL_ARGS (explicit_targs));
22489 if (return_type && strict != DEDUCE_CALL)
22491 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22492 new_args[0] = return_type;
22493 memcpy (new_args + 1, args, nargs * sizeof (tree));
22494 args = new_args;
22495 ++nargs;
22498 if (!incomplete)
22499 goto deduced;
22501 /* Never do unification on the 'this' parameter. */
22502 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22504 if (return_type && strict == DEDUCE_CALL)
22506 /* We're deducing for a call to the result of a template conversion
22507 function. The parms we really want are in return_type. */
22508 if (INDIRECT_TYPE_P (return_type))
22509 return_type = TREE_TYPE (return_type);
22510 parms = TYPE_ARG_TYPES (return_type);
22512 else if (return_type)
22514 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22517 /* We allow incomplete unification without an error message here
22518 because the standard doesn't seem to explicitly prohibit it. Our
22519 callers must be ready to deal with unification failures in any
22520 event. */
22522 /* If we aren't explaining yet, push tinst context so we can see where
22523 any errors (e.g. from class instantiations triggered by instantiation
22524 of default template arguments) come from. If we are explaining, this
22525 context is redundant. */
22526 if (!explain_p && !push_tinst_level (fn, targs))
22528 excessive_deduction_depth = true;
22529 goto fail;
22532 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22533 full_targs, parms, args, nargs, /*subr=*/0,
22534 strict, &checks, explain_p);
22535 if (!explain_p)
22536 pop_tinst_level ();
22537 if (!ok)
22538 goto fail;
22540 /* Now that we have bindings for all of the template arguments,
22541 ensure that the arguments deduced for the template template
22542 parameters have compatible template parameter lists. We cannot
22543 check this property before we have deduced all template
22544 arguments, because the template parameter types of a template
22545 template parameter might depend on prior template parameters
22546 deduced after the template template parameter. The following
22547 ill-formed example illustrates this issue:
22549 template<typename T, template<T> class C> void f(C<5>, T);
22551 template<int N> struct X {};
22553 void g() {
22554 f(X<5>(), 5l); // error: template argument deduction fails
22557 The template parameter list of 'C' depends on the template type
22558 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22559 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22560 time that we deduce 'C'. */
22561 if (!template_template_parm_bindings_ok_p
22562 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22564 unify_inconsistent_template_template_parameters (explain_p);
22565 goto fail;
22568 deduced:
22570 /* As a refinement of CWG2369, check first and foremost non-dependent
22571 conversions that we know are not going to induce template instantiation
22572 (PR99599). */
22573 if (strict == DEDUCE_CALL
22574 && incomplete
22575 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22576 convs, explain_p,
22577 /*noninst_only_p=*/true))
22578 goto fail;
22580 /* CWG2369: Check satisfaction before non-deducible conversions. */
22581 if (!constraints_satisfied_p (fn, targs))
22583 if (explain_p)
22584 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22585 goto fail;
22588 /* DR 1391: All parameters have args, now check non-dependent parms for
22589 convertibility. We don't do this if all args were explicitly specified,
22590 as the standard says that we substitute explicit args immediately. */
22591 if (incomplete
22592 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22593 convs, explain_p,
22594 /*noninst_only_p=*/false))
22595 goto fail;
22597 /* All is well so far. Now, check:
22599 [temp.deduct]
22601 When all template arguments have been deduced, all uses of
22602 template parameters in nondeduced contexts are replaced with
22603 the corresponding deduced argument values. If the
22604 substitution results in an invalid type, as described above,
22605 type deduction fails. */
22606 if (!push_tinst_level (fn, targs))
22608 excessive_deduction_depth = true;
22609 goto fail;
22612 /* Also collect access checks from the instantiation. */
22613 reopen_deferring_access_checks (checks);
22615 decl = instantiate_template (fn, targs, complain);
22617 checks = get_deferred_access_checks ();
22618 pop_deferring_access_checks ();
22620 pop_tinst_level ();
22622 if (decl == error_mark_node)
22623 goto fail;
22625 /* Now perform any access checks encountered during substitution. */
22626 push_access_scope (decl);
22627 ok = perform_access_checks (checks, complain);
22628 pop_access_scope (decl);
22629 if (!ok)
22630 goto fail;
22632 /* If we're looking for an exact match, check that what we got
22633 is indeed an exact match. It might not be if some template
22634 parameters are used in non-deduced contexts. But don't check
22635 for an exact match if we have dependent template arguments;
22636 in that case we're doing partial ordering, and we already know
22637 that we have two candidates that will provide the actual type. */
22638 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22640 tree substed = TREE_TYPE (decl);
22641 unsigned int i;
22643 tree sarg
22644 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22645 if (return_type)
22646 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22647 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22648 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22650 unify_type_mismatch (explain_p, args[i],
22651 TREE_VALUE (sarg));
22652 goto fail;
22654 if ((i < nargs || sarg)
22655 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22656 doesn't contain the trailing void, and conv fns are always (). */
22657 && !DECL_CONV_FN_P (decl))
22659 unsigned nsargs = i + list_length (sarg);
22660 unify_arity (explain_p, nargs, nsargs);
22661 goto fail;
22665 /* After doing deduction with the inherited constructor, actually return an
22666 instantiation of the inheriting constructor. */
22667 if (orig_fn != fn)
22668 decl = instantiate_template (orig_fn, targs, complain);
22670 r = decl;
22672 fail:
22673 --deduction_depth;
22674 if (excessive_deduction_depth)
22676 if (deduction_depth == 0)
22677 /* Reset once we're all the way out. */
22678 excessive_deduction_depth = false;
22681 return r;
22684 /* Returns true iff PARM is a forwarding reference in the context of
22685 template argument deduction for TMPL. */
22687 static bool
22688 forwarding_reference_p (tree parm, tree tmpl)
22690 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22691 cv-unqualified template parameter ..." */
22692 if (TYPE_REF_P (parm)
22693 && TYPE_REF_IS_RVALUE (parm)
22694 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22695 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22697 parm = TREE_TYPE (parm);
22698 /* [temp.deduct.call], "... that does not represent a template parameter
22699 of a class template (during class template argument deduction)." */
22700 if (tmpl
22701 && deduction_guide_p (tmpl)
22702 && DECL_ARTIFICIAL (tmpl))
22704 /* Since the template parameters of a synthesized guide consist of
22705 the template parameters of the class template followed by those of
22706 the constructor (if any), we can tell if PARM represents a template
22707 parameter of the class template by comparing its index with the
22708 arity of the class template. */
22709 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22710 if (TEMPLATE_TYPE_IDX (parm)
22711 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22712 return false;
22714 return true;
22716 return false;
22719 /* Adjust types before performing type deduction, as described in
22720 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22721 sections are symmetric. PARM is the type of a function parameter
22722 or the return type of the conversion function. ARG is the type of
22723 the argument passed to the call, or the type of the value
22724 initialized with the result of the conversion function.
22725 ARG_EXPR is the original argument expression, which may be null. */
22727 static int
22728 maybe_adjust_types_for_deduction (tree tparms,
22729 unification_kind_t strict,
22730 tree* parm,
22731 tree* arg,
22732 tree arg_expr)
22734 int result = 0;
22736 switch (strict)
22738 case DEDUCE_CALL:
22739 break;
22741 case DEDUCE_CONV:
22742 /* [temp.deduct.conv] First remove a reference type on parm.
22743 DRs 322 & 976 affected this. */
22744 if (TYPE_REF_P (*parm))
22745 *parm = TREE_TYPE (*parm);
22747 /* Swap PARM and ARG throughout the remainder of this
22748 function; the handling is precisely symmetric since PARM
22749 will initialize ARG rather than vice versa. */
22750 std::swap (parm, arg);
22752 break;
22754 case DEDUCE_EXACT:
22755 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22756 too, but here handle it by stripping the reference from PARM
22757 rather than by adding it to ARG. */
22758 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22759 && TYPE_REF_P (*arg)
22760 && !TYPE_REF_IS_RVALUE (*arg))
22761 *parm = TREE_TYPE (*parm);
22762 /* Nothing else to do in this case. */
22763 return 0;
22765 default:
22766 gcc_unreachable ();
22769 if (!TYPE_REF_P (*parm))
22771 /* [temp.deduct.call]
22773 If P is not a reference type:
22775 --If A is an array type, the pointer type produced by the
22776 array-to-pointer standard conversion (_conv.array_) is
22777 used in place of A for type deduction; otherwise,
22779 --If A is a function type, the pointer type produced by
22780 the function-to-pointer standard conversion
22781 (_conv.func_) is used in place of A for type deduction;
22782 otherwise,
22784 --If A is a cv-qualified type, the top level
22785 cv-qualifiers of A's type are ignored for type
22786 deduction. */
22787 if (TREE_CODE (*arg) == ARRAY_TYPE)
22788 *arg = build_pointer_type (TREE_TYPE (*arg));
22789 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22790 *arg = build_pointer_type (*arg);
22791 else
22792 *arg = TYPE_MAIN_VARIANT (*arg);
22795 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22796 an lvalue, the type 'lvalue reference to A' is used in place of A for
22797 type deduction." */
22798 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22799 && (arg_expr ? lvalue_p (arg_expr)
22800 /* try_one_overload doesn't provide an arg_expr, but
22801 functions are always lvalues. */
22802 : TREE_CODE (*arg) == FUNCTION_TYPE))
22803 *arg = build_reference_type (*arg);
22805 /* [temp.deduct.call]
22807 If P is a cv-qualified type, the top level cv-qualifiers
22808 of P's type are ignored for type deduction. If P is a
22809 reference type, the type referred to by P is used for
22810 type deduction. */
22811 *parm = TYPE_MAIN_VARIANT (*parm);
22812 if (TYPE_REF_P (*parm))
22814 *parm = TREE_TYPE (*parm);
22815 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22818 return result;
22821 /* Return true if computing a conversion from FROM to TO might induce template
22822 instantiation. Conversely, if this predicate returns false then computing
22823 the conversion definitely won't induce template instantiation. */
22825 static bool
22826 conversion_may_instantiate_p (tree to, tree from)
22828 to = non_reference (to);
22829 from = non_reference (from);
22831 bool ptr_conv_p = false;
22832 if (TYPE_PTR_P (to)
22833 && TYPE_PTR_P (from))
22835 to = TREE_TYPE (to);
22836 from = TREE_TYPE (from);
22837 ptr_conv_p = true;
22840 /* If one of the types is a not-yet-instantiated class template
22841 specialization, then computing the conversion might instantiate
22842 it in order to inspect bases, conversion functions and/or
22843 converting constructors. */
22844 if ((CLASS_TYPE_P (to)
22845 && !COMPLETE_TYPE_P (to)
22846 && CLASSTYPE_TEMPLATE_INSTANTIATION (to))
22847 || (CLASS_TYPE_P (from)
22848 && !COMPLETE_TYPE_P (from)
22849 && CLASSTYPE_TEMPLATE_INSTANTIATION (from)))
22850 return true;
22852 /* Converting from one pointer type to another, or between
22853 reference-related types, always yields a standard conversion. */
22854 if (ptr_conv_p || reference_related_p (to, from))
22855 return false;
22857 /* Converting to a non-aggregate class type will consider its
22858 user-declared constructors, which might induce instantiation. */
22859 if (CLASS_TYPE_P (to)
22860 && CLASSTYPE_NON_AGGREGATE (to))
22861 return true;
22863 /* Similarly, converting from a class type will consider its conversion
22864 functions. */
22865 if (CLASS_TYPE_P (from)
22866 && TYPE_HAS_CONVERSION (from))
22867 return true;
22869 /* Otherwise, computing this conversion definitely won't induce
22870 template instantiation. */
22871 return false;
22874 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22875 template which doesn't contain any deducible template parameters; check if
22876 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22877 unify_one_argument. */
22879 static int
22880 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22881 int flags, struct conversion **conv_p,
22882 bool explain_p, bool noninst_only_p)
22884 tree type;
22886 if (!TYPE_P (arg))
22887 type = TREE_TYPE (arg);
22888 else
22889 type = arg;
22891 if (same_type_p (parm, type))
22892 return unify_success (explain_p);
22894 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22895 if (strict == DEDUCE_CONV)
22897 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22898 return unify_success (explain_p);
22900 else if (strict == DEDUCE_CALL)
22902 if (conv_p && *conv_p)
22904 /* This conversion was already computed earlier (when
22905 computing only non-instantiating conversions). */
22906 gcc_checking_assert (!noninst_only_p);
22907 return unify_success (explain_p);
22910 if (noninst_only_p
22911 && conversion_may_instantiate_p (parm, type))
22912 return unify_success (explain_p);
22914 bool ok = false;
22915 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22916 if (conv_p)
22917 /* Avoid recalculating this in add_function_candidate. */
22918 ok = (*conv_p
22919 = good_conversion (parm, type, conv_arg, flags, complain));
22920 else
22921 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22922 if (ok)
22923 return unify_success (explain_p);
22926 if (strict == DEDUCE_EXACT)
22927 return unify_type_mismatch (explain_p, parm, arg);
22928 else
22929 return unify_arg_conversion (explain_p, parm, type, arg);
22932 static bool uses_deducible_template_parms (tree type);
22934 /* Returns true iff the expression EXPR is one from which a template
22935 argument can be deduced. In other words, if it's an undecorated
22936 use of a template non-type parameter. */
22938 static bool
22939 deducible_expression (tree expr)
22941 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22942 while (CONVERT_EXPR_P (expr)
22943 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22944 || REFERENCE_REF_P (expr))
22945 expr = TREE_OPERAND (expr, 0);
22946 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22949 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22950 deducible way; that is, if it has a max value of <PARM> - 1. */
22952 static bool
22953 deducible_array_bound (tree domain)
22955 if (domain == NULL_TREE)
22956 return false;
22958 tree max = TYPE_MAX_VALUE (domain);
22959 if (TREE_CODE (max) != MINUS_EXPR)
22960 return false;
22962 return deducible_expression (TREE_OPERAND (max, 0));
22965 /* Returns true iff the template arguments ARGS use a template parameter
22966 in a deducible way. */
22968 static bool
22969 deducible_template_args (tree args)
22971 for (tree elt : tree_vec_range (args))
22973 bool deducible;
22974 if (ARGUMENT_PACK_P (elt))
22975 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22976 else
22978 if (PACK_EXPANSION_P (elt))
22979 elt = PACK_EXPANSION_PATTERN (elt);
22980 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22981 deducible = true;
22982 else if (TYPE_P (elt))
22983 deducible = uses_deducible_template_parms (elt);
22984 else
22985 deducible = deducible_expression (elt);
22987 if (deducible)
22988 return true;
22990 return false;
22993 /* Returns true iff TYPE contains any deducible references to template
22994 parameters, as per 14.8.2.5. */
22996 static bool
22997 uses_deducible_template_parms (tree type)
22999 if (PACK_EXPANSION_P (type))
23000 type = PACK_EXPANSION_PATTERN (type);
23002 /* T
23003 cv-list T
23004 TT<T>
23005 TT<i>
23006 TT<> */
23007 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
23008 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
23009 return true;
23011 /* T*
23013 T&& */
23014 if (INDIRECT_TYPE_P (type))
23015 return uses_deducible_template_parms (TREE_TYPE (type));
23017 /* T[integer-constant ]
23018 type [i] */
23019 if (TREE_CODE (type) == ARRAY_TYPE)
23020 return (uses_deducible_template_parms (TREE_TYPE (type))
23021 || deducible_array_bound (TYPE_DOMAIN (type)));
23023 /* T type ::*
23024 type T::*
23025 T T::*
23026 T (type ::*)()
23027 type (T::*)()
23028 type (type ::*)(T)
23029 type (T::*)(T)
23030 T (type ::*)(T)
23031 T (T::*)()
23032 T (T::*)(T) */
23033 if (TYPE_PTRMEM_P (type))
23034 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
23035 || (uses_deducible_template_parms
23036 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
23038 /* template-name <T> (where template-name refers to a class template)
23039 template-name <i> (where template-name refers to a class template) */
23040 if (CLASS_TYPE_P (type)
23041 && CLASSTYPE_TEMPLATE_INFO (type)
23042 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
23043 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
23044 (CLASSTYPE_TI_ARGS (type)));
23046 /* type (T)
23048 T(T) */
23049 if (FUNC_OR_METHOD_TYPE_P (type))
23051 if (uses_deducible_template_parms (TREE_TYPE (type)))
23052 return true;
23053 tree parm = TYPE_ARG_TYPES (type);
23054 if (TREE_CODE (type) == METHOD_TYPE)
23055 parm = TREE_CHAIN (parm);
23056 for (; parm; parm = TREE_CHAIN (parm))
23057 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23058 return true;
23059 if (flag_noexcept_type
23060 && TYPE_RAISES_EXCEPTIONS (type)
23061 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23062 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23063 return true;
23066 return false;
23069 /* Subroutine of type_unification_real and unify_pack_expansion to
23070 handle unification of a single P/A pair. Parameters are as
23071 for those functions. */
23073 static int
23074 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23075 int subr, unification_kind_t strict,
23076 bool explain_p)
23078 tree arg_expr = NULL_TREE;
23079 int arg_strict;
23081 if (arg == error_mark_node || parm == error_mark_node)
23082 return unify_invalid (explain_p);
23083 if (arg == unknown_type_node)
23084 /* We can't deduce anything from this, but we might get all the
23085 template args from other function args. */
23086 return unify_success (explain_p);
23088 /* Implicit conversions (Clause 4) will be performed on a function
23089 argument to convert it to the type of the corresponding function
23090 parameter if the parameter type contains no template-parameters that
23091 participate in template argument deduction. */
23092 if (strict != DEDUCE_EXACT
23093 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23094 /* For function parameters with no deducible template parameters,
23095 just return. We'll check non-dependent conversions later. */
23096 return unify_success (explain_p);
23098 switch (strict)
23100 case DEDUCE_CALL:
23101 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23102 | UNIFY_ALLOW_MORE_CV_QUAL
23103 | UNIFY_ALLOW_DERIVED);
23104 break;
23106 case DEDUCE_CONV:
23107 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23108 break;
23110 case DEDUCE_EXACT:
23111 arg_strict = UNIFY_ALLOW_NONE;
23112 break;
23114 default:
23115 gcc_unreachable ();
23118 /* We only do these transformations if this is the top-level
23119 parameter_type_list in a call or declaration matching; in other
23120 situations (nested function declarators, template argument lists) we
23121 won't be comparing a type to an expression, and we don't do any type
23122 adjustments. */
23123 if (!subr)
23125 if (!TYPE_P (arg))
23127 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23128 if (type_unknown_p (arg))
23130 /* [temp.deduct.type] A template-argument can be
23131 deduced from a pointer to function or pointer
23132 to member function argument if the set of
23133 overloaded functions does not contain function
23134 templates and at most one of a set of
23135 overloaded functions provides a unique
23136 match. */
23137 resolve_overloaded_unification (tparms, targs, parm,
23138 arg, strict,
23139 arg_strict, explain_p);
23140 /* If a unique match was not found, this is a
23141 non-deduced context, so we still succeed. */
23142 return unify_success (explain_p);
23145 arg_expr = arg;
23146 arg = unlowered_expr_type (arg);
23147 if (arg == error_mark_node)
23148 return unify_invalid (explain_p);
23151 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23152 &parm, &arg, arg_expr);
23154 else
23155 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23156 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23157 return unify_template_argument_mismatch (explain_p, parm, arg);
23159 /* For deduction from an init-list we need the actual list. */
23160 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23161 arg = arg_expr;
23162 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23165 /* for_each_template_parm callback that always returns 0. */
23167 static int
23168 zero_r (tree, void *)
23170 return 0;
23173 /* for_each_template_parm any_fn callback to handle deduction of a template
23174 type argument from the type of an array bound. */
23176 static int
23177 array_deduction_r (tree t, void *data)
23179 tree_pair_p d = (tree_pair_p)data;
23180 tree &tparms = d->purpose;
23181 tree &targs = d->value;
23183 if (TREE_CODE (t) == ARRAY_TYPE)
23184 if (tree dom = TYPE_DOMAIN (t))
23185 if (tree max = TYPE_MAX_VALUE (dom))
23187 if (TREE_CODE (max) == MINUS_EXPR)
23188 max = TREE_OPERAND (max, 0);
23189 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23190 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23191 UNIFY_ALLOW_NONE, /*explain*/false);
23194 /* Keep walking. */
23195 return 0;
23198 /* Try to deduce any not-yet-deduced template type arguments from the type of
23199 an array bound. This is handled separately from unify because 14.8.2.5 says
23200 "The type of a type parameter is only deduced from an array bound if it is
23201 not otherwise deduced." */
23203 static void
23204 try_array_deduction (tree tparms, tree targs, tree parm)
23206 tree_pair_s data = { tparms, targs };
23207 hash_set<tree> visited;
23208 for_each_template_parm (parm, zero_r, &data, &visited,
23209 /*nondeduced*/false, array_deduction_r);
23212 /* Most parms like fn_type_unification.
23214 If SUBR is 1, we're being called recursively (to unify the
23215 arguments of a function or method parameter of a function
23216 template).
23218 CHECKS is a pointer to a vector of access checks encountered while
23219 substituting default template arguments. */
23221 static int
23222 type_unification_real (tree tparms,
23223 tree full_targs,
23224 tree xparms,
23225 const tree *xargs,
23226 unsigned int xnargs,
23227 int subr,
23228 unification_kind_t strict,
23229 vec<deferred_access_check, va_gc> **checks,
23230 bool explain_p)
23232 tree parm, arg;
23233 int i;
23234 int ntparms = TREE_VEC_LENGTH (tparms);
23235 int saw_undeduced = 0;
23236 tree parms;
23237 const tree *args;
23238 unsigned int nargs;
23239 unsigned int ia;
23241 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23242 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23243 gcc_assert (ntparms > 0);
23245 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23247 /* Reset the number of non-defaulted template arguments contained
23248 in TARGS. */
23249 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23251 again:
23252 parms = xparms;
23253 args = xargs;
23254 nargs = xnargs;
23256 /* Only fn_type_unification cares about terminal void. */
23257 if (nargs && args[nargs-1] == void_type_node)
23258 --nargs;
23260 ia = 0;
23261 while (parms && parms != void_list_node
23262 && ia < nargs)
23264 parm = TREE_VALUE (parms);
23266 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23267 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23268 /* For a function parameter pack that occurs at the end of the
23269 parameter-declaration-list, the type A of each remaining
23270 argument of the call is compared with the type P of the
23271 declarator-id of the function parameter pack. */
23272 break;
23274 parms = TREE_CHAIN (parms);
23276 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23277 /* For a function parameter pack that does not occur at the
23278 end of the parameter-declaration-list, the type of the
23279 parameter pack is a non-deduced context. */
23280 continue;
23282 arg = args[ia];
23283 ++ia;
23285 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23286 explain_p))
23287 return 1;
23290 if (parms
23291 && parms != void_list_node
23292 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23294 /* Unify the remaining arguments with the pack expansion type. */
23295 tree argvec;
23296 tree parmvec = make_tree_vec (1);
23298 /* Allocate a TREE_VEC and copy in all of the arguments */
23299 argvec = make_tree_vec (nargs - ia);
23300 for (i = 0; ia < nargs; ++ia, ++i)
23301 TREE_VEC_ELT (argvec, i) = args[ia];
23303 /* Copy the parameter into parmvec. */
23304 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23305 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23306 /*subr=*/subr, explain_p))
23307 return 1;
23309 /* Advance to the end of the list of parameters. */
23310 parms = TREE_CHAIN (parms);
23313 /* Fail if we've reached the end of the parm list, and more args
23314 are present, and the parm list isn't variadic. */
23315 if (ia < nargs && parms == void_list_node)
23316 return unify_too_many_arguments (explain_p, nargs, ia);
23317 /* Fail if parms are left and they don't have default values and
23318 they aren't all deduced as empty packs (c++/57397). This is
23319 consistent with sufficient_parms_p. */
23320 if (parms && parms != void_list_node
23321 && TREE_PURPOSE (parms) == NULL_TREE)
23323 unsigned int count = nargs;
23324 tree p = parms;
23325 bool type_pack_p;
23328 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23329 if (!type_pack_p)
23330 count++;
23331 p = TREE_CHAIN (p);
23333 while (p && p != void_list_node);
23334 if (count != nargs)
23335 return unify_too_few_arguments (explain_p, ia, count,
23336 type_pack_p);
23339 if (!subr)
23341 tsubst_flags_t complain = (explain_p
23342 ? tf_warning_or_error
23343 : tf_none);
23344 bool tried_array_deduction = (cxx_dialect < cxx17);
23346 for (i = 0; i < ntparms; i++)
23348 tree targ = TREE_VEC_ELT (targs, i);
23349 tree tparm = TREE_VEC_ELT (tparms, i);
23351 /* Clear the "incomplete" flags on all argument packs now so that
23352 substituting them into later default arguments works. */
23353 if (targ && ARGUMENT_PACK_P (targ))
23355 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23356 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23359 if (targ || tparm == error_mark_node)
23360 continue;
23361 tparm = TREE_VALUE (tparm);
23363 if (TREE_CODE (tparm) == TYPE_DECL
23364 && !tried_array_deduction)
23366 try_array_deduction (tparms, targs, xparms);
23367 tried_array_deduction = true;
23368 if (TREE_VEC_ELT (targs, i))
23369 continue;
23372 /* If this is an undeduced nontype parameter that depends on
23373 a type parameter, try another pass; its type may have been
23374 deduced from a later argument than the one from which
23375 this parameter can be deduced. */
23376 if (TREE_CODE (tparm) == PARM_DECL
23377 && !is_auto (TREE_TYPE (tparm))
23378 && uses_template_parms (TREE_TYPE (tparm))
23379 && saw_undeduced < 2)
23381 saw_undeduced = 1;
23382 continue;
23385 /* Core issue #226 (C++0x) [temp.deduct]:
23387 If a template argument has not been deduced, its
23388 default template argument, if any, is used.
23390 When we are in C++98 mode, TREE_PURPOSE will either
23391 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23392 to explicitly check cxx_dialect here. */
23393 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23394 /* OK, there is a default argument. Wait until after the
23395 conversion check to do substitution. */
23396 continue;
23398 /* If the type parameter is a parameter pack, then it will
23399 be deduced to an empty parameter pack. */
23400 if (template_parameter_pack_p (tparm))
23402 tree arg;
23404 if (TREE_CODE (tparm) == PARM_DECL)
23406 arg = make_node (NONTYPE_ARGUMENT_PACK);
23407 TREE_CONSTANT (arg) = 1;
23409 else
23410 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23412 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23414 TREE_VEC_ELT (targs, i) = arg;
23415 continue;
23418 return unify_parameter_deduction_failure (explain_p, tparm);
23421 /* During partial ordering, we deduce dependent template args. */
23422 bool any_dependent_targs = false;
23424 /* Now substitute into the default template arguments. */
23425 for (i = 0; i < ntparms; i++)
23427 tree targ = TREE_VEC_ELT (targs, i);
23428 tree tparm = TREE_VEC_ELT (tparms, i);
23430 if (targ)
23432 if (!any_dependent_targs && dependent_template_arg_p (targ))
23433 any_dependent_targs = true;
23434 continue;
23436 if (tparm == error_mark_node)
23437 continue;
23439 tree parm = TREE_VALUE (tparm);
23440 tree arg = TREE_PURPOSE (tparm);
23441 reopen_deferring_access_checks (*checks);
23442 location_t save_loc = input_location;
23443 if (DECL_P (parm))
23444 input_location = DECL_SOURCE_LOCATION (parm);
23446 if (saw_undeduced == 1
23447 && TREE_CODE (parm) == PARM_DECL
23448 && !is_auto (TREE_TYPE (parm))
23449 && uses_template_parms (TREE_TYPE (parm)))
23451 /* The type of this non-type parameter depends on undeduced
23452 parameters. Don't try to use its default argument yet,
23453 since we might deduce an argument for it on the next pass,
23454 but do check whether the arguments we already have cause
23455 substitution failure, so that that happens before we try
23456 later default arguments (78489). */
23457 ++processing_template_decl;
23458 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23459 NULL_TREE);
23460 --processing_template_decl;
23461 if (type == error_mark_node)
23462 arg = error_mark_node;
23463 else
23464 arg = NULL_TREE;
23466 else
23468 /* Even if the call is happening in template context, getting
23469 here means it's non-dependent, and a default argument is
23470 considered a separate definition under [temp.decls], so we can
23471 do this substitution without processing_template_decl. This
23472 is important if the default argument contains something that
23473 might be instantiation-dependent like access (87480). */
23474 processing_template_decl_sentinel s (!any_dependent_targs);
23475 tree substed = NULL_TREE;
23476 if (saw_undeduced == 1 && !any_dependent_targs)
23478 /* First instatiate in template context, in case we still
23479 depend on undeduced template parameters. */
23480 ++processing_template_decl;
23481 substed = tsubst_template_arg (arg, full_targs, complain,
23482 NULL_TREE);
23483 --processing_template_decl;
23484 if (substed != error_mark_node
23485 && !uses_template_parms (substed))
23486 /* We replaced all the tparms, substitute again out of
23487 template context. */
23488 substed = NULL_TREE;
23490 if (!substed)
23491 substed = tsubst_template_arg (arg, full_targs, complain,
23492 NULL_TREE);
23494 if (!uses_template_parms (substed))
23495 arg = convert_template_argument (parm, substed, full_targs,
23496 complain, i, NULL_TREE);
23497 else if (saw_undeduced == 1)
23498 arg = NULL_TREE;
23499 else if (!any_dependent_targs)
23500 arg = error_mark_node;
23503 input_location = save_loc;
23504 *checks = get_deferred_access_checks ();
23505 pop_deferring_access_checks ();
23507 if (arg == error_mark_node)
23508 return 1;
23509 else if (arg)
23511 TREE_VEC_ELT (targs, i) = arg;
23512 /* The position of the first default template argument,
23513 is also the number of non-defaulted arguments in TARGS.
23514 Record that. */
23515 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23516 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23520 if (saw_undeduced++ == 1)
23521 goto again;
23524 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23525 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23527 return unify_success (explain_p);
23530 /* Subroutine of type_unification_real. Args are like the variables
23531 at the call site. ARG is an overloaded function (or template-id);
23532 we try deducing template args from each of the overloads, and if
23533 only one succeeds, we go with that. Modifies TARGS and returns
23534 true on success. */
23536 static bool
23537 resolve_overloaded_unification (tree tparms,
23538 tree targs,
23539 tree parm,
23540 tree arg,
23541 unification_kind_t strict,
23542 int sub_strict,
23543 bool explain_p)
23545 tree tempargs = copy_node (targs);
23546 int good = 0;
23547 tree goodfn = NULL_TREE;
23548 bool addr_p;
23550 if (TREE_CODE (arg) == ADDR_EXPR)
23552 arg = TREE_OPERAND (arg, 0);
23553 addr_p = true;
23555 else
23556 addr_p = false;
23558 if (TREE_CODE (arg) == COMPONENT_REF)
23559 /* Handle `&x' where `x' is some static or non-static member
23560 function name. */
23561 arg = TREE_OPERAND (arg, 1);
23563 if (TREE_CODE (arg) == OFFSET_REF)
23564 arg = TREE_OPERAND (arg, 1);
23566 /* Strip baselink information. */
23567 if (BASELINK_P (arg))
23568 arg = BASELINK_FUNCTIONS (arg);
23570 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23572 /* If we got some explicit template args, we need to plug them into
23573 the affected templates before we try to unify, in case the
23574 explicit args will completely resolve the templates in question. */
23576 int ok = 0;
23577 tree expl_subargs = TREE_OPERAND (arg, 1);
23578 arg = TREE_OPERAND (arg, 0);
23580 for (lkp_iterator iter (arg); iter; ++iter)
23582 tree fn = *iter;
23583 tree subargs, elem;
23585 if (TREE_CODE (fn) != TEMPLATE_DECL)
23586 continue;
23588 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23589 expl_subargs, NULL_TREE, tf_none);
23590 if (subargs != error_mark_node
23591 && !any_dependent_template_arguments_p (subargs))
23593 fn = instantiate_template (fn, subargs, tf_none);
23594 if (!constraints_satisfied_p (fn))
23595 continue;
23596 if (undeduced_auto_decl (fn))
23598 /* Instantiate the function to deduce its return type. */
23599 ++function_depth;
23600 instantiate_decl (fn, /*defer*/false, /*class*/false);
23601 --function_depth;
23604 if (flag_noexcept_type)
23605 maybe_instantiate_noexcept (fn, tf_none);
23607 elem = TREE_TYPE (fn);
23608 if (try_one_overload (tparms, targs, tempargs, parm,
23609 elem, strict, sub_strict, addr_p, explain_p)
23610 && (!goodfn || !same_type_p (goodfn, elem)))
23612 goodfn = elem;
23613 ++good;
23616 else if (subargs)
23617 ++ok;
23619 /* If no templates (or more than one) are fully resolved by the
23620 explicit arguments, this template-id is a non-deduced context; it
23621 could still be OK if we deduce all template arguments for the
23622 enclosing call through other arguments. */
23623 if (good != 1)
23624 good = ok;
23626 else if (!OVL_P (arg))
23627 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23628 -- but the deduction does not succeed because the expression is
23629 not just the function on its own. */
23630 return false;
23631 else
23632 for (lkp_iterator iter (arg); iter; ++iter)
23634 tree fn = *iter;
23635 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23636 strict, sub_strict, addr_p, explain_p)
23637 && (!goodfn || !decls_match (goodfn, fn)))
23639 goodfn = fn;
23640 ++good;
23644 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23645 to function or pointer to member function argument if the set of
23646 overloaded functions does not contain function templates and at most
23647 one of a set of overloaded functions provides a unique match.
23649 So if we found multiple possibilities, we return success but don't
23650 deduce anything. */
23652 if (good == 1)
23654 int i = TREE_VEC_LENGTH (targs);
23655 for (; i--; )
23656 if (TREE_VEC_ELT (tempargs, i))
23658 tree old = TREE_VEC_ELT (targs, i);
23659 tree new_ = TREE_VEC_ELT (tempargs, i);
23660 if (new_ && old && ARGUMENT_PACK_P (old)
23661 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23662 /* Don't forget explicit template arguments in a pack. */
23663 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23664 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23665 TREE_VEC_ELT (targs, i) = new_;
23668 if (good)
23669 return true;
23671 return false;
23674 /* Core DR 115: In contexts where deduction is done and fails, or in
23675 contexts where deduction is not done, if a template argument list is
23676 specified and it, along with any default template arguments, identifies
23677 a single function template specialization, then the template-id is an
23678 lvalue for the function template specialization. */
23680 tree
23681 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23683 tree expr, offset, baselink;
23684 bool addr;
23686 if (!type_unknown_p (orig_expr))
23687 return orig_expr;
23689 expr = orig_expr;
23690 addr = false;
23691 offset = NULL_TREE;
23692 baselink = NULL_TREE;
23694 if (TREE_CODE (expr) == ADDR_EXPR)
23696 expr = TREE_OPERAND (expr, 0);
23697 addr = true;
23699 if (TREE_CODE (expr) == OFFSET_REF)
23701 offset = expr;
23702 expr = TREE_OPERAND (expr, 1);
23704 if (BASELINK_P (expr))
23706 baselink = expr;
23707 expr = BASELINK_FUNCTIONS (expr);
23710 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23712 int good = 0;
23713 tree goodfn = NULL_TREE;
23715 /* If we got some explicit template args, we need to plug them into
23716 the affected templates before we try to unify, in case the
23717 explicit args will completely resolve the templates in question. */
23719 tree expl_subargs = TREE_OPERAND (expr, 1);
23720 tree arg = TREE_OPERAND (expr, 0);
23721 tree badfn = NULL_TREE;
23722 tree badargs = NULL_TREE;
23724 for (lkp_iterator iter (arg); iter; ++iter)
23726 tree fn = *iter;
23727 tree subargs, elem;
23729 if (TREE_CODE (fn) != TEMPLATE_DECL)
23730 continue;
23732 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23733 expl_subargs, NULL_TREE, tf_none);
23734 if (subargs != error_mark_node
23735 && !any_dependent_template_arguments_p (subargs))
23737 elem = instantiate_template (fn, subargs, tf_none);
23738 if (elem == error_mark_node)
23740 badfn = fn;
23741 badargs = subargs;
23743 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23744 && constraints_satisfied_p (elem))
23746 goodfn = elem;
23747 ++good;
23751 if (good == 1)
23753 mark_used (goodfn);
23754 expr = goodfn;
23755 if (baselink)
23756 expr = build_baselink (BASELINK_BINFO (baselink),
23757 BASELINK_ACCESS_BINFO (baselink),
23758 expr, BASELINK_OPTYPE (baselink));
23759 if (offset)
23761 tree base
23762 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23763 expr = build_offset_ref (base, expr, addr, complain);
23765 if (addr)
23766 expr = cp_build_addr_expr (expr, complain);
23767 return expr;
23769 else if (good == 0 && badargs && (complain & tf_error))
23770 /* There were no good options and at least one bad one, so let the
23771 user know what the problem is. */
23772 instantiate_template (badfn, badargs, complain);
23774 return orig_expr;
23777 /* As above, but error out if the expression remains overloaded. */
23779 tree
23780 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23782 exp = resolve_nondeduced_context (exp, complain);
23783 if (type_unknown_p (exp))
23785 if (complain & tf_error)
23786 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23787 return error_mark_node;
23789 return exp;
23792 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23793 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23794 different overloads deduce different arguments for a given parm.
23795 ADDR_P is true if the expression for which deduction is being
23796 performed was of the form "& fn" rather than simply "fn".
23798 Returns 1 on success. */
23800 static int
23801 try_one_overload (tree tparms,
23802 tree orig_targs,
23803 tree targs,
23804 tree parm,
23805 tree arg,
23806 unification_kind_t strict,
23807 int sub_strict,
23808 bool addr_p,
23809 bool explain_p)
23811 int nargs;
23812 tree tempargs;
23813 int i;
23815 if (arg == error_mark_node)
23816 return 0;
23818 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23819 to function or pointer to member function argument if the set of
23820 overloaded functions does not contain function templates and at most
23821 one of a set of overloaded functions provides a unique match.
23823 So if this is a template, just return success. */
23825 if (uses_template_parms (arg))
23826 return 1;
23828 if (TREE_CODE (arg) == METHOD_TYPE)
23829 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23830 else if (addr_p)
23831 arg = build_pointer_type (arg);
23833 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23834 &parm, &arg, NULL_TREE);
23836 /* We don't copy orig_targs for this because if we have already deduced
23837 some template args from previous args, unify would complain when we
23838 try to deduce a template parameter for the same argument, even though
23839 there isn't really a conflict. */
23840 nargs = TREE_VEC_LENGTH (targs);
23841 tempargs = make_tree_vec (nargs);
23843 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23844 return 0;
23846 /* First make sure we didn't deduce anything that conflicts with
23847 explicitly specified args. */
23848 for (i = nargs; i--; )
23850 tree elt = TREE_VEC_ELT (tempargs, i);
23851 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23853 if (!elt)
23854 /*NOP*/;
23855 else if (uses_template_parms (elt))
23856 /* Since we're unifying against ourselves, we will fill in
23857 template args used in the function parm list with our own
23858 template parms. Discard them. */
23859 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23860 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23862 /* Check that the argument at each index of the deduced argument pack
23863 is equivalent to the corresponding explicitly specified argument.
23864 We may have deduced more arguments than were explicitly specified,
23865 and that's OK. */
23867 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23868 that's wrong if we deduce the same argument pack from multiple
23869 function arguments: it's only incomplete the first time. */
23871 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23872 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23874 if (TREE_VEC_LENGTH (deduced_pack)
23875 < TREE_VEC_LENGTH (explicit_pack))
23876 return 0;
23878 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23879 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23880 TREE_VEC_ELT (deduced_pack, j)))
23881 return 0;
23883 else if (oldelt && !template_args_equal (oldelt, elt))
23884 return 0;
23887 for (i = nargs; i--; )
23889 tree elt = TREE_VEC_ELT (tempargs, i);
23891 if (elt)
23892 TREE_VEC_ELT (targs, i) = elt;
23895 return 1;
23898 /* PARM is a template class (perhaps with unbound template
23899 parameters). ARG is a fully instantiated type. If ARG can be
23900 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23901 TARGS are as for unify. */
23903 static tree
23904 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23905 bool explain_p)
23907 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23908 return NULL_TREE;
23909 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23910 /* Matches anything. */;
23911 else if (CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
23912 return NULL_TREE;
23914 /* We need to make a new template argument vector for the call to
23915 unify. If we used TARGS, we'd clutter it up with the result of
23916 the attempted unification, even if this class didn't work out.
23917 We also don't want to commit ourselves to all the unifications
23918 we've already done, since unification is supposed to be done on
23919 an argument-by-argument basis. In other words, consider the
23920 following pathological case:
23922 template <int I, int J, int K>
23923 struct S {};
23925 template <int I, int J>
23926 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23928 template <int I, int J, int K>
23929 void f(S<I, J, K>, S<I, I, I>);
23931 void g() {
23932 S<0, 0, 0> s0;
23933 S<0, 1, 2> s2;
23935 f(s0, s2);
23938 Now, by the time we consider the unification involving `s2', we
23939 already know that we must have `f<0, 0, 0>'. But, even though
23940 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23941 because there are two ways to unify base classes of S<0, 1, 2>
23942 with S<I, I, I>. If we kept the already deduced knowledge, we
23943 would reject the possibility I=1. */
23944 targs = copy_template_args (targs);
23945 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23946 targ = NULL_TREE;
23948 int err;
23949 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23950 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23951 else
23952 err = unify (tparms, targs,
23953 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
23954 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (arg)),
23955 UNIFY_ALLOW_NONE, explain_p);
23957 return err ? NULL_TREE : arg;
23960 /* Given a template type PARM and a class type ARG, find the unique
23961 base type in ARG that is an instance of PARM. We do not examine
23962 ARG itself; only its base-classes. If there is not exactly one
23963 appropriate base class, return NULL_TREE. PARM may be the type of
23964 a partial specialization, as well as a plain template type. Used
23965 by unify. */
23967 static enum template_base_result
23968 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23969 bool explain_p, tree *result)
23971 tree rval = NULL_TREE;
23972 tree binfo;
23974 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23976 binfo = TYPE_BINFO (complete_type (arg));
23977 if (!binfo)
23979 /* The type could not be completed. */
23980 *result = NULL_TREE;
23981 return tbr_incomplete_type;
23984 /* Walk in inheritance graph order. The search order is not
23985 important, and this avoids multiple walks of virtual bases. */
23986 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23988 tree r = try_class_unification (tparms, targs, parm,
23989 BINFO_TYPE (binfo), explain_p);
23991 if (r)
23993 /* If there is more than one satisfactory baseclass, then:
23995 [temp.deduct.call]
23997 If they yield more than one possible deduced A, the type
23998 deduction fails.
24000 applies. */
24001 if (rval && !same_type_p (r, rval))
24003 /* [temp.deduct.call]/4.3: If there is a class C that is a
24004 (direct or indirect) base class of D and derived (directly or
24005 indirectly) from a class B and that would be a valid deduced
24006 A, the deduced A cannot be B or pointer to B, respectively. */
24007 if (DERIVED_FROM_P (r, rval))
24008 /* Ignore r. */
24009 continue;
24010 else if (DERIVED_FROM_P (rval, r))
24011 /* Ignore rval. */;
24012 else
24014 *result = NULL_TREE;
24015 return tbr_ambiguous_baseclass;
24019 rval = r;
24023 *result = rval;
24024 return tbr_success;
24027 /* Returns the level of DECL, which declares a template parameter. */
24029 static int
24030 template_decl_level (tree decl)
24032 switch (TREE_CODE (decl))
24034 case TYPE_DECL:
24035 case TEMPLATE_DECL:
24036 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
24038 case PARM_DECL:
24039 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
24041 default:
24042 gcc_unreachable ();
24044 return 0;
24047 /* Decide whether ARG can be unified with PARM, considering only the
24048 cv-qualifiers of each type, given STRICT as documented for unify.
24049 Returns nonzero iff the unification is OK on that basis. */
24051 static int
24052 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24054 int arg_quals = cp_type_quals (arg);
24055 int parm_quals = cp_type_quals (parm);
24057 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24058 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24060 /* Although a CVR qualifier is ignored when being applied to a
24061 substituted template parameter ([8.3.2]/1 for example), that
24062 does not allow us to unify "const T" with "int&" because both
24063 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24064 It is ok when we're allowing additional CV qualifiers
24065 at the outer level [14.8.2.1]/3,1st bullet. */
24066 if ((TYPE_REF_P (arg)
24067 || FUNC_OR_METHOD_TYPE_P (arg))
24068 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24069 return 0;
24071 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24072 && (parm_quals & TYPE_QUAL_RESTRICT))
24073 return 0;
24076 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24077 && (arg_quals & parm_quals) != parm_quals)
24078 return 0;
24080 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24081 && (parm_quals & arg_quals) != arg_quals)
24082 return 0;
24084 return 1;
24087 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24088 void
24089 template_parm_level_and_index (tree parm, int* level, int* index)
24091 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24092 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24093 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24095 *index = TEMPLATE_TYPE_IDX (parm);
24096 *level = TEMPLATE_TYPE_LEVEL (parm);
24098 else
24100 *index = TEMPLATE_PARM_IDX (parm);
24101 *level = TEMPLATE_PARM_LEVEL (parm);
24105 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24106 do { \
24107 if (unify (TP, TA, P, A, S, EP)) \
24108 return 1; \
24109 } while (0)
24111 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24112 expansion at the end of PACKED_PARMS. Returns 0 if the type
24113 deduction succeeds, 1 otherwise. STRICT is the same as in
24114 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24115 function call argument list. We'll need to adjust the arguments to make them
24116 types. SUBR tells us if this is from a recursive call to
24117 type_unification_real, or for comparing two template argument
24118 lists. */
24120 static int
24121 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24122 tree packed_args, unification_kind_t strict,
24123 bool subr, bool explain_p)
24125 tree parm
24126 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24127 tree pattern = PACK_EXPANSION_PATTERN (parm);
24128 tree pack, packs = NULL_TREE;
24129 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24131 /* Add in any args remembered from an earlier partial instantiation. */
24132 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24133 int levels = TMPL_ARGS_DEPTH (targs);
24135 packed_args = expand_template_argument_pack (packed_args);
24137 int len = TREE_VEC_LENGTH (packed_args);
24139 /* Determine the parameter packs we will be deducing from the
24140 pattern, and record their current deductions. */
24141 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24142 pack; pack = TREE_CHAIN (pack))
24144 tree parm_pack = TREE_VALUE (pack);
24145 int idx, level;
24147 /* Only template parameter packs can be deduced, not e.g. function
24148 parameter packs or __bases or __integer_pack. */
24149 if (!TEMPLATE_PARM_P (parm_pack))
24150 continue;
24152 /* Determine the index and level of this parameter pack. */
24153 template_parm_level_and_index (parm_pack, &level, &idx);
24154 if (level > levels)
24155 continue;
24157 /* Keep track of the parameter packs and their corresponding
24158 argument packs. */
24159 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24160 TREE_TYPE (packs) = make_tree_vec (len - start);
24163 /* Loop through all of the arguments that have not yet been
24164 unified and unify each with the pattern. */
24165 for (i = start; i < len; i++)
24167 tree parm;
24168 bool any_explicit = false;
24169 tree arg = TREE_VEC_ELT (packed_args, i);
24171 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24172 or the element of its argument pack at the current index if
24173 this argument was explicitly specified. */
24174 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24176 int idx, level;
24177 tree arg, pargs;
24178 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24180 arg = NULL_TREE;
24181 if (TREE_VALUE (pack)
24182 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24183 && (i - start < TREE_VEC_LENGTH (pargs)))
24185 any_explicit = true;
24186 arg = TREE_VEC_ELT (pargs, i - start);
24188 TMPL_ARG (targs, level, idx) = arg;
24191 /* If we had explicit template arguments, substitute them into the
24192 pattern before deduction. */
24193 if (any_explicit)
24195 /* Some arguments might still be unspecified or dependent. */
24196 bool dependent;
24197 ++processing_template_decl;
24198 dependent = any_dependent_template_arguments_p (targs);
24199 if (!dependent)
24200 --processing_template_decl;
24201 parm = tsubst (pattern, targs,
24202 explain_p ? tf_warning_or_error : tf_none,
24203 NULL_TREE);
24204 if (dependent)
24205 --processing_template_decl;
24206 if (parm == error_mark_node)
24207 return 1;
24209 else
24210 parm = pattern;
24212 /* Unify the pattern with the current argument. */
24213 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24214 explain_p))
24215 return 1;
24217 /* For each parameter pack, collect the deduced value. */
24218 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24220 int idx, level;
24221 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24223 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24224 TMPL_ARG (targs, level, idx);
24228 /* Verify that the results of unification with the parameter packs
24229 produce results consistent with what we've seen before, and make
24230 the deduced argument packs available. */
24231 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24233 tree old_pack = TREE_VALUE (pack);
24234 tree new_args = TREE_TYPE (pack);
24235 int i, len = TREE_VEC_LENGTH (new_args);
24236 int idx, level;
24237 bool nondeduced_p = false;
24239 /* By default keep the original deduced argument pack.
24240 If necessary, more specific code is going to update the
24241 resulting deduced argument later down in this function. */
24242 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24243 TMPL_ARG (targs, level, idx) = old_pack;
24245 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24246 actually deduce anything. */
24247 for (i = 0; i < len && !nondeduced_p; ++i)
24248 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24249 nondeduced_p = true;
24250 if (nondeduced_p)
24251 continue;
24253 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24255 /* If we had fewer function args than explicit template args,
24256 just use the explicits. */
24257 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24258 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24259 if (len < explicit_len)
24260 new_args = explicit_args;
24263 if (!old_pack)
24265 tree result;
24266 /* Build the deduced *_ARGUMENT_PACK. */
24267 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24269 result = make_node (NONTYPE_ARGUMENT_PACK);
24270 TREE_CONSTANT (result) = 1;
24272 else
24273 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24275 ARGUMENT_PACK_ARGS (result) = new_args;
24277 /* Note the deduced argument packs for this parameter
24278 pack. */
24279 TMPL_ARG (targs, level, idx) = result;
24281 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24282 && (ARGUMENT_PACK_ARGS (old_pack)
24283 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24285 /* We only had the explicitly-provided arguments before, but
24286 now we have a complete set of arguments. */
24287 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24289 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24290 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24291 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24293 else
24295 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24296 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24297 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24298 /* During template argument deduction for the aggregate deduction
24299 candidate, the number of elements in a trailing parameter pack
24300 is only deduced from the number of remaining function
24301 arguments if it is not otherwise deduced. */
24302 if (cxx_dialect >= cxx20
24303 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24304 /* FIXME This isn't set properly for partial instantiations. */
24305 && TPARMS_PRIMARY_TEMPLATE (tparms)
24306 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24307 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24308 if (!comp_template_args (old_args, new_args,
24309 &bad_old_arg, &bad_new_arg))
24310 /* Inconsistent unification of this parameter pack. */
24311 return unify_parameter_pack_inconsistent (explain_p,
24312 bad_old_arg,
24313 bad_new_arg);
24317 return unify_success (explain_p);
24320 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24321 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24322 parameters and return value are as for unify. */
24324 static int
24325 unify_array_domain (tree tparms, tree targs,
24326 tree parm_dom, tree arg_dom,
24327 bool explain_p)
24329 tree parm_max;
24330 tree arg_max;
24331 bool parm_cst;
24332 bool arg_cst;
24334 /* Our representation of array types uses "N - 1" as the
24335 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24336 not an integer constant. We cannot unify arbitrarily
24337 complex expressions, so we eliminate the MINUS_EXPRs
24338 here. */
24339 parm_max = TYPE_MAX_VALUE (parm_dom);
24340 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24341 if (!parm_cst)
24343 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24344 parm_max = TREE_OPERAND (parm_max, 0);
24346 arg_max = TYPE_MAX_VALUE (arg_dom);
24347 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24348 if (!arg_cst)
24350 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24351 trying to unify the type of a variable with the type
24352 of a template parameter. For example:
24354 template <unsigned int N>
24355 void f (char (&) [N]);
24356 int g();
24357 void h(int i) {
24358 char a[g(i)];
24359 f(a);
24362 Here, the type of the ARG will be "int [g(i)]", and
24363 may be a SAVE_EXPR, etc. */
24364 if (TREE_CODE (arg_max) != MINUS_EXPR)
24365 return unify_vla_arg (explain_p, arg_dom);
24366 arg_max = TREE_OPERAND (arg_max, 0);
24369 /* If only one of the bounds used a MINUS_EXPR, compensate
24370 by adding one to the other bound. */
24371 if (parm_cst && !arg_cst)
24372 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24373 integer_type_node,
24374 parm_max,
24375 integer_one_node);
24376 else if (arg_cst && !parm_cst)
24377 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24378 integer_type_node,
24379 arg_max,
24380 integer_one_node);
24382 return unify (tparms, targs, parm_max, arg_max,
24383 UNIFY_ALLOW_INTEGER, explain_p);
24386 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24388 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24390 static pa_kind_t
24391 pa_kind (tree t)
24393 if (PACK_EXPANSION_P (t))
24394 t = PACK_EXPANSION_PATTERN (t);
24395 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24396 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24397 || DECL_TYPE_TEMPLATE_P (t))
24398 return pa_tmpl;
24399 else if (TYPE_P (t))
24400 return pa_type;
24401 else
24402 return pa_expr;
24405 /* Deduce the value of template parameters. TPARMS is the (innermost)
24406 set of template parameters to a template. TARGS is the bindings
24407 for those template parameters, as determined thus far; TARGS may
24408 include template arguments for outer levels of template parameters
24409 as well. PARM is a parameter to a template function, or a
24410 subcomponent of that parameter; ARG is the corresponding argument.
24411 This function attempts to match PARM with ARG in a manner
24412 consistent with the existing assignments in TARGS. If more values
24413 are deduced, then TARGS is updated.
24415 Returns 0 if the type deduction succeeds, 1 otherwise. The
24416 parameter STRICT is a bitwise or of the following flags:
24418 UNIFY_ALLOW_NONE:
24419 Require an exact match between PARM and ARG.
24420 UNIFY_ALLOW_MORE_CV_QUAL:
24421 Allow the deduced ARG to be more cv-qualified (by qualification
24422 conversion) than ARG.
24423 UNIFY_ALLOW_LESS_CV_QUAL:
24424 Allow the deduced ARG to be less cv-qualified than ARG.
24425 UNIFY_ALLOW_DERIVED:
24426 Allow the deduced ARG to be a template base class of ARG,
24427 or a pointer to a template base class of the type pointed to by
24428 ARG.
24429 UNIFY_ALLOW_INTEGER:
24430 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24431 case for more information.
24432 UNIFY_ALLOW_OUTER_LEVEL:
24433 This is the outermost level of a deduction. Used to determine validity
24434 of qualification conversions. A valid qualification conversion must
24435 have const qualified pointers leading up to the inner type which
24436 requires additional CV quals, except at the outer level, where const
24437 is not required [conv.qual]. It would be normal to set this flag in
24438 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24439 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24440 This is the outermost level of a deduction, and PARM can be more CV
24441 qualified at this point.
24442 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24443 This is the outermost level of a deduction, and PARM can be less CV
24444 qualified at this point. */
24446 static int
24447 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24448 bool explain_p)
24450 int idx;
24451 tree targ;
24452 tree tparm;
24453 int strict_in = strict;
24454 tsubst_flags_t complain = (explain_p
24455 ? tf_warning_or_error
24456 : tf_none);
24458 /* I don't think this will do the right thing with respect to types.
24459 But the only case I've seen it in so far has been array bounds, where
24460 signedness is the only information lost, and I think that will be
24461 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24462 finish_id_expression_1, and are also OK. */
24463 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24464 parm = TREE_OPERAND (parm, 0);
24466 if (arg == error_mark_node)
24467 return unify_invalid (explain_p);
24468 if (arg == unknown_type_node
24469 || arg == init_list_type_node)
24470 /* We can't deduce anything from this, but we might get all the
24471 template args from other function args. */
24472 return unify_success (explain_p);
24474 if (parm == any_targ_node || arg == any_targ_node)
24475 return unify_success (explain_p);
24477 /* If PARM uses template parameters, then we can't bail out here,
24478 even if ARG == PARM, since we won't record unifications for the
24479 template parameters. We might need them if we're trying to
24480 figure out which of two things is more specialized. */
24481 if (arg == parm
24482 && (DECL_P (parm) || !uses_template_parms (parm)))
24483 return unify_success (explain_p);
24485 /* Handle init lists early, so the rest of the function can assume
24486 we're dealing with a type. */
24487 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24489 tree elttype;
24490 tree orig_parm = parm;
24492 if (!is_std_init_list (parm)
24493 && TREE_CODE (parm) != ARRAY_TYPE)
24494 /* We can only deduce from an initializer list argument if the
24495 parameter is std::initializer_list or an array; otherwise this
24496 is a non-deduced context. */
24497 return unify_success (explain_p);
24499 if (TREE_CODE (parm) == ARRAY_TYPE)
24500 elttype = TREE_TYPE (parm);
24501 else
24503 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24504 /* Deduction is defined in terms of a single type, so just punt
24505 on the (bizarre) std::initializer_list<T...>. */
24506 if (PACK_EXPANSION_P (elttype))
24507 return unify_success (explain_p);
24510 if (strict != DEDUCE_EXACT
24511 && TYPE_P (elttype)
24512 && !uses_deducible_template_parms (elttype))
24513 /* If ELTTYPE has no deducible template parms, skip deduction from
24514 the list elements. */;
24515 else
24516 for (auto &e: CONSTRUCTOR_ELTS (arg))
24518 tree elt = e.value;
24519 int elt_strict = strict;
24521 if (elt == error_mark_node)
24522 return unify_invalid (explain_p);
24524 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24526 tree type = TREE_TYPE (elt);
24527 if (type == error_mark_node)
24528 return unify_invalid (explain_p);
24529 /* It should only be possible to get here for a call. */
24530 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24531 elt_strict |= maybe_adjust_types_for_deduction
24532 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24533 elt = type;
24536 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24537 explain_p);
24540 if (TREE_CODE (parm) == ARRAY_TYPE
24541 && deducible_array_bound (TYPE_DOMAIN (parm)))
24543 /* Also deduce from the length of the initializer list. */
24544 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24545 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24546 if (idx == error_mark_node)
24547 return unify_invalid (explain_p);
24548 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24549 idx, explain_p);
24552 /* If the std::initializer_list<T> deduction worked, replace the
24553 deduced A with std::initializer_list<A>. */
24554 if (orig_parm != parm)
24556 idx = TEMPLATE_TYPE_IDX (orig_parm);
24557 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24558 targ = listify (targ);
24559 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24561 return unify_success (explain_p);
24564 /* If parm and arg aren't the same kind of thing (template, type, or
24565 expression), fail early. */
24566 if (pa_kind (parm) != pa_kind (arg))
24567 return unify_invalid (explain_p);
24569 /* Immediately reject some pairs that won't unify because of
24570 cv-qualification mismatches. */
24571 if (TREE_CODE (arg) == TREE_CODE (parm)
24572 && TYPE_P (arg)
24573 /* It is the elements of the array which hold the cv quals of an array
24574 type, and the elements might be template type parms. We'll check
24575 when we recurse. */
24576 && TREE_CODE (arg) != ARRAY_TYPE
24577 /* We check the cv-qualifiers when unifying with template type
24578 parameters below. We want to allow ARG `const T' to unify with
24579 PARM `T' for example, when computing which of two templates
24580 is more specialized, for example. */
24581 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24582 && !check_cv_quals_for_unify (strict_in, arg, parm))
24583 return unify_cv_qual_mismatch (explain_p, parm, arg);
24585 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24586 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24587 && !FUNC_OR_METHOD_TYPE_P (parm))
24588 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24589 /* PMFs recurse at the same level, so don't strip this yet. */
24590 if (!TYPE_PTRMEMFUNC_P (parm))
24591 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24592 strict &= ~UNIFY_ALLOW_DERIVED;
24593 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24594 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24596 switch (TREE_CODE (parm))
24598 case TYPENAME_TYPE:
24599 case SCOPE_REF:
24600 case UNBOUND_CLASS_TEMPLATE:
24601 /* In a type which contains a nested-name-specifier, template
24602 argument values cannot be deduced for template parameters used
24603 within the nested-name-specifier. */
24604 return unify_success (explain_p);
24606 case TEMPLATE_TYPE_PARM:
24607 case TEMPLATE_TEMPLATE_PARM:
24608 case BOUND_TEMPLATE_TEMPLATE_PARM:
24609 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24610 if (error_operand_p (tparm))
24611 return unify_invalid (explain_p);
24613 if (TEMPLATE_TYPE_LEVEL (parm)
24614 != template_decl_level (tparm))
24615 /* The PARM is not one we're trying to unify. Just check
24616 to see if it matches ARG. */
24618 if (TREE_CODE (arg) == TREE_CODE (parm)
24619 && (is_auto (parm) ? is_auto (arg)
24620 : same_type_p (parm, arg)))
24621 return unify_success (explain_p);
24622 else
24623 return unify_type_mismatch (explain_p, parm, arg);
24625 idx = TEMPLATE_TYPE_IDX (parm);
24626 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24627 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24628 if (error_operand_p (tparm))
24629 return unify_invalid (explain_p);
24631 /* Check for mixed types and values. */
24632 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24633 && TREE_CODE (tparm) != TYPE_DECL)
24634 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24635 && TREE_CODE (tparm) != TEMPLATE_DECL))
24636 gcc_unreachable ();
24638 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24640 if ((strict_in & UNIFY_ALLOW_DERIVED)
24641 && CLASS_TYPE_P (arg))
24643 /* First try to match ARG directly. */
24644 tree t = try_class_unification (tparms, targs, parm, arg,
24645 explain_p);
24646 if (!t)
24648 /* Otherwise, look for a suitable base of ARG, as below. */
24649 enum template_base_result r;
24650 r = get_template_base (tparms, targs, parm, arg,
24651 explain_p, &t);
24652 if (!t)
24653 return unify_no_common_base (explain_p, r, parm, arg);
24654 arg = t;
24657 /* ARG must be constructed from a template class or a template
24658 template parameter. */
24659 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24660 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24661 return unify_template_deduction_failure (explain_p, parm, arg);
24663 /* Deduce arguments T, i from TT<T> or TT<i>. */
24664 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24665 return 1;
24667 arg = TYPE_TI_TEMPLATE (arg);
24668 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24669 /* If the template is a template template parameter, use the
24670 TEMPLATE_TEMPLATE_PARM for matching. */
24671 arg = TREE_TYPE (arg);
24673 /* Fall through to deduce template name. */
24676 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24677 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24679 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24681 /* Simple cases: Value already set, does match or doesn't. */
24682 if (targ != NULL_TREE && template_args_equal (targ, arg))
24683 return unify_success (explain_p);
24684 else if (targ)
24685 return unify_inconsistency (explain_p, parm, targ, arg);
24687 else
24689 /* If PARM is `const T' and ARG is only `int', we don't have
24690 a match unless we are allowing additional qualification.
24691 If ARG is `const int' and PARM is just `T' that's OK;
24692 that binds `const int' to `T'. */
24693 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24694 arg, parm))
24695 return unify_cv_qual_mismatch (explain_p, parm, arg);
24697 /* Consider the case where ARG is `const volatile int' and
24698 PARM is `const T'. Then, T should be `volatile int'. */
24699 arg = cp_build_qualified_type
24700 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24701 if (arg == error_mark_node)
24702 return unify_invalid (explain_p);
24704 /* Simple cases: Value already set, does match or doesn't. */
24705 if (targ != NULL_TREE && same_type_p (targ, arg))
24706 return unify_success (explain_p);
24707 else if (targ)
24708 return unify_inconsistency (explain_p, parm, targ, arg);
24710 /* Make sure that ARG is not a variable-sized array. (Note
24711 that were talking about variable-sized arrays (like
24712 `int[n]'), rather than arrays of unknown size (like
24713 `int[]').) We'll get very confused by such a type since
24714 the bound of the array is not constant, and therefore
24715 not mangleable. Besides, such types are not allowed in
24716 ISO C++, so we can do as we please here. We do allow
24717 them for 'auto' deduction, since that isn't ABI-exposed. */
24718 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24719 return unify_vla_arg (explain_p, arg);
24721 /* Strip typedefs as in convert_template_argument. */
24722 arg = canonicalize_type_argument (arg, tf_none);
24725 /* If ARG is a parameter pack or an expansion, we cannot unify
24726 against it unless PARM is also a parameter pack. */
24727 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24728 && !template_parameter_pack_p (parm))
24729 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24731 /* If the argument deduction results is a METHOD_TYPE,
24732 then there is a problem.
24733 METHOD_TYPE doesn't map to any real C++ type the result of
24734 the deduction cannot be of that type. */
24735 if (TREE_CODE (arg) == METHOD_TYPE)
24736 return unify_method_type_error (explain_p, arg);
24738 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24739 return unify_success (explain_p);
24741 case TEMPLATE_PARM_INDEX:
24742 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24743 if (error_operand_p (tparm))
24744 return unify_invalid (explain_p);
24746 if (TEMPLATE_PARM_LEVEL (parm)
24747 != template_decl_level (tparm))
24749 /* The PARM is not one we're trying to unify. Just check
24750 to see if it matches ARG. */
24751 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24752 && cp_tree_equal (parm, arg));
24753 if (result)
24754 unify_expression_unequal (explain_p, parm, arg);
24755 return result;
24758 idx = TEMPLATE_PARM_IDX (parm);
24759 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24761 if (targ)
24763 if ((strict & UNIFY_ALLOW_INTEGER)
24764 && TREE_TYPE (targ) && TREE_TYPE (arg)
24765 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24766 /* We're deducing from an array bound, the type doesn't matter.
24767 This conversion should match the one below. */
24768 arg = fold (build_nop (TREE_TYPE (targ), arg));
24769 int x = !cp_tree_equal (targ, arg);
24770 if (x)
24771 unify_inconsistency (explain_p, parm, targ, arg);
24772 return x;
24775 /* [temp.deduct.type] If, in the declaration of a function template
24776 with a non-type template-parameter, the non-type
24777 template-parameter is used in an expression in the function
24778 parameter-list and, if the corresponding template-argument is
24779 deduced, the template-argument type shall match the type of the
24780 template-parameter exactly, except that a template-argument
24781 deduced from an array bound may be of any integral type.
24782 The non-type parameter might use already deduced type parameters. */
24783 tparm = TREE_TYPE (parm);
24784 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24785 /* We don't have enough levels of args to do any substitution. This
24786 can happen in the context of -fnew-ttp-matching. */;
24787 else
24789 ++processing_template_decl;
24790 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24791 --processing_template_decl;
24793 if (tree a = type_uses_auto (tparm))
24795 tparm = do_auto_deduction (tparm, arg, a,
24796 complain, adc_unify, targs,
24797 LOOKUP_NORMAL,
24798 TPARMS_PRIMARY_TEMPLATE (tparms));
24799 if (tparm == error_mark_node)
24800 return 1;
24804 if (!TREE_TYPE (arg)
24805 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24806 /* Template-parameter dependent expression. Just accept it for now.
24807 It will later be processed in convert_template_argument. */
24809 else if (same_type_ignoring_top_level_qualifiers_p
24810 (non_reference (TREE_TYPE (arg)),
24811 non_reference (tparm)))
24812 /* OK. Ignore top-level quals here because a class-type template
24813 parameter object is const. */;
24814 else if ((strict & UNIFY_ALLOW_INTEGER)
24815 && CP_INTEGRAL_TYPE_P (tparm))
24816 /* Convert the ARG to the type of PARM; the deduced non-type
24817 template argument must exactly match the types of the
24818 corresponding parameter. This conversion should match the
24819 one above. */
24820 arg = fold (build_nop (tparm, arg));
24821 else if (uses_template_parms (tparm))
24823 /* We haven't deduced the type of this parameter yet. */
24824 if (cxx_dialect >= cxx17
24825 /* We deduce from array bounds in try_array_deduction. */
24826 && !(strict & UNIFY_ALLOW_INTEGER)
24827 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24829 /* Deduce it from the non-type argument. As above, ignore
24830 top-level quals here too. */
24831 tree atype = cv_unqualified (TREE_TYPE (arg));
24832 RECUR_AND_CHECK_FAILURE (tparms, targs,
24833 tparm, atype,
24834 UNIFY_ALLOW_NONE, explain_p);
24835 /* Now check whether the type of this parameter is still
24836 dependent, and give up if so. */
24837 ++processing_template_decl;
24838 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24839 --processing_template_decl;
24840 if (uses_template_parms (tparm))
24841 return unify_success (explain_p);
24843 else
24844 /* Try again later. */
24845 return unify_success (explain_p);
24847 else
24848 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24850 /* If ARG is a parameter pack or an expansion, we cannot unify
24851 against it unless PARM is also a parameter pack. */
24852 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24853 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24854 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24857 bool removed_attr = false;
24858 arg = strip_typedefs_expr (arg, &removed_attr);
24860 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24861 return unify_success (explain_p);
24863 case PTRMEM_CST:
24865 /* A pointer-to-member constant can be unified only with
24866 another constant. */
24867 if (TREE_CODE (arg) != PTRMEM_CST)
24868 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24870 /* Just unify the class member. It would be useless (and possibly
24871 wrong, depending on the strict flags) to unify also
24872 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24873 arg refer to the same variable, even if through different
24874 classes. For instance:
24876 struct A { int x; };
24877 struct B : A { };
24879 Unification of &A::x and &B::x must succeed. */
24880 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24881 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24884 case POINTER_TYPE:
24886 if (!TYPE_PTR_P (arg))
24887 return unify_type_mismatch (explain_p, parm, arg);
24889 /* [temp.deduct.call]
24891 A can be another pointer or pointer to member type that can
24892 be converted to the deduced A via a qualification
24893 conversion (_conv.qual_).
24895 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24896 This will allow for additional cv-qualification of the
24897 pointed-to types if appropriate. */
24899 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24900 /* The derived-to-base conversion only persists through one
24901 level of pointers. */
24902 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24904 return unify (tparms, targs, TREE_TYPE (parm),
24905 TREE_TYPE (arg), strict, explain_p);
24908 case REFERENCE_TYPE:
24909 if (!TYPE_REF_P (arg))
24910 return unify_type_mismatch (explain_p, parm, arg);
24911 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24912 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24914 case ARRAY_TYPE:
24915 if (TREE_CODE (arg) != ARRAY_TYPE)
24916 return unify_type_mismatch (explain_p, parm, arg);
24917 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24918 != (TYPE_DOMAIN (arg) == NULL_TREE))
24919 return unify_type_mismatch (explain_p, parm, arg);
24920 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24921 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24922 if (TYPE_DOMAIN (parm) != NULL_TREE)
24923 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24924 TYPE_DOMAIN (arg), explain_p);
24925 return unify_success (explain_p);
24927 case REAL_TYPE:
24928 case COMPLEX_TYPE:
24929 case VECTOR_TYPE:
24930 case INTEGER_TYPE:
24931 case BOOLEAN_TYPE:
24932 case ENUMERAL_TYPE:
24933 case VOID_TYPE:
24934 case OPAQUE_TYPE:
24935 case NULLPTR_TYPE:
24936 if (TREE_CODE (arg) != TREE_CODE (parm))
24937 return unify_type_mismatch (explain_p, parm, arg);
24939 /* We have already checked cv-qualification at the top of the
24940 function. */
24941 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24942 return unify_type_mismatch (explain_p, parm, arg);
24944 /* As far as unification is concerned, this wins. Later checks
24945 will invalidate it if necessary. */
24946 return unify_success (explain_p);
24948 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24949 /* Type INTEGER_CST can come from ordinary constant template args. */
24950 case INTEGER_CST:
24951 case REAL_CST:
24952 if (!same_type_p (TREE_TYPE (parm), TREE_TYPE (arg)))
24953 return unify_template_argument_mismatch (explain_p, parm, arg);
24954 while (CONVERT_EXPR_P (arg))
24955 arg = TREE_OPERAND (arg, 0);
24957 if (TREE_CODE (arg) != TREE_CODE (parm))
24958 return unify_template_argument_mismatch (explain_p, parm, arg);
24959 return (simple_cst_equal (parm, arg)
24960 ? unify_success (explain_p)
24961 : unify_template_argument_mismatch (explain_p, parm, arg));
24963 case TREE_VEC:
24965 int i, len, argslen;
24966 int parm_variadic_p = 0;
24968 if (TREE_CODE (arg) != TREE_VEC)
24969 return unify_template_argument_mismatch (explain_p, parm, arg);
24971 len = TREE_VEC_LENGTH (parm);
24972 argslen = TREE_VEC_LENGTH (arg);
24974 /* Check for pack expansions in the parameters. */
24975 for (i = 0; i < len; ++i)
24977 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24979 if (i == len - 1)
24980 /* We can unify against something with a trailing
24981 parameter pack. */
24982 parm_variadic_p = 1;
24983 else
24984 /* [temp.deduct.type]/9: If the template argument list of
24985 P contains a pack expansion that is not the last
24986 template argument, the entire template argument list
24987 is a non-deduced context. */
24988 return unify_success (explain_p);
24992 /* If we don't have enough arguments to satisfy the parameters
24993 (not counting the pack expression at the end), or we have
24994 too many arguments for a parameter list that doesn't end in
24995 a pack expression, we can't unify. */
24996 if (parm_variadic_p
24997 ? argslen < len - parm_variadic_p
24998 : argslen != len)
24999 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
25001 /* Unify all of the parameters that precede the (optional)
25002 pack expression. */
25003 for (i = 0; i < len - parm_variadic_p; ++i)
25005 RECUR_AND_CHECK_FAILURE (tparms, targs,
25006 TREE_VEC_ELT (parm, i),
25007 TREE_VEC_ELT (arg, i),
25008 UNIFY_ALLOW_NONE, explain_p);
25010 if (parm_variadic_p)
25011 return unify_pack_expansion (tparms, targs, parm, arg,
25012 DEDUCE_EXACT,
25013 /*subr=*/true, explain_p);
25014 return unify_success (explain_p);
25017 case RECORD_TYPE:
25018 case UNION_TYPE:
25019 if (TREE_CODE (arg) != TREE_CODE (parm))
25020 return unify_type_mismatch (explain_p, parm, arg);
25022 if (TYPE_PTRMEMFUNC_P (parm))
25024 if (!TYPE_PTRMEMFUNC_P (arg))
25025 return unify_type_mismatch (explain_p, parm, arg);
25027 return unify (tparms, targs,
25028 TYPE_PTRMEMFUNC_FN_TYPE (parm),
25029 TYPE_PTRMEMFUNC_FN_TYPE (arg),
25030 strict, explain_p);
25032 else if (TYPE_PTRMEMFUNC_P (arg))
25033 return unify_type_mismatch (explain_p, parm, arg);
25035 if (CLASSTYPE_TEMPLATE_INFO (parm))
25037 tree t = NULL_TREE;
25039 if (strict_in & UNIFY_ALLOW_DERIVED)
25041 /* First, we try to unify the PARM and ARG directly. */
25042 t = try_class_unification (tparms, targs,
25043 parm, arg, explain_p);
25045 if (!t)
25047 /* Fallback to the special case allowed in
25048 [temp.deduct.call]:
25050 If P is a class, and P has the form
25051 template-id, then A can be a derived class of
25052 the deduced A. Likewise, if P is a pointer to
25053 a class of the form template-id, A can be a
25054 pointer to a derived class pointed to by the
25055 deduced A. */
25056 enum template_base_result r;
25057 r = get_template_base (tparms, targs, parm, arg,
25058 explain_p, &t);
25060 if (!t)
25062 /* Don't give the derived diagnostic if we're
25063 already dealing with the same template. */
25064 bool same_template
25065 = (CLASSTYPE_TEMPLATE_INFO (arg)
25066 && (CLASSTYPE_TI_TEMPLATE (parm)
25067 == CLASSTYPE_TI_TEMPLATE (arg)));
25068 return unify_no_common_base (explain_p && !same_template,
25069 r, parm, arg);
25073 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25074 && (CLASSTYPE_TI_TEMPLATE (parm)
25075 == CLASSTYPE_TI_TEMPLATE (arg)))
25076 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25077 Then, we should unify `int' and `U'. */
25078 t = arg;
25079 else
25080 /* There's no chance of unification succeeding. */
25081 return unify_type_mismatch (explain_p, parm, arg);
25083 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
25084 return unify (tparms, targs,
25085 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
25086 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (t)),
25087 UNIFY_ALLOW_NONE, explain_p);
25088 else
25089 return unify_success (explain_p);
25091 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25092 return unify_type_mismatch (explain_p, parm, arg);
25093 return unify_success (explain_p);
25095 case METHOD_TYPE:
25096 case FUNCTION_TYPE:
25098 unsigned int nargs;
25099 tree *args;
25100 tree a;
25101 unsigned int i;
25103 if (TREE_CODE (arg) != TREE_CODE (parm))
25104 return unify_type_mismatch (explain_p, parm, arg);
25106 /* CV qualifications for methods can never be deduced, they must
25107 match exactly. We need to check them explicitly here,
25108 because type_unification_real treats them as any other
25109 cv-qualified parameter. */
25110 if (TREE_CODE (parm) == METHOD_TYPE
25111 && (!check_cv_quals_for_unify
25112 (UNIFY_ALLOW_NONE,
25113 class_of_this_parm (arg),
25114 class_of_this_parm (parm))))
25115 return unify_cv_qual_mismatch (explain_p, parm, arg);
25116 if (TREE_CODE (arg) == FUNCTION_TYPE
25117 && type_memfn_quals (parm) != type_memfn_quals (arg))
25118 return unify_cv_qual_mismatch (explain_p, parm, arg);
25119 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25120 return unify_type_mismatch (explain_p, parm, arg);
25122 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25123 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25125 nargs = list_length (TYPE_ARG_TYPES (arg));
25126 args = XALLOCAVEC (tree, nargs);
25127 for (a = TYPE_ARG_TYPES (arg), i = 0;
25128 a != NULL_TREE && a != void_list_node;
25129 a = TREE_CHAIN (a), ++i)
25130 args[i] = TREE_VALUE (a);
25131 nargs = i;
25133 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25134 args, nargs, 1, DEDUCE_EXACT,
25135 NULL, explain_p))
25136 return 1;
25138 if (flag_noexcept_type)
25140 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25141 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25142 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25143 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25144 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25145 && uses_template_parms (TREE_PURPOSE (pspec)))
25146 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25147 TREE_PURPOSE (aspec),
25148 UNIFY_ALLOW_NONE, explain_p);
25149 else
25151 bool pn = nothrow_spec_p (pspec);
25152 bool an = nothrow_spec_p (aspec);
25153 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25154 /more/ noexcept, since function pointer conversions are the
25155 reverse of qualification conversions. */
25156 if (an == pn
25157 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25158 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25159 /* OK. */;
25160 else
25161 return unify_type_mismatch (explain_p, parm, arg);
25164 if (flag_tm)
25166 /* As for noexcept. */
25167 bool pn = tx_safe_fn_type_p (parm);
25168 bool an = tx_safe_fn_type_p (arg);
25169 if (an == pn
25170 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25171 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25172 /* OK. */;
25173 else
25174 return unify_type_mismatch (explain_p, parm, arg);
25177 return 0;
25180 case OFFSET_TYPE:
25181 /* Unify a pointer to member with a pointer to member function, which
25182 deduces the type of the member as a function type. */
25183 if (TYPE_PTRMEMFUNC_P (arg))
25185 /* Check top-level cv qualifiers */
25186 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25187 return unify_cv_qual_mismatch (explain_p, parm, arg);
25189 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25190 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25191 UNIFY_ALLOW_NONE, explain_p);
25193 /* Determine the type of the function we are unifying against. */
25194 tree fntype = static_fn_type (arg);
25196 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25199 if (TREE_CODE (arg) != OFFSET_TYPE)
25200 return unify_type_mismatch (explain_p, parm, arg);
25201 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25202 TYPE_OFFSET_BASETYPE (arg),
25203 UNIFY_ALLOW_NONE, explain_p);
25204 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25205 strict, explain_p);
25207 case CONST_DECL:
25208 /* CONST_DECL should already have been folded to its DECL_INITIAL. */
25209 gcc_unreachable ();
25211 case FIELD_DECL:
25212 case FUNCTION_DECL:
25213 case TEMPLATE_DECL:
25214 /* Matched cases are handled by the ARG == PARM test above. */
25215 return unify_template_argument_mismatch (explain_p, parm, arg);
25217 case VAR_DECL:
25218 /* We might get a variable as a non-type template argument in parm if the
25219 corresponding parameter is type-dependent. Make any necessary
25220 adjustments based on whether arg is a reference. */
25221 if (CONSTANT_CLASS_P (arg))
25222 parm = fold_non_dependent_expr (parm, complain);
25223 else if (REFERENCE_REF_P (arg))
25225 tree sub = TREE_OPERAND (arg, 0);
25226 STRIP_NOPS (sub);
25227 if (TREE_CODE (sub) == ADDR_EXPR)
25228 arg = TREE_OPERAND (sub, 0);
25230 /* Now use the normal expression code to check whether they match. */
25231 goto expr;
25233 case TYPE_ARGUMENT_PACK:
25234 case NONTYPE_ARGUMENT_PACK:
25235 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25236 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25238 case TYPEOF_TYPE:
25239 case DECLTYPE_TYPE:
25240 case TRAIT_TYPE:
25241 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25242 or TRAIT_TYPE nodes. */
25243 return unify_success (explain_p);
25245 case ERROR_MARK:
25246 /* Unification fails if we hit an error node. */
25247 return unify_invalid (explain_p);
25249 case INDIRECT_REF:
25250 if (REFERENCE_REF_P (parm))
25252 bool pexp = PACK_EXPANSION_P (arg);
25253 if (pexp)
25254 arg = PACK_EXPANSION_PATTERN (arg);
25255 if (REFERENCE_REF_P (arg))
25256 arg = TREE_OPERAND (arg, 0);
25257 if (pexp)
25258 arg = make_pack_expansion (arg, complain);
25259 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25260 strict, explain_p);
25262 /* FALLTHRU */
25264 default:
25265 /* An unresolved overload is a nondeduced context. */
25266 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25267 return unify_success (explain_p);
25268 gcc_assert (EXPR_P (parm)
25269 || TREE_CODE (parm) == CONSTRUCTOR
25270 || TREE_CODE (parm) == TRAIT_EXPR);
25271 expr:
25272 /* We must be looking at an expression. This can happen with
25273 something like:
25275 template <int I>
25276 void foo(S<I>, S<I + 2>);
25280 template<typename T>
25281 void foo(A<T, T{}>);
25283 This is a "non-deduced context":
25285 [deduct.type]
25287 The non-deduced contexts are:
25289 --A non-type template argument or an array bound in which
25290 a subexpression references a template parameter.
25292 In these cases, we assume deduction succeeded, but don't
25293 actually infer any unifications. */
25295 if (!uses_template_parms (parm)
25296 && !template_args_equal (parm, arg))
25297 return unify_expression_unequal (explain_p, parm, arg);
25298 else
25299 return unify_success (explain_p);
25302 #undef RECUR_AND_CHECK_FAILURE
25304 /* Note that DECL can be defined in this translation unit, if
25305 required. */
25307 static void
25308 mark_definable (tree decl)
25310 tree clone;
25311 DECL_NOT_REALLY_EXTERN (decl) = 1;
25312 FOR_EACH_CLONE (clone, decl)
25313 DECL_NOT_REALLY_EXTERN (clone) = 1;
25316 /* Called if RESULT is explicitly instantiated, or is a member of an
25317 explicitly instantiated class. */
25319 void
25320 mark_decl_instantiated (tree result, int extern_p)
25322 SET_DECL_EXPLICIT_INSTANTIATION (result);
25324 /* If this entity has already been written out, it's too late to
25325 make any modifications. */
25326 if (TREE_ASM_WRITTEN (result))
25327 return;
25329 /* consteval functions are never emitted. */
25330 if (TREE_CODE (result) == FUNCTION_DECL
25331 && DECL_IMMEDIATE_FUNCTION_P (result))
25332 return;
25334 /* For anonymous namespace we don't need to do anything. */
25335 if (decl_internal_context_p (result))
25337 gcc_assert (!TREE_PUBLIC (result));
25338 return;
25341 if (TREE_CODE (result) != FUNCTION_DECL)
25342 /* The TREE_PUBLIC flag for function declarations will have been
25343 set correctly by tsubst. */
25344 TREE_PUBLIC (result) = 1;
25346 if (extern_p)
25348 DECL_EXTERNAL (result) = 1;
25349 DECL_NOT_REALLY_EXTERN (result) = 0;
25351 else
25353 mark_definable (result);
25354 mark_needed (result);
25355 /* Always make artificials weak. */
25356 if (DECL_ARTIFICIAL (result) && flag_weak)
25357 comdat_linkage (result);
25358 /* For WIN32 we also want to put explicit instantiations in
25359 linkonce sections. */
25360 else if (TREE_PUBLIC (result))
25361 maybe_make_one_only (result);
25362 if (TREE_CODE (result) == FUNCTION_DECL
25363 && DECL_TEMPLATE_INSTANTIATED (result))
25364 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25365 since start_preparsed_function wouldn't have if we had an earlier
25366 extern explicit instantiation. */
25367 DECL_EXTERNAL (result) = 0;
25370 /* If EXTERN_P, then this function will not be emitted -- unless
25371 followed by an explicit instantiation, at which point its linkage
25372 will be adjusted. If !EXTERN_P, then this function will be
25373 emitted here. In neither circumstance do we want
25374 import_export_decl to adjust the linkage. */
25375 DECL_INTERFACE_KNOWN (result) = 1;
25378 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25379 important template arguments. If any are missing, we check whether
25380 they're important by using error_mark_node for substituting into any
25381 args that were used for partial ordering (the ones between ARGS and END)
25382 and seeing if it bubbles up. */
25384 static bool
25385 check_undeduced_parms (tree targs, tree args, tree end)
25387 bool found = false;
25388 for (tree& targ : tree_vec_range (targs))
25389 if (targ == NULL_TREE)
25391 found = true;
25392 targ = error_mark_node;
25394 if (found)
25396 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25397 if (substed == error_mark_node)
25398 return true;
25400 return false;
25403 /* Given two function templates PAT1 and PAT2, return:
25405 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25406 -1 if PAT2 is more specialized than PAT1.
25407 0 if neither is more specialized.
25409 LEN indicates the number of parameters we should consider
25410 (defaulted parameters should not be considered).
25412 The 1998 std underspecified function template partial ordering, and
25413 DR214 addresses the issue. We take pairs of arguments, one from
25414 each of the templates, and deduce them against each other. One of
25415 the templates will be more specialized if all the *other*
25416 template's arguments deduce against its arguments and at least one
25417 of its arguments *does* *not* deduce against the other template's
25418 corresponding argument. Deduction is done as for class templates.
25419 The arguments used in deduction have reference and top level cv
25420 qualifiers removed. Iff both arguments were originally reference
25421 types *and* deduction succeeds in both directions, an lvalue reference
25422 wins against an rvalue reference and otherwise the template
25423 with the more cv-qualified argument wins for that pairing (if
25424 neither is more cv-qualified, they both are equal). Unlike regular
25425 deduction, after all the arguments have been deduced in this way,
25426 we do *not* verify the deduced template argument values can be
25427 substituted into non-deduced contexts.
25429 The logic can be a bit confusing here, because we look at deduce1 and
25430 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25431 can find template arguments for pat1 to make arg1 look like arg2, that
25432 means that arg2 is at least as specialized as arg1. */
25435 more_specialized_fn (tree pat1, tree pat2, int len)
25437 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25438 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25439 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25440 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25441 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25442 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25443 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25444 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25445 tree origs1, origs2;
25446 bool lose1 = false;
25447 bool lose2 = false;
25449 /* C++17 [temp.func.order]/3 (CWG532)
25451 If only one of the function templates M is a non-static member of some
25452 class A, M is considered to have a new first parameter inserted in its
25453 function parameter list. Given cv as the cv-qualifiers of M (if any), the
25454 new parameter is of type "rvalue reference to cv A" if the optional
25455 ref-qualifier of M is && or if M has no ref-qualifier and the first
25456 parameter of the other template has rvalue reference type. Otherwise, the
25457 new parameter is of type "lvalue reference to cv A". */
25459 if (DECL_STATIC_FUNCTION_P (decl1) || DECL_STATIC_FUNCTION_P (decl2))
25461 /* Note C++20 DR2445 extended the above to static member functions, but
25462 I think think the old G++ behavior of just skipping the object
25463 parameter when comparing to a static member function was better, so
25464 let's stick with that for now. This is CWG2834. --jason 2023-12 */
25465 if (DECL_OBJECT_MEMBER_FUNCTION_P (decl1))
25467 len--; /* LEN is the number of significant arguments for DECL1 */
25468 args1 = TREE_CHAIN (args1);
25470 else if (DECL_OBJECT_MEMBER_FUNCTION_P (decl2))
25471 args2 = TREE_CHAIN (args2);
25473 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25474 && DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25476 /* Note DR2445 also (IMO wrongly) removed the "only one" above, which
25477 would break e.g. cpp1y/lambda-generic-variadic5.C. */
25478 len--;
25479 args1 = TREE_CHAIN (args1);
25480 args2 = TREE_CHAIN (args2);
25482 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25483 || DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25485 /* The other is a non-member or explicit object member function;
25486 rewrite the implicit object parameter to a reference. */
25487 tree ns = DECL_IOBJ_MEMBER_FUNCTION_P (decl2) ? decl2 : decl1;
25488 tree &nsargs = ns == decl2 ? args2 : args1;
25489 tree obtype = TREE_TYPE (TREE_VALUE (nsargs));
25491 nsargs = TREE_CHAIN (nsargs);
25493 cp_ref_qualifier rqual = type_memfn_rqual (TREE_TYPE (ns));
25494 if (rqual == REF_QUAL_NONE)
25496 tree otherfirst = ns == decl1 ? args2 : args1;
25497 otherfirst = TREE_VALUE (otherfirst);
25498 if (TREE_CODE (otherfirst) == REFERENCE_TYPE
25499 && TYPE_REF_IS_RVALUE (otherfirst))
25500 rqual = REF_QUAL_RVALUE;
25502 obtype = cp_build_reference_type (obtype, rqual == REF_QUAL_RVALUE);
25503 nsargs = tree_cons (NULL_TREE, obtype, nsargs);
25506 /* If only one is a conversion operator, they are unordered. */
25507 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25508 return 0;
25510 /* Consider the return type for a conversion function */
25511 if (DECL_CONV_FN_P (decl1))
25513 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25514 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25515 len++;
25518 processing_template_decl++;
25520 origs1 = args1;
25521 origs2 = args2;
25523 while (len--
25524 /* Stop when an ellipsis is seen. */
25525 && args1 != NULL_TREE && args2 != NULL_TREE)
25527 tree arg1 = TREE_VALUE (args1);
25528 tree arg2 = TREE_VALUE (args2);
25529 int deduce1, deduce2;
25530 int quals1 = -1;
25531 int quals2 = -1;
25532 int ref1 = 0;
25533 int ref2 = 0;
25535 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25536 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25538 /* When both arguments are pack expansions, we need only
25539 unify the patterns themselves. */
25540 arg1 = PACK_EXPANSION_PATTERN (arg1);
25541 arg2 = PACK_EXPANSION_PATTERN (arg2);
25543 /* This is the last comparison we need to do. */
25544 len = 0;
25547 if (TYPE_REF_P (arg1))
25549 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25550 arg1 = TREE_TYPE (arg1);
25551 quals1 = cp_type_quals (arg1);
25554 if (TYPE_REF_P (arg2))
25556 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25557 arg2 = TREE_TYPE (arg2);
25558 quals2 = cp_type_quals (arg2);
25561 arg1 = TYPE_MAIN_VARIANT (arg1);
25562 arg2 = TYPE_MAIN_VARIANT (arg2);
25564 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25566 int i, len2 = remaining_arguments (args2);
25567 tree parmvec = make_tree_vec (1);
25568 tree argvec = make_tree_vec (len2);
25569 tree ta = args2;
25571 /* Setup the parameter vector, which contains only ARG1. */
25572 TREE_VEC_ELT (parmvec, 0) = arg1;
25574 /* Setup the argument vector, which contains the remaining
25575 arguments. */
25576 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25577 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25579 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25580 argvec, DEDUCE_EXACT,
25581 /*subr=*/true, /*explain_p=*/false)
25582 == 0);
25584 /* We cannot deduce in the other direction, because ARG1 is
25585 a pack expansion but ARG2 is not. */
25586 deduce2 = 0;
25588 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25590 int i, len1 = remaining_arguments (args1);
25591 tree parmvec = make_tree_vec (1);
25592 tree argvec = make_tree_vec (len1);
25593 tree ta = args1;
25595 /* Setup the parameter vector, which contains only ARG1. */
25596 TREE_VEC_ELT (parmvec, 0) = arg2;
25598 /* Setup the argument vector, which contains the remaining
25599 arguments. */
25600 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25601 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25603 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25604 argvec, DEDUCE_EXACT,
25605 /*subr=*/true, /*explain_p=*/false)
25606 == 0);
25608 /* We cannot deduce in the other direction, because ARG2 is
25609 a pack expansion but ARG1 is not.*/
25610 deduce1 = 0;
25613 else
25615 /* The normal case, where neither argument is a pack
25616 expansion. */
25617 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25618 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25619 == 0);
25620 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25621 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25622 == 0);
25625 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25626 arg2, then arg2 is not as specialized as arg1. */
25627 if (!deduce1)
25628 lose2 = true;
25629 if (!deduce2)
25630 lose1 = true;
25632 /* "If, for a given type, deduction succeeds in both directions
25633 (i.e., the types are identical after the transformations above)
25634 and both P and A were reference types (before being replaced with
25635 the type referred to above):
25636 - if the type from the argument template was an lvalue reference and
25637 the type from the parameter template was not, the argument type is
25638 considered to be more specialized than the other; otherwise,
25639 - if the type from the argument template is more cv-qualified
25640 than the type from the parameter template (as described above),
25641 the argument type is considered to be more specialized than the other;
25642 otherwise,
25643 - neither type is more specialized than the other." */
25645 if (deduce1 && deduce2)
25647 if (ref1 && ref2 && ref1 != ref2)
25649 if (ref1 > ref2)
25650 lose1 = true;
25651 else
25652 lose2 = true;
25654 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25656 if ((quals1 & quals2) == quals2)
25657 lose2 = true;
25658 if ((quals1 & quals2) == quals1)
25659 lose1 = true;
25663 if (lose1 && lose2)
25664 /* We've failed to deduce something in either direction.
25665 These must be unordered. */
25666 break;
25668 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25669 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25670 /* We have already processed all of the arguments in our
25671 handing of the pack expansion type. */
25672 len = 0;
25674 args1 = TREE_CHAIN (args1);
25675 args2 = TREE_CHAIN (args2);
25678 /* "In most cases, all template parameters must have values in order for
25679 deduction to succeed, but for partial ordering purposes a template
25680 parameter may remain without a value provided it is not used in the
25681 types being used for partial ordering."
25683 Thus, if we are missing any of the targs1 we need to substitute into
25684 origs1, then pat2 is not as specialized as pat1. This can happen when
25685 there is a nondeduced context. */
25686 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25687 lose2 = true;
25688 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25689 lose1 = true;
25691 processing_template_decl--;
25693 /* If both deductions succeed, the partial ordering selects the more
25694 constrained template. */
25695 /* P2113: If the corresponding template-parameters of the
25696 template-parameter-lists are not equivalent ([temp.over.link]) or if
25697 the function parameters that positionally correspond between the two
25698 templates are not of the same type, neither template is more
25699 specialized than the other. */
25700 if (!lose1 && !lose2
25701 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25702 DECL_TEMPLATE_PARMS (pat2))
25703 && compparms (origs1, origs2))
25705 int winner = more_constrained (decl1, decl2);
25706 if (winner > 0)
25707 lose2 = true;
25708 else if (winner < 0)
25709 lose1 = true;
25712 /* All things being equal, if the next argument is a pack expansion
25713 for one function but not for the other, prefer the
25714 non-variadic function. FIXME this is bogus; see c++/41958. */
25715 if (lose1 == lose2
25716 && args1 && TREE_VALUE (args1)
25717 && args2 && TREE_VALUE (args2))
25719 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25720 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25723 if (lose1 == lose2)
25724 return 0;
25725 else if (!lose1)
25726 return 1;
25727 else
25728 return -1;
25731 /* Determine which of two partial specializations of TMPL is more
25732 specialized.
25734 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25735 to the first partial specialization. The TREE_PURPOSE is the
25736 innermost set of template parameters for the partial
25737 specialization. PAT2 is similar, but for the second template.
25739 Return 1 if the first partial specialization is more specialized;
25740 -1 if the second is more specialized; 0 if neither is more
25741 specialized.
25743 See [temp.class.order] for information about determining which of
25744 two templates is more specialized. */
25746 static int
25747 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25749 tree targs;
25750 int winner = 0;
25751 bool any_deductions = false;
25753 tree tmpl1 = TREE_VALUE (pat1);
25754 tree tmpl2 = TREE_VALUE (pat2);
25755 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25756 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25758 /* Just like what happens for functions, if we are ordering between
25759 different template specializations, we may encounter dependent
25760 types in the arguments, and we need our dependency check functions
25761 to behave correctly. */
25762 ++processing_template_decl;
25763 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25764 if (targs)
25766 --winner;
25767 any_deductions = true;
25770 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25771 if (targs)
25773 ++winner;
25774 any_deductions = true;
25776 --processing_template_decl;
25778 /* If both deductions succeed, the partial ordering selects the more
25779 constrained template. */
25780 if (!winner && any_deductions)
25781 winner = more_constrained (tmpl1, tmpl2);
25783 /* In the case of a tie where at least one of the templates
25784 has a parameter pack at the end, the template with the most
25785 non-packed parameters wins. */
25786 if (winner == 0
25787 && any_deductions
25788 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25789 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25791 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25792 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25793 int len1 = TREE_VEC_LENGTH (args1);
25794 int len2 = TREE_VEC_LENGTH (args2);
25796 /* We don't count the pack expansion at the end. */
25797 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25798 --len1;
25799 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25800 --len2;
25802 if (len1 > len2)
25803 return 1;
25804 else if (len1 < len2)
25805 return -1;
25808 return winner;
25811 /* Return the template arguments that will produce the function signature
25812 DECL from the function template FN, with the explicit template
25813 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25814 also match. Return NULL_TREE if no satisfactory arguments could be
25815 found. */
25817 static tree
25818 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25820 int ntparms = DECL_NTPARMS (fn);
25821 tree targs = make_tree_vec (ntparms);
25822 tree decl_type = TREE_TYPE (decl);
25823 tree decl_arg_types;
25824 tree *args;
25825 unsigned int nargs, ix;
25826 tree arg;
25828 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25830 /* Never do unification on the 'this' parameter. */
25831 decl_arg_types = skip_artificial_parms_for (decl,
25832 TYPE_ARG_TYPES (decl_type));
25834 nargs = list_length (decl_arg_types);
25835 args = XALLOCAVEC (tree, nargs);
25836 for (arg = decl_arg_types, ix = 0;
25837 arg != NULL_TREE;
25838 arg = TREE_CHAIN (arg), ++ix)
25839 args[ix] = TREE_VALUE (arg);
25841 if (fn_type_unification (fn, explicit_args, targs,
25842 args, ix,
25843 (check_rettype || DECL_CONV_FN_P (fn)
25844 ? TREE_TYPE (decl_type) : NULL_TREE),
25845 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25846 /*explain_p=*/false,
25847 /*decltype*/false)
25848 == error_mark_node)
25849 return NULL_TREE;
25851 return targs;
25854 /* Return the innermost template arguments that, when applied to a partial
25855 specialization SPEC_TMPL of TMPL, yield the ARGS.
25857 For example, suppose we have:
25859 template <class T, class U> struct S {};
25860 template <class T> struct S<T*, int> {};
25862 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25863 partial specialization and the ARGS will be {double*, int}. The resulting
25864 vector will be {double}, indicating that `T' is bound to `double'. */
25866 static tree
25867 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25869 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25870 tree spec_args
25871 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25872 int i, ntparms = TREE_VEC_LENGTH (tparms);
25873 tree deduced_args;
25874 tree innermost_deduced_args;
25876 innermost_deduced_args = make_tree_vec (ntparms);
25877 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25879 deduced_args = copy_node (args);
25880 SET_TMPL_ARGS_LEVEL (deduced_args,
25881 TMPL_ARGS_DEPTH (deduced_args),
25882 innermost_deduced_args);
25884 else
25885 deduced_args = innermost_deduced_args;
25887 bool tried_array_deduction = (cxx_dialect < cxx17);
25888 again:
25889 if (unify (tparms, deduced_args,
25890 INNERMOST_TEMPLATE_ARGS (spec_args),
25891 INNERMOST_TEMPLATE_ARGS (args),
25892 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25893 return NULL_TREE;
25895 for (i = 0; i < ntparms; ++i)
25896 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25898 if (!tried_array_deduction)
25900 try_array_deduction (tparms, innermost_deduced_args,
25901 INNERMOST_TEMPLATE_ARGS (spec_args));
25902 tried_array_deduction = true;
25903 if (TREE_VEC_ELT (innermost_deduced_args, i))
25904 goto again;
25906 return NULL_TREE;
25909 if (!push_tinst_level (spec_tmpl, deduced_args))
25911 excessive_deduction_depth = true;
25912 return NULL_TREE;
25915 /* Verify that nondeduced template arguments agree with the type
25916 obtained from argument deduction.
25918 For example:
25920 struct A { typedef int X; };
25921 template <class T, class U> struct C {};
25922 template <class T> struct C<T, typename T::X> {};
25924 Then with the instantiation `C<A, int>', we can deduce that
25925 `T' is `A' but unify () does not check whether `typename T::X'
25926 is `int'. */
25927 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25929 if (spec_args != error_mark_node)
25930 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25931 INNERMOST_TEMPLATE_ARGS (spec_args),
25932 tmpl, tf_none, false);
25934 pop_tinst_level ();
25936 if (spec_args == error_mark_node
25937 /* We only need to check the innermost arguments; the other
25938 arguments will always agree. */
25939 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25940 INNERMOST_TEMPLATE_ARGS (args)))
25941 return NULL_TREE;
25943 /* Now that we have bindings for all of the template arguments,
25944 ensure that the arguments deduced for the template template
25945 parameters have compatible template parameter lists. See the use
25946 of template_template_parm_bindings_ok_p in fn_type_unification
25947 for more information. */
25948 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25949 return NULL_TREE;
25951 return deduced_args;
25954 // Compare two function templates T1 and T2 by deducing bindings
25955 // from one against the other. If both deductions succeed, compare
25956 // constraints to see which is more constrained.
25957 static int
25958 more_specialized_inst (tree t1, tree t2)
25960 int fate = 0;
25961 int count = 0;
25963 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25965 --fate;
25966 ++count;
25969 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25971 ++fate;
25972 ++count;
25975 // If both deductions succeed, then one may be more constrained.
25976 if (count == 2 && fate == 0)
25977 fate = more_constrained (t1, t2);
25979 return fate;
25982 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25983 Return the TREE_LIST node with the most specialized template, if
25984 any. If there is no most specialized template, the error_mark_node
25985 is returned.
25987 Note that this function does not look at, or modify, the
25988 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25989 returned is one of the elements of INSTANTIATIONS, callers may
25990 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25991 and retrieve it from the value returned. */
25993 tree
25994 most_specialized_instantiation (tree templates)
25996 tree fn, champ;
25998 ++processing_template_decl;
26000 champ = templates;
26001 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
26003 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
26004 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
26005 if (fate == -1)
26006 champ = fn;
26007 else if (!fate)
26009 /* Equally specialized, move to next function. If there
26010 is no next function, nothing's most specialized. */
26011 fn = TREE_CHAIN (fn);
26012 champ = fn;
26013 if (!fn)
26014 break;
26018 if (champ)
26019 /* Now verify that champ is better than everything earlier in the
26020 instantiation list. */
26021 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
26022 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
26024 champ = NULL_TREE;
26025 break;
26029 processing_template_decl--;
26031 if (!champ)
26032 return error_mark_node;
26034 return champ;
26037 /* If DECL is a specialization of some template, return the most
26038 general such template. Otherwise, returns NULL_TREE.
26040 For example, given:
26042 template <class T> struct S { template <class U> void f(U); };
26044 if TMPL is `template <class U> void S<int>::f(U)' this will return
26045 the full template. This function will not trace past partial
26046 specializations, however. For example, given in addition:
26048 template <class T> struct S<T*> { template <class U> void f(U); };
26050 if TMPL is `template <class U> void S<int*>::f(U)' this will return
26051 `template <class T> template <class U> S<T*>::f(U)'. */
26053 tree
26054 most_general_template (const_tree decl)
26056 if (TREE_CODE (decl) != TEMPLATE_DECL)
26058 if (tree tinfo = get_template_info (decl))
26059 decl = TI_TEMPLATE (tinfo);
26060 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
26061 template friend, or a FIELD_DECL for a capture pack. */
26062 if (TREE_CODE (decl) != TEMPLATE_DECL)
26063 return NULL_TREE;
26066 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
26067 return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
26069 /* Look for more and more general templates. */
26070 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
26072 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
26073 (See cp-tree.h for details.) */
26074 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
26075 break;
26077 if (CLASS_TYPE_P (TREE_TYPE (decl))
26078 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
26079 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
26080 break;
26082 /* Stop if we run into an explicitly specialized class template. */
26083 if (!DECL_NAMESPACE_SCOPE_P (decl)
26084 && DECL_CONTEXT (decl)
26085 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
26086 break;
26088 decl = DECL_TI_TEMPLATE (decl);
26091 return CONST_CAST_TREE (decl);
26094 /* Return the most specialized of the template partial specializations
26095 which can produce TARGET, a specialization of some class or variable
26096 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26097 TEMPLATE_DECL node corresponding to the partial specialization, while
26098 the TI_ARGS is the set of template arguments that must be substituted
26099 into the template pattern in order to generate TARGET. The result is
26100 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26101 RECHECKING is true.
26103 If the choice of partial specialization is ambiguous, a diagnostic
26104 is issued, and the error_mark_node is returned. If there are no
26105 partial specializations matching TARGET, then NULL_TREE is
26106 returned, indicating that the primary template should be used. */
26108 tree
26109 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26110 bool rechecking /* = false */)
26112 tree tinfo = NULL_TREE;
26113 tree tmpl, args, decl;
26114 if (TYPE_P (target))
26116 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26117 tmpl = TI_TEMPLATE (tinfo);
26118 args = TI_ARGS (tinfo);
26119 decl = TYPE_NAME (target);
26121 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26123 tmpl = TREE_OPERAND (target, 0);
26124 args = TREE_OPERAND (target, 1);
26125 decl = DECL_TEMPLATE_RESULT (tmpl);
26127 else if (VAR_P (target))
26129 tinfo = DECL_TEMPLATE_INFO (target);
26130 tmpl = TI_TEMPLATE (tinfo);
26131 args = TI_ARGS (tinfo);
26132 decl = target;
26134 else
26135 gcc_unreachable ();
26137 if (!PRIMARY_TEMPLATE_P (tmpl))
26138 return NULL_TREE;
26140 if (!rechecking
26141 && tinfo
26142 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26143 return TI_PARTIAL_INFO (tinfo);
26145 tree main_tmpl = most_general_template (tmpl);
26146 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26147 if (!specs)
26148 /* There are no partial specializations of this template. */
26149 return NULL_TREE;
26151 push_access_scope_guard pas (decl);
26152 deferring_access_check_sentinel acs (dk_no_deferred);
26154 /* For determining which partial specialization to use, only the
26155 innermost args are interesting. */
26156 tree outer_args = NULL_TREE;
26157 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26159 outer_args = strip_innermost_template_args (args, 1);
26160 args = INNERMOST_TEMPLATE_ARGS (args);
26163 /* The caller hasn't called push_to_top_level yet, but we need
26164 get_partial_spec_bindings to be done in non-template context so that we'll
26165 fully resolve everything. */
26166 processing_template_decl_sentinel ptds;
26168 tree list = NULL_TREE;
26169 for (tree t = specs; t; t = TREE_CHAIN (t))
26171 const tree ospec_tmpl = TREE_VALUE (t);
26173 tree spec_tmpl;
26174 if (outer_args)
26176 /* Substitute in the template args from the enclosing class. */
26177 ++processing_template_decl;
26178 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26179 --processing_template_decl;
26180 if (spec_tmpl == error_mark_node)
26181 return error_mark_node;
26183 else
26184 spec_tmpl = ospec_tmpl;
26186 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26187 if (spec_args)
26189 if (outer_args)
26190 spec_args = add_to_template_args (outer_args, spec_args);
26192 /* Keep the candidate only if its constraints are satisfied. */
26193 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26194 list = tree_cons (spec_args, ospec_tmpl, list);
26198 if (! list)
26199 return NULL_TREE;
26201 tree champ = list;
26202 bool ambiguous_p = false;
26203 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26205 int fate = more_specialized_partial_spec (tmpl, champ, t);
26206 if (fate == 1)
26208 else
26210 if (fate == 0)
26212 t = TREE_CHAIN (t);
26213 if (! t)
26215 ambiguous_p = true;
26216 break;
26219 champ = t;
26223 if (!ambiguous_p)
26224 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26226 int fate = more_specialized_partial_spec (tmpl, champ, t);
26227 if (fate != 1)
26229 ambiguous_p = true;
26230 break;
26234 if (ambiguous_p)
26236 const char *str;
26237 char *spaces = NULL;
26238 if (!(complain & tf_error))
26239 return error_mark_node;
26240 if (TYPE_P (target))
26241 error ("ambiguous template instantiation for %q#T", target);
26242 else
26243 error ("ambiguous template instantiation for %q#D", target);
26244 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26245 for (tree t = list; t; t = TREE_CHAIN (t))
26247 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26248 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26249 "%s %#qS", spaces ? spaces : str, subst);
26250 spaces = spaces ? spaces : get_spaces (str);
26252 free (spaces);
26253 return error_mark_node;
26256 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26257 if (!rechecking && tinfo)
26258 TI_PARTIAL_INFO (tinfo) = result;
26259 return result;
26262 /* Explicitly instantiate DECL. */
26264 void
26265 do_decl_instantiation (tree decl, tree storage)
26267 tree result = NULL_TREE;
26268 int extern_p = 0;
26270 if (!decl || decl == error_mark_node)
26271 /* An error occurred, for which grokdeclarator has already issued
26272 an appropriate message. */
26273 return;
26274 else if (! DECL_LANG_SPECIFIC (decl))
26276 error ("explicit instantiation of non-template %q#D", decl);
26277 return;
26279 else if (DECL_DECLARED_CONCEPT_P (decl))
26281 if (VAR_P (decl))
26282 error ("explicit instantiation of variable concept %q#D", decl);
26283 else
26284 error ("explicit instantiation of function concept %q#D", decl);
26285 return;
26288 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26289 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26291 if (VAR_P (decl) && !var_templ)
26293 /* There is an asymmetry here in the way VAR_DECLs and
26294 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26295 the latter, the DECL we get back will be marked as a
26296 template instantiation, and the appropriate
26297 DECL_TEMPLATE_INFO will be set up. This does not happen for
26298 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26299 should handle VAR_DECLs as it currently handles
26300 FUNCTION_DECLs. */
26301 if (!DECL_CLASS_SCOPE_P (decl))
26303 error ("%qD is not a static data member of a class template", decl);
26304 return;
26306 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26307 if (!result || !VAR_P (result))
26309 error ("no matching template for %qD found", decl);
26310 return;
26312 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26314 error ("type %qT for explicit instantiation %qD does not match "
26315 "declared type %qT", TREE_TYPE (result), decl,
26316 TREE_TYPE (decl));
26317 return;
26320 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26322 error ("explicit instantiation of %q#D", decl);
26323 return;
26325 else
26326 result = decl;
26328 /* Check for various error cases. Note that if the explicit
26329 instantiation is valid the RESULT will currently be marked as an
26330 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26331 until we get here. */
26333 if (DECL_TEMPLATE_SPECIALIZATION (result))
26335 /* DR 259 [temp.spec].
26337 Both an explicit instantiation and a declaration of an explicit
26338 specialization shall not appear in a program unless the explicit
26339 instantiation follows a declaration of the explicit specialization.
26341 For a given set of template parameters, if an explicit
26342 instantiation of a template appears after a declaration of an
26343 explicit specialization for that template, the explicit
26344 instantiation has no effect. */
26345 return;
26347 else if (DECL_EXPLICIT_INSTANTIATION (result))
26349 /* [temp.spec]
26351 No program shall explicitly instantiate any template more
26352 than once.
26354 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26355 the first instantiation was `extern' and the second is not,
26356 and EXTERN_P for the opposite case. */
26357 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26358 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26359 /* If an "extern" explicit instantiation follows an ordinary
26360 explicit instantiation, the template is instantiated. */
26361 if (extern_p)
26362 return;
26364 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26366 error ("no matching template for %qD found", result);
26367 return;
26369 else if (!DECL_TEMPLATE_INFO (result))
26371 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26372 return;
26375 if (storage == NULL_TREE)
26377 else if (storage == ridpointers[(int) RID_EXTERN])
26379 if (cxx_dialect == cxx98)
26380 pedwarn (input_location, OPT_Wpedantic,
26381 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26382 "instantiations");
26383 extern_p = 1;
26385 else
26386 error ("storage class %qD applied to template instantiation", storage);
26388 check_explicit_instantiation_namespace (result);
26389 mark_decl_instantiated (result, extern_p);
26390 if (! extern_p)
26391 instantiate_decl (result, /*defer_ok=*/true,
26392 /*expl_inst_class_mem_p=*/false);
26395 static void
26396 mark_class_instantiated (tree t, int extern_p)
26398 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26399 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26400 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26401 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26402 if (! extern_p)
26404 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26405 rest_of_type_compilation (t, 1);
26409 /* Perform an explicit instantiation of template class T. STORAGE, if
26410 non-null, is the RID for extern, inline or static. COMPLAIN is
26411 nonzero if this is called from the parser, zero if called recursively,
26412 since the standard is unclear (as detailed below). */
26414 void
26415 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26417 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26419 if (tree ti = TYPE_TEMPLATE_INFO (t))
26420 error ("explicit instantiation of non-class template %qD",
26421 TI_TEMPLATE (ti));
26422 else
26423 error ("explicit instantiation of non-template type %qT", t);
26424 return;
26427 complete_type (t);
26429 if (!COMPLETE_TYPE_P (t))
26431 if (complain & tf_error)
26432 error ("explicit instantiation of %q#T before definition of template",
26434 return;
26437 /* At most one of these will be true. */
26438 bool extern_p = false;
26439 bool nomem_p = false;
26440 bool static_p = false;
26442 if (storage != NULL_TREE)
26444 if (storage == ridpointers[(int) RID_EXTERN])
26446 if (cxx_dialect == cxx98)
26447 pedwarn (input_location, OPT_Wpedantic,
26448 "ISO C++ 1998 forbids the use of %<extern%> on "
26449 "explicit instantiations");
26451 else
26452 pedwarn (input_location, OPT_Wpedantic,
26453 "ISO C++ forbids the use of %qE"
26454 " on explicit instantiations", storage);
26456 if (storage == ridpointers[(int) RID_INLINE])
26457 nomem_p = true;
26458 else if (storage == ridpointers[(int) RID_EXTERN])
26459 extern_p = true;
26460 else if (storage == ridpointers[(int) RID_STATIC])
26461 static_p = true;
26462 else
26463 error ("storage class %qD applied to template instantiation",
26464 storage);
26467 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26468 /* DR 259 [temp.spec].
26470 Both an explicit instantiation and a declaration of an explicit
26471 specialization shall not appear in a program unless the
26472 explicit instantiation follows a declaration of the explicit
26473 specialization.
26475 For a given set of template parameters, if an explicit
26476 instantiation of a template appears after a declaration of an
26477 explicit specialization for that template, the explicit
26478 instantiation has no effect. */
26479 return;
26481 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26483 /* We've already instantiated the template. */
26485 /* [temp.spec]
26487 No program shall explicitly instantiate any template more
26488 than once.
26490 If EXTERN_P then this is ok. */
26491 if (!extern_p && (complain & tf_error))
26492 permerror (input_location,
26493 "duplicate explicit instantiation of %q#T", t);
26495 return;
26498 check_explicit_instantiation_namespace (TYPE_NAME (t));
26499 mark_class_instantiated (t, extern_p);
26501 if (nomem_p)
26502 return;
26504 /* In contrast to implicit instantiation, where only the
26505 declarations, and not the definitions, of members are
26506 instantiated, we have here:
26508 [temp.explicit]
26510 An explicit instantiation that names a class template
26511 specialization is also an explicit instantiation of the same
26512 kind (declaration or definition) of each of its members (not
26513 including members inherited from base classes and members
26514 that are templates) that has not been previously explicitly
26515 specialized in the translation unit containing the explicit
26516 instantiation, provided that the associated constraints, if
26517 any, of that member are satisfied by the template arguments
26518 of the explicit instantiation. */
26519 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26520 if ((VAR_P (fld)
26521 || (TREE_CODE (fld) == FUNCTION_DECL
26522 && !static_p
26523 && user_provided_p (fld)))
26524 && DECL_TEMPLATE_INSTANTIATION (fld)
26525 && constraints_satisfied_p (fld))
26527 mark_decl_instantiated (fld, extern_p);
26528 if (! extern_p)
26529 instantiate_decl (fld, /*defer_ok=*/true,
26530 /*expl_inst_class_mem_p=*/true);
26532 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26534 tree type = TREE_TYPE (fld);
26536 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26537 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26538 do_type_instantiation (type, storage, 0);
26542 /* Given a function DECL, which is a specialization of TMPL, modify
26543 DECL to be a re-instantiation of TMPL with the same template
26544 arguments. TMPL should be the template into which tsubst'ing
26545 should occur for DECL, not the most general template.
26547 One reason for doing this is a scenario like this:
26549 template <class T>
26550 void f(const T&, int i);
26552 void g() { f(3, 7); }
26554 template <class T>
26555 void f(const T& t, const int i) { }
26557 Note that when the template is first instantiated, with
26558 instantiate_template, the resulting DECL will have no name for the
26559 first parameter, and the wrong type for the second. So, when we go
26560 to instantiate the DECL, we regenerate it. */
26562 static void
26563 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26565 /* The arguments used to instantiate DECL, from the most general
26566 template. */
26567 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26569 /* Make sure that we can see identifiers, and compute access correctly. */
26570 push_access_scope (decl);
26572 if (TREE_CODE (decl) == FUNCTION_DECL)
26574 tree specs;
26575 int args_depth;
26576 int parms_depth;
26578 /* Don't bother with this for unique friends that can't be redeclared and
26579 might change type if regenerated (PR69836). */
26580 if (DECL_UNIQUE_FRIEND_P (decl))
26581 goto done;
26583 /* Use the source location of the definition. */
26584 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26586 args_depth = TMPL_ARGS_DEPTH (args);
26587 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26588 if (args_depth > parms_depth)
26589 args = get_innermost_template_args (args, parms_depth);
26591 /* Instantiate a dynamic exception-specification. noexcept will be
26592 handled below. */
26593 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26594 if (TREE_VALUE (raises))
26596 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26597 args, tf_error, NULL_TREE,
26598 /*defer_ok*/false);
26599 if (specs && specs != error_mark_node)
26600 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26601 specs);
26604 /* Merge parameter declarations. */
26605 if (tree pattern_parm
26606 = skip_artificial_parms_for (code_pattern,
26607 DECL_ARGUMENTS (code_pattern)))
26609 tree *p = &DECL_ARGUMENTS (decl);
26610 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26611 p = &DECL_CHAIN (*p);
26612 *p = tsubst_decl (pattern_parm, args, tf_error);
26613 for (tree t = *p; t; t = DECL_CHAIN (t))
26614 DECL_CONTEXT (t) = decl;
26617 if (DECL_CONTRACTS (decl))
26619 /* If we're regenerating a specialization, the contracts will have
26620 been copied from the most general template. Replace those with
26621 the ones from the actual specialization. */
26622 tree tmpl = DECL_TI_TEMPLATE (decl);
26623 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26625 remove_contract_attributes (decl);
26626 copy_contract_attributes (decl, code_pattern);
26629 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26632 /* Merge additional specifiers from the CODE_PATTERN. */
26633 if (DECL_DECLARED_INLINE_P (code_pattern)
26634 && !DECL_DECLARED_INLINE_P (decl))
26635 DECL_DECLARED_INLINE_P (decl) = 1;
26637 maybe_instantiate_noexcept (decl, tf_error);
26639 else if (VAR_P (decl))
26641 start_lambda_scope (decl);
26642 DECL_INITIAL (decl) =
26643 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26644 tf_error, DECL_TI_TEMPLATE (decl));
26645 finish_lambda_scope ();
26646 if (VAR_HAD_UNKNOWN_BOUND (decl))
26647 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26648 tf_error, DECL_TI_TEMPLATE (decl));
26650 else
26651 gcc_unreachable ();
26653 done:
26654 pop_access_scope (decl);
26657 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26658 substituted to get DECL. */
26660 tree
26661 template_for_substitution (tree decl)
26663 tree tmpl = DECL_TI_TEMPLATE (decl);
26665 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26666 for the instantiation. This is not always the most general
26667 template. Consider, for example:
26669 template <class T>
26670 struct S { template <class U> void f();
26671 template <> void f<int>(); };
26673 and an instantiation of S<double>::f<int>. We want TD to be the
26674 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26675 while (/* An instantiation cannot have a definition, so we need a
26676 more general template. */
26677 DECL_TEMPLATE_INSTANTIATION (tmpl)
26678 /* We must also deal with friend templates. Given:
26680 template <class T> struct S {
26681 template <class U> friend void f() {};
26684 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26685 so far as the language is concerned, but that's still
26686 where we get the pattern for the instantiation from. On
26687 other hand, if the definition comes outside the class, say:
26689 template <class T> struct S {
26690 template <class U> friend void f();
26692 template <class U> friend void f() {}
26694 we don't need to look any further. That's what the check for
26695 DECL_INITIAL is for. */
26696 || (TREE_CODE (decl) == FUNCTION_DECL
26697 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26698 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26700 /* The present template, TD, should not be a definition. If it
26701 were a definition, we should be using it! Note that we
26702 cannot restructure the loop to just keep going until we find
26703 a template with a definition, since that might go too far if
26704 a specialization was declared, but not defined. */
26706 /* Fetch the more general template. */
26707 tmpl = DECL_TI_TEMPLATE (tmpl);
26710 return tmpl;
26713 /* Returns true if we need to instantiate this template instance even if we
26714 know we aren't going to emit it. */
26716 bool
26717 always_instantiate_p (tree decl)
26719 /* We always instantiate inline functions so that we can inline them. An
26720 explicit instantiation declaration prohibits implicit instantiation of
26721 non-inline functions. With high levels of optimization, we would
26722 normally inline non-inline functions -- but we're not allowed to do
26723 that for "extern template" functions. Therefore, we check
26724 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26725 return ((TREE_CODE (decl) == FUNCTION_DECL
26726 && (DECL_DECLARED_INLINE_P (decl)
26727 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26728 /* And we need to instantiate static data members so that
26729 their initializers are available in integral constant
26730 expressions. */
26731 || (VAR_P (decl)
26732 && decl_maybe_constant_var_p (decl)));
26735 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26736 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26737 error, true otherwise. */
26739 bool
26740 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26742 if (fn == error_mark_node)
26743 return false;
26745 /* Don't instantiate a noexcept-specification from template context. */
26746 if (processing_template_decl
26747 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26748 return true;
26750 tree fntype = TREE_TYPE (fn);
26751 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26753 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26754 && DECL_MAYBE_DELETED (fn))
26756 if (fn == current_function_decl)
26757 /* We're in start_preparsed_function, keep going. */
26758 return true;
26760 ++function_depth;
26761 maybe_synthesize_method (fn);
26762 --function_depth;
26763 return !DECL_DELETED_FN (fn);
26766 if (!spec || !TREE_PURPOSE (spec))
26767 return true;
26769 tree noex = TREE_PURPOSE (spec);
26770 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26771 && TREE_CODE (noex) != DEFERRED_PARSE)
26772 return true;
26774 tree orig_fn = NULL_TREE;
26775 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26776 its FUNCTION_DECL for the rest of this function -- push_access_scope
26777 doesn't accept TEMPLATE_DECLs. */
26778 if (DECL_FUNCTION_TEMPLATE_P (fn))
26780 orig_fn = fn;
26781 fn = DECL_TEMPLATE_RESULT (fn);
26784 if (DECL_CLONED_FUNCTION_P (fn))
26786 tree prime = DECL_CLONED_FUNCTION (fn);
26787 if (!maybe_instantiate_noexcept (prime, complain))
26788 return false;
26789 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26791 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26793 static hash_set<tree>* fns = new hash_set<tree>;
26794 bool added = false;
26795 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26797 spec = get_defaulted_eh_spec (fn, complain);
26798 if (spec == error_mark_node)
26799 /* This might have failed because of an unparsed DMI, so
26800 let's try again later. */
26801 return false;
26803 else if (!(added = !fns->add (fn)))
26805 /* If hash_set::add returns true, the element was already there. */
26806 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26807 DECL_SOURCE_LOCATION (fn));
26808 error_at (loc,
26809 "exception specification of %qD depends on itself",
26810 fn);
26811 spec = noexcept_false_spec;
26813 else if (push_tinst_level (fn))
26815 push_to_top_level ();
26816 push_access_scope (fn);
26817 push_deferring_access_checks (dk_no_deferred);
26818 input_location = DECL_SOURCE_LOCATION (fn);
26820 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
26821 && !DECL_LOCAL_DECL_P (fn))
26823 /* If needed, set current_class_ptr for the benefit of
26824 tsubst_copy/PARM_DECL. */
26825 tree this_parm = DECL_ARGUMENTS (fn);
26826 current_class_ptr = NULL_TREE;
26827 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26828 current_class_ptr = this_parm;
26831 /* If this function is represented by a TEMPLATE_DECL, then
26832 the deferred noexcept-specification might still contain
26833 dependent types, even after substitution. And we need the
26834 dependency check functions to work in build_noexcept_spec. */
26835 if (orig_fn)
26836 ++processing_template_decl;
26838 /* Do deferred instantiation of the noexcept-specifier. */
26839 noex = tsubst_expr (DEFERRED_NOEXCEPT_PATTERN (noex),
26840 DEFERRED_NOEXCEPT_ARGS (noex),
26841 tf_warning_or_error, fn);
26843 /* Build up the noexcept-specification. */
26844 spec = build_noexcept_spec (noex, tf_warning_or_error);
26846 if (orig_fn)
26847 --processing_template_decl;
26849 pop_deferring_access_checks ();
26850 pop_access_scope (fn);
26851 pop_tinst_level ();
26852 pop_from_top_level ();
26854 else
26855 spec = noexcept_false_spec;
26857 if (added)
26858 fns->remove (fn);
26861 if (spec == error_mark_node)
26863 /* This failed with a hard error, so let's go with false. */
26864 gcc_assert (seen_error ());
26865 spec = noexcept_false_spec;
26868 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26869 if (orig_fn)
26870 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26872 return true;
26875 /* We're starting to process the function INST, an instantiation of PATTERN;
26876 add their parameters to local_specializations. */
26878 void
26879 register_parameter_specializations (tree pattern, tree inst)
26881 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26882 tree spec_parm = DECL_ARGUMENTS (inst);
26883 if (DECL_IOBJ_MEMBER_FUNCTION_P (inst))
26885 register_local_specialization (spec_parm, tmpl_parm);
26886 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26887 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26889 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26891 if (!DECL_PACK_P (tmpl_parm))
26893 register_local_specialization (spec_parm, tmpl_parm);
26894 spec_parm = DECL_CHAIN (spec_parm);
26896 else
26898 /* Register the (value) argument pack as a specialization of
26899 TMPL_PARM, then move on. */
26900 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26901 register_local_specialization (argpack, tmpl_parm);
26904 gcc_assert (!spec_parm);
26907 /* Instantiate the body of D using PATTERN with ARGS. We have
26908 already determined PATTERN is the correct template to use.
26909 NESTED_P is true if this is a nested function, in which case
26910 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26912 static void
26913 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26915 tree td = NULL_TREE;
26916 tree code_pattern = pattern;
26918 if (!nested_p)
26920 td = pattern;
26921 code_pattern = DECL_TEMPLATE_RESULT (td);
26923 else
26924 /* Only OMP reductions are nested. */
26925 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26927 vec<tree> omp_privatization_save;
26928 if (current_function_decl)
26929 save_omp_privatization_clauses (omp_privatization_save);
26931 bool push_to_top = maybe_push_to_top_level (d);
26933 mark_template_arguments_used (pattern, args);
26935 if (VAR_P (d))
26937 /* The variable might be a lambda's extra scope, and that
26938 lambda's visibility depends on D's. */
26939 maybe_commonize_var (d);
26940 determine_visibility (d);
26943 /* Mark D as instantiated so that recursive calls to
26944 instantiate_decl do not try to instantiate it again. */
26945 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26947 if (td)
26948 /* Regenerate the declaration in case the template has been modified
26949 by a subsequent redeclaration. */
26950 regenerate_decl_from_template (d, td, args);
26952 /* We already set the file and line above. Reset them now in case
26953 they changed as a result of calling regenerate_decl_from_template. */
26954 input_location = DECL_SOURCE_LOCATION (d);
26956 if (VAR_P (d))
26958 /* Clear out DECL_RTL; whatever was there before may not be right
26959 since we've reset the type of the declaration. */
26960 SET_DECL_RTL (d, NULL);
26961 DECL_IN_AGGR_P (d) = 0;
26963 /* The initializer is placed in DECL_INITIAL by
26964 regenerate_decl_from_template so we don't need to
26965 push/pop_access_scope again here. Pull it out so that
26966 cp_finish_decl can process it. */
26967 bool const_init = false;
26968 tree init = DECL_INITIAL (d);
26969 DECL_INITIAL (d) = NULL_TREE;
26970 DECL_INITIALIZED_P (d) = 0;
26972 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26973 initializer. That function will defer actual emission until
26974 we have a chance to determine linkage. */
26975 DECL_EXTERNAL (d) = 0;
26977 /* Enter the scope of D so that access-checking works correctly. */
26978 bool enter_context = DECL_CLASS_SCOPE_P (d);
26979 if (enter_context)
26980 push_nested_class (DECL_CONTEXT (d));
26982 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26983 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26985 if (enter_context)
26986 pop_nested_class ();
26988 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26989 synthesize_method (d);
26990 else if (TREE_CODE (d) == FUNCTION_DECL)
26992 /* Set up the list of local specializations. */
26993 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26994 tree block = NULL_TREE;
26996 /* Set up context. */
26997 if (nested_p)
26998 block = push_stmt_list ();
26999 else
27001 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
27003 perform_instantiation_time_access_checks (code_pattern, args);
27006 /* Create substitution entries for the parameters. */
27007 register_parameter_specializations (code_pattern, d);
27009 /* Substitute into the body of the function. */
27010 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27011 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
27012 tf_warning_or_error, d);
27013 else
27015 tsubst_stmt (DECL_SAVED_TREE (code_pattern), args,
27016 tf_warning_or_error, DECL_TI_TEMPLATE (d));
27018 /* Set the current input_location to the end of the function
27019 so that finish_function knows where we are. */
27020 input_location
27021 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
27023 /* Remember if we saw an infinite loop in the template. */
27024 current_function_infinite_loop
27025 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
27028 /* Finish the function. */
27029 if (nested_p)
27030 DECL_SAVED_TREE (d) = pop_stmt_list (block);
27031 else
27033 d = finish_function (/*inline_p=*/false);
27034 expand_or_defer_fn (d);
27037 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27038 cp_check_omp_declare_reduction (d);
27041 /* We're not deferring instantiation any more. */
27042 if (!nested_p)
27043 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
27045 maybe_pop_from_top_level (push_to_top);
27047 if (current_function_decl)
27048 restore_omp_privatization_clauses (omp_privatization_save);
27051 /* Produce the definition of D, a _DECL generated from a template. If
27052 DEFER_OK is true, then we don't have to actually do the
27053 instantiation now; we just have to do it sometime. Normally it is
27054 an error if this is an explicit instantiation but D is undefined.
27055 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
27056 instantiated class template. */
27058 tree
27059 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
27061 tree tmpl = DECL_TI_TEMPLATE (d);
27062 tree gen_args;
27063 tree args;
27064 tree td;
27065 tree code_pattern;
27066 tree spec;
27067 tree gen_tmpl;
27068 bool pattern_defined;
27069 location_t saved_loc = input_location;
27070 bool external_p;
27071 bool deleted_p;
27073 /* This function should only be used to instantiate templates for
27074 functions and static member variables. */
27075 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
27077 /* A concept is never instantiated. */
27078 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
27080 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
27082 if (modules_p ())
27083 /* We may have a pending instantiation of D itself. */
27084 lazy_load_pendings (d);
27086 /* Variables are never deferred; if instantiation is required, they
27087 are instantiated right away. That allows for better code in the
27088 case that an expression refers to the value of the variable --
27089 if the variable has a constant value the referring expression can
27090 take advantage of that fact. */
27091 if (VAR_P (d))
27092 defer_ok = false;
27094 /* Don't instantiate cloned functions. Instead, instantiate the
27095 functions they cloned. */
27096 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27097 d = DECL_CLONED_FUNCTION (d);
27099 if (DECL_TEMPLATE_INSTANTIATED (d)
27100 || TREE_TYPE (d) == error_mark_node
27101 || (TREE_CODE (d) == FUNCTION_DECL
27102 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27103 || DECL_TEMPLATE_SPECIALIZATION (d))
27104 /* D has already been instantiated or explicitly specialized, so
27105 there's nothing for us to do here.
27107 It might seem reasonable to check whether or not D is an explicit
27108 instantiation, and, if so, stop here. But when an explicit
27109 instantiation is deferred until the end of the compilation,
27110 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27111 the instantiation. */
27112 return d;
27114 /* Check to see whether we know that this template will be
27115 instantiated in some other file, as with "extern template"
27116 extension. */
27117 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27119 /* In general, we do not instantiate such templates. */
27120 if (external_p && !always_instantiate_p (d))
27121 return d;
27123 gen_tmpl = most_general_template (tmpl);
27124 gen_args = DECL_TI_ARGS (d);
27126 /* We should already have the extra args. */
27127 gcc_checking_assert (tmpl == gen_tmpl
27128 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27129 == TMPL_ARGS_DEPTH (gen_args)));
27130 /* And what's in the hash table should match D. */
27131 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27132 == d
27133 || spec == NULL_TREE);
27135 /* This needs to happen before any tsubsting. */
27136 if (! push_tinst_level (d))
27137 return d;
27139 auto_timevar tv (TV_TEMPLATE_INST);
27141 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27142 for the instantiation. */
27143 td = template_for_substitution (d);
27144 args = gen_args;
27146 if (variable_template_specialization_p (d))
27148 /* Look up an explicit specialization, if any. */
27149 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27150 if (partial_ti && partial_ti != error_mark_node)
27152 td = TI_TEMPLATE (partial_ti);
27153 args = TI_ARGS (partial_ti);
27157 code_pattern = DECL_TEMPLATE_RESULT (td);
27159 /* We should never be trying to instantiate a member of a class
27160 template or partial specialization. */
27161 gcc_assert (d != code_pattern);
27163 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27164 || DECL_TEMPLATE_SPECIALIZATION (td))
27165 /* In the case of a friend template whose definition is provided
27166 outside the class, we may have too many arguments. Drop the
27167 ones we don't need. The same is true for specializations. */
27168 args = get_innermost_template_args
27169 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27171 if (TREE_CODE (d) == FUNCTION_DECL)
27173 deleted_p = DECL_DELETED_FN (code_pattern);
27174 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27175 && DECL_INITIAL (code_pattern) != error_mark_node)
27176 || DECL_DEFAULTED_FN (code_pattern)
27177 || deleted_p);
27179 else
27181 deleted_p = false;
27182 if (DECL_CLASS_SCOPE_P (code_pattern))
27183 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27184 else
27185 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27188 /* We may be in the middle of deferred access check. Disable it now. */
27189 push_deferring_access_checks (dk_no_deferred);
27191 /* Unless an explicit instantiation directive has already determined
27192 the linkage of D, remember that a definition is available for
27193 this entity. */
27194 if (pattern_defined
27195 && !DECL_INTERFACE_KNOWN (d)
27196 && !DECL_NOT_REALLY_EXTERN (d))
27197 mark_definable (d);
27199 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27200 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27201 input_location = DECL_SOURCE_LOCATION (d);
27203 /* If D is a member of an explicitly instantiated class template,
27204 and no definition is available, treat it like an implicit
27205 instantiation. */
27206 if (!pattern_defined && expl_inst_class_mem_p
27207 && DECL_EXPLICIT_INSTANTIATION (d))
27209 /* Leave linkage flags alone on instantiations with anonymous
27210 visibility. */
27211 if (TREE_PUBLIC (d))
27213 DECL_NOT_REALLY_EXTERN (d) = 0;
27214 DECL_INTERFACE_KNOWN (d) = 0;
27216 SET_DECL_IMPLICIT_INSTANTIATION (d);
27219 /* Defer all other templates, unless we have been explicitly
27220 forbidden from doing so. */
27221 if (/* If there is no definition, we cannot instantiate the
27222 template. */
27223 ! pattern_defined
27224 /* If it's OK to postpone instantiation, do so. */
27225 || defer_ok
27226 /* If this is a static data member that will be defined
27227 elsewhere, we don't want to instantiate the entire data
27228 member, but we do want to instantiate the initializer so that
27229 we can substitute that elsewhere. */
27230 || (external_p && VAR_P (d))
27231 /* Handle here a deleted function too, avoid generating
27232 its body (c++/61080). */
27233 || deleted_p)
27235 /* The definition of the static data member is now required so
27236 we must substitute the initializer. */
27237 if (VAR_P (d)
27238 && !DECL_INITIAL (d)
27239 && DECL_INITIAL (code_pattern))
27241 tree ns;
27242 tree init;
27243 bool const_init = false;
27244 bool enter_context = DECL_CLASS_SCOPE_P (d);
27246 ns = decl_namespace_context (d);
27247 push_nested_namespace (ns);
27248 if (enter_context)
27249 push_nested_class (DECL_CONTEXT (d));
27250 init = tsubst_expr (DECL_INITIAL (code_pattern),
27251 args,
27252 tf_warning_or_error, NULL_TREE);
27253 /* If instantiating the initializer involved instantiating this
27254 again, don't call cp_finish_decl twice. */
27255 if (!DECL_INITIAL (d))
27257 /* Make sure the initializer is still constant, in case of
27258 circular dependency (template/instantiate6.C). */
27259 const_init
27260 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27261 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27262 /*asmspec_tree=*/NULL_TREE, 0);
27264 if (enter_context)
27265 pop_nested_class ();
27266 pop_nested_namespace (ns);
27269 /* We restore the source position here because it's used by
27270 add_pending_template. */
27271 input_location = saved_loc;
27273 if (at_eof && !pattern_defined
27274 && DECL_EXPLICIT_INSTANTIATION (d)
27275 && DECL_NOT_REALLY_EXTERN (d))
27276 /* [temp.explicit]
27278 The definition of a non-exported function template, a
27279 non-exported member function template, or a non-exported
27280 member function or static data member of a class template
27281 shall be present in every translation unit in which it is
27282 explicitly instantiated. */
27283 permerror (input_location, "explicit instantiation of %qD "
27284 "but no definition available", d);
27286 /* If we're in unevaluated context, we just wanted to get the
27287 constant value; this isn't an odr use, so don't queue
27288 a full instantiation. */
27289 if (!cp_unevaluated_operand
27290 /* ??? Historically, we have instantiated inline functions, even
27291 when marked as "extern template". */
27292 && !(external_p && VAR_P (d)))
27293 add_pending_template (d);
27295 else
27297 set_instantiating_module (d);
27298 if (variable_template_p (gen_tmpl))
27299 note_vague_linkage_variable (d);
27300 instantiate_body (td, args, d, false);
27303 pop_deferring_access_checks ();
27304 pop_tinst_level ();
27305 input_location = saved_loc;
27307 return d;
27310 /* Run through the list of templates that we wish we could
27311 instantiate, and instantiate any we can. RETRIES is the
27312 number of times we retry pending template instantiation. */
27314 void
27315 instantiate_pending_templates (int retries)
27317 int reconsider;
27318 location_t saved_loc = input_location;
27320 /* Instantiating templates may trigger vtable generation. This in turn
27321 may require further template instantiations. We place a limit here
27322 to avoid infinite loop. */
27323 if (pending_templates && retries >= max_tinst_depth)
27325 tree decl = pending_templates->tinst->maybe_get_node ();
27327 fatal_error (input_location,
27328 "template instantiation depth exceeds maximum of %d"
27329 " instantiating %q+D, possibly from virtual table generation"
27330 " (use %<-ftemplate-depth=%> to increase the maximum)",
27331 max_tinst_depth, decl);
27332 if (TREE_CODE (decl) == FUNCTION_DECL)
27333 /* Pretend that we defined it. */
27334 DECL_INITIAL (decl) = error_mark_node;
27335 return;
27340 struct pending_template **t = &pending_templates;
27341 struct pending_template *last = NULL;
27342 reconsider = 0;
27343 while (*t)
27345 tree instantiation = reopen_tinst_level ((*t)->tinst);
27346 bool complete = false;
27348 if (TYPE_P (instantiation))
27350 if (!COMPLETE_TYPE_P (instantiation))
27352 instantiate_class_template (instantiation);
27353 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27354 for (tree fld = TYPE_FIELDS (instantiation);
27355 fld; fld = TREE_CHAIN (fld))
27356 if ((VAR_P (fld)
27357 || (TREE_CODE (fld) == FUNCTION_DECL
27358 && !DECL_ARTIFICIAL (fld)))
27359 && DECL_TEMPLATE_INSTANTIATION (fld))
27360 instantiate_decl (fld,
27361 /*defer_ok=*/false,
27362 /*expl_inst_class_mem_p=*/false);
27364 if (COMPLETE_TYPE_P (instantiation))
27365 reconsider = 1;
27368 complete = COMPLETE_TYPE_P (instantiation);
27370 else
27372 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27373 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27375 instantiation
27376 = instantiate_decl (instantiation,
27377 /*defer_ok=*/false,
27378 /*expl_inst_class_mem_p=*/false);
27379 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27380 reconsider = 1;
27383 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27384 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27387 if (complete)
27389 /* If INSTANTIATION has been instantiated, then we don't
27390 need to consider it again in the future. */
27391 struct pending_template *drop = *t;
27392 *t = (*t)->next;
27393 set_refcount_ptr (drop->tinst);
27394 pending_template_freelist ().free (drop);
27396 else
27398 last = *t;
27399 t = &(*t)->next;
27401 tinst_depth = 0;
27402 set_refcount_ptr (current_tinst_level);
27404 last_pending_template = last;
27406 while (reconsider);
27408 input_location = saved_loc;
27411 /* Substitute ARGVEC into T, which is a list of initializers for
27412 either base class or a non-static data member. The TREE_PURPOSEs
27413 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27414 instantiate_decl. */
27416 static tree
27417 tsubst_initializer_list (tree t, tree argvec)
27419 tree inits = NULL_TREE;
27420 tree target_ctor = error_mark_node;
27422 for (; t; t = TREE_CHAIN (t))
27424 tree decl;
27425 tree init;
27426 tree expanded_bases = NULL_TREE;
27427 tree expanded_arguments = NULL_TREE;
27428 int i, len = 1;
27430 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27432 tree expr;
27433 tree arg;
27435 /* Expand the base class expansion type into separate base
27436 classes. */
27437 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27438 tf_warning_or_error,
27439 NULL_TREE);
27440 if (expanded_bases == error_mark_node)
27441 continue;
27443 /* We'll be building separate TREE_LISTs of arguments for
27444 each base. */
27445 len = TREE_VEC_LENGTH (expanded_bases);
27446 expanded_arguments = make_tree_vec (len);
27447 for (i = 0; i < len; i++)
27448 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27450 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27451 expand each argument in the TREE_VALUE of t. */
27452 expr = make_node (EXPR_PACK_EXPANSION);
27453 PACK_EXPANSION_LOCAL_P (expr) = true;
27454 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27455 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27457 if (TREE_VALUE (t) == void_type_node)
27458 /* VOID_TYPE_NODE is used to indicate
27459 value-initialization. */
27461 for (i = 0; i < len; i++)
27462 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27464 else
27466 /* Substitute parameter packs into each argument in the
27467 TREE_LIST. */
27468 in_base_initializer = 1;
27469 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27471 tree expanded_exprs;
27473 /* Expand the argument. */
27474 tree value;
27475 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27476 value = TREE_VALUE (arg);
27477 else
27479 value = expr;
27480 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27482 expanded_exprs
27483 = tsubst_pack_expansion (value, argvec,
27484 tf_warning_or_error,
27485 NULL_TREE);
27486 if (expanded_exprs == error_mark_node)
27487 continue;
27489 /* Prepend each of the expanded expressions to the
27490 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27491 for (i = 0; i < len; i++)
27492 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27493 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27494 TREE_VEC_ELT (expanded_arguments, i)
27495 = tree_cons (NULL_TREE,
27496 TREE_VEC_ELT (expanded_exprs, j),
27497 TREE_VEC_ELT (expanded_arguments, i));
27498 else
27499 TREE_VEC_ELT (expanded_arguments, i)
27500 = tree_cons (NULL_TREE,
27501 TREE_VEC_ELT (expanded_exprs, i),
27502 TREE_VEC_ELT (expanded_arguments, i));
27504 in_base_initializer = 0;
27506 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27507 since we built them backwards. */
27508 for (i = 0; i < len; i++)
27510 TREE_VEC_ELT (expanded_arguments, i) =
27511 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27516 for (i = 0; i < len; ++i)
27518 if (expanded_bases)
27520 decl = TREE_VEC_ELT (expanded_bases, i);
27521 decl = expand_member_init (decl);
27522 init = TREE_VEC_ELT (expanded_arguments, i);
27524 else
27526 tree tmp;
27527 if (TYPE_P (TREE_PURPOSE (t)))
27528 decl = tsubst (TREE_PURPOSE (t), argvec,
27529 tf_warning_or_error, NULL_TREE);
27530 else
27531 decl = tsubst_expr (TREE_PURPOSE (t), argvec,
27532 tf_warning_or_error, NULL_TREE);
27534 decl = expand_member_init (decl);
27535 if (decl && !DECL_P (decl))
27536 in_base_initializer = 1;
27538 init = TREE_VALUE (t);
27539 tmp = init;
27540 if (init != void_type_node)
27541 init = tsubst_expr (init, argvec,
27542 tf_warning_or_error, NULL_TREE);
27543 if (init == NULL_TREE && tmp != NULL_TREE)
27544 /* If we had an initializer but it instantiated to nothing,
27545 value-initialize the object. This will only occur when
27546 the initializer was a pack expansion where the parameter
27547 packs used in that expansion were of length zero. */
27548 init = void_type_node;
27549 in_base_initializer = 0;
27552 if (target_ctor != error_mark_node
27553 && init != error_mark_node)
27555 error ("mem-initializer for %qD follows constructor delegation",
27556 decl);
27557 return inits;
27559 /* Look for a target constructor. */
27560 if (init != error_mark_node
27561 && decl && CLASS_TYPE_P (decl)
27562 && same_type_p (decl, current_class_type))
27564 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27565 if (inits)
27567 error ("constructor delegation follows mem-initializer for %qD",
27568 TREE_PURPOSE (inits));
27569 continue;
27571 target_ctor = init;
27574 if (decl)
27576 init = build_tree_list (decl, init);
27577 /* Carry over the dummy TREE_TYPE node containing the source
27578 location. */
27579 TREE_TYPE (init) = TREE_TYPE (t);
27580 TREE_CHAIN (init) = inits;
27581 inits = init;
27585 return inits;
27588 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27589 is the instantiation (which should have been created with
27590 start_enum) and ARGS are the template arguments to use. */
27592 static void
27593 tsubst_enum (tree tag, tree newtag, tree args)
27595 tree e;
27597 if (SCOPED_ENUM_P (newtag))
27598 begin_scope (sk_scoped_enum, newtag);
27600 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27602 tree value;
27603 tree decl = TREE_VALUE (e);
27605 /* Note that in a template enum, the TREE_VALUE is the
27606 CONST_DECL, not the corresponding INTEGER_CST. */
27607 value = tsubst_expr (DECL_INITIAL (decl),
27608 args, tf_warning_or_error, NULL_TREE);
27610 /* Give this enumeration constant the correct access. */
27611 set_current_access_from_decl (decl);
27613 /* Actually build the enumerator itself. Here we're assuming that
27614 enumerators can't have dependent attributes. */
27615 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27616 DECL_ATTRIBUTES (decl),
27617 DECL_SOURCE_LOCATION (decl));
27618 /* Attribute deprecated without an argument isn't sticky: it'll
27619 melt into a tree flag, so we need to propagate the flag here,
27620 since we just created a new enumerator. */
27621 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27622 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27625 if (SCOPED_ENUM_P (newtag))
27626 finish_scope ();
27628 finish_enum_value_list (newtag);
27629 finish_enum (newtag);
27631 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27632 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27633 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27634 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27637 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27638 its type -- but without substituting the innermost set of template
27639 arguments. So, innermost set of template parameters will appear in
27640 the type. */
27642 tree
27643 get_mostly_instantiated_function_type (tree decl)
27645 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27646 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27649 /* Return truthvalue if we're processing a template different from
27650 the last one involved in diagnostics. */
27651 bool
27652 problematic_instantiation_changed (void)
27654 return current_tinst_level != last_error_tinst_level;
27657 /* Remember current template involved in diagnostics. */
27658 void
27659 record_last_problematic_instantiation (void)
27661 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27664 struct tinst_level *
27665 current_instantiation (void)
27667 return current_tinst_level;
27670 /* Return TRUE if current_function_decl is being instantiated, false
27671 otherwise. */
27673 bool
27674 instantiating_current_function_p (void)
27676 return (current_instantiation ()
27677 && (current_instantiation ()->maybe_get_node ()
27678 == current_function_decl));
27681 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27682 type. Return false for ok, true for disallowed. Issue error and
27683 inform messages under control of COMPLAIN. */
27685 static bool
27686 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27688 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27689 return false;
27690 else if (TYPE_PTR_P (type))
27691 return false;
27692 else if (TYPE_REF_P (type)
27693 && !TYPE_REF_IS_RVALUE (type))
27694 return false;
27695 else if (TYPE_PTRMEM_P (type))
27696 return false;
27697 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27699 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27701 if (complain & tf_error)
27702 error ("non-type template parameters of deduced class type only "
27703 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27704 return true;
27706 return false;
27708 else if (TREE_CODE (type) == NULLPTR_TYPE)
27709 return false;
27710 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27711 && cxx_dialect < cxx11)
27712 /* Fall through; before C++11 alias templates, a bound ttp
27713 always instantiates into a class type. */;
27714 else if (WILDCARD_TYPE_P (type))
27715 /* Any other wildcard type not already handled above is allowed. */
27716 return false;
27717 else if (TREE_CODE (type) == COMPLEX_TYPE)
27718 /* Fall through. */;
27719 else if (VOID_TYPE_P (type))
27720 /* Fall through. */;
27721 else if (cxx_dialect >= cxx20)
27723 if (dependent_type_p (type))
27724 return false;
27725 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27726 return true;
27727 if (structural_type_p (type))
27728 return false;
27729 if (complain & tf_error)
27731 auto_diagnostic_group d;
27732 error ("%qT is not a valid type for a template non-type "
27733 "parameter because it is not structural", type);
27734 structural_type_p (type, true);
27736 return true;
27738 else if (CLASS_TYPE_P (type))
27740 if (complain & tf_error)
27741 error ("non-type template parameters of class type only available "
27742 "with %<-std=c++20%> or %<-std=gnu++20%>");
27743 return true;
27746 if (complain & tf_error)
27748 if (type == error_mark_node)
27749 inform (input_location, "invalid template non-type parameter");
27750 else
27751 error ("%q#T is not a valid type for a template non-type parameter",
27752 type);
27754 return true;
27757 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27759 static bool
27760 value_dependent_noexcept_spec_p (tree type)
27762 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27763 if (tree noex = TREE_PURPOSE (spec))
27764 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27765 affect overload resolution and treating it as dependent breaks
27766 things. Same for an unparsed noexcept expression. */
27767 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27768 && TREE_CODE (noex) != DEFERRED_PARSE
27769 && value_dependent_expression_p (noex))
27770 return true;
27772 return false;
27775 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27776 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27778 static bool
27779 dependent_type_p_r (tree type)
27781 tree scope;
27783 /* [temp.dep.type]
27785 A type is dependent if it is:
27787 -- a template parameter. Template template parameters are types
27788 for us (since TYPE_P holds true for them) so we handle
27789 them here. */
27790 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27791 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27792 return true;
27793 /* -- a qualified-id with a nested-name-specifier which contains a
27794 class-name that names a dependent type or whose unqualified-id
27795 names a dependent type. */
27796 if (TREE_CODE (type) == TYPENAME_TYPE)
27797 return true;
27799 /* An alias template specialization can be dependent even if the
27800 resulting type is not. */
27801 if (dependent_alias_template_spec_p (type, nt_transparent))
27802 return true;
27804 /* -- a cv-qualified type where the cv-unqualified type is
27805 dependent.
27806 No code is necessary for this bullet; the code below handles
27807 cv-qualified types, and we don't want to strip aliases with
27808 TYPE_MAIN_VARIANT because of DR 1558. */
27809 /* -- a compound type constructed from any dependent type. */
27810 if (TYPE_PTRMEM_P (type))
27811 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27812 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27813 (type)));
27814 else if (INDIRECT_TYPE_P (type))
27815 return dependent_type_p (TREE_TYPE (type));
27816 else if (FUNC_OR_METHOD_TYPE_P (type))
27818 tree arg_type;
27820 if (dependent_type_p (TREE_TYPE (type)))
27821 return true;
27822 for (arg_type = TYPE_ARG_TYPES (type);
27823 arg_type;
27824 arg_type = TREE_CHAIN (arg_type))
27825 if (dependent_type_p (TREE_VALUE (arg_type)))
27826 return true;
27827 if (cxx_dialect >= cxx17
27828 && value_dependent_noexcept_spec_p (type))
27829 /* A value-dependent noexcept-specifier makes the type dependent. */
27830 return true;
27831 return false;
27833 /* -- an array type constructed from any dependent type or whose
27834 size is specified by a constant expression that is
27835 value-dependent.
27837 We checked for type- and value-dependence of the bounds in
27838 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27839 if (TREE_CODE (type) == ARRAY_TYPE)
27841 if (TYPE_DOMAIN (type)
27842 && dependent_type_p (TYPE_DOMAIN (type)))
27843 return true;
27844 return dependent_type_p (TREE_TYPE (type));
27847 /* -- a template-id in which either the template name is a template
27848 parameter ... */
27849 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27850 return true;
27851 /* ... or any of the template arguments is a dependent type or
27852 an expression that is type-dependent or value-dependent. */
27853 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27854 && (any_dependent_template_arguments_p
27855 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27856 return true;
27858 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27859 dependent; if the argument of the `typeof' expression is not
27860 type-dependent, then it should already been have resolved. */
27861 if (TREE_CODE (type) == TYPEOF_TYPE
27862 || TREE_CODE (type) == DECLTYPE_TYPE
27863 || TREE_CODE (type) == TRAIT_TYPE)
27864 return true;
27866 /* A template argument pack is dependent if any of its packed
27867 arguments are. */
27868 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27870 tree args = ARGUMENT_PACK_ARGS (type);
27871 for (tree arg : tree_vec_range (args))
27872 if (dependent_template_arg_p (arg))
27873 return true;
27876 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27877 be template parameters. */
27878 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27879 return true;
27881 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27882 return true;
27884 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27885 return true;
27887 /* The standard does not specifically mention types that are local
27888 to template functions or local classes, but they should be
27889 considered dependent too. For example:
27891 template <int I> void f() {
27892 enum E { a = I };
27893 S<sizeof (E)> s;
27896 The size of `E' cannot be known until the value of `I' has been
27897 determined. Therefore, `E' must be considered dependent. */
27898 scope = TYPE_CONTEXT (type);
27899 if (scope && TYPE_P (scope))
27900 return dependent_type_p (scope);
27901 /* Don't use type_dependent_expression_p here, as it can lead
27902 to infinite recursion trying to determine whether a lambda
27903 nested in a lambda is dependent (c++/47687). */
27904 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27905 && DECL_LANG_SPECIFIC (scope)
27906 && DECL_TEMPLATE_INFO (scope)
27907 && (any_dependent_template_arguments_p
27908 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27909 return true;
27911 /* Other types are non-dependent. */
27912 return false;
27915 /* Returns TRUE if TYPE is dependent, in the sense of
27916 [temp.dep.type]. Note that a NULL type is considered dependent. */
27918 bool
27919 dependent_type_p (tree type)
27921 /* If there are no template parameters in scope, then there can't be
27922 any dependent types. */
27923 if (!processing_template_decl)
27925 /* If we are not processing a template, then nobody should be
27926 providing us with a dependent type. */
27927 gcc_assert (type);
27928 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27929 return false;
27932 /* If the type is NULL, we have not computed a type for the entity
27933 in question; in that case, the type is dependent. */
27934 if (!type)
27935 return true;
27937 /* Erroneous types can be considered non-dependent. */
27938 if (type == error_mark_node)
27939 return false;
27941 /* If we have not already computed the appropriate value for TYPE,
27942 do so now. */
27943 if (!TYPE_DEPENDENT_P_VALID (type))
27945 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27946 TYPE_DEPENDENT_P_VALID (type) = 1;
27949 return TYPE_DEPENDENT_P (type);
27952 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27953 lookup. In other words, a dependent type that is not the current
27954 instantiation. */
27956 bool
27957 dependent_scope_p (tree scope)
27959 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27960 && !currently_open_class (scope));
27963 /* True if we might find more declarations in SCOPE during instantiation than
27964 we can when parsing the template. */
27966 bool
27967 dependentish_scope_p (tree scope)
27969 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27972 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27973 an unknown base of 'this' (and is therefore instantiation-dependent). */
27975 static bool
27976 unknown_base_ref_p (tree t)
27978 if (!current_class_ptr)
27979 return false;
27981 tree mem = TREE_OPERAND (t, 1);
27982 if (shared_member_p (mem))
27983 return false;
27985 tree cur = current_nonlambda_class_type ();
27986 if (!any_dependent_bases_p (cur))
27987 return false;
27989 tree ctx = TREE_OPERAND (t, 0);
27990 if (DERIVED_FROM_P (ctx, cur))
27991 return false;
27993 return true;
27996 /* T is a SCOPE_REF; return whether we need to consider it
27997 instantiation-dependent so that we can check access at instantiation
27998 time even though we know which member it resolves to. */
28000 static bool
28001 instantiation_dependent_scope_ref_p (tree t)
28003 if (DECL_P (TREE_OPERAND (t, 1))
28004 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
28005 && !dependent_scope_p (TREE_OPERAND (t, 0))
28006 && !unknown_base_ref_p (t)
28007 && accessible_in_template_p (TREE_OPERAND (t, 0),
28008 TREE_OPERAND (t, 1)))
28009 return false;
28010 else
28011 return true;
28014 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
28015 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
28016 expression. */
28018 /* Note that this predicate is not appropriate for general expressions;
28019 only constant expressions (that satisfy potential_constant_expression)
28020 can be tested for value dependence. */
28022 bool
28023 value_dependent_expression_p (tree expression)
28025 if (!processing_template_decl || expression == NULL_TREE)
28026 return false;
28028 /* A type-dependent expression is also value-dependent. */
28029 if (type_dependent_expression_p (expression))
28030 return true;
28032 switch (TREE_CODE (expression))
28034 case BASELINK:
28035 /* A dependent member function of the current instantiation. */
28036 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
28038 case FUNCTION_DECL:
28039 /* A dependent member function of the current instantiation. */
28040 if (DECL_CLASS_SCOPE_P (expression)
28041 && dependent_type_p (DECL_CONTEXT (expression)))
28042 return true;
28043 break;
28045 case IDENTIFIER_NODE:
28046 /* A name that has not been looked up -- must be dependent. */
28047 return true;
28049 case TEMPLATE_PARM_INDEX:
28050 /* A non-type template parm. */
28051 return true;
28053 case CONST_DECL:
28054 /* A non-type template parm. */
28055 if (DECL_TEMPLATE_PARM_P (expression))
28056 return true;
28057 return value_dependent_expression_p (DECL_INITIAL (expression));
28059 case VAR_DECL:
28060 /* A constant with literal type and is initialized
28061 with an expression that is value-dependent. */
28062 if (DECL_DEPENDENT_INIT_P (expression))
28063 return true;
28064 if (DECL_HAS_VALUE_EXPR_P (expression))
28066 tree value_expr = DECL_VALUE_EXPR (expression);
28067 if (value_dependent_expression_p (value_expr)
28068 /* __PRETTY_FUNCTION__ inside a template function is dependent
28069 on the name of the function. */
28070 || (DECL_PRETTY_FUNCTION_P (expression)
28071 /* It might be used in a template, but not a template
28072 function, in which case its DECL_VALUE_EXPR will be
28073 "top level". */
28074 && value_expr == error_mark_node))
28075 return true;
28077 else if (TYPE_REF_P (TREE_TYPE (expression)))
28078 /* FIXME cp_finish_decl doesn't fold reference initializers. */
28079 return true;
28080 /* We have a constexpr variable and we're processing a template. When
28081 there's lifetime extension involved (for which finish_compound_literal
28082 used to create a temporary), we'll not be able to evaluate the
28083 variable until instantiating, so pretend it's value-dependent. */
28084 else if (DECL_DECLARED_CONSTEXPR_P (expression)
28085 && !TREE_CONSTANT (expression))
28086 return true;
28087 return false;
28089 case DYNAMIC_CAST_EXPR:
28090 case STATIC_CAST_EXPR:
28091 case CONST_CAST_EXPR:
28092 case REINTERPRET_CAST_EXPR:
28093 case CAST_EXPR:
28094 case IMPLICIT_CONV_EXPR:
28095 /* These expressions are value-dependent if the type to which
28096 the cast occurs is dependent or the expression being casted
28097 is value-dependent. */
28099 tree type = TREE_TYPE (expression);
28101 if (dependent_type_p (type))
28102 return true;
28104 /* A functional cast has a list of operands. */
28105 expression = TREE_OPERAND (expression, 0);
28106 if (!expression)
28108 /* If there are no operands, it must be an expression such
28109 as "int()". This should not happen for aggregate types
28110 because it would form non-constant expressions. */
28111 gcc_assert (cxx_dialect >= cxx11
28112 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28114 return false;
28117 if (TREE_CODE (expression) == TREE_LIST)
28118 return any_value_dependent_elements_p (expression);
28120 if (TREE_CODE (type) == REFERENCE_TYPE
28121 && has_value_dependent_address (expression))
28122 return true;
28124 return value_dependent_expression_p (expression);
28127 case SIZEOF_EXPR:
28128 if (SIZEOF_EXPR_TYPE_P (expression))
28129 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28130 /* FALLTHRU */
28131 case ALIGNOF_EXPR:
28132 case TYPEID_EXPR:
28133 /* A `sizeof' expression is value-dependent if the operand is
28134 type-dependent or is a pack expansion. */
28135 expression = TREE_OPERAND (expression, 0);
28136 if (PACK_EXPANSION_P (expression))
28137 return true;
28138 else if (TYPE_P (expression))
28139 return dependent_type_p (expression);
28140 return instantiation_dependent_uneval_expression_p (expression);
28142 case AT_ENCODE_EXPR:
28143 /* An 'encode' expression is value-dependent if the operand is
28144 type-dependent. */
28145 expression = TREE_OPERAND (expression, 0);
28146 return dependent_type_p (expression);
28148 case NOEXCEPT_EXPR:
28149 expression = TREE_OPERAND (expression, 0);
28150 return instantiation_dependent_uneval_expression_p (expression);
28152 case SCOPE_REF:
28153 /* All instantiation-dependent expressions should also be considered
28154 value-dependent. */
28155 return instantiation_dependent_scope_ref_p (expression);
28157 case COMPONENT_REF:
28158 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28159 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28161 case NONTYPE_ARGUMENT_PACK:
28162 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28163 is value-dependent. */
28164 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28165 if (value_dependent_expression_p (arg))
28166 return true;
28167 return false;
28169 case TRAIT_EXPR:
28171 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28172 return true;
28174 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28175 if (!type2)
28176 return false;
28178 if (TREE_CODE (type2) != TREE_VEC)
28179 return dependent_type_p (type2);
28181 for (tree arg : tree_vec_range (type2))
28182 if (dependent_type_p (arg))
28183 return true;
28185 return false;
28188 case MODOP_EXPR:
28189 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28190 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28192 case ARRAY_REF:
28193 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28194 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28196 case ADDR_EXPR:
28198 tree op = TREE_OPERAND (expression, 0);
28199 return (value_dependent_expression_p (op)
28200 || has_value_dependent_address (op));
28203 case REQUIRES_EXPR:
28204 /* Treat all requires-expressions as value-dependent so
28205 we don't try to fold them. */
28206 return true;
28208 case TYPE_REQ:
28209 return dependent_type_p (TREE_OPERAND (expression, 0));
28211 case CALL_EXPR:
28213 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28214 return true;
28215 tree fn = get_callee_fndecl (expression);
28216 int i, nargs;
28217 nargs = call_expr_nargs (expression);
28218 for (i = 0; i < nargs; ++i)
28220 tree op = CALL_EXPR_ARG (expression, i);
28221 /* In a call to a constexpr member function, look through the
28222 implicit ADDR_EXPR on the object argument so that it doesn't
28223 cause the call to be considered value-dependent. We also
28224 look through it in potential_constant_expression. */
28225 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28226 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
28227 && TREE_CODE (op) == ADDR_EXPR)
28228 op = TREE_OPERAND (op, 0);
28229 if (value_dependent_expression_p (op))
28230 return true;
28232 return false;
28235 case TEMPLATE_ID_EXPR:
28236 return concept_definition_p (TREE_OPERAND (expression, 0))
28237 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28239 case CONSTRUCTOR:
28241 unsigned ix;
28242 tree val;
28243 if (dependent_type_p (TREE_TYPE (expression)))
28244 return true;
28245 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28246 if (value_dependent_expression_p (val))
28247 return true;
28248 return false;
28251 case STMT_EXPR:
28252 /* Treat a GNU statement expression as dependent to avoid crashing
28253 under instantiate_non_dependent_expr; it can't be constant. */
28254 return true;
28256 case NEW_EXPR:
28257 case VEC_NEW_EXPR:
28258 /* The second operand is a type, which type_dependent_expression_p
28259 (and therefore value_dependent_expression_p) doesn't want to see. */
28260 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28261 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28262 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28264 default:
28265 /* A constant expression is value-dependent if any subexpression is
28266 value-dependent. */
28267 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28269 case tcc_reference:
28270 case tcc_unary:
28271 case tcc_comparison:
28272 case tcc_binary:
28273 case tcc_expression:
28274 case tcc_vl_exp:
28276 int i, len = cp_tree_operand_length (expression);
28278 for (i = 0; i < len; i++)
28280 tree t = TREE_OPERAND (expression, i);
28282 /* In some cases, some of the operands may be missing.
28283 (For example, in the case of PREDECREMENT_EXPR, the
28284 amount to increment by may be missing.) That doesn't
28285 make the expression dependent. */
28286 if (t && value_dependent_expression_p (t))
28287 return true;
28290 break;
28291 default:
28292 break;
28294 break;
28297 /* The expression is not value-dependent. */
28298 return false;
28301 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28302 [temp.dep.expr]. Note that an expression with no type is
28303 considered dependent. Other parts of the compiler arrange for an
28304 expression with type-dependent subexpressions to have no type, so
28305 this function doesn't have to be fully recursive. */
28307 bool
28308 type_dependent_expression_p (tree expression)
28310 if (!processing_template_decl)
28311 return false;
28313 if (expression == NULL_TREE || expression == error_mark_node)
28314 return false;
28316 gcc_checking_assert (!TYPE_P (expression));
28318 STRIP_ANY_LOCATION_WRAPPER (expression);
28320 /* An unresolved name is always dependent. */
28321 if (identifier_p (expression)
28322 || TREE_CODE (expression) == USING_DECL
28323 || TREE_CODE (expression) == WILDCARD_DECL)
28324 return true;
28326 /* A lambda-expression in template context is dependent. dependent_type_p is
28327 true for a lambda in the scope of a class or function template, but that
28328 doesn't cover all template contexts, like a default template argument. */
28329 if (TREE_CODE (expression) == LAMBDA_EXPR)
28330 return true;
28332 /* A fold expression is type-dependent. */
28333 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28334 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28335 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28336 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28337 return true;
28339 /* Some expression forms are never type-dependent. */
28340 if (TREE_CODE (expression) == SIZEOF_EXPR
28341 || TREE_CODE (expression) == ALIGNOF_EXPR
28342 || TREE_CODE (expression) == AT_ENCODE_EXPR
28343 || TREE_CODE (expression) == NOEXCEPT_EXPR
28344 || TREE_CODE (expression) == TRAIT_EXPR
28345 || TREE_CODE (expression) == TYPEID_EXPR
28346 || TREE_CODE (expression) == DELETE_EXPR
28347 || TREE_CODE (expression) == VEC_DELETE_EXPR
28348 || TREE_CODE (expression) == THROW_EXPR
28349 || TREE_CODE (expression) == REQUIRES_EXPR)
28350 return false;
28352 /* The types of these expressions depends only on the type to which
28353 the cast occurs. */
28354 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28355 || TREE_CODE (expression) == STATIC_CAST_EXPR
28356 || TREE_CODE (expression) == CONST_CAST_EXPR
28357 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28358 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28359 || TREE_CODE (expression) == CAST_EXPR)
28360 return dependent_type_p (TREE_TYPE (expression));
28362 /* The types of these expressions depends only on the type created
28363 by the expression. */
28364 if (TREE_CODE (expression) == NEW_EXPR
28365 || TREE_CODE (expression) == VEC_NEW_EXPR)
28367 /* For NEW_EXPR tree nodes created inside a template, either
28368 the object type itself or a TREE_LIST may appear as the
28369 operand 1. */
28370 tree type = TREE_OPERAND (expression, 1);
28371 if (TREE_CODE (type) == TREE_LIST)
28372 /* This is an array type. We need to check array dimensions
28373 as well. */
28374 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28375 || value_dependent_expression_p
28376 (TREE_OPERAND (TREE_VALUE (type), 1));
28377 /* Array type whose dimension has to be deduced. */
28378 else if (TREE_CODE (type) == ARRAY_TYPE
28379 && TREE_OPERAND (expression, 2) == NULL_TREE)
28380 return true;
28381 else
28382 return dependent_type_p (type);
28385 if (TREE_CODE (expression) == SCOPE_REF)
28387 tree scope = TREE_OPERAND (expression, 0);
28388 tree name = TREE_OPERAND (expression, 1);
28390 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28391 contains an identifier associated by name lookup with one or more
28392 declarations declared with a dependent type, or...a
28393 nested-name-specifier or qualified-id that names a member of an
28394 unknown specialization. */
28395 return (type_dependent_expression_p (name)
28396 || dependent_scope_p (scope));
28399 if (TREE_CODE (expression) == TEMPLATE_DECL
28400 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28401 return uses_outer_template_parms (expression);
28403 if (TREE_CODE (expression) == STMT_EXPR)
28404 expression = stmt_expr_value_expr (expression);
28406 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28408 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28409 if (type_dependent_expression_p (elt.value))
28410 return true;
28411 return false;
28414 /* A static data member of the current instantiation with incomplete
28415 array type is type-dependent, as the definition and specializations
28416 can have different bounds. */
28417 if (VAR_P (expression)
28418 && DECL_CLASS_SCOPE_P (expression)
28419 && dependent_type_p (DECL_CONTEXT (expression))
28420 && VAR_HAD_UNKNOWN_BOUND (expression))
28421 return true;
28423 /* An array of unknown bound depending on a variadic parameter, eg:
28425 template<typename... Args>
28426 void foo (Args... args)
28428 int arr[] = { args... };
28431 template<int... vals>
28432 void bar ()
28434 int arr[] = { vals... };
28437 If the array has no length and has an initializer, it must be that
28438 we couldn't determine its length in cp_complete_array_type because
28439 it is dependent. */
28440 if (((VAR_P (expression) && DECL_INITIAL (expression))
28441 || COMPOUND_LITERAL_P (expression))
28442 && TREE_TYPE (expression) != NULL_TREE
28443 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28444 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28445 return true;
28447 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28448 if (BASELINK_P (expression))
28450 if (BASELINK_OPTYPE (expression)
28451 && dependent_type_p (BASELINK_OPTYPE (expression)))
28452 return true;
28453 expression = BASELINK_FUNCTIONS (expression);
28456 /* A function or variable template-id is type-dependent if it has any
28457 dependent template arguments. */
28458 if (VAR_OR_FUNCTION_DECL_P (expression)
28459 && DECL_LANG_SPECIFIC (expression)
28460 && DECL_TEMPLATE_INFO (expression))
28462 /* Consider the innermost template arguments, since those are the ones
28463 that come from the template-id; the template arguments for the
28464 enclosing class do not make it type-dependent unless they are used in
28465 the type of the decl. */
28466 if (instantiates_primary_template_p (expression)
28467 && (any_dependent_template_arguments_p
28468 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28469 return true;
28472 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28473 type-dependent. Checking this is important for functions with auto return
28474 type, which looks like a dependent type. */
28475 if (TREE_CODE (expression) == FUNCTION_DECL
28476 && !(DECL_CLASS_SCOPE_P (expression)
28477 && dependent_type_p (DECL_CONTEXT (expression)))
28478 && !(DECL_LANG_SPECIFIC (expression)
28479 && DECL_UNIQUE_FRIEND_P (expression)
28480 && (!DECL_FRIEND_CONTEXT (expression)
28481 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28482 && !DECL_LOCAL_DECL_P (expression))
28484 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28485 || undeduced_auto_decl (expression));
28486 return false;
28489 /* Otherwise, its constraints could still depend on outer template parameters
28490 from its (dependent) scope. */
28491 if (TREE_CODE (expression) == FUNCTION_DECL
28492 /* As an optimization, check this cheaper sufficient condition first.
28493 (At this point we've established that we're looking at a member of
28494 a dependent class, so it makes sense to start treating say undeduced
28495 auto as dependent.) */
28496 && !dependent_type_p (TREE_TYPE (expression))
28497 && uses_outer_template_parms_in_constraints (expression))
28498 return true;
28500 /* Always dependent, on the number of arguments if nothing else. */
28501 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28502 return true;
28504 if (TREE_TYPE (expression) == unknown_type_node)
28506 if (TREE_CODE (expression) == ADDR_EXPR)
28507 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28508 if (TREE_CODE (expression) == COMPONENT_REF
28509 || TREE_CODE (expression) == OFFSET_REF)
28511 if (type_dependent_object_expression_p (TREE_OPERAND (expression, 0)))
28512 return true;
28513 expression = TREE_OPERAND (expression, 1);
28514 if (identifier_p (expression))
28515 return false;
28517 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28518 if (TREE_CODE (expression) == SCOPE_REF)
28519 return false;
28521 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28522 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28523 || TREE_CODE (expression) == CO_YIELD_EXPR)
28524 return true;
28526 if (BASELINK_P (expression))
28528 if (BASELINK_OPTYPE (expression)
28529 && dependent_type_p (BASELINK_OPTYPE (expression)))
28530 return true;
28531 expression = BASELINK_FUNCTIONS (expression);
28534 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28536 if (any_dependent_template_arguments_p
28537 (TREE_OPERAND (expression, 1)))
28538 return true;
28539 expression = TREE_OPERAND (expression, 0);
28540 if (identifier_p (expression))
28541 return true;
28544 gcc_assert (OVL_P (expression));
28546 for (lkp_iterator iter (expression); iter; ++iter)
28547 if (type_dependent_expression_p (*iter))
28548 return true;
28550 return false;
28553 /* The type of a non-type template parm declared with a placeholder type
28554 depends on the corresponding template argument, even though
28555 placeholders are not normally considered dependent. */
28556 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28557 && is_auto (TREE_TYPE (expression)))
28558 return true;
28560 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28562 /* Dependent type attributes might not have made it from the decl to
28563 the type yet. */
28564 if (DECL_P (expression)
28565 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28566 return true;
28568 return (dependent_type_p (TREE_TYPE (expression)));
28571 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28572 type-dependent if the expression refers to a member of the current
28573 instantiation and the type of the referenced member is dependent, or the
28574 class member access expression refers to a member of an unknown
28575 specialization.
28577 This function returns true if the OBJECT in such a class member access
28578 expression is of an unknown specialization. */
28580 bool
28581 type_dependent_object_expression_p (tree object)
28583 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28584 dependent. */
28585 if (TREE_CODE (object) == IDENTIFIER_NODE)
28586 return true;
28587 tree scope = TREE_TYPE (object);
28588 return (!scope || dependent_scope_p (scope));
28591 /* walk_tree callback function for instantiation_dependent_expression_p,
28592 below. Returns non-zero if a dependent subexpression is found. */
28594 static tree
28595 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28596 void * /*data*/)
28598 if (TYPE_P (*tp))
28600 /* We don't have to worry about decltype currently because decltype
28601 of an instantiation-dependent expr is a dependent type. This
28602 might change depending on the resolution of DR 1172. */
28603 *walk_subtrees = false;
28604 return NULL_TREE;
28606 enum tree_code code = TREE_CODE (*tp);
28607 switch (code)
28609 /* Don't treat an argument list as dependent just because it has no
28610 TREE_TYPE. */
28611 case TREE_LIST:
28612 case TREE_VEC:
28613 case NONTYPE_ARGUMENT_PACK:
28614 return NULL_TREE;
28616 case TEMPLATE_PARM_INDEX:
28617 if (dependent_type_p (TREE_TYPE (*tp)))
28618 return *tp;
28619 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28620 return *tp;
28621 /* We'll check value-dependence separately. */
28622 return NULL_TREE;
28624 /* Handle expressions with type operands. */
28625 case SIZEOF_EXPR:
28626 case ALIGNOF_EXPR:
28627 case TYPEID_EXPR:
28628 case AT_ENCODE_EXPR:
28630 tree op = TREE_OPERAND (*tp, 0);
28631 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28632 op = TREE_TYPE (op);
28633 if (TYPE_P (op))
28635 if (dependent_type_p (op))
28636 return *tp;
28637 else
28639 *walk_subtrees = false;
28640 return NULL_TREE;
28643 break;
28646 case COMPONENT_REF:
28647 if (identifier_p (TREE_OPERAND (*tp, 1)))
28648 /* In a template, finish_class_member_access_expr creates a
28649 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28650 type-dependent, so that we can check access control at
28651 instantiation time (PR 42277). See also Core issue 1273. */
28652 return *tp;
28653 break;
28655 case SCOPE_REF:
28656 if (instantiation_dependent_scope_ref_p (*tp))
28657 return *tp;
28658 else
28659 break;
28661 /* Treat statement-expressions as dependent. */
28662 case BIND_EXPR:
28663 return *tp;
28665 /* Treat requires-expressions as dependent. */
28666 case REQUIRES_EXPR:
28667 return *tp;
28669 case CONSTRUCTOR:
28670 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28671 return *tp;
28672 break;
28674 case TEMPLATE_DECL:
28675 case FUNCTION_DECL:
28676 /* Before C++17, a noexcept-specifier isn't part of the function type
28677 so it doesn't affect type dependence, but we still want to consider it
28678 for instantiation dependence. */
28679 if (cxx_dialect < cxx17
28680 && DECL_DECLARES_FUNCTION_P (*tp)
28681 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28682 return *tp;
28683 break;
28685 default:
28686 break;
28689 if (type_dependent_expression_p (*tp))
28690 return *tp;
28691 else
28692 return NULL_TREE;
28695 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28696 sense defined by the ABI:
28698 "An expression is instantiation-dependent if it is type-dependent
28699 or value-dependent, or it has a subexpression that is type-dependent
28700 or value-dependent."
28702 Except don't actually check value-dependence for unevaluated expressions,
28703 because in sizeof(i) we don't care about the value of i. Checking
28704 type-dependence will in turn check value-dependence of array bounds/template
28705 arguments as needed. */
28707 bool
28708 instantiation_dependent_uneval_expression_p (tree expression)
28710 tree result;
28712 if (!processing_template_decl)
28713 return false;
28715 if (expression == error_mark_node)
28716 return false;
28718 result = cp_walk_tree_without_duplicates (&expression,
28719 instantiation_dependent_r, NULL);
28720 return result != NULL_TREE;
28723 /* As above, but also check value-dependence of the expression as a whole. */
28725 bool
28726 instantiation_dependent_expression_p (tree expression)
28728 return (instantiation_dependent_uneval_expression_p (expression)
28729 || (processing_template_decl
28730 && potential_constant_expression (expression)
28731 && value_dependent_expression_p (expression)));
28734 /* Like type_dependent_expression_p, but it also works while not processing
28735 a template definition, i.e. during substitution or mangling. */
28737 bool
28738 type_dependent_expression_p_push (tree expr)
28740 bool b;
28741 ++processing_template_decl;
28742 b = type_dependent_expression_p (expr);
28743 --processing_template_decl;
28744 return b;
28747 /* Returns TRUE if ARGS contains a type-dependent expression. */
28749 bool
28750 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28752 if (!processing_template_decl || !args)
28753 return false;
28755 for (tree arg : *args)
28756 if (type_dependent_expression_p (arg))
28757 return true;
28759 return false;
28762 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28763 expressions) contains any type-dependent expressions. */
28765 bool
28766 any_type_dependent_elements_p (const_tree list)
28768 for (; list; list = TREE_CHAIN (list))
28769 if (type_dependent_expression_p (TREE_VALUE (list)))
28770 return true;
28772 return false;
28775 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28776 expressions) contains any value-dependent expressions. */
28778 bool
28779 any_value_dependent_elements_p (const_tree list)
28781 for (; list; list = TREE_CHAIN (list))
28782 if (value_dependent_expression_p (TREE_VALUE (list)))
28783 return true;
28785 return false;
28788 /* Returns TRUE if the ARG (a template argument) is dependent. */
28790 bool
28791 dependent_template_arg_p (tree arg)
28793 if (!processing_template_decl)
28794 return false;
28796 /* Assume a template argument that was wrongly written by the user
28797 is dependent. This is consistent with what
28798 any_dependent_template_arguments_p [that calls this function]
28799 does. */
28800 if (!arg || arg == error_mark_node)
28801 return true;
28803 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28804 arg = argument_pack_select_arg (arg);
28806 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28807 return true;
28808 if (TREE_CODE (arg) == TEMPLATE_DECL)
28810 if (DECL_TEMPLATE_PARM_P (arg))
28811 return true;
28812 /* A member template of a dependent class is not necessarily
28813 type-dependent, but it is a dependent template argument because it
28814 will be a member of an unknown specialization to that template. */
28815 tree scope = CP_DECL_CONTEXT (arg);
28816 return TYPE_P (scope) && dependent_type_p (scope);
28818 else if (ARGUMENT_PACK_P (arg))
28820 tree args = ARGUMENT_PACK_ARGS (arg);
28821 for (tree arg : tree_vec_range (args))
28822 if (dependent_template_arg_p (arg))
28823 return true;
28824 return false;
28826 else if (TYPE_P (arg))
28827 return dependent_type_p (arg);
28828 else
28829 return value_dependent_expression_p (arg);
28832 /* Identify any expressions that use function parms. */
28834 static tree
28835 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28837 tree t = *tp;
28838 if (TREE_CODE (t) == PARM_DECL)
28840 *walk_subtrees = 0;
28841 return t;
28843 return NULL_TREE;
28846 /* Returns true if a type specialization formed using the template
28847 arguments ARGS needs to use structural equality. */
28849 bool
28850 any_template_arguments_need_structural_equality_p (tree args)
28852 int i;
28853 int j;
28855 if (!args)
28856 return false;
28857 if (args == error_mark_node)
28858 return true;
28860 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28862 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28863 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28865 tree arg = TREE_VEC_ELT (level, j);
28866 tree packed_args = NULL_TREE;
28867 int k, len = 1;
28869 if (ARGUMENT_PACK_P (arg))
28871 /* Look inside the argument pack. */
28872 packed_args = ARGUMENT_PACK_ARGS (arg);
28873 len = TREE_VEC_LENGTH (packed_args);
28876 for (k = 0; k < len; ++k)
28878 if (packed_args)
28879 arg = TREE_VEC_ELT (packed_args, k);
28881 if (error_operand_p (arg))
28882 return true;
28883 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28884 continue;
28885 else if (arg == any_targ_node)
28886 /* An any_targ_node argument (added by add_defaults_to_ttp)
28887 makes the corresponding specialization not canonicalizable,
28888 since template_args_equal always return true for it. We
28889 may see this when called from bind_template_template_parm. */
28890 return true;
28891 /* Checking current_function_decl because this structural
28892 comparison is only necessary for redeclaration. */
28893 else if (!current_function_decl
28894 && dependent_template_arg_p (arg)
28895 && (cp_walk_tree_without_duplicates
28896 (&arg, find_parm_usage_r, NULL)))
28897 /* The identity of a class template specialization that uses
28898 a function parameter depends on the identity of the function.
28899 And if this specialization appeared in the trailing return
28900 type thereof, we don't know the identity of the function
28901 (e.g. if it's a redeclaration or a new function) until we
28902 form its signature and go through duplicate_decls. Thus
28903 it's unsafe to decide on a canonical type now (which depends
28904 on the DECL_CONTEXT of the function parameter, which can get
28905 mutated after the fact by duplicate_decls), so just require
28906 structural equality in this case (PR52830). */
28907 return true;
28908 else if (TYPE_P (arg)
28909 && TYPE_STRUCTURAL_EQUALITY_P (arg)
28910 && dependent_alias_template_spec_p (arg, nt_transparent))
28911 /* Require structural equality for specializations written
28912 in terms of a dependent alias template specialization. */
28913 return true;
28914 else if (CLASS_TYPE_P (arg)
28915 && TYPE_TEMPLATE_INFO (arg)
28916 && TYPE_STRUCTURAL_EQUALITY_P (arg))
28917 /* Require structural equality for specializations written
28918 in terms of a class template specialization that itself
28919 needs structural equality. */
28920 return true;
28925 return false;
28928 /* Returns true if ARGS (a collection of template arguments) contains
28929 any dependent arguments. */
28931 bool
28932 any_dependent_template_arguments_p (const_tree args)
28934 if (args == error_mark_node)
28935 return true;
28936 if (!processing_template_decl || !args)
28937 return false;
28939 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28941 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28942 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28943 if (dependent_template_arg_p (arg))
28944 return true;
28947 return false;
28950 /* Returns true if ARGS contains any errors. */
28952 bool
28953 any_erroneous_template_args_p (const_tree args)
28955 int i;
28956 int j;
28958 if (args == error_mark_node)
28959 return true;
28961 if (args && TREE_CODE (args) != TREE_VEC)
28963 if (tree ti = get_template_info (args))
28964 args = TI_ARGS (ti);
28965 else
28966 args = NULL_TREE;
28969 if (!args)
28970 return false;
28972 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28974 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28975 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28976 if (error_operand_p (TREE_VEC_ELT (level, j)))
28977 return true;
28980 return false;
28983 /* Returns TRUE if the template TMPL is type-dependent. */
28985 bool
28986 dependent_template_p (tree tmpl)
28988 if (TREE_CODE (tmpl) == OVERLOAD)
28990 for (lkp_iterator iter (tmpl); iter; ++iter)
28991 if (dependent_template_p (*iter))
28992 return true;
28993 return false;
28996 /* Template template parameters are dependent. */
28997 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28998 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28999 return true;
29000 /* So are names that have not been looked up. */
29001 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
29002 return true;
29003 return false;
29006 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
29008 bool
29009 dependent_template_id_p (tree tmpl, tree args)
29011 return (dependent_template_p (tmpl)
29012 || any_dependent_template_arguments_p (args));
29015 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
29016 are dependent. */
29018 bool
29019 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
29021 int i;
29023 if (!processing_template_decl)
29024 return false;
29026 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
29028 tree decl = TREE_VEC_ELT (declv, i);
29029 tree init = TREE_VEC_ELT (initv, i);
29030 tree cond = TREE_VEC_ELT (condv, i);
29031 tree incr = TREE_VEC_ELT (incrv, i);
29033 if (type_dependent_expression_p (decl)
29034 || TREE_CODE (decl) == SCOPE_REF)
29035 return true;
29037 if (init && type_dependent_expression_p (init))
29038 return true;
29040 if (cond == global_namespace)
29041 return true;
29043 if (type_dependent_expression_p (cond))
29044 return true;
29046 if (COMPARISON_CLASS_P (cond)
29047 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
29048 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
29049 return true;
29051 if (TREE_CODE (incr) == MODOP_EXPR)
29053 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
29054 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
29055 return true;
29057 else if (type_dependent_expression_p (incr))
29058 return true;
29059 else if (TREE_CODE (incr) == MODIFY_EXPR)
29061 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
29062 return true;
29063 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
29065 tree t = TREE_OPERAND (incr, 1);
29066 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
29067 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
29068 return true;
29070 /* If this loop has a class iterator with != comparison
29071 with increment other than i++/++i/i--/--i, make sure the
29072 increment is constant. */
29073 if (CLASS_TYPE_P (TREE_TYPE (decl))
29074 && TREE_CODE (cond) == NE_EXPR)
29076 if (TREE_OPERAND (t, 0) == decl)
29077 t = TREE_OPERAND (t, 1);
29078 else
29079 t = TREE_OPERAND (t, 0);
29080 if (TREE_CODE (t) != INTEGER_CST)
29081 return true;
29087 return false;
29090 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
29091 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
29092 no such TYPE can be found. Note that this function peers inside
29093 uninstantiated templates and therefore should be used only in
29094 extremely limited situations. ONLY_CURRENT_P restricts this
29095 peering to the currently open classes hierarchy (which is required
29096 when comparing types). */
29098 tree
29099 resolve_typename_type (tree type, bool only_current_p)
29101 tree scope;
29102 tree name;
29103 tree decl;
29104 int quals;
29105 tree pushed_scope;
29106 tree result;
29108 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
29110 scope = TYPE_CONTEXT (type);
29111 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
29112 gcc_checking_assert (uses_template_parms (scope));
29114 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
29115 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29116 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29117 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29118 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29119 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29120 the TYPENAME_TYPE instead, we avoid messing up with a possible
29121 typedef variant case. */
29122 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29124 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29125 it first before we can figure out what NAME refers to. */
29126 if (TREE_CODE (scope) == TYPENAME_TYPE)
29128 if (TYPENAME_IS_RESOLVING_P (scope))
29129 /* Given a class template A with a dependent base with nested type C,
29130 typedef typename A::C::C C will land us here, as trying to resolve
29131 the initial A::C leads to the local C typedef, which leads back to
29132 A::C::C. So we break the recursion now. */
29133 return type;
29134 else
29135 scope = resolve_typename_type (scope, only_current_p);
29137 /* If we don't know what SCOPE refers to, then we cannot resolve the
29138 TYPENAME_TYPE. */
29139 if (!CLASS_TYPE_P (scope))
29140 return type;
29141 /* If this is a typedef, we don't want to look inside (c++/11987). */
29142 if (typedef_variant_p (type))
29143 return type;
29144 /* If SCOPE isn't the template itself, it will not have a valid
29145 TYPE_FIELDS list. */
29146 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29147 /* scope is either the template itself or a compatible instantiation
29148 like X<T>, so look up the name in the original template. */
29149 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29150 /* If scope has no fields, it can't be a current instantiation. Check this
29151 before currently_open_class to avoid infinite recursion (71515). */
29152 if (!TYPE_FIELDS (scope))
29153 return type;
29154 /* If the SCOPE is not the current instantiation, there's no reason
29155 to look inside it. */
29156 if (only_current_p && !currently_open_class (scope))
29157 return type;
29158 /* Enter the SCOPE so that name lookup will be resolved as if we
29159 were in the class definition. In particular, SCOPE will no
29160 longer be considered a dependent type. */
29161 pushed_scope = push_scope (scope);
29162 /* Look up the declaration. */
29163 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29164 tf_warning_or_error);
29166 result = NULL_TREE;
29168 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29169 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29170 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29171 if (!decl)
29172 /*nop*/;
29173 else if (identifier_p (fullname)
29174 && TREE_CODE (decl) == TYPE_DECL)
29176 result = TREE_TYPE (decl);
29177 if (result == error_mark_node)
29178 result = NULL_TREE;
29180 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29181 && DECL_CLASS_TEMPLATE_P (decl))
29183 /* Obtain the template and the arguments. */
29184 tree tmpl = TREE_OPERAND (fullname, 0);
29185 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29187 /* We get here with a plain identifier because a previous tentative
29188 parse of the nested-name-specifier as part of a ptr-operator saw
29189 ::template X<A>. The use of ::template is necessary in a
29190 ptr-operator, but wrong in a declarator-id.
29192 [temp.names]: In a qualified-id of a declarator-id, the keyword
29193 template shall not appear at the top level. */
29194 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29195 "keyword %<template%> not allowed in declarator-id");
29196 tmpl = decl;
29198 tree args = TREE_OPERAND (fullname, 1);
29199 /* Instantiate the template. */
29200 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29201 /*entering_scope=*/true,
29202 tf_error | tf_user);
29203 if (result == error_mark_node)
29204 result = NULL_TREE;
29207 /* Leave the SCOPE. */
29208 if (pushed_scope)
29209 pop_scope (pushed_scope);
29211 /* If we failed to resolve it, return the original typename. */
29212 if (!result)
29213 return type;
29215 /* If lookup found a typename type, resolve that too. */
29216 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29218 /* Ill-formed programs can cause infinite recursion here, so we
29219 must catch that. */
29220 TYPENAME_IS_RESOLVING_P (result) = 1;
29221 result = resolve_typename_type (result, only_current_p);
29222 TYPENAME_IS_RESOLVING_P (result) = 0;
29225 /* Qualify the resulting type. */
29226 quals = cp_type_quals (type);
29227 if (quals)
29228 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29230 return result;
29233 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29234 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29235 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29237 static tree
29238 make_auto_1 (tree name, bool set_canonical, int level = -1)
29240 if (level == -1)
29241 level = current_template_depth + 1;
29242 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29243 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29244 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29245 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29246 (0, level, level, TYPE_NAME (au), NULL_TREE);
29247 if (set_canonical)
29248 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29249 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29250 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29251 if (name == decltype_auto_identifier)
29252 AUTO_IS_DECLTYPE (au) = true;
29254 return au;
29257 tree
29258 make_decltype_auto (void)
29260 return make_auto_1 (decltype_auto_identifier, true);
29263 tree
29264 make_auto (void)
29266 return make_auto_1 (auto_identifier, true);
29269 /* Return a C++17 deduction placeholder for class template TMPL.
29270 There are represented as an 'auto' with the special level 0 and
29271 CLASS_PLACEHOLDER_TEMPLATE set. */
29273 tree
29274 make_template_placeholder (tree tmpl)
29276 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29277 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29278 /* Our canonical type depends on the placeholder. */
29279 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29280 return t;
29283 /* True iff T is a C++17 class template deduction placeholder. */
29285 bool
29286 template_placeholder_p (tree t)
29288 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29291 /* Make a "constrained auto" type-specifier. This is an auto or
29292 decltype(auto) type with constraints that must be associated after
29293 deduction. The constraint is formed from the given concept CON
29294 and its optional sequence of template arguments ARGS.
29296 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29298 static tree
29299 make_constrained_placeholder_type (tree type, tree con, tree args)
29301 /* Build the constraint. */
29302 tree tmpl = DECL_TI_TEMPLATE (con);
29303 tree expr = tmpl;
29304 if (TREE_CODE (con) == FUNCTION_DECL)
29305 expr = ovl_make (tmpl);
29306 ++processing_template_decl;
29307 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29308 --processing_template_decl;
29310 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29311 = build_tree_list (current_template_parms, expr);
29313 /* Our canonical type depends on the constraint. */
29314 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29316 /* Attach the constraint to the type declaration. */
29317 return TYPE_NAME (type);
29320 /* Make a "constrained auto" type-specifier. */
29322 tree
29323 make_constrained_auto (tree con, tree args)
29325 tree type = make_auto_1 (auto_identifier, false);
29326 return make_constrained_placeholder_type (type, con, args);
29329 /* Make a "constrained decltype(auto)" type-specifier. */
29331 tree
29332 make_constrained_decltype_auto (tree con, tree args)
29334 tree type = make_auto_1 (decltype_auto_identifier, false);
29335 return make_constrained_placeholder_type (type, con, args);
29338 /* Returns true if the placeholder type constraint T has any dependent
29339 (explicit) template arguments. */
29341 static bool
29342 placeholder_type_constraint_dependent_p (tree t)
29344 tree id = unpack_concept_check (t);
29345 tree args = TREE_OPERAND (id, 1);
29346 tree first = TREE_VEC_ELT (args, 0);
29347 if (ARGUMENT_PACK_P (first))
29349 args = expand_template_argument_pack (args);
29350 first = TREE_VEC_ELT (args, 0);
29352 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29353 || is_auto (first));
29354 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29355 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29356 return true;
29357 return false;
29360 /* Build and return a concept definition. Like other templates, the
29361 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29362 the TEMPLATE_DECL. */
29364 tree
29365 finish_concept_definition (cp_expr id, tree init, tree attrs)
29367 gcc_assert (identifier_p (id));
29368 gcc_assert (processing_template_decl);
29370 location_t loc = id.get_location();
29372 /* A concept-definition shall not have associated constraints. */
29373 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29375 error_at (loc, "a concept cannot be constrained");
29376 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29379 /* A concept-definition shall appear in namespace scope. Templates
29380 aren't allowed in block scope, so we only need to check for class
29381 scope. */
29382 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29384 error_at (loc, "concept %qE not in namespace scope", *id);
29385 return error_mark_node;
29388 if (current_template_depth > 1)
29390 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29391 return error_mark_node;
29394 /* Initially build the concept declaration; its type is bool. */
29395 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29396 DECL_CONTEXT (decl) = current_scope ();
29397 DECL_INITIAL (decl) = init;
29399 if (attrs)
29400 cplus_decl_attributes (&decl, attrs, 0);
29402 set_originating_module (decl, false);
29404 /* Push the enclosing template. */
29405 return push_template_decl (decl);
29408 /* Given type ARG, return std::initializer_list<ARG>. */
29410 static tree
29411 listify (tree arg)
29413 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29415 if (std_init_list == error_mark_node
29416 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29418 gcc_rich_location richloc (input_location);
29419 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29420 error_at (&richloc,
29421 "deducing from brace-enclosed initializer list"
29422 " requires %<#include <initializer_list>%>");
29424 return error_mark_node;
29426 tree argvec = make_tree_vec (1);
29427 TREE_VEC_ELT (argvec, 0) = arg;
29429 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29430 NULL_TREE, 0, tf_warning_or_error);
29433 /* Replace auto in TYPE with std::initializer_list<auto>. */
29435 static tree
29436 listify_autos (tree type, tree auto_node)
29438 tree init_auto = listify (strip_top_quals (auto_node));
29439 tree argvec = make_tree_vec (1);
29440 TREE_VEC_ELT (argvec, 0) = init_auto;
29441 if (processing_template_decl)
29442 argvec = add_to_template_args (current_template_args (), argvec);
29443 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29446 /* Hash traits for hashing possibly constrained 'auto'
29447 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29449 struct auto_hash : default_hash_traits<tree>
29451 static inline hashval_t hash (tree);
29452 static inline bool equal (tree, tree);
29455 /* Hash the 'auto' T. */
29457 inline hashval_t
29458 auto_hash::hash (tree t)
29460 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29461 /* Matching constrained-type-specifiers denote the same template
29462 parameter, so hash the constraint. */
29463 return hash_placeholder_constraint (c);
29464 else
29465 /* But unconstrained autos are all separate, so just hash the pointer. */
29466 return iterative_hash_object (t, 0);
29469 /* Compare two 'auto's. */
29471 inline bool
29472 auto_hash::equal (tree t1, tree t2)
29474 if (t1 == t2)
29475 return true;
29477 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29478 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29480 /* Two unconstrained autos are distinct. */
29481 if (!c1 || !c2)
29482 return false;
29484 return equivalent_placeholder_constraints (c1, c2);
29487 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29488 constrained) auto, add it to the vector. */
29490 static int
29491 extract_autos_r (tree t, void *data)
29493 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29494 if (is_auto (t) && !template_placeholder_p (t))
29496 /* All the autos were built with index 0; fix that up now. */
29497 tree *p = hash.find_slot (t, INSERT);
29498 int idx;
29499 if (*p)
29500 /* If this is a repeated constrained-type-specifier, use the index we
29501 chose before. */
29502 idx = TEMPLATE_TYPE_IDX (*p);
29503 else
29505 /* Otherwise this is new, so use the current count. */
29506 *p = t;
29507 idx = hash.elements () - 1;
29509 if (idx != TEMPLATE_TYPE_IDX (t))
29511 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29512 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29513 TEMPLATE_TYPE_IDX (t) = idx;
29514 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29518 /* Always keep walking. */
29519 return 0;
29522 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29523 says they can appear anywhere in the type. */
29525 static tree
29526 extract_autos (tree type)
29528 hash_set<tree> visited;
29529 hash_table<auto_hash> hash (2);
29531 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29533 tree tree_vec = make_tree_vec (hash.elements());
29534 for (tree elt : hash)
29536 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29537 TREE_VEC_ELT (tree_vec, i)
29538 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29541 return tree_vec;
29544 /* The stem for deduction guide names. */
29545 const char *const dguide_base = "__dguide_";
29547 /* Return the name for a deduction guide for class template TMPL. */
29549 tree
29550 dguide_name (tree tmpl)
29552 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29553 tree tname = TYPE_IDENTIFIER (type);
29554 char *buf = (char *) alloca (1 + strlen (dguide_base)
29555 + IDENTIFIER_LENGTH (tname));
29556 memcpy (buf, dguide_base, strlen (dguide_base));
29557 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29558 IDENTIFIER_LENGTH (tname) + 1);
29559 tree dname = get_identifier (buf);
29560 TREE_TYPE (dname) = type;
29561 return dname;
29564 /* True if NAME is the name of a deduction guide. */
29566 bool
29567 dguide_name_p (tree name)
29569 return (TREE_CODE (name) == IDENTIFIER_NODE
29570 && TREE_TYPE (name)
29571 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29574 /* True if FN is a deduction guide. */
29576 bool
29577 deduction_guide_p (const_tree fn)
29579 if (DECL_P (fn))
29580 if (tree name = DECL_NAME (fn))
29581 return dguide_name_p (name);
29582 return false;
29585 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29587 bool
29588 copy_guide_p (const_tree fn)
29590 gcc_assert (deduction_guide_p (fn));
29591 if (!DECL_ARTIFICIAL (fn))
29592 return false;
29593 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29594 return (TREE_CHAIN (parms) == void_list_node
29595 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29598 /* True if FN is a guide generated from a constructor template. */
29600 bool
29601 template_guide_p (const_tree fn)
29603 gcc_assert (deduction_guide_p (fn));
29604 if (!DECL_ARTIFICIAL (fn))
29605 return false;
29606 tree tmpl = DECL_TI_TEMPLATE (fn);
29607 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29608 return PRIMARY_TEMPLATE_P (org);
29609 return false;
29612 /* True if FN is an aggregate initialization guide or the copy deduction
29613 guide. */
29615 bool
29616 builtin_guide_p (const_tree fn)
29618 if (!deduction_guide_p (fn))
29619 return false;
29620 if (!DECL_ARTIFICIAL (fn))
29621 /* Explicitly declared. */
29622 return false;
29623 if (DECL_ABSTRACT_ORIGIN (fn))
29624 /* Derived from a constructor. */
29625 return false;
29626 return true;
29629 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29630 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29631 template parameter types. Note that the handling of template template
29632 parameters relies on current_template_parms being set appropriately for the
29633 new template. */
29635 static tree
29636 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29637 tree tsubst_args, tsubst_flags_t complain)
29639 if (olddecl == error_mark_node)
29640 return error_mark_node;
29642 tree oldidx = get_template_parm_index (olddecl);
29644 tree newtype;
29645 if (TREE_CODE (olddecl) == TYPE_DECL
29646 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29648 tree oldtype = TREE_TYPE (olddecl);
29649 newtype = cxx_make_type (TREE_CODE (oldtype));
29650 TYPE_MAIN_VARIANT (newtype) = newtype;
29652 else
29654 newtype = TREE_TYPE (olddecl);
29655 if (type_uses_auto (newtype))
29657 // Substitute once to fix references to other template parameters.
29658 newtype = tsubst (newtype, tsubst_args,
29659 complain|tf_partial, NULL_TREE);
29660 // Now substitute again to reduce the level of the auto.
29661 newtype = tsubst (newtype, current_template_args (),
29662 complain, NULL_TREE);
29664 else
29665 newtype = tsubst (newtype, tsubst_args,
29666 complain, NULL_TREE);
29669 tree newdecl
29670 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29671 DECL_NAME (olddecl), newtype);
29672 SET_DECL_TEMPLATE_PARM_P (newdecl);
29674 tree newidx;
29675 if (TREE_CODE (olddecl) == TYPE_DECL
29676 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29678 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29679 = build_template_parm_index (index, level, level,
29680 newdecl, newtype);
29681 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29682 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29683 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29685 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29687 tree newresult
29688 = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29689 DECL_NAME (olddecl), newtype);
29690 DECL_ARTIFICIAL (newresult) = true;
29691 DECL_TEMPLATE_RESULT (newdecl) = newresult;
29692 // First create a copy (ttargs) of tsubst_args with an
29693 // additional level for the template template parameter's own
29694 // template parameters (ttparms).
29695 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29696 (DECL_TEMPLATE_PARMS (olddecl)));
29697 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29698 tree ttargs = make_tree_vec (depth + 1);
29699 for (int i = 0; i < depth; ++i)
29700 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29701 TREE_VEC_ELT (ttargs, depth)
29702 = template_parms_level_to_args (ttparms);
29703 // Substitute ttargs into ttparms to fix references to
29704 // other template parameters.
29705 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29706 complain|tf_partial);
29707 // Now substitute again with args based on tparms, to reduce
29708 // the level of the ttparms.
29709 ttargs = current_template_args ();
29710 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29711 complain);
29712 // Finally, tack the adjusted parms onto tparms.
29713 ttparms = tree_cons (size_int (level + 1), ttparms,
29714 copy_node (current_template_parms));
29715 // As with all template template parms, the parameter list captured
29716 // by this template template parm that corresponds to its own level
29717 // should be empty. This avoids infinite recursion when structurally
29718 // comparing two such rewritten template template parms (PR102479).
29719 gcc_assert (!TREE_VEC_LENGTH
29720 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29721 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29722 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29723 // All done.
29724 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29725 DECL_TEMPLATE_INFO (newresult)
29726 = build_template_info (newdecl, template_parms_to_args (ttparms));
29729 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29730 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29731 else
29732 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29734 else
29736 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29737 tree newconst
29738 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29739 TREE_CODE (oldconst),
29740 DECL_NAME (oldconst), newtype);
29741 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29742 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29743 SET_DECL_TEMPLATE_PARM_P (newconst);
29744 newidx = build_template_parm_index (index, level, level,
29745 newconst, newtype);
29746 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29747 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29748 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29751 return newdecl;
29754 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29755 template parameter. */
29757 static tree
29758 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29759 tree targs, unsigned targs_index, tsubst_flags_t complain)
29761 tree olddecl = TREE_VALUE (oldelt);
29762 tree newdecl = rewrite_template_parm (olddecl, index, level,
29763 targs, complain);
29764 if (newdecl == error_mark_node)
29765 return error_mark_node;
29766 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29767 targs, complain, NULL_TREE);
29768 tree list = build_tree_list (newdef, newdecl);
29769 TEMPLATE_PARM_CONSTRAINTS (list)
29770 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29771 targs, complain, NULL_TREE);
29772 int depth = TMPL_ARGS_DEPTH (targs);
29773 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29774 return list;
29777 /* Returns a C++17 class deduction guide template based on the constructor
29778 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29779 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29780 aggregate initialization guide. OUTER_ARGS are the template arguments
29781 for the enclosing scope of the class. */
29783 static tree
29784 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29786 tree tparms, targs, fparms, fargs, ci;
29787 bool memtmpl = false;
29788 bool explicit_p;
29789 location_t loc;
29790 tree fn_tmpl = NULL_TREE;
29792 if (outer_args)
29794 ++processing_template_decl;
29795 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29796 --processing_template_decl;
29799 if (!DECL_DECLARES_FUNCTION_P (ctor))
29801 if (TYPE_P (ctor))
29803 bool copy_p = TYPE_REF_P (ctor);
29804 if (copy_p)
29805 fparms = tree_cons (NULL_TREE, type, void_list_node);
29806 else
29807 fparms = void_list_node;
29809 else if (TREE_CODE (ctor) == TREE_LIST)
29810 fparms = ctor;
29811 else
29812 gcc_unreachable ();
29814 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29815 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29816 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29817 ci = NULL_TREE;
29818 fargs = NULL_TREE;
29819 loc = DECL_SOURCE_LOCATION (ctmpl);
29820 explicit_p = false;
29822 else
29824 ++processing_template_decl;
29825 bool ok = true;
29827 complain |= tf_dguide;
29829 fn_tmpl
29830 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29831 : DECL_TI_TEMPLATE (ctor));
29832 if (outer_args)
29833 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29834 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29836 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29837 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29838 fully specialized args for the enclosing class. Strip those off, as
29839 the deduction guide won't have those template parameters. */
29840 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29841 TMPL_PARMS_DEPTH (tparms));
29842 /* Discard the 'this' parameter. */
29843 fparms = FUNCTION_ARG_CHAIN (ctor);
29844 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29845 ci = get_constraints (ctor);
29846 loc = DECL_SOURCE_LOCATION (ctor);
29847 explicit_p = DECL_NONCONVERTING_P (ctor);
29849 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29851 memtmpl = true;
29853 /* For a member template constructor, we need to flatten the two
29854 template parameter lists into one, and then adjust the function
29855 signature accordingly. This gets...complicated. */
29856 tree save_parms = current_template_parms;
29858 /* For a member template we should have two levels of parms/args, one
29859 for the class and one for the constructor. We stripped
29860 specialized args for further enclosing classes above. */
29861 const int depth = 2;
29862 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29864 /* Template args for translating references to the two-level template
29865 parameters into references to the one-level template parameters we
29866 are creating. */
29867 tree tsubst_args = copy_node (targs);
29868 TMPL_ARGS_LEVEL (tsubst_args, depth)
29869 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29871 /* Template parms for the constructor template. */
29872 tree ftparms = TREE_VALUE (tparms);
29873 unsigned flen = TREE_VEC_LENGTH (ftparms);
29874 /* Template parms for the class template. */
29875 tparms = TREE_CHAIN (tparms);
29876 tree ctparms = TREE_VALUE (tparms);
29877 unsigned clen = TREE_VEC_LENGTH (ctparms);
29878 /* Template parms for the deduction guide start as a copy of the
29879 template parms for the class. We set current_template_parms for
29880 lookup_template_class_1. */
29881 current_template_parms = tparms = copy_node (tparms);
29882 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29883 for (unsigned i = 0; i < clen; ++i)
29884 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29886 /* Now we need to rewrite the constructor parms to append them to the
29887 class parms. */
29888 for (unsigned i = 0; i < flen; ++i)
29890 unsigned index = i + clen;
29891 unsigned level = 1;
29892 tree oldelt = TREE_VEC_ELT (ftparms, i);
29893 tree newelt
29894 = rewrite_tparm_list (oldelt, index, level,
29895 tsubst_args, i, complain);
29896 if (newelt == error_mark_node)
29897 ok = false;
29898 TREE_VEC_ELT (new_vec, index) = newelt;
29901 /* Now we have a final set of template parms to substitute into the
29902 function signature. */
29903 targs = template_parms_to_args (tparms);
29904 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29905 complain, ctor);
29906 if (fparms == error_mark_node)
29907 ok = false;
29908 if (ci)
29910 if (outer_args)
29911 /* FIXME: We'd like to avoid substituting outer template
29912 arguments into the constraint ahead of time, but the
29913 construction of tsubst_args assumes that outer arguments
29914 are already substituted in. */
29915 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29916 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29919 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29920 cp_unevaluated_operand. */
29921 cp_evaluated ev;
29922 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29923 current_template_parms = save_parms;
29925 else
29927 /* Substitute in the same arguments to rewrite class members into
29928 references to members of an unknown specialization. */
29929 cp_evaluated ev;
29930 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29931 fargs = tsubst (fargs, targs, complain, ctor);
29932 if (ci)
29934 if (outer_args)
29935 /* FIXME: As above. */
29936 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29937 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29941 --processing_template_decl;
29942 if (!ok)
29943 return error_mark_node;
29946 if (!memtmpl)
29948 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29949 tparms = copy_node (tparms);
29950 INNERMOST_TEMPLATE_PARMS (tparms)
29951 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29954 tree fntype = build_function_type (type, fparms);
29955 tree ded_fn = build_lang_decl_loc (loc,
29956 FUNCTION_DECL,
29957 dguide_name (type), fntype);
29958 DECL_ARGUMENTS (ded_fn) = fargs;
29959 DECL_ARTIFICIAL (ded_fn) = true;
29960 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29961 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29962 DECL_ARTIFICIAL (ded_tmpl) = true;
29963 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29964 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29965 if (DECL_P (ctor))
29966 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29967 if (ci)
29968 set_constraints (ded_tmpl, ci);
29970 return ded_tmpl;
29973 /* Add to LIST the member types for the reshaped initializer CTOR. */
29975 static tree
29976 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29978 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29979 tree idx, val; unsigned i;
29980 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29982 tree ftype = elt ? elt : TREE_TYPE (idx);
29983 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29984 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29986 tree subelt = NULL_TREE;
29987 if (TREE_CODE (ftype) == ARRAY_TYPE)
29988 subelt = TREE_TYPE (ftype);
29989 list = collect_ctor_idx_types (val, list, subelt);
29990 continue;
29992 tree arg = NULL_TREE;
29993 if (i == v->length() - 1
29994 && PACK_EXPANSION_P (ftype))
29995 /* Give the trailing pack expansion parameter a default argument to
29996 match aggregate initialization behavior, even if we deduce the
29997 length of the pack separately to more than we have initializers. */
29998 arg = build_constructor (init_list_type_node, NULL);
29999 /* if ei is of array type and xi is a braced-init-list or string literal,
30000 Ti is an rvalue reference to the declared type of ei */
30001 STRIP_ANY_LOCATION_WRAPPER (val);
30002 if (TREE_CODE (ftype) == ARRAY_TYPE
30003 && (BRACE_ENCLOSED_INITIALIZER_P (val)
30004 || TREE_CODE (val) == STRING_CST))
30006 if (TREE_CODE (val) == STRING_CST)
30007 ftype = cp_build_qualified_type
30008 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30009 ftype = (cp_build_reference_type
30010 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30012 list = tree_cons (arg, ftype, list);
30015 return list;
30018 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30020 static bool
30021 is_spec_or_derived (tree etype, tree tmpl)
30023 if (!etype || !CLASS_TYPE_P (etype))
30024 return false;
30026 etype = cv_unqualified (etype);
30027 tree type = TREE_TYPE (tmpl);
30028 tree tparms = (INNERMOST_TEMPLATE_PARMS
30029 (DECL_TEMPLATE_PARMS (tmpl)));
30030 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30031 int err = unify (tparms, targs, type, etype,
30032 UNIFY_ALLOW_DERIVED, /*explain*/false);
30033 ggc_free (targs);
30034 return !err;
30037 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30038 INIT. */
30040 static tree
30041 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30043 if (cxx_dialect < cxx20)
30044 return NULL_TREE;
30046 if (init == NULL_TREE)
30047 return NULL_TREE;
30049 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30051 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30052 tree tinfo = get_template_info (under);
30053 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30054 return alias_ctad_tweaks (tmpl, guide);
30055 return NULL_TREE;
30058 /* We might be creating a guide for a class member template, e.g.,
30060 template<typename U> struct A {
30061 template<typename T> struct B { T t; };
30064 At this point, A will have been instantiated. Below, we need to
30065 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30066 const bool member_template_p
30067 = (DECL_TEMPLATE_INFO (tmpl)
30068 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30069 tree type = TREE_TYPE (tmpl);
30070 tree template_type = (member_template_p
30071 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30072 : type);
30073 if (!CP_AGGREGATE_TYPE_P (template_type))
30074 return NULL_TREE;
30076 /* No aggregate candidate for copy-initialization. */
30077 if (args->length() == 1)
30079 tree val = (*args)[0];
30080 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30081 return NULL_TREE;
30084 /* If we encounter a problem, we just won't add the candidate. */
30085 tsubst_flags_t complain = tf_none;
30087 tree parms = NULL_TREE;
30088 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30090 init = reshape_init (template_type, init, complain);
30091 if (init == error_mark_node)
30092 return NULL_TREE;
30093 parms = collect_ctor_idx_types (init, parms);
30094 /* If we're creating a deduction guide for a member class template,
30095 we've used the original template pattern type for the reshape_init
30096 above; this is done because we want PARMS to be a template parameter
30097 type, something that can be deduced when used as a function template
30098 parameter. At this point the outer class template has already been
30099 partially instantiated (we deferred the deduction until the enclosing
30100 scope is non-dependent). Therefore we have to partially instantiate
30101 PARMS, so that its template level is properly reduced and we don't get
30102 mismatches when deducing types using the guide with PARMS. */
30103 if (member_template_p)
30105 ++processing_template_decl;
30106 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30107 --processing_template_decl;
30110 else if (TREE_CODE (init) == TREE_LIST)
30112 int len = list_length (init);
30113 for (tree field = TYPE_FIELDS (type);
30114 len;
30115 --len, field = DECL_CHAIN (field))
30117 field = next_aggregate_field (field);
30118 if (!field)
30119 return NULL_TREE;
30120 tree ftype = finish_decltype_type (field, true, complain);
30121 parms = tree_cons (NULL_TREE, ftype, parms);
30124 else
30125 /* Aggregate initialization doesn't apply to an initializer expression. */
30126 return NULL_TREE;
30128 if (parms)
30130 tree last = parms;
30131 parms = nreverse (parms);
30132 TREE_CHAIN (last) = void_list_node;
30133 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30134 return guide;
30137 return NULL_TREE;
30140 /* UGUIDES are the deduction guides for the underlying template of alias
30141 template TMPL; adjust them to be deduction guides for TMPL.
30143 This routine also handles C++23 inherited CTAD, in which case TMPL is a
30144 TREE_LIST representing a synthetic alias template whose TREE_PURPOSE is
30145 the template parameter list of the alias template (equivalently, of the
30146 derived class) and TREE_VALUE the defining-type-id (equivalently, the
30147 base whose guides we're inheriting). UGUIDES are the base's guides. */
30149 static tree
30150 alias_ctad_tweaks (tree tmpl, tree uguides)
30152 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30153 class type (9.2.8.2) where the template-name names an alias template A,
30154 the defining-type-id of A must be of the form
30156 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30158 as specified in 9.2.8.2. The guides of A are the set of functions or
30159 function templates formed as follows. For each function or function
30160 template f in the guides of the template named by the simple-template-id
30161 of the defining-type-id, the template arguments of the return type of f
30162 are deduced from the defining-type-id of A according to the process in
30163 13.10.2.5 with the exception that deduction does not fail if not all
30164 template arguments are deduced. Let g denote the result of substituting
30165 these deductions into f. If substitution succeeds, form a function or
30166 function template f' with the following properties and add it to the set
30167 of guides of A:
30169 * The function type of f' is the function type of g.
30171 * If f is a function template, f' is a function template whose template
30172 parameter list consists of all the template parameters of A (including
30173 their default template arguments) that appear in the above deductions or
30174 (recursively) in their default template arguments, followed by the
30175 template parameters of f that were not deduced (including their default
30176 template arguments), otherwise f' is not a function template.
30178 * The associated constraints (13.5.2) are the conjunction of the
30179 associated constraints of g and a constraint that is satisfied if and only
30180 if the arguments of A are deducible (see below) from the return type.
30182 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30183 be so as well.
30185 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30186 considered to be so as well.
30188 * The explicit-specifier of f' is the explicit-specifier of g (if
30189 any). */
30191 enum { alias, inherited } ctad_kind;
30192 tree atype, fullatparms, utype;
30193 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30195 ctad_kind = alias;
30196 atype = TREE_TYPE (tmpl);
30197 fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30198 utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30200 else
30202 ctad_kind = inherited;
30203 atype = NULL_TREE;
30204 fullatparms = TREE_PURPOSE (tmpl);
30205 utype = TREE_VALUE (tmpl);
30208 tsubst_flags_t complain = tf_warning_or_error;
30209 tree aguides = NULL_TREE;
30210 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30211 unsigned natparms = TREE_VEC_LENGTH (atparms);
30212 for (ovl_iterator iter (uguides); iter; ++iter)
30214 tree f = *iter;
30215 tree in_decl = f;
30216 location_t loc = DECL_SOURCE_LOCATION (f);
30217 tree ret = TREE_TYPE (TREE_TYPE (f));
30218 tree fprime = f;
30219 if (TREE_CODE (f) == TEMPLATE_DECL)
30221 processing_template_decl_sentinel ptds (/*reset*/false);
30222 ++processing_template_decl;
30224 /* Deduce template arguments for f from the type-id of A. */
30225 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30226 unsigned len = TREE_VEC_LENGTH (ftparms);
30227 tree targs = make_tree_vec (len);
30228 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30229 if (err)
30230 /* CWG2664: Discard any deductions, still build the guide. */
30231 for (unsigned i = 0; i < len; ++i)
30232 TREE_VEC_ELT (targs, i) = NULL_TREE;
30234 /* The number of parms for f' is the number of parms of A used in
30235 the deduced arguments plus non-deduced parms of f. */
30236 unsigned ndlen = 0;
30237 unsigned j;
30238 for (unsigned i = 0; i < len; ++i)
30239 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30240 ++ndlen;
30241 find_template_parameter_info ftpi (fullatparms);
30242 ftpi.find_in_recursive (targs);
30243 unsigned nusedatparms = ftpi.num_found ();
30244 unsigned nfparms = nusedatparms + ndlen;
30245 tree gtparms = make_tree_vec (nfparms);
30247 /* Set current_template_parms as in build_deduction_guide. */
30248 auto ctp = make_temp_override (current_template_parms);
30249 current_template_parms = copy_node (fullatparms);
30250 TREE_VALUE (current_template_parms) = gtparms;
30252 j = 0;
30253 unsigned level = 1;
30255 /* First copy over the used parms of A. */
30256 tree atargs = make_tree_vec (natparms);
30257 for (unsigned i = 0; i < natparms; ++i)
30259 tree elt = TREE_VEC_ELT (atparms, i);
30260 if (ftpi.found (elt))
30262 unsigned index = j++;
30263 tree nelt = rewrite_tparm_list (elt, index, level,
30264 atargs, i, complain);
30265 TREE_VEC_ELT (gtparms, index) = nelt;
30268 gcc_checking_assert (j == nusedatparms);
30270 /* Adjust the deduced template args for f to refer to the A parms
30271 with their new indexes. */
30272 if (nusedatparms && nusedatparms != natparms)
30273 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30275 /* Now rewrite the non-deduced parms of f. */
30276 for (unsigned i = 0; ndlen && i < len; ++i)
30277 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30279 --ndlen;
30280 unsigned index = j++;
30281 tree oldlist = TREE_VEC_ELT (ftparms, i);
30282 tree list = rewrite_tparm_list (oldlist, index, level,
30283 targs, i, complain);
30284 TREE_VEC_ELT (gtparms, index) = list;
30286 gtparms = build_tree_list (size_one_node, gtparms);
30288 /* Substitute the deduced arguments plus the rewritten template
30289 parameters into f to get g. This covers the type, copyness,
30290 guideness, and explicit-specifier. */
30291 tree g;
30293 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30294 if cp_unevaluated_operand. */
30295 cp_evaluated ev;
30296 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain,
30297 /*use_spec_table=*/false);
30299 if (g == error_mark_node)
30300 continue;
30301 if (nfparms == 0)
30303 /* The targs are all non-dependent, so g isn't a template. */
30304 fprime = g;
30305 ret = TREE_TYPE (TREE_TYPE (fprime));
30306 goto non_template;
30308 DECL_USE_TEMPLATE (g) = 0;
30309 fprime = build_template_decl (g, gtparms, false);
30310 DECL_TEMPLATE_RESULT (fprime) = g;
30311 TREE_TYPE (fprime) = TREE_TYPE (g);
30312 tree gtargs = template_parms_to_args (gtparms);
30313 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30314 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30316 /* Substitute the associated constraints. */
30317 tree ci = get_constraints (f);
30318 if (ci)
30319 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30320 if (ci == error_mark_node)
30321 continue;
30323 /* Add a constraint that the return type matches the instantiation of
30324 A with the same template arguments. */
30325 ret = TREE_TYPE (TREE_TYPE (fprime));
30326 if (ctad_kind == alias
30327 && (!same_type_p (atype, ret)
30328 /* FIXME this should mean they don't compare as equivalent. */
30329 || dependent_alias_template_spec_p (atype, nt_opaque)))
30331 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30332 ci = append_constraint (ci, same);
30335 if (ci)
30337 remove_constraints (fprime);
30338 set_constraints (fprime, ci);
30341 else
30343 /* For a non-template deduction guide, if the arguments of A aren't
30344 deducible from the return type, don't add the candidate. */
30345 non_template:
30346 if (ctad_kind == alias
30347 && !type_targs_deducible_from (tmpl, ret))
30348 continue;
30351 /* Rewrite the return type of the inherited guide in terms of the
30352 derived class. This is specified as replacing the return type R
30353 with typename CC<R>::type where the partially specialized CC maps a
30354 base class specialization to a specialization of the derived class
30355 having such a base (inducing substitution failure if no such derived
30356 class exists).
30358 As specified this mapping would be done at instantiation time using
30359 non-dependent template arguments, but we do it ahead of time using
30360 the generic arguments. This seems to be good enough since generic
30361 deduction should succeed only if concrete deduction would. */
30362 if (ctad_kind == inherited)
30364 processing_template_decl_sentinel ptds (/*reset*/false);
30365 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30366 ++processing_template_decl;
30368 tree targs = type_targs_deducible_from (tmpl, ret);
30369 if (!targs)
30370 continue;
30372 if (TREE_CODE (f) != TEMPLATE_DECL)
30373 fprime = copy_decl (fprime);
30374 tree fntype = TREE_TYPE (fprime);
30375 ret = lookup_template_class (TPARMS_PRIMARY_TEMPLATE (atparms), targs,
30376 in_decl, NULL_TREE, false, complain);
30377 fntype = build_function_type (ret, TYPE_ARG_TYPES (fntype));
30378 TREE_TYPE (fprime) = fntype;
30379 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30380 TREE_TYPE (DECL_TEMPLATE_RESULT (fprime)) = fntype;
30383 aguides = lookup_add (fprime, aguides);
30386 return aguides;
30389 /* CTOR is a using-decl inheriting the constructors of some base of the class
30390 template TMPL; adjust the base's guides be deduction guides for TMPL. */
30392 static tree
30393 inherited_ctad_tweaks (tree tmpl, tree ctor, tsubst_flags_t complain)
30395 /* [over.match.class.deduct]: In addition, if C is defined and inherits
30396 constructors ([namespace.udecl]) from a direct base class denoted in the
30397 base-specifier-list by a class-or-decltype B, let A be an alias template
30398 whose template parameter list is that of C and whose defining-type-id is
30399 B. If A is a deducible template ([dcl.type.simple]), the set contains the
30400 guides of A with the return type R of each guide replaced with typename
30401 CC::type given a class template
30403 template <typename> class CC;
30405 whose primary template is not defined and with a single partial
30406 specialization whose template parameter list is that of A and whose
30407 template argument list is a specialization of A with the template argument
30408 list of A ([temp.dep.type]) having a member typedef type designating a
30409 template specialization with the template argument list of A but with C as
30410 the template. */
30412 /* FIXME: Also recognize inherited constructors of the form 'using C::B::B',
30413 which seem to be represented with TYPENAME_TYPE C::B as USING_DECL_SCOPE?
30414 And recognize constructors inherited from a non-dependent base class, which
30415 seem to be missing from the overload set entirely? */
30416 tree scope = USING_DECL_SCOPE (ctor);
30417 if (!CLASS_TYPE_P (scope)
30418 || !CLASSTYPE_TEMPLATE_INFO (scope)
30419 || !PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope)))
30420 return NULL_TREE;
30422 tree t = build_tree_list (DECL_TEMPLATE_PARMS (tmpl), scope);
30423 bool any_dguides_p;
30424 tree uguides = deduction_guides_for (CLASSTYPE_TI_TEMPLATE (scope),
30425 any_dguides_p, complain);
30426 return alias_ctad_tweaks (t, uguides);
30429 /* If template arguments for TMPL can be deduced from TYPE, return
30430 the deduced arguments, otherwise return NULL_TREE.
30431 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30432 [over.match.class.deduct].
30434 This check is specified in terms of partial specialization, so the behavior
30435 should be parallel to that of get_partial_spec_bindings. */
30437 tree
30438 type_targs_deducible_from (tree tmpl, tree type)
30440 tree tparms, ttype;
30441 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30443 /* If tmpl is a class template, this is trivial: it's deducible if
30444 TYPE is a specialization of TMPL. */
30445 if (DECL_CLASS_TEMPLATE_P (tmpl))
30447 if (CLASS_TYPE_P (type)
30448 && CLASSTYPE_TEMPLATE_INFO (type)
30449 && CLASSTYPE_TI_TEMPLATE (type) == tmpl)
30450 return INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
30451 else
30452 return NULL_TREE;
30455 /* Otherwise it's an alias template. */
30456 tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30457 ttype = TREE_TYPE (tmpl);
30459 else
30461 /* TMPL is a synthetic alias template represented as a TREE_LIST as
30462 per alias_ctad_tweaks. */
30463 tparms = INNERMOST_TEMPLATE_PARMS (TREE_PURPOSE (tmpl));
30464 ttype = TREE_VALUE (tmpl);
30465 tmpl = TI_TEMPLATE (TYPE_TEMPLATE_INFO_MAYBE_ALIAS (ttype));
30468 int len = TREE_VEC_LENGTH (tparms);
30469 tree targs = make_tree_vec (len);
30470 bool tried_array_deduction = (cxx_dialect < cxx17);
30472 again:
30473 if (unify (tparms, targs, ttype, type,
30474 UNIFY_ALLOW_NONE, false))
30475 return NULL_TREE;
30477 /* We don't fail on an undeduced targ the second time through (like
30478 get_partial_spec_bindings) because we're going to try defaults. */
30479 for (int i = 0; i < len; ++i)
30480 if (! TREE_VEC_ELT (targs, i))
30482 tree tparm = TREE_VEC_ELT (tparms, i);
30483 tparm = TREE_VALUE (tparm);
30485 if (!tried_array_deduction
30486 && TREE_CODE (tparm) == TYPE_DECL)
30488 try_array_deduction (tparms, targs, ttype);
30489 tried_array_deduction = true;
30490 if (TREE_VEC_ELT (targs, i))
30491 goto again;
30493 /* If the type parameter is a parameter pack, then it will be deduced
30494 to an empty parameter pack. This is another case that doesn't model
30495 well as partial specialization. */
30496 if (template_parameter_pack_p (tparm))
30498 tree arg;
30499 if (TREE_CODE (tparm) == PARM_DECL)
30501 arg = make_node (NONTYPE_ARGUMENT_PACK);
30502 TREE_CONSTANT (arg) = 1;
30504 else
30505 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30506 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30507 TREE_VEC_ELT (targs, i) = arg;
30511 /* Maybe add in default template args. This seems like a flaw in the
30512 specification in terms of partial specialization, since it says the
30513 partial specialization has the the template parameter list of A, but a
30514 partial specialization can't have default targs. */
30515 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30516 if (targs == error_mark_node)
30517 return NULL_TREE;
30519 /* I believe we don't need the template_template_parm_bindings_ok_p call
30520 because coerce_template_parms did coerce_template_template_parms. */
30522 if (!constraints_satisfied_p (tmpl, targs))
30523 return NULL_TREE;
30525 return targs;
30528 /* Return artificial deduction guides built from the constructors of class
30529 template TMPL. */
30531 static tree
30532 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30534 tree outer_args = outer_template_args (tmpl);
30535 tree type = TREE_TYPE (most_general_template (tmpl));
30537 tree cands = NULL_TREE;
30539 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30541 /* We handle C++23 inherited CTAD below. */
30542 if (iter.using_p ())
30543 continue;
30545 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30546 cands = lookup_add (guide, cands);
30549 if (cxx_dialect >= cxx23)
30550 for (tree ctor : ovl_range (CLASSTYPE_CONSTRUCTORS (type)))
30551 if (TREE_CODE (ctor) == USING_DECL)
30553 tree uguides = inherited_ctad_tweaks (tmpl, ctor, complain);
30554 if (uguides)
30555 cands = lookup_add (uguides, cands);
30558 /* Add implicit default constructor deduction guide. */
30559 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30561 tree guide = build_deduction_guide (type, type, outer_args,
30562 complain);
30563 cands = lookup_add (guide, cands);
30566 /* Add copy guide. */
30568 tree gtype = build_reference_type (type);
30569 tree guide = build_deduction_guide (type, gtype, outer_args,
30570 complain);
30571 cands = lookup_add (guide, cands);
30574 return cands;
30577 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30579 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30580 aggregate candidate is added separately because it depends on the
30581 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30582 guide. */
30584 static tree
30585 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30587 tree guides = NULL_TREE;
30588 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30590 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30591 tree tinfo = get_template_info (under);
30592 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30593 complain);
30595 else
30597 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30598 dguide_name (tmpl),
30599 LOOK_want::NORMAL, /*complain*/false);
30600 if (guides == error_mark_node)
30601 guides = NULL_TREE;
30602 else
30603 any_dguides_p = true;
30606 /* Cache the deduction guides for a template. We also remember the result of
30607 lookup, and rebuild everything if it changes; should be very rare. */
30608 /* FIXME: Also rebuild if this is a class template that inherits guides from a
30609 base class, and lookup for the latter changed. */
30610 tree_pair_p cache = NULL;
30611 if (tree_pair_p &r
30612 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30614 cache = r;
30615 if (cache->purpose == guides)
30616 return cache->value;
30618 else
30620 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30621 cache->purpose = guides;
30624 tree cands = NULL_TREE;
30625 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30626 cands = alias_ctad_tweaks (tmpl, guides);
30627 else
30629 cands = ctor_deduction_guides_for (tmpl, complain);
30630 for (ovl_iterator it (guides); it; ++it)
30631 cands = lookup_add (*it, cands);
30634 cache->value = cands;
30635 return cands;
30638 /* Return whether TMPL is a (class template argument-) deducible template. */
30640 bool
30641 ctad_template_p (tree tmpl)
30643 /* A deducible template is either a class template or is an alias template
30644 whose defining-type-id is of the form
30646 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30648 where the nested-name-specifier (if any) is non-dependent and the
30649 template-name of the simple-template-id names a deducible template. */
30651 if (DECL_CLASS_TEMPLATE_P (tmpl)
30652 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30653 return true;
30654 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30655 return false;
30656 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30657 if (tree tinfo = get_template_info (orig))
30658 return ctad_template_p (TI_TEMPLATE (tinfo));
30659 return false;
30662 /* Deduce template arguments for the class template placeholder PTYPE for
30663 template TMPL based on the initializer INIT, and return the resulting
30664 type. */
30666 static tree
30667 do_class_deduction (tree ptype, tree tmpl, tree init,
30668 int flags, tsubst_flags_t complain)
30670 /* We should have handled this in the caller. */
30671 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30672 return ptype;
30674 /* If the class was erroneous, don't try to deduce, because that
30675 can generate a lot of diagnostic. */
30676 if (TREE_TYPE (tmpl)
30677 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30678 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30679 return ptype;
30681 /* Wait until the enclosing scope is non-dependent. */
30682 if (DECL_CLASS_SCOPE_P (tmpl)
30683 && dependent_type_p (DECL_CONTEXT (tmpl)))
30684 return ptype;
30686 /* Initializing one placeholder from another. */
30687 if (init
30688 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30689 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30690 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30691 == TEMPLATE_PARM_INDEX)))
30692 && is_auto (TREE_TYPE (init))
30693 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30694 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30696 if (!ctad_template_p (tmpl))
30698 if (complain & tf_error)
30699 error ("non-deducible template %qT used without template arguments", tmpl);
30700 return error_mark_node;
30702 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30704 if (complain & tf_error)
30706 /* Be permissive with equivalent alias templates. */
30707 tree u = get_underlying_template (tmpl);
30708 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30709 bool complained
30710 = emit_diagnostic (dk, input_location, 0,
30711 "alias template deduction only available "
30712 "with %<-std=c++20%> or %<-std=gnu++20%>");
30713 if (u == tmpl)
30714 return error_mark_node;
30715 else if (complained)
30717 inform (input_location, "use %qD directly instead", u);
30718 tmpl = u;
30721 else
30722 return error_mark_node;
30725 /* Wait until the initializer is non-dependent. */
30726 if (type_dependent_expression_p (init))
30727 return ptype;
30729 /* Don't bother with the alias rules for an equivalent template. */
30730 tmpl = get_underlying_template (tmpl);
30732 tree type = TREE_TYPE (tmpl);
30734 bool try_list_cand = false;
30735 bool list_init_p = false;
30737 releasing_vec rv_args = NULL;
30738 vec<tree,va_gc> *&args = *&rv_args;
30739 if (init == NULL_TREE)
30740 args = make_tree_vector ();
30741 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30743 list_init_p = true;
30744 try_list_cand = true;
30745 if (CONSTRUCTOR_NELTS (init) == 1
30746 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30748 /* As an exception, the first phase in 16.3.1.7 (considering the
30749 initializer list as a single argument) is omitted if the
30750 initializer list consists of a single expression of type cv U,
30751 where U is a specialization of C or a class derived from a
30752 specialization of C. */
30753 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30754 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30755 try_list_cand = false;
30757 if (try_list_cand || is_std_init_list (type))
30758 args = make_tree_vector_single (init);
30759 else
30760 args = make_tree_vector_from_ctor (init);
30762 else if (TREE_CODE (init) == TREE_LIST)
30763 args = make_tree_vector_from_list (init);
30764 else
30765 args = make_tree_vector_single (init);
30767 /* Do this now to avoid problems with erroneous args later on. */
30768 args = resolve_args (args, complain);
30769 if (args == NULL)
30770 return error_mark_node;
30772 bool any_dguides_p = false;
30773 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30774 if (cands == error_mark_node)
30775 return error_mark_node;
30777 /* Prune explicit deduction guides in copy-initialization context (but
30778 not copy-list-initialization). */
30779 bool elided = false;
30780 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30782 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30783 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30784 elided = true;
30786 if (elided)
30788 /* Found a nonconverting guide, prune the candidates. */
30789 tree pruned = NULL_TREE;
30790 for (lkp_iterator iter (cands); iter; ++iter)
30791 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30792 pruned = lookup_add (*iter, pruned);
30794 cands = pruned;
30798 if (!any_dguides_p)
30799 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30800 cands = lookup_add (guide, cands);
30802 tree fndecl = error_mark_node;
30804 /* If this is list-initialization and the class has a list guide, first
30805 try deducing from the list as a single argument, as [over.match.list]. */
30806 if (try_list_cand)
30808 tree list_cands = NULL_TREE;
30809 for (tree dg : lkp_range (cands))
30810 if (is_list_ctor (dg))
30811 list_cands = lookup_add (dg, list_cands);
30812 if (list_cands)
30813 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30814 if (fndecl == error_mark_node)
30816 /* That didn't work, now try treating the list as a sequence of
30817 arguments. */
30818 release_tree_vector (args);
30819 args = make_tree_vector_from_ctor (init);
30820 args = resolve_args (args, complain);
30821 if (args == NULL)
30822 return error_mark_node;
30826 if (elided && !cands)
30828 error ("cannot deduce template arguments for copy-initialization"
30829 " of %qT, as it has no non-explicit deduction guides or "
30830 "user-declared constructors", type);
30831 return error_mark_node;
30833 else if (!cands && fndecl == error_mark_node)
30835 error ("cannot deduce template arguments of %qT, as it has no viable "
30836 "deduction guides", type);
30837 return error_mark_node;
30840 if (fndecl == error_mark_node)
30841 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30843 if (fndecl == error_mark_node)
30845 if (complain & tf_warning_or_error)
30847 error ("class template argument deduction failed:");
30848 perform_dguide_overload_resolution (cands, args, complain);
30849 if (elided)
30850 inform (input_location, "explicit deduction guides not considered "
30851 "for copy-initialization");
30853 return error_mark_node;
30855 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30856 constructor is chosen, the initialization is ill-formed. */
30857 else if (flags & LOOKUP_ONLYCONVERTING)
30859 if (DECL_NONCONVERTING_P (fndecl))
30861 if (complain & tf_warning_or_error)
30863 // TODO: Pass down location from cp_finish_decl.
30864 error ("class template argument deduction for %qT failed: "
30865 "explicit deduction guide selected in "
30866 "copy-list-initialization", type);
30867 inform (DECL_SOURCE_LOCATION (fndecl),
30868 "explicit deduction guide declared here");
30871 return error_mark_node;
30875 /* If CTAD succeeded but the type doesn't have any explicit deduction
30876 guides, this deduction might not be what the user intended. */
30877 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30879 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30880 || global_dc->m_warn_system_headers)
30881 && warning (OPT_Wctad_maybe_unsupported,
30882 "%qT may not intend to support class template argument "
30883 "deduction", type))
30884 inform (input_location, "add a deduction guide to suppress this "
30885 "warning");
30888 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30889 cp_type_quals (ptype));
30892 /* Return true if INIT is an unparenthesized id-expression or an
30893 unparenthesized class member access. Used for the argument of
30894 decltype(auto). */
30896 bool
30897 unparenthesized_id_or_class_member_access_p (tree init)
30899 STRIP_ANY_LOCATION_WRAPPER (init);
30901 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30902 reference type). Only the latter is an id-expression. */
30903 if (REFERENCE_REF_P (init)
30904 && !REF_PARENTHESIZED_P (init))
30905 init = TREE_OPERAND (init, 0);
30906 return (DECL_P (init)
30907 || ((TREE_CODE (init) == COMPONENT_REF
30908 || TREE_CODE (init) == SCOPE_REF)
30909 && !REF_PARENTHESIZED_P (init)));
30912 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30913 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30914 The CONTEXT determines the context in which auto deduction is performed
30915 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30917 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30918 to properly substitute the result. It's also used in the adc_unify and
30919 adc_requirement contexts to communicate the necessary template arguments
30920 to satisfaction. OUTER_TARGS is ignored in other contexts.
30922 Additionally for adc_unify contexts TMPL is the template for which TYPE
30923 is a template parameter type.
30925 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30926 scope may be appended to the list of deduced template arguments prior to
30927 determining constraint satisfaction as appropriate. */
30929 tree
30930 do_auto_deduction (tree type, tree init, tree auto_node,
30931 tsubst_flags_t complain /* = tf_warning_or_error */,
30932 auto_deduction_context context /* = adc_unspecified */,
30933 tree outer_targs /* = NULL_TREE */,
30934 int flags /* = LOOKUP_NORMAL */,
30935 tree tmpl /* = NULL_TREE */)
30937 if (type == error_mark_node || init == error_mark_node)
30938 return error_mark_node;
30940 if (init && type_dependent_expression_p (init)
30941 && context != adc_unify)
30942 /* Defining a subset of type-dependent expressions that we can deduce
30943 from ahead of time isn't worth the trouble. */
30944 return type;
30946 /* Similarly, we can't deduce from another undeduced decl. */
30947 if (init && undeduced_auto_decl (init))
30948 return type;
30950 /* We may be doing a partial substitution, but we still want to replace
30951 auto_node. */
30952 complain &= ~tf_partial;
30954 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30956 /* We don't recurse here because we can't deduce from a nested
30957 initializer_list. */
30958 if (CONSTRUCTOR_ELTS (init))
30959 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30960 elt.value = resolve_nondeduced_context (elt.value, complain);
30962 else if (init)
30963 init = resolve_nondeduced_context (init, complain);
30965 /* In C++23, we must deduce the type to int&& for code like
30966 decltype(auto) f(int&& x) { return (x); }
30968 auto&& f(int x) { return x; }
30969 so we use treat_lvalue_as_rvalue_p. But don't do it for
30970 decltype(auto) f(int x) { return x; }
30971 where we should deduce 'int' rather than 'int&&'; transmogrifying
30972 INIT to an rvalue would break that. */
30973 tree r;
30974 if (cxx_dialect >= cxx23
30975 && context == adc_return_type
30976 && (!AUTO_IS_DECLTYPE (auto_node)
30977 || !unparenthesized_id_or_class_member_access_p (init))
30978 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30979 /*return*/true)))
30980 init = r;
30982 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30983 /* C++17 class template argument deduction. */
30984 return do_class_deduction (type, ctmpl, init, flags, complain);
30986 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30987 /* Nothing we can do with this, even in deduction context. */
30988 return type;
30990 location_t loc = cp_expr_loc_or_input_loc (init);
30992 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30993 with either a new invented type template parameter U or, if the
30994 initializer is a braced-init-list (8.5.4), with
30995 std::initializer_list<U>. */
30996 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30998 if (!DIRECT_LIST_INIT_P (init))
30999 type = listify_autos (type, auto_node);
31000 else if (CONSTRUCTOR_NELTS (init) == 1)
31001 init = CONSTRUCTOR_ELT (init, 0)->value;
31002 else
31004 if (complain & tf_warning_or_error)
31006 if (permerror (loc, "direct-list-initialization of "
31007 "%<auto%> requires exactly one element"))
31008 inform (loc,
31009 "for deduction to %<std::initializer_list%>, use copy-"
31010 "list-initialization (i.e. add %<=%> before the %<{%>)");
31012 type = listify_autos (type, auto_node);
31016 if (type == error_mark_node || init == error_mark_node)
31017 return error_mark_node;
31019 tree targs;
31020 if (context == adc_decomp_type
31021 && auto_node == type
31022 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
31024 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
31025 and initializer has array type, deduce cv-qualified array type. */
31026 targs = make_tree_vec (1);
31027 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
31029 else if (AUTO_IS_DECLTYPE (auto_node))
31031 const bool id = unparenthesized_id_or_class_member_access_p (init);
31032 tree deduced = finish_decltype_type (init, id, complain);
31033 deduced = canonicalize_type_argument (deduced, complain);
31034 if (deduced == error_mark_node)
31035 return error_mark_node;
31036 targs = make_tree_vec (1);
31037 TREE_VEC_ELT (targs, 0) = deduced;
31039 else
31041 if (error_operand_p (init))
31042 return error_mark_node;
31044 tree parms = build_tree_list (NULL_TREE, type);
31045 tree tparms;
31047 if (flag_concepts_ts)
31048 tparms = extract_autos (type);
31049 else
31051 tparms = make_tree_vec (1);
31052 TREE_VEC_ELT (tparms, 0)
31053 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
31056 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
31057 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
31058 DEDUCE_CALL,
31059 NULL, /*explain_p=*/false);
31060 if (val > 0)
31062 if (processing_template_decl)
31063 /* Try again at instantiation time. */
31064 return type;
31065 if (type && type != error_mark_node
31066 && (complain & tf_error))
31067 /* If type is error_mark_node a diagnostic must have been
31068 emitted by now. Also, having a mention to '<type error>'
31069 in the diagnostic is not really useful to the user. */
31071 if (cfun
31072 && FNDECL_USED_AUTO (current_function_decl)
31073 && (auto_node
31074 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
31075 && LAMBDA_FUNCTION_P (current_function_decl))
31076 error_at (loc, "unable to deduce lambda return type from %qE",
31077 init);
31078 else
31079 error_at (loc, "unable to deduce %qT from %qE", type, init);
31080 type_unification_real (tparms, targs, parms, &init, 1, 0,
31081 DEDUCE_CALL,
31082 NULL, /*explain_p=*/true);
31084 return error_mark_node;
31088 /* Check any placeholder constraints against the deduced type. */
31089 if (processing_template_decl && context == adc_unify)
31090 /* Constraints will be checked after deduction. */;
31091 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
31093 if (processing_template_decl)
31095 gcc_checking_assert (context == adc_variable_type
31096 || context == adc_return_type
31097 || context == adc_decomp_type);
31098 gcc_checking_assert (!type_dependent_expression_p (init));
31099 /* If the constraint is dependent, we need to wait until
31100 instantiation time to resolve the placeholder. */
31101 if (placeholder_type_constraint_dependent_p (constr))
31102 return type;
31105 if (context == adc_return_type
31106 || context == adc_variable_type
31107 || context == adc_decomp_type)
31108 if (tree fn = current_function_decl)
31109 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
31111 outer_targs = DECL_TEMPLATE_INFO (fn)
31112 ? DECL_TI_ARGS (fn) : NULL_TREE;
31113 if (LAMBDA_FUNCTION_P (fn))
31115 /* As in satisfy_declaration_constraints. */
31116 tree regen_args = lambda_regenerating_args (fn);
31117 if (outer_targs)
31118 outer_targs = add_to_template_args (regen_args, outer_targs);
31119 else
31120 outer_targs = regen_args;
31124 tree full_targs = outer_targs;
31125 if (context == adc_unify && tmpl)
31126 full_targs = add_outermost_template_args (tmpl, full_targs);
31127 full_targs = add_to_template_args (full_targs, targs);
31129 /* HACK: Compensate for callers not always communicating all levels of
31130 outer template arguments by filling in the outermost missing levels
31131 with dummy levels before checking satisfaction. We'll still crash
31132 if the constraint depends on a template argument belonging to one of
31133 these missing levels, but this hack otherwise allows us to handle a
31134 large subset of possible constraints (including all non-dependent
31135 constraints). */
31136 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31137 - TMPL_ARGS_DEPTH (full_targs)))
31139 tree dummy_levels = make_tree_vec (missing_levels);
31140 for (int i = 0; i < missing_levels; ++i)
31141 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31142 full_targs = add_to_template_args (dummy_levels, full_targs);
31145 if (!constraints_satisfied_p (auto_node, full_targs))
31147 if (complain & tf_warning_or_error)
31149 auto_diagnostic_group d;
31150 switch (context)
31152 case adc_unspecified:
31153 case adc_unify:
31154 error_at (loc, "placeholder constraints not satisfied");
31155 break;
31156 case adc_variable_type:
31157 case adc_decomp_type:
31158 error_at (loc, "deduced initializer does not satisfy "
31159 "placeholder constraints");
31160 break;
31161 case adc_return_type:
31162 error_at (loc, "deduced return type does not satisfy "
31163 "placeholder constraints");
31164 break;
31165 case adc_requirement:
31166 error_at (loc, "deduced expression type does not satisfy "
31167 "placeholder constraints");
31168 break;
31170 diagnose_constraints (loc, auto_node, full_targs);
31172 return error_mark_node;
31176 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31177 /* The outer template arguments are already substituted into type
31178 (but we still may have used them for constraint checking above). */;
31179 else if (context == adc_unify)
31180 targs = add_to_template_args (outer_targs, targs);
31181 else if (processing_template_decl)
31182 targs = add_to_template_args (current_template_args (), targs);
31183 return tsubst (type, targs, complain, NULL_TREE);
31186 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31187 result. */
31189 tree
31190 splice_late_return_type (tree type, tree late_return_type)
31192 if (late_return_type)
31194 gcc_assert (is_auto (type) || seen_error ());
31195 return late_return_type;
31198 if (tree auto_node = find_type_usage (type, is_auto))
31199 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31201 /* In an abbreviated function template we didn't know we were dealing
31202 with a function template when we saw the auto return type, so rebuild
31203 the return type using an auto with the correct level. */
31204 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31205 tree auto_vec = make_tree_vec (1);
31206 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31207 tree targs = add_outermost_template_args (current_template_args (),
31208 auto_vec);
31209 /* Also rebuild the constraint info in terms of the new auto. */
31210 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31211 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31212 = build_tree_list (current_template_parms,
31213 tsubst_constraint (TREE_VALUE (ci), targs,
31214 tf_none, NULL_TREE));
31215 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31216 return tsubst (type, targs, tf_none, NULL_TREE);
31218 return type;
31221 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31222 'decltype(auto)' or a deduced class template. */
31224 bool
31225 is_auto (const_tree type)
31227 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31228 && (TYPE_IDENTIFIER (type) == auto_identifier
31229 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31230 return true;
31231 else
31232 return false;
31235 /* for_each_template_parm callback for type_uses_auto. */
31238 is_auto_r (tree tp, void */*data*/)
31240 return is_auto (tp);
31243 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31244 a use of `auto'. Returns NULL_TREE otherwise. */
31246 tree
31247 type_uses_auto (tree type)
31249 if (type == NULL_TREE)
31250 return NULL_TREE;
31252 /* For parameter packs, check the contents of the pack. */
31253 if (PACK_EXPANSION_P (type))
31254 type = PACK_EXPANSION_PATTERN (type);
31256 if (flag_concepts_ts)
31258 /* The Concepts TS allows multiple autos in one type-specifier; just
31259 return the first one we find, do_auto_deduction will collect all of
31260 them. */
31261 if (uses_template_parms (type))
31262 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31263 /*visited*/NULL, /*nondeduced*/false);
31264 else
31265 return NULL_TREE;
31267 else
31268 return find_type_usage (type, is_auto);
31271 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31272 concepts are enabled, auto is acceptable in template arguments, but
31273 only when TEMPL identifies a template class. Return TRUE if any
31274 such errors were reported. */
31276 bool
31277 check_auto_in_tmpl_args (tree tmpl, tree args)
31279 if (!flag_concepts_ts)
31280 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31281 have already been rejected by the parser more generally. */
31282 return false;
31284 /* If there were previous errors, nevermind. */
31285 if (!args || TREE_CODE (args) != TREE_VEC)
31286 return false;
31288 /* If TMPL is an identifier, we're parsing and we can't tell yet
31289 whether TMPL is supposed to be a type, a function or a variable.
31290 We'll only be able to tell during template substitution, so we
31291 expect to be called again then. If concepts are enabled and we
31292 know we have a type, we're ok. */
31293 if (identifier_p (tmpl)
31294 || (DECL_P (tmpl)
31295 && (DECL_TYPE_TEMPLATE_P (tmpl)
31296 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31297 return false;
31299 /* Quickly search for any occurrences of auto; usually there won't
31300 be any, and then we'll avoid allocating the vector. */
31301 if (!type_uses_auto (args))
31302 return false;
31304 bool errors = false;
31306 tree vec = extract_autos (args);
31307 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31309 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31310 error_at (DECL_SOURCE_LOCATION (xauto),
31311 "invalid use of %qT in template argument", xauto);
31312 errors = true;
31315 return errors;
31318 /* Recursively walk over && expressions searching for EXPR. Return a reference
31319 to that expression. */
31321 static tree *find_template_requirement (tree *t, tree key)
31323 if (*t == key)
31324 return t;
31325 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31327 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31328 return p;
31329 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31330 return p;
31332 return 0;
31335 /* Convert the generic type parameters in PARM that match the types given in the
31336 range [START_IDX, END_IDX) from the current_template_parms into generic type
31337 packs. */
31339 tree
31340 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31342 tree current = current_template_parms;
31343 int depth = TMPL_PARMS_DEPTH (current);
31344 current = INNERMOST_TEMPLATE_PARMS (current);
31345 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31347 for (int i = 0; i < start_idx; ++i)
31348 TREE_VEC_ELT (replacement, i)
31349 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31351 for (int i = start_idx; i < end_idx; ++i)
31353 /* Create a distinct parameter pack type from the current parm and add it
31354 to the replacement args to tsubst below into the generic function
31355 parameter. */
31356 tree node = TREE_VEC_ELT (current, i);
31357 tree o = TREE_TYPE (TREE_VALUE (node));
31358 tree t = copy_type (o);
31359 TEMPLATE_TYPE_PARM_INDEX (t)
31360 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31361 t, 0, 0, tf_none);
31362 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31363 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31364 TYPE_MAIN_VARIANT (t) = t;
31365 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31366 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31367 TREE_VEC_ELT (replacement, i) = t;
31369 /* Replace the current template parameter with new pack. */
31370 TREE_VALUE (node) = TREE_CHAIN (t);
31372 /* Surgically adjust the associated constraint of adjusted parameter
31373 and it's corresponding contribution to the current template
31374 requirements. */
31375 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31377 tree id = unpack_concept_check (constr);
31378 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31379 /* Use UNKNOWN_LOCATION so write_template_args can tell the
31380 difference between this and a fold the user wrote. */
31381 location_t loc = UNKNOWN_LOCATION;
31382 tree fold = finish_left_unary_fold_expr (loc, constr,
31383 TRUTH_ANDIF_EXPR);
31384 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31386 /* If there was a constraint, we also need to replace that in
31387 the template requirements, which we've already built. */
31388 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31389 reqs = find_template_requirement (reqs, constr);
31390 *reqs = fold;
31394 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31395 TREE_VEC_ELT (replacement, i)
31396 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31398 /* If there are more levels then build up the replacement with the outer
31399 template parms. */
31400 if (depth > 1)
31401 replacement = add_to_template_args (template_parms_to_args
31402 (TREE_CHAIN (current_template_parms)),
31403 replacement);
31405 return tsubst (parm, replacement, tf_none, NULL_TREE);
31408 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31409 0..N-1. */
31411 void
31412 declare_integer_pack (void)
31414 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31415 build_function_type_list (integer_type_node,
31416 integer_type_node,
31417 NULL_TREE),
31418 NULL_TREE, ECF_CONST);
31419 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31420 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31421 CP_BUILT_IN_INTEGER_PACK);
31424 /* Walk the decl or type specialization table calling FN on each
31425 entry. */
31427 void
31428 walk_specializations (bool decls_p,
31429 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31430 void *data)
31432 spec_hash_table *table = decls_p ? decl_specializations
31433 : type_specializations;
31434 spec_hash_table::iterator end (table->end ());
31435 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31436 fn (decls_p, *iter, data);
31439 /* Lookup the specialization of *ELT, in the decl or type
31440 specialization table. Return the SPEC that's already there, or
31441 NULL if nothing. */
31443 tree
31444 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31446 hash_table<spec_hasher> *specializations
31447 = decl_p ? decl_specializations : type_specializations;
31448 hashval_t hash = spec_hasher::hash (elt);
31449 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31451 if (slot)
31452 return (*slot)->spec;
31454 return NULL_TREE;
31457 /* Return flags encoding whether SPEC is on the instantiation and/or
31458 specialization lists of TMPL. */
31460 unsigned
31461 get_mergeable_specialization_flags (tree tmpl, tree decl)
31463 unsigned flags = 0;
31465 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31466 inst; inst = TREE_CHAIN (inst))
31467 if (TREE_VALUE (inst) == decl)
31469 flags |= 1;
31470 break;
31473 if (CLASS_TYPE_P (TREE_TYPE (decl))
31474 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31475 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31476 /* Only need to search if DECL is a partial specialization. */
31477 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31478 part; part = TREE_CHAIN (part))
31479 if (TREE_VALUE (part) == decl)
31481 flags |= 2;
31482 break;
31485 return flags;
31488 /* Add a new specialization described by SPEC. DECL is the
31489 maybe-template decl and FLAGS is as returned from
31490 get_mergeable_specialization_flags. */
31492 void
31493 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31494 tree decl, unsigned flags)
31496 hashval_t hash = spec_hasher::hash (elt);
31497 if (decl_p)
31499 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31501 gcc_checking_assert (!*slot);
31502 auto entry = ggc_alloc<spec_entry> ();
31503 *entry = *elt;
31504 *slot = entry;
31506 if (alias_p)
31508 elt->spec = TREE_TYPE (elt->spec);
31509 gcc_checking_assert (elt->spec);
31513 if (!decl_p || alias_p)
31515 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31517 /* We don't distinguish different constrained partial type
31518 specializations, so there could be duplicates. Everything else
31519 must be new. */
31520 if (!(flags & 2 && *slot))
31522 gcc_checking_assert (!*slot);
31524 auto entry = ggc_alloc<spec_entry> ();
31525 *entry = *elt;
31526 *slot = entry;
31530 if (flags & 1)
31531 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31532 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31534 if (flags & 2)
31536 /* A partial specialization. */
31537 tree cons = tree_cons (elt->args, decl,
31538 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31539 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31540 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31544 /* Set up the hash tables for template instantiations. */
31546 void
31547 init_template_processing (void)
31549 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31550 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31552 if (cxx_dialect >= cxx11)
31553 declare_integer_pack ();
31556 /* Print stats about the template hash tables for -fstats. */
31558 void
31559 print_template_statistics (void)
31561 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31562 "%f collisions\n", (long) decl_specializations->size (),
31563 (long) decl_specializations->elements (),
31564 decl_specializations->collisions ());
31565 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31566 "%f collisions\n", (long) type_specializations->size (),
31567 (long) type_specializations->elements (),
31568 type_specializations->collisions ());
31571 #if CHECKING_P
31573 namespace selftest {
31575 /* Verify that type_dependent_expression_p () works correctly, even
31576 in the presence of location wrapper nodes. */
31578 static void
31579 test_type_dependent_expression_p ()
31581 location_t loc = BUILTINS_LOCATION;
31583 tree name = get_identifier ("foo");
31585 /* If no templates are involved, nothing is type-dependent. */
31586 gcc_assert (!processing_template_decl);
31587 ASSERT_FALSE (type_dependent_expression_p (name));
31589 ++processing_template_decl;
31591 /* Within a template, an unresolved name is always type-dependent. */
31592 ASSERT_TRUE (type_dependent_expression_p (name));
31594 /* Ensure it copes with NULL_TREE and errors. */
31595 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31596 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31598 /* A USING_DECL in a template should be type-dependent, even if wrapped
31599 with a location wrapper (PR c++/83799). */
31600 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31601 TREE_TYPE (using_decl) = integer_type_node;
31602 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31603 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31604 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31605 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31607 --processing_template_decl;
31610 /* Run all of the selftests within this file. */
31612 void
31613 cp_pt_cc_tests ()
31615 test_type_dependent_expression_p ();
31618 } // namespace selftest
31620 #endif /* #if CHECKING_P */
31622 #include "gt-cp-pt.h"