c++: cast to array of unknown bound [PR93259]
[official-gcc.git] / gcc / cp / pt.cc
blob31e3e3910989b3678c55a556cfb763d216b30778
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2022 Free Software Foundation, Inc.
3 Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4 Rewritten by Jason Merrill (jason@cygnus.com).
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* Known bugs or deficiencies include:
24 all methods must be provided in header files; can't use a source
25 file that contains only the method templates and "just win".
27 Fixed by: C++20 modules. */
29 #include "config.h"
30 #define INCLUDE_ALGORITHM // for std::equal
31 #include "system.h"
32 #include "coretypes.h"
33 #include "cp-tree.h"
34 #include "timevar.h"
35 #include "stringpool.h"
36 #include "varasm.h"
37 #include "attribs.h"
38 #include "stor-layout.h"
39 #include "intl.h"
40 #include "c-family/c-objc.h"
41 #include "cp-objcp-common.h"
42 #include "toplev.h"
43 #include "tree-iterator.h"
44 #include "type-utils.h"
45 #include "gimplify.h"
46 #include "gcc-rich-location.h"
47 #include "selftest.h"
48 #include "target.h"
50 /* The type of functions taking a tree, and some additional data, and
51 returning an int. */
52 typedef int (*tree_fn_t) (tree, void*);
54 /* The PENDING_TEMPLATES is a list of templates whose instantiations
55 have been deferred, either because their definitions were not yet
56 available, or because we were putting off doing the work. */
57 struct GTY ((chain_next ("%h.next"))) pending_template
59 struct pending_template *next;
60 struct tinst_level *tinst;
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
66 int processing_template_parmlist;
67 static int template_header_count;
69 static vec<int> inline_parm_levels;
71 static GTY(()) struct tinst_level *current_tinst_level;
73 static GTY(()) vec<tree, va_gc> *saved_access_scope;
75 /* Live only within one (recursive) call to tsubst_expr. We use
76 this to pass the statement expression node from the STMT_EXPR
77 to the EXPR_STMT that is its result. */
78 static tree cur_stmt_expr;
80 // -------------------------------------------------------------------------- //
81 // Local Specialization Stack
83 // Implementation of the RAII helper for creating new local
84 // specializations.
85 local_specialization_stack::local_specialization_stack (lss_policy policy)
86 : saved (local_specializations)
88 if (policy == lss_nop)
90 else if (policy == lss_blank || !saved)
91 local_specializations = new hash_map<tree, tree>;
92 else
93 local_specializations = new hash_map<tree, tree>(*saved);
96 local_specialization_stack::~local_specialization_stack ()
98 if (local_specializations != saved)
100 delete local_specializations;
101 local_specializations = saved;
105 /* True if we've recursed into fn_type_unification too many times. */
106 static bool excessive_deduction_depth;
108 struct spec_hasher : ggc_ptr_hash<spec_entry>
110 static hashval_t hash (tree, tree);
111 static hashval_t hash (spec_entry *);
112 static bool equal (spec_entry *, spec_entry *);
115 /* The general template is not in these tables. */
116 typedef hash_table<spec_hasher> spec_hash_table;
117 static GTY (()) spec_hash_table *decl_specializations;
118 static GTY (()) spec_hash_table *type_specializations;
120 /* Contains canonical template parameter types. The vector is indexed by
121 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
122 TREE_LIST, whose TREE_VALUEs contain the canonical template
123 parameters of various types and levels. */
124 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
126 #define UNIFY_ALLOW_NONE 0
127 #define UNIFY_ALLOW_MORE_CV_QUAL 1
128 #define UNIFY_ALLOW_LESS_CV_QUAL 2
129 #define UNIFY_ALLOW_DERIVED 4
130 #define UNIFY_ALLOW_INTEGER 8
131 #define UNIFY_ALLOW_OUTER_LEVEL 16
132 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
133 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
135 enum template_base_result {
136 tbr_incomplete_type,
137 tbr_ambiguous_baseclass,
138 tbr_success
141 static bool resolve_overloaded_unification (tree, tree, tree, tree,
142 unification_kind_t, int,
143 bool);
144 static int try_one_overload (tree, tree, tree, tree, tree,
145 unification_kind_t, int, bool, bool);
146 static int unify (tree, tree, tree, tree, int, bool);
147 static void add_pending_template (tree);
148 static tree reopen_tinst_level (struct tinst_level *);
149 static tree tsubst_initializer_list (tree, tree);
150 static tree get_partial_spec_bindings (tree, tree, tree);
151 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
152 bool, bool);
153 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
154 bool, bool);
155 static void tsubst_enum (tree, tree, tree);
156 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
157 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
158 struct conversion **, bool);
159 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
160 tree*, tree*, tree);
161 static int type_unification_real (tree, tree, tree, const tree *,
162 unsigned int, int, unification_kind_t,
163 vec<deferred_access_check, va_gc> **,
164 bool);
165 static void note_template_header (int);
166 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
167 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
168 static tree convert_template_argument (tree, tree, tree,
169 tsubst_flags_t, int, tree);
170 static tree for_each_template_parm (tree, tree_fn_t, void*,
171 hash_set<tree> *, bool, tree_fn_t = NULL);
172 static tree expand_template_argument_pack (tree);
173 static tree build_template_parm_index (int, int, int, tree, tree);
174 static bool inline_needs_template_parms (tree, bool);
175 static void push_inline_template_parms_recursive (tree, int);
176 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
177 static int mark_template_parm (tree, void *);
178 static int template_parm_this_level_p (tree, void *);
179 static tree tsubst_friend_function (tree, tree);
180 static tree tsubst_friend_class (tree, tree);
181 static int can_complete_type_without_circularity (tree);
182 static tree get_bindings (tree, tree, tree, bool);
183 static int template_decl_level (tree);
184 static int check_cv_quals_for_unify (int, tree, tree);
185 static int unify_pack_expansion (tree, tree, tree,
186 tree, unification_kind_t, bool, bool);
187 static tree copy_template_args (tree);
188 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
189 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
190 tree most_specialized_partial_spec (tree, tsubst_flags_t);
191 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
192 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
193 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
194 static bool check_specialization_scope (void);
195 static tree process_partial_specialization (tree);
196 static enum template_base_result get_template_base (tree, tree, tree, tree,
197 bool , tree *);
198 static tree try_class_unification (tree, tree, tree, tree, bool);
199 static bool class_nttp_const_wrapper_p (tree t);
200 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
201 tree, tree);
202 static bool template_template_parm_bindings_ok_p (tree, tree);
203 static void tsubst_default_arguments (tree, tsubst_flags_t);
204 static tree for_each_template_parm_r (tree *, int *, void *);
205 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
206 static void copy_default_args_to_explicit_spec (tree);
207 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
208 static bool dependent_template_arg_p (tree);
209 static bool dependent_type_p_r (tree);
210 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
211 static tree tsubst_decl (tree, tree, tsubst_flags_t);
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 bool complex_alias_template_p (const_tree tmpl);
218 static tree get_underlying_template (tree);
219 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
220 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
221 static tree make_argument_pack (tree);
222 static void register_parameter_specializations (tree, tree);
223 static tree enclosing_instantiation_of (tree tctx);
224 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
225 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
227 /* Make the current scope suitable for access checking when we are
228 processing T. T can be FUNCTION_DECL for instantiated function
229 template, VAR_DECL for static member variable, or TYPE_DECL for
230 for a class or alias template (needed by instantiate_decl). */
232 void
233 push_access_scope (tree t)
235 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
236 || TREE_CODE (t) == TYPE_DECL);
238 if (DECL_FRIEND_CONTEXT (t))
239 push_nested_class (DECL_FRIEND_CONTEXT (t));
240 else if (DECL_IMPLICIT_TYPEDEF_P (t)
241 && CLASS_TYPE_P (TREE_TYPE (t)))
242 push_nested_class (TREE_TYPE (t));
243 else if (DECL_CLASS_SCOPE_P (t))
244 push_nested_class (DECL_CONTEXT (t));
245 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
246 /* An artificial deduction guide should have the same access as
247 the constructor. */
248 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
249 else
250 push_to_top_level ();
252 if (TREE_CODE (t) == FUNCTION_DECL)
254 vec_safe_push (saved_access_scope, current_function_decl);
255 current_function_decl = t;
259 /* Restore the scope set up by push_access_scope. T is the node we
260 are processing. */
262 void
263 pop_access_scope (tree t)
265 if (TREE_CODE (t) == FUNCTION_DECL)
266 current_function_decl = saved_access_scope->pop();
268 if (DECL_FRIEND_CONTEXT (t)
269 || (DECL_IMPLICIT_TYPEDEF_P (t)
270 && CLASS_TYPE_P (TREE_TYPE (t)))
271 || DECL_CLASS_SCOPE_P (t)
272 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
273 pop_nested_class ();
274 else
275 pop_from_top_level ();
278 /* Do any processing required when DECL (a member template
279 declaration) is finished. Returns the TEMPLATE_DECL corresponding
280 to DECL, unless it is a specialization, in which case the DECL
281 itself is returned. */
283 tree
284 finish_member_template_decl (tree decl)
286 if (decl == error_mark_node)
287 return error_mark_node;
289 gcc_assert (DECL_P (decl));
291 if (TREE_CODE (decl) == TYPE_DECL)
293 tree type;
295 type = TREE_TYPE (decl);
296 if (type == error_mark_node)
297 return error_mark_node;
298 if (MAYBE_CLASS_TYPE_P (type)
299 && CLASSTYPE_TEMPLATE_INFO (type)
300 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
302 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
303 check_member_template (tmpl);
304 return tmpl;
306 return NULL_TREE;
308 else if (TREE_CODE (decl) == FIELD_DECL)
309 error_at (DECL_SOURCE_LOCATION (decl),
310 "data member %qD cannot be a member template", decl);
311 else if (DECL_TEMPLATE_INFO (decl))
313 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
315 check_member_template (DECL_TI_TEMPLATE (decl));
316 return DECL_TI_TEMPLATE (decl);
318 else
319 return decl;
321 else
322 error_at (DECL_SOURCE_LOCATION (decl),
323 "invalid member template declaration %qD", decl);
325 return error_mark_node;
328 /* Create a template info node. */
330 tree
331 build_template_info (tree template_decl, tree template_args)
333 tree result = make_node (TEMPLATE_INFO);
334 TI_TEMPLATE (result) = template_decl;
335 TI_ARGS (result) = template_args;
336 return result;
339 /* Return the template info node corresponding to T, whatever T is. */
341 tree
342 get_template_info (const_tree t)
344 tree tinfo = NULL_TREE;
346 if (!t || t == error_mark_node)
347 return NULL;
349 if (TREE_CODE (t) == NAMESPACE_DECL
350 || TREE_CODE (t) == PARM_DECL)
351 return NULL;
353 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
354 tinfo = DECL_TEMPLATE_INFO (t);
356 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
357 t = TREE_TYPE (t);
359 if (OVERLOAD_TYPE_P (t))
360 tinfo = TYPE_TEMPLATE_INFO (t);
361 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
362 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
364 return tinfo;
367 /* Returns the template nesting level of the indicated class TYPE.
369 For example, in:
370 template <class T>
371 struct A
373 template <class U>
374 struct B {};
377 A<T>::B<U> has depth two, while A<T> has depth one.
378 Both A<T>::B<int> and A<int>::B<U> have depth one, if
379 they are instantiations, not specializations.
381 This function is guaranteed to return 0 if passed NULL_TREE so
382 that, for example, `template_class_depth (current_class_type)' is
383 always safe. */
386 template_class_depth (tree type)
388 int depth;
390 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
392 tree tinfo = get_template_info (type);
394 if (tinfo
395 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
396 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
397 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
398 ++depth;
400 if (DECL_P (type))
402 if (tree fctx = DECL_FRIEND_CONTEXT (type))
403 type = fctx;
404 else
405 type = CP_DECL_CONTEXT (type);
407 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
408 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
409 else
410 type = CP_TYPE_CONTEXT (type);
413 return depth;
416 /* Return TRUE if NODE instantiates a template that has arguments of
417 its own, be it directly a primary template or indirectly through a
418 partial specializations. */
419 static bool
420 instantiates_primary_template_p (tree node)
422 tree tinfo = get_template_info (node);
423 if (!tinfo)
424 return false;
426 tree tmpl = TI_TEMPLATE (tinfo);
427 if (PRIMARY_TEMPLATE_P (tmpl))
428 return true;
430 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
431 return false;
433 /* So now we know we have a specialization, but it could be a full
434 or a partial specialization. To tell which, compare the depth of
435 its template arguments with those of its context. */
437 tree ctxt = DECL_CONTEXT (tmpl);
438 tree ctinfo = get_template_info (ctxt);
439 if (!ctinfo)
440 return true;
442 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
443 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
446 /* Subroutine of maybe_begin_member_template_processing.
447 Returns true if processing DECL needs us to push template parms. */
449 static bool
450 inline_needs_template_parms (tree decl, bool nsdmi)
452 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
453 return false;
455 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
456 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
459 /* Subroutine of maybe_begin_member_template_processing.
460 Push the template parms in PARMS, starting from LEVELS steps into the
461 chain, and ending at the beginning, since template parms are listed
462 innermost first. */
464 static void
465 push_inline_template_parms_recursive (tree parmlist, int levels)
467 tree parms = TREE_VALUE (parmlist);
468 int i;
470 if (levels > 1)
471 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
473 ++processing_template_decl;
474 current_template_parms
475 = tree_cons (size_int (current_template_depth + 1),
476 parms, current_template_parms);
477 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
479 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
480 NULL);
481 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
483 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
485 if (error_operand_p (parm))
486 continue;
488 gcc_assert (DECL_P (parm));
490 switch (TREE_CODE (parm))
492 case TYPE_DECL:
493 case TEMPLATE_DECL:
494 pushdecl (parm);
495 break;
497 case PARM_DECL:
498 /* Push the CONST_DECL. */
499 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
500 break;
502 default:
503 gcc_unreachable ();
508 /* Restore the template parameter context for a member template, a
509 friend template defined in a class definition, or a non-template
510 member of template class. */
512 void
513 maybe_begin_member_template_processing (tree decl)
515 tree parms;
516 int levels = 0;
517 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
519 if (nsdmi)
521 tree ctx = DECL_CONTEXT (decl);
522 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
523 /* Disregard full specializations (c++/60999). */
524 && uses_template_parms (ctx)
525 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
528 if (inline_needs_template_parms (decl, nsdmi))
530 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
531 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
533 if (DECL_TEMPLATE_SPECIALIZATION (decl))
535 --levels;
536 parms = TREE_CHAIN (parms);
539 push_inline_template_parms_recursive (parms, levels);
542 /* Remember how many levels of template parameters we pushed so that
543 we can pop them later. */
544 inline_parm_levels.safe_push (levels);
547 /* Undo the effects of maybe_begin_member_template_processing. */
549 void
550 maybe_end_member_template_processing (void)
552 int i;
553 int last;
555 if (inline_parm_levels.length () == 0)
556 return;
558 last = inline_parm_levels.pop ();
559 for (i = 0; i < last; ++i)
561 --processing_template_decl;
562 current_template_parms = TREE_CHAIN (current_template_parms);
563 poplevel (0, 0, 0);
567 /* Return a new template argument vector which contains all of ARGS,
568 but has as its innermost set of arguments the EXTRA_ARGS. */
570 tree
571 add_to_template_args (tree args, tree extra_args)
573 tree new_args;
574 int extra_depth;
575 int i;
576 int j;
578 if (args == NULL_TREE || extra_args == error_mark_node)
579 return extra_args;
581 extra_depth = TMPL_ARGS_DEPTH (extra_args);
582 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
584 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
585 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
587 for (j = 1; j <= extra_depth; ++j, ++i)
588 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
590 return new_args;
593 /* Like add_to_template_args, but only the outermost ARGS are added to
594 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
595 (EXTRA_ARGS) levels are added. This function is used to combine
596 the template arguments from a partial instantiation with the
597 template arguments used to attain the full instantiation from the
598 partial instantiation.
600 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
602 tree
603 add_outermost_template_args (tree args, tree extra_args)
605 tree new_args;
607 if (!args)
608 return extra_args;
609 if (TREE_CODE (args) == TEMPLATE_DECL)
611 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
612 args = TI_ARGS (ti);
615 /* If there are more levels of EXTRA_ARGS than there are ARGS,
616 something very fishy is going on. */
617 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
619 /* If *all* the new arguments will be the EXTRA_ARGS, just return
620 them. */
621 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
622 return extra_args;
624 /* For the moment, we make ARGS look like it contains fewer levels. */
625 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
627 new_args = add_to_template_args (args, extra_args);
629 /* Now, we restore ARGS to its full dimensions. */
630 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
632 return new_args;
635 /* Return the N levels of innermost template arguments from the ARGS. */
637 tree
638 get_innermost_template_args (tree args, int n)
640 tree new_args;
641 int extra_levels;
642 int i;
644 gcc_assert (n >= 0);
646 /* If N is 1, just return the innermost set of template arguments. */
647 if (n == 1)
648 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
650 /* If we're not removing anything, just return the arguments we were
651 given. */
652 extra_levels = TMPL_ARGS_DEPTH (args) - n;
653 gcc_assert (extra_levels >= 0);
654 if (extra_levels == 0)
655 return args;
657 /* Make a new set of arguments, not containing the outer arguments. */
658 new_args = make_tree_vec (n);
659 for (i = 1; i <= n; ++i)
660 SET_TMPL_ARGS_LEVEL (new_args, i,
661 TMPL_ARGS_LEVEL (args, i + extra_levels));
663 return new_args;
666 /* The inverse of get_innermost_template_args: Return all but the innermost
667 EXTRA_LEVELS levels of template arguments from the ARGS. */
669 static tree
670 strip_innermost_template_args (tree args, int extra_levels)
672 tree new_args;
673 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
674 int i;
676 gcc_assert (n >= 0);
678 /* If N is 1, just return the outermost set of template arguments. */
679 if (n == 1)
680 return TMPL_ARGS_LEVEL (args, 1);
682 /* If we're not removing anything, just return the arguments we were
683 given. */
684 gcc_assert (extra_levels >= 0);
685 if (extra_levels == 0)
686 return args;
688 /* Make a new set of arguments, not containing the inner arguments. */
689 new_args = make_tree_vec (n);
690 for (i = 1; i <= n; ++i)
691 SET_TMPL_ARGS_LEVEL (new_args, i,
692 TMPL_ARGS_LEVEL (args, i));
694 return new_args;
697 /* We've got a template header coming up; push to a new level for storing
698 the parms. */
700 void
701 begin_template_parm_list (void)
703 /* We use a non-tag-transparent scope here, which causes pushtag to
704 put tags in this scope, rather than in the enclosing class or
705 namespace scope. This is the right thing, since we want
706 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
707 global template class, push_template_decl handles putting the
708 TEMPLATE_DECL into top-level scope. For a nested template class,
709 e.g.:
711 template <class T> struct S1 {
712 template <class T> struct S2 {};
715 pushtag contains special code to insert the TEMPLATE_DECL for S2
716 at the right scope. */
717 begin_scope (sk_template_parms, NULL);
718 ++processing_template_decl;
719 ++processing_template_parmlist;
720 note_template_header (0);
722 /* Add a dummy parameter level while we process the parameter list. */
723 current_template_parms
724 = tree_cons (size_int (current_template_depth + 1),
725 make_tree_vec (0),
726 current_template_parms);
729 /* This routine is called when a specialization is declared. If it is
730 invalid to declare a specialization here, an error is reported and
731 false is returned, otherwise this routine will return true. */
733 static bool
734 check_specialization_scope (void)
736 tree scope = current_scope ();
738 /* [temp.expl.spec]
740 An explicit specialization shall be declared in the namespace of
741 which the template is a member, or, for member templates, in the
742 namespace of which the enclosing class or enclosing class
743 template is a member. An explicit specialization of a member
744 function, member class or static data member of a class template
745 shall be declared in the namespace of which the class template
746 is a member. */
747 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
749 error ("explicit specialization in non-namespace scope %qD", scope);
750 return false;
753 /* [temp.expl.spec]
755 In an explicit specialization declaration for a member of a class
756 template or a member template that appears in namespace scope,
757 the member template and some of its enclosing class templates may
758 remain unspecialized, except that the declaration shall not
759 explicitly specialize a class member template if its enclosing
760 class templates are not explicitly specialized as well. */
761 if (current_template_parms)
763 error ("enclosing class templates are not explicitly specialized");
764 return false;
767 return true;
770 /* We've just seen template <>. */
772 bool
773 begin_specialization (void)
775 begin_scope (sk_template_spec, NULL);
776 note_template_header (1);
777 return check_specialization_scope ();
780 /* Called at then end of processing a declaration preceded by
781 template<>. */
783 void
784 end_specialization (void)
786 finish_scope ();
787 reset_specialization ();
790 /* Any template <>'s that we have seen thus far are not referring to a
791 function specialization. */
793 void
794 reset_specialization (void)
796 processing_specialization = 0;
797 template_header_count = 0;
800 /* We've just seen a template header. If SPECIALIZATION is nonzero,
801 it was of the form template <>. */
803 static void
804 note_template_header (int specialization)
806 processing_specialization = specialization;
807 template_header_count++;
810 /* We're beginning an explicit instantiation. */
812 void
813 begin_explicit_instantiation (void)
815 gcc_assert (!processing_explicit_instantiation);
816 processing_explicit_instantiation = true;
820 void
821 end_explicit_instantiation (void)
823 gcc_assert (processing_explicit_instantiation);
824 processing_explicit_instantiation = false;
827 /* An explicit specialization or partial specialization of TMPL is being
828 declared. Check that the namespace in which the specialization is
829 occurring is permissible. Returns false iff it is invalid to
830 specialize TMPL in the current namespace. */
832 static bool
833 check_specialization_namespace (tree tmpl)
835 tree tpl_ns = decl_namespace_context (tmpl);
837 /* [tmpl.expl.spec]
839 An explicit specialization shall be declared in a namespace enclosing the
840 specialized template. An explicit specialization whose declarator-id is
841 not qualified shall be declared in the nearest enclosing namespace of the
842 template, or, if the namespace is inline (7.3.1), any namespace from its
843 enclosing namespace set. */
844 if (current_scope() != DECL_CONTEXT (tmpl)
845 && !at_namespace_scope_p ())
847 error ("specialization of %qD must appear at namespace scope", tmpl);
848 return false;
851 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
852 /* Same or enclosing namespace. */
853 return true;
854 else
856 auto_diagnostic_group d;
857 if (permerror (input_location,
858 "specialization of %qD in different namespace", tmpl))
859 inform (DECL_SOURCE_LOCATION (tmpl),
860 " from definition of %q#D", tmpl);
861 return false;
865 /* SPEC is an explicit instantiation. Check that it is valid to
866 perform this explicit instantiation in the current namespace. */
868 static void
869 check_explicit_instantiation_namespace (tree spec)
871 tree ns;
873 /* DR 275: An explicit instantiation shall appear in an enclosing
874 namespace of its template. */
875 ns = decl_namespace_context (spec);
876 if (!is_nested_namespace (current_namespace, ns))
877 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
878 "(which does not enclose namespace %qD)",
879 spec, current_namespace, ns);
882 /* Returns true if TYPE is a new partial specialization that needs to be
883 set up. This may also modify TYPE to point to the correct (new or
884 existing) constrained partial specialization. */
886 static bool
887 maybe_new_partial_specialization (tree& type)
889 /* An implicit instantiation of an incomplete type implies
890 the definition of a new class template.
892 template<typename T>
893 struct S;
895 template<typename T>
896 struct S<T*>;
898 Here, S<T*> is an implicit instantiation of S whose type
899 is incomplete. */
900 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
901 return true;
903 /* It can also be the case that TYPE is a completed specialization.
904 Continuing the previous example, suppose we also declare:
906 template<typename T>
907 requires Integral<T>
908 struct S<T*>;
910 Here, S<T*> refers to the specialization S<T*> defined
911 above. However, we need to differentiate definitions because
912 we intend to define a new partial specialization. In this case,
913 we rely on the fact that the constraints are different for
914 this declaration than that above.
916 Note that we also get here for injected class names and
917 late-parsed template definitions. We must ensure that we
918 do not create new type declarations for those cases. */
919 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
921 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
922 tree args = CLASSTYPE_TI_ARGS (type);
924 /* If there are no template parameters, this cannot be a new
925 partial template specialization? */
926 if (!current_template_parms)
927 return false;
929 /* The injected-class-name is not a new partial specialization. */
930 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
931 return false;
933 /* If the constraints are not the same as those of the primary
934 then, we can probably create a new specialization. */
935 tree type_constr = current_template_constraints ();
937 if (type == TREE_TYPE (tmpl))
939 tree main_constr = get_constraints (tmpl);
940 if (equivalent_constraints (type_constr, main_constr))
941 return false;
944 /* Also, if there's a pre-existing specialization with matching
945 constraints, then this also isn't new. */
946 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
947 while (specs)
949 tree spec_tmpl = TREE_VALUE (specs);
950 tree spec_args = TREE_PURPOSE (specs);
951 tree spec_constr = get_constraints (spec_tmpl);
952 if (comp_template_args (args, spec_args)
953 && equivalent_constraints (type_constr, spec_constr))
955 type = TREE_TYPE (spec_tmpl);
956 return false;
958 specs = TREE_CHAIN (specs);
961 /* Create a new type node (and corresponding type decl)
962 for the newly declared specialization. */
963 tree t = make_class_type (TREE_CODE (type));
964 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
965 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
967 /* We only need a separate type node for storing the definition of this
968 partial specialization; uses of S<T*> are unconstrained, so all are
969 equivalent. So keep TYPE_CANONICAL the same. */
970 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
972 /* Build the corresponding type decl. */
973 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
974 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
975 DECL_SOURCE_LOCATION (d) = input_location;
976 TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
977 TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
979 set_instantiating_module (d);
980 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
982 type = t;
983 return true;
986 return false;
989 /* The TYPE is being declared. If it is a template type, that means it
990 is a partial specialization. Do appropriate error-checking. */
992 tree
993 maybe_process_partial_specialization (tree type)
995 tree context;
997 if (type == error_mark_node)
998 return error_mark_node;
1000 /* A lambda that appears in specialization context is not itself a
1001 specialization. */
1002 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1003 return type;
1005 /* An injected-class-name is not a specialization. */
1006 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1007 return type;
1009 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1011 error ("name of class shadows template template parameter %qD",
1012 TYPE_NAME (type));
1013 return error_mark_node;
1016 context = TYPE_CONTEXT (type);
1018 if (TYPE_ALIAS_P (type))
1020 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1022 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1023 error ("specialization of alias template %qD",
1024 TI_TEMPLATE (tinfo));
1025 else
1026 error ("explicit specialization of non-template %qT", type);
1027 return error_mark_node;
1029 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1031 /* This is for ordinary explicit specialization and partial
1032 specialization of a template class such as:
1034 template <> class C<int>;
1038 template <class T> class C<T*>;
1040 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1042 if (maybe_new_partial_specialization (type))
1044 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1045 && !at_namespace_scope_p ())
1046 return error_mark_node;
1047 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1048 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1049 if (processing_template_decl)
1051 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1052 if (decl == error_mark_node)
1053 return error_mark_node;
1054 return TREE_TYPE (decl);
1057 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1058 error ("specialization of %qT after instantiation", type);
1059 else if (errorcount && !processing_specialization
1060 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1061 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1062 /* Trying to define a specialization either without a template<> header
1063 or in an inappropriate place. We've already given an error, so just
1064 bail now so we don't actually define the specialization. */
1065 return error_mark_node;
1067 else if (CLASS_TYPE_P (type)
1068 && !CLASSTYPE_USE_TEMPLATE (type)
1069 && CLASSTYPE_TEMPLATE_INFO (type)
1070 && context && CLASS_TYPE_P (context)
1071 && CLASSTYPE_TEMPLATE_INFO (context))
1073 /* This is for an explicit specialization of member class
1074 template according to [temp.expl.spec/18]:
1076 template <> template <class U> class C<int>::D;
1078 The context `C<int>' must be an implicit instantiation.
1079 Otherwise this is just a member class template declared
1080 earlier like:
1082 template <> class C<int> { template <class U> class D; };
1083 template <> template <class U> class C<int>::D;
1085 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1086 while in the second case, `C<int>::D' is a primary template
1087 and `C<T>::D' may not exist. */
1089 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1090 && !COMPLETE_TYPE_P (type))
1092 tree t;
1093 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1095 if (current_namespace
1096 != decl_namespace_context (tmpl))
1098 if (permerror (input_location,
1099 "specialization of %qD in different namespace",
1100 type))
1101 inform (DECL_SOURCE_LOCATION (tmpl),
1102 "from definition of %q#D", tmpl);
1105 /* Check for invalid specialization after instantiation:
1107 template <> template <> class C<int>::D<int>;
1108 template <> template <class U> class C<int>::D; */
1110 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1111 t; t = TREE_CHAIN (t))
1113 tree inst = TREE_VALUE (t);
1114 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1115 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1117 /* We already have a full specialization of this partial
1118 instantiation, or a full specialization has been
1119 looked up but not instantiated. Reassign it to the
1120 new member specialization template. */
1121 spec_entry elt;
1122 spec_entry *entry;
1124 elt.tmpl = most_general_template (tmpl);
1125 elt.args = CLASSTYPE_TI_ARGS (inst);
1126 elt.spec = inst;
1128 type_specializations->remove_elt (&elt);
1130 elt.tmpl = tmpl;
1131 CLASSTYPE_TI_ARGS (inst)
1132 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1134 spec_entry **slot
1135 = type_specializations->find_slot (&elt, INSERT);
1136 entry = ggc_alloc<spec_entry> ();
1137 *entry = elt;
1138 *slot = entry;
1140 else
1141 /* But if we've had an implicit instantiation, that's a
1142 problem ([temp.expl.spec]/6). */
1143 error ("specialization %qT after instantiation %qT",
1144 type, inst);
1147 /* Mark TYPE as a specialization. And as a result, we only
1148 have one level of template argument for the innermost
1149 class template. */
1150 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1151 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1152 CLASSTYPE_TI_ARGS (type)
1153 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1156 else if (processing_specialization)
1158 /* Someday C++0x may allow for enum template specialization. */
1159 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1160 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1161 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1162 "of %qD not allowed by ISO C++", type);
1163 else
1165 error ("explicit specialization of non-template %qT", type);
1166 return error_mark_node;
1170 return type;
1173 /* Returns nonzero if we can optimize the retrieval of specializations
1174 for TMPL, a TEMPLATE_DECL. In particular, for such a template, we
1175 do not use DECL_TEMPLATE_SPECIALIZATIONS at all. */
1177 static inline bool
1178 optimize_specialization_lookup_p (tree tmpl)
1180 return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1181 && DECL_CLASS_SCOPE_P (tmpl)
1182 /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1183 parameter. */
1184 && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1185 /* The optimized lookup depends on the fact that the
1186 template arguments for the member function template apply
1187 purely to the containing class, which is not true if the
1188 containing class is an explicit or partial
1189 specialization. */
1190 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1191 && !DECL_MEMBER_TEMPLATE_P (tmpl)
1192 && !DECL_CONV_FN_P (tmpl)
1193 /* It is possible to have a template that is not a member
1194 template and is not a member of a template class:
1196 template <typename T>
1197 struct S { friend A::f(); };
1199 Here, the friend function is a template, but the context does
1200 not have template information. The optimized lookup relies
1201 on having ARGS be the template arguments for both the class
1202 and the function template. */
1203 && !DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1206 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1207 gone through coerce_template_parms by now. */
1209 static void
1210 verify_unstripped_args_1 (tree inner)
1212 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1214 tree arg = TREE_VEC_ELT (inner, i);
1215 if (TREE_CODE (arg) == TEMPLATE_DECL)
1216 /* OK */;
1217 else if (TYPE_P (arg))
1218 gcc_assert (strip_typedefs (arg, NULL) == arg);
1219 else if (ARGUMENT_PACK_P (arg))
1220 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1221 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1222 /* Allow typedefs on the type of a non-type argument, since a
1223 parameter can have them. */;
1224 else
1225 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1229 static void
1230 verify_unstripped_args (tree args)
1232 ++processing_template_decl;
1233 if (!any_dependent_template_arguments_p (args))
1234 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1235 --processing_template_decl;
1238 /* Retrieve the specialization (in the sense of [temp.spec] - a
1239 specialization is either an instantiation or an explicit
1240 specialization) of TMPL for the given template ARGS. If there is
1241 no such specialization, return NULL_TREE. The ARGS are a vector of
1242 arguments, or a vector of vectors of arguments, in the case of
1243 templates with more than one level of parameters.
1245 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1246 then we search for a partial specialization matching ARGS. This
1247 parameter is ignored if TMPL is not a class template.
1249 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1250 result is a NONTYPE_ARGUMENT_PACK. */
1252 static tree
1253 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1255 if (tmpl == NULL_TREE)
1256 return NULL_TREE;
1258 if (args == error_mark_node)
1259 return NULL_TREE;
1261 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1262 || TREE_CODE (tmpl) == FIELD_DECL);
1264 /* There should be as many levels of arguments as there are
1265 levels of parameters. */
1266 gcc_assert (TMPL_ARGS_DEPTH (args)
1267 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1268 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1269 : template_class_depth (DECL_CONTEXT (tmpl))));
1271 if (flag_checking)
1272 verify_unstripped_args (args);
1274 /* Lambda functions in templates aren't instantiated normally, but through
1275 tsubst_lambda_expr. */
1276 if (lambda_fn_in_template_p (tmpl))
1277 return NULL_TREE;
1279 if (optimize_specialization_lookup_p (tmpl))
1281 /* The template arguments actually apply to the containing
1282 class. Find the class specialization with those
1283 arguments. */
1284 tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1285 tree class_specialization
1286 = retrieve_specialization (class_template, args, 0);
1287 if (!class_specialization)
1288 return NULL_TREE;
1290 /* Find the instance of TMPL. */
1291 tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1292 for (ovl_iterator iter (fns); iter; ++iter)
1294 tree fn = *iter;
1295 if (tree ti = get_template_info (fn))
1296 if (TI_TEMPLATE (ti) == tmpl
1297 /* using-declarations can bring in a different
1298 instantiation of tmpl as a member of a different
1299 instantiation of tmpl's class. We don't want those
1300 here. */
1301 && DECL_CONTEXT (fn) == class_specialization)
1302 return fn;
1304 return NULL_TREE;
1306 else
1308 spec_entry *found;
1309 spec_entry elt;
1310 spec_hash_table *specializations;
1312 elt.tmpl = tmpl;
1313 elt.args = args;
1314 elt.spec = NULL_TREE;
1316 if (DECL_CLASS_TEMPLATE_P (tmpl))
1317 specializations = type_specializations;
1318 else
1319 specializations = decl_specializations;
1321 if (hash == 0)
1322 hash = spec_hasher::hash (&elt);
1323 found = specializations->find_with_hash (&elt, hash);
1324 if (found)
1325 return found->spec;
1328 return NULL_TREE;
1331 /* Like retrieve_specialization, but for local declarations. */
1333 tree
1334 retrieve_local_specialization (tree tmpl)
1336 if (local_specializations == NULL)
1337 return NULL_TREE;
1339 tree *slot = local_specializations->get (tmpl);
1340 return slot ? *slot : NULL_TREE;
1343 /* Returns nonzero iff DECL is a specialization of TMPL. */
1346 is_specialization_of (tree decl, tree tmpl)
1348 tree t;
1350 if (TREE_CODE (decl) == FUNCTION_DECL)
1352 for (t = decl;
1353 t != NULL_TREE;
1354 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1355 if (t == tmpl)
1356 return 1;
1358 else
1360 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1362 for (t = TREE_TYPE (decl);
1363 t != NULL_TREE;
1364 t = CLASSTYPE_USE_TEMPLATE (t)
1365 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1366 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1367 return 1;
1370 return 0;
1373 /* Returns nonzero iff DECL is a specialization of friend declaration
1374 FRIEND_DECL according to [temp.friend]. */
1376 bool
1377 is_specialization_of_friend (tree decl, tree friend_decl)
1379 bool need_template = true;
1380 int template_depth;
1382 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1383 || TREE_CODE (decl) == TYPE_DECL);
1385 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1386 of a template class, we want to check if DECL is a specialization
1387 if this. */
1388 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1389 && DECL_TEMPLATE_INFO (friend_decl)
1390 && !DECL_USE_TEMPLATE (friend_decl))
1392 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1393 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1394 need_template = false;
1396 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1397 && !PRIMARY_TEMPLATE_P (friend_decl))
1398 need_template = false;
1400 /* There is nothing to do if this is not a template friend. */
1401 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1402 return false;
1404 if (is_specialization_of (decl, friend_decl))
1405 return true;
1407 /* [temp.friend/6]
1408 A member of a class template may be declared to be a friend of a
1409 non-template class. In this case, the corresponding member of
1410 every specialization of the class template is a friend of the
1411 class granting friendship.
1413 For example, given a template friend declaration
1415 template <class T> friend void A<T>::f();
1417 the member function below is considered a friend
1419 template <> struct A<int> {
1420 void f();
1423 For this type of template friend, TEMPLATE_DEPTH below will be
1424 nonzero. To determine if DECL is a friend of FRIEND, we first
1425 check if the enclosing class is a specialization of another. */
1427 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1428 if (template_depth
1429 && DECL_CLASS_SCOPE_P (decl)
1430 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1431 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1433 /* Next, we check the members themselves. In order to handle
1434 a few tricky cases, such as when FRIEND_DECL's are
1436 template <class T> friend void A<T>::g(T t);
1437 template <class T> template <T t> friend void A<T>::h();
1439 and DECL's are
1441 void A<int>::g(int);
1442 template <int> void A<int>::h();
1444 we need to figure out ARGS, the template arguments from
1445 the context of DECL. This is required for template substitution
1446 of `T' in the function parameter of `g' and template parameter
1447 of `h' in the above examples. Here ARGS corresponds to `int'. */
1449 tree context = DECL_CONTEXT (decl);
1450 tree args = NULL_TREE;
1451 int current_depth = 0;
1453 while (current_depth < template_depth)
1455 if (CLASSTYPE_TEMPLATE_INFO (context))
1457 if (current_depth == 0)
1458 args = TYPE_TI_ARGS (context);
1459 else
1460 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1461 current_depth++;
1463 context = TYPE_CONTEXT (context);
1466 if (TREE_CODE (decl) == FUNCTION_DECL)
1468 bool is_template;
1469 tree friend_type;
1470 tree decl_type;
1471 tree friend_args_type;
1472 tree decl_args_type;
1474 /* Make sure that both DECL and FRIEND_DECL are templates or
1475 non-templates. */
1476 is_template = DECL_TEMPLATE_INFO (decl)
1477 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1478 if (need_template ^ is_template)
1479 return false;
1480 else if (is_template)
1482 /* If both are templates, check template parameter list. */
1483 tree friend_parms
1484 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1485 args, tf_none);
1486 if (!comp_template_parms
1487 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1488 friend_parms))
1489 return false;
1491 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1493 else
1494 decl_type = TREE_TYPE (decl);
1496 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1497 tf_none, NULL_TREE);
1498 if (friend_type == error_mark_node)
1499 return false;
1501 /* Check if return types match. */
1502 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1503 return false;
1505 /* Check if function parameter types match, ignoring the
1506 `this' parameter. */
1507 friend_args_type = TYPE_ARG_TYPES (friend_type);
1508 decl_args_type = TYPE_ARG_TYPES (decl_type);
1509 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1510 friend_args_type = TREE_CHAIN (friend_args_type);
1511 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1512 decl_args_type = TREE_CHAIN (decl_args_type);
1514 return compparms (decl_args_type, friend_args_type);
1516 else
1518 /* DECL is a TYPE_DECL */
1519 bool is_template;
1520 tree decl_type = TREE_TYPE (decl);
1522 /* Make sure that both DECL and FRIEND_DECL are templates or
1523 non-templates. */
1524 is_template
1525 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1526 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1528 if (need_template ^ is_template)
1529 return false;
1530 else if (is_template)
1532 tree friend_parms;
1533 /* If both are templates, check the name of the two
1534 TEMPLATE_DECL's first because is_friend didn't. */
1535 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1536 != DECL_NAME (friend_decl))
1537 return false;
1539 /* Now check template parameter list. */
1540 friend_parms
1541 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1542 args, tf_none);
1543 return comp_template_parms
1544 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1545 friend_parms);
1547 else
1548 return (DECL_NAME (decl)
1549 == DECL_NAME (friend_decl));
1552 return false;
1555 /* Register the specialization SPEC as a specialization of TMPL with
1556 the indicated ARGS. IS_FRIEND indicates whether the specialization
1557 is actually just a friend declaration. ATTRLIST is the list of
1558 attributes that the specialization is declared with or NULL when
1559 it isn't. Returns SPEC, or an equivalent prior declaration, if
1560 available.
1562 We also store instantiations of field packs in the hash table, even
1563 though they are not themselves templates, to make lookup easier. */
1565 static tree
1566 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1567 hashval_t hash)
1569 tree fn;
1570 spec_entry **slot = NULL;
1571 spec_entry elt;
1573 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1574 || (TREE_CODE (tmpl) == FIELD_DECL
1575 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1577 if (TREE_CODE (spec) == FUNCTION_DECL
1578 && uses_template_parms (DECL_TI_ARGS (spec)))
1579 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1580 register it; we want the corresponding TEMPLATE_DECL instead.
1581 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1582 the more obvious `uses_template_parms (spec)' to avoid problems
1583 with default function arguments. In particular, given
1584 something like this:
1586 template <class T> void f(T t1, T t = T())
1588 the default argument expression is not substituted for in an
1589 instantiation unless and until it is actually needed. */
1590 return spec;
1592 if (optimize_specialization_lookup_p (tmpl))
1593 /* We don't put these specializations in the hash table, but we might
1594 want to give an error about a mismatch. */
1595 fn = retrieve_specialization (tmpl, args, 0);
1596 else
1598 elt.tmpl = tmpl;
1599 elt.args = args;
1600 elt.spec = spec;
1602 if (hash == 0)
1603 hash = spec_hasher::hash (&elt);
1605 slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1606 if (*slot)
1607 fn = (*slot)->spec;
1608 else
1609 fn = NULL_TREE;
1612 /* We can sometimes try to re-register a specialization that we've
1613 already got. In particular, regenerate_decl_from_template calls
1614 duplicate_decls which will update the specialization list. But,
1615 we'll still get called again here anyhow. It's more convenient
1616 to simply allow this than to try to prevent it. */
1617 if (fn == spec)
1618 return spec;
1619 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1621 if (DECL_TEMPLATE_INSTANTIATION (fn))
1623 if (DECL_ODR_USED (fn)
1624 || DECL_EXPLICIT_INSTANTIATION (fn))
1626 error ("specialization of %qD after instantiation",
1627 fn);
1628 return error_mark_node;
1630 else
1632 tree clone;
1633 /* This situation should occur only if the first
1634 specialization is an implicit instantiation, the
1635 second is an explicit specialization, and the
1636 implicit instantiation has not yet been used. That
1637 situation can occur if we have implicitly
1638 instantiated a member function and then specialized
1639 it later.
1641 We can also wind up here if a friend declaration that
1642 looked like an instantiation turns out to be a
1643 specialization:
1645 template <class T> void foo(T);
1646 class S { friend void foo<>(int) };
1647 template <> void foo(int);
1649 We transform the existing DECL in place so that any
1650 pointers to it become pointers to the updated
1651 declaration.
1653 If there was a definition for the template, but not
1654 for the specialization, we want this to look as if
1655 there were no definition, and vice versa. */
1656 DECL_INITIAL (fn) = NULL_TREE;
1657 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1658 /* The call to duplicate_decls will have applied
1659 [temp.expl.spec]:
1661 An explicit specialization of a function template
1662 is inline only if it is explicitly declared to be,
1663 and independently of whether its function template
1666 to the primary function; now copy the inline bits to
1667 the various clones. */
1668 FOR_EACH_CLONE (clone, fn)
1670 DECL_DECLARED_INLINE_P (clone)
1671 = DECL_DECLARED_INLINE_P (fn);
1672 DECL_SOURCE_LOCATION (clone)
1673 = DECL_SOURCE_LOCATION (fn);
1674 DECL_DELETED_FN (clone)
1675 = DECL_DELETED_FN (fn);
1677 check_specialization_namespace (tmpl);
1679 return fn;
1682 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1684 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1685 if (dd == error_mark_node)
1686 /* We've already complained in duplicate_decls. */
1687 return error_mark_node;
1689 if (dd == NULL_TREE && DECL_INITIAL (spec))
1690 /* Dup decl failed, but this is a new definition. Set the
1691 line number so any errors match this new
1692 definition. */
1693 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1695 return fn;
1698 else if (fn)
1699 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1701 /* A specialization must be declared in the same namespace as the
1702 template it is specializing. */
1703 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1704 && !check_specialization_namespace (tmpl))
1705 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1707 if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1709 spec_entry *entry = ggc_alloc<spec_entry> ();
1710 gcc_assert (tmpl && args && spec);
1711 *entry = elt;
1712 *slot = entry;
1713 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1714 && PRIMARY_TEMPLATE_P (tmpl)
1715 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1716 || variable_template_p (tmpl))
1717 /* If TMPL is a forward declaration of a template function, keep a list
1718 of all specializations in case we need to reassign them to a friend
1719 template later in tsubst_friend_function.
1721 Also keep a list of all variable template instantiations so that
1722 process_partial_specialization can check whether a later partial
1723 specialization would have used it. */
1724 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1725 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1728 return spec;
1731 /* Restricts tree and type comparisons. */
1732 int comparing_specializations;
1733 int comparing_dependent_aliases;
1735 /* Returns true iff two spec_entry nodes are equivalent. */
1737 bool
1738 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1740 int equal;
1742 ++comparing_specializations;
1743 ++comparing_dependent_aliases;
1744 ++processing_template_decl;
1745 equal = (e1->tmpl == e2->tmpl
1746 && comp_template_args (e1->args, e2->args));
1747 if (equal && flag_concepts
1748 /* tmpl could be a FIELD_DECL for a capture pack. */
1749 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1750 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1751 && uses_template_parms (e1->args))
1753 /* Partial specializations of a variable template can be distinguished by
1754 constraints. */
1755 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1756 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1757 equal = equivalent_constraints (c1, c2);
1759 --processing_template_decl;
1760 --comparing_dependent_aliases;
1761 --comparing_specializations;
1763 return equal;
1766 /* Returns a hash for a template TMPL and template arguments ARGS. */
1768 static hashval_t
1769 hash_tmpl_and_args (tree tmpl, tree args)
1771 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1772 return iterative_hash_template_arg (args, val);
1775 hashval_t
1776 spec_hasher::hash (tree tmpl, tree args)
1778 ++comparing_specializations;
1779 hashval_t val = hash_tmpl_and_args (tmpl, args);
1780 --comparing_specializations;
1781 return val;
1784 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1785 ignoring SPEC. */
1787 hashval_t
1788 spec_hasher::hash (spec_entry *e)
1790 return spec_hasher::hash (e->tmpl, e->args);
1793 /* Recursively calculate a hash value for a template argument ARG, for use
1794 in the hash tables of template specializations. We must be
1795 careful to (at least) skip the same entities template_args_equal
1796 does. */
1798 hashval_t
1799 iterative_hash_template_arg (tree arg, hashval_t val)
1801 if (arg == NULL_TREE)
1802 return iterative_hash_object (arg, val);
1804 if (!TYPE_P (arg))
1805 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1806 while (CONVERT_EXPR_P (arg)
1807 || TREE_CODE (arg) == NON_LVALUE_EXPR
1808 || class_nttp_const_wrapper_p (arg))
1809 arg = TREE_OPERAND (arg, 0);
1811 enum tree_code code = TREE_CODE (arg);
1813 val = iterative_hash_object (code, val);
1815 switch (code)
1817 case ARGUMENT_PACK_SELECT:
1818 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1819 preserving it in a hash table, which is bad because it will change
1820 meaning when gen_elem_of_pack_expansion_instantiation changes the
1821 ARGUMENT_PACK_SELECT_INDEX. */
1822 gcc_unreachable ();
1824 case ERROR_MARK:
1825 return val;
1827 case IDENTIFIER_NODE:
1828 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1830 case TREE_VEC:
1831 for (tree elt : tree_vec_range (arg))
1832 val = iterative_hash_template_arg (elt, val);
1833 return val;
1835 case TYPE_PACK_EXPANSION:
1836 case EXPR_PACK_EXPANSION:
1837 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1838 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1840 case TYPE_ARGUMENT_PACK:
1841 case NONTYPE_ARGUMENT_PACK:
1842 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1844 case TREE_LIST:
1845 for (; arg; arg = TREE_CHAIN (arg))
1846 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1847 return val;
1849 case OVERLOAD:
1850 for (lkp_iterator iter (arg); iter; ++iter)
1851 val = iterative_hash_template_arg (*iter, val);
1852 return val;
1854 case CONSTRUCTOR:
1856 iterative_hash_template_arg (TREE_TYPE (arg), val);
1857 for (auto &e: CONSTRUCTOR_ELTS (arg))
1859 val = iterative_hash_template_arg (e.index, val);
1860 val = iterative_hash_template_arg (e.value, val);
1862 return val;
1865 case PARM_DECL:
1866 if (!DECL_ARTIFICIAL (arg))
1868 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1869 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1871 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1873 case TARGET_EXPR:
1874 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1876 case PTRMEM_CST:
1877 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1878 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1880 case TEMPLATE_PARM_INDEX:
1881 val = iterative_hash_template_arg
1882 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1883 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1884 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1886 case TRAIT_EXPR:
1887 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1888 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1889 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1891 case BASELINK:
1892 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1893 val);
1894 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1895 val);
1897 case MODOP_EXPR:
1898 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1899 code = TREE_CODE (TREE_OPERAND (arg, 1));
1900 val = iterative_hash_object (code, val);
1901 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1903 case LAMBDA_EXPR:
1904 /* [temp.over.link] Two lambda-expressions are never considered
1905 equivalent.
1907 So just hash the closure type. */
1908 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1910 case CAST_EXPR:
1911 case IMPLICIT_CONV_EXPR:
1912 case STATIC_CAST_EXPR:
1913 case REINTERPRET_CAST_EXPR:
1914 case CONST_CAST_EXPR:
1915 case DYNAMIC_CAST_EXPR:
1916 case NEW_EXPR:
1917 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1918 /* Now hash operands as usual. */
1919 break;
1921 case CALL_EXPR:
1923 tree fn = CALL_EXPR_FN (arg);
1924 if (tree name = dependent_name (fn))
1926 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1927 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1928 fn = name;
1930 val = iterative_hash_template_arg (fn, val);
1931 call_expr_arg_iterator ai;
1932 for (tree x = first_call_expr_arg (arg, &ai); x;
1933 x = next_call_expr_arg (&ai))
1934 val = iterative_hash_template_arg (x, val);
1935 return val;
1938 default:
1939 break;
1942 char tclass = TREE_CODE_CLASS (code);
1943 switch (tclass)
1945 case tcc_type:
1946 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1948 // We want an alias specialization that survived strip_typedefs
1949 // to hash differently from its TYPE_CANONICAL, to avoid hash
1950 // collisions that compare as different in template_args_equal.
1951 // These could be dependent specializations that strip_typedefs
1952 // left alone, or untouched specializations because
1953 // coerce_template_parms returns the unconverted template
1954 // arguments if it sees incomplete argument packs.
1955 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1956 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1959 switch (TREE_CODE (arg))
1961 case TEMPLATE_TEMPLATE_PARM:
1963 tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1965 /* Do not recurse with TPI directly, as that is unbounded
1966 recursion. */
1967 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1968 val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1970 break;
1972 case DECLTYPE_TYPE:
1973 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1974 break;
1976 case TYPENAME_TYPE:
1977 if (comparing_specializations)
1979 /* Hash the components that are relevant to TYPENAME_TYPE
1980 equivalence as determined by structural_comptypes. We
1981 can only coherently do this when comparing_specializations
1982 is set, because otherwise structural_comptypes tries
1983 resolving TYPENAME_TYPE via the current instantiation. */
1984 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1985 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1986 val = iterative_hash_template_arg (context, val);
1987 val = iterative_hash_template_arg (fullname, val);
1989 break;
1991 default:
1992 if (tree canonical = TYPE_CANONICAL (arg))
1993 val = iterative_hash_object (TYPE_HASH (canonical), val);
1994 break;
1997 return val;
1999 case tcc_declaration:
2000 case tcc_constant:
2001 return iterative_hash_expr (arg, val);
2003 default:
2004 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
2005 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
2006 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
2007 return val;
2011 /* Unregister the specialization SPEC as a specialization of TMPL.
2012 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
2013 if the SPEC was listed as a specialization of TMPL.
2015 Note that SPEC has been ggc_freed, so we can't look inside it. */
2017 bool
2018 reregister_specialization (tree spec, tree tinfo, tree new_spec)
2020 spec_entry *entry;
2021 spec_entry elt;
2023 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
2024 elt.args = TI_ARGS (tinfo);
2025 elt.spec = NULL_TREE;
2027 entry = decl_specializations->find (&elt);
2028 if (entry != NULL)
2030 gcc_assert (entry->spec == spec || entry->spec == new_spec);
2031 gcc_assert (new_spec != NULL_TREE);
2032 entry->spec = new_spec;
2033 return 1;
2036 return 0;
2039 /* Like register_specialization, but for local declarations. We are
2040 registering SPEC, an instantiation of TMPL. */
2042 void
2043 register_local_specialization (tree spec, tree tmpl)
2045 gcc_assert (tmpl != spec);
2046 local_specializations->put (tmpl, spec);
2049 /* TYPE is a class type. Returns true if TYPE is an explicitly
2050 specialized class. */
2052 bool
2053 explicit_class_specialization_p (tree type)
2055 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2056 return false;
2057 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2060 /* Print the list of functions at FNS, going through all the overloads
2061 for each element of the list. Alternatively, FNS cannot be a
2062 TREE_LIST, in which case it will be printed together with all the
2063 overloads.
2065 MORE and *STR should respectively be FALSE and NULL when the function
2066 is called from the outside. They are used internally on recursive
2067 calls. print_candidates manages the two parameters and leaves NULL
2068 in *STR when it ends. */
2070 static void
2071 print_candidates_1 (tree fns, char **str, bool more = false)
2073 if (TREE_CODE (fns) == TREE_LIST)
2074 for (; fns; fns = TREE_CHAIN (fns))
2075 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2076 else
2077 for (lkp_iterator iter (fns); iter;)
2079 tree cand = *iter;
2080 ++iter;
2082 const char *pfx = *str;
2083 if (!pfx)
2085 if (more || iter)
2086 pfx = _("candidates are:");
2087 else
2088 pfx = _("candidate is:");
2089 *str = get_spaces (pfx);
2091 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2095 /* Print the list of candidate FNS in an error message. FNS can also
2096 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2098 void
2099 print_candidates (tree fns)
2101 char *str = NULL;
2102 print_candidates_1 (fns, &str);
2103 free (str);
2106 /* Get a (possibly) constrained template declaration for the
2107 purpose of ordering candidates. */
2108 static tree
2109 get_template_for_ordering (tree list)
2111 gcc_assert (TREE_CODE (list) == TREE_LIST);
2112 tree f = TREE_VALUE (list);
2113 if (tree ti = DECL_TEMPLATE_INFO (f))
2114 return TI_TEMPLATE (ti);
2115 return f;
2118 /* Among candidates having the same signature, return the
2119 most constrained or NULL_TREE if there is no best candidate.
2120 If the signatures of candidates vary (e.g., template
2121 specialization vs. member function), then there can be no
2122 most constrained.
2124 Note that we don't compare constraints on the functions
2125 themselves, but rather those of their templates. */
2126 static tree
2127 most_constrained_function (tree candidates)
2129 // Try to find the best candidate in a first pass.
2130 tree champ = candidates;
2131 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2133 int winner = more_constrained (get_template_for_ordering (champ),
2134 get_template_for_ordering (c));
2135 if (winner == -1)
2136 champ = c; // The candidate is more constrained
2137 else if (winner == 0)
2138 return NULL_TREE; // Neither is more constrained
2141 // Verify that the champ is better than previous candidates.
2142 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2143 if (!more_constrained (get_template_for_ordering (champ),
2144 get_template_for_ordering (c)))
2145 return NULL_TREE;
2148 return champ;
2152 /* Returns the template (one of the functions given by TEMPLATE_ID)
2153 which can be specialized to match the indicated DECL with the
2154 explicit template args given in TEMPLATE_ID. The DECL may be
2155 NULL_TREE if none is available. In that case, the functions in
2156 TEMPLATE_ID are non-members.
2158 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2159 specialization of a member template.
2161 The TEMPLATE_COUNT is the number of references to qualifying
2162 template classes that appeared in the name of the function. See
2163 check_explicit_specialization for a more accurate description.
2165 TSK indicates what kind of template declaration (if any) is being
2166 declared. TSK_TEMPLATE indicates that the declaration given by
2167 DECL, though a FUNCTION_DECL, has template parameters, and is
2168 therefore a template function.
2170 The template args (those explicitly specified and those deduced)
2171 are output in a newly created vector *TARGS_OUT.
2173 If it is impossible to determine the result, an error message is
2174 issued. The error_mark_node is returned to indicate failure. */
2176 static tree
2177 determine_specialization (tree template_id,
2178 tree decl,
2179 tree* targs_out,
2180 int need_member_template,
2181 int template_count,
2182 tmpl_spec_kind tsk)
2184 tree fns;
2185 tree targs;
2186 tree explicit_targs;
2187 tree candidates = NULL_TREE;
2189 /* A TREE_LIST of templates of which DECL may be a specialization.
2190 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2191 corresponding TREE_PURPOSE is the set of template arguments that,
2192 when used to instantiate the template, would produce a function
2193 with the signature of DECL. */
2194 tree templates = NULL_TREE;
2195 int header_count;
2196 cp_binding_level *b;
2198 *targs_out = NULL_TREE;
2200 if (template_id == error_mark_node || decl == error_mark_node)
2201 return error_mark_node;
2203 /* We shouldn't be specializing a member template of an
2204 unspecialized class template; we already gave an error in
2205 check_specialization_scope, now avoid crashing. */
2206 if (!VAR_P (decl)
2207 && template_count && DECL_CLASS_SCOPE_P (decl)
2208 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2210 gcc_assert (errorcount);
2211 return error_mark_node;
2214 fns = TREE_OPERAND (template_id, 0);
2215 explicit_targs = TREE_OPERAND (template_id, 1);
2217 if (fns == error_mark_node)
2218 return error_mark_node;
2220 /* Check for baselinks. */
2221 if (BASELINK_P (fns))
2222 fns = BASELINK_FUNCTIONS (fns);
2224 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2226 error_at (DECL_SOURCE_LOCATION (decl),
2227 "%qD is not a function template", fns);
2228 return error_mark_node;
2230 else if (VAR_P (decl) && !variable_template_p (fns))
2232 error ("%qD is not a variable template", fns);
2233 return error_mark_node;
2236 /* Count the number of template headers specified for this
2237 specialization. */
2238 header_count = 0;
2239 for (b = current_binding_level;
2240 b->kind == sk_template_parms;
2241 b = b->level_chain)
2242 ++header_count;
2244 tree orig_fns = fns;
2245 bool header_mismatch = false;
2247 if (variable_template_p (fns))
2249 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2250 targs = coerce_template_parms (parms, explicit_targs, fns,
2251 tf_warning_or_error,
2252 /*req_all*/true, /*use_defarg*/true);
2253 if (targs != error_mark_node
2254 && constraints_satisfied_p (fns, targs))
2255 templates = tree_cons (targs, fns, templates);
2257 else for (lkp_iterator iter (fns); iter; ++iter)
2259 tree fn = *iter;
2261 if (TREE_CODE (fn) == TEMPLATE_DECL)
2263 tree decl_arg_types;
2264 tree fn_arg_types;
2266 /* In case of explicit specialization, we need to check if
2267 the number of template headers appearing in the specialization
2268 is correct. This is usually done in check_explicit_specialization,
2269 but the check done there cannot be exhaustive when specializing
2270 member functions. Consider the following code:
2272 template <> void A<int>::f(int);
2273 template <> template <> void A<int>::f(int);
2275 Assuming that A<int> is not itself an explicit specialization
2276 already, the first line specializes "f" which is a non-template
2277 member function, whilst the second line specializes "f" which
2278 is a template member function. So both lines are syntactically
2279 correct, and check_explicit_specialization does not reject
2280 them.
2282 Here, we can do better, as we are matching the specialization
2283 against the declarations. We count the number of template
2284 headers, and we check if they match TEMPLATE_COUNT + 1
2285 (TEMPLATE_COUNT is the number of qualifying template classes,
2286 plus there must be another header for the member template
2287 itself).
2289 Notice that if header_count is zero, this is not a
2290 specialization but rather a template instantiation, so there
2291 is no check we can perform here. */
2292 if (header_count && header_count != template_count + 1)
2294 header_mismatch = true;
2295 continue;
2298 /* Check that the number of template arguments at the
2299 innermost level for DECL is the same as for FN. */
2300 if (current_binding_level->kind == sk_template_parms
2301 && !current_binding_level->explicit_spec_p
2302 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2303 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2304 (current_template_parms))))
2305 continue;
2307 /* DECL might be a specialization of FN. */
2308 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2309 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2311 /* For a non-static member function, we need to make sure
2312 that the const qualification is the same. Since
2313 get_bindings does not try to merge the "this" parameter,
2314 we must do the comparison explicitly. */
2315 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2317 if (!same_type_p (TREE_VALUE (fn_arg_types),
2318 TREE_VALUE (decl_arg_types)))
2319 continue;
2321 /* And the ref-qualification. */
2322 if (type_memfn_rqual (TREE_TYPE (decl))
2323 != type_memfn_rqual (TREE_TYPE (fn)))
2324 continue;
2327 /* Skip the "this" parameter and, for constructors of
2328 classes with virtual bases, the VTT parameter. A
2329 full specialization of a constructor will have a VTT
2330 parameter, but a template never will. */
2331 decl_arg_types
2332 = skip_artificial_parms_for (decl, decl_arg_types);
2333 fn_arg_types
2334 = skip_artificial_parms_for (fn, fn_arg_types);
2336 /* Function templates cannot be specializations; there are
2337 no partial specializations of functions. Therefore, if
2338 the type of DECL does not match FN, there is no
2339 match.
2341 Note that it should never be the case that we have both
2342 candidates added here, and for regular member functions
2343 below. */
2344 if (tsk == tsk_template)
2346 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2347 current_template_parms))
2348 continue;
2349 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2350 TREE_TYPE (TREE_TYPE (fn))))
2351 continue;
2352 if (!compparms (fn_arg_types, decl_arg_types))
2353 continue;
2355 tree freq = get_constraints (fn);
2356 tree dreq = get_constraints (decl);
2357 if (!freq != !dreq)
2358 continue;
2359 if (freq)
2361 /* C++20 CA104: Substitute directly into the
2362 constraint-expression. */
2363 tree fargs = DECL_TI_ARGS (fn);
2364 tsubst_flags_t complain = tf_none;
2365 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2366 if (!cp_tree_equal (freq, dreq))
2367 continue;
2370 candidates = tree_cons (NULL_TREE, fn, candidates);
2371 continue;
2374 /* See whether this function might be a specialization of this
2375 template. Suppress access control because we might be trying
2376 to make this specialization a friend, and we have already done
2377 access control for the declaration of the specialization. */
2378 push_deferring_access_checks (dk_no_check);
2379 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2380 pop_deferring_access_checks ();
2382 if (!targs)
2383 /* We cannot deduce template arguments that when used to
2384 specialize TMPL will produce DECL. */
2385 continue;
2387 if (uses_template_parms (targs))
2388 /* We deduced something involving 'auto', which isn't a valid
2389 template argument. */
2390 continue;
2392 /* Save this template, and the arguments deduced. */
2393 templates = tree_cons (targs, fn, templates);
2395 else if (need_member_template)
2396 /* FN is an ordinary member function, and we need a
2397 specialization of a member template. */
2399 else if (TREE_CODE (fn) != FUNCTION_DECL)
2400 /* We can get IDENTIFIER_NODEs here in certain erroneous
2401 cases. */
2403 else if (!DECL_FUNCTION_MEMBER_P (fn))
2404 /* This is just an ordinary non-member function. Nothing can
2405 be a specialization of that. */
2407 else if (DECL_ARTIFICIAL (fn))
2408 /* Cannot specialize functions that are created implicitly. */
2410 else
2412 tree decl_arg_types;
2414 /* This is an ordinary member function. However, since
2415 we're here, we can assume its enclosing class is a
2416 template class. For example,
2418 template <typename T> struct S { void f(); };
2419 template <> void S<int>::f() {}
2421 Here, S<int>::f is a non-template, but S<int> is a
2422 template class. If FN has the same type as DECL, we
2423 might be in business. */
2425 if (!DECL_TEMPLATE_INFO (fn))
2426 /* Its enclosing class is an explicit specialization
2427 of a template class. This is not a candidate. */
2428 continue;
2430 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2431 TREE_TYPE (TREE_TYPE (fn))))
2432 /* The return types differ. */
2433 continue;
2435 /* Adjust the type of DECL in case FN is a static member. */
2436 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2437 if (DECL_STATIC_FUNCTION_P (fn)
2438 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2439 decl_arg_types = TREE_CHAIN (decl_arg_types);
2441 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2442 decl_arg_types))
2443 continue;
2445 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2446 && (type_memfn_rqual (TREE_TYPE (decl))
2447 != type_memfn_rqual (TREE_TYPE (fn))))
2448 continue;
2450 // If the deduced arguments do not satisfy the constraints,
2451 // this is not a candidate.
2452 if (flag_concepts && !constraints_satisfied_p (fn))
2453 continue;
2455 // Add the candidate.
2456 candidates = tree_cons (NULL_TREE, fn, candidates);
2460 if (templates && TREE_CHAIN (templates))
2462 /* We have:
2464 [temp.expl.spec]
2466 It is possible for a specialization with a given function
2467 signature to be instantiated from more than one function
2468 template. In such cases, explicit specification of the
2469 template arguments must be used to uniquely identify the
2470 function template specialization being specialized.
2472 Note that here, there's no suggestion that we're supposed to
2473 determine which of the candidate templates is most
2474 specialized. However, we, also have:
2476 [temp.func.order]
2478 Partial ordering of overloaded function template
2479 declarations is used in the following contexts to select
2480 the function template to which a function template
2481 specialization refers:
2483 -- when an explicit specialization refers to a function
2484 template.
2486 So, we do use the partial ordering rules, at least for now.
2487 This extension can only serve to make invalid programs valid,
2488 so it's safe. And, there is strong anecdotal evidence that
2489 the committee intended the partial ordering rules to apply;
2490 the EDG front end has that behavior, and John Spicer claims
2491 that the committee simply forgot to delete the wording in
2492 [temp.expl.spec]. */
2493 tree tmpl = most_specialized_instantiation (templates);
2494 if (tmpl != error_mark_node)
2496 templates = tmpl;
2497 TREE_CHAIN (templates) = NULL_TREE;
2501 // Concepts allows multiple declarations of member functions
2502 // with the same signature. Like above, we need to rely on
2503 // on the partial ordering of those candidates to determine which
2504 // is the best.
2505 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2507 if (tree cand = most_constrained_function (candidates))
2509 candidates = cand;
2510 TREE_CHAIN (cand) = NULL_TREE;
2514 if (templates == NULL_TREE && candidates == NULL_TREE)
2516 error ("template-id %qD for %q+D does not match any template "
2517 "declaration", template_id, decl);
2518 if (header_mismatch)
2519 inform (DECL_SOURCE_LOCATION (decl),
2520 "saw %d %<template<>%>, need %d for "
2521 "specializing a member function template",
2522 header_count, template_count + 1);
2523 print_candidates (orig_fns);
2524 return error_mark_node;
2526 else if ((templates && TREE_CHAIN (templates))
2527 || (candidates && TREE_CHAIN (candidates))
2528 || (templates && candidates))
2530 error ("ambiguous template specialization %qD for %q+D",
2531 template_id, decl);
2532 candidates = chainon (candidates, templates);
2533 print_candidates (candidates);
2534 return error_mark_node;
2537 /* We have one, and exactly one, match. */
2538 if (candidates)
2540 tree fn = TREE_VALUE (candidates);
2541 *targs_out = copy_node (DECL_TI_ARGS (fn));
2543 /* Propagate the candidate's constraints to the declaration. */
2544 if (tsk != tsk_template)
2545 set_constraints (decl, get_constraints (fn));
2547 /* DECL is a re-declaration or partial instantiation of a template
2548 function. */
2549 if (TREE_CODE (fn) == TEMPLATE_DECL)
2550 return fn;
2551 /* It was a specialization of an ordinary member function in a
2552 template class. */
2553 return DECL_TI_TEMPLATE (fn);
2556 /* It was a specialization of a template. */
2557 targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2558 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2560 *targs_out = copy_node (targs);
2561 SET_TMPL_ARGS_LEVEL (*targs_out,
2562 TMPL_ARGS_DEPTH (*targs_out),
2563 TREE_PURPOSE (templates));
2565 else
2566 *targs_out = TREE_PURPOSE (templates);
2567 return TREE_VALUE (templates);
2570 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2571 but with the default argument values filled in from those in the
2572 TMPL_TYPES. */
2574 static tree
2575 copy_default_args_to_explicit_spec_1 (tree spec_types,
2576 tree tmpl_types)
2578 tree new_spec_types;
2580 if (!spec_types)
2581 return NULL_TREE;
2583 if (spec_types == void_list_node)
2584 return void_list_node;
2586 /* Substitute into the rest of the list. */
2587 new_spec_types =
2588 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2589 TREE_CHAIN (tmpl_types));
2591 /* Add the default argument for this parameter. */
2592 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2593 TREE_VALUE (spec_types),
2594 new_spec_types);
2597 /* DECL is an explicit specialization. Replicate default arguments
2598 from the template it specializes. (That way, code like:
2600 template <class T> void f(T = 3);
2601 template <> void f(double);
2602 void g () { f (); }
2604 works, as required.) An alternative approach would be to look up
2605 the correct default arguments at the call-site, but this approach
2606 is consistent with how implicit instantiations are handled. */
2608 static void
2609 copy_default_args_to_explicit_spec (tree decl)
2611 tree tmpl;
2612 tree spec_types;
2613 tree tmpl_types;
2614 tree new_spec_types;
2615 tree old_type;
2616 tree new_type;
2617 tree t;
2618 tree object_type = NULL_TREE;
2619 tree in_charge = NULL_TREE;
2620 tree vtt = NULL_TREE;
2622 /* See if there's anything we need to do. */
2623 tmpl = DECL_TI_TEMPLATE (decl);
2624 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2625 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2626 if (TREE_PURPOSE (t))
2627 break;
2628 if (!t)
2629 return;
2631 old_type = TREE_TYPE (decl);
2632 spec_types = TYPE_ARG_TYPES (old_type);
2634 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2636 /* Remove the this pointer, but remember the object's type for
2637 CV quals. */
2638 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2639 spec_types = TREE_CHAIN (spec_types);
2640 tmpl_types = TREE_CHAIN (tmpl_types);
2642 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2644 /* DECL may contain more parameters than TMPL due to the extra
2645 in-charge parameter in constructors and destructors. */
2646 in_charge = spec_types;
2647 spec_types = TREE_CHAIN (spec_types);
2649 if (DECL_HAS_VTT_PARM_P (decl))
2651 vtt = spec_types;
2652 spec_types = TREE_CHAIN (spec_types);
2656 /* Compute the merged default arguments. */
2657 new_spec_types =
2658 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2660 /* Compute the new FUNCTION_TYPE. */
2661 if (object_type)
2663 if (vtt)
2664 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2665 TREE_VALUE (vtt),
2666 new_spec_types);
2668 if (in_charge)
2669 /* Put the in-charge parameter back. */
2670 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2671 TREE_VALUE (in_charge),
2672 new_spec_types);
2674 new_type = build_method_type_directly (object_type,
2675 TREE_TYPE (old_type),
2676 new_spec_types);
2678 else
2679 new_type = build_function_type (TREE_TYPE (old_type),
2680 new_spec_types);
2681 new_type = cp_build_type_attribute_variant (new_type,
2682 TYPE_ATTRIBUTES (old_type));
2683 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2685 TREE_TYPE (decl) = new_type;
2688 /* Return the number of template headers we expect to see for a definition
2689 or specialization of CTYPE or one of its non-template members. */
2692 num_template_headers_for_class (tree ctype)
2694 int num_templates = 0;
2696 while (ctype && CLASS_TYPE_P (ctype))
2698 /* You're supposed to have one `template <...>' for every
2699 template class, but you don't need one for a full
2700 specialization. For example:
2702 template <class T> struct S{};
2703 template <> struct S<int> { void f(); };
2704 void S<int>::f () {}
2706 is correct; there shouldn't be a `template <>' for the
2707 definition of `S<int>::f'. */
2708 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2709 /* If CTYPE does not have template information of any
2710 kind, then it is not a template, nor is it nested
2711 within a template. */
2712 break;
2713 if (explicit_class_specialization_p (ctype))
2714 break;
2715 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2716 ++num_templates;
2718 ctype = TYPE_CONTEXT (ctype);
2721 return num_templates;
2724 /* Do a simple sanity check on the template headers that precede the
2725 variable declaration DECL. */
2727 void
2728 check_template_variable (tree decl)
2730 tree ctx = CP_DECL_CONTEXT (decl);
2731 int wanted = num_template_headers_for_class (ctx);
2732 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2733 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2735 if (cxx_dialect < cxx14)
2736 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2737 "variable templates only available with "
2738 "%<-std=c++14%> or %<-std=gnu++14%>");
2740 // Namespace-scope variable templates should have a template header.
2741 ++wanted;
2743 if (template_header_count > wanted)
2745 auto_diagnostic_group d;
2746 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2747 "too many template headers for %qD "
2748 "(should be %d)",
2749 decl, wanted);
2750 if (warned && CLASS_TYPE_P (ctx)
2751 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2752 inform (DECL_SOURCE_LOCATION (decl),
2753 "members of an explicitly specialized class are defined "
2754 "without a template header");
2758 /* An explicit specialization whose declarator-id or class-head-name is not
2759 qualified shall be declared in the nearest enclosing namespace of the
2760 template, or, if the namespace is inline (7.3.1), any namespace from its
2761 enclosing namespace set.
2763 If the name declared in the explicit instantiation is an unqualified name,
2764 the explicit instantiation shall appear in the namespace where its template
2765 is declared or, if that namespace is inline (7.3.1), any namespace from its
2766 enclosing namespace set. */
2768 void
2769 check_unqualified_spec_or_inst (tree t, location_t loc)
2771 tree tmpl = most_general_template (t);
2772 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2773 && !is_nested_namespace (current_namespace,
2774 CP_DECL_CONTEXT (tmpl), true))
2776 if (processing_specialization)
2777 permerror (loc, "explicit specialization of %qD outside its "
2778 "namespace must use a nested-name-specifier", tmpl);
2779 else if (processing_explicit_instantiation
2780 && cxx_dialect >= cxx11)
2781 /* This was allowed in C++98, so only pedwarn. */
2782 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2783 "outside its namespace must use a nested-name-"
2784 "specifier", tmpl);
2788 /* Warn for a template specialization SPEC that is missing some of a set
2789 of function or type attributes that the template TEMPL is declared with.
2790 ATTRLIST is a list of additional attributes that SPEC should be taken
2791 to ultimately be declared with. */
2793 static void
2794 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2796 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2797 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2799 /* Avoid warning if the difference between the primary and
2800 the specialization is not in one of the attributes below. */
2801 const char* const blacklist[] = {
2802 "alloc_align", "alloc_size", "assume_aligned", "format",
2803 "format_arg", "malloc", "nonnull", NULL
2806 /* Put together a list of the black listed attributes that the primary
2807 template is declared with that the specialization is not, in case
2808 it's not apparent from the most recent declaration of the primary. */
2809 pretty_printer str;
2810 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2811 blacklist, &str);
2813 if (!nattrs)
2814 return;
2816 auto_diagnostic_group d;
2817 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2818 "explicit specialization %q#D may be missing attributes",
2819 spec))
2820 inform (DECL_SOURCE_LOCATION (tmpl),
2821 nattrs > 1
2822 ? G_("missing primary template attributes %s")
2823 : G_("missing primary template attribute %s"),
2824 pp_formatted_text (&str));
2827 /* Check to see if the function just declared, as indicated in
2828 DECLARATOR, and in DECL, is a specialization of a function
2829 template. We may also discover that the declaration is an explicit
2830 instantiation at this point.
2832 Returns DECL, or an equivalent declaration that should be used
2833 instead if all goes well. Issues an error message if something is
2834 amiss. Returns error_mark_node if the error is not easily
2835 recoverable.
2837 FLAGS is a bitmask consisting of the following flags:
2839 2: The function has a definition.
2840 4: The function is a friend.
2842 The TEMPLATE_COUNT is the number of references to qualifying
2843 template classes that appeared in the name of the function. For
2844 example, in
2846 template <class T> struct S { void f(); };
2847 void S<int>::f();
2849 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2850 classes are not counted in the TEMPLATE_COUNT, so that in
2852 template <class T> struct S {};
2853 template <> struct S<int> { void f(); }
2854 template <> void S<int>::f();
2856 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2857 invalid; there should be no template <>.)
2859 If the function is a specialization, it is marked as such via
2860 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2861 is set up correctly, and it is added to the list of specializations
2862 for that template. */
2864 tree
2865 check_explicit_specialization (tree declarator,
2866 tree decl,
2867 int template_count,
2868 int flags,
2869 tree attrlist)
2871 int have_def = flags & 2;
2872 int is_friend = flags & 4;
2873 bool is_concept = flags & 8;
2874 int specialization = 0;
2875 int explicit_instantiation = 0;
2876 int member_specialization = 0;
2877 tree ctype = DECL_CLASS_CONTEXT (decl);
2878 tree dname = DECL_NAME (decl);
2879 tmpl_spec_kind tsk;
2881 if (is_friend)
2883 if (!processing_specialization)
2884 tsk = tsk_none;
2885 else
2886 tsk = tsk_excessive_parms;
2888 else
2889 tsk = current_tmpl_spec_kind (template_count);
2891 switch (tsk)
2893 case tsk_none:
2894 if (processing_specialization && !VAR_P (decl))
2896 specialization = 1;
2897 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2899 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2900 || (DECL_LANG_SPECIFIC (decl)
2901 && DECL_IMPLICIT_INSTANTIATION (decl)))
2903 if (is_friend)
2904 /* This could be something like:
2906 template <class T> void f(T);
2907 class S { friend void f<>(int); } */
2908 specialization = 1;
2909 else
2911 /* This case handles bogus declarations like template <>
2912 template <class T> void f<int>(); */
2914 error_at (cp_expr_loc_or_input_loc (declarator),
2915 "template-id %qE in declaration of primary template",
2916 declarator);
2917 return decl;
2920 break;
2922 case tsk_invalid_member_spec:
2923 /* The error has already been reported in
2924 check_specialization_scope. */
2925 return error_mark_node;
2927 case tsk_invalid_expl_inst:
2928 error ("template parameter list used in explicit instantiation");
2930 /* Fall through. */
2932 case tsk_expl_inst:
2933 if (have_def)
2934 error ("definition provided for explicit instantiation");
2936 explicit_instantiation = 1;
2937 break;
2939 case tsk_excessive_parms:
2940 case tsk_insufficient_parms:
2941 if (tsk == tsk_excessive_parms)
2942 error ("too many template parameter lists in declaration of %qD",
2943 decl);
2944 else if (template_header_count)
2945 error("too few template parameter lists in declaration of %qD", decl);
2946 else
2947 error("explicit specialization of %qD must be introduced by "
2948 "%<template <>%>", decl);
2950 /* Fall through. */
2951 case tsk_expl_spec:
2952 if (is_concept)
2953 error ("explicit specialization declared %<concept%>");
2955 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2956 /* In cases like template<> constexpr bool v = true;
2957 We'll give an error in check_template_variable. */
2958 break;
2960 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2961 if (ctype)
2962 member_specialization = 1;
2963 else
2964 specialization = 1;
2965 break;
2967 case tsk_template:
2968 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2970 /* This case handles bogus declarations like template <>
2971 template <class T> void f<int>(); */
2973 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2974 error_at (cp_expr_loc_or_input_loc (declarator),
2975 "template-id %qE in declaration of primary template",
2976 declarator);
2977 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2979 /* Partial specialization of variable template. */
2980 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2981 specialization = 1;
2982 goto ok;
2984 else if (cxx_dialect < cxx14)
2985 error_at (cp_expr_loc_or_input_loc (declarator),
2986 "non-type partial specialization %qE "
2987 "is not allowed", declarator);
2988 else
2989 error_at (cp_expr_loc_or_input_loc (declarator),
2990 "non-class, non-variable partial specialization %qE "
2991 "is not allowed", declarator);
2992 return decl;
2993 ok:;
2996 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2997 /* This is a specialization of a member template, without
2998 specialization the containing class. Something like:
3000 template <class T> struct S {
3001 template <class U> void f (U);
3003 template <> template <class U> void S<int>::f(U) {}
3005 That's a specialization -- but of the entire template. */
3006 specialization = 1;
3007 break;
3009 default:
3010 gcc_unreachable ();
3013 if ((specialization || member_specialization)
3014 /* This doesn't apply to variable templates. */
3015 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
3017 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
3018 for (; t; t = TREE_CHAIN (t))
3019 if (TREE_PURPOSE (t))
3021 permerror (input_location,
3022 "default argument specified in explicit specialization");
3023 break;
3027 if (specialization || member_specialization || explicit_instantiation)
3029 tree tmpl = NULL_TREE;
3030 tree targs = NULL_TREE;
3031 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
3032 bool found_hidden = false;
3034 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
3035 if (!was_template_id)
3037 tree fns;
3039 gcc_assert (identifier_p (declarator));
3040 if (ctype)
3041 fns = dname;
3042 else
3044 /* If there is no class context, the explicit instantiation
3045 must be at namespace scope. */
3046 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3048 /* Find the namespace binding, using the declaration
3049 context. */
3050 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3051 LOOK_want::NORMAL, true);
3052 if (fns == error_mark_node)
3054 /* If lookup fails, look for a friend declaration so we can
3055 give a better diagnostic. */
3056 fns = (lookup_qualified_name
3057 (CP_DECL_CONTEXT (decl), dname,
3058 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3059 /*complain*/true));
3060 found_hidden = true;
3063 if (fns == error_mark_node || !is_overloaded_fn (fns))
3065 error ("%qD is not a template function", dname);
3066 fns = error_mark_node;
3070 declarator = lookup_template_function (fns, NULL_TREE);
3073 if (declarator == error_mark_node)
3074 return error_mark_node;
3076 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3078 if (!explicit_instantiation)
3079 /* A specialization in class scope. This is invalid,
3080 but the error will already have been flagged by
3081 check_specialization_scope. */
3082 return error_mark_node;
3083 else
3085 /* It's not valid to write an explicit instantiation in
3086 class scope, e.g.:
3088 class C { template void f(); }
3090 This case is caught by the parser. However, on
3091 something like:
3093 template class C { void f(); };
3095 (which is invalid) we can get here. The error will be
3096 issued later. */
3100 return decl;
3102 else if (ctype != NULL_TREE
3103 && (identifier_p (TREE_OPERAND (declarator, 0))))
3105 // We'll match variable templates in start_decl.
3106 if (VAR_P (decl))
3107 return decl;
3109 /* Find the list of functions in ctype that have the same
3110 name as the declared function. */
3111 tree name = TREE_OPERAND (declarator, 0);
3113 if (constructor_name_p (name, ctype))
3115 if (DECL_CONSTRUCTOR_P (decl)
3116 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3117 : !CLASSTYPE_DESTRUCTOR (ctype))
3119 /* From [temp.expl.spec]:
3121 If such an explicit specialization for the member
3122 of a class template names an implicitly-declared
3123 special member function (clause _special_), the
3124 program is ill-formed.
3126 Similar language is found in [temp.explicit]. */
3127 error ("specialization of implicitly-declared special member function");
3128 return error_mark_node;
3131 name = DECL_NAME (decl);
3134 /* For a type-conversion operator, We might be looking for
3135 `operator int' which will be a specialization of
3136 `operator T'. Grab all the conversion operators, and
3137 then select from them. */
3138 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3139 ? conv_op_identifier : name);
3141 if (fns == NULL_TREE)
3143 error ("no member function %qD declared in %qT", name, ctype);
3144 return error_mark_node;
3146 else
3147 TREE_OPERAND (declarator, 0) = fns;
3150 /* Figure out what exactly is being specialized at this point.
3151 Note that for an explicit instantiation, even one for a
3152 member function, we cannot tell a priori whether the
3153 instantiation is for a member template, or just a member
3154 function of a template class. Even if a member template is
3155 being instantiated, the member template arguments may be
3156 elided if they can be deduced from the rest of the
3157 declaration. */
3158 tmpl = determine_specialization (declarator, decl,
3159 &targs,
3160 member_specialization,
3161 template_count,
3162 tsk);
3164 if (!tmpl || tmpl == error_mark_node)
3165 /* We couldn't figure out what this declaration was
3166 specializing. */
3167 return error_mark_node;
3168 else
3170 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3172 auto_diagnostic_group d;
3173 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3174 "friend declaration %qD is not visible to "
3175 "explicit specialization", tmpl))
3176 inform (DECL_SOURCE_LOCATION (tmpl),
3177 "friend declaration here");
3180 if (!ctype && !is_friend
3181 && CP_DECL_CONTEXT (decl) == current_namespace)
3182 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3184 tree gen_tmpl = most_general_template (tmpl);
3186 if (explicit_instantiation)
3188 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3189 is done by do_decl_instantiation later. */
3191 int arg_depth = TMPL_ARGS_DEPTH (targs);
3192 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3194 if (arg_depth > parm_depth)
3196 /* If TMPL is not the most general template (for
3197 example, if TMPL is a friend template that is
3198 injected into namespace scope), then there will
3199 be too many levels of TARGS. Remove some of them
3200 here. */
3201 int i;
3202 tree new_targs;
3204 new_targs = make_tree_vec (parm_depth);
3205 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3206 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3207 = TREE_VEC_ELT (targs, i);
3208 targs = new_targs;
3211 return instantiate_template (tmpl, targs, tf_error);
3214 /* If we thought that the DECL was a member function, but it
3215 turns out to be specializing a static member function,
3216 make DECL a static member function as well. */
3217 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3218 && DECL_STATIC_FUNCTION_P (tmpl)
3219 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3220 revert_static_member_fn (decl);
3222 /* If this is a specialization of a member template of a
3223 template class, we want to return the TEMPLATE_DECL, not
3224 the specialization of it. */
3225 if (tsk == tsk_template && !was_template_id)
3227 tree result = DECL_TEMPLATE_RESULT (tmpl);
3228 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3229 DECL_INITIAL (result) = NULL_TREE;
3230 if (have_def)
3232 tree parm;
3233 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3234 DECL_SOURCE_LOCATION (result)
3235 = DECL_SOURCE_LOCATION (decl);
3236 /* We want to use the argument list specified in the
3237 definition, not in the original declaration. */
3238 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3239 for (parm = DECL_ARGUMENTS (result); parm;
3240 parm = DECL_CHAIN (parm))
3241 DECL_CONTEXT (parm) = result;
3243 return register_specialization (tmpl, gen_tmpl, targs,
3244 is_friend, 0);
3247 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3248 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3250 if (was_template_id)
3251 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3253 /* Inherit default function arguments from the template
3254 DECL is specializing. */
3255 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3256 copy_default_args_to_explicit_spec (decl);
3258 /* This specialization has the same protection as the
3259 template it specializes. */
3260 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3261 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3263 /* 7.1.1-1 [dcl.stc]
3265 A storage-class-specifier shall not be specified in an
3266 explicit specialization...
3268 The parser rejects these, so unless action is taken here,
3269 explicit function specializations will always appear with
3270 global linkage.
3272 The action recommended by the C++ CWG in response to C++
3273 defect report 605 is to make the storage class and linkage
3274 of the explicit specialization match the templated function:
3276 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3278 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3280 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3281 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3283 /* A concept cannot be specialized. */
3284 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3286 error ("explicit specialization of function concept %qD",
3287 gen_tmpl);
3288 return error_mark_node;
3291 /* This specialization has the same linkage and visibility as
3292 the function template it specializes. */
3293 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3294 if (! TREE_PUBLIC (decl))
3296 DECL_INTERFACE_KNOWN (decl) = 1;
3297 DECL_NOT_REALLY_EXTERN (decl) = 1;
3299 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3300 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3302 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3303 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3307 /* If DECL is a friend declaration, declared using an
3308 unqualified name, the namespace associated with DECL may
3309 have been set incorrectly. For example, in:
3311 template <typename T> void f(T);
3312 namespace N {
3313 struct S { friend void f<int>(int); }
3316 we will have set the DECL_CONTEXT for the friend
3317 declaration to N, rather than to the global namespace. */
3318 if (DECL_NAMESPACE_SCOPE_P (decl))
3319 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3321 if (is_friend && !have_def)
3322 /* This is not really a declaration of a specialization.
3323 It's just the name of an instantiation. But, it's not
3324 a request for an instantiation, either. */
3325 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3326 else if (TREE_CODE (decl) == FUNCTION_DECL)
3327 /* A specialization is not necessarily COMDAT. */
3328 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3329 && DECL_DECLARED_INLINE_P (decl));
3330 else if (VAR_P (decl))
3331 DECL_COMDAT (decl) = false;
3333 /* If this is a full specialization, register it so that we can find
3334 it again. Partial specializations will be registered in
3335 process_partial_specialization. */
3336 if (!processing_template_decl)
3338 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3340 decl = register_specialization (decl, gen_tmpl, targs,
3341 is_friend, 0);
3345 /* A 'structor should already have clones. */
3346 gcc_assert (decl == error_mark_node
3347 || variable_template_p (tmpl)
3348 || !(DECL_CONSTRUCTOR_P (decl)
3349 || DECL_DESTRUCTOR_P (decl))
3350 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3354 return decl;
3357 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3358 parameters. These are represented in the same format used for
3359 DECL_TEMPLATE_PARMS. */
3362 comp_template_parms (const_tree parms1, const_tree parms2)
3364 const_tree p1;
3365 const_tree p2;
3367 if (parms1 == parms2)
3368 return 1;
3370 for (p1 = parms1, p2 = parms2;
3371 p1 != NULL_TREE && p2 != NULL_TREE;
3372 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3374 tree t1 = TREE_VALUE (p1);
3375 tree t2 = TREE_VALUE (p2);
3376 int i;
3378 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3379 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3381 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3382 return 0;
3384 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3386 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3387 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3389 /* If either of the template parameters are invalid, assume
3390 they match for the sake of error recovery. */
3391 if (error_operand_p (parm1) || error_operand_p (parm2))
3392 return 1;
3394 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3395 return 0;
3397 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3398 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3399 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3400 continue;
3401 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3402 return 0;
3406 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3407 /* One set of parameters has more parameters lists than the
3408 other. */
3409 return 0;
3411 return 1;
3414 /* Returns true if two template parameters are declared with
3415 equivalent constraints. */
3417 static bool
3418 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3420 tree req1 = TREE_TYPE (parm1);
3421 tree req2 = TREE_TYPE (parm2);
3422 if (!req1 != !req2)
3423 return false;
3424 if (req1)
3425 return cp_tree_equal (req1, req2);
3426 return true;
3429 /* Returns true when two template parameters are equivalent. */
3431 static bool
3432 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3434 tree decl1 = TREE_VALUE (parm1);
3435 tree decl2 = TREE_VALUE (parm2);
3437 /* If either of the template parameters are invalid, assume
3438 they match for the sake of error recovery. */
3439 if (error_operand_p (decl1) || error_operand_p (decl2))
3440 return true;
3442 /* ... they declare parameters of the same kind. */
3443 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3444 return false;
3446 /* ... one parameter was introduced by a parameter declaration, then
3447 both are. This case arises as a result of eagerly rewriting declarations
3448 during parsing. */
3449 if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3450 return false;
3452 /* ... if either declares a pack, they both do. */
3453 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3454 return false;
3456 if (TREE_CODE (decl1) == PARM_DECL)
3458 /* ... if they declare non-type parameters, the types are equivalent. */
3459 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3460 return false;
3462 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3464 /* ... if they declare template template parameters, their template
3465 parameter lists are equivalent. */
3466 if (!template_heads_equivalent_p (decl1, decl2))
3467 return false;
3470 /* ... if they are declared with a qualified-concept name, they both
3471 are, and those names are equivalent. */
3472 return template_parameter_constraints_equivalent_p (parm1, parm2);
3475 /* Returns true if two template parameters lists are equivalent.
3476 Two template parameter lists are equivalent if they have the
3477 same length and their corresponding parameters are equivalent.
3479 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3480 data structure returned by DECL_TEMPLATE_PARMS.
3482 This is generally the same implementation as comp_template_parms
3483 except that it also the concept names and arguments used to
3484 introduce parameters. */
3486 static bool
3487 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3489 if (parms1 == parms2)
3490 return true;
3492 const_tree p1 = parms1;
3493 const_tree p2 = parms2;
3494 while (p1 != NULL_TREE && p2 != NULL_TREE)
3496 tree list1 = TREE_VALUE (p1);
3497 tree list2 = TREE_VALUE (p2);
3499 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3500 return 0;
3502 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3504 tree parm1 = TREE_VEC_ELT (list1, i);
3505 tree parm2 = TREE_VEC_ELT (list2, i);
3506 if (!template_parameters_equivalent_p (parm1, parm2))
3507 return false;
3510 p1 = TREE_CHAIN (p1);
3511 p2 = TREE_CHAIN (p2);
3514 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3515 return false;
3517 return true;
3520 /* Return true if the requires-clause of the template parameter lists are
3521 equivalent and false otherwise. */
3522 static bool
3523 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3525 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3526 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3527 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3528 return false;
3529 if (!cp_tree_equal (req1, req2))
3530 return false;
3531 return true;
3534 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3535 Two template heads are equivalent if their template parameter
3536 lists are equivalent and their requires clauses are equivalent.
3538 In pre-C++20, this is equivalent to calling comp_template_parms
3539 for the template parameters of TMPL1 and TMPL2. */
3541 bool
3542 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3544 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3545 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3547 /* Don't change the matching rules for pre-C++20. */
3548 if (cxx_dialect < cxx20)
3549 return comp_template_parms (parms1, parms2);
3551 /* ... have the same number of template parameters, and their
3552 corresponding parameters are equivalent. */
3553 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3554 return false;
3556 /* ... if either has a requires-clause, they both do and their
3557 corresponding constraint-expressions are equivalent. */
3558 return template_requirements_equivalent_p (parms1, parms2);
3561 /* Determine whether PARM is a parameter pack. */
3563 bool
3564 template_parameter_pack_p (const_tree parm)
3566 /* Determine if we have a non-type template parameter pack. */
3567 if (TREE_CODE (parm) == PARM_DECL)
3568 return (DECL_TEMPLATE_PARM_P (parm)
3569 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3570 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3571 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3573 /* If this is a list of template parameters, we could get a
3574 TYPE_DECL or a TEMPLATE_DECL. */
3575 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3576 parm = TREE_TYPE (parm);
3578 /* Otherwise it must be a type template parameter. */
3579 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3580 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3581 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3584 /* Determine if T is a function parameter pack. */
3586 bool
3587 function_parameter_pack_p (const_tree t)
3589 if (t && TREE_CODE (t) == PARM_DECL)
3590 return DECL_PACK_P (t);
3591 return false;
3594 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3595 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3597 tree
3598 get_function_template_decl (const_tree primary_func_tmpl_inst)
3600 if (! primary_func_tmpl_inst
3601 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3602 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3603 return NULL;
3605 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3608 /* Return true iff the function parameter PARAM_DECL was expanded
3609 from the function parameter pack PACK. */
3611 bool
3612 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3614 if (DECL_ARTIFICIAL (param_decl)
3615 || !function_parameter_pack_p (pack))
3616 return false;
3618 /* The parameter pack and its pack arguments have the same
3619 DECL_PARM_INDEX. */
3620 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3623 /* Determine whether ARGS describes a variadic template args list,
3624 i.e., one that is terminated by a template argument pack. */
3626 static bool
3627 template_args_variadic_p (tree args)
3629 int nargs;
3630 tree last_parm;
3632 if (args == NULL_TREE)
3633 return false;
3635 args = INNERMOST_TEMPLATE_ARGS (args);
3636 nargs = TREE_VEC_LENGTH (args);
3638 if (nargs == 0)
3639 return false;
3641 last_parm = TREE_VEC_ELT (args, nargs - 1);
3643 return ARGUMENT_PACK_P (last_parm);
3646 /* Generate a new name for the parameter pack name NAME (an
3647 IDENTIFIER_NODE) that incorporates its */
3649 static tree
3650 make_ith_pack_parameter_name (tree name, int i)
3652 /* Munge the name to include the parameter index. */
3653 #define NUMBUF_LEN 128
3654 char numbuf[NUMBUF_LEN];
3655 char* newname;
3656 int newname_len;
3658 if (name == NULL_TREE)
3659 return name;
3660 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3661 newname_len = IDENTIFIER_LENGTH (name)
3662 + strlen (numbuf) + 2;
3663 newname = (char*)alloca (newname_len);
3664 snprintf (newname, newname_len,
3665 "%s#%i", IDENTIFIER_POINTER (name), i);
3666 return get_identifier (newname);
3669 /* Return true if T is a primary function, class or alias template
3670 specialization, not including the template pattern. */
3672 bool
3673 primary_template_specialization_p (const_tree t)
3675 if (!t)
3676 return false;
3678 if (VAR_OR_FUNCTION_DECL_P (t))
3679 return (DECL_LANG_SPECIFIC (t)
3680 && DECL_USE_TEMPLATE (t)
3681 && DECL_TEMPLATE_INFO (t)
3682 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3683 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3684 return (CLASSTYPE_TEMPLATE_INFO (t)
3685 && CLASSTYPE_USE_TEMPLATE (t)
3686 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3687 else if (alias_template_specialization_p (t, nt_transparent))
3688 return true;
3689 return false;
3692 /* Return true if PARM is a template template parameter. */
3694 bool
3695 template_template_parameter_p (const_tree parm)
3697 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3700 /* Return true iff PARM is a DECL representing a type template
3701 parameter. */
3703 bool
3704 template_type_parameter_p (const_tree parm)
3706 return (parm
3707 && (TREE_CODE (parm) == TYPE_DECL
3708 || TREE_CODE (parm) == TEMPLATE_DECL)
3709 && DECL_TEMPLATE_PARM_P (parm));
3712 /* Return the template parameters of T if T is a
3713 primary template instantiation, NULL otherwise. */
3715 tree
3716 get_primary_template_innermost_parameters (const_tree t)
3718 tree parms = NULL, template_info = NULL;
3720 if ((template_info = get_template_info (t))
3721 && primary_template_specialization_p (t))
3722 parms = INNERMOST_TEMPLATE_PARMS
3723 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3725 return parms;
3728 /* Returns the template arguments of T if T is a template instantiation,
3729 NULL otherwise. */
3731 tree
3732 get_template_innermost_arguments (const_tree t)
3734 tree args = NULL, template_info = NULL;
3736 if ((template_info = get_template_info (t))
3737 && TI_ARGS (template_info))
3738 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3740 return args;
3743 /* Return the argument pack elements of T if T is a template argument pack,
3744 NULL otherwise. */
3746 tree
3747 get_template_argument_pack_elems (const_tree t)
3749 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3750 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3751 return NULL;
3753 return ARGUMENT_PACK_ARGS (t);
3756 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3757 ARGUMENT_PACK_SELECT represents. */
3759 static tree
3760 argument_pack_select_arg (tree t)
3762 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3763 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3765 /* If the selected argument is an expansion E, that most likely means we were
3766 called from gen_elem_of_pack_expansion_instantiation during the
3767 substituting of an argument pack (of which the Ith element is a pack
3768 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3769 In this case, the Ith element resulting from this substituting is going to
3770 be a pack expansion, which pattern is the pattern of E. Let's return the
3771 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3772 resulting pack expansion from it. */
3773 if (PACK_EXPANSION_P (arg))
3775 /* Make sure we aren't throwing away arg info. */
3776 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3777 arg = PACK_EXPANSION_PATTERN (arg);
3780 return arg;
3783 /* Return a modification of ARGS that's suitable for preserving inside a hash
3784 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3785 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3787 static tree
3788 preserve_args (tree args, bool cow_p = true)
3790 if (!args)
3791 return NULL_TREE;
3793 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3795 tree t = TREE_VEC_ELT (args, i);
3796 tree r;
3797 if (!t)
3798 r = NULL_TREE;
3799 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3800 r = argument_pack_select_arg (t);
3801 else if (TREE_CODE (t) == TREE_VEC)
3802 r = preserve_args (t, cow_p);
3803 else
3804 r = t;
3805 if (r != t)
3807 if (cow_p)
3809 args = copy_template_args (args);
3810 cow_p = false;
3812 TREE_VEC_ELT (args, i) = r;
3816 return args;
3819 /* True iff FN is a function representing a built-in variadic parameter
3820 pack. */
3822 bool
3823 builtin_pack_fn_p (tree fn)
3825 if (!fn
3826 || TREE_CODE (fn) != FUNCTION_DECL
3827 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3828 return false;
3830 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3831 return true;
3833 return false;
3836 /* True iff CALL is a call to a function representing a built-in variadic
3837 parameter pack. */
3839 static bool
3840 builtin_pack_call_p (tree call)
3842 if (TREE_CODE (call) != CALL_EXPR)
3843 return false;
3844 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3847 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3849 static tree
3850 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3851 tree in_decl)
3853 tree ohi = CALL_EXPR_ARG (call, 0);
3854 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3855 false/*fn*/, true/*int_cst*/);
3857 if (instantiation_dependent_expression_p (hi))
3859 if (hi != ohi)
3861 call = copy_node (call);
3862 CALL_EXPR_ARG (call, 0) = hi;
3864 tree ex = make_pack_expansion (call, complain);
3865 tree vec = make_tree_vec (1);
3866 TREE_VEC_ELT (vec, 0) = ex;
3867 return vec;
3869 else
3871 hi = instantiate_non_dependent_expr_sfinae (hi, complain);
3872 hi = cxx_constant_value (hi);
3873 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3875 /* Calculate the largest value of len that won't make the size of the vec
3876 overflow an int. The compiler will exceed resource limits long before
3877 this, but it seems a decent place to diagnose. */
3878 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3880 if (len < 0 || len > max)
3882 if ((complain & tf_error)
3883 && hi != error_mark_node)
3884 error ("argument to %<__integer_pack%> must be between 0 and %d",
3885 max);
3886 return error_mark_node;
3889 tree vec = make_tree_vec (len);
3891 for (int i = 0; i < len; ++i)
3892 TREE_VEC_ELT (vec, i) = size_int (i);
3894 return vec;
3898 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3899 CALL. */
3901 static tree
3902 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3903 tree in_decl)
3905 if (!builtin_pack_call_p (call))
3906 return NULL_TREE;
3908 tree fn = CALL_EXPR_FN (call);
3910 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3911 return expand_integer_pack (call, args, complain, in_decl);
3913 return NULL_TREE;
3916 /* Return true if the tree T has the extra args mechanism for
3917 avoiding partial instantiation. */
3919 static bool
3920 has_extra_args_mechanism_p (const_tree t)
3922 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3923 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3924 || (TREE_CODE (t) == IF_STMT
3925 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3928 /* Structure used to track the progress of find_parameter_packs_r. */
3929 struct find_parameter_pack_data
3931 /* TREE_LIST that will contain all of the parameter packs found by
3932 the traversal. */
3933 tree* parameter_packs;
3935 /* Set of AST nodes that have been visited by the traversal. */
3936 hash_set<tree> *visited;
3938 /* True iff we're making a type pack expansion. */
3939 bool type_pack_expansion_p;
3941 /* True iff we found a subtree that has the extra args mechanism. */
3942 bool found_extra_args_tree_p = false;
3945 /* Identifies all of the argument packs that occur in a template
3946 argument and appends them to the TREE_LIST inside DATA, which is a
3947 find_parameter_pack_data structure. This is a subroutine of
3948 make_pack_expansion and uses_parameter_packs. */
3949 static tree
3950 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3952 tree t = *tp;
3953 struct find_parameter_pack_data* ppd =
3954 (struct find_parameter_pack_data*)data;
3955 bool parameter_pack_p = false;
3957 #define WALK_SUBTREE(NODE) \
3958 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3959 ppd, ppd->visited) \
3961 /* Don't look through typedefs; we are interested in whether a
3962 parameter pack is actually written in the expression/type we're
3963 looking at, not the target type. */
3964 if (TYPE_P (t) && typedef_variant_p (t))
3966 /* But do look at arguments for an alias template. */
3967 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3968 cp_walk_tree (&TI_ARGS (tinfo),
3969 &find_parameter_packs_r,
3970 ppd, ppd->visited);
3971 *walk_subtrees = 0;
3972 return NULL_TREE;
3975 /* Identify whether this is a parameter pack or not. */
3976 switch (TREE_CODE (t))
3978 case TEMPLATE_PARM_INDEX:
3979 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3980 parameter_pack_p = true;
3981 break;
3983 case TEMPLATE_TYPE_PARM:
3984 t = TYPE_MAIN_VARIANT (t);
3985 /* FALLTHRU */
3986 case TEMPLATE_TEMPLATE_PARM:
3987 /* If the placeholder appears in the decl-specifier-seq of a function
3988 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3989 is a pack expansion, the invented template parameter is a template
3990 parameter pack. */
3991 if (ppd->type_pack_expansion_p && is_auto (t))
3992 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3993 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3994 parameter_pack_p = true;
3995 break;
3997 case FIELD_DECL:
3998 case PARM_DECL:
3999 if (DECL_PACK_P (t))
4001 /* We don't want to walk into the type of a PARM_DECL,
4002 because we don't want to see the type parameter pack. */
4003 *walk_subtrees = 0;
4004 parameter_pack_p = true;
4006 break;
4008 case VAR_DECL:
4009 if (DECL_PACK_P (t))
4011 /* We don't want to walk into the type of a variadic capture proxy,
4012 because we don't want to see the type parameter pack. */
4013 *walk_subtrees = 0;
4014 parameter_pack_p = true;
4016 else if (variable_template_specialization_p (t))
4018 cp_walk_tree (&DECL_TI_ARGS (t),
4019 find_parameter_packs_r,
4020 ppd, ppd->visited);
4021 *walk_subtrees = 0;
4023 break;
4025 case CALL_EXPR:
4026 if (builtin_pack_call_p (t))
4027 parameter_pack_p = true;
4028 break;
4030 case BASES:
4031 parameter_pack_p = true;
4032 break;
4033 default:
4034 /* Not a parameter pack. */
4035 break;
4038 if (parameter_pack_p)
4040 /* Add this parameter pack to the list. */
4041 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
4044 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
4045 ppd->found_extra_args_tree_p = true;
4047 if (TYPE_P (t))
4048 cp_walk_tree (&TYPE_CONTEXT (t),
4049 &find_parameter_packs_r, ppd, ppd->visited);
4051 /* This switch statement will return immediately if we don't find a
4052 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
4053 switch (TREE_CODE (t))
4055 case BOUND_TEMPLATE_TEMPLATE_PARM:
4056 /* Check the template itself. */
4057 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
4058 &find_parameter_packs_r, ppd, ppd->visited);
4059 return NULL_TREE;
4061 case DECL_EXPR:
4063 tree decl = DECL_EXPR_DECL (t);
4064 /* Ignore the declaration of a capture proxy for a parameter pack. */
4065 if (is_capture_proxy (decl))
4066 *walk_subtrees = 0;
4067 if (is_typedef_decl (decl))
4068 /* Since we stop at typedefs above, we need to look through them at
4069 the point of the DECL_EXPR. */
4070 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4071 &find_parameter_packs_r, ppd, ppd->visited);
4072 return NULL_TREE;
4075 case TEMPLATE_DECL:
4076 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4077 return NULL_TREE;
4078 cp_walk_tree (&TREE_TYPE (t),
4079 &find_parameter_packs_r, ppd, ppd->visited);
4080 return NULL_TREE;
4082 case TYPE_PACK_EXPANSION:
4083 case EXPR_PACK_EXPANSION:
4084 *walk_subtrees = 0;
4085 return NULL_TREE;
4087 case INTEGER_TYPE:
4088 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4089 ppd, ppd->visited);
4090 *walk_subtrees = 0;
4091 return NULL_TREE;
4093 case IDENTIFIER_NODE:
4094 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4095 ppd->visited);
4096 *walk_subtrees = 0;
4097 return NULL_TREE;
4099 case LAMBDA_EXPR:
4101 /* Since we defer implicit capture, look in the parms and body. */
4102 tree fn = lambda_function (t);
4103 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4104 ppd->visited);
4105 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4106 ppd->visited);
4107 return NULL_TREE;
4110 case DECLTYPE_TYPE:
4112 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4113 type_pack_expansion_p to false so that any placeholders
4114 within the expression don't get marked as parameter packs. */
4115 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4116 ppd->type_pack_expansion_p = false;
4117 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4118 ppd, ppd->visited);
4119 ppd->type_pack_expansion_p = type_pack_expansion_p;
4120 *walk_subtrees = 0;
4121 return NULL_TREE;
4124 case IF_STMT:
4125 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4126 ppd, ppd->visited);
4127 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4128 ppd, ppd->visited);
4129 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4130 ppd, ppd->visited);
4131 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4132 *walk_subtrees = 0;
4133 return NULL_TREE;
4135 case TAG_DEFN:
4136 t = TREE_TYPE (t);
4137 if (CLASS_TYPE_P (t))
4138 /* Local class, need to look through the whole definition. */
4139 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4140 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4141 ppd, ppd->visited);
4142 else
4143 /* Enum, look at the values. */
4144 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4145 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4146 &find_parameter_packs_r,
4147 ppd, ppd->visited);
4148 return NULL_TREE;
4150 case FUNCTION_TYPE:
4151 case METHOD_TYPE:
4152 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4153 break;
4155 default:
4156 return NULL_TREE;
4159 #undef WALK_SUBTREE
4161 return NULL_TREE;
4164 /* Determines if the expression or type T uses any parameter packs. */
4165 tree
4166 uses_parameter_packs (tree t)
4168 tree parameter_packs = NULL_TREE;
4169 struct find_parameter_pack_data ppd;
4170 ppd.parameter_packs = &parameter_packs;
4171 ppd.visited = new hash_set<tree>;
4172 ppd.type_pack_expansion_p = false;
4173 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4174 delete ppd.visited;
4175 return parameter_packs;
4178 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4179 representation a base-class initializer into a parameter pack
4180 expansion. If all goes well, the resulting node will be an
4181 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4182 respectively. */
4183 tree
4184 make_pack_expansion (tree arg, tsubst_flags_t complain)
4186 tree result;
4187 tree parameter_packs = NULL_TREE;
4188 bool for_types = false;
4189 struct find_parameter_pack_data ppd;
4191 if (!arg || arg == error_mark_node)
4192 return arg;
4194 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4196 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4197 class initializer. In this case, the TREE_PURPOSE will be a
4198 _TYPE node (representing the base class expansion we're
4199 initializing) and the TREE_VALUE will be a TREE_LIST
4200 containing the initialization arguments.
4202 The resulting expansion looks somewhat different from most
4203 expansions. Rather than returning just one _EXPANSION, we
4204 return a TREE_LIST whose TREE_PURPOSE is a
4205 TYPE_PACK_EXPANSION containing the bases that will be
4206 initialized. The TREE_VALUE will be identical to the
4207 original TREE_VALUE, which is a list of arguments that will
4208 be passed to each base. We do not introduce any new pack
4209 expansion nodes into the TREE_VALUE (although it is possible
4210 that some already exist), because the TREE_PURPOSE and
4211 TREE_VALUE all need to be expanded together with the same
4212 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4213 resulting TREE_PURPOSE will mention the parameter packs in
4214 both the bases and the arguments to the bases. */
4215 tree purpose;
4216 tree value;
4217 tree parameter_packs = NULL_TREE;
4219 /* Determine which parameter packs will be used by the base
4220 class expansion. */
4221 ppd.visited = new hash_set<tree>;
4222 ppd.parameter_packs = &parameter_packs;
4223 ppd.type_pack_expansion_p = false;
4224 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4225 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4226 &ppd, ppd.visited);
4228 if (parameter_packs == NULL_TREE)
4230 if (complain & tf_error)
4231 error ("base initializer expansion %qT contains no parameter packs",
4232 arg);
4233 delete ppd.visited;
4234 return error_mark_node;
4237 if (TREE_VALUE (arg) != void_type_node)
4239 /* Collect the sets of parameter packs used in each of the
4240 initialization arguments. */
4241 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4243 /* Determine which parameter packs will be expanded in this
4244 argument. */
4245 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4246 &ppd, ppd.visited);
4250 delete ppd.visited;
4252 /* Create the pack expansion type for the base type. */
4253 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4254 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4255 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4256 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4258 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4259 they will rarely be compared to anything. */
4260 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4262 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4265 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4266 for_types = true;
4268 /* Build the PACK_EXPANSION_* node. */
4269 result = for_types
4270 ? cxx_make_type (TYPE_PACK_EXPANSION)
4271 : make_node (EXPR_PACK_EXPANSION);
4272 PACK_EXPANSION_PATTERN (result) = arg;
4273 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4275 /* Propagate type and const-expression information. */
4276 TREE_TYPE (result) = TREE_TYPE (arg);
4277 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4278 /* Mark this read now, since the expansion might be length 0. */
4279 mark_exp_read (arg);
4281 else
4282 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4283 they will rarely be compared to anything. */
4284 SET_TYPE_STRUCTURAL_EQUALITY (result);
4286 /* Determine which parameter packs will be expanded. */
4287 ppd.parameter_packs = &parameter_packs;
4288 ppd.visited = new hash_set<tree>;
4289 ppd.type_pack_expansion_p = TYPE_P (arg);
4290 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4291 delete ppd.visited;
4293 /* Make sure we found some parameter packs. */
4294 if (parameter_packs == NULL_TREE)
4296 if (complain & tf_error)
4298 if (TYPE_P (arg))
4299 error ("expansion pattern %qT contains no parameter packs", arg);
4300 else
4301 error ("expansion pattern %qE contains no parameter packs", arg);
4303 return error_mark_node;
4305 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4307 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4308 if (ppd.found_extra_args_tree_p)
4309 /* If the pattern of this pack expansion contains a subtree that has
4310 the extra args mechanism for avoiding partial instantiation, then
4311 force this pack expansion to also use extra args. Otherwise
4312 partial instantiation of this pack expansion may not lower the
4313 level of some parameter packs within the pattern, which would
4314 confuse tsubst_pack_expansion later (PR101764). */
4315 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4317 return result;
4320 /* Checks T for any "bare" parameter packs, which have not yet been
4321 expanded, and issues an error if any are found. This operation can
4322 only be done on full expressions or types (e.g., an expression
4323 statement, "if" condition, etc.), because we could have expressions like:
4325 foo(f(g(h(args)))...)
4327 where "args" is a parameter pack. check_for_bare_parameter_packs
4328 should not be called for the subexpressions args, h(args),
4329 g(h(args)), or f(g(h(args))), because we would produce erroneous
4330 error messages.
4332 Returns TRUE and emits an error if there were bare parameter packs,
4333 returns FALSE otherwise. */
4334 bool
4335 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4337 tree parameter_packs = NULL_TREE;
4338 struct find_parameter_pack_data ppd;
4340 if (!processing_template_decl || !t || t == error_mark_node)
4341 return false;
4343 if (TREE_CODE (t) == TYPE_DECL)
4344 t = TREE_TYPE (t);
4346 ppd.parameter_packs = &parameter_packs;
4347 ppd.visited = new hash_set<tree>;
4348 ppd.type_pack_expansion_p = false;
4349 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4350 delete ppd.visited;
4352 if (!parameter_packs)
4353 return false;
4355 if (loc == UNKNOWN_LOCATION)
4356 loc = cp_expr_loc_or_input_loc (t);
4358 /* It's OK for a lambda to have an unexpanded parameter pack from the
4359 containing context, but do complain about unexpanded capture packs. */
4360 tree lam = current_lambda_expr ();
4361 if (lam)
4362 lam = TREE_TYPE (lam);
4364 if (lam && lam != current_class_type)
4366 /* We're in a lambda, but it isn't the innermost class.
4367 This should work, but currently doesn't. */
4368 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4369 return true;
4372 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4373 for (; parameter_packs;
4374 parameter_packs = TREE_CHAIN (parameter_packs))
4376 tree pack = TREE_VALUE (parameter_packs);
4377 if (is_capture_proxy (pack)
4378 || (TREE_CODE (pack) == PARM_DECL
4379 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4380 break;
4383 if (parameter_packs)
4385 error_at (loc, "parameter packs not expanded with %<...%>:");
4386 while (parameter_packs)
4388 tree pack = TREE_VALUE (parameter_packs);
4389 tree name = NULL_TREE;
4391 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4392 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4393 name = TYPE_NAME (pack);
4394 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4395 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4396 else if (TREE_CODE (pack) == CALL_EXPR)
4397 name = DECL_NAME (CALL_EXPR_FN (pack));
4398 else
4399 name = DECL_NAME (pack);
4401 if (name)
4402 inform (loc, " %qD", name);
4403 else
4404 inform (loc, " %s", "<anonymous>");
4406 parameter_packs = TREE_CHAIN (parameter_packs);
4409 return true;
4412 return false;
4415 /* Expand any parameter packs that occur in the template arguments in
4416 ARGS. */
4417 tree
4418 expand_template_argument_pack (tree args)
4420 if (args == error_mark_node)
4421 return error_mark_node;
4423 tree result_args = NULL_TREE;
4424 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4425 int num_result_args = -1;
4426 int non_default_args_count = -1;
4428 /* First, determine if we need to expand anything, and the number of
4429 slots we'll need. */
4430 for (in_arg = 0; in_arg < nargs; ++in_arg)
4432 tree arg = TREE_VEC_ELT (args, in_arg);
4433 if (arg == NULL_TREE)
4434 return args;
4435 if (ARGUMENT_PACK_P (arg))
4437 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4438 if (num_result_args < 0)
4439 num_result_args = in_arg + num_packed;
4440 else
4441 num_result_args += num_packed;
4443 else
4445 if (num_result_args >= 0)
4446 num_result_args++;
4450 /* If no expansion is necessary, we're done. */
4451 if (num_result_args < 0)
4452 return args;
4454 /* Expand arguments. */
4455 result_args = make_tree_vec (num_result_args);
4456 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4457 non_default_args_count =
4458 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4459 for (in_arg = 0; in_arg < nargs; ++in_arg)
4461 tree arg = TREE_VEC_ELT (args, in_arg);
4462 if (ARGUMENT_PACK_P (arg))
4464 tree packed = ARGUMENT_PACK_ARGS (arg);
4465 int i, num_packed = TREE_VEC_LENGTH (packed);
4466 for (i = 0; i < num_packed; ++i, ++out_arg)
4467 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4468 if (non_default_args_count > 0)
4469 non_default_args_count += num_packed - 1;
4471 else
4473 TREE_VEC_ELT (result_args, out_arg) = arg;
4474 ++out_arg;
4477 if (non_default_args_count >= 0)
4478 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4479 return result_args;
4482 /* Checks if DECL shadows a template parameter.
4484 [temp.local]: A template-parameter shall not be redeclared within its
4485 scope (including nested scopes).
4487 Emits an error and returns TRUE if the DECL shadows a parameter,
4488 returns FALSE otherwise. */
4490 bool
4491 check_template_shadow (tree decl)
4493 tree olddecl;
4495 /* If we're not in a template, we can't possibly shadow a template
4496 parameter. */
4497 if (!current_template_parms)
4498 return true;
4500 /* Figure out what we're shadowing. */
4501 decl = OVL_FIRST (decl);
4502 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4504 /* If there's no previous binding for this name, we're not shadowing
4505 anything, let alone a template parameter. */
4506 if (!olddecl)
4507 return true;
4509 /* If we're not shadowing a template parameter, we're done. Note
4510 that OLDDECL might be an OVERLOAD (or perhaps even an
4511 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4512 node. */
4513 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4514 return true;
4516 /* We check for decl != olddecl to avoid bogus errors for using a
4517 name inside a class. We check TPFI to avoid duplicate errors for
4518 inline member templates. */
4519 if (decl == olddecl
4520 || (DECL_TEMPLATE_PARM_P (decl)
4521 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4522 return true;
4524 /* Don't complain about the injected class name, as we've already
4525 complained about the class itself. */
4526 if (DECL_SELF_REFERENCE_P (decl))
4527 return false;
4529 if (DECL_TEMPLATE_PARM_P (decl))
4530 error ("declaration of template parameter %q+D shadows "
4531 "template parameter", decl);
4532 else
4533 error ("declaration of %q+#D shadows template parameter", decl);
4534 inform (DECL_SOURCE_LOCATION (olddecl),
4535 "template parameter %qD declared here", olddecl);
4536 return false;
4539 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4540 ORIG_LEVEL, DECL, and TYPE. */
4542 static tree
4543 build_template_parm_index (int index,
4544 int level,
4545 int orig_level,
4546 tree decl,
4547 tree type)
4549 tree t = make_node (TEMPLATE_PARM_INDEX);
4550 TEMPLATE_PARM_IDX (t) = index;
4551 TEMPLATE_PARM_LEVEL (t) = level;
4552 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4553 TEMPLATE_PARM_DECL (t) = decl;
4554 TREE_TYPE (t) = type;
4555 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4556 TREE_READONLY (t) = TREE_READONLY (decl);
4558 return t;
4561 struct ctp_hasher : ggc_ptr_hash<tree_node>
4563 static hashval_t hash (tree t)
4565 tree_code code = TREE_CODE (t);
4566 hashval_t val = iterative_hash_object (code, 0);
4567 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4568 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4569 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4570 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4571 return val;
4574 static bool equal (tree t, tree u)
4576 return comptypes (t, u, COMPARE_STRUCTURAL);
4580 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4582 /* Find the canonical type parameter for the given template type
4583 parameter. Returns the canonical type parameter, which may be TYPE
4584 if no such parameter existed. */
4586 tree
4587 canonical_type_parameter (tree type)
4589 if (ctp_table == NULL)
4590 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4592 tree& slot = *ctp_table->find_slot (type, INSERT);
4593 if (slot == NULL_TREE)
4594 slot = type;
4595 return slot;
4598 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4599 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4600 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4601 new one is created. */
4603 static tree
4604 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4605 tsubst_flags_t complain)
4607 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4608 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4609 != TEMPLATE_PARM_LEVEL (index) - levels)
4610 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4612 tree orig_decl = TEMPLATE_PARM_DECL (index);
4614 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4615 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4616 type);
4617 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4618 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4619 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4620 DECL_ARTIFICIAL (decl) = 1;
4621 SET_DECL_TEMPLATE_PARM_P (decl);
4623 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4624 TEMPLATE_PARM_LEVEL (index) - levels,
4625 TEMPLATE_PARM_ORIG_LEVEL (index),
4626 decl, type);
4627 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4628 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4629 = TEMPLATE_PARM_PARAMETER_PACK (index);
4631 /* Template template parameters need this. */
4632 tree inner = decl;
4633 if (TREE_CODE (decl) == TEMPLATE_DECL)
4635 inner = build_decl (DECL_SOURCE_LOCATION (decl),
4636 TYPE_DECL, DECL_NAME (decl), type);
4637 DECL_TEMPLATE_RESULT (decl) = inner;
4638 DECL_ARTIFICIAL (inner) = true;
4639 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4640 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4643 /* Attach the TPI to the decl. */
4644 if (TREE_CODE (inner) == TYPE_DECL)
4645 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4646 else
4647 DECL_INITIAL (decl) = tpi;
4650 return TEMPLATE_PARM_DESCENDANTS (index);
4653 /* Process information from new template parameter PARM and append it
4654 to the LIST being built. This new parameter is a non-type
4655 parameter iff IS_NON_TYPE is true. This new parameter is a
4656 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4657 is in PARM_LOC. */
4659 tree
4660 process_template_parm (tree list, location_t parm_loc, tree parm,
4661 bool is_non_type, bool is_parameter_pack)
4663 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4664 tree prev = NULL_TREE;
4665 int idx = 0;
4667 if (list)
4669 prev = tree_last (list);
4671 tree p = TREE_VALUE (prev);
4672 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4673 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4674 else if (TREE_CODE (p) == PARM_DECL)
4675 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4677 ++idx;
4680 tree decl = NULL_TREE;
4681 tree defval = TREE_PURPOSE (parm);
4682 tree constr = TREE_TYPE (parm);
4684 if (is_non_type)
4686 parm = TREE_VALUE (parm);
4688 SET_DECL_TEMPLATE_PARM_P (parm);
4690 if (TREE_TYPE (parm) != error_mark_node)
4692 /* [temp.param]
4694 The top-level cv-qualifiers on the template-parameter are
4695 ignored when determining its type. */
4696 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4697 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4698 TREE_TYPE (parm) = error_mark_node;
4699 else if (uses_parameter_packs (TREE_TYPE (parm))
4700 && !is_parameter_pack
4701 /* If we're in a nested template parameter list, the template
4702 template parameter could be a parameter pack. */
4703 && processing_template_parmlist == 1)
4705 /* This template parameter is not a parameter pack, but it
4706 should be. Complain about "bare" parameter packs. */
4707 check_for_bare_parameter_packs (TREE_TYPE (parm));
4709 /* Recover by calling this a parameter pack. */
4710 is_parameter_pack = true;
4714 /* A template parameter is not modifiable. */
4715 TREE_CONSTANT (parm) = 1;
4716 TREE_READONLY (parm) = 1;
4717 decl = build_decl (parm_loc,
4718 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4719 TREE_CONSTANT (decl) = 1;
4720 TREE_READONLY (decl) = 1;
4721 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4722 = build_template_parm_index (idx, current_template_depth,
4723 current_template_depth,
4724 decl, TREE_TYPE (parm));
4726 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4727 = is_parameter_pack;
4729 else
4731 tree t;
4732 parm = TREE_VALUE (TREE_VALUE (parm));
4734 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4736 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4737 /* This is for distinguishing between real templates and template
4738 template parameters */
4739 TREE_TYPE (parm) = t;
4741 /* any_template_parm_r expects to be able to get the targs of a
4742 DECL_TEMPLATE_RESULT. */
4743 tree result = DECL_TEMPLATE_RESULT (parm);
4744 TREE_TYPE (result) = t;
4745 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4746 tree tinfo = build_template_info (parm, args);
4747 retrofit_lang_decl (result);
4748 DECL_TEMPLATE_INFO (result) = tinfo;
4750 decl = parm;
4752 else
4754 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4755 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4756 decl = build_decl (parm_loc,
4757 TYPE_DECL, parm, t);
4760 TYPE_NAME (t) = decl;
4761 TYPE_STUB_DECL (t) = decl;
4762 parm = decl;
4763 TEMPLATE_TYPE_PARM_INDEX (t)
4764 = build_template_parm_index (idx, current_template_depth,
4765 current_template_depth,
4766 decl, TREE_TYPE (parm));
4767 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4768 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4770 DECL_ARTIFICIAL (decl) = 1;
4771 SET_DECL_TEMPLATE_PARM_P (decl);
4773 /* Build requirements for the type/template parameter.
4774 This must be done after SET_DECL_TEMPLATE_PARM_P or
4775 process_template_parm could fail. */
4776 tree reqs = finish_shorthand_constraint (parm, constr);
4778 decl = pushdecl (decl);
4779 if (!is_non_type)
4780 parm = decl;
4782 /* Build the parameter node linking the parameter declaration,
4783 its default argument (if any), and its constraints (if any). */
4784 parm = build_tree_list (defval, parm);
4785 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4787 if (prev)
4788 TREE_CHAIN (prev) = parm;
4789 else
4790 list = parm;
4792 return list;
4795 /* The end of a template parameter list has been reached. Process the
4796 tree list into a parameter vector, converting each parameter into a more
4797 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4798 as PARM_DECLs. */
4800 tree
4801 end_template_parm_list (tree parms)
4803 tree saved_parmlist = make_tree_vec (list_length (parms));
4805 /* Pop the dummy parameter level and add the real one. We do not
4806 morph the dummy parameter in place, as it might have been
4807 captured by a (nested) template-template-parm. */
4808 current_template_parms = TREE_CHAIN (current_template_parms);
4810 current_template_parms
4811 = tree_cons (size_int (current_template_depth + 1),
4812 saved_parmlist, current_template_parms);
4814 for (unsigned ix = 0; parms; ix++)
4816 tree parm = parms;
4817 parms = TREE_CHAIN (parms);
4818 TREE_CHAIN (parm) = NULL_TREE;
4820 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4823 --processing_template_parmlist;
4825 return saved_parmlist;
4828 // Explicitly indicate the end of the template parameter list. We assume
4829 // that the current template parameters have been constructed and/or
4830 // managed explicitly, as when creating new template template parameters
4831 // from a shorthand constraint.
4832 void
4833 end_template_parm_list ()
4835 --processing_template_parmlist;
4838 /* end_template_decl is called after a template declaration is seen. */
4840 void
4841 end_template_decl (void)
4843 reset_specialization ();
4845 if (! processing_template_decl)
4846 return;
4848 /* This matches the pushlevel in begin_template_parm_list. */
4849 finish_scope ();
4851 --processing_template_decl;
4852 current_template_parms = TREE_CHAIN (current_template_parms);
4855 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4856 thereof, and converts it into an argument suitable to be passed to
4857 the type substitution functions. Note that if the TREE_LIST contains
4858 an error_mark node, the returned argument is error_mark_node. */
4860 tree
4861 template_parm_to_arg (tree t)
4863 if (!t)
4864 return NULL_TREE;
4866 if (TREE_CODE (t) == TREE_LIST)
4867 t = TREE_VALUE (t);
4869 if (error_operand_p (t))
4870 return error_mark_node;
4872 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4874 if (TREE_CODE (t) == TYPE_DECL
4875 || TREE_CODE (t) == TEMPLATE_DECL)
4876 t = TREE_TYPE (t);
4877 else
4878 t = DECL_INITIAL (t);
4881 gcc_assert (TEMPLATE_PARM_P (t));
4883 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4884 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4886 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4888 /* Turn this argument into a TYPE_ARGUMENT_PACK
4889 with a single element, which expands T. */
4890 tree vec = make_tree_vec (1);
4891 if (CHECKING_P)
4892 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4894 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4896 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4897 ARGUMENT_PACK_ARGS (t) = vec;
4900 else
4902 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4904 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4905 with a single element, which expands T. */
4906 tree vec = make_tree_vec (1);
4907 if (CHECKING_P)
4908 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4910 t = convert_from_reference (t);
4911 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4913 t = make_node (NONTYPE_ARGUMENT_PACK);
4914 ARGUMENT_PACK_ARGS (t) = vec;
4916 else
4917 t = convert_from_reference (t);
4919 return t;
4922 /* If T looks like a generic template argument produced by template_parm_to_arg,
4923 return the corresponding template parameter, otherwise return NULL_TREE. */
4925 static tree
4926 template_arg_to_parm (tree t)
4928 if (t == NULL_TREE)
4929 return NULL_TREE;
4931 if (ARGUMENT_PACK_P (t))
4933 tree args = ARGUMENT_PACK_ARGS (t);
4934 if (TREE_VEC_LENGTH (args) == 1
4935 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4936 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4939 if (REFERENCE_REF_P (t))
4940 t = TREE_OPERAND (t, 0);
4942 if (TEMPLATE_PARM_P (t))
4943 return t;
4944 else
4945 return NULL_TREE;
4948 /* Given a single level of template parameters (a TREE_VEC), return it
4949 as a set of template arguments. */
4951 tree
4952 template_parms_level_to_args (tree parms)
4954 parms = copy_node (parms);
4955 TREE_TYPE (parms) = NULL_TREE;
4956 for (tree& parm : tree_vec_range (parms))
4957 parm = template_parm_to_arg (parm);
4959 if (CHECKING_P)
4960 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4962 return parms;
4965 /* Given a set of template parameters, return them as a set of template
4966 arguments. The template parameters are represented as a TREE_VEC, in
4967 the form documented in cp-tree.h for template arguments. */
4969 tree
4970 template_parms_to_args (tree parms)
4972 tree header;
4973 tree args = NULL_TREE;
4974 int length = TMPL_PARMS_DEPTH (parms);
4975 int l = length;
4977 /* If there is only one level of template parameters, we do not
4978 create a TREE_VEC of TREE_VECs. Instead, we return a single
4979 TREE_VEC containing the arguments. */
4980 if (length > 1)
4981 args = make_tree_vec (length);
4983 for (header = parms; header; header = TREE_CHAIN (header))
4985 tree a = template_parms_level_to_args (TREE_VALUE (header));
4987 if (length > 1)
4988 TREE_VEC_ELT (args, --l) = a;
4989 else
4990 args = a;
4993 return args;
4996 /* Within the declaration of a template, return the currently active
4997 template parameters as an argument TREE_VEC. */
4999 static tree
5000 current_template_args (void)
5002 return template_parms_to_args (current_template_parms);
5005 /* Return the fully generic arguments for of TMPL, i.e. what
5006 current_template_args would be while parsing it. */
5008 tree
5009 generic_targs_for (tree tmpl)
5011 if (tmpl == NULL_TREE)
5012 return NULL_TREE;
5013 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
5014 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
5015 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
5016 template parameter, it has no TEMPLATE_INFO; for a partial
5017 specialization, it has the arguments for the primary template, and we
5018 want the arguments for the partial specialization. */;
5019 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
5020 if (tree ti = get_template_info (result))
5021 return TI_ARGS (ti);
5022 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
5025 /* Update the declared TYPE by doing any lookups which were thought to be
5026 dependent, but are not now that we know the SCOPE of the declarator. */
5028 tree
5029 maybe_update_decl_type (tree orig_type, tree scope)
5031 tree type = orig_type;
5033 if (type == NULL_TREE)
5034 return type;
5036 if (TREE_CODE (orig_type) == TYPE_DECL)
5037 type = TREE_TYPE (type);
5039 if (scope && TYPE_P (scope) && dependent_type_p (scope)
5040 && dependent_type_p (type)
5041 /* Don't bother building up the args in this case. */
5042 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5044 /* tsubst in the args corresponding to the template parameters,
5045 including auto if present. Most things will be unchanged, but
5046 make_typename_type and tsubst_qualified_id will resolve
5047 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5048 tree args = current_template_args ();
5049 tree auto_node = type_uses_auto (type);
5050 tree pushed;
5051 if (auto_node)
5053 tree auto_vec = make_tree_vec (1);
5054 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5055 args = add_to_template_args (args, auto_vec);
5057 pushed = push_scope (scope);
5058 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5059 if (pushed)
5060 pop_scope (scope);
5063 if (type == error_mark_node)
5064 return orig_type;
5066 if (TREE_CODE (orig_type) == TYPE_DECL)
5068 if (same_type_p (type, TREE_TYPE (orig_type)))
5069 type = orig_type;
5070 else
5071 type = TYPE_NAME (type);
5073 return type;
5076 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5077 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5078 the new template is a member template. */
5080 static tree
5081 build_template_decl (tree decl, tree parms, bool member_template_p)
5083 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5085 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5086 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5087 DECL_TEMPLATE_PARMS (tmpl) = parms;
5088 DECL_TEMPLATE_RESULT (tmpl) = decl;
5089 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5090 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5091 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5092 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5094 /* Propagate module information from the decl. */
5095 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5097 return tmpl;
5100 struct template_parm_data
5102 /* The level of the template parameters we are currently
5103 processing. */
5104 int level;
5106 /* The index of the specialization argument we are currently
5107 processing. */
5108 int current_arg;
5110 /* An array whose size is the number of template parameters. The
5111 elements are nonzero if the parameter has been used in any one
5112 of the arguments processed so far. */
5113 int* parms;
5115 /* An array whose size is the number of template arguments. The
5116 elements are nonzero if the argument makes use of template
5117 parameters of this level. */
5118 int* arg_uses_template_parms;
5121 /* Subroutine of push_template_decl used to see if each template
5122 parameter in a partial specialization is used in the explicit
5123 argument list. If T is of the LEVEL given in DATA (which is
5124 treated as a template_parm_data*), then DATA->PARMS is marked
5125 appropriately. */
5127 static int
5128 mark_template_parm (tree t, void* data)
5130 int level;
5131 int idx;
5132 struct template_parm_data* tpd = (struct template_parm_data*) data;
5134 template_parm_level_and_index (t, &level, &idx);
5136 if (level == tpd->level)
5138 tpd->parms[idx] = 1;
5139 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5142 /* In C++17 the type of a non-type argument is a deduced context. */
5143 if (cxx_dialect >= cxx17
5144 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5145 for_each_template_parm (TREE_TYPE (t),
5146 &mark_template_parm,
5147 data,
5148 NULL,
5149 /*include_nondeduced_p=*/false);
5151 /* Return zero so that for_each_template_parm will continue the
5152 traversal of the tree; we want to mark *every* template parm. */
5153 return 0;
5156 /* Process the partial specialization DECL. */
5158 static tree
5159 process_partial_specialization (tree decl)
5161 tree type = TREE_TYPE (decl);
5162 tree tinfo = get_template_info (decl);
5163 tree maintmpl = TI_TEMPLATE (tinfo);
5164 tree specargs = TI_ARGS (tinfo);
5165 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5166 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5167 tree inner_parms;
5168 tree inst;
5169 int nargs = TREE_VEC_LENGTH (inner_args);
5170 int ntparms;
5171 int i;
5172 bool did_error_intro = false;
5173 struct template_parm_data tpd;
5174 struct template_parm_data tpd2;
5176 gcc_assert (current_template_parms);
5178 /* A concept cannot be specialized. */
5179 if (flag_concepts && variable_concept_p (maintmpl))
5181 error ("specialization of variable concept %q#D", maintmpl);
5182 return error_mark_node;
5185 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5186 ntparms = TREE_VEC_LENGTH (inner_parms);
5188 /* We check that each of the template parameters given in the
5189 partial specialization is used in the argument list to the
5190 specialization. For example:
5192 template <class T> struct S;
5193 template <class T> struct S<T*>;
5195 The second declaration is OK because `T*' uses the template
5196 parameter T, whereas
5198 template <class T> struct S<int>;
5200 is no good. Even trickier is:
5202 template <class T>
5203 struct S1
5205 template <class U>
5206 struct S2;
5207 template <class U>
5208 struct S2<T>;
5211 The S2<T> declaration is actually invalid; it is a
5212 full-specialization. Of course,
5214 template <class U>
5215 struct S2<T (*)(U)>;
5217 or some such would have been OK. */
5218 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5219 tpd.parms = XALLOCAVEC (int, ntparms);
5220 memset (tpd.parms, 0, sizeof (int) * ntparms);
5222 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5223 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5224 for (i = 0; i < nargs; ++i)
5226 tpd.current_arg = i;
5227 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5228 &mark_template_parm,
5229 &tpd,
5230 NULL,
5231 /*include_nondeduced_p=*/false);
5233 for (i = 0; i < ntparms; ++i)
5234 if (tpd.parms[i] == 0)
5236 /* One of the template parms was not used in a deduced context in the
5237 specialization. */
5238 if (!did_error_intro)
5240 error ("template parameters not deducible in "
5241 "partial specialization:");
5242 did_error_intro = true;
5245 inform (input_location, " %qD",
5246 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5249 if (did_error_intro)
5250 return error_mark_node;
5252 /* [temp.class.spec]
5254 The argument list of the specialization shall not be identical to
5255 the implicit argument list of the primary template. */
5256 tree main_args
5257 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5258 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5259 && (!flag_concepts
5260 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5262 if (!flag_concepts)
5263 error ("partial specialization %q+D does not specialize "
5264 "any template arguments; to define the primary template, "
5265 "remove the template argument list", decl);
5266 else
5267 error ("partial specialization %q+D does not specialize any "
5268 "template arguments and is not more constrained than "
5269 "the primary template; to define the primary template, "
5270 "remove the template argument list", decl);
5271 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5274 /* A partial specialization that replaces multiple parameters of the
5275 primary template with a pack expansion is less specialized for those
5276 parameters. */
5277 if (nargs < DECL_NTPARMS (maintmpl))
5279 error ("partial specialization is not more specialized than the "
5280 "primary template because it replaces multiple parameters "
5281 "with a pack expansion");
5282 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5283 /* Avoid crash in process_partial_specialization. */
5284 return decl;
5287 else if (nargs > DECL_NTPARMS (maintmpl))
5289 error ("too many arguments for partial specialization %qT", type);
5290 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5291 /* Avoid crash below. */
5292 return decl;
5295 /* If we aren't in a dependent class, we can actually try deduction. */
5296 else if (tpd.level == 1
5297 /* FIXME we should be able to handle a partial specialization of a
5298 partial instantiation, but currently we can't (c++/41727). */
5299 && TMPL_ARGS_DEPTH (specargs) == 1
5300 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5302 auto_diagnostic_group d;
5303 if (pedwarn (input_location, 0,
5304 "partial specialization %qD is not more specialized than",
5305 decl))
5306 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5307 maintmpl);
5310 /* [temp.spec.partial]
5312 The type of a template parameter corresponding to a specialized
5313 non-type argument shall not be dependent on a parameter of the
5314 specialization.
5316 Also, we verify that pack expansions only occur at the
5317 end of the argument list. */
5318 tpd2.parms = 0;
5319 for (i = 0; i < nargs; ++i)
5321 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5322 tree arg = TREE_VEC_ELT (inner_args, i);
5323 tree packed_args = NULL_TREE;
5324 int j, len = 1;
5326 if (ARGUMENT_PACK_P (arg))
5328 /* Extract the arguments from the argument pack. We'll be
5329 iterating over these in the following loop. */
5330 packed_args = ARGUMENT_PACK_ARGS (arg);
5331 len = TREE_VEC_LENGTH (packed_args);
5334 for (j = 0; j < len; j++)
5336 if (packed_args)
5337 /* Get the Jth argument in the parameter pack. */
5338 arg = TREE_VEC_ELT (packed_args, j);
5340 if (PACK_EXPANSION_P (arg))
5342 /* Pack expansions must come at the end of the
5343 argument list. */
5344 if ((packed_args && j < len - 1)
5345 || (!packed_args && i < nargs - 1))
5347 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5348 error ("parameter pack argument %qE must be at the "
5349 "end of the template argument list", arg);
5350 else
5351 error ("parameter pack argument %qT must be at the "
5352 "end of the template argument list", arg);
5356 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5357 /* We only care about the pattern. */
5358 arg = PACK_EXPANSION_PATTERN (arg);
5360 if (/* These first two lines are the `non-type' bit. */
5361 !TYPE_P (arg)
5362 && TREE_CODE (arg) != TEMPLATE_DECL
5363 /* This next two lines are the `argument expression is not just a
5364 simple identifier' condition and also the `specialized
5365 non-type argument' bit. */
5366 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5367 && !((REFERENCE_REF_P (arg)
5368 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5369 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5371 /* Look at the corresponding template parameter,
5372 marking which template parameters its type depends
5373 upon. */
5374 tree type = TREE_TYPE (parm);
5376 if (!tpd2.parms)
5378 /* We haven't yet initialized TPD2. Do so now. */
5379 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5380 /* The number of parameters here is the number in the
5381 main template, which, as checked in the assertion
5382 above, is NARGS. */
5383 tpd2.parms = XALLOCAVEC (int, nargs);
5384 tpd2.level =
5385 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5388 /* Mark the template parameters. But this time, we're
5389 looking for the template parameters of the main
5390 template, not in the specialization. */
5391 tpd2.current_arg = i;
5392 tpd2.arg_uses_template_parms[i] = 0;
5393 memset (tpd2.parms, 0, sizeof (int) * nargs);
5394 for_each_template_parm (type,
5395 &mark_template_parm,
5396 &tpd2,
5397 NULL,
5398 /*include_nondeduced_p=*/false);
5400 if (tpd2.arg_uses_template_parms [i])
5402 /* The type depended on some template parameters.
5403 If they are fully specialized in the
5404 specialization, that's OK. */
5405 int j;
5406 int count = 0;
5407 for (j = 0; j < nargs; ++j)
5408 if (tpd2.parms[j] != 0
5409 && tpd.arg_uses_template_parms [j])
5410 ++count;
5411 if (count != 0)
5412 error_n (input_location, count,
5413 "type %qT of template argument %qE depends "
5414 "on a template parameter",
5415 "type %qT of template argument %qE depends "
5416 "on template parameters",
5417 type,
5418 arg);
5424 /* We should only get here once. */
5425 if (TREE_CODE (decl) == TYPE_DECL)
5426 gcc_assert (!COMPLETE_TYPE_P (type));
5428 // Build the template decl.
5429 tree tmpl = build_template_decl (decl, current_template_parms,
5430 DECL_MEMBER_TEMPLATE_P (maintmpl));
5431 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5432 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5433 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5435 /* Give template template parms a DECL_CONTEXT of the template
5436 for which they are a parameter. */
5437 for (i = 0; i < ntparms; ++i)
5439 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5440 if (TREE_CODE (parm) == TEMPLATE_DECL)
5441 DECL_CONTEXT (parm) = tmpl;
5444 if (VAR_P (decl))
5445 /* We didn't register this in check_explicit_specialization so we could
5446 wait until the constraints were set. */
5447 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5448 else
5449 associate_classtype_constraints (type);
5451 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5452 = tree_cons (specargs, tmpl,
5453 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5454 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5456 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5457 inst = TREE_CHAIN (inst))
5459 tree instance = TREE_VALUE (inst);
5460 if (TYPE_P (instance)
5461 ? (COMPLETE_TYPE_P (instance)
5462 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5463 : DECL_TEMPLATE_INSTANTIATION (instance))
5465 tree spec = most_specialized_partial_spec (instance, tf_none);
5466 tree inst_decl = (DECL_P (instance)
5467 ? instance : TYPE_NAME (instance));
5468 if (!spec)
5469 /* OK */;
5470 else if (spec == error_mark_node)
5471 permerror (input_location,
5472 "declaration of %qD ambiguates earlier template "
5473 "instantiation for %qD", decl, inst_decl);
5474 else if (TREE_VALUE (spec) == tmpl)
5475 permerror (input_location,
5476 "partial specialization of %qD after instantiation "
5477 "of %qD", decl, inst_decl);
5481 return decl;
5484 /* PARM is a template parameter of some form; return the corresponding
5485 TEMPLATE_PARM_INDEX. */
5487 static tree
5488 get_template_parm_index (tree parm)
5490 if (TREE_CODE (parm) == PARM_DECL
5491 || TREE_CODE (parm) == CONST_DECL)
5492 parm = DECL_INITIAL (parm);
5493 else if (TREE_CODE (parm) == TYPE_DECL
5494 || TREE_CODE (parm) == TEMPLATE_DECL)
5495 parm = TREE_TYPE (parm);
5496 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5497 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5498 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5499 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5500 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5501 return parm;
5504 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5505 parameter packs used by the template parameter PARM. */
5507 static void
5508 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5510 /* A type parm can't refer to another parm. */
5511 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5512 return;
5513 else if (TREE_CODE (parm) == PARM_DECL)
5515 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5516 ppd, ppd->visited);
5517 return;
5520 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5522 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5523 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5525 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5526 if (template_parameter_pack_p (p))
5527 /* Any packs in the type are expanded by this parameter. */;
5528 else
5529 fixed_parameter_pack_p_1 (p, ppd);
5533 /* PARM is a template parameter pack. Return any parameter packs used in
5534 its type or the type of any of its template parameters. If there are
5535 any such packs, it will be instantiated into a fixed template parameter
5536 list by partial instantiation rather than be fully deduced. */
5538 tree
5539 fixed_parameter_pack_p (tree parm)
5541 /* This can only be true in a member template. */
5542 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5543 return NULL_TREE;
5544 /* This can only be true for a parameter pack. */
5545 if (!template_parameter_pack_p (parm))
5546 return NULL_TREE;
5547 /* A type parm can't refer to another parm. */
5548 if (TREE_CODE (parm) == TYPE_DECL)
5549 return NULL_TREE;
5551 tree parameter_packs = NULL_TREE;
5552 struct find_parameter_pack_data ppd;
5553 ppd.parameter_packs = &parameter_packs;
5554 ppd.visited = new hash_set<tree>;
5555 ppd.type_pack_expansion_p = false;
5557 fixed_parameter_pack_p_1 (parm, &ppd);
5559 delete ppd.visited;
5560 return parameter_packs;
5563 /* Check that a template declaration's use of default arguments and
5564 parameter packs is not invalid. Here, PARMS are the template
5565 parameters. IS_PRIMARY is true if DECL is the thing declared by
5566 a primary template. IS_PARTIAL is true if DECL is a partial
5567 specialization.
5569 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5570 function template declaration or a friend class template
5571 declaration. In the function case, 1 indicates a declaration, 2
5572 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5573 emitted for extraneous default arguments.
5575 Returns TRUE if there were no errors found, FALSE otherwise. */
5577 bool
5578 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5579 bool is_partial, int is_friend_decl)
5581 const char *msg;
5582 int last_level_to_check;
5583 tree parm_level;
5584 bool no_errors = true;
5586 /* [temp.param]
5588 A default template-argument shall not be specified in a
5589 function template declaration or a function template definition, nor
5590 in the template-parameter-list of the definition of a member of a
5591 class template. */
5593 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5594 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5595 /* You can't have a function template declaration in a local
5596 scope, nor you can you define a member of a class template in a
5597 local scope. */
5598 return true;
5600 if ((TREE_CODE (decl) == TYPE_DECL
5601 && TREE_TYPE (decl)
5602 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5603 || (TREE_CODE (decl) == FUNCTION_DECL
5604 && LAMBDA_FUNCTION_P (decl)))
5605 /* A lambda doesn't have an explicit declaration; don't complain
5606 about the parms of the enclosing class. */
5607 return true;
5609 if (current_class_type
5610 && !TYPE_BEING_DEFINED (current_class_type)
5611 && DECL_LANG_SPECIFIC (decl)
5612 && DECL_DECLARES_FUNCTION_P (decl)
5613 /* If this is either a friend defined in the scope of the class
5614 or a member function. */
5615 && (DECL_FUNCTION_MEMBER_P (decl)
5616 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5617 : DECL_FRIEND_CONTEXT (decl)
5618 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5619 : false)
5620 /* And, if it was a member function, it really was defined in
5621 the scope of the class. */
5622 && (!DECL_FUNCTION_MEMBER_P (decl)
5623 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5624 /* We already checked these parameters when the template was
5625 declared, so there's no need to do it again now. This function
5626 was defined in class scope, but we're processing its body now
5627 that the class is complete. */
5628 return true;
5630 /* Core issue 226 (C++0x only): the following only applies to class
5631 templates. */
5632 if (is_primary
5633 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5635 /* [temp.param]
5637 If a template-parameter has a default template-argument, all
5638 subsequent template-parameters shall have a default
5639 template-argument supplied. */
5640 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5642 tree inner_parms = TREE_VALUE (parm_level);
5643 int ntparms = TREE_VEC_LENGTH (inner_parms);
5644 int seen_def_arg_p = 0;
5645 int i;
5647 for (i = 0; i < ntparms; ++i)
5649 tree parm = TREE_VEC_ELT (inner_parms, i);
5651 if (parm == error_mark_node)
5652 continue;
5654 if (TREE_PURPOSE (parm))
5655 seen_def_arg_p = 1;
5656 else if (seen_def_arg_p
5657 && !template_parameter_pack_p (TREE_VALUE (parm)))
5659 error ("no default argument for %qD", TREE_VALUE (parm));
5660 /* For better subsequent error-recovery, we indicate that
5661 there should have been a default argument. */
5662 TREE_PURPOSE (parm) = error_mark_node;
5663 no_errors = false;
5665 else if (!is_partial
5666 && !is_friend_decl
5667 /* Don't complain about an enclosing partial
5668 specialization. */
5669 && parm_level == parms
5670 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5671 && i < ntparms - 1
5672 && template_parameter_pack_p (TREE_VALUE (parm))
5673 /* A fixed parameter pack will be partially
5674 instantiated into a fixed length list. */
5675 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5677 /* A primary class template, primary variable template
5678 (DR 2032), or alias template can only have one
5679 parameter pack, at the end of the template
5680 parameter list. */
5682 error ("parameter pack %q+D must be at the end of the"
5683 " template parameter list", TREE_VALUE (parm));
5685 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5686 = error_mark_node;
5687 no_errors = false;
5693 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5694 || is_partial
5695 || !is_primary
5696 || is_friend_decl)
5697 /* For an ordinary class template, default template arguments are
5698 allowed at the innermost level, e.g.:
5699 template <class T = int>
5700 struct S {};
5701 but, in a partial specialization, they're not allowed even
5702 there, as we have in [temp.class.spec]:
5704 The template parameter list of a specialization shall not
5705 contain default template argument values.
5707 So, for a partial specialization, or for a function template
5708 (in C++98/C++03), we look at all of them. */
5710 else
5711 /* But, for a primary class template that is not a partial
5712 specialization we look at all template parameters except the
5713 innermost ones. */
5714 parms = TREE_CHAIN (parms);
5716 /* Figure out what error message to issue. */
5717 if (is_friend_decl == 2)
5718 msg = G_("default template arguments may not be used in function template "
5719 "friend re-declaration");
5720 else if (is_friend_decl)
5721 msg = G_("default template arguments may not be used in template "
5722 "friend declarations");
5723 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5724 msg = G_("default template arguments may not be used in function templates "
5725 "without %<-std=c++11%> or %<-std=gnu++11%>");
5726 else if (is_partial)
5727 msg = G_("default template arguments may not be used in "
5728 "partial specializations");
5729 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5730 msg = G_("default argument for template parameter for class enclosing %qD");
5731 else
5732 /* Per [temp.param]/9, "A default template-argument shall not be
5733 specified in the template-parameter-lists of the definition of
5734 a member of a class template that appears outside of the member's
5735 class.", thus if we aren't handling a member of a class template
5736 there is no need to examine the parameters. */
5737 return true;
5739 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5740 /* If we're inside a class definition, there's no need to
5741 examine the parameters to the class itself. On the one
5742 hand, they will be checked when the class is defined, and,
5743 on the other, default arguments are valid in things like:
5744 template <class T = double>
5745 struct S { template <class U> void f(U); };
5746 Here the default argument for `S' has no bearing on the
5747 declaration of `f'. */
5748 last_level_to_check = template_class_depth (current_class_type) + 1;
5749 else
5750 /* Check everything. */
5751 last_level_to_check = 0;
5753 for (parm_level = parms;
5754 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5755 parm_level = TREE_CHAIN (parm_level))
5757 tree inner_parms = TREE_VALUE (parm_level);
5758 int i;
5759 int ntparms;
5761 ntparms = TREE_VEC_LENGTH (inner_parms);
5762 for (i = 0; i < ntparms; ++i)
5764 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5765 continue;
5767 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5769 if (msg)
5771 no_errors = false;
5772 if (is_friend_decl == 2)
5773 return no_errors;
5775 error (msg, decl);
5776 msg = 0;
5779 /* Clear out the default argument so that we are not
5780 confused later. */
5781 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5785 /* At this point, if we're still interested in issuing messages,
5786 they must apply to classes surrounding the object declared. */
5787 if (msg)
5788 msg = G_("default argument for template parameter for class "
5789 "enclosing %qD");
5792 return no_errors;
5795 /* Worker for push_template_decl_real, called via
5796 for_each_template_parm. DATA is really an int, indicating the
5797 level of the parameters we are interested in. If T is a template
5798 parameter of that level, return nonzero. */
5800 static int
5801 template_parm_this_level_p (tree t, void* data)
5803 int this_level = *(int *)data;
5804 int level;
5806 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5807 level = TEMPLATE_PARM_LEVEL (t);
5808 else
5809 level = TEMPLATE_TYPE_LEVEL (t);
5810 return level == this_level;
5813 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5814 DATA is really an int, indicating the innermost outer level of parameters.
5815 If T is a template parameter of that level or further out, return
5816 nonzero. */
5818 static int
5819 template_parm_outer_level (tree t, void *data)
5821 int this_level = *(int *)data;
5822 int level;
5824 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5825 level = TEMPLATE_PARM_LEVEL (t);
5826 else
5827 level = TEMPLATE_TYPE_LEVEL (t);
5828 return level <= this_level;
5831 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5832 parameters given by current_template_args, or reuses a
5833 previously existing one, if appropriate. Returns the DECL, or an
5834 equivalent one, if it is replaced via a call to duplicate_decls.
5836 If IS_FRIEND is true, DECL is a friend declaration. */
5838 tree
5839 push_template_decl (tree decl, bool is_friend)
5841 if (decl == error_mark_node || !current_template_parms)
5842 return error_mark_node;
5844 /* See if this is a partial specialization. */
5845 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5846 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5847 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5848 || (VAR_P (decl)
5849 && DECL_LANG_SPECIFIC (decl)
5850 && DECL_TEMPLATE_SPECIALIZATION (decl)
5851 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5853 /* No surprising friend functions. */
5854 gcc_checking_assert (is_friend
5855 || !(TREE_CODE (decl) == FUNCTION_DECL
5856 && DECL_UNIQUE_FRIEND_P (decl)));
5858 tree ctx;
5859 if (is_friend)
5860 /* For a friend, we want the context of the friend, not
5861 the type of which it is a friend. */
5862 ctx = CP_DECL_CONTEXT (decl);
5863 else if (CP_DECL_CONTEXT (decl)
5864 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5865 /* In the case of a virtual function, we want the class in which
5866 it is defined. */
5867 ctx = CP_DECL_CONTEXT (decl);
5868 else
5869 /* Otherwise, if we're currently defining some class, the DECL
5870 is assumed to be a member of the class. */
5871 ctx = current_scope ();
5873 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5874 ctx = NULL_TREE;
5876 if (!DECL_CONTEXT (decl))
5877 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5879 /* See if this is a primary template. */
5880 bool is_primary = false;
5881 if (is_friend && ctx
5882 && uses_template_parms_level (ctx, current_template_depth))
5883 /* A friend template that specifies a class context, i.e.
5884 template <typename T> friend void A<T>::f();
5885 is not primary. */
5887 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5888 /* Lambdas are not primary. */
5890 else
5891 is_primary = template_parm_scope_p ();
5893 /* True if the template is a member template, in the sense of
5894 [temp.mem]. */
5895 bool member_template_p = false;
5897 if (is_primary)
5899 warning (OPT_Wtemplates, "template %qD declared", decl);
5901 if (DECL_CLASS_SCOPE_P (decl))
5902 member_template_p = true;
5904 if (TREE_CODE (decl) == TYPE_DECL
5905 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5907 error ("template class without a name");
5908 return error_mark_node;
5910 else if (TREE_CODE (decl) == FUNCTION_DECL)
5912 if (member_template_p)
5914 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5915 error ("member template %qD may not have virt-specifiers", decl);
5917 if (DECL_DESTRUCTOR_P (decl))
5919 /* [temp.mem]
5921 A destructor shall not be a member template. */
5922 error_at (DECL_SOURCE_LOCATION (decl),
5923 "destructor %qD declared as member template", decl);
5924 return error_mark_node;
5926 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5927 && (!prototype_p (TREE_TYPE (decl))
5928 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5929 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5930 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5931 == void_list_node)))
5933 /* [basic.stc.dynamic.allocation]
5935 An allocation function can be a function
5936 template. ... Template allocation functions shall
5937 have two or more parameters. */
5938 error ("invalid template declaration of %qD", decl);
5939 return error_mark_node;
5942 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5943 && CLASS_TYPE_P (TREE_TYPE (decl)))
5944 /* Class template. */;
5945 else if (TREE_CODE (decl) == TYPE_DECL
5946 && TYPE_DECL_ALIAS_P (decl))
5947 /* alias-declaration */
5948 gcc_assert (!DECL_ARTIFICIAL (decl));
5949 else if (VAR_P (decl))
5950 /* C++14 variable template. */;
5951 else if (TREE_CODE (decl) == CONCEPT_DECL)
5952 /* C++20 concept definitions. */;
5953 else
5955 error ("template declaration of %q#D", decl);
5956 return error_mark_node;
5960 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5961 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5962 || (VAR_OR_FUNCTION_DECL_P (decl)
5963 && DECL_LOCAL_DECL_P (decl))));
5965 /* Check to see that the rules regarding the use of default
5966 arguments are not being violated. We check args for a friend
5967 functions when we know whether it's a definition, introducing
5968 declaration or re-declaration. */
5969 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5970 check_default_tmpl_args (decl, current_template_parms,
5971 is_primary, is_partial, is_friend);
5973 /* Ensure that there are no parameter packs in the type of this
5974 declaration that have not been expanded. */
5975 if (TREE_CODE (decl) == FUNCTION_DECL)
5977 /* Check each of the arguments individually to see if there are
5978 any bare parameter packs. */
5979 tree type = TREE_TYPE (decl);
5980 tree arg = DECL_ARGUMENTS (decl);
5981 tree argtype = TYPE_ARG_TYPES (type);
5983 while (arg && argtype)
5985 if (!DECL_PACK_P (arg)
5986 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5988 /* This is a PARM_DECL that contains unexpanded parameter
5989 packs. We have already complained about this in the
5990 check_for_bare_parameter_packs call, so just replace
5991 these types with ERROR_MARK_NODE. */
5992 TREE_TYPE (arg) = error_mark_node;
5993 TREE_VALUE (argtype) = error_mark_node;
5996 arg = DECL_CHAIN (arg);
5997 argtype = TREE_CHAIN (argtype);
6000 /* Check for bare parameter packs in the return type and the
6001 exception specifiers. */
6002 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
6003 /* Errors were already issued, set return type to int
6004 as the frontend doesn't expect error_mark_node as
6005 the return type. */
6006 TREE_TYPE (type) = integer_type_node;
6007 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
6008 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
6010 else
6012 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
6013 ? DECL_ORIGINAL_TYPE (decl)
6014 : TREE_TYPE (decl)))
6016 TREE_TYPE (decl) = error_mark_node;
6017 return error_mark_node;
6020 if (is_partial && VAR_P (decl)
6021 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
6022 return error_mark_node;
6025 if (is_partial)
6026 return process_partial_specialization (decl);
6028 tree args = current_template_args ();
6029 tree tmpl = NULL_TREE;
6030 bool new_template_p = false;
6031 if (local_p)
6033 /* Does not get a template head. */
6034 tmpl = NULL_TREE;
6035 gcc_checking_assert (!is_primary);
6037 else if (!ctx
6038 || TREE_CODE (ctx) == FUNCTION_DECL
6039 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6040 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6041 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6042 && DECL_TEMPLATE_INFO (decl))))
6044 if (DECL_LANG_SPECIFIC (decl)
6045 && DECL_TEMPLATE_INFO (decl)
6046 && DECL_TI_TEMPLATE (decl))
6047 tmpl = DECL_TI_TEMPLATE (decl);
6048 /* If DECL is a TYPE_DECL for a class-template, then there won't
6049 be DECL_LANG_SPECIFIC. The information equivalent to
6050 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6051 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6052 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6053 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6055 /* Since a template declaration already existed for this
6056 class-type, we must be redeclaring it here. Make sure
6057 that the redeclaration is valid. */
6058 redeclare_class_template (TREE_TYPE (decl),
6059 current_template_parms,
6060 current_template_constraints ());
6061 /* We don't need to create a new TEMPLATE_DECL; just use the
6062 one we already had. */
6063 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6065 else
6067 tmpl = build_template_decl (decl, current_template_parms,
6068 member_template_p);
6069 new_template_p = true;
6071 if (DECL_LANG_SPECIFIC (decl)
6072 && DECL_TEMPLATE_SPECIALIZATION (decl))
6074 /* A specialization of a member template of a template
6075 class. */
6076 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6077 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6078 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6082 else
6084 tree a, t, current, parms;
6085 int i;
6086 tree tinfo = get_template_info (decl);
6088 if (!tinfo)
6090 error ("template definition of non-template %q#D", decl);
6091 return error_mark_node;
6094 tmpl = TI_TEMPLATE (tinfo);
6096 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6097 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6098 && DECL_TEMPLATE_SPECIALIZATION (decl)
6099 && DECL_MEMBER_TEMPLATE_P (tmpl))
6101 /* The declaration is a specialization of a member
6102 template, declared outside the class. Therefore, the
6103 innermost template arguments will be NULL, so we
6104 replace them with the arguments determined by the
6105 earlier call to check_explicit_specialization. */
6106 args = DECL_TI_ARGS (decl);
6108 tree new_tmpl
6109 = build_template_decl (decl, current_template_parms,
6110 member_template_p);
6111 DECL_TI_TEMPLATE (decl) = new_tmpl;
6112 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6113 DECL_TEMPLATE_INFO (new_tmpl)
6114 = build_template_info (tmpl, args);
6116 register_specialization (new_tmpl,
6117 most_general_template (tmpl),
6118 args,
6119 is_friend, 0);
6120 return decl;
6123 /* Make sure the template headers we got make sense. */
6125 parms = DECL_TEMPLATE_PARMS (tmpl);
6126 i = TMPL_PARMS_DEPTH (parms);
6127 if (TMPL_ARGS_DEPTH (args) != i)
6129 error ("expected %d levels of template parms for %q#D, got %d",
6130 i, decl, TMPL_ARGS_DEPTH (args));
6131 DECL_INTERFACE_KNOWN (decl) = 1;
6132 return error_mark_node;
6134 else
6135 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6137 a = TMPL_ARGS_LEVEL (args, i);
6138 t = INNERMOST_TEMPLATE_PARMS (parms);
6140 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6142 if (current == decl)
6143 error ("got %d template parameters for %q#D",
6144 TREE_VEC_LENGTH (a), decl);
6145 else
6146 error ("got %d template parameters for %q#T",
6147 TREE_VEC_LENGTH (a), current);
6148 error (" but %d required", TREE_VEC_LENGTH (t));
6149 /* Avoid crash in import_export_decl. */
6150 DECL_INTERFACE_KNOWN (decl) = 1;
6151 return error_mark_node;
6154 if (current == decl)
6155 current = ctx;
6156 else if (current == NULL_TREE)
6157 /* Can happen in erroneous input. */
6158 break;
6159 else
6160 current = get_containing_scope (current);
6163 /* Check that the parms are used in the appropriate qualifying scopes
6164 in the declarator. */
6165 if (!comp_template_args
6166 (TI_ARGS (tinfo),
6167 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6169 error ("template arguments to %qD do not match original "
6170 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6171 if (!uses_template_parms (TI_ARGS (tinfo)))
6172 inform (input_location, "use %<template<>%> for"
6173 " an explicit specialization");
6174 /* Avoid crash in import_export_decl. */
6175 DECL_INTERFACE_KNOWN (decl) = 1;
6176 return error_mark_node;
6180 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6182 if (new_template_p)
6184 /* Push template declarations for global functions and types.
6185 Note that we do not try to push a global template friend
6186 declared in a template class; such a thing may well depend on
6187 the template parameters of the class and we'll push it when
6188 instantiating the befriending class. */
6189 if (!ctx
6190 && !(is_friend && template_class_depth (current_class_type) > 0))
6192 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6193 if (pushed == error_mark_node)
6194 return error_mark_node;
6196 /* pushdecl may have found an existing template. */
6197 if (pushed != tmpl)
6199 decl = DECL_TEMPLATE_RESULT (pushed);
6200 tmpl = NULL_TREE;
6203 else if (is_friend)
6205 /* Record this decl as belonging to the current class. It's
6206 not chained onto anything else. */
6207 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6208 gcc_checking_assert (!DECL_CHAIN (tmpl));
6209 DECL_CHAIN (tmpl) = current_scope ();
6212 else if (tmpl)
6213 /* The type may have been completed, or (erroneously) changed. */
6214 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6216 if (tmpl)
6218 if (is_primary)
6220 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6222 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6224 /* Give template template parms a DECL_CONTEXT of the template
6225 for which they are a parameter. */
6226 parms = INNERMOST_TEMPLATE_PARMS (parms);
6227 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6229 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6230 if (TREE_CODE (parm) == TEMPLATE_DECL)
6231 DECL_CONTEXT (parm) = tmpl;
6234 if (TREE_CODE (decl) == TYPE_DECL
6235 && TYPE_DECL_ALIAS_P (decl))
6237 if (tree constr
6238 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6240 /* ??? Why don't we do this here for all templates? */
6241 constr = build_constraints (constr, NULL_TREE);
6242 set_constraints (decl, constr);
6244 if (complex_alias_template_p (tmpl))
6245 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6249 /* The DECL_TI_ARGS of DECL contains full set of arguments
6250 referring wback to its most general template. If TMPL is a
6251 specialization, ARGS may only have the innermost set of
6252 arguments. Add the missing argument levels if necessary. */
6253 if (DECL_TEMPLATE_INFO (tmpl))
6254 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6256 tree info = build_template_info (tmpl, args);
6258 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6259 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6260 else
6262 retrofit_lang_decl (decl);
6263 DECL_TEMPLATE_INFO (decl) = info;
6267 if (flag_implicit_templates
6268 && !is_friend
6269 && TREE_PUBLIC (decl)
6270 && VAR_OR_FUNCTION_DECL_P (decl))
6271 /* Set DECL_COMDAT on template instantiations; if we force
6272 them to be emitted by explicit instantiation,
6273 mark_needed will tell cgraph to do the right thing. */
6274 DECL_COMDAT (decl) = true;
6276 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6278 return decl;
6281 /* FN is an inheriting constructor that inherits from the constructor
6282 template INHERITED; turn FN into a constructor template with a matching
6283 template header. */
6285 tree
6286 add_inherited_template_parms (tree fn, tree inherited)
6288 tree inner_parms
6289 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6290 inner_parms = copy_node (inner_parms);
6291 tree parms
6292 = tree_cons (size_int (current_template_depth + 1),
6293 inner_parms, current_template_parms);
6294 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6295 tree args = template_parms_to_args (parms);
6296 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6297 DECL_ARTIFICIAL (tmpl) = true;
6298 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6299 return tmpl;
6302 /* Called when a class template TYPE is redeclared with the indicated
6303 template PARMS, e.g.:
6305 template <class T> struct S;
6306 template <class T> struct S {}; */
6308 bool
6309 redeclare_class_template (tree type, tree parms, tree cons)
6311 tree tmpl;
6312 tree tmpl_parms;
6313 int i;
6315 if (!TYPE_TEMPLATE_INFO (type))
6317 error ("%qT is not a template type", type);
6318 return false;
6321 tmpl = TYPE_TI_TEMPLATE (type);
6322 if (!PRIMARY_TEMPLATE_P (tmpl))
6323 /* The type is nested in some template class. Nothing to worry
6324 about here; there are no new template parameters for the nested
6325 type. */
6326 return true;
6328 if (!parms)
6330 error ("template specifiers not specified in declaration of %qD",
6331 tmpl);
6332 return false;
6335 parms = INNERMOST_TEMPLATE_PARMS (parms);
6336 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6338 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6340 error_n (input_location, TREE_VEC_LENGTH (parms),
6341 "redeclared with %d template parameter",
6342 "redeclared with %d template parameters",
6343 TREE_VEC_LENGTH (parms));
6344 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6345 "previous declaration %qD used %d template parameter",
6346 "previous declaration %qD used %d template parameters",
6347 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6348 return false;
6351 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6353 tree tmpl_parm;
6354 tree parm;
6356 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6357 || TREE_VEC_ELT (parms, i) == error_mark_node)
6358 continue;
6360 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6361 if (error_operand_p (tmpl_parm))
6362 return false;
6364 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6366 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6367 TEMPLATE_DECL. */
6368 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6369 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6370 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6371 || (TREE_CODE (tmpl_parm) != PARM_DECL
6372 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6373 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6374 || (TREE_CODE (tmpl_parm) == PARM_DECL
6375 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6376 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6378 auto_diagnostic_group d;
6379 error ("template parameter %q+#D", tmpl_parm);
6380 if (DECL_P (parm))
6381 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6382 else
6383 inform (input_location, "redeclared here");
6384 return false;
6387 /* The parameters can be declared to introduce different
6388 constraints. */
6389 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6390 tree p2 = TREE_VEC_ELT (parms, i);
6391 if (!template_parameter_constraints_equivalent_p (p1, p2))
6393 auto_diagnostic_group d;
6394 error ("declaration of template parameter %q+#D with different "
6395 "constraints", parm);
6396 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6397 "original declaration appeared here");
6398 return false;
6401 /* Give each template template parm in this redeclaration a
6402 DECL_CONTEXT of the template for which they are a parameter. */
6403 if (TREE_CODE (parm) == TEMPLATE_DECL)
6405 gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6406 DECL_CONTEXT (parm) = tmpl;
6410 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6411 return false;
6413 tree ci = get_constraints (tmpl);
6414 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6415 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6417 /* Two classes with different constraints declare different entities. */
6418 if (!cp_tree_equal (req1, req2))
6420 auto_diagnostic_group d;
6421 error_at (input_location, "redeclaration %q#D with different "
6422 "constraints", tmpl);
6423 inform (DECL_SOURCE_LOCATION (tmpl),
6424 "original declaration appeared here");
6425 return false;
6428 return true;
6431 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6432 to be used when the caller has already checked
6433 !instantiation_dependent_uneval_expression_p (expr)
6434 and cleared processing_template_decl. */
6436 tree
6437 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6439 return tsubst_copy_and_build (expr,
6440 /*args=*/NULL_TREE,
6441 complain,
6442 /*in_decl=*/NULL_TREE,
6443 /*function_p=*/false,
6444 /*integral_constant_expression_p=*/true);
6447 /* Instantiate the non-dependent expression EXPR. */
6449 tree
6450 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6452 if (expr == NULL_TREE)
6453 return NULL_TREE;
6455 if (processing_template_decl)
6457 /* The caller should have checked this already. */
6458 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6459 processing_template_decl_sentinel s;
6460 expr = instantiate_non_dependent_expr_internal (expr, complain);
6462 return expr;
6465 tree
6466 instantiate_non_dependent_expr (tree expr)
6468 return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6471 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6472 expression is dependent or non-constant. */
6474 tree
6475 instantiate_non_dependent_or_null (tree expr)
6477 if (expr == NULL_TREE)
6478 return NULL_TREE;
6479 if (processing_template_decl)
6481 if (!is_nondependent_constant_expression (expr))
6482 expr = NULL_TREE;
6483 else
6485 processing_template_decl_sentinel s;
6486 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6489 return expr;
6492 /* True iff T is a specialization of a variable template. */
6494 bool
6495 variable_template_specialization_p (tree t)
6497 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6498 return false;
6499 tree tmpl = DECL_TI_TEMPLATE (t);
6500 return variable_template_p (tmpl);
6503 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6504 template declaration, or a TYPE_DECL for an alias declaration. */
6506 bool
6507 alias_type_or_template_p (tree t)
6509 if (t == NULL_TREE)
6510 return false;
6511 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6512 || (TYPE_P (t)
6513 && TYPE_NAME (t)
6514 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6515 || DECL_ALIAS_TEMPLATE_P (t));
6518 /* If T is a specialization of an alias template, return it; otherwise return
6519 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6521 tree
6522 alias_template_specialization_p (const_tree t,
6523 bool transparent_typedefs)
6525 if (!TYPE_P (t))
6526 return NULL_TREE;
6528 /* It's an alias template specialization if it's an alias and its
6529 TYPE_NAME is a specialization of a primary template. */
6530 if (typedef_variant_p (t))
6532 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6533 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6534 return CONST_CAST_TREE (t);
6535 if (transparent_typedefs)
6536 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6537 (TYPE_NAME (t)),
6538 transparent_typedefs);
6541 return NULL_TREE;
6544 /* Data structure for complex_alias_template_*. */
6546 struct uses_all_template_parms_data
6548 int level;
6549 bool *seen;
6552 /* walk_tree callback for complex_alias_template_p. */
6554 static tree
6555 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6557 tree t = *tp;
6558 auto &data = *(struct uses_all_template_parms_data*)data_;
6560 switch (TREE_CODE (t))
6562 case TEMPLATE_TYPE_PARM:
6563 case TEMPLATE_PARM_INDEX:
6564 case TEMPLATE_TEMPLATE_PARM:
6565 case BOUND_TEMPLATE_TEMPLATE_PARM:
6567 tree idx = get_template_parm_index (t);
6568 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6569 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6572 default:;
6575 if (!PACK_EXPANSION_P (t))
6576 return 0;
6578 /* An alias template with a pack expansion that expands a pack from the
6579 enclosing class needs to be considered complex, to avoid confusion with
6580 the same pack being used as an argument to the alias's own template
6581 parameter (91966). */
6582 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6583 pack = TREE_CHAIN (pack))
6585 tree parm_pack = TREE_VALUE (pack);
6586 if (!TEMPLATE_PARM_P (parm_pack))
6587 continue;
6588 int idx, level;
6589 template_parm_level_and_index (parm_pack, &level, &idx);
6590 if (level < data.level)
6591 return t;
6593 /* Consider the expanded packs to be used outside the expansion... */
6594 data.seen[idx] = true;
6597 /* ...but don't walk into the pattern. Consider PR104008:
6599 template <typename T, typename... Ts>
6600 using IsOneOf = disjunction<is_same<T, Ts>...>;
6602 where IsOneOf seemingly uses all of its template parameters in its
6603 expansion (and does not expand a pack from the enclosing class), so the
6604 alias was not marked as complex. However, if it is used like
6605 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6606 expansion. So only Ts is considered used by the pack expansion. */
6607 *walk_subtrees = false;
6609 return 0;
6612 /* An alias template is complex from a SFINAE perspective if a template-id
6613 using that alias can be ill-formed when the expansion is not, as with
6614 the void_t template.
6616 Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6617 template arguments are empty packs. */
6619 static bool
6620 complex_alias_template_p (const_tree tmpl)
6622 /* A renaming alias isn't complex. */
6623 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6624 return false;
6626 /* Any other constrained alias is complex. */
6627 if (get_constraints (tmpl))
6628 return true;
6630 struct uses_all_template_parms_data data;
6631 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6632 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6633 data.level = TMPL_PARMS_DEPTH (parms);
6634 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6635 data.seen = XALLOCAVEC (bool, len);
6636 for (int i = 0; i < len; ++i)
6637 data.seen[i] = false;
6639 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6640 return true;
6641 for (int i = 0; i < len; ++i)
6642 if (!data.seen[i])
6643 return true;
6644 return false;
6647 /* If T is a specialization of a complex alias template with dependent
6648 template-arguments, return it; otherwise return NULL_TREE. If T is a
6649 typedef to such a specialization, return the specialization. */
6651 tree
6652 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6654 if (t == error_mark_node)
6655 return NULL_TREE;
6656 gcc_assert (TYPE_P (t));
6658 if (!typedef_variant_p (t))
6659 return NULL_TREE;
6661 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6662 if (tinfo
6663 && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6664 && (any_dependent_template_arguments_p
6665 (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6666 return CONST_CAST_TREE (t);
6668 if (transparent_typedefs)
6670 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6671 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6674 return NULL_TREE;
6677 /* Return the number of innermost template parameters in TMPL. */
6679 static int
6680 num_innermost_template_parms (const_tree tmpl)
6682 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6683 return TREE_VEC_LENGTH (parms);
6686 /* Return either TMPL or another template that it is equivalent to under DR
6687 1286: An alias that just changes the name of a template is equivalent to
6688 the other template. */
6690 static tree
6691 get_underlying_template (tree tmpl)
6693 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6694 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6696 /* Determine if the alias is equivalent to an underlying template. */
6697 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6698 /* The underlying type may have been ill-formed. Don't proceed. */
6699 if (!orig_type)
6700 break;
6701 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6702 if (!tinfo)
6703 break;
6705 tree underlying = TI_TEMPLATE (tinfo);
6706 if (!PRIMARY_TEMPLATE_P (underlying)
6707 || (num_innermost_template_parms (tmpl)
6708 != num_innermost_template_parms (underlying)))
6709 break;
6711 /* Does the alias add cv-quals? */
6712 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6713 break;
6715 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6716 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6717 break;
6719 /* Are any default template arguments equivalent? */
6720 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6721 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6722 const int nparms = TREE_VEC_LENGTH (aparms);
6723 for (int i = 0; i < nparms; ++i)
6725 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6726 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6727 if (!template_args_equal (adefarg, udefarg))
6728 goto top_break;
6731 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6732 it's appropriate to treat a less-constrained alias as equivalent. */
6733 if (!at_least_as_constrained (underlying, tmpl))
6734 break;
6736 /* Alias is equivalent. Strip it and repeat. */
6737 tmpl = underlying;
6739 top_break:;
6741 return tmpl;
6744 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6745 must be a reference-to-function or a pointer-to-function type, as specified
6746 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6747 and check that the resulting function has external linkage. */
6749 static tree
6750 convert_nontype_argument_function (tree type, tree expr,
6751 tsubst_flags_t complain)
6753 tree fns = expr;
6754 tree fn, fn_no_ptr;
6755 linkage_kind linkage;
6757 fn = instantiate_type (type, fns, tf_none);
6758 if (fn == error_mark_node)
6759 return error_mark_node;
6761 if (value_dependent_expression_p (fn))
6762 goto accept;
6764 fn_no_ptr = fn;
6765 if (REFERENCE_REF_P (fn_no_ptr))
6766 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6767 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6768 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6769 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6770 if (BASELINK_P (fn_no_ptr))
6771 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6773 /* [temp.arg.nontype]/1
6775 A template-argument for a non-type, non-template template-parameter
6776 shall be one of:
6777 [...]
6778 -- the address of an object or function with external [C++11: or
6779 internal] linkage. */
6781 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6782 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6784 if (complain & tf_error)
6786 location_t loc = cp_expr_loc_or_input_loc (expr);
6787 error_at (loc, "%qE is not a valid template argument for type %qT",
6788 expr, type);
6789 if (TYPE_PTR_P (type))
6790 inform (loc, "it must be the address of a function "
6791 "with external linkage");
6792 else
6793 inform (loc, "it must be the name of a function with "
6794 "external linkage");
6796 return NULL_TREE;
6799 linkage = decl_linkage (fn_no_ptr);
6800 if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6802 if (complain & tf_error)
6804 location_t loc = cp_expr_loc_or_input_loc (expr);
6805 if (cxx_dialect >= cxx11)
6806 error_at (loc, "%qE is not a valid template argument for type "
6807 "%qT because %qD has no linkage",
6808 expr, type, fn_no_ptr);
6809 else
6810 error_at (loc, "%qE is not a valid template argument for type "
6811 "%qT because %qD does not have external linkage",
6812 expr, type, fn_no_ptr);
6814 return NULL_TREE;
6817 accept:
6818 if (TYPE_REF_P (type))
6820 if (REFERENCE_REF_P (fn))
6821 fn = TREE_OPERAND (fn, 0);
6822 else
6823 fn = build_address (fn);
6825 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6826 fn = build_nop (type, fn);
6828 return fn;
6831 /* Subroutine of convert_nontype_argument.
6832 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6833 Emit an error otherwise. */
6835 static bool
6836 check_valid_ptrmem_cst_expr (tree type, tree expr,
6837 tsubst_flags_t complain)
6839 tree orig_expr = expr;
6840 STRIP_NOPS (expr);
6841 if (null_ptr_cst_p (expr))
6842 return true;
6843 if (TREE_CODE (expr) == PTRMEM_CST
6844 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6845 PTRMEM_CST_CLASS (expr)))
6846 return true;
6847 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6848 return true;
6849 if (processing_template_decl
6850 && TREE_CODE (expr) == ADDR_EXPR
6851 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6852 return true;
6853 if (complain & tf_error)
6855 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6856 error_at (loc, "%qE is not a valid template argument for type %qT",
6857 orig_expr, type);
6858 if (TREE_CODE (expr) != PTRMEM_CST)
6859 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6860 else
6861 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6863 return false;
6866 /* Returns TRUE iff the address of OP is value-dependent.
6868 14.6.2.4 [temp.dep.temp]:
6869 A non-integral non-type template-argument is dependent if its type is
6870 dependent or it has either of the following forms
6871 qualified-id
6872 & qualified-id
6873 and contains a nested-name-specifier which specifies a class-name that
6874 names a dependent type.
6876 We generalize this to just say that the address of a member of a
6877 dependent class is value-dependent; the above doesn't cover the
6878 address of a static data member named with an unqualified-id. */
6880 static bool
6881 has_value_dependent_address (tree op)
6883 STRIP_ANY_LOCATION_WRAPPER (op);
6885 /* We could use get_inner_reference here, but there's no need;
6886 this is only relevant for template non-type arguments, which
6887 can only be expressed as &id-expression. */
6888 if (DECL_P (op))
6890 tree ctx = CP_DECL_CONTEXT (op);
6892 if (TYPE_P (ctx) && dependent_type_p (ctx))
6893 return true;
6895 if (VAR_P (op)
6896 && TREE_STATIC (op)
6897 && TREE_CODE (ctx) == FUNCTION_DECL
6898 && type_dependent_expression_p (ctx))
6899 return true;
6902 return false;
6905 /* The next set of functions are used for providing helpful explanatory
6906 diagnostics for failed overload resolution. Their messages should be
6907 indented by two spaces for consistency with the messages in
6908 call.cc */
6910 static int
6911 unify_success (bool /*explain_p*/)
6913 return 0;
6916 /* Other failure functions should call this one, to provide a single function
6917 for setting a breakpoint on. */
6919 static int
6920 unify_invalid (bool /*explain_p*/)
6922 return 1;
6925 static int
6926 unify_parameter_deduction_failure (bool explain_p, tree parm)
6928 if (explain_p)
6929 inform (input_location,
6930 " couldn%'t deduce template parameter %qD", parm);
6931 return unify_invalid (explain_p);
6934 static int
6935 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6937 if (explain_p)
6938 inform (input_location,
6939 " types %qT and %qT have incompatible cv-qualifiers",
6940 parm, arg);
6941 return unify_invalid (explain_p);
6944 static int
6945 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6947 if (explain_p)
6948 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6949 return unify_invalid (explain_p);
6952 static int
6953 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6955 if (explain_p)
6956 inform (input_location,
6957 " template parameter %qD is not a parameter pack, but "
6958 "argument %qD is",
6959 parm, arg);
6960 return unify_invalid (explain_p);
6963 static int
6964 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6966 if (explain_p)
6967 inform (input_location,
6968 " template argument %qE does not match "
6969 "pointer-to-member constant %qE",
6970 arg, parm);
6971 return unify_invalid (explain_p);
6974 static int
6975 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6977 if (explain_p)
6978 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6979 return unify_invalid (explain_p);
6982 static int
6983 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6985 if (explain_p)
6986 inform (input_location,
6987 " inconsistent parameter pack deduction with %qT and %qT",
6988 old_arg, new_arg);
6989 return unify_invalid (explain_p);
6992 static int
6993 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6995 if (explain_p)
6997 if (TYPE_P (parm))
6998 inform (input_location,
6999 " deduced conflicting types for parameter %qT (%qT and %qT)",
7000 parm, first, second);
7001 else
7002 inform (input_location,
7003 " deduced conflicting values for non-type parameter "
7004 "%qE (%qE and %qE)", parm, first, second);
7006 return unify_invalid (explain_p);
7009 static int
7010 unify_vla_arg (bool explain_p, tree arg)
7012 if (explain_p)
7013 inform (input_location,
7014 " variable-sized array type %qT is not "
7015 "a valid template argument",
7016 arg);
7017 return unify_invalid (explain_p);
7020 static int
7021 unify_method_type_error (bool explain_p, tree arg)
7023 if (explain_p)
7024 inform (input_location,
7025 " member function type %qT is not a valid template argument",
7026 arg);
7027 return unify_invalid (explain_p);
7030 static int
7031 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7033 if (explain_p)
7035 if (least_p)
7036 inform_n (input_location, wanted,
7037 " candidate expects at least %d argument, %d provided",
7038 " candidate expects at least %d arguments, %d provided",
7039 wanted, have);
7040 else
7041 inform_n (input_location, wanted,
7042 " candidate expects %d argument, %d provided",
7043 " candidate expects %d arguments, %d provided",
7044 wanted, have);
7046 return unify_invalid (explain_p);
7049 static int
7050 unify_too_many_arguments (bool explain_p, int have, int wanted)
7052 return unify_arity (explain_p, have, wanted);
7055 static int
7056 unify_too_few_arguments (bool explain_p, int have, int wanted,
7057 bool least_p = false)
7059 return unify_arity (explain_p, have, wanted, least_p);
7062 static int
7063 unify_arg_conversion (bool explain_p, tree to_type,
7064 tree from_type, tree arg)
7066 if (explain_p)
7067 inform (cp_expr_loc_or_input_loc (arg),
7068 " cannot convert %qE (type %qT) to type %qT",
7069 arg, from_type, to_type);
7070 return unify_invalid (explain_p);
7073 static int
7074 unify_no_common_base (bool explain_p, enum template_base_result r,
7075 tree parm, tree arg)
7077 if (explain_p)
7078 switch (r)
7080 case tbr_ambiguous_baseclass:
7081 inform (input_location, " %qT is an ambiguous base class of %qT",
7082 parm, arg);
7083 break;
7084 default:
7085 inform (input_location, " %qT is not derived from %qT", arg, parm);
7086 break;
7088 return unify_invalid (explain_p);
7091 static int
7092 unify_inconsistent_template_template_parameters (bool explain_p)
7094 if (explain_p)
7095 inform (input_location,
7096 " template parameters of a template template argument are "
7097 "inconsistent with other deduced template arguments");
7098 return unify_invalid (explain_p);
7101 static int
7102 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7104 if (explain_p)
7105 inform (input_location,
7106 " cannot deduce a template for %qT from non-template type %qT",
7107 parm, arg);
7108 return unify_invalid (explain_p);
7111 static int
7112 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7114 if (explain_p)
7115 inform (input_location,
7116 " template argument %qE does not match %qE", arg, parm);
7117 return unify_invalid (explain_p);
7120 /* True if T is a C++20 template parameter object to store the argument for a
7121 template parameter of class type. */
7123 bool
7124 template_parm_object_p (const_tree t)
7126 return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
7127 && startswith (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA"));
7130 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7131 argument for TYPE, points to an unsuitable object.
7133 Also adjust the type of the index in C++20 array subobject references. */
7135 static bool
7136 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7138 switch (TREE_CODE (expr))
7140 CASE_CONVERT:
7141 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7142 complain);
7144 case TARGET_EXPR:
7145 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7146 complain);
7148 case CONSTRUCTOR:
7150 for (auto &e: CONSTRUCTOR_ELTS (expr))
7151 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7152 return true;
7154 break;
7156 case ADDR_EXPR:
7158 tree decl = TREE_OPERAND (expr, 0);
7160 if (cxx_dialect >= cxx20)
7161 while (TREE_CODE (decl) == COMPONENT_REF
7162 || TREE_CODE (decl) == ARRAY_REF)
7164 tree &op = TREE_OPERAND (decl, 1);
7165 if (TREE_CODE (decl) == ARRAY_REF
7166 && TREE_CODE (op) == INTEGER_CST)
7167 /* Canonicalize array offsets to ptrdiff_t; how they were
7168 written doesn't matter for subobject identity. */
7169 op = fold_convert (ptrdiff_type_node, op);
7170 decl = TREE_OPERAND (decl, 0);
7173 if (!VAR_P (decl))
7175 if (complain & tf_error)
7176 error_at (cp_expr_loc_or_input_loc (expr),
7177 "%qE is not a valid template argument of type %qT "
7178 "because %qE is not a variable", expr, type, decl);
7179 return true;
7181 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7183 if (complain & tf_error)
7184 error_at (cp_expr_loc_or_input_loc (expr),
7185 "%qE is not a valid template argument of type %qT "
7186 "in C++98 because %qD does not have external linkage",
7187 expr, type, decl);
7188 return true;
7190 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7191 && decl_linkage (decl) == lk_none)
7193 if (complain & tf_error)
7194 error_at (cp_expr_loc_or_input_loc (expr),
7195 "%qE is not a valid template argument of type %qT "
7196 "because %qD has no linkage", expr, type, decl);
7197 return true;
7199 /* C++17: For a non-type template-parameter of reference or pointer
7200 type, the value of the constant expression shall not refer to (or
7201 for a pointer type, shall not be the address of):
7202 * a subobject (4.5),
7203 * a temporary object (15.2),
7204 * a string literal (5.13.5),
7205 * the result of a typeid expression (8.2.8), or
7206 * a predefined __func__ variable (11.4.1). */
7207 else if (DECL_ARTIFICIAL (decl))
7209 if (complain & tf_error)
7210 error ("the address of %qD is not a valid template argument",
7211 decl);
7212 return true;
7214 else if (cxx_dialect < cxx20
7215 && !(same_type_ignoring_top_level_qualifiers_p
7216 (strip_array_types (TREE_TYPE (type)),
7217 strip_array_types (TREE_TYPE (decl)))))
7219 if (complain & tf_error)
7220 error ("the address of the %qT subobject of %qD is not a "
7221 "valid template argument", TREE_TYPE (type), decl);
7222 return true;
7224 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7226 if (complain & tf_error)
7227 error ("the address of %qD is not a valid template argument "
7228 "because it does not have static storage duration",
7229 decl);
7230 return true;
7233 break;
7235 default:
7236 if (!INDIRECT_TYPE_P (type))
7237 /* We're only concerned about pointers and references here. */;
7238 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7239 /* Null pointer values are OK in C++11. */;
7240 else
7242 if (VAR_P (expr))
7244 if (complain & tf_error)
7245 error ("%qD is not a valid template argument "
7246 "because %qD is a variable, not the address of "
7247 "a variable", expr, expr);
7248 return true;
7250 else
7252 if (complain & tf_error)
7253 error ("%qE is not a valid template argument for %qT "
7254 "because it is not the address of a variable",
7255 expr, type);
7256 return true;
7260 return false;
7264 /* The template arguments corresponding to template parameter objects of types
7265 that contain pointers to members. */
7267 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7269 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7270 template argument EXPR. */
7272 static tree
7273 get_template_parm_object (tree expr, tsubst_flags_t complain)
7275 if (TREE_CODE (expr) == TARGET_EXPR)
7276 expr = TARGET_EXPR_INITIAL (expr);
7278 if (!TREE_CONSTANT (expr))
7280 if ((complain & tf_error)
7281 && require_rvalue_constant_expression (expr))
7282 cxx_constant_value (expr);
7283 return error_mark_node;
7285 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7286 return error_mark_node;
7288 /* This is no longer a compound literal. */
7289 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7291 tree name = mangle_template_parm_object (expr);
7292 tree decl = get_global_binding (name);
7293 if (decl)
7294 return decl;
7296 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7297 decl = create_temporary_var (type);
7298 DECL_CONTEXT (decl) = NULL_TREE;
7299 TREE_STATIC (decl) = true;
7300 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7301 TREE_READONLY (decl) = true;
7302 DECL_NAME (decl) = name;
7303 SET_DECL_ASSEMBLER_NAME (decl, name);
7304 comdat_linkage (decl);
7306 if (!zero_init_p (type))
7308 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7309 lower_var_init before we're done mangling. So store the original
7310 value elsewhere. */
7311 tree copy = unshare_constructor (expr);
7312 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7315 pushdecl_top_level_and_finish (decl, expr);
7317 return decl;
7320 /* Return the actual template argument corresponding to template parameter
7321 object VAR. */
7323 tree
7324 tparm_object_argument (tree var)
7326 if (zero_init_p (TREE_TYPE (var)))
7327 return DECL_INITIAL (var);
7328 return *(tparm_obj_values->get (var));
7331 /* Attempt to convert the non-type template parameter EXPR to the
7332 indicated TYPE. If the conversion is successful, return the
7333 converted value. If the conversion is unsuccessful, return
7334 NULL_TREE if we issued an error message, or error_mark_node if we
7335 did not. We issue error messages for out-and-out bad template
7336 parameters, but not simply because the conversion failed, since we
7337 might be just trying to do argument deduction. Both TYPE and EXPR
7338 must be non-dependent.
7340 The conversion follows the special rules described in
7341 [temp.arg.nontype], and it is much more strict than an implicit
7342 conversion.
7344 This function is called twice for each template argument (see
7345 lookup_template_class for a more accurate description of this
7346 problem). This means that we need to handle expressions which
7347 are not valid in a C++ source, but can be created from the
7348 first call (for instance, casts to perform conversions). These
7349 hacks can go away after we fix the double coercion problem. */
7351 static tree
7352 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7354 tree expr_type;
7355 location_t loc = cp_expr_loc_or_input_loc (expr);
7357 /* Detect immediately string literals as invalid non-type argument.
7358 This special-case is not needed for correctness (we would easily
7359 catch this later), but only to provide better diagnostic for this
7360 common user mistake. As suggested by DR 100, we do not mention
7361 linkage issues in the diagnostic as this is not the point. */
7362 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7364 if (complain & tf_error)
7365 error ("%qE is not a valid template argument for type %qT "
7366 "because string literals can never be used in this context",
7367 expr, type);
7368 return NULL_TREE;
7371 /* Add the ADDR_EXPR now for the benefit of
7372 value_dependent_expression_p. */
7373 if (TYPE_PTROBV_P (type)
7374 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7376 expr = decay_conversion (expr, complain);
7377 if (expr == error_mark_node)
7378 return error_mark_node;
7381 /* If we are in a template, EXPR may be non-dependent, but still
7382 have a syntactic, rather than semantic, form. For example, EXPR
7383 might be a SCOPE_REF, rather than the VAR_DECL to which the
7384 SCOPE_REF refers. Preserving the qualifying scope is necessary
7385 so that access checking can be performed when the template is
7386 instantiated -- but here we need the resolved form so that we can
7387 convert the argument. */
7388 bool non_dep = false;
7389 if (TYPE_REF_OBJ_P (type)
7390 && has_value_dependent_address (expr))
7391 /* If we want the address and it's value-dependent, don't fold. */;
7392 else if (processing_template_decl
7393 && is_nondependent_constant_expression (expr))
7394 non_dep = true;
7395 if (error_operand_p (expr))
7396 return error_mark_node;
7397 expr_type = TREE_TYPE (expr);
7399 /* If the argument is non-dependent, perform any conversions in
7400 non-dependent context as well. */
7401 processing_template_decl_sentinel s (non_dep);
7402 if (non_dep)
7403 expr = instantiate_non_dependent_expr_internal (expr, complain);
7405 bool val_dep_p = value_dependent_expression_p (expr);
7406 if (val_dep_p)
7407 expr = canonicalize_expr_argument (expr, complain);
7408 else
7409 STRIP_ANY_LOCATION_WRAPPER (expr);
7411 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7412 to a non-type argument of "nullptr". */
7413 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7414 expr = fold_simple (convert (type, expr));
7416 /* In C++11, integral or enumeration non-type template arguments can be
7417 arbitrary constant expressions. Pointer and pointer to
7418 member arguments can be general constant expressions that evaluate
7419 to a null value, but otherwise still need to be of a specific form. */
7420 if (cxx_dialect >= cxx11)
7422 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7423 /* A PTRMEM_CST is already constant, and a valid template
7424 argument for a parameter of pointer to member type, we just want
7425 to leave it in that form rather than lower it to a
7426 CONSTRUCTOR. */;
7427 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7428 || cxx_dialect >= cxx17)
7430 /* C++17: A template-argument for a non-type template-parameter shall
7431 be a converted constant expression (8.20) of the type of the
7432 template-parameter. */
7433 expr = build_converted_constant_expr (type, expr, complain);
7434 if (expr == error_mark_node)
7435 /* Make sure we return NULL_TREE only if we have really issued
7436 an error, as described above. */
7437 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7438 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7440 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7441 return expr;
7443 expr = maybe_constant_value (expr, NULL_TREE,
7444 /*manifestly_const_eval=*/true);
7445 expr = convert_from_reference (expr);
7446 /* EXPR may have become value-dependent. */
7447 val_dep_p = value_dependent_expression_p (expr);
7449 else if (TYPE_PTR_OR_PTRMEM_P (type))
7451 tree folded = maybe_constant_value (expr, NULL_TREE,
7452 /*manifestly_const_eval=*/true);
7453 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7454 : null_member_pointer_value_p (folded))
7455 expr = folded;
7459 if (TYPE_REF_P (type))
7460 expr = mark_lvalue_use (expr);
7461 else
7462 expr = mark_rvalue_use (expr);
7464 /* HACK: Due to double coercion, we can get a
7465 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7466 which is the tree that we built on the first call (see
7467 below when coercing to reference to object or to reference to
7468 function). We just strip everything and get to the arg.
7469 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7470 for examples. */
7471 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7473 /* Check this before we strip *& to avoid redundancy. */
7474 if (!mark_single_function (expr, complain))
7475 return error_mark_node;
7477 tree probe_type, probe = expr;
7478 if (REFERENCE_REF_P (probe))
7479 probe = TREE_OPERAND (probe, 0);
7480 probe_type = TREE_TYPE (probe);
7481 if (TREE_CODE (probe) == NOP_EXPR)
7483 /* ??? Maybe we could use convert_from_reference here, but we
7484 would need to relax its constraints because the NOP_EXPR
7485 could actually change the type to something more cv-qualified,
7486 and this is not folded by convert_from_reference. */
7487 tree addr = TREE_OPERAND (probe, 0);
7488 if (TYPE_REF_P (probe_type)
7489 && TREE_CODE (addr) == ADDR_EXPR
7490 && TYPE_PTR_P (TREE_TYPE (addr))
7491 && (same_type_ignoring_top_level_qualifiers_p
7492 (TREE_TYPE (probe_type),
7493 TREE_TYPE (TREE_TYPE (addr)))))
7495 expr = TREE_OPERAND (addr, 0);
7496 expr_type = TREE_TYPE (probe_type);
7501 /* [temp.arg.nontype]/5, bullet 1
7503 For a non-type template-parameter of integral or enumeration type,
7504 integral promotions (_conv.prom_) and integral conversions
7505 (_conv.integral_) are applied. */
7506 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7507 || TREE_CODE (type) == REAL_TYPE)
7509 if (cxx_dialect < cxx11)
7511 tree t = build_converted_constant_expr (type, expr, complain);
7512 t = maybe_constant_value (t);
7513 if (t != error_mark_node)
7514 expr = t;
7517 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7518 return error_mark_node;
7520 /* Notice that there are constant expressions like '4 % 0' which
7521 do not fold into integer constants. */
7522 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7524 if (complain & tf_error)
7526 int errs = errorcount, warns = warningcount + werrorcount;
7527 if (!require_potential_constant_expression (expr))
7528 expr = error_mark_node;
7529 else
7530 expr = cxx_constant_value (expr);
7531 if (errorcount > errs || warningcount + werrorcount > warns)
7532 inform (loc, "in template argument for type %qT", type);
7533 if (expr == error_mark_node)
7534 return NULL_TREE;
7535 /* else cxx_constant_value complained but gave us
7536 a real constant, so go ahead. */
7537 if (!CONSTANT_CLASS_P (expr))
7539 /* Some assemble time constant expressions like
7540 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7541 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7542 as we can emit them into .rodata initializers of
7543 variables, yet they can't fold into an INTEGER_CST at
7544 compile time. Refuse them here. */
7545 gcc_checking_assert (reduced_constant_expression_p (expr));
7546 error_at (loc, "template argument %qE for type %qT not "
7547 "a compile-time constant", expr, type);
7548 return NULL_TREE;
7551 else
7552 return NULL_TREE;
7555 /* Avoid typedef problems. */
7556 if (TREE_TYPE (expr) != type)
7557 expr = fold_convert (type, expr);
7559 /* [temp.arg.nontype]/5, bullet 2
7561 For a non-type template-parameter of type pointer to object,
7562 qualification conversions (_conv.qual_) and the array-to-pointer
7563 conversion (_conv.array_) are applied. */
7564 else if (TYPE_PTROBV_P (type))
7566 tree decayed = expr;
7568 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7569 decay_conversion or an explicit cast. If it's a problematic cast,
7570 we'll complain about it below. */
7571 if (TREE_CODE (expr) == NOP_EXPR)
7573 tree probe = expr;
7574 STRIP_NOPS (probe);
7575 if (TREE_CODE (probe) == ADDR_EXPR
7576 && TYPE_PTR_P (TREE_TYPE (probe)))
7578 expr = probe;
7579 expr_type = TREE_TYPE (expr);
7583 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7585 A template-argument for a non-type, non-template template-parameter
7586 shall be one of: [...]
7588 -- the name of a non-type template-parameter;
7589 -- the address of an object or function with external linkage, [...]
7590 expressed as "& id-expression" where the & is optional if the name
7591 refers to a function or array, or if the corresponding
7592 template-parameter is a reference.
7594 Here, we do not care about functions, as they are invalid anyway
7595 for a parameter of type pointer-to-object. */
7597 if (val_dep_p)
7598 /* Non-type template parameters are OK. */
7600 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7601 /* Null pointer values are OK in C++11. */;
7602 else if (TREE_CODE (expr) != ADDR_EXPR
7603 && !INDIRECT_TYPE_P (expr_type))
7604 /* Other values, like integer constants, might be valid
7605 non-type arguments of some other type. */
7606 return error_mark_node;
7607 else if (invalid_tparm_referent_p (type, expr, complain))
7608 return NULL_TREE;
7610 expr = decayed;
7612 expr = perform_qualification_conversions (type, expr);
7613 if (expr == error_mark_node)
7614 return error_mark_node;
7616 /* [temp.arg.nontype]/5, bullet 3
7618 For a non-type template-parameter of type reference to object, no
7619 conversions apply. The type referred to by the reference may be more
7620 cv-qualified than the (otherwise identical) type of the
7621 template-argument. The template-parameter is bound directly to the
7622 template-argument, which must be an lvalue. */
7623 else if (TYPE_REF_OBJ_P (type))
7625 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7626 expr_type))
7627 return error_mark_node;
7629 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7631 if (complain & tf_error)
7632 error ("%qE is not a valid template argument for type %qT "
7633 "because of conflicts in cv-qualification", expr, type);
7634 return NULL_TREE;
7637 if (!lvalue_p (expr))
7639 if (complain & tf_error)
7640 error ("%qE is not a valid template argument for type %qT "
7641 "because it is not an lvalue", expr, type);
7642 return NULL_TREE;
7645 /* [temp.arg.nontype]/1
7647 A template-argument for a non-type, non-template template-parameter
7648 shall be one of: [...]
7650 -- the address of an object or function with external linkage. */
7651 if (INDIRECT_REF_P (expr)
7652 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7654 expr = TREE_OPERAND (expr, 0);
7655 if (DECL_P (expr))
7657 if (complain & tf_error)
7658 error ("%q#D is not a valid template argument for type %qT "
7659 "because a reference variable does not have a constant "
7660 "address", expr, type);
7661 return NULL_TREE;
7665 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7666 /* OK, dependent reference. We don't want to ask whether a DECL is
7667 itself value-dependent, since what we want here is its address. */;
7668 else
7670 expr = build_address (expr);
7672 if (invalid_tparm_referent_p (type, expr, complain))
7673 return NULL_TREE;
7676 if (!same_type_p (type, TREE_TYPE (expr)))
7677 expr = build_nop (type, expr);
7679 /* [temp.arg.nontype]/5, bullet 4
7681 For a non-type template-parameter of type pointer to function, only
7682 the function-to-pointer conversion (_conv.func_) is applied. If the
7683 template-argument represents a set of overloaded functions (or a
7684 pointer to such), the matching function is selected from the set
7685 (_over.over_). */
7686 else if (TYPE_PTRFN_P (type))
7688 /* If the argument is a template-id, we might not have enough
7689 context information to decay the pointer. */
7690 if (!type_unknown_p (expr_type))
7692 expr = decay_conversion (expr, complain);
7693 if (expr == error_mark_node)
7694 return error_mark_node;
7697 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7698 /* Null pointer values are OK in C++11. */
7699 return perform_qualification_conversions (type, expr);
7701 expr = convert_nontype_argument_function (type, expr, complain);
7702 if (!expr || expr == error_mark_node)
7703 return expr;
7705 /* [temp.arg.nontype]/5, bullet 5
7707 For a non-type template-parameter of type reference to function, no
7708 conversions apply. If the template-argument represents a set of
7709 overloaded functions, the matching function is selected from the set
7710 (_over.over_). */
7711 else if (TYPE_REFFN_P (type))
7713 if (TREE_CODE (expr) == ADDR_EXPR)
7715 if (complain & tf_error)
7717 error ("%qE is not a valid template argument for type %qT "
7718 "because it is a pointer", expr, type);
7719 inform (input_location, "try using %qE instead",
7720 TREE_OPERAND (expr, 0));
7722 return NULL_TREE;
7725 expr = convert_nontype_argument_function (type, expr, complain);
7726 if (!expr || expr == error_mark_node)
7727 return expr;
7729 /* [temp.arg.nontype]/5, bullet 6
7731 For a non-type template-parameter of type pointer to member function,
7732 no conversions apply. If the template-argument represents a set of
7733 overloaded member functions, the matching member function is selected
7734 from the set (_over.over_). */
7735 else if (TYPE_PTRMEMFUNC_P (type))
7737 expr = instantiate_type (type, expr, tf_none);
7738 if (expr == error_mark_node)
7739 return error_mark_node;
7741 /* [temp.arg.nontype] bullet 1 says the pointer to member
7742 expression must be a pointer-to-member constant. */
7743 if (!val_dep_p
7744 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7745 return NULL_TREE;
7747 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7748 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7749 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7750 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7752 /* [temp.arg.nontype]/5, bullet 7
7754 For a non-type template-parameter of type pointer to data member,
7755 qualification conversions (_conv.qual_) are applied. */
7756 else if (TYPE_PTRDATAMEM_P (type))
7758 /* [temp.arg.nontype] bullet 1 says the pointer to member
7759 expression must be a pointer-to-member constant. */
7760 if (!val_dep_p
7761 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7762 return NULL_TREE;
7764 expr = perform_qualification_conversions (type, expr);
7765 if (expr == error_mark_node)
7766 return expr;
7768 else if (NULLPTR_TYPE_P (type))
7770 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7772 if (complain & tf_error)
7773 error ("%qE is not a valid template argument for type %qT "
7774 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7775 return NULL_TREE;
7777 return expr;
7779 else if (CLASS_TYPE_P (type))
7781 /* Replace the argument with a reference to the corresponding template
7782 parameter object. */
7783 if (!val_dep_p)
7784 expr = get_template_parm_object (expr, complain);
7785 if (expr == error_mark_node)
7786 return NULL_TREE;
7788 /* A template non-type parameter must be one of the above. */
7789 else
7790 gcc_unreachable ();
7792 /* Sanity check: did we actually convert the argument to the
7793 right type? */
7794 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7795 (type, TREE_TYPE (expr)));
7796 return convert_from_reference (expr);
7799 /* Subroutine of coerce_template_template_parms, which returns 1 if
7800 PARM_PARM and ARG_PARM match using the rule for the template
7801 parameters of template template parameters. Both PARM and ARG are
7802 template parameters; the rest of the arguments are the same as for
7803 coerce_template_template_parms.
7805 static int
7806 coerce_template_template_parm (tree parm,
7807 tree arg,
7808 tsubst_flags_t complain,
7809 tree in_decl,
7810 tree outer_args)
7812 if (arg == NULL_TREE || error_operand_p (arg)
7813 || parm == NULL_TREE || error_operand_p (parm))
7814 return 0;
7816 if (TREE_CODE (arg) != TREE_CODE (parm))
7817 return 0;
7819 switch (TREE_CODE (parm))
7821 case TEMPLATE_DECL:
7822 /* We encounter instantiations of templates like
7823 template <template <template <class> class> class TT>
7824 class C; */
7826 tree parmparm = DECL_TEMPLATE_PARMS (parm);
7827 tree argparm = DECL_TEMPLATE_PARMS (arg);
7829 if (!coerce_template_template_parms
7830 (parmparm, argparm, complain, in_decl, outer_args))
7831 return 0;
7833 /* Fall through. */
7835 case TYPE_DECL:
7836 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7837 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7838 /* Argument is a parameter pack but parameter is not. */
7839 return 0;
7840 break;
7842 case PARM_DECL:
7843 /* The tsubst call is used to handle cases such as
7845 template <int> class C {};
7846 template <class T, template <T> class TT> class D {};
7847 D<int, C> d;
7849 i.e. the parameter list of TT depends on earlier parameters. */
7850 if (!uses_template_parms (TREE_TYPE (arg)))
7852 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7853 if (!uses_template_parms (t)
7854 && !same_type_p (t, TREE_TYPE (arg)))
7855 return 0;
7858 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7859 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7860 /* Argument is a parameter pack but parameter is not. */
7861 return 0;
7863 break;
7865 default:
7866 gcc_unreachable ();
7869 return 1;
7872 /* Coerce template argument list ARGLIST for use with template
7873 template-parameter TEMPL. */
7875 static tree
7876 coerce_template_args_for_ttp (tree templ, tree arglist,
7877 tsubst_flags_t complain)
7879 /* Consider an example where a template template parameter declared as
7881 template <class T, class U = std::allocator<T> > class TT
7883 The template parameter level of T and U are one level larger than
7884 of TT. To proper process the default argument of U, say when an
7885 instantiation `TT<int>' is seen, we need to build the full
7886 arguments containing {int} as the innermost level. Outer levels,
7887 available when not appearing as default template argument, can be
7888 obtained from the arguments of the enclosing template.
7890 Suppose that TT is later substituted with std::vector. The above
7891 instantiation is `TT<int, std::allocator<T> >' with TT at
7892 level 1, and T at level 2, while the template arguments at level 1
7893 becomes {std::vector} and the inner level 2 is {int}. */
7895 tree outer = DECL_CONTEXT (templ);
7896 if (outer)
7897 outer = generic_targs_for (outer);
7898 else if (current_template_parms)
7900 /* This is an argument of the current template, so we haven't set
7901 DECL_CONTEXT yet. */
7902 tree relevant_template_parms;
7904 /* Parameter levels that are greater than the level of the given
7905 template template parm are irrelevant. */
7906 relevant_template_parms = current_template_parms;
7907 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7908 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7909 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7911 outer = template_parms_to_args (relevant_template_parms);
7914 if (outer)
7915 arglist = add_to_template_args (outer, arglist);
7917 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7918 return coerce_template_parms (parmlist, arglist, templ,
7919 complain,
7920 /*require_all_args=*/true,
7921 /*use_default_args=*/true);
7924 /* A cache of template template parameters with match-all default
7925 arguments. */
7926 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7928 /* T is a bound template template-parameter. Copy its arguments into default
7929 arguments of the template template-parameter's template parameters. */
7931 static tree
7932 add_defaults_to_ttp (tree otmpl)
7934 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7935 return *c;
7937 tree ntmpl = copy_node (otmpl);
7939 tree ntype = copy_node (TREE_TYPE (otmpl));
7940 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7941 TYPE_MAIN_VARIANT (ntype) = ntype;
7942 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7943 TYPE_NAME (ntype) = ntmpl;
7944 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7946 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7947 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7948 TEMPLATE_PARM_DECL (idx) = ntmpl;
7949 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7951 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7952 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7953 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7954 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7955 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7957 tree o = TREE_VEC_ELT (vec, i);
7958 if (!template_parameter_pack_p (TREE_VALUE (o)))
7960 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7961 TREE_PURPOSE (n) = any_targ_node;
7965 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7966 return ntmpl;
7969 /* ARG is a bound potential template template-argument, and PARGS is a list
7970 of arguments for the corresponding template template-parameter. Adjust
7971 PARGS as appropriate for application to ARG's template, and if ARG is a
7972 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7973 arguments to the template template parameter. */
7975 static tree
7976 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7978 ++processing_template_decl;
7979 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7980 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7982 /* When comparing two template template-parameters in partial ordering,
7983 rewrite the one currently being used as an argument to have default
7984 arguments for all parameters. */
7985 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7986 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7987 if (pargs != error_mark_node)
7988 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7989 TYPE_TI_ARGS (arg));
7991 else
7993 tree aparms
7994 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7995 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7996 /*require_all*/true,
7997 /*use_default*/true);
7999 --processing_template_decl;
8000 return pargs;
8003 /* Subroutine of unify for the case when PARM is a
8004 BOUND_TEMPLATE_TEMPLATE_PARM. */
8006 static int
8007 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
8008 bool explain_p)
8010 tree parmvec = TYPE_TI_ARGS (parm);
8011 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
8013 /* The template template parm might be variadic and the argument
8014 not, so flatten both argument lists. */
8015 parmvec = expand_template_argument_pack (parmvec);
8016 argvec = expand_template_argument_pack (argvec);
8018 if (flag_new_ttp)
8020 /* In keeping with P0522R0, adjust P's template arguments
8021 to apply to A's template; then flatten it again. */
8022 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
8023 nparmvec = expand_template_argument_pack (nparmvec);
8025 if (unify (tparms, targs, nparmvec, argvec,
8026 UNIFY_ALLOW_NONE, explain_p))
8027 return 1;
8029 /* If the P0522 adjustment eliminated a pack expansion, deduce
8030 empty packs. */
8031 if (flag_new_ttp
8032 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8033 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8034 DEDUCE_EXACT, /*sub*/true, explain_p))
8035 return 1;
8037 else
8039 /* Deduce arguments T, i from TT<T> or TT<i>.
8040 We check each element of PARMVEC and ARGVEC individually
8041 rather than the whole TREE_VEC since they can have
8042 different number of elements, which is allowed under N2555. */
8044 int len = TREE_VEC_LENGTH (parmvec);
8046 /* Check if the parameters end in a pack, making them
8047 variadic. */
8048 int parm_variadic_p = 0;
8049 if (len > 0
8050 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8051 parm_variadic_p = 1;
8053 for (int i = 0; i < len - parm_variadic_p; ++i)
8054 /* If the template argument list of P contains a pack
8055 expansion that is not the last template argument, the
8056 entire template argument list is a non-deduced
8057 context. */
8058 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8059 return unify_success (explain_p);
8061 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8062 return unify_too_few_arguments (explain_p,
8063 TREE_VEC_LENGTH (argvec), len);
8065 for (int i = 0; i < len - parm_variadic_p; ++i)
8066 if (unify (tparms, targs,
8067 TREE_VEC_ELT (parmvec, i),
8068 TREE_VEC_ELT (argvec, i),
8069 UNIFY_ALLOW_NONE, explain_p))
8070 return 1;
8072 if (parm_variadic_p
8073 && unify_pack_expansion (tparms, targs,
8074 parmvec, argvec,
8075 DEDUCE_EXACT,
8076 /*subr=*/true, explain_p))
8077 return 1;
8080 return 0;
8083 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
8084 template template parameters. Both PARM_PARMS and ARG_PARMS are
8085 vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
8086 or PARM_DECL.
8088 Consider the example:
8089 template <class T> class A;
8090 template<template <class U> class TT> class B;
8092 For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
8093 the parameters to A, and OUTER_ARGS contains A. */
8095 static int
8096 coerce_template_template_parms (tree parm_parms_full,
8097 tree arg_parms_full,
8098 tsubst_flags_t complain,
8099 tree in_decl,
8100 tree outer_args)
8102 int nparms, nargs, i;
8103 tree parm, arg;
8104 int variadic_p = 0;
8106 tree parm_parms = INNERMOST_TEMPLATE_PARMS (parm_parms_full);
8107 tree arg_parms = INNERMOST_TEMPLATE_PARMS (arg_parms_full);
8109 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
8110 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
8112 nparms = TREE_VEC_LENGTH (parm_parms);
8113 nargs = TREE_VEC_LENGTH (arg_parms);
8115 if (flag_new_ttp)
8117 /* P0522R0: A template template-parameter P is at least as specialized as
8118 a template template-argument A if, given the following rewrite to two
8119 function templates, the function template corresponding to P is at
8120 least as specialized as the function template corresponding to A
8121 according to the partial ordering rules for function templates
8122 ([temp.func.order]). Given an invented class template X with the
8123 template parameter list of A (including default arguments):
8125 * Each of the two function templates has the same template parameters,
8126 respectively, as P or A.
8128 * Each function template has a single function parameter whose type is
8129 a specialization of X with template arguments corresponding to the
8130 template parameters from the respective function template where, for
8131 each template parameter PP in the template parameter list of the
8132 function template, a corresponding template argument AA is formed. If
8133 PP declares a parameter pack, then AA is the pack expansion
8134 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8136 If the rewrite produces an invalid type, then P is not at least as
8137 specialized as A. */
8139 /* So coerce P's args to apply to A's parms, and then deduce between A's
8140 args and the converted args. If that succeeds, A is at least as
8141 specialized as P, so they match.*/
8142 processing_template_decl_sentinel ptds (/*reset*/false);
8143 ++processing_template_decl;
8145 tree pargs = template_parms_level_to_args (parm_parms);
8147 /* PARM, and thus the context in which we are passing ARG to it, may be
8148 at a deeper level than ARG; when trying to coerce to ARG_PARMS, we
8149 want to provide the right number of levels, so we reduce the number of
8150 levels in OUTER_ARGS before prepending them. This is most important
8151 when ARG is a namespace-scope template, as in alias-decl-ttp2.C.
8153 ARG might also be deeper than PARM (ttp23). In that case, we include
8154 all of OUTER_ARGS. The missing levels seem potentially problematic,
8155 but I can't come up with a testcase that breaks. */
8156 if (int arg_outer_levs = TMPL_PARMS_DEPTH (arg_parms_full) - 1)
8158 auto x = make_temp_override (TREE_VEC_LENGTH (outer_args));
8159 if (TMPL_ARGS_DEPTH (outer_args) > arg_outer_levs)
8160 TREE_VEC_LENGTH (outer_args) = arg_outer_levs;
8161 pargs = add_to_template_args (outer_args, pargs);
8164 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
8165 /*require_all*/true, /*use_default*/true);
8166 if (pargs != error_mark_node)
8168 tree targs = make_tree_vec (nargs);
8169 tree aargs = template_parms_level_to_args (arg_parms);
8170 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8171 /*explain*/false))
8172 return 1;
8176 /* Determine whether we have a parameter pack at the end of the
8177 template template parameter's template parameter list. */
8178 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8180 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8182 if (error_operand_p (parm))
8183 return 0;
8185 switch (TREE_CODE (parm))
8187 case TEMPLATE_DECL:
8188 case TYPE_DECL:
8189 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8190 variadic_p = 1;
8191 break;
8193 case PARM_DECL:
8194 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8195 variadic_p = 1;
8196 break;
8198 default:
8199 gcc_unreachable ();
8203 if (nargs != nparms
8204 && !(variadic_p && nargs >= nparms - 1))
8205 return 0;
8207 /* Check all of the template parameters except the parameter pack at
8208 the end (if any). */
8209 for (i = 0; i < nparms - variadic_p; ++i)
8211 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8212 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8213 continue;
8215 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8216 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8218 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8219 outer_args))
8220 return 0;
8224 if (variadic_p)
8226 /* Check each of the template parameters in the template
8227 argument against the template parameter pack at the end of
8228 the template template parameter. */
8229 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8230 return 0;
8232 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8234 for (; i < nargs; ++i)
8236 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8237 continue;
8239 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8241 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8242 outer_args))
8243 return 0;
8247 return 1;
8250 /* Verifies that the deduced template arguments (in TARGS) for the
8251 template template parameters (in TPARMS) represent valid bindings,
8252 by comparing the template parameter list of each template argument
8253 to the template parameter list of its corresponding template
8254 template parameter, in accordance with DR150. This
8255 routine can only be called after all template arguments have been
8256 deduced. It will return TRUE if all of the template template
8257 parameter bindings are okay, FALSE otherwise. */
8258 bool
8259 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8261 int i, ntparms = TREE_VEC_LENGTH (tparms);
8262 bool ret = true;
8264 /* We're dealing with template parms in this process. */
8265 ++processing_template_decl;
8267 targs = INNERMOST_TEMPLATE_ARGS (targs);
8269 for (i = 0; i < ntparms; ++i)
8271 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8272 tree targ = TREE_VEC_ELT (targs, i);
8274 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8276 tree packed_args = NULL_TREE;
8277 int idx, len = 1;
8279 if (ARGUMENT_PACK_P (targ))
8281 /* Look inside the argument pack. */
8282 packed_args = ARGUMENT_PACK_ARGS (targ);
8283 len = TREE_VEC_LENGTH (packed_args);
8286 for (idx = 0; idx < len; ++idx)
8288 tree targ_parms = NULL_TREE;
8290 if (packed_args)
8291 /* Extract the next argument from the argument
8292 pack. */
8293 targ = TREE_VEC_ELT (packed_args, idx);
8295 if (PACK_EXPANSION_P (targ))
8296 /* Look at the pattern of the pack expansion. */
8297 targ = PACK_EXPANSION_PATTERN (targ);
8299 /* Extract the template parameters from the template
8300 argument. */
8301 if (TREE_CODE (targ) == TEMPLATE_DECL)
8302 targ_parms = DECL_TEMPLATE_PARMS (targ);
8303 else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8304 targ_parms = DECL_TEMPLATE_PARMS (TYPE_NAME (targ));
8306 /* Verify that we can coerce the template template
8307 parameters from the template argument to the template
8308 parameter. This requires an exact match. */
8309 if (targ_parms
8310 && !coerce_template_template_parms
8311 (DECL_TEMPLATE_PARMS (tparm),
8312 targ_parms,
8313 tf_none,
8314 tparm,
8315 targs))
8317 ret = false;
8318 goto out;
8324 out:
8326 --processing_template_decl;
8327 return ret;
8330 /* Since type attributes aren't mangled, we need to strip them from
8331 template type arguments. */
8333 tree
8334 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8336 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8337 return arg;
8338 bool removed_attributes = false;
8339 tree canon = strip_typedefs (arg, &removed_attributes);
8340 if (removed_attributes
8341 && (complain & tf_warning))
8342 warning (OPT_Wignored_attributes,
8343 "ignoring attributes on template argument %qT", arg);
8344 return canon;
8347 /* And from inside dependent non-type arguments like sizeof(Type). */
8349 static tree
8350 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8352 if (!arg || arg == error_mark_node)
8353 return arg;
8354 bool removed_attributes = false;
8355 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8356 if (removed_attributes
8357 && (complain & tf_warning))
8358 warning (OPT_Wignored_attributes,
8359 "ignoring attributes in template argument %qE", arg);
8360 return canon;
8363 /* A template declaration can be substituted for a constrained
8364 template template parameter only when the argument is no more
8365 constrained than the parameter. */
8367 static bool
8368 is_compatible_template_arg (tree parm, tree arg)
8370 tree parm_cons = get_constraints (parm);
8372 /* For now, allow constrained template template arguments
8373 and unconstrained template template parameters. */
8374 if (parm_cons == NULL_TREE)
8375 return true;
8377 /* If the template parameter is constrained, we need to rewrite its
8378 constraints in terms of the ARG's template parameters. This ensures
8379 that all of the template parameter types will have the same depth.
8381 Note that this is only valid when coerce_template_template_parm is
8382 true for the innermost template parameters of PARM and ARG. In other
8383 words, because coercion is successful, this conversion will be valid. */
8384 tree new_args = NULL_TREE;
8385 if (parm_cons)
8387 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8388 new_args = template_parms_level_to_args (aparms);
8389 ++processing_template_decl;
8390 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8391 tf_none, NULL_TREE);
8392 --processing_template_decl;
8393 if (parm_cons == error_mark_node)
8394 return false;
8397 return weakly_subsumes (parm_cons, arg);
8400 // Convert a placeholder argument into a binding to the original
8401 // parameter. The original parameter is saved as the TREE_TYPE of
8402 // ARG.
8403 static inline tree
8404 convert_wildcard_argument (tree parm, tree arg)
8406 TREE_TYPE (arg) = parm;
8407 return arg;
8410 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8411 because one of them is dependent. But we need to represent the
8412 conversion for the benefit of cp_tree_equal. */
8414 static tree
8415 maybe_convert_nontype_argument (tree type, tree arg)
8417 /* Auto parms get no conversion. */
8418 if (type_uses_auto (type))
8419 return arg;
8420 /* We don't need or want to add this conversion now if we're going to use the
8421 argument for deduction. */
8422 if (value_dependent_expression_p (arg))
8423 return arg;
8425 type = cv_unqualified (type);
8426 tree argtype = TREE_TYPE (arg);
8427 if (same_type_p (type, argtype))
8428 return arg;
8430 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8431 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8432 return arg;
8435 /* Convert the indicated template ARG as necessary to match the
8436 indicated template PARM. Returns the converted ARG, or
8437 error_mark_node if the conversion was unsuccessful. Error and
8438 warning messages are issued under control of COMPLAIN. This
8439 conversion is for the Ith parameter in the parameter list. ARGS is
8440 the full set of template arguments deduced so far. */
8442 static tree
8443 convert_template_argument (tree parm,
8444 tree arg,
8445 tree args,
8446 tsubst_flags_t complain,
8447 int i,
8448 tree in_decl)
8450 tree orig_arg;
8451 tree val;
8452 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8454 if (parm == error_mark_node || error_operand_p (arg))
8455 return error_mark_node;
8457 /* Trivially convert placeholders. */
8458 if (TREE_CODE (arg) == WILDCARD_DECL)
8459 return convert_wildcard_argument (parm, arg);
8461 if (arg == any_targ_node)
8462 return arg;
8464 if (TREE_CODE (arg) == TREE_LIST
8465 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8467 /* The template argument was the name of some
8468 member function. That's usually
8469 invalid, but static members are OK. In any
8470 case, grab the underlying fields/functions
8471 and issue an error later if required. */
8472 TREE_TYPE (arg) = unknown_type_node;
8475 orig_arg = arg;
8477 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8478 requires_type = (TREE_CODE (parm) == TYPE_DECL
8479 || requires_tmpl_type);
8481 /* When determining whether an argument pack expansion is a template,
8482 look at the pattern. */
8483 if (PACK_EXPANSION_P (arg))
8484 arg = PACK_EXPANSION_PATTERN (arg);
8486 /* Deal with an injected-class-name used as a template template arg. */
8487 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8489 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8490 if (TREE_CODE (t) == TEMPLATE_DECL)
8492 if (cxx_dialect >= cxx11)
8493 /* OK under DR 1004. */;
8494 else if (complain & tf_warning_or_error)
8495 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8496 " used as template template argument", TYPE_NAME (arg));
8497 else if (flag_pedantic_errors)
8498 t = arg;
8500 arg = t;
8504 is_tmpl_type =
8505 ((TREE_CODE (arg) == TEMPLATE_DECL
8506 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8507 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8508 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8509 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8511 if (is_tmpl_type
8512 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8513 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8514 arg = TYPE_STUB_DECL (arg);
8516 is_type = TYPE_P (arg) || is_tmpl_type;
8518 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8519 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8521 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8523 if (complain & tf_error)
8524 error ("invalid use of destructor %qE as a type", orig_arg);
8525 return error_mark_node;
8528 permerror (input_location,
8529 "to refer to a type member of a template parameter, "
8530 "use %<typename %E%>", orig_arg);
8532 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8533 TREE_OPERAND (arg, 1),
8534 typename_type,
8535 complain);
8536 arg = orig_arg;
8537 is_type = 1;
8539 if (is_type != requires_type)
8541 if (in_decl)
8543 if (complain & tf_error)
8545 error ("type/value mismatch at argument %d in template "
8546 "parameter list for %qD",
8547 i + 1, in_decl);
8548 if (is_type)
8550 /* The template argument is a type, but we're expecting
8551 an expression. */
8552 inform (input_location,
8553 " expected a constant of type %qT, got %qT",
8554 TREE_TYPE (parm),
8555 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8556 /* [temp.arg]/2: "In a template-argument, an ambiguity
8557 between a type-id and an expression is resolved to a
8558 type-id, regardless of the form of the corresponding
8559 template-parameter." So give the user a clue. */
8560 if (TREE_CODE (arg) == FUNCTION_TYPE)
8561 inform (input_location, " ambiguous template argument "
8562 "for non-type template parameter is treated as "
8563 "function type");
8565 else if (requires_tmpl_type)
8566 inform (input_location,
8567 " expected a class template, got %qE", orig_arg);
8568 else
8569 inform (input_location,
8570 " expected a type, got %qE", orig_arg);
8573 return error_mark_node;
8575 if (is_tmpl_type ^ requires_tmpl_type)
8577 if (in_decl && (complain & tf_error))
8579 error ("type/value mismatch at argument %d in template "
8580 "parameter list for %qD",
8581 i + 1, in_decl);
8582 if (is_tmpl_type)
8583 inform (input_location,
8584 " expected a type, got %qT", DECL_NAME (arg));
8585 else
8586 inform (input_location,
8587 " expected a class template, got %qT", orig_arg);
8589 return error_mark_node;
8592 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8593 /* We already did the appropriate conversion when packing args. */
8594 val = orig_arg;
8595 else if (is_type)
8597 if (requires_tmpl_type)
8599 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8600 /* The number of argument required is not known yet.
8601 Just accept it for now. */
8602 val = orig_arg;
8603 else
8605 tree parmparm = DECL_TEMPLATE_PARMS (parm);
8606 tree argparm;
8608 /* Strip alias templates that are equivalent to another
8609 template. */
8610 arg = get_underlying_template (arg);
8611 argparm = DECL_TEMPLATE_PARMS (arg);
8613 if (coerce_template_template_parms (parmparm, argparm,
8614 complain, in_decl,
8615 args))
8617 val = arg;
8619 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8620 TEMPLATE_DECL. */
8621 if (val != error_mark_node)
8623 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8624 val = TREE_TYPE (val);
8625 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8626 val = make_pack_expansion (val, complain);
8629 else
8631 if (in_decl && (complain & tf_error))
8633 error ("type/value mismatch at argument %d in "
8634 "template parameter list for %qD",
8635 i + 1, in_decl);
8636 inform (input_location,
8637 " expected a template of type %qD, got %qT",
8638 parm, orig_arg);
8641 val = error_mark_node;
8644 // Check that the constraints are compatible before allowing the
8645 // substitution.
8646 if (val != error_mark_node)
8647 if (!is_compatible_template_arg (parm, arg))
8649 if (in_decl && (complain & tf_error))
8651 error ("constraint mismatch at argument %d in "
8652 "template parameter list for %qD",
8653 i + 1, in_decl);
8654 inform (input_location, " expected %qD but got %qD",
8655 parm, arg);
8657 val = error_mark_node;
8661 else
8662 val = orig_arg;
8663 /* We only form one instance of each template specialization.
8664 Therefore, if we use a non-canonical variant (i.e., a
8665 typedef), any future messages referring to the type will use
8666 the typedef, which is confusing if those future uses do not
8667 themselves also use the typedef. */
8668 if (TYPE_P (val))
8669 val = canonicalize_type_argument (val, complain);
8671 else
8673 tree t = TREE_TYPE (parm);
8675 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8676 > TMPL_ARGS_DEPTH (args))
8677 /* We don't have enough levels of args to do any substitution. This
8678 can happen in the context of -fnew-ttp-matching. */;
8679 else if (tree a = type_uses_auto (t))
8681 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8682 LOOKUP_IMPLICIT);
8683 if (t == error_mark_node)
8684 return error_mark_node;
8686 else
8687 t = tsubst (t, args, complain, in_decl);
8689 /* Perform array-to-pointer and function-to-pointer conversion
8690 as per [temp.param]/10. */
8691 t = type_decays_to (t);
8693 if (invalid_nontype_parm_type_p (t, complain))
8694 return error_mark_node;
8696 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8697 this non-type template parameter, as per [temp.param]/6. */
8698 t = cv_unqualified (t);
8700 if (t != TREE_TYPE (parm))
8701 t = canonicalize_type_argument (t, complain);
8703 if (!type_dependent_expression_p (orig_arg)
8704 && !uses_template_parms (t))
8705 /* We used to call digest_init here. However, digest_init
8706 will report errors, which we don't want when complain
8707 is zero. More importantly, digest_init will try too
8708 hard to convert things: for example, `0' should not be
8709 converted to pointer type at this point according to
8710 the standard. Accepting this is not merely an
8711 extension, since deciding whether or not these
8712 conversions can occur is part of determining which
8713 function template to call, or whether a given explicit
8714 argument specification is valid. */
8715 val = convert_nontype_argument (t, orig_arg, complain);
8716 else
8718 val = canonicalize_expr_argument (orig_arg, complain);
8719 val = maybe_convert_nontype_argument (t, val);
8723 if (val == NULL_TREE)
8724 val = error_mark_node;
8725 else if (val == error_mark_node && (complain & tf_error))
8726 error_at (cp_expr_loc_or_input_loc (orig_arg),
8727 "could not convert template argument %qE from %qT to %qT",
8728 orig_arg, TREE_TYPE (orig_arg), t);
8730 if (INDIRECT_REF_P (val))
8732 /* Reject template arguments that are references to built-in
8733 functions with no library fallbacks. */
8734 const_tree inner = TREE_OPERAND (val, 0);
8735 const_tree innertype = TREE_TYPE (inner);
8736 if (innertype
8737 && TYPE_REF_P (innertype)
8738 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8739 && TREE_OPERAND_LENGTH (inner) > 0
8740 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8741 return error_mark_node;
8744 if (TREE_CODE (val) == SCOPE_REF)
8746 /* Strip typedefs from the SCOPE_REF. */
8747 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8748 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8749 complain);
8750 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8751 QUALIFIED_NAME_IS_TEMPLATE (val));
8755 return val;
8758 /* Coerces the remaining template arguments in INNER_ARGS (from
8759 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8760 Returns the coerced argument pack. PARM_IDX is the position of this
8761 parameter in the template parameter list. ARGS is the original
8762 template argument list. */
8763 static tree
8764 coerce_template_parameter_pack (tree parms,
8765 int parm_idx,
8766 tree args,
8767 tree inner_args,
8768 int arg_idx,
8769 tree new_args,
8770 int* lost,
8771 tree in_decl,
8772 tsubst_flags_t complain)
8774 tree parm = TREE_VEC_ELT (parms, parm_idx);
8775 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8776 tree packed_args;
8777 tree argument_pack;
8778 tree packed_parms = NULL_TREE;
8780 if (arg_idx > nargs)
8781 arg_idx = nargs;
8783 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8785 /* When the template parameter is a non-type template parameter pack
8786 or template template parameter pack whose type or template
8787 parameters use parameter packs, we know exactly how many arguments
8788 we are looking for. Build a vector of the instantiated decls for
8789 these template parameters in PACKED_PARMS. */
8790 /* We can't use make_pack_expansion here because it would interpret a
8791 _DECL as a use rather than a declaration. */
8792 tree decl = TREE_VALUE (parm);
8793 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8794 PACK_EXPANSION_PATTERN (exp) = decl;
8795 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8796 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8798 TREE_VEC_LENGTH (args)--;
8799 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8800 TREE_VEC_LENGTH (args)++;
8802 if (packed_parms == error_mark_node)
8803 return error_mark_node;
8805 /* If we're doing a partial instantiation of a member template,
8806 verify that all of the types used for the non-type
8807 template parameter pack are, in fact, valid for non-type
8808 template parameters. */
8809 if (arg_idx < nargs
8810 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8812 int j, len = TREE_VEC_LENGTH (packed_parms);
8813 for (j = 0; j < len; ++j)
8815 tree t = TREE_VEC_ELT (packed_parms, j);
8816 if (TREE_CODE (t) == PARM_DECL
8817 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8818 return error_mark_node;
8820 /* We don't know how many args we have yet, just
8821 use the unconverted ones for now. */
8822 return NULL_TREE;
8825 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8827 /* Check if we have a placeholder pack, which indicates we're
8828 in the context of a introduction list. In that case we want
8829 to match this pack to the single placeholder. */
8830 else if (arg_idx < nargs
8831 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8832 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8834 nargs = arg_idx + 1;
8835 packed_args = make_tree_vec (1);
8837 else
8838 packed_args = make_tree_vec (nargs - arg_idx);
8840 /* Convert the remaining arguments, which will be a part of the
8841 parameter pack "parm". */
8842 int first_pack_arg = arg_idx;
8843 for (; arg_idx < nargs; ++arg_idx)
8845 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8846 tree actual_parm = TREE_VALUE (parm);
8847 int pack_idx = arg_idx - first_pack_arg;
8849 if (packed_parms)
8851 /* Once we've packed as many args as we have types, stop. */
8852 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8853 break;
8854 else if (PACK_EXPANSION_P (arg))
8855 /* We don't know how many args we have yet, just
8856 use the unconverted ones for now. */
8857 return NULL_TREE;
8858 else
8859 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8862 if (arg == error_mark_node)
8864 if (complain & tf_error)
8865 error ("template argument %d is invalid", arg_idx + 1);
8867 else
8868 arg = convert_template_argument (actual_parm,
8869 arg, new_args, complain, parm_idx,
8870 in_decl);
8871 if (arg == error_mark_node)
8872 (*lost)++;
8873 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8876 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8877 && TREE_VEC_LENGTH (packed_args) > 0)
8879 if (complain & tf_error)
8880 error ("wrong number of template arguments (%d, should be %d)",
8881 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8882 return error_mark_node;
8885 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8886 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8887 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8888 else
8890 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8891 TREE_CONSTANT (argument_pack) = 1;
8894 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8895 if (CHECKING_P)
8896 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8897 TREE_VEC_LENGTH (packed_args));
8898 return argument_pack;
8901 /* Returns the number of pack expansions in the template argument vector
8902 ARGS. */
8904 static int
8905 pack_expansion_args_count (tree args)
8907 int i;
8908 int count = 0;
8909 if (args)
8910 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8912 tree elt = TREE_VEC_ELT (args, i);
8913 if (elt && PACK_EXPANSION_P (elt))
8914 ++count;
8916 return count;
8919 /* Convert all template arguments to their appropriate types, and
8920 return a vector containing the innermost resulting template
8921 arguments. If any error occurs, return error_mark_node. Error and
8922 warning messages are issued under control of COMPLAIN.
8924 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8925 for arguments not specified in ARGS. Otherwise, if
8926 USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8927 unspecified arguments. If REQUIRE_ALL_ARGS is true, but
8928 USE_DEFAULT_ARGS is false, then all arguments must be specified in
8929 ARGS. */
8931 static tree
8932 coerce_template_parms (tree parms,
8933 tree args,
8934 tree in_decl,
8935 tsubst_flags_t complain,
8936 bool require_all_args,
8937 bool use_default_args)
8939 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8940 tree orig_inner_args;
8941 tree inner_args;
8942 tree new_args;
8943 tree new_inner_args;
8945 /* When used as a boolean value, indicates whether this is a
8946 variadic template parameter list. Since it's an int, we can also
8947 subtract it from nparms to get the number of non-variadic
8948 parameters. */
8949 int variadic_p = 0;
8950 int variadic_args_p = 0;
8951 int post_variadic_parms = 0;
8953 /* Adjustment to nparms for fixed parameter packs. */
8954 int fixed_pack_adjust = 0;
8955 int fixed_packs = 0;
8956 int missing = 0;
8958 /* Likewise for parameters with default arguments. */
8959 int default_p = 0;
8961 if (args == error_mark_node)
8962 return error_mark_node;
8964 nparms = TREE_VEC_LENGTH (parms);
8966 /* Determine if there are any parameter packs or default arguments. */
8967 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8969 tree parm = TREE_VEC_ELT (parms, parm_idx);
8970 if (variadic_p)
8971 ++post_variadic_parms;
8972 if (template_parameter_pack_p (TREE_VALUE (parm)))
8973 ++variadic_p;
8974 if (TREE_PURPOSE (parm))
8975 ++default_p;
8978 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8979 /* If there are no parameters that follow a parameter pack, we need to
8980 expand any argument packs so that we can deduce a parameter pack from
8981 some non-packed args followed by an argument pack, as in variadic85.C.
8982 If there are such parameters, we need to leave argument packs intact
8983 so the arguments are assigned properly. This can happen when dealing
8984 with a nested class inside a partial specialization of a class
8985 template, as in variadic92.C, or when deducing a template parameter pack
8986 from a sub-declarator, as in variadic114.C. */
8987 if (!post_variadic_parms)
8988 inner_args = expand_template_argument_pack (inner_args);
8990 /* Count any pack expansion args. */
8991 variadic_args_p = pack_expansion_args_count (inner_args);
8993 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8994 if ((nargs - variadic_args_p > nparms && !variadic_p)
8995 || (nargs < nparms - variadic_p
8996 && require_all_args
8997 && !variadic_args_p
8998 && (!use_default_args
8999 || (TREE_VEC_ELT (parms, nargs) != error_mark_node
9000 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
9002 bad_nargs:
9003 if (complain & tf_error)
9005 if (variadic_p || default_p)
9007 nparms -= variadic_p + default_p;
9008 error ("wrong number of template arguments "
9009 "(%d, should be at least %d)", nargs, nparms);
9011 else
9012 error ("wrong number of template arguments "
9013 "(%d, should be %d)", nargs, nparms);
9015 if (in_decl)
9016 inform (DECL_SOURCE_LOCATION (in_decl),
9017 "provided for %qD", in_decl);
9020 return error_mark_node;
9022 /* We can't pass a pack expansion to a non-pack parameter of an alias
9023 template (DR 1430). */
9024 else if (in_decl
9025 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9026 || concept_definition_p (in_decl))
9027 && variadic_args_p
9028 && nargs - variadic_args_p < nparms - variadic_p)
9030 if (complain & tf_error)
9032 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9034 tree arg = TREE_VEC_ELT (inner_args, i);
9035 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9037 if (PACK_EXPANSION_P (arg)
9038 && !template_parameter_pack_p (parm))
9040 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9041 error_at (location_of (arg),
9042 "pack expansion argument for non-pack parameter "
9043 "%qD of alias template %qD", parm, in_decl);
9044 else
9045 error_at (location_of (arg),
9046 "pack expansion argument for non-pack parameter "
9047 "%qD of concept %qD", parm, in_decl);
9048 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9049 goto found;
9052 gcc_unreachable ();
9053 found:;
9055 return error_mark_node;
9058 /* We need to evaluate the template arguments, even though this
9059 template-id may be nested within a "sizeof". */
9060 cp_evaluated ev;
9062 new_inner_args = make_tree_vec (nparms);
9063 new_args = add_outermost_template_args (args, new_inner_args);
9064 int pack_adjust = 0;
9065 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9067 tree arg;
9068 tree parm;
9070 /* Get the Ith template parameter. */
9071 parm = TREE_VEC_ELT (parms, parm_idx);
9073 if (parm == error_mark_node)
9075 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9076 continue;
9079 /* Calculate the next argument. */
9080 if (arg_idx < nargs)
9081 arg = TREE_VEC_ELT (inner_args, arg_idx);
9082 else
9083 arg = NULL_TREE;
9085 if (template_parameter_pack_p (TREE_VALUE (parm))
9086 && (arg || require_all_args || !(complain & tf_partial))
9087 && !(arg && ARGUMENT_PACK_P (arg)))
9089 /* Some arguments will be placed in the
9090 template parameter pack PARM. */
9091 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9092 inner_args, arg_idx,
9093 new_args, &lost,
9094 in_decl, complain);
9096 if (arg == NULL_TREE)
9098 /* We don't know how many args we have yet, just use the
9099 unconverted (and still packed) ones for now. */
9100 new_inner_args = orig_inner_args;
9101 arg_idx = nargs;
9102 break;
9105 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9107 /* Store this argument. */
9108 if (arg == error_mark_node)
9110 lost++;
9111 /* We are done with all of the arguments. */
9112 arg_idx = nargs;
9113 break;
9115 else
9117 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9118 arg_idx += pack_adjust;
9119 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9121 ++fixed_packs;
9122 fixed_pack_adjust += pack_adjust;
9126 continue;
9128 else if (arg)
9130 if (PACK_EXPANSION_P (arg))
9132 /* "If every valid specialization of a variadic template
9133 requires an empty template parameter pack, the template is
9134 ill-formed, no diagnostic required." So check that the
9135 pattern works with this parameter. */
9136 tree pattern = PACK_EXPANSION_PATTERN (arg);
9137 tree conv = convert_template_argument (TREE_VALUE (parm),
9138 pattern, new_args,
9139 complain, parm_idx,
9140 in_decl);
9141 if (conv == error_mark_node)
9143 if (complain & tf_error)
9144 inform (input_location, "so any instantiation with a "
9145 "non-empty parameter pack would be ill-formed");
9146 ++lost;
9148 else if (TYPE_P (conv) && !TYPE_P (pattern))
9149 /* Recover from missing typename. */
9150 TREE_VEC_ELT (inner_args, arg_idx)
9151 = make_pack_expansion (conv, complain);
9153 /* We don't know how many args we have yet, just
9154 use the unconverted ones for now. */
9155 new_inner_args = inner_args;
9156 arg_idx = nargs;
9157 break;
9160 else if (require_all_args)
9162 /* There must be a default arg in this case. */
9163 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9164 complain, in_decl);
9165 /* The position of the first default template argument,
9166 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9167 Record that. */
9168 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9169 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9170 arg_idx - pack_adjust);
9172 else
9173 break;
9175 if (arg == error_mark_node)
9177 if (complain & tf_error)
9178 error ("template argument %d is invalid", arg_idx + 1);
9180 else if (!arg)
9182 /* This can occur if there was an error in the template
9183 parameter list itself (which we would already have
9184 reported) that we are trying to recover from, e.g., a class
9185 template with a parameter list such as
9186 template<typename..., typename> (cpp0x/variadic150.C). */
9187 ++lost;
9189 /* This can also happen with a fixed parameter pack (71834). */
9190 if (arg_idx >= nargs)
9191 ++missing;
9193 else
9194 arg = convert_template_argument (TREE_VALUE (parm),
9195 arg, new_args, complain,
9196 parm_idx, in_decl);
9198 if (arg == error_mark_node)
9199 lost++;
9201 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9204 if (missing || arg_idx < nargs - variadic_args_p)
9206 /* If we had fixed parameter packs, we didn't know how many arguments we
9207 actually needed earlier; now we do. */
9208 nparms += fixed_pack_adjust;
9209 variadic_p -= fixed_packs;
9210 goto bad_nargs;
9213 if (arg_idx < nargs)
9215 /* We had some pack expansion arguments that will only work if the packs
9216 are empty, but wait until instantiation time to complain.
9217 See variadic-ttp3.C. */
9219 /* Except that we can't provide empty packs to alias templates or
9220 concepts when there are no corresponding parameters. Basically,
9221 we can get here with this:
9223 template<typename T> concept C = true;
9225 template<typename... Args>
9226 requires C<Args...>
9227 void f();
9229 When parsing C<Args...>, we try to form a concept check of
9230 C<?, Args...>. Without the extra check for substituting an empty
9231 pack past the last parameter, we can accept the check as valid.
9233 FIXME: This may be valid for alias templates (but I doubt it).
9235 FIXME: The error could be better also. */
9236 if (in_decl && concept_definition_p (in_decl))
9238 if (complain & tf_error)
9239 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9240 "too many arguments");
9241 return error_mark_node;
9244 int len = nparms + (nargs - arg_idx);
9245 tree args = make_tree_vec (len);
9246 int i = 0;
9247 for (; i < nparms; ++i)
9248 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9249 for (; i < len; ++i, ++arg_idx)
9250 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9251 arg_idx - pack_adjust);
9252 new_inner_args = args;
9255 if (lost)
9257 gcc_assert (!(complain & tf_error) || seen_error ());
9258 return error_mark_node;
9261 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9262 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9263 TREE_VEC_LENGTH (new_inner_args));
9265 return new_inner_args;
9268 /* Convert all template arguments to their appropriate types, and
9269 return a vector containing the innermost resulting template
9270 arguments. If any error occurs, return error_mark_node. Error and
9271 warning messages are not issued.
9273 Note that no function argument deduction is performed, and default
9274 arguments are used to fill in unspecified arguments. */
9275 tree
9276 coerce_template_parms (tree parms, tree args, tree in_decl)
9278 return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9281 /* Convert all template arguments to their appropriate type, and
9282 instantiate default arguments as needed. This returns a vector
9283 containing the innermost resulting template arguments, or
9284 error_mark_node if unsuccessful. */
9285 tree
9286 coerce_template_parms (tree parms, tree args, tree in_decl,
9287 tsubst_flags_t complain)
9289 return coerce_template_parms (parms, args, in_decl, complain, true, true);
9292 /* Like coerce_template_parms. If PARMS represents all template
9293 parameters levels, this function returns a vector of vectors
9294 representing all the resulting argument levels. Note that in this
9295 case, only the innermost arguments are coerced because the
9296 outermost ones are supposed to have been coerced already.
9298 Otherwise, if PARMS represents only (the innermost) vector of
9299 parameters, this function returns a vector containing just the
9300 innermost resulting arguments. */
9302 static tree
9303 coerce_innermost_template_parms (tree parms,
9304 tree args,
9305 tree in_decl,
9306 tsubst_flags_t complain,
9307 bool require_all_args,
9308 bool use_default_args)
9310 int parms_depth = TMPL_PARMS_DEPTH (parms);
9311 int args_depth = TMPL_ARGS_DEPTH (args);
9312 tree coerced_args;
9314 if (parms_depth > 1)
9316 coerced_args = make_tree_vec (parms_depth);
9317 tree level;
9318 int cur_depth;
9320 for (level = parms, cur_depth = parms_depth;
9321 parms_depth > 0 && level != NULL_TREE;
9322 level = TREE_CHAIN (level), --cur_depth)
9324 tree l;
9325 if (cur_depth == args_depth)
9326 l = coerce_template_parms (TREE_VALUE (level),
9327 args, in_decl, complain,
9328 require_all_args,
9329 use_default_args);
9330 else
9331 l = TMPL_ARGS_LEVEL (args, cur_depth);
9333 if (l == error_mark_node)
9334 return error_mark_node;
9336 SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9339 else
9340 coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9341 args, in_decl, complain,
9342 require_all_args,
9343 use_default_args);
9344 return coerced_args;
9347 /* Returns true if T is a wrapper to make a C++20 template parameter
9348 object const. */
9350 static bool
9351 class_nttp_const_wrapper_p (tree t)
9353 if (cxx_dialect < cxx20)
9354 return false;
9355 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9356 && CP_TYPE_CONST_P (TREE_TYPE (t))
9357 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9360 /* Returns 1 if template args OT and NT are equivalent. */
9363 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9365 if (nt == ot)
9366 return 1;
9367 if (nt == NULL_TREE || ot == NULL_TREE)
9368 return false;
9369 if (nt == any_targ_node || ot == any_targ_node)
9370 return true;
9372 if (class_nttp_const_wrapper_p (nt))
9373 nt = TREE_OPERAND (nt, 0);
9374 if (class_nttp_const_wrapper_p (ot))
9375 ot = TREE_OPERAND (ot, 0);
9377 /* DR 1558: Don't treat an alias template specialization with dependent
9378 arguments as equivalent to its underlying type when used as a template
9379 argument; we need them to be distinct so that we substitute into the
9380 specialization arguments at instantiation time. And aliases can't be
9381 equivalent without being ==, so we don't need to look any deeper.
9383 During partial ordering, however, we need to treat them normally so we can
9384 order uses of the same alias with different cv-qualification (79960). */
9385 auto cso = make_temp_override (comparing_dependent_aliases);
9386 if (!partial_order)
9387 ++comparing_dependent_aliases;
9389 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9390 /* For member templates */
9391 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9392 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9393 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9394 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9395 PACK_EXPANSION_PATTERN (nt))
9396 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9397 PACK_EXPANSION_EXTRA_ARGS (nt)));
9398 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9399 return cp_tree_equal (ot, nt);
9400 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9401 gcc_unreachable ();
9402 else if (TYPE_P (nt) || TYPE_P (ot))
9404 if (!(TYPE_P (nt) && TYPE_P (ot)))
9405 return false;
9406 return same_type_p (ot, nt);
9408 else
9410 /* Try to treat a template non-type argument that has been converted
9411 to the parameter type as equivalent to one that hasn't yet. */
9412 for (enum tree_code code1 = TREE_CODE (ot);
9413 CONVERT_EXPR_CODE_P (code1)
9414 || code1 == NON_LVALUE_EXPR;
9415 code1 = TREE_CODE (ot))
9416 ot = TREE_OPERAND (ot, 0);
9418 for (enum tree_code code2 = TREE_CODE (nt);
9419 CONVERT_EXPR_CODE_P (code2)
9420 || code2 == NON_LVALUE_EXPR;
9421 code2 = TREE_CODE (nt))
9422 nt = TREE_OPERAND (nt, 0);
9424 return cp_tree_equal (ot, nt);
9428 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9429 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9430 NEWARG_PTR with the offending arguments if they are non-NULL. */
9432 bool
9433 comp_template_args (tree oldargs, tree newargs,
9434 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */,
9435 bool partial_order /* = false */)
9437 if (oldargs == newargs)
9438 return true;
9440 if (!oldargs || !newargs)
9441 return false;
9443 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9444 return false;
9446 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9448 tree nt = TREE_VEC_ELT (newargs, i);
9449 tree ot = TREE_VEC_ELT (oldargs, i);
9451 if (! template_args_equal (ot, nt, partial_order))
9453 if (oldarg_ptr != NULL)
9454 *oldarg_ptr = ot;
9455 if (newarg_ptr != NULL)
9456 *newarg_ptr = nt;
9457 return false;
9460 return true;
9463 inline bool
9464 comp_template_args_porder (tree oargs, tree nargs)
9466 return comp_template_args (oargs, nargs, NULL, NULL, true);
9469 /* Implement a freelist interface for objects of type T.
9471 Head is a separate object, rather than a regular member, so that we
9472 can define it as a GTY deletable pointer, which is highly
9473 desirable. A data member could be declared that way, but then the
9474 containing object would implicitly get GTY((user)), which would
9475 prevent us from instantiating freelists as global objects.
9476 Although this way we can create freelist global objects, they're
9477 such thin wrappers that instantiating temporaries at every use
9478 loses nothing and saves permanent storage for the freelist object.
9480 Member functions next, anew, poison and reinit have default
9481 implementations that work for most of the types we're interested
9482 in, but if they don't work for some type, they should be explicitly
9483 specialized. See the comments before them for requirements, and
9484 the example specializations for the tree_list_freelist. */
9485 template <typename T>
9486 class freelist
9488 /* Return the next object in a chain. We could just do type
9489 punning, but if we access the object with its underlying type, we
9490 avoid strict-aliasing trouble. This needs only work between
9491 poison and reinit. */
9492 static T *&next (T *obj) { return obj->next; }
9494 /* Return a newly allocated, uninitialized or minimally-initialized
9495 object of type T. Any initialization performed by anew should
9496 either remain across the life of the object and the execution of
9497 poison, or be redone by reinit. */
9498 static T *anew () { return ggc_alloc<T> (); }
9500 /* Optionally scribble all over the bits holding the object, so that
9501 they become (mostly?) uninitialized memory. This is called while
9502 preparing to make the object part of the free list. */
9503 static void poison (T *obj) {
9504 T *p ATTRIBUTE_UNUSED = obj;
9505 T **q ATTRIBUTE_UNUSED = &next (obj);
9507 #ifdef ENABLE_GC_CHECKING
9508 /* Poison the data, to indicate the data is garbage. */
9509 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9510 memset (p, 0xa5, sizeof (*p));
9511 #endif
9512 /* Let valgrind know the object is free. */
9513 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9515 /* Let valgrind know the next portion of the object is available,
9516 but uninitialized. */
9517 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9520 /* Bring an object that underwent at least one lifecycle after anew
9521 and before the most recent free and poison, back to a usable
9522 state, reinitializing whatever is needed for it to be
9523 functionally equivalent to an object just allocated and returned
9524 by anew. This may poison or clear the next field, used by
9525 freelist housekeeping after poison was called. */
9526 static void reinit (T *obj) {
9527 T **q ATTRIBUTE_UNUSED = &next (obj);
9529 #ifdef ENABLE_GC_CHECKING
9530 memset (q, 0xa5, sizeof (*q));
9531 #endif
9532 /* Let valgrind know the entire object is available, but
9533 uninitialized. */
9534 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9537 /* Reference a GTY-deletable pointer that points to the first object
9538 in the free list proper. */
9539 T *&head;
9540 public:
9541 /* Construct a freelist object chaining objects off of HEAD. */
9542 freelist (T *&head) : head(head) {}
9544 /* Add OBJ to the free object list. The former head becomes OBJ's
9545 successor. */
9546 void free (T *obj)
9548 poison (obj);
9549 next (obj) = head;
9550 head = obj;
9553 /* Take an object from the free list, if one is available, or
9554 allocate a new one. Objects taken from the free list should be
9555 regarded as filled with garbage, except for bits that are
9556 configured to be preserved across free and alloc. */
9557 T *alloc ()
9559 if (head)
9561 T *obj = head;
9562 head = next (head);
9563 reinit (obj);
9564 return obj;
9566 else
9567 return anew ();
9571 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9572 want to allocate a TREE_LIST using the usual interface, and ensure
9573 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9574 build_tree_list logic in reinit, so this could go out of sync. */
9575 template <>
9576 inline tree &
9577 freelist<tree_node>::next (tree obj)
9579 return TREE_CHAIN (obj);
9581 template <>
9582 inline tree
9583 freelist<tree_node>::anew ()
9585 return build_tree_list (NULL, NULL);
9587 template <>
9588 inline void
9589 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9591 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9592 tree p ATTRIBUTE_UNUSED = obj;
9593 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9594 tree *q ATTRIBUTE_UNUSED = &next (obj);
9596 #ifdef ENABLE_GC_CHECKING
9597 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9599 /* Poison the data, to indicate the data is garbage. */
9600 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9601 memset (p, 0xa5, size);
9602 #endif
9603 /* Let valgrind know the object is free. */
9604 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9605 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9606 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9607 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9609 #ifdef ENABLE_GC_CHECKING
9610 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9611 /* Keep TREE_CHAIN functional. */
9612 TREE_SET_CODE (obj, TREE_LIST);
9613 #else
9614 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9615 #endif
9617 template <>
9618 inline void
9619 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9621 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9623 #ifdef ENABLE_GC_CHECKING
9624 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9625 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9626 memset (obj, 0, sizeof (tree_list));
9627 #endif
9629 /* Let valgrind know the entire object is available, but
9630 uninitialized. */
9631 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9633 #ifdef ENABLE_GC_CHECKING
9634 TREE_SET_CODE (obj, TREE_LIST);
9635 #else
9636 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9637 #endif
9640 /* Point to the first object in the TREE_LIST freelist. */
9641 static GTY((deletable)) tree tree_list_freelist_head;
9642 /* Return the/an actual TREE_LIST freelist. */
9643 static inline freelist<tree_node>
9644 tree_list_freelist ()
9646 return tree_list_freelist_head;
9649 /* Point to the first object in the tinst_level freelist. */
9650 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9651 /* Return the/an actual tinst_level freelist. */
9652 static inline freelist<tinst_level>
9653 tinst_level_freelist ()
9655 return tinst_level_freelist_head;
9658 /* Point to the first object in the pending_template freelist. */
9659 static GTY((deletable)) pending_template *pending_template_freelist_head;
9660 /* Return the/an actual pending_template freelist. */
9661 static inline freelist<pending_template>
9662 pending_template_freelist ()
9664 return pending_template_freelist_head;
9667 /* Build the TREE_LIST object out of a split list, store it
9668 permanently, and return it. */
9669 tree
9670 tinst_level::to_list ()
9672 gcc_assert (split_list_p ());
9673 tree ret = tree_list_freelist ().alloc ();
9674 TREE_PURPOSE (ret) = tldcl;
9675 TREE_VALUE (ret) = targs;
9676 tldcl = ret;
9677 targs = NULL;
9678 gcc_assert (tree_list_p ());
9679 return ret;
9682 const unsigned short tinst_level::refcount_infinity;
9684 /* Increment OBJ's refcount unless it is already infinite. */
9685 static tinst_level *
9686 inc_refcount_use (tinst_level *obj)
9688 if (obj && obj->refcount != tinst_level::refcount_infinity)
9689 ++obj->refcount;
9690 return obj;
9693 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9694 void
9695 tinst_level::free (tinst_level *obj)
9697 if (obj->tree_list_p ())
9698 tree_list_freelist ().free (obj->get_node ());
9699 tinst_level_freelist ().free (obj);
9702 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9703 OBJ's DECL and OBJ, and start over with the tinst_level object that
9704 used to be referenced by OBJ's NEXT. */
9705 static void
9706 dec_refcount_use (tinst_level *obj)
9708 while (obj
9709 && obj->refcount != tinst_level::refcount_infinity
9710 && !--obj->refcount)
9712 tinst_level *next = obj->next;
9713 tinst_level::free (obj);
9714 obj = next;
9718 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9719 and of the former PTR. Omitting the second argument is equivalent
9720 to passing (T*)NULL; this is allowed because passing the
9721 zero-valued integral constant NULL confuses type deduction and/or
9722 overload resolution. */
9723 template <typename T>
9724 static void
9725 set_refcount_ptr (T *& ptr, T *obj = NULL)
9727 T *save = ptr;
9728 ptr = inc_refcount_use (obj);
9729 dec_refcount_use (save);
9732 static void
9733 add_pending_template (tree d)
9735 tree ti = (TYPE_P (d)
9736 ? CLASSTYPE_TEMPLATE_INFO (d)
9737 : DECL_TEMPLATE_INFO (d));
9738 struct pending_template *pt;
9739 int level;
9741 if (TI_PENDING_TEMPLATE_FLAG (ti))
9742 return;
9744 /* We are called both from instantiate_decl, where we've already had a
9745 tinst_level pushed, and instantiate_template, where we haven't.
9746 Compensate. */
9747 gcc_assert (TREE_CODE (d) != TREE_LIST);
9748 level = !current_tinst_level
9749 || current_tinst_level->maybe_get_node () != d;
9751 if (level)
9752 push_tinst_level (d);
9754 pt = pending_template_freelist ().alloc ();
9755 pt->next = NULL;
9756 pt->tinst = NULL;
9757 set_refcount_ptr (pt->tinst, current_tinst_level);
9758 if (last_pending_template)
9759 last_pending_template->next = pt;
9760 else
9761 pending_templates = pt;
9763 last_pending_template = pt;
9765 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9767 if (level)
9768 pop_tinst_level ();
9772 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9773 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9774 documentation for TEMPLATE_ID_EXPR. */
9776 tree
9777 lookup_template_function (tree fns, tree arglist)
9779 if (fns == error_mark_node || arglist == error_mark_node)
9780 return error_mark_node;
9782 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9784 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9786 error ("%q#D is not a function template", fns);
9787 return error_mark_node;
9790 if (BASELINK_P (fns))
9792 fns = copy_node (fns);
9793 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9794 unknown_type_node,
9795 BASELINK_FUNCTIONS (fns),
9796 arglist);
9797 return fns;
9800 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9803 /* Within the scope of a template class S<T>, the name S gets bound
9804 (in build_self_reference) to a TYPE_DECL for the class, not a
9805 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9806 or one of its enclosing classes, and that type is a template,
9807 return the associated TEMPLATE_DECL. Otherwise, the original
9808 DECL is returned.
9810 Also handle the case when DECL is a TREE_LIST of ambiguous
9811 injected-class-names from different bases. */
9813 tree
9814 maybe_get_template_decl_from_type_decl (tree decl)
9816 if (decl == NULL_TREE)
9817 return decl;
9819 /* DR 176: A lookup that finds an injected-class-name (10.2
9820 [class.member.lookup]) can result in an ambiguity in certain cases
9821 (for example, if it is found in more than one base class). If all of
9822 the injected-class-names that are found refer to specializations of
9823 the same class template, and if the name is followed by a
9824 template-argument-list, the reference refers to the class template
9825 itself and not a specialization thereof, and is not ambiguous. */
9826 if (TREE_CODE (decl) == TREE_LIST)
9828 tree t, tmpl = NULL_TREE;
9829 for (t = decl; t; t = TREE_CHAIN (t))
9831 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9832 if (!tmpl)
9833 tmpl = elt;
9834 else if (tmpl != elt)
9835 break;
9837 if (tmpl && t == NULL_TREE)
9838 return tmpl;
9839 else
9840 return decl;
9843 return (decl != NULL_TREE
9844 && DECL_SELF_REFERENCE_P (decl)
9845 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9846 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9849 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9850 parameters, find the desired type.
9852 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9854 IN_DECL, if non-NULL, is the template declaration we are trying to
9855 instantiate.
9857 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9858 the class we are looking up.
9860 Issue error and warning messages under control of COMPLAIN.
9862 If the template class is really a local class in a template
9863 function, then the FUNCTION_CONTEXT is the function in which it is
9864 being instantiated.
9866 ??? Note that this function is currently called *twice* for each
9867 template-id: the first time from the parser, while creating the
9868 incomplete type (finish_template_type), and the second type during the
9869 real instantiation (instantiate_template_class). This is surely something
9870 that we want to avoid. It also causes some problems with argument
9871 coercion (see convert_nontype_argument for more information on this). */
9873 tree
9874 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9875 int entering_scope, tsubst_flags_t complain)
9877 auto_timevar tv (TV_TEMPLATE_INST);
9879 tree templ = NULL_TREE, parmlist;
9880 tree t;
9881 spec_entry **slot;
9882 spec_entry *entry;
9883 spec_entry elt;
9884 hashval_t hash;
9886 if (identifier_p (d1))
9888 tree value = innermost_non_namespace_value (d1);
9889 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9890 templ = value;
9891 else
9893 if (context)
9894 push_decl_namespace (context);
9895 templ = lookup_name (d1);
9896 templ = maybe_get_template_decl_from_type_decl (templ);
9897 if (context)
9898 pop_decl_namespace ();
9901 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9903 tree type = TREE_TYPE (d1);
9905 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9906 an implicit typename for the second A. Deal with it. */
9907 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9908 type = TREE_TYPE (type);
9910 if (CLASSTYPE_TEMPLATE_INFO (type))
9912 templ = CLASSTYPE_TI_TEMPLATE (type);
9913 d1 = DECL_NAME (templ);
9916 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9917 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9919 templ = TYPE_TI_TEMPLATE (d1);
9920 d1 = DECL_NAME (templ);
9922 else if (DECL_TYPE_TEMPLATE_P (d1))
9924 templ = d1;
9925 d1 = DECL_NAME (templ);
9927 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9929 templ = d1;
9930 d1 = DECL_NAME (templ);
9933 /* Issue an error message if we didn't find a template. */
9934 if (! templ)
9936 if (complain & tf_error)
9937 error ("%qT is not a template", d1);
9938 return error_mark_node;
9941 if (TREE_CODE (templ) != TEMPLATE_DECL
9942 /* Make sure it's a user visible template, if it was named by
9943 the user. */
9944 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9945 && !PRIMARY_TEMPLATE_P (templ)))
9947 if (complain & tf_error)
9949 error ("non-template type %qT used as a template", d1);
9950 if (in_decl)
9951 error ("for template declaration %q+D", in_decl);
9953 return error_mark_node;
9956 complain &= ~tf_user;
9958 /* An alias that just changes the name of a template is equivalent to the
9959 other template, so if any of the arguments are pack expansions, strip
9960 the alias to avoid problems with a pack expansion passed to a non-pack
9961 alias template parameter (DR 1430). */
9962 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9963 templ = get_underlying_template (templ);
9965 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9967 tree parm;
9968 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9969 if (arglist2 == error_mark_node
9970 || (!uses_template_parms (arglist2)
9971 && check_instantiated_args (templ, arglist2, complain)))
9972 return error_mark_node;
9974 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9975 return parm;
9977 else
9979 tree template_type = TREE_TYPE (templ);
9980 tree gen_tmpl;
9981 tree type_decl;
9982 tree found = NULL_TREE;
9983 int arg_depth;
9984 int parm_depth;
9985 int is_dependent_type;
9986 int use_partial_inst_tmpl = false;
9988 if (template_type == error_mark_node)
9989 /* An error occurred while building the template TEMPL, and a
9990 diagnostic has most certainly been emitted for that
9991 already. Let's propagate that error. */
9992 return error_mark_node;
9994 gen_tmpl = most_general_template (templ);
9995 if (modules_p ())
9996 lazy_load_pendings (gen_tmpl);
9998 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9999 parm_depth = TMPL_PARMS_DEPTH (parmlist);
10000 arg_depth = TMPL_ARGS_DEPTH (arglist);
10002 if (arg_depth == 1 && parm_depth > 1)
10004 /* We've been given an incomplete set of template arguments.
10005 For example, given:
10007 template <class T> struct S1 {
10008 template <class U> struct S2 {};
10009 template <class U> struct S2<U*> {};
10012 we will be called with an ARGLIST of `U*', but the
10013 TEMPLATE will be `template <class T> template
10014 <class U> struct S1<T>::S2'. We must fill in the missing
10015 arguments. */
10016 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
10017 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
10018 arg_depth = TMPL_ARGS_DEPTH (arglist);
10021 /* Now we should have enough arguments. */
10022 gcc_assert (parm_depth == arg_depth);
10024 /* From here on, we're only interested in the most general
10025 template. */
10027 /* Shortcut looking up the current class scope again. */
10028 if (current_class_type)
10029 if (tree ti = CLASSTYPE_TEMPLATE_INFO (current_class_type))
10030 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
10031 && comp_template_args (arglist, TI_ARGS (ti)))
10032 return current_class_type;
10034 /* Calculate the BOUND_ARGS. These will be the args that are
10035 actually tsubst'd into the definition to create the
10036 instantiation. */
10037 arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
10038 complain,
10039 /*require_all_args=*/true,
10040 /*use_default_args=*/true);
10042 if (arglist == error_mark_node)
10043 /* We were unable to bind the arguments. */
10044 return error_mark_node;
10046 /* In the scope of a template class, explicit references to the
10047 template class refer to the type of the template, not any
10048 instantiation of it. For example, in:
10050 template <class T> class C { void f(C<T>); }
10052 the `C<T>' is just the same as `C'. Outside of the
10053 class, however, such a reference is an instantiation. */
10054 if (entering_scope
10055 || !PRIMARY_TEMPLATE_P (gen_tmpl)
10056 || currently_open_class (template_type))
10058 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10060 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10061 return template_type;
10064 /* If we already have this specialization, return it. */
10065 elt.tmpl = gen_tmpl;
10066 elt.args = arglist;
10067 elt.spec = NULL_TREE;
10068 hash = spec_hasher::hash (&elt);
10069 entry = type_specializations->find_with_hash (&elt, hash);
10071 if (entry)
10072 return entry->spec;
10074 /* If the template's constraints are not satisfied,
10075 then we cannot form a valid type.
10077 Note that the check is deferred until after the hash
10078 lookup. This prevents redundant checks on previously
10079 instantiated specializations. */
10080 if (flag_concepts
10081 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10082 && !constraints_satisfied_p (gen_tmpl, arglist))
10084 if (complain & tf_error)
10086 auto_diagnostic_group d;
10087 error ("template constraint failure for %qD", gen_tmpl);
10088 diagnose_constraints (input_location, gen_tmpl, arglist);
10090 return error_mark_node;
10093 is_dependent_type = uses_template_parms (arglist);
10095 /* If the deduced arguments are invalid, then the binding
10096 failed. */
10097 if (!is_dependent_type
10098 && check_instantiated_args (gen_tmpl,
10099 INNERMOST_TEMPLATE_ARGS (arglist),
10100 complain))
10101 return error_mark_node;
10103 if (!is_dependent_type
10104 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10105 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10106 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10107 /* This occurs when the user has tried to define a tagged type
10108 in a scope that forbids it. We emitted an error during the
10109 parse. We didn't complete the bail out then, so here we
10110 are. */
10111 return error_mark_node;
10113 context = DECL_CONTEXT (gen_tmpl);
10114 if (context && TYPE_P (context))
10116 if (!uses_template_parms (DECL_CONTEXT (templ)))
10117 /* If the context of the partially instantiated template is
10118 already non-dependent, then we might as well use it. */
10119 context = DECL_CONTEXT (templ);
10120 else
10122 context = tsubst_aggr_type (context, arglist,
10123 complain, in_decl, true);
10124 /* Try completing the enclosing context if it's not already so. */
10125 if (context != error_mark_node
10126 && !COMPLETE_TYPE_P (context))
10128 context = complete_type (context);
10129 if (COMPLETE_TYPE_P (context))
10131 /* Completion could have caused us to register the desired
10132 specialization already, so check the table again. */
10133 entry = type_specializations->find_with_hash (&elt, hash);
10134 if (entry)
10135 return entry->spec;
10140 else
10141 context = tsubst (context, arglist, complain, in_decl);
10143 if (context == error_mark_node)
10144 return error_mark_node;
10146 if (!context)
10147 context = global_namespace;
10149 /* Create the type. */
10150 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10152 /* The user referred to a specialization of an alias
10153 template represented by GEN_TMPL.
10155 [temp.alias]/2 says:
10157 When a template-id refers to the specialization of an
10158 alias template, it is equivalent to the associated
10159 type obtained by substitution of its
10160 template-arguments for the template-parameters in the
10161 type-id of the alias template. */
10163 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10164 /* Note that the call above (by indirectly calling
10165 register_specialization in tsubst_decl) registers the
10166 TYPE_DECL representing the specialization of the alias
10167 template. So next time someone substitutes ARGLIST for
10168 the template parms into the alias template (GEN_TMPL),
10169 she'll get that TYPE_DECL back. */
10171 if (t == error_mark_node)
10172 return t;
10174 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10176 if (!is_dependent_type)
10178 set_current_access_from_decl (TYPE_NAME (template_type));
10179 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10180 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10181 arglist, complain, in_decl),
10182 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10183 arglist, complain, in_decl),
10184 SCOPED_ENUM_P (template_type), NULL);
10186 if (t == error_mark_node)
10187 return t;
10189 else
10191 /* We don't want to call start_enum for this type, since
10192 the values for the enumeration constants may involve
10193 template parameters. And, no one should be interested
10194 in the enumeration constants for such a type. */
10195 t = cxx_make_type (ENUMERAL_TYPE);
10196 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10198 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10199 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10200 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10202 else if (CLASS_TYPE_P (template_type))
10204 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10205 instantiated here. */
10206 gcc_assert (!LAMBDA_TYPE_P (template_type));
10208 t = make_class_type (TREE_CODE (template_type));
10209 CLASSTYPE_DECLARED_CLASS (t)
10210 = CLASSTYPE_DECLARED_CLASS (template_type);
10211 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10213 /* A local class. Make sure the decl gets registered properly. */
10214 if (context == current_function_decl)
10215 if (pushtag (DECL_NAME (gen_tmpl), t)
10216 == error_mark_node)
10217 return error_mark_node;
10219 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10220 /* This instantiation is another name for the primary
10221 template type. Set the TYPE_CANONICAL field
10222 appropriately. */
10223 TYPE_CANONICAL (t) = template_type;
10224 else if (any_template_arguments_need_structural_equality_p (arglist))
10225 SET_TYPE_STRUCTURAL_EQUALITY (t);
10227 else
10228 gcc_unreachable ();
10230 /* If we called start_enum or pushtag above, this information
10231 will already be set up. */
10232 type_decl = TYPE_NAME (t);
10233 if (!type_decl)
10235 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10237 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10238 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10239 DECL_SOURCE_LOCATION (type_decl)
10240 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10243 set_instantiating_module (type_decl);
10244 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10245 of export flag. We want to propagate this because it might
10246 be a friend declaration that pushes a new hidden binding. */
10247 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10249 if (CLASS_TYPE_P (template_type))
10251 TREE_PRIVATE (type_decl)
10252 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10253 TREE_PROTECTED (type_decl)
10254 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10255 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10257 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10258 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10262 if (OVERLOAD_TYPE_P (t)
10263 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10265 static const char *tags[] = {"abi_tag", "may_alias"};
10267 for (unsigned ix = 0; ix != 2; ix++)
10269 tree attributes
10270 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10272 if (attributes)
10273 TYPE_ATTRIBUTES (t)
10274 = tree_cons (TREE_PURPOSE (attributes),
10275 TREE_VALUE (attributes),
10276 TYPE_ATTRIBUTES (t));
10280 /* Let's consider the explicit specialization of a member
10281 of a class template specialization that is implicitly instantiated,
10282 e.g.:
10283 template<class T>
10284 struct S
10286 template<class U> struct M {}; //#0
10289 template<>
10290 template<>
10291 struct S<int>::M<char> //#1
10293 int i;
10295 [temp.expl.spec]/4 says this is valid.
10297 In this case, when we write:
10298 S<int>::M<char> m;
10300 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10301 the one of #0.
10303 When we encounter #1, we want to store the partial instantiation
10304 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10306 For all cases other than this "explicit specialization of member of a
10307 class template", we just want to store the most general template into
10308 the CLASSTYPE_TI_TEMPLATE of M.
10310 This case of "explicit specialization of member of a class template"
10311 only happens when:
10312 1/ the enclosing class is an instantiation of, and therefore not
10313 the same as, the context of the most general template, and
10314 2/ we aren't looking at the partial instantiation itself, i.e.
10315 the innermost arguments are not the same as the innermost parms of
10316 the most general template.
10318 So it's only when 1/ and 2/ happens that we want to use the partial
10319 instantiation of the member template in lieu of its most general
10320 template. */
10322 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10323 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10324 /* the enclosing class must be an instantiation... */
10325 && CLASS_TYPE_P (context)
10326 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10328 TREE_VEC_LENGTH (arglist)--;
10329 ++processing_template_decl;
10330 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10331 tree partial_inst_args =
10332 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10333 arglist, complain, NULL_TREE);
10334 --processing_template_decl;
10335 TREE_VEC_LENGTH (arglist)++;
10336 if (partial_inst_args == error_mark_node)
10337 return error_mark_node;
10338 use_partial_inst_tmpl =
10339 /*...and we must not be looking at the partial instantiation
10340 itself. */
10341 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10342 partial_inst_args);
10345 if (!use_partial_inst_tmpl)
10346 /* This case is easy; there are no member templates involved. */
10347 found = gen_tmpl;
10348 else
10350 /* This is a full instantiation of a member template. Find
10351 the partial instantiation of which this is an instance. */
10353 /* Temporarily reduce by one the number of levels in the ARGLIST
10354 so as to avoid comparing the last set of arguments. */
10355 TREE_VEC_LENGTH (arglist)--;
10356 /* We don't use COMPLAIN in the following call because this isn't
10357 the immediate context of deduction. For instance, tf_partial
10358 could be set here as we might be at the beginning of template
10359 argument deduction when any explicitly specified template
10360 arguments are substituted into the function type. tf_partial
10361 could lead into trouble because we wouldn't find the partial
10362 instantiation that might have been created outside tf_partial
10363 context, because the levels of template parameters wouldn't
10364 match, because in a tf_partial context, tsubst doesn't reduce
10365 TEMPLATE_PARM_LEVEL. */
10366 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10367 TREE_VEC_LENGTH (arglist)++;
10368 /* FOUND is either a proper class type, or an alias
10369 template specialization. In the later case, it's a
10370 TYPE_DECL, resulting from the substituting of arguments
10371 for parameters in the TYPE_DECL of the alias template
10372 done earlier. So be careful while getting the template
10373 of FOUND. */
10374 found = (TREE_CODE (found) == TEMPLATE_DECL
10375 ? found
10376 : (TREE_CODE (found) == TYPE_DECL
10377 ? DECL_TI_TEMPLATE (found)
10378 : CLASSTYPE_TI_TEMPLATE (found)));
10380 if (DECL_CLASS_TEMPLATE_P (found)
10381 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10383 /* If this partial instantiation is specialized, we want to
10384 use it for hash table lookup. */
10385 elt.tmpl = found;
10386 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10387 hash = spec_hasher::hash (&elt);
10391 /* Build template info for the new specialization. */
10392 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10394 elt.spec = t;
10395 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10396 gcc_checking_assert (*slot == NULL);
10397 entry = ggc_alloc<spec_entry> ();
10398 *entry = elt;
10399 *slot = entry;
10401 /* Note this use of the partial instantiation so we can check it
10402 later in maybe_process_partial_specialization. */
10403 DECL_TEMPLATE_INSTANTIATIONS (found)
10404 = tree_cons (arglist, t,
10405 DECL_TEMPLATE_INSTANTIATIONS (found));
10407 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10408 && !uses_template_parms (current_nonlambda_scope ())
10409 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10410 /* Now that the type has been registered on the instantiations
10411 list, we set up the enumerators. Because the enumeration
10412 constants may involve the enumeration type itself, we make
10413 sure to register the type first, and then create the
10414 constants. That way, doing tsubst_expr for the enumeration
10415 constants won't result in recursive calls here; we'll find
10416 the instantiation and exit above. */
10417 tsubst_enum (template_type, t, arglist);
10419 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10420 /* If the type makes use of template parameters, the
10421 code that generates debugging information will crash. */
10422 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10424 /* Possibly limit visibility based on template args. */
10425 TREE_PUBLIC (type_decl) = 1;
10426 determine_visibility (type_decl);
10428 inherit_targ_abi_tags (t);
10430 return t;
10434 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10436 tree
10437 lookup_template_variable (tree templ, tree arglist)
10439 if (flag_concepts && variable_concept_p (templ))
10440 return build_concept_check (templ, arglist, tf_none);
10442 /* The type of the expression is NULL_TREE since the template-id could refer
10443 to an explicit or partial specialization. */
10444 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10447 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10449 tree
10450 finish_template_variable (tree var, tsubst_flags_t complain)
10452 tree templ = TREE_OPERAND (var, 0);
10453 tree arglist = TREE_OPERAND (var, 1);
10455 tree parms = DECL_TEMPLATE_PARMS (templ);
10456 arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10457 /*req_all*/true,
10458 /*use_default*/true);
10459 if (arglist == error_mark_node)
10460 return error_mark_node;
10462 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10464 if (complain & tf_error)
10466 auto_diagnostic_group d;
10467 error ("use of invalid variable template %qE", var);
10468 diagnose_constraints (location_of (var), templ, arglist);
10470 return error_mark_node;
10473 return instantiate_template (templ, arglist, complain);
10476 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10477 TARGS template args, and instantiate it if it's not dependent. */
10479 tree
10480 lookup_and_finish_template_variable (tree templ, tree targs,
10481 tsubst_flags_t complain)
10483 templ = lookup_template_variable (templ, targs);
10484 if (!any_dependent_template_arguments_p (targs))
10486 templ = finish_template_variable (templ, complain);
10487 mark_used (templ);
10490 return convert_from_reference (templ);
10493 /* If the set of template parameters PARMS contains a template parameter
10494 at the given LEVEL and INDEX, then return this parameter. Otherwise
10495 return NULL_TREE. */
10497 static tree
10498 corresponding_template_parameter (tree parms, int level, int index)
10500 while (TMPL_PARMS_DEPTH (parms) > level)
10501 parms = TREE_CHAIN (parms);
10503 if (TMPL_PARMS_DEPTH (parms) != level
10504 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10505 return NULL_TREE;
10507 tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10508 /* As in template_parm_to_arg. */
10509 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10510 t = TREE_TYPE (t);
10511 else
10512 t = DECL_INITIAL (t);
10514 gcc_assert (TEMPLATE_PARM_P (t));
10515 return t;
10518 /* Return the template parameter from PARMS that positionally corresponds
10519 to the template parameter PARM, or else return NULL_TREE. */
10521 static tree
10522 corresponding_template_parameter (tree parms, tree parm)
10524 int level, index;
10525 template_parm_level_and_index (parm, &level, &index);
10526 return corresponding_template_parameter (parms, level, index);
10530 struct pair_fn_data
10532 tree_fn_t fn;
10533 tree_fn_t any_fn;
10534 void *data;
10535 /* True when we should also visit template parameters that occur in
10536 non-deduced contexts. */
10537 bool include_nondeduced_p;
10538 hash_set<tree> *visited;
10541 /* Called from for_each_template_parm via walk_tree. */
10543 static tree
10544 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10546 tree t = *tp;
10547 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10548 tree_fn_t fn = pfd->fn;
10549 void *data = pfd->data;
10550 tree result = NULL_TREE;
10552 #define WALK_SUBTREE(NODE) \
10553 do \
10555 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10556 pfd->include_nondeduced_p, \
10557 pfd->any_fn); \
10558 if (result) goto out; \
10560 while (0)
10562 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10563 return t;
10565 if (TYPE_P (t)
10566 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10567 WALK_SUBTREE (TYPE_CONTEXT (t));
10569 switch (TREE_CODE (t))
10571 case RECORD_TYPE:
10572 if (TYPE_PTRMEMFUNC_P (t))
10573 break;
10574 /* Fall through. */
10576 case UNION_TYPE:
10577 case ENUMERAL_TYPE:
10578 if (!TYPE_TEMPLATE_INFO (t))
10579 *walk_subtrees = 0;
10580 else
10581 WALK_SUBTREE (TYPE_TI_ARGS (t));
10582 break;
10584 case INTEGER_TYPE:
10585 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10586 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10587 break;
10589 case METHOD_TYPE:
10590 /* Since we're not going to walk subtrees, we have to do this
10591 explicitly here. */
10592 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10593 /* Fall through. */
10595 case FUNCTION_TYPE:
10596 /* Check the return type. */
10597 WALK_SUBTREE (TREE_TYPE (t));
10599 /* Check the parameter types. Since default arguments are not
10600 instantiated until they are needed, the TYPE_ARG_TYPES may
10601 contain expressions that involve template parameters. But,
10602 no-one should be looking at them yet. And, once they're
10603 instantiated, they don't contain template parameters, so
10604 there's no point in looking at them then, either. */
10606 tree parm;
10608 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10609 WALK_SUBTREE (TREE_VALUE (parm));
10611 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10612 want walk_tree walking into them itself. */
10613 *walk_subtrees = 0;
10616 if (flag_noexcept_type)
10618 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10619 if (spec)
10620 WALK_SUBTREE (TREE_PURPOSE (spec));
10622 break;
10624 case TYPEOF_TYPE:
10625 case DECLTYPE_TYPE:
10626 case UNDERLYING_TYPE:
10627 if (pfd->include_nondeduced_p
10628 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10629 pfd->visited,
10630 pfd->include_nondeduced_p,
10631 pfd->any_fn))
10632 return error_mark_node;
10633 *walk_subtrees = false;
10634 break;
10636 case FUNCTION_DECL:
10637 case VAR_DECL:
10638 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10639 WALK_SUBTREE (DECL_TI_ARGS (t));
10640 break;
10642 case PARM_DECL:
10643 WALK_SUBTREE (TREE_TYPE (t));
10644 break;
10646 case CONST_DECL:
10647 if (DECL_TEMPLATE_PARM_P (t))
10648 WALK_SUBTREE (DECL_INITIAL (t));
10649 if (DECL_CONTEXT (t)
10650 && pfd->include_nondeduced_p)
10651 WALK_SUBTREE (DECL_CONTEXT (t));
10652 break;
10654 case BOUND_TEMPLATE_TEMPLATE_PARM:
10655 /* Record template parameters such as `T' inside `TT<T>'. */
10656 WALK_SUBTREE (TYPE_TI_ARGS (t));
10657 /* Fall through. */
10659 case TEMPLATE_TEMPLATE_PARM:
10660 case TEMPLATE_TYPE_PARM:
10661 case TEMPLATE_PARM_INDEX:
10662 if (fn && (*fn)(t, data))
10663 return t;
10664 else if (!fn)
10665 return t;
10666 break;
10668 case TEMPLATE_DECL:
10669 /* A template template parameter is encountered. */
10670 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10671 WALK_SUBTREE (TREE_TYPE (t));
10673 /* Already substituted template template parameter */
10674 *walk_subtrees = 0;
10675 break;
10677 case TYPENAME_TYPE:
10678 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10679 partial instantiation. */
10680 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10681 *walk_subtrees = 0;
10682 break;
10684 case INDIRECT_REF:
10685 case COMPONENT_REF:
10686 /* If there's no type, then this thing must be some expression
10687 involving template parameters. */
10688 if (!fn && !TREE_TYPE (t))
10689 return error_mark_node;
10690 break;
10692 case CONSTRUCTOR:
10693 case TRAIT_EXPR:
10694 case PLUS_EXPR:
10695 case MULT_EXPR:
10696 case SCOPE_REF:
10697 /* These are non-deduced contexts. */
10698 if (!pfd->include_nondeduced_p)
10699 *walk_subtrees = 0;
10700 break;
10702 case MODOP_EXPR:
10703 case CAST_EXPR:
10704 case IMPLICIT_CONV_EXPR:
10705 case REINTERPRET_CAST_EXPR:
10706 case CONST_CAST_EXPR:
10707 case STATIC_CAST_EXPR:
10708 case DYNAMIC_CAST_EXPR:
10709 case ARROW_EXPR:
10710 case DOTSTAR_EXPR:
10711 case TYPEID_EXPR:
10712 case PSEUDO_DTOR_EXPR:
10713 if (!fn)
10714 return error_mark_node;
10715 break;
10717 case REQUIRES_EXPR:
10719 if (!fn)
10720 return error_mark_node;
10722 /* Recursively walk the type of each constraint variable. */
10723 tree p = TREE_OPERAND (t, 0);
10724 while (p)
10726 WALK_SUBTREE (TREE_TYPE (p));
10727 p = TREE_CHAIN (p);
10730 break;
10732 default:
10733 break;
10736 #undef WALK_SUBTREE
10738 /* We didn't find any template parameters we liked. */
10739 out:
10740 return result;
10743 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10744 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10745 call FN with the parameter and the DATA.
10746 If FN returns nonzero, the iteration is terminated, and
10747 for_each_template_parm returns 1. Otherwise, the iteration
10748 continues. If FN never returns a nonzero value, the value
10749 returned by for_each_template_parm is 0. If FN is NULL, it is
10750 considered to be the function which always returns 1.
10752 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10753 parameters that occur in non-deduced contexts. When false, only
10754 visits those template parameters that can be deduced. */
10756 static tree
10757 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10758 hash_set<tree> *visited,
10759 bool include_nondeduced_p,
10760 tree_fn_t any_fn)
10762 struct pair_fn_data pfd;
10763 tree result;
10765 /* Set up. */
10766 pfd.fn = fn;
10767 pfd.any_fn = any_fn;
10768 pfd.data = data;
10769 pfd.include_nondeduced_p = include_nondeduced_p;
10771 /* Walk the tree. (Conceptually, we would like to walk without
10772 duplicates, but for_each_template_parm_r recursively calls
10773 for_each_template_parm, so we would need to reorganize a fair
10774 bit to use walk_tree_without_duplicates, so we keep our own
10775 visited list.) */
10776 if (visited)
10777 pfd.visited = visited;
10778 else
10779 pfd.visited = new hash_set<tree>;
10780 result = cp_walk_tree (&t,
10781 for_each_template_parm_r,
10782 &pfd,
10783 pfd.visited);
10785 /* Clean up. */
10786 if (!visited)
10788 delete pfd.visited;
10789 pfd.visited = 0;
10792 return result;
10795 struct find_template_parameter_info
10797 explicit find_template_parameter_info (tree ctx_parms)
10798 : parm_list (NULL_TREE),
10799 ctx_parms (ctx_parms),
10800 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10803 hash_set<tree> visited;
10804 hash_set<tree> parms;
10805 tree parm_list;
10806 tree ctx_parms;
10807 int max_depth;
10810 /* Appends the declaration of T to the list in DATA. */
10812 static int
10813 keep_template_parm (tree t, void* data)
10815 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10817 /* Template parameters declared within the expression are not part of
10818 the parameter mapping. For example, in this concept:
10820 template<typename T>
10821 concept C = requires { <expr> } -> same_as<int>;
10823 the return specifier same_as<int> declares a new decltype parameter
10824 that must not be part of the parameter mapping. The same is true
10825 for generic lambda parameters, lambda template parameters, etc. */
10826 int level;
10827 int index;
10828 template_parm_level_and_index (t, &level, &index);
10829 if (level == 0 || level > ftpi->max_depth)
10830 return 0;
10832 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10833 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10834 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10835 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10837 /* This template parameter might be an argument to a cached dependent
10838 specalization that was formed earlier inside some other template, in
10839 which case the parameter is not among the ones that are in-scope.
10840 Look in CTX_PARMS to find the corresponding in-scope template
10841 parameter, and use it instead. */
10842 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10843 t = in_scope;
10845 /* Arguments like const T yield parameters like const T. This means that
10846 a template-id like X<T, const T> would yield two distinct parameters:
10847 T and const T. Adjust types to their unqualified versions. */
10848 if (TYPE_P (t))
10849 t = TYPE_MAIN_VARIANT (t);
10850 if (!ftpi->parms.add (t))
10851 ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10853 /* Verify the parameter we found has a valid index. */
10854 if (flag_checking)
10856 tree parms = ftpi->ctx_parms;
10857 while (TMPL_PARMS_DEPTH (parms) > level)
10858 parms = TREE_CHAIN (parms);
10859 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10860 gcc_assert (index < len);
10863 return 0;
10866 /* Ensure that we recursively examine certain terms that are not normally
10867 visited in for_each_template_parm_r. */
10869 static int
10870 any_template_parm_r (tree t, void *data)
10872 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10874 #define WALK_SUBTREE(NODE) \
10875 do \
10877 for_each_template_parm (NODE, keep_template_parm, data, \
10878 &ftpi->visited, true, \
10879 any_template_parm_r); \
10881 while (0)
10883 /* A mention of a member alias/typedef is a use of all of its template
10884 arguments, including those from the enclosing class, so we don't use
10885 alias_template_specialization_p here. */
10886 if (TYPE_P (t) && typedef_variant_p (t))
10887 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10888 WALK_SUBTREE (TI_ARGS (tinfo));
10890 switch (TREE_CODE (t))
10892 case TEMPLATE_TYPE_PARM:
10893 /* Type constraints of a placeholder type may contain parameters. */
10894 if (is_auto (t))
10895 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10896 WALK_SUBTREE (constr);
10897 break;
10899 case TEMPLATE_ID_EXPR:
10900 /* Search through references to variable templates. */
10901 WALK_SUBTREE (TREE_OPERAND (t, 0));
10902 WALK_SUBTREE (TREE_OPERAND (t, 1));
10903 break;
10905 case TEMPLATE_PARM_INDEX:
10906 WALK_SUBTREE (TREE_TYPE (t));
10907 break;
10909 case TEMPLATE_DECL:
10910 /* If T is a member template that shares template parameters with
10911 ctx_parms, we need to mark all those parameters for mapping.
10912 To that end, it should suffice to just walk the DECL_CONTEXT of
10913 the template (assuming the template is not overly general). */
10914 WALK_SUBTREE (DECL_CONTEXT (t));
10915 break;
10917 case LAMBDA_EXPR:
10919 /* Look in the parms and body. */
10920 tree fn = lambda_function (t);
10921 WALK_SUBTREE (TREE_TYPE (fn));
10922 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10924 break;
10926 case IDENTIFIER_NODE:
10927 if (IDENTIFIER_CONV_OP_P (t))
10928 /* The conversion-type-id of a conversion operator may be dependent. */
10929 WALK_SUBTREE (TREE_TYPE (t));
10930 break;
10932 case CONVERT_EXPR:
10933 if (is_dummy_object (t))
10934 WALK_SUBTREE (TREE_TYPE (t));
10935 break;
10937 default:
10938 break;
10941 /* Keep walking. */
10942 return 0;
10945 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10946 are the template parameters in scope. */
10948 tree
10949 find_template_parameters (tree t, tree ctx_parms)
10951 if (!ctx_parms)
10952 return NULL_TREE;
10954 find_template_parameter_info ftpi (ctx_parms);
10955 for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10956 /*include_nondeduced*/true, any_template_parm_r);
10957 return ftpi.parm_list;
10960 /* Returns true if T depends on any template parameter. */
10962 bool
10963 uses_template_parms (tree t)
10965 if (t == NULL_TREE || t == error_mark_node)
10966 return false;
10968 /* Namespaces can't depend on any template parameters. */
10969 if (TREE_CODE (t) == NAMESPACE_DECL)
10970 return false;
10972 processing_template_decl_sentinel ptds (/*reset*/false);
10973 ++processing_template_decl;
10975 if (TYPE_P (t))
10976 return dependent_type_p (t);
10977 else if (TREE_CODE (t) == TREE_VEC)
10978 return any_dependent_template_arguments_p (t);
10979 else if (TREE_CODE (t) == TREE_LIST)
10980 return (uses_template_parms (TREE_VALUE (t))
10981 || uses_template_parms (TREE_CHAIN (t)));
10982 else if (TREE_CODE (t) == TYPE_DECL)
10983 return dependent_type_p (TREE_TYPE (t));
10984 else
10985 return instantiation_dependent_expression_p (t);
10988 /* Returns true iff we're processing an incompletely instantiated function
10989 template. Useful instead of processing_template_decl because the latter
10990 is set to 0 during instantiate_non_dependent_expr. */
10992 bool
10993 in_template_function (void)
10995 /* Inspect the less volatile cfun->decl instead of current_function_decl;
10996 the latter might get set for e.g. access checking during satisfaction. */
10997 tree fn = cfun ? cfun->decl : NULL_TREE;
10998 bool ret;
10999 ++processing_template_decl;
11000 ret = (fn && DECL_LANG_SPECIFIC (fn)
11001 && DECL_TEMPLATE_INFO (fn)
11002 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
11003 --processing_template_decl;
11004 return ret;
11007 /* Returns true if T depends on any template parameter with level LEVEL. */
11009 bool
11010 uses_template_parms_level (tree t, int level)
11012 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
11013 /*include_nondeduced_p=*/true);
11016 /* Returns true if the signature of DECL depends on any template parameter from
11017 its enclosing class. */
11019 static bool
11020 uses_outer_template_parms (tree decl)
11022 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11023 if (depth == 0)
11024 return false;
11025 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
11026 &depth, NULL, /*include_nondeduced_p=*/true))
11027 return true;
11028 if (PRIMARY_TEMPLATE_P (decl)
11029 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11031 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
11032 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
11034 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
11035 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11036 if (TREE_CODE (parm) == PARM_DECL
11037 && for_each_template_parm (TREE_TYPE (parm),
11038 template_parm_outer_level,
11039 &depth, NULL, /*nondeduced*/true))
11040 return true;
11041 if (TREE_CODE (parm) == TEMPLATE_DECL
11042 && uses_outer_template_parms (parm))
11043 return true;
11044 if (defarg
11045 && for_each_template_parm (defarg, template_parm_outer_level,
11046 &depth, NULL, /*nondeduced*/true))
11047 return true;
11050 if (uses_outer_template_parms_in_constraints (decl))
11051 return true;
11052 return false;
11055 /* Returns true if the constraints of DECL depend on any template parameters
11056 from its enclosing scope. */
11058 bool
11059 uses_outer_template_parms_in_constraints (tree decl)
11061 tree ci = get_constraints (decl);
11062 if (ci)
11063 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11064 if (!ci)
11065 return false;
11066 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11067 if (depth == 0)
11068 return false;
11069 return for_each_template_parm (ci, template_parm_outer_level,
11070 &depth, NULL, /*nondeduced*/true);
11073 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11074 ill-formed translation unit, i.e. a variable or function that isn't
11075 usable in a constant expression. */
11077 static inline bool
11078 neglectable_inst_p (tree d)
11080 return (d && DECL_P (d)
11081 && !undeduced_auto_decl (d)
11082 && !(TREE_CODE (d) == FUNCTION_DECL
11083 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11084 : decl_maybe_constant_var_p (d)));
11087 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11088 neglectable and instantiated from within an erroneous instantiation. */
11090 static bool
11091 limit_bad_template_recursion (tree decl)
11093 struct tinst_level *lev = current_tinst_level;
11094 int errs = errorcount + sorrycount;
11095 if (errs == 0 || !neglectable_inst_p (decl))
11096 return false;
11098 /* Avoid instantiating members of an ill-formed class. */
11099 bool refuse
11100 = (DECL_CLASS_SCOPE_P (decl)
11101 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11103 if (!refuse)
11105 for (; lev; lev = lev->next)
11106 if (neglectable_inst_p (lev->maybe_get_node ()))
11107 break;
11108 refuse = (lev && errs > lev->errors);
11111 if (refuse)
11113 /* Don't warn about it not being defined. */
11114 suppress_warning (decl, OPT_Wunused);
11115 tree clone;
11116 FOR_EACH_CLONE (clone, decl)
11117 suppress_warning (clone, OPT_Wunused);
11119 return refuse;
11122 static int tinst_depth;
11123 extern int max_tinst_depth;
11124 int depth_reached;
11126 static GTY(()) struct tinst_level *last_error_tinst_level;
11128 /* We're starting to instantiate D; record the template instantiation context
11129 at LOC for diagnostics and to restore it later. */
11131 bool
11132 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11134 struct tinst_level *new_level;
11136 if (tinst_depth >= max_tinst_depth)
11138 /* Tell error.cc not to try to instantiate any templates. */
11139 at_eof = 2;
11140 fatal_error (input_location,
11141 "template instantiation depth exceeds maximum of %d"
11142 " (use %<-ftemplate-depth=%> to increase the maximum)",
11143 max_tinst_depth);
11144 return false;
11147 /* If the current instantiation caused problems, don't let it instantiate
11148 anything else. Do allow deduction substitution and decls usable in
11149 constant expressions. */
11150 if (!targs && limit_bad_template_recursion (tldcl))
11152 /* Avoid no_linkage_errors and unused function (and all other)
11153 warnings for this decl. */
11154 suppress_warning (tldcl);
11155 return false;
11158 /* When not -quiet, dump template instantiations other than functions, since
11159 announce_function will take care of those. */
11160 if (!quiet_flag && !targs
11161 && TREE_CODE (tldcl) != TREE_LIST
11162 && TREE_CODE (tldcl) != FUNCTION_DECL)
11163 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11165 new_level = tinst_level_freelist ().alloc ();
11166 new_level->tldcl = tldcl;
11167 new_level->targs = targs;
11168 new_level->locus = loc;
11169 new_level->errors = errorcount + sorrycount;
11170 new_level->next = NULL;
11171 new_level->refcount = 0;
11172 new_level->path = new_level->visible = nullptr;
11173 set_refcount_ptr (new_level->next, current_tinst_level);
11174 set_refcount_ptr (current_tinst_level, new_level);
11176 ++tinst_depth;
11177 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11178 depth_reached = tinst_depth;
11180 return true;
11183 /* We're starting substitution of TMPL<ARGS>; record the template
11184 substitution context for diagnostics and to restore it later. */
11186 bool
11187 push_tinst_level (tree tmpl, tree args)
11189 return push_tinst_level_loc (tmpl, args, input_location);
11192 /* We're starting to instantiate D; record INPUT_LOCATION and the
11193 template instantiation context for diagnostics and to restore it
11194 later. */
11196 bool
11197 push_tinst_level (tree d)
11199 return push_tinst_level_loc (d, input_location);
11202 /* Likewise, but record LOC as the program location. */
11204 bool
11205 push_tinst_level_loc (tree d, location_t loc)
11207 gcc_assert (TREE_CODE (d) != TREE_LIST);
11208 return push_tinst_level_loc (d, NULL, loc);
11211 /* We're done instantiating this template; return to the instantiation
11212 context. */
11214 void
11215 pop_tinst_level (void)
11217 /* Restore the filename and line number stashed away when we started
11218 this instantiation. */
11219 input_location = current_tinst_level->locus;
11220 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11221 --tinst_depth;
11224 /* We're instantiating a deferred template; restore the template
11225 instantiation context in which the instantiation was requested, which
11226 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11228 static tree
11229 reopen_tinst_level (struct tinst_level *level)
11231 struct tinst_level *t;
11233 tinst_depth = 0;
11234 for (t = level; t; t = t->next)
11235 ++tinst_depth;
11237 set_refcount_ptr (current_tinst_level, level);
11238 pop_tinst_level ();
11239 if (current_tinst_level)
11240 current_tinst_level->errors = errorcount+sorrycount;
11241 return level->maybe_get_node ();
11244 /* Returns the TINST_LEVEL which gives the original instantiation
11245 context. */
11247 struct tinst_level *
11248 outermost_tinst_level (void)
11250 struct tinst_level *level = current_tinst_level;
11251 if (level)
11252 while (level->next)
11253 level = level->next;
11254 return level;
11257 /* True iff T is a friend function declaration that is not itself a template
11258 and is not defined in a class template. */
11260 bool
11261 non_templated_friend_p (tree t)
11263 if (t && TREE_CODE (t) == FUNCTION_DECL
11264 && DECL_UNIQUE_FRIEND_P (t))
11266 tree ti = DECL_TEMPLATE_INFO (t);
11267 if (!ti)
11268 return true;
11269 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11270 if (DECL_FRIEND_CONTEXT (t))
11271 return false;
11272 /* Non-templated friends in a class template are still represented with a
11273 TEMPLATE_DECL; check that its primary template is the befriending
11274 class. Note that DECL_PRIMARY_TEMPLATE is null for
11275 template <class T> friend A<T>::f(); */
11276 tree tmpl = TI_TEMPLATE (ti);
11277 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11278 return (primary && primary != tmpl);
11280 else
11281 return false;
11284 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11285 vector of template arguments, as for tsubst.
11287 Returns an appropriate tsubst'd friend declaration. */
11289 static tree
11290 tsubst_friend_function (tree decl, tree args)
11292 tree new_friend;
11294 if (TREE_CODE (decl) == FUNCTION_DECL
11295 && DECL_TEMPLATE_INSTANTIATION (decl)
11296 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11297 /* This was a friend declared with an explicit template
11298 argument list, e.g.:
11300 friend void f<>(T);
11302 to indicate that f was a template instantiation, not a new
11303 function declaration. Now, we have to figure out what
11304 instantiation of what template. */
11306 tree template_id, arglist, fns;
11307 tree new_args;
11308 tree tmpl;
11309 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11311 /* Friend functions are looked up in the containing namespace scope.
11312 We must enter that scope, to avoid finding member functions of the
11313 current class with same name. */
11314 push_nested_namespace (ns);
11315 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11316 tf_warning_or_error, NULL_TREE,
11317 /*integral_constant_expression_p=*/false);
11318 pop_nested_namespace (ns);
11319 arglist = tsubst (DECL_TI_ARGS (decl), args,
11320 tf_warning_or_error, NULL_TREE);
11321 template_id = lookup_template_function (fns, arglist);
11323 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11324 tmpl = determine_specialization (template_id, new_friend,
11325 &new_args,
11326 /*need_member_template=*/0,
11327 TREE_VEC_LENGTH (args),
11328 tsk_none);
11329 return instantiate_template (tmpl, new_args, tf_error);
11332 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11333 if (new_friend == error_mark_node)
11334 return error_mark_node;
11336 /* The NEW_FRIEND will look like an instantiation, to the
11337 compiler, but is not an instantiation from the point of view of
11338 the language. For example, we might have had:
11340 template <class T> struct S {
11341 template <class U> friend void f(T, U);
11344 Then, in S<int>, template <class U> void f(int, U) is not an
11345 instantiation of anything. */
11347 DECL_USE_TEMPLATE (new_friend) = 0;
11348 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11350 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11351 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11352 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11353 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11355 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11356 match in decls_match. */
11357 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11358 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11359 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11360 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11362 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11363 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11364 tsubst_each_template_parm_constraints (parms, args,
11365 tf_warning_or_error);
11369 /* The mangled name for the NEW_FRIEND is incorrect. The function
11370 is not a template instantiation and should not be mangled like
11371 one. Therefore, we forget the mangling here; we'll recompute it
11372 later if we need it. */
11373 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11375 SET_DECL_RTL (new_friend, NULL);
11376 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11379 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11381 tree old_decl;
11382 tree ns;
11384 /* We must save some information from NEW_FRIEND before calling
11385 duplicate decls since that function will free NEW_FRIEND if
11386 possible. */
11387 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11388 tree new_friend_result_template_info = NULL_TREE;
11389 bool new_friend_is_defn =
11390 (new_friend_template_info
11391 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11392 (template_for_substitution (new_friend)))
11393 != NULL_TREE));
11394 tree not_tmpl = new_friend;
11396 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11398 /* This declaration is a `primary' template. */
11399 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11401 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11402 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11405 /* Inside pushdecl_namespace_level, we will push into the
11406 current namespace. However, the friend function should go
11407 into the namespace of the template. */
11408 ns = decl_namespace_context (new_friend);
11409 push_nested_namespace (ns);
11410 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11411 pop_nested_namespace (ns);
11413 if (old_decl == error_mark_node)
11414 return error_mark_node;
11416 if (old_decl != new_friend)
11418 /* This new friend declaration matched an existing
11419 declaration. For example, given:
11421 template <class T> void f(T);
11422 template <class U> class C {
11423 template <class T> friend void f(T) {}
11426 the friend declaration actually provides the definition
11427 of `f', once C has been instantiated for some type. So,
11428 old_decl will be the out-of-class template declaration,
11429 while new_friend is the in-class definition.
11431 But, if `f' was called before this point, the
11432 instantiation of `f' will have DECL_TI_ARGS corresponding
11433 to `T' but not to `U', references to which might appear
11434 in the definition of `f'. Previously, the most general
11435 template for an instantiation of `f' was the out-of-class
11436 version; now it is the in-class version. Therefore, we
11437 run through all specialization of `f', adding to their
11438 DECL_TI_ARGS appropriately. In particular, they need a
11439 new set of outer arguments, corresponding to the
11440 arguments for this class instantiation.
11442 The same situation can arise with something like this:
11444 friend void f(int);
11445 template <class T> class C {
11446 friend void f(T) {}
11449 when `C<int>' is instantiated. Now, `f(int)' is defined
11450 in the class. */
11452 if (!new_friend_is_defn)
11453 /* On the other hand, if the in-class declaration does
11454 *not* provide a definition, then we don't want to alter
11455 existing definitions. We can just leave everything
11456 alone. */
11458 else
11460 tree new_template = TI_TEMPLATE (new_friend_template_info);
11461 tree new_args = TI_ARGS (new_friend_template_info);
11463 /* Overwrite whatever template info was there before, if
11464 any, with the new template information pertaining to
11465 the declaration. */
11466 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11468 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11470 /* We should have called reregister_specialization in
11471 duplicate_decls. */
11472 gcc_assert (retrieve_specialization (new_template,
11473 new_args, 0)
11474 == old_decl);
11476 /* Instantiate it if the global has already been used. */
11477 if (DECL_ODR_USED (old_decl))
11478 instantiate_decl (old_decl, /*defer_ok=*/true,
11479 /*expl_inst_class_mem_p=*/false);
11481 else
11483 tree t;
11485 /* Indicate that the old function template is a partial
11486 instantiation. */
11487 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11488 = new_friend_result_template_info;
11490 gcc_assert (new_template
11491 == most_general_template (new_template));
11492 gcc_assert (new_template != old_decl);
11494 /* Reassign any specializations already in the hash table
11495 to the new more general template, and add the
11496 additional template args. */
11497 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11498 t != NULL_TREE;
11499 t = TREE_CHAIN (t))
11501 tree spec = TREE_VALUE (t);
11502 spec_entry elt;
11504 elt.tmpl = old_decl;
11505 elt.args = DECL_TI_ARGS (spec);
11506 elt.spec = NULL_TREE;
11508 decl_specializations->remove_elt (&elt);
11510 DECL_TI_ARGS (spec)
11511 = add_outermost_template_args (new_args,
11512 DECL_TI_ARGS (spec));
11514 register_specialization
11515 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11518 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11522 /* The information from NEW_FRIEND has been merged into OLD_DECL
11523 by duplicate_decls. */
11524 new_friend = old_decl;
11527 else
11529 tree context = DECL_CONTEXT (new_friend);
11530 bool dependent_p;
11532 /* In the code
11533 template <class T> class C {
11534 template <class U> friend void C1<U>::f (); // case 1
11535 friend void C2<T>::f (); // case 2
11537 we only need to make sure CONTEXT is a complete type for
11538 case 2. To distinguish between the two cases, we note that
11539 CONTEXT of case 1 remains dependent type after tsubst while
11540 this isn't true for case 2. */
11541 ++processing_template_decl;
11542 dependent_p = dependent_type_p (context);
11543 --processing_template_decl;
11545 if (!dependent_p
11546 && !complete_type_or_else (context, NULL_TREE))
11547 return error_mark_node;
11549 if (COMPLETE_TYPE_P (context))
11551 tree fn = new_friend;
11552 /* do_friend adds the TEMPLATE_DECL for any member friend
11553 template even if it isn't a member template, i.e.
11554 template <class T> friend A<T>::f();
11555 Look through it in that case. */
11556 if (TREE_CODE (fn) == TEMPLATE_DECL
11557 && !PRIMARY_TEMPLATE_P (fn))
11558 fn = DECL_TEMPLATE_RESULT (fn);
11559 /* Check to see that the declaration is really present, and,
11560 possibly obtain an improved declaration. */
11561 fn = check_classfn (context, fn, NULL_TREE);
11563 if (fn)
11564 new_friend = fn;
11568 return new_friend;
11571 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11572 template arguments, as for tsubst.
11574 Returns an appropriate tsubst'd friend type or error_mark_node on
11575 failure. */
11577 static tree
11578 tsubst_friend_class (tree friend_tmpl, tree args)
11580 tree tmpl;
11582 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11584 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11585 return TREE_TYPE (tmpl);
11588 tree context = CP_DECL_CONTEXT (friend_tmpl);
11589 if (TREE_CODE (context) == NAMESPACE_DECL)
11590 push_nested_namespace (context);
11591 else
11593 context = tsubst (context, args, tf_error, NULL_TREE);
11594 push_nested_class (context);
11597 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11598 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11600 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11602 /* The friend template has already been declared. Just
11603 check to see that the declarations match, and install any new
11604 default parameters. We must tsubst the default parameters,
11605 of course. We only need the innermost template parameters
11606 because that is all that redeclare_class_template will look
11607 at. */
11608 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11609 > TMPL_ARGS_DEPTH (args))
11611 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11612 args, tf_warning_or_error);
11613 tsubst_each_template_parm_constraints (parms, args,
11614 tf_warning_or_error);
11615 location_t saved_input_location = input_location;
11616 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11617 tree cons = get_constraints (tmpl);
11618 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11619 input_location = saved_input_location;
11622 else
11624 /* The friend template has not already been declared. In this
11625 case, the instantiation of the template class will cause the
11626 injection of this template into the namespace scope. */
11627 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11629 if (tmpl != error_mark_node)
11631 /* The new TMPL is not an instantiation of anything, so we
11632 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11633 for the new type because that is supposed to be the
11634 corresponding template decl, i.e., TMPL. */
11635 DECL_USE_TEMPLATE (tmpl) = 0;
11636 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11637 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11638 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11639 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11641 /* Substitute into and set the constraints on the new declaration. */
11642 if (tree ci = get_constraints (friend_tmpl))
11644 ++processing_template_decl;
11645 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11646 DECL_FRIEND_CONTEXT (friend_tmpl));
11647 --processing_template_decl;
11648 set_constraints (tmpl, ci);
11649 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11650 args, tf_warning_or_error);
11653 /* Inject this template into the enclosing namspace scope. */
11654 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11658 if (TREE_CODE (context) == NAMESPACE_DECL)
11659 pop_nested_namespace (context);
11660 else
11661 pop_nested_class ();
11663 return TREE_TYPE (tmpl);
11666 /* Returns zero if TYPE cannot be completed later due to circularity.
11667 Otherwise returns one. */
11669 static int
11670 can_complete_type_without_circularity (tree type)
11672 if (type == NULL_TREE || type == error_mark_node)
11673 return 0;
11674 else if (COMPLETE_TYPE_P (type))
11675 return 1;
11676 else if (TREE_CODE (type) == ARRAY_TYPE)
11677 return can_complete_type_without_circularity (TREE_TYPE (type));
11678 else if (CLASS_TYPE_P (type)
11679 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11680 return 0;
11681 else
11682 return 1;
11685 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11686 tsubst_flags_t, tree);
11688 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11689 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11691 static tree
11692 tsubst_attribute (tree t, tree *decl_p, tree args,
11693 tsubst_flags_t complain, tree in_decl)
11695 gcc_assert (ATTR_IS_DEPENDENT (t));
11697 tree val = TREE_VALUE (t);
11698 if (val == NULL_TREE)
11699 /* Nothing to do. */;
11700 else if ((flag_openmp || flag_openmp_simd)
11701 && is_attribute_p ("omp declare simd",
11702 get_attribute_name (t)))
11704 tree clauses = TREE_VALUE (val);
11705 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11706 complain, in_decl);
11707 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11708 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11709 tree parms = DECL_ARGUMENTS (*decl_p);
11710 clauses
11711 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11712 if (clauses)
11713 val = build_tree_list (NULL_TREE, clauses);
11714 else
11715 val = NULL_TREE;
11717 else if (flag_openmp
11718 && is_attribute_p ("omp declare variant base",
11719 get_attribute_name (t)))
11721 ++cp_unevaluated_operand;
11722 tree varid
11723 = tsubst_expr (TREE_PURPOSE (val), args, complain,
11724 in_decl, /*integral_constant_expression_p=*/false);
11725 --cp_unevaluated_operand;
11726 tree chain = TREE_CHAIN (val);
11727 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11728 tree ctx = copy_list (TREE_VALUE (val));
11729 tree simd = get_identifier ("simd");
11730 tree score = get_identifier (" score");
11731 tree condition = get_identifier ("condition");
11732 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11734 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11735 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11736 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11738 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11740 tree clauses = TREE_VALUE (t2);
11741 clauses = tsubst_omp_clauses (clauses,
11742 C_ORT_OMP_DECLARE_SIMD, args,
11743 complain, in_decl);
11744 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11745 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11746 TREE_VALUE (t2) = clauses;
11748 else
11750 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11751 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11752 if (TREE_VALUE (t3))
11754 bool allow_string
11755 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11756 && TREE_PURPOSE (t3) != score);
11757 tree v = TREE_VALUE (t3);
11758 if (TREE_CODE (v) == STRING_CST && allow_string)
11759 continue;
11760 v = tsubst_expr (v, args, complain, in_decl, true);
11761 v = fold_non_dependent_expr (v);
11762 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11763 || (TREE_PURPOSE (t3) == score
11764 ? TREE_CODE (v) != INTEGER_CST
11765 : !tree_fits_shwi_p (v)))
11767 location_t loc
11768 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11769 match_loc);
11770 if (TREE_PURPOSE (t3) == score)
11771 error_at (loc, "score argument must be "
11772 "constant integer expression");
11773 else if (allow_string)
11774 error_at (loc, "property must be constant "
11775 "integer expression or string "
11776 "literal");
11777 else
11778 error_at (loc, "property must be constant "
11779 "integer expression");
11780 return NULL_TREE;
11782 else if (TREE_PURPOSE (t3) == score
11783 && tree_int_cst_sgn (v) < 0)
11785 location_t loc
11786 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11787 match_loc);
11788 error_at (loc, "score argument must be "
11789 "non-negative");
11790 return NULL_TREE;
11792 TREE_VALUE (t3) = v;
11797 val = tree_cons (varid, ctx, chain);
11799 /* If the first attribute argument is an identifier, don't
11800 pass it through tsubst. Attributes like mode, format,
11801 cleanup and several target specific attributes expect it
11802 unmodified. */
11803 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11805 tree chain
11806 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11807 /*integral_constant_expression_p=*/false);
11808 if (chain != TREE_CHAIN (val))
11809 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11811 else if (PACK_EXPANSION_P (val))
11813 /* An attribute pack expansion. */
11814 tree purp = TREE_PURPOSE (t);
11815 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11816 if (pack == error_mark_node)
11817 return error_mark_node;
11818 int len = TREE_VEC_LENGTH (pack);
11819 tree list = NULL_TREE;
11820 tree *q = &list;
11821 for (int i = 0; i < len; ++i)
11823 tree elt = TREE_VEC_ELT (pack, i);
11824 *q = build_tree_list (purp, elt);
11825 q = &TREE_CHAIN (*q);
11827 return list;
11829 else
11830 val = tsubst_expr (val, args, complain, in_decl,
11831 /*integral_constant_expression_p=*/false);
11833 if (val == error_mark_node)
11834 return error_mark_node;
11835 if (val != TREE_VALUE (t))
11836 return build_tree_list (TREE_PURPOSE (t), val);
11837 return t;
11840 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11841 unchanged or a new TREE_LIST chain. */
11843 static tree
11844 tsubst_attributes (tree attributes, tree args,
11845 tsubst_flags_t complain, tree in_decl)
11847 tree last_dep = NULL_TREE;
11849 for (tree t = attributes; t; t = TREE_CHAIN (t))
11850 if (ATTR_IS_DEPENDENT (t))
11852 last_dep = t;
11853 attributes = copy_list (attributes);
11854 break;
11857 if (last_dep)
11858 for (tree *p = &attributes; *p; )
11860 tree t = *p;
11861 if (ATTR_IS_DEPENDENT (t))
11863 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11864 if (subst != t)
11866 *p = subst;
11867 while (*p)
11868 p = &TREE_CHAIN (*p);
11869 *p = TREE_CHAIN (t);
11870 continue;
11873 p = &TREE_CHAIN (*p);
11876 return attributes;
11879 /* Apply any attributes which had to be deferred until instantiation
11880 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11881 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11882 false on error. */
11884 static bool
11885 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11886 tree args, tsubst_flags_t complain, tree in_decl)
11888 tree t;
11889 tree *p;
11891 if (attributes == NULL_TREE)
11892 return true;
11894 if (DECL_P (*decl_p))
11896 if (TREE_TYPE (*decl_p) == error_mark_node)
11897 return false;
11898 p = &DECL_ATTRIBUTES (*decl_p);
11899 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11900 to our attributes parameter. */
11901 gcc_assert (*p == attributes);
11903 else
11905 p = &TYPE_ATTRIBUTES (*decl_p);
11906 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11907 lookup_template_class_1, and should be preserved. */
11908 gcc_assert (*p != attributes);
11909 while (*p)
11910 p = &TREE_CHAIN (*p);
11913 /* save_template_attributes puts the dependent attributes at the beginning of
11914 the list; find the non-dependent ones. */
11915 for (t = attributes; t; t = TREE_CHAIN (t))
11916 if (!ATTR_IS_DEPENDENT (t))
11917 break;
11918 tree nondep = t;
11920 /* Apply any non-dependent attributes. */
11921 *p = nondep;
11923 if (nondep == attributes)
11924 return true;
11926 /* And then any dependent ones. */
11927 tree late_attrs = NULL_TREE;
11928 tree *q = &late_attrs;
11929 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
11931 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11932 if (*q == error_mark_node)
11933 return false;
11934 if (*q == t)
11936 *q = copy_node (t);
11937 TREE_CHAIN (*q) = NULL_TREE;
11939 while (*q)
11940 q = &TREE_CHAIN (*q);
11943 /* cplus_decl_attributes can add some attributes implicitly. For templates,
11944 those attributes should have been added already when those templates were
11945 parsed, and shouldn't be added based on from which context they are
11946 first time instantiated. */
11947 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
11948 auto o2 = make_temp_override (optimization_current_node,
11949 optimization_default_node);
11950 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
11951 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
11952 NULL);
11954 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11956 return true;
11959 /* The template TMPL is being instantiated with the template arguments TARGS.
11960 Perform the access checks that we deferred when parsing the template. */
11962 static void
11963 perform_instantiation_time_access_checks (tree tmpl, tree targs)
11965 unsigned i;
11966 deferred_access_check *chk;
11968 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11969 return;
11971 if (vec<deferred_access_check, va_gc> *access_checks
11972 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11973 FOR_EACH_VEC_ELT (*access_checks, i, chk)
11975 tree decl = chk->decl;
11976 tree diag_decl = chk->diag_decl;
11977 tree type_scope = TREE_TYPE (chk->binfo);
11979 if (uses_template_parms (type_scope))
11980 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11982 /* Make access check error messages point to the location
11983 of the use of the typedef. */
11984 iloc_sentinel ils (chk->loc);
11985 perform_or_defer_access_check (TYPE_BINFO (type_scope),
11986 decl, diag_decl, tf_warning_or_error);
11990 tree
11991 instantiate_class_template (tree type)
11993 auto_timevar tv (TV_TEMPLATE_INST);
11995 tree templ, args, pattern, t, member;
11996 tree typedecl;
11997 tree pbinfo;
11998 tree base_list;
11999 unsigned int saved_maximum_field_alignment;
12000 tree fn_context;
12002 if (type == error_mark_node)
12003 return error_mark_node;
12005 if (COMPLETE_OR_OPEN_TYPE_P (type)
12006 || uses_template_parms (type))
12007 return type;
12009 /* Figure out which template is being instantiated. */
12010 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12011 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12013 /* Mark the type as in the process of being defined. */
12014 TYPE_BEING_DEFINED (type) = 1;
12016 /* We may be in the middle of deferred access check. Disable
12017 it now. */
12018 deferring_access_check_sentinel acs (dk_no_deferred);
12020 /* Determine what specialization of the original template to
12021 instantiate. */
12022 t = most_specialized_partial_spec (type, tf_warning_or_error);
12023 if (t == error_mark_node)
12024 return error_mark_node;
12025 else if (t)
12027 /* This TYPE is actually an instantiation of a partial
12028 specialization. We replace the innermost set of ARGS with
12029 the arguments appropriate for substitution. For example,
12030 given:
12032 template <class T> struct S {};
12033 template <class T> struct S<T*> {};
12035 and supposing that we are instantiating S<int*>, ARGS will
12036 presently be {int*} -- but we need {int}. */
12037 pattern = TREE_TYPE (t);
12038 args = TREE_PURPOSE (t);
12040 else
12042 pattern = TREE_TYPE (templ);
12043 args = CLASSTYPE_TI_ARGS (type);
12046 /* If the template we're instantiating is incomplete, then clearly
12047 there's nothing we can do. */
12048 if (!COMPLETE_TYPE_P (pattern))
12050 /* We can try again later. */
12051 TYPE_BEING_DEFINED (type) = 0;
12052 return type;
12055 /* If we've recursively instantiated too many templates, stop. */
12056 if (! push_tinst_level (type))
12057 return type;
12059 int saved_unevaluated_operand = cp_unevaluated_operand;
12060 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12062 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12063 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12064 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12065 fn_context = error_mark_node;
12066 if (!fn_context)
12067 push_to_top_level ();
12068 else
12070 cp_unevaluated_operand = 0;
12071 c_inhibit_evaluation_warnings = 0;
12073 /* Use #pragma pack from the template context. */
12074 saved_maximum_field_alignment = maximum_field_alignment;
12075 maximum_field_alignment = TYPE_PRECISION (pattern);
12077 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12079 /* Set the input location to the most specialized template definition.
12080 This is needed if tsubsting causes an error. */
12081 typedecl = TYPE_MAIN_DECL (pattern);
12082 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12083 DECL_SOURCE_LOCATION (typedecl);
12085 set_instantiating_module (TYPE_NAME (type));
12087 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12088 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12089 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12090 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12091 if (ANON_AGGR_TYPE_P (pattern))
12092 SET_ANON_AGGR_TYPE_P (type);
12093 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12095 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12096 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12097 /* Adjust visibility for template arguments. */
12098 determine_visibility (TYPE_MAIN_DECL (type));
12100 if (CLASS_TYPE_P (type))
12101 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12103 pbinfo = TYPE_BINFO (pattern);
12105 /* We should never instantiate a nested class before its enclosing
12106 class; we need to look up the nested class by name before we can
12107 instantiate it, and that lookup should instantiate the enclosing
12108 class. */
12109 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12110 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12112 base_list = NULL_TREE;
12113 /* Defer access checking while we substitute into the types named in
12114 the base-clause. */
12115 push_deferring_access_checks (dk_deferred);
12116 if (BINFO_N_BASE_BINFOS (pbinfo))
12118 tree pbase_binfo;
12119 int i;
12121 /* Substitute into each of the bases to determine the actual
12122 basetypes. */
12123 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12125 tree base;
12126 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12127 tree expanded_bases = NULL_TREE;
12128 int idx, len = 1;
12130 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12132 expanded_bases =
12133 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12134 args, tf_error, NULL_TREE);
12135 if (expanded_bases == error_mark_node)
12136 continue;
12138 len = TREE_VEC_LENGTH (expanded_bases);
12141 for (idx = 0; idx < len; idx++)
12143 if (expanded_bases)
12144 /* Extract the already-expanded base class. */
12145 base = TREE_VEC_ELT (expanded_bases, idx);
12146 else
12147 /* Substitute to figure out the base class. */
12148 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12149 NULL_TREE);
12151 if (base == error_mark_node)
12152 continue;
12154 base_list = tree_cons (access, base, base_list);
12155 if (BINFO_VIRTUAL_P (pbase_binfo))
12156 TREE_TYPE (base_list) = integer_type_node;
12160 /* The list is now in reverse order; correct that. */
12161 base_list = nreverse (base_list);
12163 /* Now call xref_basetypes to set up all the base-class
12164 information. */
12165 xref_basetypes (type, base_list);
12167 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12168 (int) ATTR_FLAG_TYPE_IN_PLACE,
12169 args, tf_error, NULL_TREE);
12170 fixup_attribute_variants (type);
12172 /* Now that our base classes are set up, enter the scope of the
12173 class, so that name lookups into base classes, etc. will work
12174 correctly. This is precisely analogous to what we do in
12175 begin_class_definition when defining an ordinary non-template
12176 class, except we also need to push the enclosing classes. */
12177 push_nested_class (type);
12179 /* Now check accessibility of the types named in its base-clause,
12180 relative to the scope of the class. */
12181 pop_to_parent_deferring_access_checks ();
12183 /* A vector to hold members marked with attribute used. */
12184 auto_vec<tree> used;
12186 /* Now members are processed in the order of declaration. */
12187 for (member = CLASSTYPE_DECL_LIST (pattern);
12188 member; member = TREE_CHAIN (member))
12190 tree t = TREE_VALUE (member);
12192 if (TREE_PURPOSE (member))
12194 if (TYPE_P (t))
12196 if (LAMBDA_TYPE_P (t))
12197 /* A closure type for a lambda in an NSDMI or default argument.
12198 Ignore it; it will be regenerated when needed. */
12199 continue;
12201 bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
12202 && TYPE_LANG_SPECIFIC (t)
12203 && CLASSTYPE_IS_TEMPLATE (t));
12205 /* If the member is a class template, then -- even after
12206 substitution -- there may be dependent types in the
12207 template argument list for the class. We increment
12208 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
12209 that function will assume that no types are dependent
12210 when outside of a template. */
12211 if (class_template_p)
12212 ++processing_template_decl;
12213 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12214 if (class_template_p)
12215 --processing_template_decl;
12216 if (newtag == error_mark_node)
12217 continue;
12219 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12221 tree name = TYPE_IDENTIFIER (t);
12223 if (class_template_p)
12224 /* Unfortunately, lookup_template_class sets
12225 CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
12226 instantiation (i.e., for the type of a member
12227 template class nested within a template class.)
12228 This behavior is required for
12229 maybe_process_partial_specialization to work
12230 correctly, but is not accurate in this case;
12231 the TAG is not an instantiation of anything.
12232 (The corresponding TEMPLATE_DECL is an
12233 instantiation, but the TYPE is not.) */
12234 CLASSTYPE_USE_TEMPLATE (newtag) = 0;
12236 /* Now, install the tag. We don't use pushtag
12237 because that does too much work -- creating an
12238 implicit typedef, which we've already done. */
12239 set_identifier_type_value (name, TYPE_NAME (newtag));
12240 maybe_add_class_template_decl_list (type, newtag, false);
12241 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12242 determine_visibility (TYPE_NAME (newtag));
12245 else if (DECL_DECLARES_FUNCTION_P (t))
12247 tree r;
12249 if (TREE_CODE (t) == TEMPLATE_DECL)
12250 ++processing_template_decl;
12251 r = tsubst (t, args, tf_error, NULL_TREE);
12252 if (TREE_CODE (t) == TEMPLATE_DECL)
12253 --processing_template_decl;
12254 set_current_access_from_decl (r);
12255 finish_member_declaration (r);
12256 /* Instantiate members marked with attribute used. */
12257 if (r != error_mark_node && DECL_PRESERVE_P (r))
12258 used.safe_push (r);
12259 if (TREE_CODE (r) == FUNCTION_DECL
12260 && DECL_OMP_DECLARE_REDUCTION_P (r))
12261 cp_check_omp_declare_reduction (r);
12263 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12264 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12265 /* A closure type for a lambda in an NSDMI or default argument.
12266 Ignore it; it will be regenerated when needed. */;
12267 else
12269 /* Build new TYPE_FIELDS. */
12270 if (TREE_CODE (t) == STATIC_ASSERT)
12271 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE,
12272 /*integral_constant_expression_p=*/true);
12273 else if (TREE_CODE (t) != CONST_DECL)
12275 tree r;
12276 tree vec = NULL_TREE;
12277 int len = 1;
12279 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12280 /* The file and line for this declaration, to
12281 assist in error message reporting. Since we
12282 called push_tinst_level above, we don't need to
12283 restore these. */
12284 input_location = DECL_SOURCE_LOCATION (t);
12286 if (TREE_CODE (t) == TEMPLATE_DECL)
12287 ++processing_template_decl;
12288 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12289 if (TREE_CODE (t) == TEMPLATE_DECL)
12290 --processing_template_decl;
12292 if (TREE_CODE (r) == TREE_VEC)
12294 /* A capture pack became multiple fields. */
12295 vec = r;
12296 len = TREE_VEC_LENGTH (vec);
12299 for (int i = 0; i < len; ++i)
12301 if (vec)
12302 r = TREE_VEC_ELT (vec, i);
12303 if (VAR_P (r))
12305 /* In [temp.inst]:
12307 [t]he initialization (and any associated
12308 side-effects) of a static data member does
12309 not occur unless the static data member is
12310 itself used in a way that requires the
12311 definition of the static data member to
12312 exist.
12314 Therefore, we do not substitute into the
12315 initialized for the static data member here. */
12316 finish_static_data_member_decl
12318 /*init=*/NULL_TREE,
12319 /*init_const_expr_p=*/false,
12320 /*asmspec_tree=*/NULL_TREE,
12321 /*flags=*/0);
12322 /* Instantiate members marked with attribute used. */
12323 if (r != error_mark_node && DECL_PRESERVE_P (r))
12324 used.safe_push (r);
12326 else if (TREE_CODE (r) == FIELD_DECL)
12328 /* Determine whether R has a valid type and can be
12329 completed later. If R is invalid, then its type
12330 is replaced by error_mark_node. */
12331 tree rtype = TREE_TYPE (r);
12332 if (can_complete_type_without_circularity (rtype))
12333 complete_type (rtype);
12335 if (!complete_or_array_type_p (rtype))
12337 /* If R's type couldn't be completed and
12338 it isn't a flexible array member (whose
12339 type is incomplete by definition) give
12340 an error. */
12341 cxx_incomplete_type_error (r, rtype);
12342 TREE_TYPE (r) = error_mark_node;
12344 else if (TREE_CODE (rtype) == ARRAY_TYPE
12345 && TYPE_DOMAIN (rtype) == NULL_TREE
12346 && (TREE_CODE (type) == UNION_TYPE
12347 || TREE_CODE (type) == QUAL_UNION_TYPE))
12349 error ("flexible array member %qD in union", r);
12350 TREE_TYPE (r) = error_mark_node;
12352 else if (!verify_type_context (input_location,
12353 TCTX_FIELD, rtype))
12354 TREE_TYPE (r) = error_mark_node;
12357 /* If it is a TYPE_DECL for a class-scoped
12358 ENUMERAL_TYPE, such a thing will already have
12359 been added to the field list by tsubst_enum
12360 in finish_member_declaration case above. */
12361 if (!(TREE_CODE (r) == TYPE_DECL
12362 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12363 && DECL_ARTIFICIAL (r)))
12365 set_current_access_from_decl (r);
12366 finish_member_declaration (r);
12372 else
12374 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12375 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12377 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12379 tree friend_type = t;
12380 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12382 /* template <class T> friend class C; */
12383 friend_type = tsubst_friend_class (friend_type, args);
12385 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12387 /* template <class T> friend class C::D; */
12388 friend_type = tsubst (friend_type, args,
12389 tf_warning_or_error, NULL_TREE);
12390 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12391 friend_type = TREE_TYPE (friend_type);
12393 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12394 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12396 /* This could be either
12398 friend class T::C;
12400 when dependent_type_p is false or
12402 template <class U> friend class T::C;
12404 otherwise. */
12405 /* Bump processing_template_decl in case this is something like
12406 template <class T> friend struct A<T>::B. */
12407 ++processing_template_decl;
12408 friend_type = tsubst (friend_type, args,
12409 tf_warning_or_error, NULL_TREE);
12410 --processing_template_decl;
12412 else if (uses_template_parms (friend_type))
12413 /* friend class C<T>; */
12414 friend_type = tsubst (friend_type, args,
12415 tf_warning_or_error, NULL_TREE);
12417 /* Otherwise it's
12419 friend class C;
12421 where C is already declared or
12423 friend class C<int>;
12425 We don't have to do anything in these cases. */
12427 if (friend_type != error_mark_node)
12428 make_friend_class (type, friend_type, /*complain=*/false);
12430 else
12432 /* Build new DECL_FRIENDLIST. */
12433 tree r;
12435 /* The file and line for this declaration, to
12436 assist in error message reporting. Since we
12437 called push_tinst_level above, we don't need to
12438 restore these. */
12439 input_location = DECL_SOURCE_LOCATION (t);
12441 if (TREE_CODE (t) == TEMPLATE_DECL)
12443 ++processing_template_decl;
12444 push_deferring_access_checks (dk_no_check);
12447 r = tsubst_friend_function (t, args);
12448 add_friend (type, r, /*complain=*/false);
12449 if (TREE_CODE (t) == TEMPLATE_DECL)
12451 pop_deferring_access_checks ();
12452 --processing_template_decl;
12458 if (fn_context)
12460 /* Restore these before substituting into the lambda capture
12461 initializers. */
12462 cp_unevaluated_operand = saved_unevaluated_operand;
12463 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12466 /* Set the file and line number information to whatever is given for
12467 the class itself. This puts error messages involving generated
12468 implicit functions at a predictable point, and the same point
12469 that would be used for non-template classes. */
12470 input_location = DECL_SOURCE_LOCATION (typedecl);
12472 unreverse_member_declarations (type);
12473 finish_struct_1 (type);
12474 TYPE_BEING_DEFINED (type) = 0;
12476 /* Remember if instantiating this class ran into errors, so we can avoid
12477 instantiating member functions in limit_bad_template_recursion. We set
12478 this flag even if the problem was in another instantiation triggered by
12479 this one, as that will likely also cause trouble for member functions. */
12480 if (errorcount + sorrycount > current_tinst_level->errors)
12481 CLASSTYPE_ERRONEOUS (type) = true;
12483 /* We don't instantiate default arguments for member functions. 14.7.1:
12485 The implicit instantiation of a class template specialization causes
12486 the implicit instantiation of the declarations, but not of the
12487 definitions or default arguments, of the class member functions,
12488 member classes, static data members and member templates.... */
12490 perform_instantiation_time_access_checks (pattern, args);
12491 perform_deferred_access_checks (tf_warning_or_error);
12493 /* Now that we've gone through all the members, instantiate those
12494 marked with attribute used. We must do this in the context of
12495 the class -- not the context we pushed from, as that might be
12496 inside a template and change the behaviour of mark_used. */
12497 for (tree x : used)
12498 mark_used (x);
12500 pop_nested_class ();
12501 maximum_field_alignment = saved_maximum_field_alignment;
12502 if (!fn_context)
12503 pop_from_top_level ();
12504 pop_tinst_level ();
12506 /* The vtable for a template class can be emitted in any translation
12507 unit in which the class is instantiated. When there is no key
12508 method, however, finish_struct_1 will already have added TYPE to
12509 the keyed_classes. */
12510 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12511 vec_safe_push (keyed_classes, type);
12513 return type;
12516 tree
12517 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12519 tree r;
12521 if (!t)
12522 r = t;
12523 else if (TYPE_P (t))
12524 r = tsubst (t, args, complain, in_decl);
12525 else
12527 if (!(complain & tf_warning))
12528 ++c_inhibit_evaluation_warnings;
12529 r = tsubst_expr (t, args, complain, in_decl,
12530 /*integral_constant_expression_p=*/true);
12531 if (!(complain & tf_warning))
12532 --c_inhibit_evaluation_warnings;
12535 return r;
12538 /* Given a function parameter pack TMPL_PARM and some function parameters
12539 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12540 and set *SPEC_P to point at the next point in the list. */
12542 tree
12543 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12545 /* Collect all of the extra "packed" parameters into an
12546 argument pack. */
12547 tree argpack;
12548 tree spec_parm = *spec_p;
12549 int len;
12551 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12552 if (tmpl_parm
12553 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12554 break;
12556 spec_parm = *spec_p;
12557 if (len == 1 && DECL_PACK_P (spec_parm))
12559 /* The instantiation is still a parameter pack; don't wrap it in a
12560 NONTYPE_ARGUMENT_PACK. */
12561 argpack = spec_parm;
12562 spec_parm = DECL_CHAIN (spec_parm);
12564 else
12566 /* Fill in PARMVEC with all of the parameters. */
12567 tree parmvec = make_tree_vec (len);
12568 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12569 for (int i = 0; i < len; i++)
12571 tree elt = spec_parm;
12572 if (DECL_PACK_P (elt))
12573 elt = make_pack_expansion (elt);
12574 TREE_VEC_ELT (parmvec, i) = elt;
12575 spec_parm = DECL_CHAIN (spec_parm);
12578 /* Build the argument packs. */
12579 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12581 *spec_p = spec_parm;
12583 return argpack;
12586 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12587 NONTYPE_ARGUMENT_PACK. */
12589 static tree
12590 make_fnparm_pack (tree spec_parm)
12592 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12595 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12596 pack expansion with no extra args, 2 if it has extra args, or 0
12597 if it is not a pack expansion. */
12599 static int
12600 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12602 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12603 /* We're being called before this happens in tsubst_pack_expansion. */
12604 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12605 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12606 if (i >= TREE_VEC_LENGTH (vec))
12607 return 0;
12608 tree elt = TREE_VEC_ELT (vec, i);
12609 if (DECL_P (elt))
12610 /* A decl pack is itself an expansion. */
12611 elt = TREE_TYPE (elt);
12612 if (!PACK_EXPANSION_P (elt))
12613 return 0;
12614 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12615 return 2;
12616 return 1;
12620 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12622 static tree
12623 make_argument_pack_select (tree arg_pack, unsigned index)
12625 tree aps = make_node (ARGUMENT_PACK_SELECT);
12627 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12628 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12630 return aps;
12633 /* This is a subroutine of tsubst_pack_expansion.
12635 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12636 mechanism to store the (non complete list of) arguments of the
12637 substitution and return a non substituted pack expansion, in order
12638 to wait for when we have enough arguments to really perform the
12639 substitution. */
12641 static bool
12642 use_pack_expansion_extra_args_p (tree t,
12643 tree parm_packs,
12644 int arg_pack_len,
12645 bool has_empty_arg)
12647 if (has_empty_arg
12648 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12649 return true;
12651 /* If one pack has an expansion and another pack has a normal
12652 argument or if one pack has an empty argument and an another
12653 one hasn't then tsubst_pack_expansion cannot perform the
12654 substitution and need to fall back on the
12655 PACK_EXPANSION_EXTRA mechanism. */
12656 if (parm_packs == NULL_TREE)
12657 return false;
12658 else if (has_empty_arg)
12660 /* If all the actual packs are pack expansions, we can still
12661 subsitute directly. */
12662 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12664 tree a = TREE_VALUE (p);
12665 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12666 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12667 a = ARGUMENT_PACK_ARGS (a);
12668 if (TREE_VEC_LENGTH (a) == 1)
12669 a = TREE_VEC_ELT (a, 0);
12670 if (PACK_EXPANSION_P (a))
12671 continue;
12672 return true;
12674 return false;
12677 for (int i = 0 ; i < arg_pack_len; ++i)
12679 bool has_expansion_arg = false;
12680 bool has_non_expansion_arg = false;
12681 for (tree parm_pack = parm_packs;
12682 parm_pack;
12683 parm_pack = TREE_CHAIN (parm_pack))
12685 tree arg = TREE_VALUE (parm_pack);
12687 int exp = argument_pack_element_is_expansion_p (arg, i);
12688 if (exp == 2)
12689 /* We can't substitute a pack expansion with extra args into
12690 our pattern. */
12691 return true;
12692 else if (exp)
12693 has_expansion_arg = true;
12694 else
12695 has_non_expansion_arg = true;
12698 if (has_expansion_arg && has_non_expansion_arg)
12700 gcc_checking_assert (false);
12701 return true;
12704 return false;
12707 /* [temp.variadic]/6 says that:
12709 The instantiation of a pack expansion [...]
12710 produces a list E1,E2, ..., En, where N is the number of elements
12711 in the pack expansion parameters.
12713 This subroutine of tsubst_pack_expansion produces one of these Ei.
12715 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12716 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12717 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12718 INDEX is the index 'i' of the element Ei to produce. ARGS,
12719 COMPLAIN, and IN_DECL are the same parameters as for the
12720 tsubst_pack_expansion function.
12722 The function returns the resulting Ei upon successful completion,
12723 or error_mark_node.
12725 Note that this function possibly modifies the ARGS parameter, so
12726 it's the responsibility of the caller to restore it. */
12728 static tree
12729 gen_elem_of_pack_expansion_instantiation (tree pattern,
12730 tree parm_packs,
12731 unsigned index,
12732 tree args /* This parm gets
12733 modified. */,
12734 tsubst_flags_t complain,
12735 tree in_decl)
12737 tree t;
12738 bool ith_elem_is_expansion = false;
12740 /* For each parameter pack, change the substitution of the parameter
12741 pack to the ith argument in its argument pack, then expand the
12742 pattern. */
12743 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12745 tree parm = TREE_PURPOSE (pack);
12746 tree arg_pack = TREE_VALUE (pack);
12747 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12749 ith_elem_is_expansion |=
12750 argument_pack_element_is_expansion_p (arg_pack, index);
12752 /* Select the Ith argument from the pack. */
12753 if (TREE_CODE (parm) == PARM_DECL
12754 || VAR_P (parm)
12755 || TREE_CODE (parm) == FIELD_DECL)
12757 if (index == 0)
12759 aps = make_argument_pack_select (arg_pack, index);
12760 if (!mark_used (parm, complain) && !(complain & tf_error))
12761 return error_mark_node;
12762 register_local_specialization (aps, parm);
12764 else
12765 aps = retrieve_local_specialization (parm);
12767 else
12769 int idx, level;
12770 template_parm_level_and_index (parm, &level, &idx);
12772 if (index == 0)
12774 aps = make_argument_pack_select (arg_pack, index);
12775 /* Update the corresponding argument. */
12776 TMPL_ARG (args, level, idx) = aps;
12778 else
12779 /* Re-use the ARGUMENT_PACK_SELECT. */
12780 aps = TMPL_ARG (args, level, idx);
12782 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12785 /* Substitute into the PATTERN with the (possibly altered)
12786 arguments. */
12787 if (pattern == in_decl)
12788 /* Expanding a fixed parameter pack from
12789 coerce_template_parameter_pack. */
12790 t = tsubst_decl (pattern, args, complain);
12791 else if (pattern == error_mark_node)
12792 t = error_mark_node;
12793 else if (!TYPE_P (pattern))
12794 t = tsubst_expr (pattern, args, complain, in_decl,
12795 /*integral_constant_expression_p=*/false);
12796 else
12798 t = tsubst (pattern, args, complain, in_decl);
12799 if (is_auto (t) && !ith_elem_is_expansion)
12800 /* When expanding the fake auto... pack expansion from add_capture, we
12801 need to mark that the expansion is no longer a pack. */
12802 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12805 /* If the Ith argument pack element is a pack expansion, then
12806 the Ith element resulting from the substituting is going to
12807 be a pack expansion as well. */
12808 if (ith_elem_is_expansion)
12809 t = make_pack_expansion (t, complain);
12811 return t;
12814 /* When the unexpanded parameter pack in a fold expression expands to an empty
12815 sequence, the value of the expression is as follows; the program is
12816 ill-formed if the operator is not listed in this table.
12818 && true
12819 || false
12820 , void() */
12822 tree
12823 expand_empty_fold (tree t, tsubst_flags_t complain)
12825 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12826 if (!FOLD_EXPR_MODIFY_P (t))
12827 switch (code)
12829 case TRUTH_ANDIF_EXPR:
12830 return boolean_true_node;
12831 case TRUTH_ORIF_EXPR:
12832 return boolean_false_node;
12833 case COMPOUND_EXPR:
12834 return void_node;
12835 default:
12836 break;
12839 if (complain & tf_error)
12840 error_at (location_of (t),
12841 "fold of empty expansion over %O", code);
12842 return error_mark_node;
12845 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12846 form an expression that combines the two terms using the
12847 operator of T. */
12849 static tree
12850 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12852 tree_code code = FOLD_EXPR_OP (t);
12854 tree lookups = templated_operator_saved_lookups (t);
12856 // Handle compound assignment operators.
12857 if (FOLD_EXPR_MODIFY_P (t))
12858 return build_x_modify_expr (input_location, left, code, right,
12859 lookups, complain);
12861 warning_sentinel s(warn_parentheses);
12862 switch (code)
12864 case COMPOUND_EXPR:
12865 return build_x_compound_expr (input_location, left, right,
12866 lookups, complain);
12867 default:
12868 return build_x_binary_op (input_location, code,
12869 left, TREE_CODE (left),
12870 right, TREE_CODE (right),
12871 lookups, /*overload=*/NULL,
12872 complain);
12876 /* Substitute ARGS into the pack of a fold expression T. */
12878 static inline tree
12879 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12881 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12884 /* Substitute ARGS into the pack of a fold expression T. */
12886 static inline tree
12887 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12889 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12892 /* Expand a PACK of arguments into a grouped as left fold.
12893 Given a pack containing elements A0, A1, ..., An and an
12894 operator @, this builds the expression:
12896 ((A0 @ A1) @ A2) ... @ An
12898 Note that PACK must not be empty.
12900 The operator is defined by the original fold expression T. */
12902 static tree
12903 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12905 tree left = TREE_VEC_ELT (pack, 0);
12906 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12908 tree right = TREE_VEC_ELT (pack, i);
12909 left = fold_expression (t, left, right, complain);
12911 return left;
12914 /* Substitute into a unary left fold expression. */
12916 static tree
12917 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12918 tree in_decl)
12920 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12921 if (pack == error_mark_node)
12922 return error_mark_node;
12923 if (PACK_EXPANSION_P (pack))
12925 tree r = copy_node (t);
12926 FOLD_EXPR_PACK (r) = pack;
12927 return r;
12929 if (TREE_VEC_LENGTH (pack) == 0)
12930 return expand_empty_fold (t, complain);
12931 else
12932 return expand_left_fold (t, pack, complain);
12935 /* Substitute into a binary left fold expression.
12937 Do ths by building a single (non-empty) vector of argumnts and
12938 building the expression from those elements. */
12940 static tree
12941 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12942 tree in_decl)
12944 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12945 if (pack == error_mark_node)
12946 return error_mark_node;
12947 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12948 if (init == error_mark_node)
12949 return error_mark_node;
12951 if (PACK_EXPANSION_P (pack))
12953 tree r = copy_node (t);
12954 FOLD_EXPR_PACK (r) = pack;
12955 FOLD_EXPR_INIT (r) = init;
12956 return r;
12959 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12960 TREE_VEC_ELT (vec, 0) = init;
12961 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12962 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12964 return expand_left_fold (t, vec, complain);
12967 /* Expand a PACK of arguments into a grouped as right fold.
12968 Given a pack containing elementns A0, A1, ..., and an
12969 operator @, this builds the expression:
12971 A0@ ... (An-2 @ (An-1 @ An))
12973 Note that PACK must not be empty.
12975 The operator is defined by the original fold expression T. */
12977 tree
12978 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12980 // Build the expression.
12981 int n = TREE_VEC_LENGTH (pack);
12982 tree right = TREE_VEC_ELT (pack, n - 1);
12983 for (--n; n != 0; --n)
12985 tree left = TREE_VEC_ELT (pack, n - 1);
12986 right = fold_expression (t, left, right, complain);
12988 return right;
12991 /* Substitute into a unary right fold expression. */
12993 static tree
12994 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12995 tree in_decl)
12997 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12998 if (pack == error_mark_node)
12999 return error_mark_node;
13000 if (PACK_EXPANSION_P (pack))
13002 tree r = copy_node (t);
13003 FOLD_EXPR_PACK (r) = pack;
13004 return r;
13006 if (TREE_VEC_LENGTH (pack) == 0)
13007 return expand_empty_fold (t, complain);
13008 else
13009 return expand_right_fold (t, pack, complain);
13012 /* Substitute into a binary right fold expression.
13014 Do ths by building a single (non-empty) vector of arguments and
13015 building the expression from those elements. */
13017 static tree
13018 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13019 tree in_decl)
13021 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13022 if (pack == error_mark_node)
13023 return error_mark_node;
13024 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13025 if (init == error_mark_node)
13026 return error_mark_node;
13028 if (PACK_EXPANSION_P (pack))
13030 tree r = copy_node (t);
13031 FOLD_EXPR_PACK (r) = pack;
13032 FOLD_EXPR_INIT (r) = init;
13033 return r;
13036 int n = TREE_VEC_LENGTH (pack);
13037 tree vec = make_tree_vec (n + 1);
13038 for (int i = 0; i < n; ++i)
13039 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13040 TREE_VEC_ELT (vec, n) = init;
13042 return expand_right_fold (t, vec, complain);
13045 /* Walk through the pattern of a pack expansion, adding everything in
13046 local_specializations to a list. */
13048 class el_data
13050 public:
13051 /* Set of variables declared within the pattern. */
13052 hash_set<tree> internal;
13053 /* Set of AST nodes that have been visited by the traversal. */
13054 hash_set<tree> visited;
13055 /* List of local_specializations used within the pattern. */
13056 tree extra;
13057 tsubst_flags_t complain;
13059 el_data (tsubst_flags_t c)
13060 : extra (NULL_TREE), complain (c) {}
13062 static tree
13063 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
13065 el_data &data = *reinterpret_cast<el_data*>(data_);
13066 tree *extra = &data.extra;
13067 tsubst_flags_t complain = data.complain;
13069 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13070 /* Remember local typedefs (85214). */
13071 tp = &TYPE_NAME (*tp);
13073 if (TREE_CODE (*tp) == DECL_EXPR)
13075 tree decl = DECL_EXPR_DECL (*tp);
13076 data.internal.add (decl);
13077 if (VAR_P (decl)
13078 && DECL_DECOMPOSITION_P (decl)
13079 && TREE_TYPE (decl) != error_mark_node)
13081 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13082 for (tree decl2 = DECL_CHAIN (decl);
13083 decl2
13084 && VAR_P (decl2)
13085 && DECL_DECOMPOSITION_P (decl2)
13086 && DECL_NAME (decl2)
13087 && TREE_TYPE (decl2) != error_mark_node;
13088 decl2 = DECL_CHAIN (decl2))
13090 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13091 data.internal.add (decl2);
13095 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13097 /* Since we defer implicit capture, look in the parms and body. */
13098 tree fn = lambda_function (*tp);
13099 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13100 &data.visited);
13101 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13102 &data.visited);
13104 else if (tree spec = retrieve_local_specialization (*tp))
13106 if (data.internal.contains (*tp))
13107 /* Don't mess with variables declared within the pattern. */
13108 return NULL_TREE;
13109 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13111 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13112 tree args = ARGUMENT_PACK_ARGS (spec);
13113 if (TREE_VEC_LENGTH (args) == 1)
13115 tree elt = TREE_VEC_ELT (args, 0);
13116 if (PACK_EXPANSION_P (elt))
13117 elt = PACK_EXPANSION_PATTERN (elt);
13118 if (DECL_PACK_P (elt))
13119 spec = elt;
13121 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13123 /* Handle lambda capture here, since we aren't doing any
13124 substitution now, and so tsubst_copy won't call
13125 process_outer_var_ref. */
13126 tree args = ARGUMENT_PACK_ARGS (spec);
13127 int len = TREE_VEC_LENGTH (args);
13128 for (int i = 0; i < len; ++i)
13130 tree arg = TREE_VEC_ELT (args, i);
13131 tree carg = arg;
13132 if (outer_automatic_var_p (arg))
13133 carg = process_outer_var_ref (arg, complain);
13134 if (carg != arg)
13136 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13137 proxies. */
13138 if (i == 0)
13140 spec = copy_node (spec);
13141 args = copy_node (args);
13142 ARGUMENT_PACK_ARGS (spec) = args;
13143 register_local_specialization (spec, *tp);
13145 TREE_VEC_ELT (args, i) = carg;
13150 if (outer_automatic_var_p (spec))
13151 spec = process_outer_var_ref (spec, complain);
13152 *extra = tree_cons (*tp, spec, *extra);
13154 return NULL_TREE;
13156 static tree
13157 extract_local_specs (tree pattern, tsubst_flags_t complain)
13159 el_data data (complain);
13160 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13161 return data.extra;
13164 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13165 for use in PACK_EXPANSION_EXTRA_ARGS. */
13167 tree
13168 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13170 /* Make a copy of the extra arguments so that they won't get changed
13171 out from under us. */
13172 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13173 if (local_specializations)
13174 if (tree locals = extract_local_specs (pattern, complain))
13175 extra = tree_cons (NULL_TREE, extra, locals);
13176 return extra;
13179 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13180 normal template args to ARGS. */
13182 tree
13183 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13185 if (extra && TREE_CODE (extra) == TREE_LIST)
13187 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13189 /* The partial instantiation involved local declarations collected in
13190 extract_local_specs; map from the general template to our local
13191 context. */
13192 tree gen = TREE_PURPOSE (elt);
13193 tree inst = TREE_VALUE (elt);
13194 if (DECL_P (inst))
13195 if (tree local = retrieve_local_specialization (inst))
13196 inst = local;
13197 /* else inst is already a full instantiation of the pack. */
13198 register_local_specialization (inst, gen);
13200 gcc_assert (!TREE_PURPOSE (extra));
13201 extra = TREE_VALUE (extra);
13203 if (uses_template_parms (extra))
13205 /* This can happen after dependent substitution into a
13206 requires-expr or a lambda that uses constexpr if. */
13207 extra = tsubst_template_args (extra, args, complain, in_decl);
13208 args = add_outermost_template_args (args, extra);
13210 else
13211 args = add_to_template_args (extra, args);
13212 return args;
13215 /* Substitute ARGS into T, which is an pack expansion
13216 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13217 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13218 (if only a partial substitution could be performed) or
13219 ERROR_MARK_NODE if there was an error. */
13220 tree
13221 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13222 tree in_decl)
13224 tree pattern;
13225 tree pack, packs = NULL_TREE;
13226 bool unsubstituted_packs = false;
13227 int i, len = -1;
13228 tree result;
13229 bool need_local_specializations = false;
13230 int levels;
13232 gcc_assert (PACK_EXPANSION_P (t));
13233 pattern = PACK_EXPANSION_PATTERN (t);
13235 /* Add in any args remembered from an earlier partial instantiation. */
13236 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13238 levels = TMPL_ARGS_DEPTH (args);
13240 /* Determine the argument packs that will instantiate the parameter
13241 packs used in the expansion expression. While we're at it,
13242 compute the number of arguments to be expanded and make sure it
13243 is consistent. */
13244 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13245 pack = TREE_CHAIN (pack))
13247 tree parm_pack = TREE_VALUE (pack);
13248 tree arg_pack = NULL_TREE;
13249 tree orig_arg = NULL_TREE;
13250 int level = 0;
13252 if (TREE_CODE (parm_pack) == BASES)
13254 gcc_assert (parm_pack == pattern);
13255 if (BASES_DIRECT (parm_pack))
13256 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13257 args, complain,
13258 in_decl, false),
13259 complain);
13260 else
13261 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13262 args, complain, in_decl,
13263 false), complain);
13265 else if (builtin_pack_call_p (parm_pack))
13267 if (parm_pack != pattern)
13269 if (complain & tf_error)
13270 sorry ("%qE is not the entire pattern of the pack expansion",
13271 parm_pack);
13272 return error_mark_node;
13274 return expand_builtin_pack_call (parm_pack, args,
13275 complain, in_decl);
13277 else if (TREE_CODE (parm_pack) == PARM_DECL)
13279 /* We know we have correct local_specializations if this
13280 expansion is at function scope, or if we're dealing with a
13281 local parameter in a requires expression; for the latter,
13282 tsubst_requires_expr set it up appropriately. */
13283 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13284 arg_pack = retrieve_local_specialization (parm_pack);
13285 else
13286 /* We can't rely on local_specializations for a parameter
13287 name used later in a function declaration (such as in a
13288 late-specified return type). Even if it exists, it might
13289 have the wrong value for a recursive call. */
13290 need_local_specializations = true;
13292 if (!arg_pack)
13294 /* This parameter pack was used in an unevaluated context. Just
13295 make a dummy decl, since it's only used for its type. */
13296 ++cp_unevaluated_operand;
13297 arg_pack = tsubst_decl (parm_pack, args, complain);
13298 --cp_unevaluated_operand;
13299 if (arg_pack && DECL_PACK_P (arg_pack))
13300 /* Partial instantiation of the parm_pack, we can't build
13301 up an argument pack yet. */
13302 arg_pack = NULL_TREE;
13303 else
13304 arg_pack = make_fnparm_pack (arg_pack);
13306 else if (DECL_PACK_P (arg_pack))
13307 /* This argument pack isn't fully instantiated yet. */
13308 arg_pack = NULL_TREE;
13310 else if (is_capture_proxy (parm_pack))
13312 arg_pack = retrieve_local_specialization (parm_pack);
13313 if (DECL_PACK_P (arg_pack))
13314 arg_pack = NULL_TREE;
13316 else
13318 int idx;
13319 template_parm_level_and_index (parm_pack, &level, &idx);
13320 if (level <= levels)
13321 arg_pack = TMPL_ARG (args, level, idx);
13323 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13324 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13325 arg_pack = NULL_TREE;
13328 orig_arg = arg_pack;
13329 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13330 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13332 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13333 /* This can only happen if we forget to expand an argument
13334 pack somewhere else. Just return an error, silently. */
13336 result = make_tree_vec (1);
13337 TREE_VEC_ELT (result, 0) = error_mark_node;
13338 return result;
13341 if (arg_pack)
13343 int my_len =
13344 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13346 /* Don't bother trying to do a partial substitution with
13347 incomplete packs; we'll try again after deduction. */
13348 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13349 return t;
13351 if (len < 0)
13352 len = my_len;
13353 else if (len != my_len)
13355 if (!(complain & tf_error))
13356 /* Fail quietly. */;
13357 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13358 error ("mismatched argument pack lengths while expanding %qT",
13359 pattern);
13360 else
13361 error ("mismatched argument pack lengths while expanding %qE",
13362 pattern);
13363 return error_mark_node;
13366 /* Keep track of the parameter packs and their corresponding
13367 argument packs. */
13368 packs = tree_cons (parm_pack, arg_pack, packs);
13369 TREE_TYPE (packs) = orig_arg;
13371 else
13373 /* We can't substitute for this parameter pack. We use a flag as
13374 well as the missing_level counter because function parameter
13375 packs don't have a level. */
13376 gcc_assert (processing_template_decl || is_auto (parm_pack));
13377 unsubstituted_packs = true;
13381 /* If the expansion is just T..., return the matching argument pack, unless
13382 we need to call convert_from_reference on all the elements. This is an
13383 important optimization; see c++/68422. */
13384 if (!unsubstituted_packs
13385 && TREE_PURPOSE (packs) == pattern)
13387 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13389 /* If the argument pack is a single pack expansion, pull it out. */
13390 if (TREE_VEC_LENGTH (args) == 1
13391 && pack_expansion_args_count (args))
13392 return TREE_VEC_ELT (args, 0);
13394 /* Types need no adjustment, nor does sizeof..., and if we still have
13395 some pack expansion args we won't do anything yet. */
13396 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13397 || PACK_EXPANSION_SIZEOF_P (t)
13398 || pack_expansion_args_count (args))
13399 return args;
13400 /* Also optimize expression pack expansions if we can tell that the
13401 elements won't have reference type. */
13402 tree type = TREE_TYPE (pattern);
13403 if (type && !TYPE_REF_P (type)
13404 && !PACK_EXPANSION_P (type)
13405 && !WILDCARD_TYPE_P (type))
13406 return args;
13407 /* Otherwise use the normal path so we get convert_from_reference. */
13410 /* We cannot expand this expansion expression, because we don't have
13411 all of the argument packs we need. */
13412 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13414 /* We got some full packs, but we can't substitute them in until we
13415 have values for all the packs. So remember these until then. */
13417 t = make_pack_expansion (pattern, complain);
13418 PACK_EXPANSION_EXTRA_ARGS (t)
13419 = build_extra_args (pattern, args, complain);
13420 return t;
13423 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13424 type, so create our own local specializations map; the current map is
13425 either NULL or (in the case of recursive unification) might have
13426 bindings that we don't want to use or alter. */
13427 local_specialization_stack lss (need_local_specializations
13428 ? lss_blank : lss_nop);
13430 if (unsubstituted_packs)
13432 /* There were no real arguments, we're just replacing a parameter
13433 pack with another version of itself. Substitute into the
13434 pattern and return a PACK_EXPANSION_*. The caller will need to
13435 deal with that. */
13436 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13437 result = tsubst_expr (pattern, args, complain, in_decl,
13438 /*integral_constant_expression_p=*/false);
13439 else
13440 result = tsubst (pattern, args, complain, in_decl);
13441 result = make_pack_expansion (result, complain);
13442 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13443 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13444 if (PACK_EXPANSION_AUTO_P (t))
13446 /* This is a fake auto... pack expansion created in add_capture with
13447 _PACKS that don't appear in the pattern. Copy one over. */
13448 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13449 pack = retrieve_local_specialization (TREE_VALUE (packs));
13450 gcc_checking_assert (DECL_PACK_P (pack));
13451 PACK_EXPANSION_PARAMETER_PACKS (result)
13452 = build_tree_list (NULL_TREE, pack);
13453 PACK_EXPANSION_AUTO_P (result) = true;
13455 return result;
13458 gcc_assert (len >= 0);
13460 /* For each argument in each argument pack, substitute into the
13461 pattern. */
13462 result = make_tree_vec (len);
13463 tree elem_args = copy_template_args (args);
13464 for (i = 0; i < len; ++i)
13466 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13468 elem_args, complain,
13469 in_decl);
13470 TREE_VEC_ELT (result, i) = t;
13471 if (t == error_mark_node)
13473 result = error_mark_node;
13474 break;
13478 /* Update ARGS to restore the substitution from parameter packs to
13479 their argument packs. */
13480 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13482 tree parm = TREE_PURPOSE (pack);
13484 if (TREE_CODE (parm) == PARM_DECL
13485 || VAR_P (parm)
13486 || TREE_CODE (parm) == FIELD_DECL)
13487 register_local_specialization (TREE_TYPE (pack), parm);
13488 else
13490 int idx, level;
13492 if (TREE_VALUE (pack) == NULL_TREE)
13493 continue;
13495 template_parm_level_and_index (parm, &level, &idx);
13497 /* Update the corresponding argument. */
13498 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13499 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13500 TREE_TYPE (pack);
13501 else
13502 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13506 /* If the dependent pack arguments were such that we end up with only a
13507 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13508 if (len == 1 && TREE_CODE (result) == TREE_VEC
13509 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13510 return TREE_VEC_ELT (result, 0);
13512 return result;
13515 /* Make an argument pack out of the TREE_VEC VEC. */
13517 static tree
13518 make_argument_pack (tree vec)
13520 tree pack;
13522 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13523 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13524 else
13526 pack = make_node (NONTYPE_ARGUMENT_PACK);
13527 TREE_CONSTANT (pack) = 1;
13529 ARGUMENT_PACK_ARGS (pack) = vec;
13530 return pack;
13533 /* Return an exact copy of template args T that can be modified
13534 independently. */
13536 static tree
13537 copy_template_args (tree t)
13539 if (t == error_mark_node)
13540 return t;
13542 int len = TREE_VEC_LENGTH (t);
13543 tree new_vec = make_tree_vec (len);
13545 for (int i = 0; i < len; ++i)
13547 tree elt = TREE_VEC_ELT (t, i);
13548 if (elt && TREE_CODE (elt) == TREE_VEC)
13549 elt = copy_template_args (elt);
13550 TREE_VEC_ELT (new_vec, i) = elt;
13553 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13554 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13556 return new_vec;
13559 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13561 tree
13562 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13563 tree in_decl)
13565 /* This flag is used only during deduction, and we don't expect to
13566 substitute such ARGUMENT_PACKs. */
13567 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13569 /* Substitute into each of the arguments. */
13570 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13571 args, complain, in_decl);
13572 if (pack_args == error_mark_node)
13573 return error_mark_node;
13575 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13576 return orig_arg;
13578 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13579 template parameter, we might be able to avoid allocating a new
13580 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13581 if the substituted result is identical to it. */
13582 if (tree parm = template_arg_to_parm (orig_arg))
13584 int level, index;
13585 template_parm_level_and_index (parm, &level, &index);
13586 if (TMPL_ARGS_DEPTH (args) >= level)
13587 if (tree arg = TMPL_ARG (args, level, index))
13588 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13589 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13591 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13592 return arg;
13596 tree new_arg;
13597 if (TYPE_P (orig_arg))
13599 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13600 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13602 else
13604 new_arg = make_node (TREE_CODE (orig_arg));
13605 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13607 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13608 return new_arg;
13611 /* Substitute ARGS into the vector or list of template arguments T. */
13613 tree
13614 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13616 if (t == error_mark_node)
13617 return error_mark_node;
13619 const int len = TREE_VEC_LENGTH (t);
13620 tree *elts = XALLOCAVEC (tree, len);
13621 int expanded_len_adjust = 0;
13623 /* True iff the substituted result is identical to T. */
13624 bool const_subst_p = true;
13626 for (int i = 0; i < len; i++)
13628 tree orig_arg = TREE_VEC_ELT (t, i);
13629 tree new_arg;
13631 if (!orig_arg)
13632 new_arg = NULL_TREE;
13633 else if (TREE_CODE (orig_arg) == TREE_VEC)
13634 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13635 else if (PACK_EXPANSION_P (orig_arg))
13637 /* Substitute into an expansion expression. */
13638 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13640 if (TREE_CODE (new_arg) == TREE_VEC)
13641 /* Add to the expanded length adjustment the number of
13642 expanded arguments. We subtract one from this
13643 measurement, because the argument pack expression
13644 itself is already counted as 1 in
13645 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13646 the argument pack is empty. */
13647 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13649 else if (ARGUMENT_PACK_P (orig_arg))
13650 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13651 else
13652 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13654 if (new_arg == error_mark_node)
13655 return error_mark_node;
13657 elts[i] = new_arg;
13658 if (new_arg != orig_arg)
13659 const_subst_p = false;
13662 if (const_subst_p)
13663 return t;
13665 tree maybe_reuse = NULL_TREE;
13667 /* If ARGS and T are both multi-level, the substituted result may be
13668 identical to ARGS. */
13669 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13670 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13671 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13672 maybe_reuse = args;
13673 /* If T appears to be a vector of generic template arguments, the
13674 substituted result may be identical to the corresponding level
13675 from ARGS. */
13676 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13678 int level, index;
13679 template_parm_level_and_index (parm, &level, &index);
13680 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13681 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13684 /* If the substituted result is identical to MAYBE_REUSE, return
13685 it and avoid allocating a new TREE_VEC, as an optimization. */
13686 if (maybe_reuse != NULL_TREE
13687 && TREE_VEC_LENGTH (maybe_reuse) == len
13688 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13689 return maybe_reuse;
13691 /* If T consists of only a pack expansion for which substitution yielded
13692 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13693 of effectively making a copy. */
13694 if (len == 1
13695 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13696 && TREE_CODE (elts[0]) == TREE_VEC)
13697 return elts[0];
13699 /* Make space for the expanded arguments coming from template
13700 argument packs. */
13701 tree r = make_tree_vec (len + expanded_len_adjust);
13702 /* T can contain TREE_VECs. That happens if T contains the
13703 arguments for a member template.
13704 In that case each TREE_VEC in T represents a level of template
13705 arguments, and T won't carry any non defaulted argument count.
13706 It will rather be the nested TREE_VECs that will carry one.
13707 In other words, T carries a non defaulted argument count only
13708 if it doesn't contain any nested TREE_VEC. */
13709 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13711 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13712 count += expanded_len_adjust;
13713 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13716 int out = 0;
13717 for (int i = 0; i < len; i++)
13719 tree orig_arg = TREE_VEC_ELT (t, i);
13720 if (orig_arg
13721 && PACK_EXPANSION_P (orig_arg)
13722 && TREE_CODE (elts[i]) == TREE_VEC)
13724 /* Now expand the template argument pack "in place". */
13725 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13726 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13728 else
13730 TREE_VEC_ELT (r, out) = elts[i];
13731 out++;
13734 gcc_assert (out == TREE_VEC_LENGTH (r));
13736 return r;
13739 /* Substitute ARGS into one level PARMS of template parameters. */
13741 static tree
13742 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13744 if (parms == error_mark_node)
13745 return error_mark_node;
13747 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13749 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13751 tree tuple = TREE_VEC_ELT (parms, i);
13753 if (tuple == error_mark_node)
13754 continue;
13756 TREE_VEC_ELT (new_vec, i) =
13757 tsubst_template_parm (tuple, args, complain);
13760 return new_vec;
13763 /* Return the result of substituting ARGS into the template parameters
13764 given by PARMS. If there are m levels of ARGS and m + n levels of
13765 PARMS, then the result will contain n levels of PARMS. For
13766 example, if PARMS is `template <class T> template <class U>
13767 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13768 result will be `template <int*, double, class V>'. */
13770 static tree
13771 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13773 tree r = NULL_TREE;
13774 tree* new_parms;
13776 /* When substituting into a template, we must set
13777 PROCESSING_TEMPLATE_DECL as the template parameters may be
13778 dependent if they are based on one-another, and the dependency
13779 predicates are short-circuit outside of templates. */
13780 ++processing_template_decl;
13782 for (new_parms = &r;
13783 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13784 new_parms = &(TREE_CHAIN (*new_parms)),
13785 parms = TREE_CHAIN (parms))
13787 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13788 args, complain);
13789 *new_parms =
13790 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13791 - TMPL_ARGS_DEPTH (args)),
13792 new_vec, NULL_TREE);
13793 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13794 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13797 --processing_template_decl;
13799 return r;
13802 /* Return the result of substituting ARGS into one template parameter
13803 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13804 parameter and which TREE_PURPOSE is the default argument of the
13805 template parameter. */
13807 static tree
13808 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13810 tree default_value, parm_decl;
13812 if (args == NULL_TREE
13813 || t == NULL_TREE
13814 || t == error_mark_node)
13815 return t;
13817 gcc_assert (TREE_CODE (t) == TREE_LIST);
13819 default_value = TREE_PURPOSE (t);
13820 parm_decl = TREE_VALUE (t);
13822 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13823 if (TREE_CODE (parm_decl) == PARM_DECL
13824 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13825 parm_decl = error_mark_node;
13826 default_value = tsubst_template_arg (default_value, args,
13827 complain, NULL_TREE);
13829 tree r = build_tree_list (default_value, parm_decl);
13830 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13831 return r;
13834 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13835 parameter in PARMS for sake of declaration matching. */
13837 static void
13838 tsubst_each_template_parm_constraints (tree parms, tree args,
13839 tsubst_flags_t complain)
13841 ++processing_template_decl;
13842 for (; parms; parms = TREE_CHAIN (parms))
13844 tree level = TREE_VALUE (parms);
13845 for (tree parm : tree_vec_range (level))
13846 TEMPLATE_PARM_CONSTRAINTS (parm)
13847 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13848 complain, NULL_TREE);
13850 --processing_template_decl;
13853 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13854 type T. If T is not an aggregate or enumeration type, it is
13855 handled as if by tsubst. IN_DECL is as for tsubst. If
13856 ENTERING_SCOPE is nonzero, T is the context for a template which
13857 we are presently tsubst'ing. Return the substituted value. */
13859 static tree
13860 tsubst_aggr_type (tree t,
13861 tree args,
13862 tsubst_flags_t complain,
13863 tree in_decl,
13864 int entering_scope)
13866 if (t == NULL_TREE)
13867 return NULL_TREE;
13869 /* If T is an alias template specialization, we want to substitute that
13870 rather than strip it, especially if it's dependent_alias_template_spec_p.
13871 It should be OK not to handle entering_scope in this case, since
13872 DECL_CONTEXT will never be an alias template specialization. We only get
13873 here with an alias when tsubst calls us for TYPENAME_TYPE. */
13874 if (alias_template_specialization_p (t, nt_transparent))
13875 return tsubst (t, args, complain, in_decl);
13877 switch (TREE_CODE (t))
13879 case RECORD_TYPE:
13880 if (TYPE_PTRMEMFUNC_P (t))
13881 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13883 /* Fall through. */
13884 case ENUMERAL_TYPE:
13885 case UNION_TYPE:
13886 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13888 tree argvec;
13889 tree r;
13891 /* In "sizeof(X<I>)" we need to evaluate "I". */
13892 cp_evaluated ev;
13894 /* Figure out what arguments are appropriate for the
13895 type we are trying to find. For example, given:
13897 template <class T> struct S;
13898 template <class T, class U> void f(T, U) { S<U> su; }
13900 and supposing that we are instantiating f<int, double>,
13901 then our ARGS will be {int, double}, but, when looking up
13902 S we only want {double}. */
13903 argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13904 complain, in_decl);
13905 if (argvec == error_mark_node)
13906 r = error_mark_node;
13907 else
13909 r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
13910 entering_scope, complain);
13911 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
13914 return r;
13916 else
13917 /* This is not a template type, so there's nothing to do. */
13918 return t;
13920 default:
13921 return tsubst (t, args, complain, in_decl);
13925 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
13926 indexed in reverse order of the parameters. */
13928 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
13930 /* Return a reference to the vec* of defarg insts for FN. */
13932 static vec<tree,va_gc> *&
13933 defarg_insts_for (tree fn)
13935 if (!defarg_inst)
13936 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
13937 tree_vec_map in = { { fn }, nullptr };
13938 tree_vec_map **slot
13939 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
13940 if (!*slot)
13942 *slot = ggc_alloc<tree_vec_map> ();
13943 **slot = in;
13945 return (*slot)->to;
13948 /* Substitute into the default argument ARG (a default argument for
13949 FN), which has the indicated TYPE. */
13951 tree
13952 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13953 tsubst_flags_t complain)
13955 int errs = errorcount + sorrycount;
13957 /* This can happen in invalid code. */
13958 if (TREE_CODE (arg) == DEFERRED_PARSE)
13959 return arg;
13961 /* Shortcut {}. */
13962 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13963 && CONSTRUCTOR_NELTS (arg) == 0)
13964 return arg;
13966 tree parm = FUNCTION_FIRST_USER_PARM (fn);
13967 parm = chain_index (parmnum, parm);
13968 tree parmtype = TREE_TYPE (parm);
13969 if (DECL_BY_REFERENCE (parm))
13970 parmtype = TREE_TYPE (parmtype);
13971 if (parmtype == error_mark_node)
13972 return error_mark_node;
13974 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13976 /* Remember the location of the pointer to the vec rather than the location
13977 of the particular element, in case the vec grows in tsubst_expr. */
13978 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
13979 /* Index in reverse order to avoid allocating space for initial parameters
13980 that don't have default arguments. */
13981 unsigned ridx = list_length (parm);
13982 if (vec_safe_length (defs) < ridx)
13983 vec_safe_grow_cleared (defs, ridx);
13984 else if (tree inst = (*defs)[ridx - 1])
13985 return inst;
13987 /* This default argument came from a template. Instantiate the
13988 default argument here, not in tsubst. In the case of
13989 something like:
13991 template <class T>
13992 struct S {
13993 static T t();
13994 void f(T = t());
13997 we must be careful to do name lookup in the scope of S<T>,
13998 rather than in the current class. */
13999 push_to_top_level ();
14000 push_access_scope (fn);
14001 push_deferring_access_checks (dk_no_deferred);
14002 start_lambda_scope (parm);
14004 /* The default argument expression may cause implicitly defined
14005 member functions to be synthesized, which will result in garbage
14006 collection. We must treat this situation as if we were within
14007 the body of function so as to avoid collecting live data on the
14008 stack. */
14009 ++function_depth;
14010 arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
14011 complain, NULL_TREE,
14012 /*integral_constant_expression_p=*/false);
14013 --function_depth;
14015 finish_lambda_scope ();
14017 /* Make sure the default argument is reasonable. */
14018 arg = check_default_argument (type, arg, complain);
14020 if (errorcount+sorrycount > errs
14021 && (complain & tf_warning_or_error))
14022 inform (input_location,
14023 " when instantiating default argument for call to %qD", fn);
14025 pop_deferring_access_checks ();
14026 pop_access_scope (fn);
14027 pop_from_top_level ();
14029 if (arg != error_mark_node && !cp_unevaluated_operand)
14030 (*defs)[ridx - 1] = arg;
14032 return arg;
14035 /* Substitute into all the default arguments for FN. */
14037 static void
14038 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14040 tree arg;
14041 tree tmpl_args;
14043 tmpl_args = DECL_TI_ARGS (fn);
14045 /* If this function is not yet instantiated, we certainly don't need
14046 its default arguments. */
14047 if (uses_template_parms (tmpl_args))
14048 return;
14049 /* Don't do this again for clones. */
14050 if (DECL_CLONED_FUNCTION_P (fn))
14051 return;
14053 int i = 0;
14054 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14055 arg;
14056 arg = TREE_CHAIN (arg), ++i)
14057 if (TREE_PURPOSE (arg))
14058 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14059 TREE_VALUE (arg),
14060 TREE_PURPOSE (arg),
14061 complain);
14064 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14065 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14067 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14069 void
14070 store_explicit_specifier (tree v, tree t)
14072 if (!explicit_specifier_map)
14073 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14074 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14075 explicit_specifier_map->put (v, t);
14078 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14080 tree
14081 lookup_explicit_specifier (tree v)
14083 return *explicit_specifier_map->get (v);
14086 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14087 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14088 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14089 identical to T. */
14091 static tree
14092 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14093 tree raises, tsubst_flags_t complain)
14095 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14097 tree new_type;
14098 if (TREE_CODE (t) == FUNCTION_TYPE)
14100 new_type = build_function_type (return_type, arg_types);
14101 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14103 else
14105 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14106 /* Don't pick up extra function qualifiers from the basetype. */
14107 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14108 if (! MAYBE_CLASS_TYPE_P (r))
14110 /* [temp.deduct]
14112 Type deduction may fail for any of the following
14113 reasons:
14115 -- Attempting to create "pointer to member of T" when T
14116 is not a class type. */
14117 if (complain & tf_error)
14118 error ("creating pointer to member function of non-class type %qT",
14120 return error_mark_node;
14123 new_type = build_method_type_directly (r, return_type,
14124 TREE_CHAIN (arg_types));
14126 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14128 cp_ref_qualifier rqual = type_memfn_rqual (t);
14129 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14130 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14133 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14134 each of its formal parameters. If there is a disagreement then rebuild
14135 DECL's function type according to its formal parameter types, as part of a
14136 resolution for Core issues 1001/1322. */
14138 static void
14139 maybe_rebuild_function_decl_type (tree decl)
14141 bool function_type_needs_rebuilding = false;
14142 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14144 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14145 while (parm_type_list && parm_type_list != void_list_node)
14147 tree parm_type = TREE_VALUE (parm_type_list);
14148 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14149 if (!same_type_p (parm_type, formal_parm_type_unqual))
14151 function_type_needs_rebuilding = true;
14152 break;
14155 parm_list = DECL_CHAIN (parm_list);
14156 parm_type_list = TREE_CHAIN (parm_type_list);
14160 if (!function_type_needs_rebuilding)
14161 return;
14163 const tree fntype = TREE_TYPE (decl);
14164 tree parm_list = DECL_ARGUMENTS (decl);
14165 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14166 tree new_parm_type_list = NULL_TREE;
14167 tree *q = &new_parm_type_list;
14168 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14170 *q = copy_node (old_parm_type_list);
14171 parm_list = DECL_CHAIN (parm_list);
14172 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14173 q = &TREE_CHAIN (*q);
14175 while (old_parm_type_list && old_parm_type_list != void_list_node)
14177 *q = copy_node (old_parm_type_list);
14178 tree *new_parm_type = &TREE_VALUE (*q);
14179 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14180 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14181 *new_parm_type = formal_parm_type_unqual;
14183 parm_list = DECL_CHAIN (parm_list);
14184 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14185 q = &TREE_CHAIN (*q);
14187 if (old_parm_type_list == void_list_node)
14188 *q = void_list_node;
14190 TREE_TYPE (decl)
14191 = rebuild_function_or_method_type (fntype,
14192 TREE_TYPE (fntype), new_parm_type_list,
14193 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14196 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14198 static tree
14199 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14200 tree lambda_fntype)
14202 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14203 hashval_t hash = 0;
14204 tree in_decl = t;
14206 /* Nobody should be tsubst'ing into non-template functions. */
14207 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14208 || DECL_LOCAL_DECL_P (t));
14210 if (DECL_LOCAL_DECL_P (t))
14212 if (tree spec = retrieve_local_specialization (t))
14213 return spec;
14215 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14217 /* If T is not dependent, just return it. */
14218 if (!uses_template_parms (DECL_TI_ARGS (t))
14219 && !LAMBDA_FUNCTION_P (t))
14220 return t;
14222 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14223 if (non_templated_friend_p (t))
14224 goto friend_case;
14226 /* Calculate the most general template of which R is a
14227 specialization. */
14228 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14230 /* We're substituting a lambda function under tsubst_lambda_expr but not
14231 directly from it; find the matching function we're already inside.
14232 But don't do this if T is a generic lambda with a single level of
14233 template parms, as in that case we're doing a normal instantiation. */
14234 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14235 && (!generic_lambda_fn_p (t)
14236 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14237 return enclosing_instantiation_of (t);
14239 /* Calculate the complete set of arguments used to
14240 specialize R. */
14241 argvec = tsubst_template_args (DECL_TI_ARGS
14242 (DECL_TEMPLATE_RESULT
14243 (DECL_TI_TEMPLATE (t))),
14244 args, complain, in_decl);
14245 if (argvec == error_mark_node)
14246 return error_mark_node;
14248 /* Check to see if we already have this specialization. */
14249 if (!lambda_fntype)
14251 hash = spec_hasher::hash (gen_tmpl, argvec);
14252 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14253 /* The spec for these args might be a partial instantiation of the
14254 template, but here what we want is the FUNCTION_DECL. */
14255 return STRIP_TEMPLATE (spec);
14258 else
14260 /* This special case arises when we have something like this:
14262 template <class T> struct S {
14263 friend void f<int>(int, double);
14266 Here, the DECL_TI_TEMPLATE for the friend declaration
14267 will be an IDENTIFIER_NODE. We are being called from
14268 tsubst_friend_function, and we want only to create a
14269 new decl (R) with appropriate types so that we can call
14270 determine_specialization. */
14271 friend_case:
14272 gen_tmpl = NULL_TREE;
14273 argvec = NULL_TREE;
14276 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14277 : NULL_TREE);
14278 tree ctx = closure ? closure : DECL_CONTEXT (t);
14279 bool member = ctx && TYPE_P (ctx);
14281 if (member && !closure)
14282 ctx = tsubst_aggr_type (ctx, args,
14283 complain, t, /*entering_scope=*/1);
14285 tree type = (lambda_fntype ? lambda_fntype
14286 : tsubst (TREE_TYPE (t), args,
14287 complain | tf_fndecl_type, in_decl));
14288 if (type == error_mark_node)
14289 return error_mark_node;
14291 /* If we hit excessive deduction depth, the type is bogus even if
14292 it isn't error_mark_node, so don't build a decl. */
14293 if (excessive_deduction_depth)
14294 return error_mark_node;
14296 /* We do NOT check for matching decls pushed separately at this
14297 point, as they may not represent instantiations of this
14298 template, and in any case are considered separate under the
14299 discrete model. */
14300 tree r = copy_decl (t);
14301 DECL_USE_TEMPLATE (r) = 0;
14302 TREE_TYPE (r) = type;
14303 /* Clear out the mangled name and RTL for the instantiation. */
14304 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14305 SET_DECL_RTL (r, NULL);
14306 /* Leave DECL_INITIAL set on deleted instantiations. */
14307 if (!DECL_DELETED_FN (r))
14308 DECL_INITIAL (r) = NULL_TREE;
14309 DECL_CONTEXT (r) = ctx;
14310 set_instantiating_module (r);
14312 /* Handle explicit(dependent-expr). */
14313 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14315 tree spec = lookup_explicit_specifier (t);
14316 spec = tsubst_copy_and_build (spec, args, complain, in_decl,
14317 /*function_p=*/false,
14318 /*i_c_e_p=*/true);
14319 spec = build_explicit_specifier (spec, complain);
14320 if (instantiation_dependent_expression_p (spec))
14321 store_explicit_specifier (r, spec);
14322 else
14324 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14325 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14329 /* OpenMP UDRs have the only argument a reference to the declared
14330 type. We want to diagnose if the declared type is a reference,
14331 which is invalid, but as references to references are usually
14332 quietly merged, diagnose it here. */
14333 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14335 tree argtype
14336 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14337 argtype = tsubst (argtype, args, complain, in_decl);
14338 if (TYPE_REF_P (argtype))
14339 error_at (DECL_SOURCE_LOCATION (t),
14340 "reference type %qT in "
14341 "%<#pragma omp declare reduction%>", argtype);
14342 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14343 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14344 argtype);
14347 if (member && DECL_CONV_FN_P (r))
14348 /* Type-conversion operator. Reconstruct the name, in
14349 case it's the name of one of the template's parameters. */
14350 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14352 tree parms = DECL_ARGUMENTS (t);
14353 if (closure)
14354 parms = DECL_CHAIN (parms);
14355 parms = tsubst (parms, args, complain, t);
14356 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14357 DECL_CONTEXT (parm) = r;
14358 if (closure)
14360 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14361 DECL_NAME (tparm) = closure_identifier;
14362 DECL_CHAIN (tparm) = parms;
14363 parms = tparm;
14365 DECL_ARGUMENTS (r) = parms;
14366 DECL_RESULT (r) = NULL_TREE;
14368 maybe_rebuild_function_decl_type (r);
14370 TREE_STATIC (r) = 0;
14371 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14372 DECL_EXTERNAL (r) = 1;
14373 /* If this is an instantiation of a function with internal
14374 linkage, we already know what object file linkage will be
14375 assigned to the instantiation. */
14376 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14377 DECL_DEFER_OUTPUT (r) = 0;
14378 DECL_CHAIN (r) = NULL_TREE;
14379 DECL_PENDING_INLINE_INFO (r) = 0;
14380 DECL_PENDING_INLINE_P (r) = 0;
14381 DECL_SAVED_TREE (r) = NULL_TREE;
14382 DECL_STRUCT_FUNCTION (r) = NULL;
14383 TREE_USED (r) = 0;
14384 /* We'll re-clone as appropriate in instantiate_template. */
14385 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14387 /* If we aren't complaining now, return on error before we register
14388 the specialization so that we'll complain eventually. */
14389 if ((complain & tf_error) == 0
14390 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14391 && !grok_op_properties (r, /*complain=*/false))
14392 return error_mark_node;
14394 /* Associate the constraints directly with the instantiation. We
14395 don't substitute through the constraints; that's only done when
14396 they are checked. */
14397 if (tree ci = get_constraints (t))
14398 set_constraints (r, ci);
14400 if (DECL_FRIEND_CONTEXT (t))
14401 SET_DECL_FRIEND_CONTEXT (r,
14402 tsubst (DECL_FRIEND_CONTEXT (t),
14403 args, complain, in_decl));
14405 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14406 args, complain, in_decl))
14407 return error_mark_node;
14409 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14410 this in the special friend case mentioned above where
14411 GEN_TMPL is NULL. */
14412 if (gen_tmpl && !closure)
14414 DECL_TEMPLATE_INFO (r)
14415 = build_template_info (gen_tmpl, argvec);
14416 SET_DECL_IMPLICIT_INSTANTIATION (r);
14418 tree new_r
14419 = register_specialization (r, gen_tmpl, argvec, false, hash);
14420 if (new_r != r)
14421 /* We instantiated this while substituting into
14422 the type earlier (template/friend54.C). */
14423 return new_r;
14425 /* We're not supposed to instantiate default arguments
14426 until they are called, for a template. But, for a
14427 declaration like:
14429 template <class T> void f ()
14430 { extern void g(int i = T()); }
14432 we should do the substitution when the template is
14433 instantiated. We handle the member function case in
14434 instantiate_class_template since the default arguments
14435 might refer to other members of the class. */
14436 if (!member
14437 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14438 && !uses_template_parms (argvec))
14439 tsubst_default_arguments (r, complain);
14441 else if (DECL_LOCAL_DECL_P (r))
14443 if (!cp_unevaluated_operand)
14444 register_local_specialization (r, t);
14446 else
14447 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14449 /* Copy the list of befriending classes. */
14450 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14451 *friends;
14452 friends = &TREE_CHAIN (*friends))
14454 *friends = copy_node (*friends);
14455 TREE_VALUE (*friends)
14456 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14459 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14461 maybe_retrofit_in_chrg (r);
14462 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14463 return error_mark_node;
14464 /* If this is an instantiation of a member template, clone it.
14465 If it isn't, that'll be handled by
14466 clone_constructors_and_destructors. */
14467 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14468 clone_cdtor (r, /*update_methods=*/false);
14470 else if ((complain & tf_error) != 0
14471 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14472 && !grok_op_properties (r, /*complain=*/true))
14473 return error_mark_node;
14475 /* Possibly limit visibility based on template args. */
14476 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14477 if (DECL_VISIBILITY_SPECIFIED (t))
14479 DECL_VISIBILITY_SPECIFIED (r) = 0;
14480 DECL_ATTRIBUTES (r)
14481 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14483 determine_visibility (r);
14484 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14485 && !processing_template_decl)
14486 defaulted_late_check (r);
14488 if (flag_openmp)
14489 if (tree attr = lookup_attribute ("omp declare variant base",
14490 DECL_ATTRIBUTES (r)))
14491 omp_declare_variant_finalize (r, attr);
14493 return r;
14496 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14498 static tree
14499 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14500 tree lambda_fntype)
14502 /* We can get here when processing a member function template,
14503 member class template, or template template parameter. */
14504 tree decl = DECL_TEMPLATE_RESULT (t);
14505 tree in_decl = t;
14506 tree spec;
14507 tree tmpl_args;
14508 tree full_args;
14509 tree r;
14510 hashval_t hash = 0;
14512 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14514 /* Template template parameter is treated here. */
14515 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14516 if (new_type == error_mark_node)
14517 r = error_mark_node;
14518 /* If we get a real template back, return it. This can happen in
14519 the context of most_specialized_partial_spec. */
14520 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14521 r = new_type;
14522 else
14523 /* The new TEMPLATE_DECL was built in
14524 reduce_template_parm_level. */
14525 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14526 return r;
14529 if (!lambda_fntype)
14531 /* We might already have an instance of this template.
14532 The ARGS are for the surrounding class type, so the
14533 full args contain the tsubst'd args for the context,
14534 plus the innermost args from the template decl. */
14535 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14536 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14537 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14538 /* Because this is a template, the arguments will still be
14539 dependent, even after substitution. If
14540 PROCESSING_TEMPLATE_DECL is not set, the dependency
14541 predicates will short-circuit. */
14542 ++processing_template_decl;
14543 full_args = tsubst_template_args (tmpl_args, args,
14544 complain, in_decl);
14545 --processing_template_decl;
14546 if (full_args == error_mark_node)
14547 return error_mark_node;
14549 /* If this is a default template template argument,
14550 tsubst might not have changed anything. */
14551 if (full_args == tmpl_args)
14552 return t;
14554 hash = spec_hasher::hash (t, full_args);
14555 spec = retrieve_specialization (t, full_args, hash);
14556 if (spec != NULL_TREE)
14558 if (TYPE_P (spec))
14559 /* Type partial instantiations are stored as the type by
14560 lookup_template_class_1, not here as the template. */
14561 spec = CLASSTYPE_TI_TEMPLATE (spec);
14562 return spec;
14566 /* Make a new template decl. It will be similar to the
14567 original, but will record the current template arguments.
14568 We also create a new function declaration, which is just
14569 like the old one, but points to this new template, rather
14570 than the old one. */
14571 r = copy_decl (t);
14572 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14573 DECL_CHAIN (r) = NULL_TREE;
14575 // Build new template info linking to the original template decl.
14576 if (!lambda_fntype)
14578 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14579 SET_DECL_IMPLICIT_INSTANTIATION (r);
14581 else
14582 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14584 /* The template parameters for this new template are all the
14585 template parameters for the old template, except the
14586 outermost level of parameters. */
14587 auto tparm_guard = make_temp_override (current_template_parms);
14588 DECL_TEMPLATE_PARMS (r)
14589 = current_template_parms
14590 = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14591 complain);
14593 bool class_p = false;
14594 tree inner = decl;
14595 ++processing_template_decl;
14596 if (TREE_CODE (inner) == FUNCTION_DECL)
14597 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14598 else
14600 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14602 class_p = true;
14603 inner = TREE_TYPE (inner);
14605 if (class_p)
14606 inner = tsubst_aggr_type (inner, args, complain,
14607 in_decl, /*entering*/1);
14608 else
14609 inner = tsubst (inner, args, complain, in_decl);
14611 --processing_template_decl;
14612 if (inner == error_mark_node)
14613 return error_mark_node;
14615 if (class_p)
14617 /* For a partial specialization, we need to keep pointing to
14618 the primary template. */
14619 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14620 CLASSTYPE_TI_TEMPLATE (inner) = r;
14622 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14623 inner = TYPE_MAIN_DECL (inner);
14625 else if (lambda_fntype)
14627 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14628 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14630 else
14632 DECL_TI_TEMPLATE (inner) = r;
14633 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14636 DECL_TEMPLATE_RESULT (r) = inner;
14637 TREE_TYPE (r) = TREE_TYPE (inner);
14638 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14640 if (modules_p ())
14642 /* Propagate module information from the decl. */
14643 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14644 if (DECL_LANG_SPECIFIC (inner))
14645 /* If this is a constrained template, the above tsubst of
14646 inner can find the unconstrained template, which may have
14647 come from an import. This is ok, because we don't
14648 register this instantiation (see below). */
14649 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14650 || (TEMPLATE_PARMS_CONSTRAINTS
14651 (DECL_TEMPLATE_PARMS (t))));
14654 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14655 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14657 if (PRIMARY_TEMPLATE_P (t))
14658 DECL_PRIMARY_TEMPLATE (r) = r;
14660 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14661 /* Record this non-type partial instantiation. */
14662 register_specialization (r, t,
14663 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14664 false, hash);
14666 return r;
14669 /* True if FN is the op() for a lambda in an uninstantiated template. */
14671 bool
14672 lambda_fn_in_template_p (tree fn)
14674 if (!fn || !LAMBDA_FUNCTION_P (fn))
14675 return false;
14676 tree closure = DECL_CONTEXT (fn);
14677 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14680 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14681 which the above is true. */
14683 bool
14684 regenerated_lambda_fn_p (tree fn)
14686 if (!fn || !LAMBDA_FUNCTION_P (fn))
14687 return false;
14688 tree closure = DECL_CONTEXT (fn);
14689 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14690 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14693 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14694 If T is not a regenerated LAMBDA_EXPR, return T. */
14696 tree
14697 most_general_lambda (tree t)
14699 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14700 t = TI_TEMPLATE (ti);
14701 return t;
14704 /* Return the set of template arguments used to regenerate the lambda T
14705 from its most general lambda. */
14707 tree
14708 lambda_regenerating_args (tree t)
14710 if (LAMBDA_FUNCTION_P (t))
14711 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14712 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14713 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14714 return TI_ARGS (ti);
14715 else
14716 return NULL_TREE;
14719 /* We're instantiating a variable from template function TCTX. Return the
14720 corresponding current enclosing scope. We can match them up using
14721 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14722 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14723 the template definition in regenerate_decl_from_template. */
14725 static tree
14726 enclosing_instantiation_of (tree tctx)
14728 tree fn = current_function_decl;
14730 /* We shouldn't ever need to do this for other artificial functions. */
14731 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14733 for (; fn; fn = decl_function_context (fn))
14734 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14735 return fn;
14736 gcc_unreachable ();
14739 /* Substitute the ARGS into the T, which is a _DECL. Return the
14740 result of the substitution. Issue error and warning messages under
14741 control of COMPLAIN. */
14743 static tree
14744 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14746 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14747 location_t saved_loc;
14748 tree r = NULL_TREE;
14749 tree in_decl = t;
14750 hashval_t hash = 0;
14752 /* Set the filename and linenumber to improve error-reporting. */
14753 saved_loc = input_location;
14754 input_location = DECL_SOURCE_LOCATION (t);
14756 switch (TREE_CODE (t))
14758 case TEMPLATE_DECL:
14759 r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14760 break;
14762 case FUNCTION_DECL:
14763 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14764 break;
14766 case PARM_DECL:
14768 tree type = NULL_TREE;
14769 int i, len = 1;
14770 tree expanded_types = NULL_TREE;
14771 tree prev_r = NULL_TREE;
14772 tree first_r = NULL_TREE;
14774 if (DECL_PACK_P (t))
14776 /* If there is a local specialization that isn't a
14777 parameter pack, it means that we're doing a "simple"
14778 substitution from inside tsubst_pack_expansion. Just
14779 return the local specialization (which will be a single
14780 parm). */
14781 tree spec = retrieve_local_specialization (t);
14782 if (spec
14783 && TREE_CODE (spec) == PARM_DECL
14784 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14785 RETURN (spec);
14787 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14788 the parameters in this function parameter pack. */
14789 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14790 complain, in_decl);
14791 if (TREE_CODE (expanded_types) == TREE_VEC)
14793 len = TREE_VEC_LENGTH (expanded_types);
14795 /* Zero-length parameter packs are boring. Just substitute
14796 into the chain. */
14797 if (len == 0 && !cp_unevaluated_operand)
14798 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14799 TREE_CHAIN (t)));
14801 else
14803 /* All we did was update the type. Make a note of that. */
14804 type = expanded_types;
14805 expanded_types = NULL_TREE;
14809 /* Loop through all of the parameters we'll build. When T is
14810 a function parameter pack, LEN is the number of expanded
14811 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14812 r = NULL_TREE;
14813 for (i = 0; i < len; ++i)
14815 prev_r = r;
14816 r = copy_node (t);
14817 if (DECL_TEMPLATE_PARM_P (t))
14818 SET_DECL_TEMPLATE_PARM_P (r);
14820 if (expanded_types)
14821 /* We're on the Ith parameter of the function parameter
14822 pack. */
14824 /* Get the Ith type. */
14825 type = TREE_VEC_ELT (expanded_types, i);
14827 /* Rename the parameter to include the index. */
14828 DECL_NAME (r)
14829 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14831 else if (!type)
14832 /* We're dealing with a normal parameter. */
14833 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14835 type = type_decays_to (type);
14836 TREE_TYPE (r) = type;
14837 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14839 if (DECL_INITIAL (r))
14841 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14842 DECL_INITIAL (r) = TREE_TYPE (r);
14843 else
14844 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14845 complain, in_decl);
14848 DECL_CONTEXT (r) = NULL_TREE;
14850 if (!DECL_TEMPLATE_PARM_P (r))
14851 DECL_ARG_TYPE (r) = type_passed_as (type);
14853 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14854 args, complain, in_decl))
14855 return error_mark_node;
14857 /* Keep track of the first new parameter we
14858 generate. That's what will be returned to the
14859 caller. */
14860 if (!first_r)
14861 first_r = r;
14863 /* Build a proper chain of parameters when substituting
14864 into a function parameter pack. */
14865 if (prev_r)
14866 DECL_CHAIN (prev_r) = r;
14869 /* If cp_unevaluated_operand is set, we're just looking for a
14870 single dummy parameter, so don't keep going. */
14871 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14872 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14873 complain, DECL_CHAIN (t));
14875 /* FIRST_R contains the start of the chain we've built. */
14876 r = first_r;
14878 break;
14880 case FIELD_DECL:
14882 tree type = NULL_TREE;
14883 tree vec = NULL_TREE;
14884 tree expanded_types = NULL_TREE;
14885 int len = 1;
14887 if (PACK_EXPANSION_P (TREE_TYPE (t)))
14889 /* This field is a lambda capture pack. Return a TREE_VEC of
14890 the expanded fields to instantiate_class_template_1. */
14891 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14892 complain, in_decl);
14893 if (TREE_CODE (expanded_types) == TREE_VEC)
14895 len = TREE_VEC_LENGTH (expanded_types);
14896 vec = make_tree_vec (len);
14898 else
14900 /* All we did was update the type. Make a note of that. */
14901 type = expanded_types;
14902 expanded_types = NULL_TREE;
14906 for (int i = 0; i < len; ++i)
14908 r = copy_decl (t);
14909 if (expanded_types)
14911 type = TREE_VEC_ELT (expanded_types, i);
14912 DECL_NAME (r)
14913 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14915 else if (!type)
14916 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14918 if (type == error_mark_node)
14919 RETURN (error_mark_node);
14920 TREE_TYPE (r) = type;
14921 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14923 if (DECL_C_BIT_FIELD (r))
14924 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14925 number of bits. */
14926 DECL_BIT_FIELD_REPRESENTATIVE (r)
14927 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14928 complain, in_decl,
14929 /*integral_constant_expression_p=*/true);
14930 if (DECL_INITIAL (t))
14932 /* Set up DECL_TEMPLATE_INFO so that we can get at the
14933 NSDMI in perform_member_init. Still set DECL_INITIAL
14934 so that we know there is one. */
14935 DECL_INITIAL (r) = void_node;
14936 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14937 retrofit_lang_decl (r);
14938 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14940 /* We don't have to set DECL_CONTEXT here; it is set by
14941 finish_member_declaration. */
14942 DECL_CHAIN (r) = NULL_TREE;
14944 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14945 args, complain, in_decl))
14946 return error_mark_node;
14948 if (vec)
14949 TREE_VEC_ELT (vec, i) = r;
14952 if (vec)
14953 r = vec;
14955 break;
14957 case USING_DECL:
14958 /* We reach here only for member using decls. We also need to check
14959 uses_template_parms because DECL_DEPENDENT_P is not set for a
14960 using-declaration that designates a member of the current
14961 instantiation (c++/53549). */
14962 if (DECL_DEPENDENT_P (t)
14963 || uses_template_parms (USING_DECL_SCOPE (t)))
14965 tree scope = USING_DECL_SCOPE (t);
14966 tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14967 if (PACK_EXPANSION_P (scope))
14969 tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14970 int len = TREE_VEC_LENGTH (vec);
14971 r = make_tree_vec (len);
14972 for (int i = 0; i < len; ++i)
14974 tree escope = TREE_VEC_ELT (vec, i);
14975 tree elt = do_class_using_decl (escope, name);
14976 if (!elt)
14978 r = error_mark_node;
14979 break;
14981 else
14983 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14984 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14986 TREE_VEC_ELT (r, i) = elt;
14989 else
14991 tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14992 complain, in_decl);
14993 r = do_class_using_decl (inst_scope, name);
14994 if (!r)
14995 r = error_mark_node;
14996 else
14998 TREE_PROTECTED (r) = TREE_PROTECTED (t);
14999 TREE_PRIVATE (r) = TREE_PRIVATE (t);
15003 else
15005 r = copy_node (t);
15006 DECL_CHAIN (r) = NULL_TREE;
15008 break;
15010 case TYPE_DECL:
15011 case VAR_DECL:
15013 tree argvec = NULL_TREE;
15014 tree gen_tmpl = NULL_TREE;
15015 tree tmpl = NULL_TREE;
15016 tree type = NULL_TREE;
15018 if (TREE_TYPE (t) == error_mark_node)
15019 RETURN (error_mark_node);
15021 if (TREE_CODE (t) == TYPE_DECL
15022 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15024 /* If this is the canonical decl, we don't have to
15025 mess with instantiations, and often we can't (for
15026 typename, template type parms and such). Note that
15027 TYPE_NAME is not correct for the above test if
15028 we've copied the type for a typedef. */
15029 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15030 if (type == error_mark_node)
15031 RETURN (error_mark_node);
15032 r = TYPE_NAME (type);
15033 break;
15036 /* Check to see if we already have the specialization we
15037 need. */
15038 tree spec = NULL_TREE;
15039 bool local_p = false;
15040 tree ctx = DECL_CONTEXT (t);
15041 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15042 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15044 local_p = false;
15045 if (DECL_CLASS_SCOPE_P (t))
15047 ctx = tsubst_aggr_type (ctx, args,
15048 complain,
15049 in_decl, /*entering_scope=*/1);
15050 if (DECL_SELF_REFERENCE_P (t))
15051 /* The context and type of an injected-class-name are
15052 the same, so we don't need to substitute both. */
15053 type = ctx;
15054 /* If CTX is unchanged, then T is in fact the
15055 specialization we want. That situation occurs when
15056 referencing a static data member within in its own
15057 class. We can use pointer equality, rather than
15058 same_type_p, because DECL_CONTEXT is always
15059 canonical... */
15060 if (ctx == DECL_CONTEXT (t)
15061 /* ... unless T is a member template; in which
15062 case our caller can be willing to create a
15063 specialization of that template represented
15064 by T. */
15065 && !(DECL_TI_TEMPLATE (t)
15066 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15067 spec = t;
15070 if (!spec)
15072 tmpl = DECL_TI_TEMPLATE (t);
15073 gen_tmpl = most_general_template (tmpl);
15074 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15075 if (argvec != error_mark_node
15076 && PRIMARY_TEMPLATE_P (gen_tmpl)
15077 && TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (argvec))
15078 /* We're fully specializing a template declaration, so
15079 we need to coerce the innermost arguments corresponding to
15080 the template. */
15081 argvec = (coerce_innermost_template_parms
15082 (DECL_TEMPLATE_PARMS (gen_tmpl),
15083 argvec, t, complain,
15084 /*all*/true, /*defarg*/true));
15085 if (argvec == error_mark_node)
15086 RETURN (error_mark_node);
15087 hash = spec_hasher::hash (gen_tmpl, argvec);
15088 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15091 else
15093 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15094 /* Subsequent calls to pushdecl will fill this in. */
15095 ctx = NULL_TREE;
15096 /* A local variable. */
15097 local_p = true;
15098 /* Unless this is a reference to a static variable from an
15099 enclosing function, in which case we need to fill it in now. */
15100 if (TREE_STATIC (t))
15102 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15103 if (fn != current_function_decl)
15104 ctx = fn;
15106 spec = retrieve_local_specialization (t);
15108 /* If we already have the specialization we need, there is
15109 nothing more to do. */
15110 if (spec)
15112 r = spec;
15113 break;
15116 /* Create a new node for the specialization we need. */
15117 if (type == NULL_TREE)
15119 if (is_typedef_decl (t))
15120 type = DECL_ORIGINAL_TYPE (t);
15121 else
15122 type = TREE_TYPE (t);
15123 if (VAR_P (t)
15124 && VAR_HAD_UNKNOWN_BOUND (t)
15125 && type != error_mark_node)
15126 type = strip_array_domain (type);
15127 tsubst_flags_t tcomplain = complain;
15128 if (VAR_P (t))
15129 tcomplain |= tf_tst_ok;
15130 type = tsubst (type, args, tcomplain, in_decl);
15131 /* Substituting the type might have recursively instantiated this
15132 same alias (c++/86171). */
15133 if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15134 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15136 r = spec;
15137 break;
15140 r = copy_decl (t);
15141 if (VAR_P (r))
15143 DECL_INITIALIZED_P (r) = 0;
15144 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15145 if (type == error_mark_node)
15146 RETURN (error_mark_node);
15147 if (TREE_CODE (type) == FUNCTION_TYPE)
15149 /* It may seem that this case cannot occur, since:
15151 typedef void f();
15152 void g() { f x; }
15154 declares a function, not a variable. However:
15156 typedef void f();
15157 template <typename T> void g() { T t; }
15158 template void g<f>();
15160 is an attempt to declare a variable with function
15161 type. */
15162 error ("variable %qD has function type",
15163 /* R is not yet sufficiently initialized, so we
15164 just use its name. */
15165 DECL_NAME (r));
15166 RETURN (error_mark_node);
15168 type = complete_type (type);
15169 /* Wait until cp_finish_decl to set this again, to handle
15170 circular dependency (template/instantiate6.C). */
15171 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15172 type = check_var_type (DECL_NAME (r), type,
15173 DECL_SOURCE_LOCATION (r));
15174 if (DECL_HAS_VALUE_EXPR_P (t))
15176 tree ve = DECL_VALUE_EXPR (t);
15177 /* If the DECL_VALUE_EXPR is converted to the declared type,
15178 preserve the identity so that gimplify_type_sizes works. */
15179 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15180 if (nop)
15181 ve = TREE_OPERAND (ve, 0);
15182 ve = tsubst_expr (ve, args, complain, in_decl,
15183 /*constant_expression_p=*/false);
15184 if (REFERENCE_REF_P (ve))
15186 gcc_assert (TYPE_REF_P (type));
15187 ve = TREE_OPERAND (ve, 0);
15189 if (nop)
15190 ve = build_nop (type, ve);
15191 else if (DECL_LANG_SPECIFIC (t)
15192 && DECL_OMP_PRIVATIZED_MEMBER (t)
15193 && TREE_CODE (ve) == COMPONENT_REF
15194 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15195 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15196 type = TREE_TYPE (ve);
15197 else
15198 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15199 == TYPE_MAIN_VARIANT (type));
15200 SET_DECL_VALUE_EXPR (r, ve);
15202 if (CP_DECL_THREAD_LOCAL_P (r)
15203 && !processing_template_decl)
15204 set_decl_tls_model (r, decl_default_tls_model (r));
15206 else if (DECL_SELF_REFERENCE_P (t))
15207 SET_DECL_SELF_REFERENCE_P (r);
15208 TREE_TYPE (r) = type;
15209 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15210 DECL_CONTEXT (r) = ctx;
15211 /* Clear out the mangled name and RTL for the instantiation. */
15212 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15213 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15214 SET_DECL_RTL (r, NULL);
15215 set_instantiating_module (r);
15217 /* The initializer must not be expanded until it is required;
15218 see [temp.inst]. */
15219 DECL_INITIAL (r) = NULL_TREE;
15220 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15221 if (VAR_P (r))
15223 if (DECL_LANG_SPECIFIC (r))
15224 SET_DECL_DEPENDENT_INIT_P (r, false);
15226 SET_DECL_MODE (r, VOIDmode);
15228 /* Possibly limit visibility based on template args. */
15229 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15230 if (DECL_VISIBILITY_SPECIFIED (t))
15232 DECL_VISIBILITY_SPECIFIED (r) = 0;
15233 DECL_ATTRIBUTES (r)
15234 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15236 determine_visibility (r);
15239 if (!local_p)
15241 /* A static data member declaration is always marked
15242 external when it is declared in-class, even if an
15243 initializer is present. We mimic the non-template
15244 processing here. */
15245 DECL_EXTERNAL (r) = 1;
15246 if (DECL_NAMESPACE_SCOPE_P (t))
15247 DECL_NOT_REALLY_EXTERN (r) = 1;
15249 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15250 SET_DECL_IMPLICIT_INSTANTIATION (r);
15251 if (!error_operand_p (r) || (complain & tf_error))
15252 register_specialization (r, gen_tmpl, argvec, false, hash);
15254 else
15256 if (DECL_LANG_SPECIFIC (r))
15257 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15258 if (!cp_unevaluated_operand)
15259 register_local_specialization (r, t);
15262 DECL_CHAIN (r) = NULL_TREE;
15264 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15265 /*flags=*/0,
15266 args, complain, in_decl))
15267 return error_mark_node;
15269 /* Preserve a typedef that names a type. */
15270 if (is_typedef_decl (r) && type != error_mark_node)
15272 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15273 set_underlying_type (r);
15275 /* common_handle_aligned_attribute doesn't apply the alignment
15276 to DECL_ORIGINAL_TYPE. */
15277 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15278 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15279 TYPE_ALIGN (TREE_TYPE (t)));
15282 layout_decl (r, 0);
15284 break;
15286 default:
15287 gcc_unreachable ();
15289 #undef RETURN
15291 out:
15292 /* Restore the file and line information. */
15293 input_location = saved_loc;
15295 return r;
15298 /* Substitute into the complete parameter type list PARMS. */
15300 tree
15301 tsubst_function_parms (tree parms,
15302 tree args,
15303 tsubst_flags_t complain,
15304 tree in_decl)
15306 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15309 /* Substitute into the ARG_TYPES of a function type.
15310 If END is a TREE_CHAIN, leave it and any following types
15311 un-substituted. */
15313 static tree
15314 tsubst_arg_types (tree arg_types,
15315 tree args,
15316 tree end,
15317 tsubst_flags_t complain,
15318 tree in_decl)
15320 tree type = NULL_TREE;
15321 int len = 1;
15322 tree expanded_args = NULL_TREE;
15324 if (!arg_types || arg_types == void_list_node || arg_types == end)
15325 return arg_types;
15327 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15329 /* For a pack expansion, perform substitution on the
15330 entire expression. Later on, we'll handle the arguments
15331 one-by-one. */
15332 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15333 args, complain, in_decl);
15335 if (TREE_CODE (expanded_args) == TREE_VEC)
15336 /* So that we'll spin through the parameters, one by one. */
15337 len = TREE_VEC_LENGTH (expanded_args);
15338 else
15340 /* We only partially substituted into the parameter
15341 pack. Our type is TYPE_PACK_EXPANSION. */
15342 type = expanded_args;
15343 expanded_args = NULL_TREE;
15346 else
15347 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15349 /* Check if a substituted type is erroneous before substituting into
15350 the rest of the chain. */
15351 for (int i = 0; i < len; i++)
15353 if (expanded_args)
15354 type = TREE_VEC_ELT (expanded_args, i);
15356 if (type == error_mark_node)
15357 return error_mark_node;
15358 if (VOID_TYPE_P (type))
15360 if (complain & tf_error)
15362 error ("invalid parameter type %qT", type);
15363 if (in_decl)
15364 error ("in declaration %q+D", in_decl);
15366 return error_mark_node;
15370 /* We do not substitute into default arguments here. The standard
15371 mandates that they be instantiated only when needed, which is
15372 done in build_over_call. */
15373 tree default_arg = TREE_PURPOSE (arg_types);
15375 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15376 since the new op() won't have any associated template arguments for us
15377 to refer to later. */
15378 if (lambda_fn_in_template_p (in_decl)
15379 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15380 && DECL_LOCAL_DECL_P (in_decl)))
15381 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
15382 false/*fn*/, false/*constexpr*/);
15384 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15385 args, end, complain, in_decl);
15386 if (remaining_arg_types == error_mark_node)
15387 return error_mark_node;
15389 for (int i = len-1; i >= 0; i--)
15391 if (expanded_args)
15392 type = TREE_VEC_ELT (expanded_args, i);
15394 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15395 top-level qualifiers as required. */
15396 type = cv_unqualified (type_decays_to (type));
15398 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15400 /* We've instantiated a template before its default arguments
15401 have been parsed. This can happen for a nested template
15402 class, and is not an error unless we require the default
15403 argument in a call of this function. */
15404 remaining_arg_types
15405 = tree_cons (default_arg, type, remaining_arg_types);
15406 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15407 remaining_arg_types);
15409 else
15410 remaining_arg_types
15411 = hash_tree_cons (default_arg, type, remaining_arg_types);
15414 return remaining_arg_types;
15417 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15418 *not* handle the exception-specification for FNTYPE, because the
15419 initial substitution of explicitly provided template parameters
15420 during argument deduction forbids substitution into the
15421 exception-specification:
15423 [temp.deduct]
15425 All references in the function type of the function template to the
15426 corresponding template parameters are replaced by the specified tem-
15427 plate argument values. If a substitution in a template parameter or
15428 in the function type of the function template results in an invalid
15429 type, type deduction fails. [Note: The equivalent substitution in
15430 exception specifications is done only when the function is instanti-
15431 ated, at which point a program is ill-formed if the substitution
15432 results in an invalid type.] */
15434 static tree
15435 tsubst_function_type (tree t,
15436 tree args,
15437 tsubst_flags_t complain,
15438 tree in_decl)
15440 tree return_type;
15441 tree arg_types = NULL_TREE;
15443 /* The TYPE_CONTEXT is not used for function/method types. */
15444 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15446 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15447 failure. */
15448 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15450 if (late_return_type_p)
15452 /* Substitute the argument types. */
15453 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15454 complain, in_decl);
15455 if (arg_types == error_mark_node)
15456 return error_mark_node;
15458 tree save_ccp = current_class_ptr;
15459 tree save_ccr = current_class_ref;
15460 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15461 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15462 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15463 if (do_inject)
15465 /* DR 1207: 'this' is in scope in the trailing return type. */
15466 inject_this_parameter (this_type, cp_type_quals (this_type));
15469 /* Substitute the return type. */
15470 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15472 if (do_inject)
15474 current_class_ptr = save_ccp;
15475 current_class_ref = save_ccr;
15478 else
15479 /* Substitute the return type. */
15480 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15482 if (return_type == error_mark_node)
15483 return error_mark_node;
15484 /* DR 486 clarifies that creation of a function type with an
15485 invalid return type is a deduction failure. */
15486 if (TREE_CODE (return_type) == ARRAY_TYPE
15487 || TREE_CODE (return_type) == FUNCTION_TYPE)
15489 if (complain & tf_error)
15491 if (TREE_CODE (return_type) == ARRAY_TYPE)
15492 error ("function returning an array");
15493 else
15494 error ("function returning a function");
15496 return error_mark_node;
15499 if (!late_return_type_p)
15501 /* Substitute the argument types. */
15502 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15503 complain, in_decl);
15504 if (arg_types == error_mark_node)
15505 return error_mark_node;
15508 /* Construct a new type node and return it. */
15509 return rebuild_function_or_method_type (t, return_type, arg_types,
15510 /*raises=*/NULL_TREE, complain);
15513 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15514 ARGS into that specification, and return the substituted
15515 specification. If there is no specification, return NULL_TREE. */
15517 static tree
15518 tsubst_exception_specification (tree fntype,
15519 tree args,
15520 tsubst_flags_t complain,
15521 tree in_decl,
15522 bool defer_ok)
15524 tree specs;
15525 tree new_specs;
15527 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15528 new_specs = NULL_TREE;
15529 if (specs && TREE_PURPOSE (specs))
15531 /* A noexcept-specifier. */
15532 tree expr = TREE_PURPOSE (specs);
15533 if (TREE_CODE (expr) == INTEGER_CST)
15534 new_specs = expr;
15535 else if (defer_ok)
15537 /* Defer instantiation of noexcept-specifiers to avoid
15538 excessive instantiations (c++/49107). */
15539 new_specs = make_node (DEFERRED_NOEXCEPT);
15540 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15542 /* We already partially instantiated this member template,
15543 so combine the new args with the old. */
15544 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15545 = DEFERRED_NOEXCEPT_PATTERN (expr);
15546 DEFERRED_NOEXCEPT_ARGS (new_specs)
15547 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15549 else
15551 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15552 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15555 else
15557 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15559 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15560 args);
15561 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15563 new_specs = tsubst_copy_and_build
15564 (expr, args, complain, in_decl, /*function_p=*/false,
15565 /*integral_constant_expression_p=*/true);
15567 new_specs = build_noexcept_spec (new_specs, complain);
15568 /* We've instantiated a template before a noexcept-specifier
15569 contained therein has been parsed. This can happen for
15570 a nested template class:
15572 struct S {
15573 template<typename> struct B { B() noexcept(...); };
15574 struct A : B<int> { ... use B() ... };
15577 where completing B<int> will trigger instantiating the
15578 noexcept, even though we only parse it at the end of S. */
15579 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15581 gcc_checking_assert (defer_ok);
15582 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15585 else if (specs)
15587 if (! TREE_VALUE (specs))
15588 new_specs = specs;
15589 else
15590 while (specs)
15592 tree spec;
15593 int i, len = 1;
15594 tree expanded_specs = NULL_TREE;
15596 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15598 /* Expand the pack expansion type. */
15599 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15600 args, complain,
15601 in_decl);
15603 if (expanded_specs == error_mark_node)
15604 return error_mark_node;
15605 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15606 len = TREE_VEC_LENGTH (expanded_specs);
15607 else
15609 /* We're substituting into a member template, so
15610 we got a TYPE_PACK_EXPANSION back. Add that
15611 expansion and move on. */
15612 gcc_assert (TREE_CODE (expanded_specs)
15613 == TYPE_PACK_EXPANSION);
15614 new_specs = add_exception_specifier (new_specs,
15615 expanded_specs,
15616 complain);
15617 specs = TREE_CHAIN (specs);
15618 continue;
15622 for (i = 0; i < len; ++i)
15624 if (expanded_specs)
15625 spec = TREE_VEC_ELT (expanded_specs, i);
15626 else
15627 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15628 if (spec == error_mark_node)
15629 return spec;
15630 new_specs = add_exception_specifier (new_specs, spec,
15631 complain);
15634 specs = TREE_CHAIN (specs);
15637 return new_specs;
15640 /* Substitute through a TREE_LIST of types or expressions, handling pack
15641 expansions. */
15643 tree
15644 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15646 if (t == void_list_node)
15647 return t;
15649 tree purpose = TREE_PURPOSE (t);
15650 tree purposevec = NULL_TREE;
15651 if (!purpose)
15653 else if (PACK_EXPANSION_P (purpose))
15655 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15656 if (TREE_CODE (purpose) == TREE_VEC)
15657 purposevec = purpose;
15659 else if (TYPE_P (purpose))
15660 purpose = tsubst (purpose, args, complain, in_decl);
15661 else
15662 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15663 if (purpose == error_mark_node || purposevec == error_mark_node)
15664 return error_mark_node;
15666 tree value = TREE_VALUE (t);
15667 tree valuevec = NULL_TREE;
15668 if (!value)
15670 else if (PACK_EXPANSION_P (value))
15672 value = tsubst_pack_expansion (value, args, complain, in_decl);
15673 if (TREE_CODE (value) == TREE_VEC)
15674 valuevec = value;
15676 else if (TYPE_P (value))
15677 value = tsubst (value, args, complain, in_decl);
15678 else
15679 value = tsubst_copy_and_build (value, args, complain, in_decl);
15680 if (value == error_mark_node || valuevec == error_mark_node)
15681 return error_mark_node;
15683 tree chain = TREE_CHAIN (t);
15684 if (!chain)
15686 else if (TREE_CODE (chain) == TREE_LIST)
15687 chain = tsubst_tree_list (chain, args, complain, in_decl);
15688 else if (TYPE_P (chain))
15689 chain = tsubst (chain, args, complain, in_decl);
15690 else
15691 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15692 if (chain == error_mark_node)
15693 return error_mark_node;
15695 if (purpose == TREE_PURPOSE (t)
15696 && value == TREE_VALUE (t)
15697 && chain == TREE_CHAIN (t))
15698 return t;
15700 int len;
15701 /* Determine the number of arguments. */
15702 if (purposevec)
15704 len = TREE_VEC_LENGTH (purposevec);
15705 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15707 else if (valuevec)
15708 len = TREE_VEC_LENGTH (valuevec);
15709 else
15710 len = 1;
15712 for (int i = len; i-- > 0; )
15714 if (purposevec)
15715 purpose = TREE_VEC_ELT (purposevec, i);
15716 if (valuevec)
15717 value = TREE_VEC_ELT (valuevec, i);
15719 if (value && TYPE_P (value))
15720 chain = hash_tree_cons (purpose, value, chain);
15721 else
15722 chain = tree_cons (purpose, value, chain);
15725 return chain;
15728 /* Take the tree structure T and replace template parameters used
15729 therein with the argument vector ARGS. IN_DECL is an associated
15730 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15731 Issue error and warning messages under control of COMPLAIN. Note
15732 that we must be relatively non-tolerant of extensions here, in
15733 order to preserve conformance; if we allow substitutions that
15734 should not be allowed, we may allow argument deductions that should
15735 not succeed, and therefore report ambiguous overload situations
15736 where there are none. In theory, we could allow the substitution,
15737 but indicate that it should have failed, and allow our caller to
15738 make sure that the right thing happens, but we don't try to do this
15739 yet.
15741 This function is used for dealing with types, decls and the like;
15742 for expressions, use tsubst_expr or tsubst_copy. */
15744 tree
15745 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15747 enum tree_code code;
15748 tree type, r = NULL_TREE;
15750 if (t == NULL_TREE || t == error_mark_node
15751 || t == integer_type_node
15752 || t == void_type_node
15753 || t == char_type_node
15754 || t == unknown_type_node
15755 || TREE_CODE (t) == NAMESPACE_DECL
15756 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15757 return t;
15759 if (DECL_P (t))
15760 return tsubst_decl (t, args, complain);
15762 if (args == NULL_TREE)
15763 return t;
15765 code = TREE_CODE (t);
15767 gcc_assert (code != IDENTIFIER_NODE);
15768 type = TREE_TYPE (t);
15770 gcc_assert (type != unknown_type_node);
15772 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15773 return d;
15775 /* Reuse typedefs. We need to do this to handle dependent attributes,
15776 such as attribute aligned. */
15777 if (TYPE_P (t)
15778 && typedef_variant_p (t))
15780 tree decl = TYPE_NAME (t);
15782 if (alias_template_specialization_p (t, nt_opaque))
15784 /* DECL represents an alias template and we want to
15785 instantiate it. */
15786 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15787 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15788 r = instantiate_alias_template (tmpl, gen_args, complain);
15790 else if (DECL_CLASS_SCOPE_P (decl)
15791 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15792 && uses_template_parms (DECL_CONTEXT (decl)))
15794 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15795 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15796 r = retrieve_specialization (tmpl, gen_args, 0);
15798 else if (DECL_FUNCTION_SCOPE_P (decl)
15799 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15800 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15801 r = retrieve_local_specialization (decl);
15802 else
15803 /* The typedef is from a non-template context. */
15804 return t;
15806 if (r)
15808 r = TREE_TYPE (r);
15809 r = cp_build_qualified_type
15810 (r, cp_type_quals (t) | cp_type_quals (r),
15811 complain | tf_ignore_bad_quals);
15812 return r;
15814 else
15816 /* We don't have an instantiation yet, so drop the typedef. */
15817 int quals = cp_type_quals (t);
15818 t = DECL_ORIGINAL_TYPE (decl);
15819 t = cp_build_qualified_type (t, quals,
15820 complain | tf_ignore_bad_quals);
15824 bool fndecl_type = (complain & tf_fndecl_type);
15825 complain &= ~tf_fndecl_type;
15827 bool tst_ok = (complain & tf_tst_ok);
15828 complain &= ~tf_tst_ok;
15830 if (type
15831 && code != TYPENAME_TYPE
15832 && code != TEMPLATE_TYPE_PARM
15833 && code != TEMPLATE_PARM_INDEX
15834 && code != IDENTIFIER_NODE
15835 && code != FUNCTION_TYPE
15836 && code != METHOD_TYPE)
15837 type = tsubst (type, args, complain, in_decl);
15838 if (type == error_mark_node)
15839 return error_mark_node;
15841 switch (code)
15843 case RECORD_TYPE:
15844 case UNION_TYPE:
15845 case ENUMERAL_TYPE:
15846 return tsubst_aggr_type (t, args, complain, in_decl,
15847 /*entering_scope=*/0);
15849 case ERROR_MARK:
15850 case IDENTIFIER_NODE:
15851 case VOID_TYPE:
15852 case OPAQUE_TYPE:
15853 case REAL_TYPE:
15854 case COMPLEX_TYPE:
15855 case VECTOR_TYPE:
15856 case BOOLEAN_TYPE:
15857 case NULLPTR_TYPE:
15858 case LANG_TYPE:
15859 return t;
15861 case INTEGER_TYPE:
15862 if (t == integer_type_node)
15863 return t;
15865 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15866 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15867 return t;
15870 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15872 max = tsubst_expr (omax, args, complain, in_decl,
15873 /*integral_constant_expression_p=*/false);
15875 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15876 needed. */
15877 if (TREE_CODE (max) == NOP_EXPR
15878 && TREE_SIDE_EFFECTS (omax)
15879 && !TREE_TYPE (max))
15880 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15882 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
15883 with TREE_SIDE_EFFECTS that indicates this is not an integral
15884 constant expression. */
15885 if (processing_template_decl
15886 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15888 gcc_assert (TREE_CODE (max) == NOP_EXPR);
15889 TREE_SIDE_EFFECTS (max) = 1;
15892 return compute_array_index_type (NULL_TREE, max, complain);
15895 case TEMPLATE_TYPE_PARM:
15896 if (template_placeholder_p (t))
15898 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
15899 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
15900 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15901 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
15903 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
15904 return make_template_placeholder (tmpl);
15905 else
15906 return t;
15908 /* Fall through. */
15909 case TEMPLATE_TEMPLATE_PARM:
15910 case BOUND_TEMPLATE_TEMPLATE_PARM:
15911 case TEMPLATE_PARM_INDEX:
15913 int idx;
15914 int level;
15915 int levels;
15916 tree arg = NULL_TREE;
15918 r = NULL_TREE;
15920 gcc_assert (TREE_VEC_LENGTH (args) > 0);
15921 template_parm_level_and_index (t, &level, &idx);
15923 levels = TMPL_ARGS_DEPTH (args);
15924 if (level <= levels
15925 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15927 arg = TMPL_ARG (args, level, idx);
15929 /* See through ARGUMENT_PACK_SELECT arguments. */
15930 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15931 arg = argument_pack_select_arg (arg);
15934 if (arg == error_mark_node)
15935 return error_mark_node;
15936 else if (arg != NULL_TREE)
15938 if (ARGUMENT_PACK_P (arg))
15939 /* If ARG is an argument pack, we don't actually want to
15940 perform a substitution here, because substitutions
15941 for argument packs are only done
15942 element-by-element. We can get to this point when
15943 substituting the type of a non-type template
15944 parameter pack, when that type actually contains
15945 template parameter packs from an outer template, e.g.,
15947 template<typename... Types> struct A {
15948 template<Types... Values> struct B { };
15949 }; */
15950 return t;
15952 if (code == TEMPLATE_TYPE_PARM)
15954 int quals;
15956 /* When building concept checks for the purpose of
15957 deducing placeholders, we can end up with wildcards
15958 where types are expected. Adjust this to the deduced
15959 value. */
15960 if (TREE_CODE (arg) == WILDCARD_DECL)
15961 arg = TREE_TYPE (TREE_TYPE (arg));
15963 gcc_assert (TYPE_P (arg));
15965 quals = cp_type_quals (arg) | cp_type_quals (t);
15967 return cp_build_qualified_type
15968 (arg, quals, complain | tf_ignore_bad_quals);
15970 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15972 /* We are processing a type constructed from a
15973 template template parameter. */
15974 tree argvec = tsubst (TYPE_TI_ARGS (t),
15975 args, complain, in_decl);
15976 if (argvec == error_mark_node)
15977 return error_mark_node;
15979 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15980 || TREE_CODE (arg) == TEMPLATE_DECL
15981 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15983 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15984 /* Consider this code:
15986 template <template <class> class Template>
15987 struct Internal {
15988 template <class Arg> using Bind = Template<Arg>;
15991 template <template <class> class Template, class Arg>
15992 using Instantiate = Template<Arg>; //#0
15994 template <template <class> class Template,
15995 class Argument>
15996 using Bind =
15997 Instantiate<Internal<Template>::template Bind,
15998 Argument>; //#1
16000 When #1 is parsed, the
16001 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16002 parameter `Template' in #0 matches the
16003 UNBOUND_CLASS_TEMPLATE representing the argument
16004 `Internal<Template>::template Bind'; We then want
16005 to assemble the type `Bind<Argument>' that can't
16006 be fully created right now, because
16007 `Internal<Template>' not being complete, the Bind
16008 template cannot be looked up in that context. So
16009 we need to "store" `Bind<Argument>' for later
16010 when the context of Bind becomes complete. Let's
16011 store that in a TYPENAME_TYPE. */
16012 return make_typename_type (TYPE_CONTEXT (arg),
16013 build_nt (TEMPLATE_ID_EXPR,
16014 TYPE_IDENTIFIER (arg),
16015 argvec),
16016 typename_type,
16017 complain);
16019 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16020 are resolving nested-types in the signature of a
16021 member function templates. Otherwise ARG is a
16022 TEMPLATE_DECL and is the real template to be
16023 instantiated. */
16024 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16025 arg = TYPE_NAME (arg);
16027 r = lookup_template_class (arg,
16028 argvec, in_decl,
16029 DECL_CONTEXT (arg),
16030 /*entering_scope=*/0,
16031 complain);
16032 return cp_build_qualified_type
16033 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16035 else if (code == TEMPLATE_TEMPLATE_PARM)
16036 return arg;
16037 else
16038 /* TEMPLATE_PARM_INDEX. */
16039 return convert_from_reference (unshare_expr (arg));
16042 if (level == 1)
16043 /* This can happen during the attempted tsubst'ing in
16044 unify. This means that we don't yet have any information
16045 about the template parameter in question. */
16046 return t;
16048 /* Early in template argument deduction substitution, we don't
16049 want to reduce the level of 'auto', or it will be confused
16050 with a normal template parm in subsequent deduction.
16051 Similarly, don't reduce the level of template parameters to
16052 avoid mismatches when deducing their types. */
16053 if (complain & tf_partial)
16054 return t;
16056 /* If we get here, we must have been looking at a parm for a
16057 more deeply nested template. Make a new version of this
16058 template parameter, but with a lower level. */
16059 switch (code)
16061 case TEMPLATE_TYPE_PARM:
16062 case TEMPLATE_TEMPLATE_PARM:
16063 case BOUND_TEMPLATE_TEMPLATE_PARM:
16064 if (cp_type_quals (t))
16066 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
16067 r = cp_build_qualified_type
16068 (r, cp_type_quals (t),
16069 complain | (code == TEMPLATE_TYPE_PARM
16070 ? tf_ignore_bad_quals : 0));
16072 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16073 && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16074 && (r = (TEMPLATE_PARM_DESCENDANTS
16075 (TEMPLATE_TYPE_PARM_INDEX (t))))
16076 && (r = TREE_TYPE (r))
16077 && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
16078 /* Break infinite recursion when substituting the constraints
16079 of a constrained placeholder. */;
16080 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16081 && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16082 && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
16083 r = TEMPLATE_PARM_DESCENDANTS (arg))
16084 && (TEMPLATE_PARM_LEVEL (r)
16085 == TEMPLATE_PARM_LEVEL (arg) - levels))
16086 /* Cache the simple case of lowering a type parameter. */
16087 r = TREE_TYPE (r);
16088 else
16090 r = copy_type (t);
16091 TEMPLATE_TYPE_PARM_INDEX (r)
16092 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16093 r, levels, args, complain);
16094 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16095 TYPE_MAIN_VARIANT (r) = r;
16096 TYPE_POINTER_TO (r) = NULL_TREE;
16097 TYPE_REFERENCE_TO (r) = NULL_TREE;
16099 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
16100 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16101 /* Propagate constraints on placeholders since they are
16102 only instantiated during satisfaction. */
16103 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16105 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16107 tree tinfo = TYPE_TEMPLATE_INFO (t);
16108 /* We might need to substitute into the types of non-type
16109 template parameters. */
16110 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16111 complain, in_decl);
16112 if (tmpl == error_mark_node)
16113 return error_mark_node;
16114 tree argvec = tsubst (TI_ARGS (tinfo), args,
16115 complain, in_decl);
16116 if (argvec == error_mark_node)
16117 return error_mark_node;
16119 TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
16120 = build_template_info (tmpl, argvec);
16123 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16124 SET_TYPE_STRUCTURAL_EQUALITY (r);
16125 else
16126 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16128 break;
16130 case TEMPLATE_PARM_INDEX:
16131 /* OK, now substitute the type of the non-type parameter. We
16132 couldn't do it earlier because it might be an auto parameter,
16133 and we wouldn't need to if we had an argument. */
16134 type = tsubst (type, args, complain, in_decl);
16135 if (type == error_mark_node)
16136 return error_mark_node;
16137 r = reduce_template_parm_level (t, type, levels, args, complain);
16138 break;
16140 default:
16141 gcc_unreachable ();
16144 return r;
16147 case TREE_LIST:
16148 return tsubst_tree_list (t, args, complain, in_decl);
16150 case TREE_BINFO:
16151 /* We should never be tsubsting a binfo. */
16152 gcc_unreachable ();
16154 case TREE_VEC:
16155 /* A vector of template arguments. */
16156 gcc_assert (!type);
16157 return tsubst_template_args (t, args, complain, in_decl);
16159 case POINTER_TYPE:
16160 case REFERENCE_TYPE:
16162 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16163 return t;
16165 /* [temp.deduct]
16167 Type deduction may fail for any of the following
16168 reasons:
16170 -- Attempting to create a pointer to reference type.
16171 -- Attempting to create a reference to a reference type or
16172 a reference to void.
16174 Core issue 106 says that creating a reference to a reference
16175 during instantiation is no longer a cause for failure. We
16176 only enforce this check in strict C++98 mode. */
16177 if ((TYPE_REF_P (type)
16178 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16179 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16181 static location_t last_loc;
16183 /* We keep track of the last time we issued this error
16184 message to avoid spewing a ton of messages during a
16185 single bad template instantiation. */
16186 if (complain & tf_error
16187 && last_loc != input_location)
16189 if (VOID_TYPE_P (type))
16190 error ("forming reference to void");
16191 else if (code == POINTER_TYPE)
16192 error ("forming pointer to reference type %qT", type);
16193 else
16194 error ("forming reference to reference type %qT", type);
16195 last_loc = input_location;
16198 return error_mark_node;
16200 else if (TREE_CODE (type) == FUNCTION_TYPE
16201 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16202 || type_memfn_rqual (type) != REF_QUAL_NONE))
16204 if (complain & tf_error)
16206 if (code == POINTER_TYPE)
16207 error ("forming pointer to qualified function type %qT",
16208 type);
16209 else
16210 error ("forming reference to qualified function type %qT",
16211 type);
16213 return error_mark_node;
16215 else if (code == POINTER_TYPE)
16217 r = build_pointer_type (type);
16218 if (TREE_CODE (type) == METHOD_TYPE)
16219 r = build_ptrmemfunc_type (r);
16221 else if (TYPE_REF_P (type))
16222 /* In C++0x, during template argument substitution, when there is an
16223 attempt to create a reference to a reference type, reference
16224 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16226 "If a template-argument for a template-parameter T names a type
16227 that is a reference to a type A, an attempt to create the type
16228 'lvalue reference to cv T' creates the type 'lvalue reference to
16229 A,' while an attempt to create the type type rvalue reference to
16230 cv T' creates the type T"
16232 r = cp_build_reference_type
16233 (TREE_TYPE (type),
16234 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16235 else
16236 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16237 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16239 if (r != error_mark_node)
16240 /* Will this ever be needed for TYPE_..._TO values? */
16241 layout_type (r);
16243 return r;
16245 case OFFSET_TYPE:
16247 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16248 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16250 /* [temp.deduct]
16252 Type deduction may fail for any of the following
16253 reasons:
16255 -- Attempting to create "pointer to member of T" when T
16256 is not a class type. */
16257 if (complain & tf_error)
16258 error ("creating pointer to member of non-class type %qT", r);
16259 return error_mark_node;
16261 if (TYPE_REF_P (type))
16263 if (complain & tf_error)
16264 error ("creating pointer to member reference type %qT", type);
16265 return error_mark_node;
16267 if (VOID_TYPE_P (type))
16269 if (complain & tf_error)
16270 error ("creating pointer to member of type void");
16271 return error_mark_node;
16273 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16274 if (TREE_CODE (type) == FUNCTION_TYPE)
16276 /* The type of the implicit object parameter gets its
16277 cv-qualifiers from the FUNCTION_TYPE. */
16278 tree memptr;
16279 tree method_type
16280 = build_memfn_type (type, r, type_memfn_quals (type),
16281 type_memfn_rqual (type));
16282 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16283 return cp_build_qualified_type (memptr, cp_type_quals (t),
16284 complain);
16286 else
16287 return cp_build_qualified_type (build_ptrmem_type (r, type),
16288 cp_type_quals (t),
16289 complain);
16291 case FUNCTION_TYPE:
16292 case METHOD_TYPE:
16294 tree fntype;
16295 tree specs;
16296 fntype = tsubst_function_type (t, args, complain, in_decl);
16297 if (fntype == error_mark_node)
16298 return error_mark_node;
16300 /* Substitute the exception specification. */
16301 specs = tsubst_exception_specification (t, args, complain, in_decl,
16302 /*defer_ok*/fndecl_type);
16303 if (specs == error_mark_node)
16304 return error_mark_node;
16305 if (specs)
16306 fntype = build_exception_variant (fntype, specs);
16307 return fntype;
16309 case ARRAY_TYPE:
16311 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16312 if (domain == error_mark_node)
16313 return error_mark_node;
16315 /* As an optimization, we avoid regenerating the array type if
16316 it will obviously be the same as T. */
16317 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16318 return t;
16320 /* These checks should match the ones in create_array_type_for_decl.
16322 [temp.deduct]
16324 The deduction may fail for any of the following reasons:
16326 -- Attempting to create an array with an element type that
16327 is void, a function type, or a reference type, or [DR337]
16328 an abstract class type. */
16329 if (VOID_TYPE_P (type)
16330 || TREE_CODE (type) == FUNCTION_TYPE
16331 || (TREE_CODE (type) == ARRAY_TYPE
16332 && TYPE_DOMAIN (type) == NULL_TREE)
16333 || TYPE_REF_P (type))
16335 if (complain & tf_error)
16336 error ("creating array of %qT", type);
16337 return error_mark_node;
16340 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16341 !(complain & tf_error)))
16342 return error_mark_node;
16344 r = build_cplus_array_type (type, domain);
16346 if (!valid_array_size_p (input_location, r, in_decl,
16347 (complain & tf_error)))
16348 return error_mark_node;
16350 if (TYPE_USER_ALIGN (t))
16352 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16353 TYPE_USER_ALIGN (r) = 1;
16356 return r;
16359 case TYPENAME_TYPE:
16361 tree ctx = TYPE_CONTEXT (t);
16362 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16364 ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16365 if (ctx == error_mark_node
16366 || TREE_VEC_LENGTH (ctx) > 1)
16367 return error_mark_node;
16368 if (TREE_VEC_LENGTH (ctx) == 0)
16370 if (complain & tf_error)
16371 error ("%qD is instantiated for an empty pack",
16372 TYPENAME_TYPE_FULLNAME (t));
16373 return error_mark_node;
16375 ctx = TREE_VEC_ELT (ctx, 0);
16377 else
16378 ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16379 /*entering_scope=*/1);
16380 if (ctx == error_mark_node)
16381 return error_mark_node;
16383 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16384 complain, in_decl);
16385 if (f == error_mark_node)
16386 return error_mark_node;
16388 if (!MAYBE_CLASS_TYPE_P (ctx))
16390 if (complain & tf_error)
16391 error ("%qT is not a class, struct, or union type", ctx);
16392 return error_mark_node;
16394 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16396 /* Normally, make_typename_type does not require that the CTX
16397 have complete type in order to allow things like:
16399 template <class T> struct S { typename S<T>::X Y; };
16401 But, such constructs have already been resolved by this
16402 point, so here CTX really should have complete type, unless
16403 it's a partial instantiation. */
16404 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16405 return error_mark_node;
16408 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16409 if (tst_ok)
16410 tcomplain |= tf_tst_ok;
16411 f = make_typename_type (ctx, f, typename_type, tcomplain);
16412 if (f == error_mark_node)
16413 return f;
16414 if (TREE_CODE (f) == TYPE_DECL)
16416 complain |= tf_ignore_bad_quals;
16417 f = TREE_TYPE (f);
16420 if (TREE_CODE (f) != TYPENAME_TYPE)
16422 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16424 if (complain & tf_error)
16425 error ("%qT resolves to %qT, which is not an enumeration type",
16426 t, f);
16427 else
16428 return error_mark_node;
16430 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16432 if (complain & tf_error)
16433 error ("%qT resolves to %qT, which is not a class type",
16434 t, f);
16435 else
16436 return error_mark_node;
16440 return cp_build_qualified_type
16441 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16444 case UNBOUND_CLASS_TEMPLATE:
16446 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16447 in_decl, /*entering_scope=*/1);
16448 tree name = TYPE_IDENTIFIER (t);
16449 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16451 if (ctx == error_mark_node || name == error_mark_node)
16452 return error_mark_node;
16454 if (parm_list)
16455 parm_list = tsubst_template_parms (parm_list, args, complain);
16456 return make_unbound_class_template (ctx, name, parm_list, complain);
16459 case TYPEOF_TYPE:
16461 tree type;
16463 ++cp_unevaluated_operand;
16464 ++c_inhibit_evaluation_warnings;
16466 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16467 complain, in_decl,
16468 /*integral_constant_expression_p=*/false);
16470 --cp_unevaluated_operand;
16471 --c_inhibit_evaluation_warnings;
16473 type = finish_typeof (type);
16474 return cp_build_qualified_type (type,
16475 cp_type_quals (t)
16476 | cp_type_quals (type),
16477 complain);
16480 case DECLTYPE_TYPE:
16482 tree type;
16484 ++cp_unevaluated_operand;
16485 ++c_inhibit_evaluation_warnings;
16487 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16488 complain|tf_decltype, in_decl,
16489 /*function_p*/false,
16490 /*integral_constant_expression*/false);
16492 --cp_unevaluated_operand;
16493 --c_inhibit_evaluation_warnings;
16495 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16496 type = lambda_capture_field_type (type,
16497 false /*explicit_init*/,
16498 DECLTYPE_FOR_REF_CAPTURE (t));
16499 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16500 type = lambda_proxy_type (type);
16501 else
16503 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16504 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16505 && EXPR_P (type))
16506 /* In a template ~id could be either a complement expression
16507 or an unqualified-id naming a destructor; if instantiating
16508 it produces an expression, it's not an id-expression or
16509 member access. */
16510 id = false;
16511 type = finish_decltype_type (type, id, complain);
16513 return cp_build_qualified_type (type,
16514 cp_type_quals (t)
16515 | cp_type_quals (type),
16516 complain | tf_ignore_bad_quals);
16519 case UNDERLYING_TYPE:
16521 tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16522 complain, in_decl);
16523 return finish_underlying_type (type);
16526 case TYPE_ARGUMENT_PACK:
16527 case NONTYPE_ARGUMENT_PACK:
16528 return tsubst_argument_pack (t, args, complain, in_decl);
16530 case VOID_CST:
16531 case INTEGER_CST:
16532 case REAL_CST:
16533 case STRING_CST:
16534 case PLUS_EXPR:
16535 case MINUS_EXPR:
16536 case NEGATE_EXPR:
16537 case NOP_EXPR:
16538 case INDIRECT_REF:
16539 case ADDR_EXPR:
16540 case CALL_EXPR:
16541 case ARRAY_REF:
16542 case SCOPE_REF:
16543 /* We should use one of the expression tsubsts for these codes. */
16544 gcc_unreachable ();
16546 default:
16547 sorry ("use of %qs in template", get_tree_code_name (code));
16548 return error_mark_node;
16552 /* OLDFNS is a lookup set of member functions from some class template, and
16553 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16554 of that class template. Return the subset of NEWFNS which are
16555 specializations of a function from OLDFNS. */
16557 static tree
16558 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16560 /* Record all member functions from the old lookup set OLDFNS into
16561 VISIBLE_SET. */
16562 hash_set<tree> visible_set;
16563 bool seen_dep_using = false;
16564 for (tree fn : lkp_range (oldfns))
16566 if (TREE_CODE (fn) == USING_DECL)
16568 /* Imprecisely handle dependent using-decl by keeping all members
16569 in the new lookup set that are defined in a base class, i.e.
16570 members that could plausibly have been introduced by this
16571 dependent using-decl.
16572 FIXME: Track which members are introduced by a dependent
16573 using-decl precisely, perhaps by performing another lookup
16574 from the substituted USING_DECL_SCOPE. */
16575 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16576 seen_dep_using = true;
16578 else
16579 visible_set.add (fn);
16582 /* Returns true iff (a less specialized version of) FN appeared in
16583 the old lookup set OLDFNS. */
16584 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16585 if (DECL_CONTEXT (fn) != newtype)
16586 /* FN is a member function from a base class, introduced via a
16587 using-decl; if it might have been introduced by a dependent
16588 using-decl then just conservatively keep it, otherwise look
16589 in the old lookup set for FN exactly. */
16590 return seen_dep_using || visible_set.contains (fn);
16591 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16592 /* FN is a member function template from the current class;
16593 look in the old lookup set for the TEMPLATE_DECL from which
16594 it was specialized. */
16595 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16596 else
16597 /* FN is a non-template member function from the current class;
16598 look in the old lookup set for the FUNCTION_DECL from which
16599 it was specialized. */
16600 return visible_set.contains (DECL_TEMPLATE_RESULT
16601 (DECL_TI_TEMPLATE (fn)));
16604 bool lookup_changed_p = false;
16605 for (tree fn : lkp_range (newfns))
16606 if (!visible_p (fn))
16608 lookup_changed_p = true;
16609 break;
16611 if (!lookup_changed_p)
16612 return newfns;
16614 /* Filter out from NEWFNS the member functions that weren't
16615 previously visible according to OLDFNS. */
16616 tree filtered_fns = NULL_TREE;
16617 unsigned filtered_size = 0;
16618 for (tree fn : lkp_range (newfns))
16619 if (visible_p (fn))
16621 filtered_fns = lookup_add (fn, filtered_fns);
16622 filtered_size++;
16624 gcc_checking_assert (seen_dep_using
16625 ? filtered_size >= visible_set.elements ()
16626 : filtered_size == visible_set.elements ());
16628 return filtered_fns;
16631 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16632 expression on the left-hand side of the "." or "->" operator. We
16633 only do the lookup if we had a dependent BASELINK. Otherwise we
16634 adjust it onto the instantiated heirarchy. */
16636 static tree
16637 tsubst_baselink (tree baselink, tree object_type,
16638 tree args, tsubst_flags_t complain, tree in_decl)
16640 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16641 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16642 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16644 tree optype = BASELINK_OPTYPE (baselink);
16645 optype = tsubst (optype, args, complain, in_decl);
16647 tree template_args = NULL_TREE;
16648 bool template_id_p = false;
16649 tree fns = BASELINK_FUNCTIONS (baselink);
16650 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16652 template_id_p = true;
16653 template_args = TREE_OPERAND (fns, 1);
16654 fns = TREE_OPERAND (fns, 0);
16655 if (template_args)
16656 template_args = tsubst_template_args (template_args, args,
16657 complain, in_decl);
16660 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16661 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16662 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16663 || optype != BASELINK_OPTYPE (baselink));
16665 if (dependent_p)
16667 tree name = OVL_NAME (fns);
16668 if (IDENTIFIER_CONV_OP_P (name))
16669 name = make_conv_op_name (optype);
16671 /* See maybe_dependent_member_ref. */
16672 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16674 if (template_id_p)
16675 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16676 template_args);
16677 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16678 /* ::template */false);
16681 if (name == complete_dtor_identifier)
16682 /* Treat as-if non-dependent below. */
16683 dependent_p = false;
16685 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16686 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16687 complain);
16688 if (maybe_incomplete)
16690 /* Filter out from the new lookup set those functions which didn't
16691 appear in the original lookup set (in a less specialized form).
16692 This is needed to preserve the consistency of member lookup
16693 performed in an incomplete-class context, within which
16694 later-declared members ought to remain invisible. */
16695 BASELINK_FUNCTIONS (baselink)
16696 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16697 binfo_type);
16698 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16701 if (!baselink)
16703 if ((complain & tf_error)
16704 && constructor_name_p (name, qualifying_scope))
16705 error ("cannot call constructor %<%T::%D%> directly",
16706 qualifying_scope, name);
16707 return error_mark_node;
16710 fns = BASELINK_FUNCTIONS (baselink);
16712 else
16714 /* We're going to overwrite pieces below, make a duplicate. */
16715 baselink = copy_node (baselink);
16717 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16719 /* The decl we found was from non-dependent scope, but we still need
16720 to update the binfos for the instantiated qualifying_scope. */
16721 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16722 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16723 ba_unique, nullptr, complain);
16727 /* If lookup found a single function, mark it as used at this point.
16728 (If lookup found multiple functions the one selected later by
16729 overload resolution will be marked as used at that point.) */
16730 if (!template_id_p && !really_overloaded_fn (fns))
16732 tree fn = OVL_FIRST (fns);
16733 bool ok = mark_used (fn, complain);
16734 if (!ok && !(complain & tf_error))
16735 return error_mark_node;
16736 if (ok && BASELINK_P (baselink))
16737 /* We might have instantiated an auto function. */
16738 TREE_TYPE (baselink) = TREE_TYPE (fn);
16741 if (BASELINK_P (baselink))
16743 /* Add back the template arguments, if present. */
16744 if (template_id_p)
16745 BASELINK_FUNCTIONS (baselink)
16746 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16748 /* Update the conversion operator type. */
16749 BASELINK_OPTYPE (baselink) = optype;
16752 if (!object_type)
16753 object_type = current_class_type;
16755 if (qualified_p || !dependent_p)
16757 baselink = adjust_result_of_qualified_name_lookup (baselink,
16758 qualifying_scope,
16759 object_type);
16760 if (!qualified_p)
16761 /* We need to call adjust_result_of_qualified_name_lookup in case the
16762 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16763 so that we still get virtual function binding. */
16764 BASELINK_QUALIFIED_P (baselink) = false;
16767 return baselink;
16770 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16771 true if the qualified-id will be a postfix-expression in-and-of
16772 itself; false if more of the postfix-expression follows the
16773 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16774 of "&". */
16776 static tree
16777 tsubst_qualified_id (tree qualified_id, tree args,
16778 tsubst_flags_t complain, tree in_decl,
16779 bool done, bool address_p)
16781 tree expr;
16782 tree scope;
16783 tree name;
16784 bool is_template;
16785 tree template_args;
16786 location_t loc = EXPR_LOCATION (qualified_id);
16788 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16790 /* Figure out what name to look up. */
16791 name = TREE_OPERAND (qualified_id, 1);
16792 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16794 is_template = true;
16795 template_args = TREE_OPERAND (name, 1);
16796 if (template_args)
16797 template_args = tsubst_template_args (template_args, args,
16798 complain, in_decl);
16799 if (template_args == error_mark_node)
16800 return error_mark_node;
16801 name = TREE_OPERAND (name, 0);
16803 else
16805 is_template = false;
16806 template_args = NULL_TREE;
16809 /* Substitute into the qualifying scope. When there are no ARGS, we
16810 are just trying to simplify a non-dependent expression. In that
16811 case the qualifying scope may be dependent, and, in any case,
16812 substituting will not help. */
16813 scope = TREE_OPERAND (qualified_id, 0);
16814 if (args)
16816 scope = tsubst (scope, args, complain, in_decl);
16817 expr = tsubst_copy (name, args, complain, in_decl);
16819 else
16820 expr = name;
16822 if (dependent_scope_p (scope))
16824 if (TREE_CODE (expr) == SCOPE_REF)
16825 /* We built one in tsubst_baselink. */
16826 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
16827 else
16829 if (is_template)
16830 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
16831 template_args);
16832 expr = build_qualified_name (NULL_TREE, scope, expr,
16833 QUALIFIED_NAME_IS_TEMPLATE
16834 (qualified_id));
16836 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
16837 return expr;
16840 if (!BASELINK_P (name) && !DECL_P (expr))
16842 if (TREE_CODE (expr) == BIT_NOT_EXPR)
16844 /* A BIT_NOT_EXPR is used to represent a destructor. */
16845 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16847 error ("qualifying type %qT does not match destructor name ~%qT",
16848 scope, TREE_OPERAND (expr, 0));
16849 expr = error_mark_node;
16851 else
16852 expr = lookup_qualified_name (scope, complete_dtor_identifier,
16853 LOOK_want::NORMAL, false);
16855 else
16856 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16857 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16858 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16860 if (complain & tf_error)
16862 error ("dependent-name %qE is parsed as a non-type, but "
16863 "instantiation yields a type", qualified_id);
16864 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16866 return error_mark_node;
16870 if (DECL_P (expr))
16872 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16873 scope, complain))
16874 return error_mark_node;
16875 /* Remember that there was a reference to this entity. */
16876 if (!mark_used (expr, complain) && !(complain & tf_error))
16877 return error_mark_node;
16880 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16882 if (complain & tf_error)
16883 qualified_name_lookup_error (scope,
16884 TREE_OPERAND (qualified_id, 1),
16885 expr, input_location);
16886 return error_mark_node;
16889 if (is_template)
16891 /* We may be repeating a check already done during parsing, but
16892 if it was well-formed and passed then, it will pass again
16893 now, and if it didn't, we wouldn't have got here. The case
16894 we want to catch is when we couldn't tell then, and can now,
16895 namely when templ prior to substitution was an
16896 identifier. */
16897 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16898 return error_mark_node;
16900 if (variable_template_p (expr))
16901 expr = lookup_and_finish_template_variable (expr, template_args,
16902 complain);
16903 else
16904 expr = lookup_template_function (expr, template_args);
16907 if (expr == error_mark_node && complain & tf_error)
16908 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16909 expr, input_location);
16910 else if (TYPE_P (scope))
16912 expr = (adjust_result_of_qualified_name_lookup
16913 (expr, scope, current_nonlambda_class_type ()));
16914 expr = (finish_qualified_id_expr
16915 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16916 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16917 /*template_arg_p=*/false, complain));
16920 /* Expressions do not generally have reference type. */
16921 if (TREE_CODE (expr) != SCOPE_REF
16922 /* However, if we're about to form a pointer-to-member, we just
16923 want the referenced member referenced. */
16924 && TREE_CODE (expr) != OFFSET_REF)
16925 expr = convert_from_reference (expr);
16927 if (REF_PARENTHESIZED_P (qualified_id))
16928 expr = force_paren_expr (expr);
16930 expr = maybe_wrap_with_location (expr, loc);
16932 return expr;
16935 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
16936 initializer, DECL is the substituted VAR_DECL. Other arguments are as
16937 for tsubst. */
16939 static tree
16940 tsubst_init (tree init, tree decl, tree args,
16941 tsubst_flags_t complain, tree in_decl)
16943 if (!init)
16944 return NULL_TREE;
16946 init = tsubst_expr (init, args, complain, in_decl, false);
16948 tree type = TREE_TYPE (decl);
16950 if (!init && type != error_mark_node)
16952 if (tree auto_node = type_uses_auto (type))
16954 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16956 if (complain & tf_error)
16957 error ("initializer for %q#D expands to an empty list "
16958 "of expressions", decl);
16959 return error_mark_node;
16962 else if (!dependent_type_p (type))
16964 /* If we had an initializer but it
16965 instantiated to nothing,
16966 value-initialize the object. This will
16967 only occur when the initializer was a
16968 pack expansion where the parameter packs
16969 used in that expansion were of length
16970 zero. */
16971 init = build_value_init (type, complain);
16972 if (TREE_CODE (init) == AGGR_INIT_EXPR)
16973 init = get_target_expr_sfinae (init, complain);
16974 if (TREE_CODE (init) == TARGET_EXPR)
16975 TARGET_EXPR_DIRECT_INIT_P (init) = true;
16979 return init;
16982 /* If T is a reference to a dependent member of the current instantiation C and
16983 we are trying to refer to that member in a partial instantiation of C,
16984 return a SCOPE_REF; otherwise, return NULL_TREE.
16986 This can happen when forming a C++17 deduction guide, as in PR96199. */
16988 static tree
16989 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16990 tree in_decl)
16992 if (!(complain & tf_dguide))
16993 return NULL_TREE;
16995 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
16996 if (!decl || !DECL_P (decl))
16997 return NULL_TREE;
16999 tree ctx = context_for_name_lookup (decl);
17000 if (!CLASS_TYPE_P (ctx))
17001 return NULL_TREE;
17003 ctx = tsubst (ctx, args, complain, in_decl);
17004 if (!dependent_scope_p (ctx))
17005 return NULL_TREE;
17007 if (TYPE_P (t))
17009 if (typedef_variant_p (t))
17010 t = strip_typedefs (t);
17011 tree decl = TYPE_NAME (t);
17012 if (decl)
17013 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17014 if (!decl)
17015 return NULL_TREE;
17016 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17017 complain);
17020 tree name = DECL_NAME (t);
17021 tree fullname = name;
17022 if (instantiates_primary_template_p (t))
17024 tree tinfo = get_template_info (t);
17025 name = DECL_NAME (TI_TEMPLATE (tinfo));
17026 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17027 targs = tsubst_template_args (targs, args, complain, in_decl);
17028 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17031 if (TREE_CODE (t) == TYPE_DECL)
17033 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17034 && TYPE_NAME (TREE_TYPE (t)) == t)
17035 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17036 scope, but it doesn't need to be rewritten again. */
17037 return NULL_TREE;
17038 tree type = build_typename_type (ctx, name, fullname, typename_type);
17039 return TYPE_NAME (type);
17041 else if (DECL_TYPE_TEMPLATE_P (t))
17042 return make_unbound_class_template (ctx, name,
17043 NULL_TREE, complain);
17044 else
17045 return build_qualified_name (NULL_TREE, ctx, fullname,
17046 TREE_CODE (t) == TEMPLATE_DECL);
17049 /* Like tsubst, but deals with expressions. This function just replaces
17050 template parms; to finish processing the resultant expression, use
17051 tsubst_copy_and_build or tsubst_expr. */
17053 static tree
17054 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17056 enum tree_code code;
17057 tree r;
17059 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17060 return t;
17062 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17063 return d;
17065 code = TREE_CODE (t);
17067 switch (code)
17069 case PARM_DECL:
17070 r = retrieve_local_specialization (t);
17072 if (r == NULL_TREE)
17074 /* We get here for a use of 'this' in an NSDMI. */
17075 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17076 return current_class_ptr;
17078 /* This can happen for a parameter name used later in a function
17079 declaration (such as in a late-specified return type). Just
17080 make a dummy decl, since it's only used for its type. */
17081 gcc_assert (cp_unevaluated_operand != 0);
17082 r = tsubst_decl (t, args, complain);
17083 /* Give it the template pattern as its context; its true context
17084 hasn't been instantiated yet and this is good enough for
17085 mangling. */
17086 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17089 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17090 r = argument_pack_select_arg (r);
17091 if (!mark_used (r, complain) && !(complain & tf_error))
17092 return error_mark_node;
17093 return r;
17095 case CONST_DECL:
17097 tree enum_type;
17098 tree v;
17100 if (DECL_TEMPLATE_PARM_P (t))
17101 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17102 /* There is no need to substitute into namespace-scope
17103 enumerators. */
17104 if (DECL_NAMESPACE_SCOPE_P (t))
17105 return t;
17106 /* If ARGS is NULL, then T is known to be non-dependent. */
17107 if (args == NULL_TREE)
17108 return scalar_constant_value (t);
17110 /* Unfortunately, we cannot just call lookup_name here.
17111 Consider:
17113 template <int I> int f() {
17114 enum E { a = I };
17115 struct S { void g() { E e = a; } };
17118 When we instantiate f<7>::S::g(), say, lookup_name is not
17119 clever enough to find f<7>::a. */
17120 enum_type
17121 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17122 /*entering_scope=*/0);
17124 for (v = TYPE_VALUES (enum_type);
17125 v != NULL_TREE;
17126 v = TREE_CHAIN (v))
17127 if (TREE_PURPOSE (v) == DECL_NAME (t))
17128 return TREE_VALUE (v);
17130 /* We didn't find the name. That should never happen; if
17131 name-lookup found it during preliminary parsing, we
17132 should find it again here during instantiation. */
17133 gcc_unreachable ();
17135 return t;
17137 case FIELD_DECL:
17138 if (DECL_CONTEXT (t))
17140 tree ctx;
17142 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17143 /*entering_scope=*/1);
17144 if (ctx != DECL_CONTEXT (t))
17146 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17147 if (!r)
17149 if (complain & tf_error)
17150 error ("using invalid field %qD", t);
17151 return error_mark_node;
17153 return r;
17157 return t;
17159 case VAR_DECL:
17160 case FUNCTION_DECL:
17161 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17162 r = tsubst (t, args, complain, in_decl);
17163 else if (DECL_LOCAL_DECL_P (t))
17165 /* Local specialization will usually have been created when
17166 we instantiated the DECL_EXPR_DECL. */
17167 r = retrieve_local_specialization (t);
17168 if (!r)
17170 /* We're in a generic lambda referencing a local extern
17171 from an outer block-scope of a non-template. */
17172 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17173 r = t;
17176 else if (local_variable_p (t)
17177 && uses_template_parms (DECL_CONTEXT (t)))
17179 r = retrieve_local_specialization (t);
17180 if (r == NULL_TREE)
17182 /* First try name lookup to find the instantiation. */
17183 r = lookup_name (DECL_NAME (t));
17184 if (r)
17186 if (!VAR_P (r))
17188 /* During error-recovery we may find a non-variable,
17189 even an OVERLOAD: just bail out and avoid ICEs and
17190 duplicate diagnostics (c++/62207). */
17191 gcc_assert (seen_error ());
17192 return error_mark_node;
17194 if (!is_capture_proxy (r))
17196 /* Make sure the one we found is the one we want. */
17197 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17198 if (ctx != DECL_CONTEXT (r))
17199 r = NULL_TREE;
17203 if (r)
17204 /* OK */;
17205 else
17207 /* This can happen for a variable used in a
17208 late-specified return type of a local lambda, or for a
17209 local static or constant. Building a new VAR_DECL
17210 should be OK in all those cases. */
17211 r = tsubst_decl (t, args, complain);
17212 if (local_specializations)
17213 /* Avoid infinite recursion (79640). */
17214 register_local_specialization (r, t);
17215 if (decl_maybe_constant_var_p (r))
17217 /* We can't call cp_finish_decl, so handle the
17218 initializer by hand. */
17219 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17220 complain, in_decl);
17221 if (!processing_template_decl)
17222 init = maybe_constant_init (init);
17223 if (processing_template_decl
17224 ? potential_constant_expression (init)
17225 : reduced_constant_expression_p (init))
17226 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17227 = TREE_CONSTANT (r) = true;
17228 DECL_INITIAL (r) = init;
17229 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17230 TREE_TYPE (r)
17231 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17232 complain, adc_variable_type);
17234 gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
17235 || decl_constant_var_p (r)
17236 || seen_error ());
17237 if (!processing_template_decl
17238 && !TREE_STATIC (r))
17239 r = process_outer_var_ref (r, complain);
17241 /* Remember this for subsequent uses. */
17242 if (local_specializations)
17243 register_local_specialization (r, t);
17245 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17246 r = argument_pack_select_arg (r);
17248 else
17249 r = t;
17250 if (!mark_used (r, complain))
17251 return error_mark_node;
17252 return r;
17254 case NAMESPACE_DECL:
17255 return t;
17257 case OVERLOAD:
17258 return t;
17260 case BASELINK:
17261 return tsubst_baselink (t, current_nonlambda_class_type (),
17262 args, complain, in_decl);
17264 case TEMPLATE_DECL:
17265 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17266 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17267 args, complain, in_decl);
17268 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17269 return tsubst (t, args, complain, in_decl);
17270 else if (DECL_CLASS_SCOPE_P (t)
17271 && uses_template_parms (DECL_CONTEXT (t)))
17273 /* Template template argument like the following example need
17274 special treatment:
17276 template <template <class> class TT> struct C {};
17277 template <class T> struct D {
17278 template <class U> struct E {};
17279 C<E> c; // #1
17281 D<int> d; // #2
17283 We are processing the template argument `E' in #1 for
17284 the template instantiation #2. Originally, `E' is a
17285 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17286 have to substitute this with one having context `D<int>'. */
17288 tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
17289 return lookup_field (context, DECL_NAME(t), 0, false);
17291 else
17292 /* Ordinary template template argument. */
17293 return t;
17295 case NON_LVALUE_EXPR:
17296 case VIEW_CONVERT_EXPR:
17298 /* Handle location wrappers by substituting the wrapped node
17299 first, *then* reusing the resulting type. Doing the type
17300 first ensures that we handle template parameters and
17301 parameter pack expansions. */
17302 if (location_wrapper_p (t))
17304 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17305 complain, in_decl);
17306 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17308 tree op = TREE_OPERAND (t, 0);
17309 if (code == VIEW_CONVERT_EXPR
17310 && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
17312 /* Wrapper to make a C++20 template parameter object const. */
17313 op = tsubst_copy (op, args, complain, in_decl);
17314 if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
17316 /* The template argument is not const, presumably because
17317 it is still dependent, and so not the const template parm
17318 object. */
17319 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17320 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
17321 (type, TREE_TYPE (op)));
17322 if (TREE_CODE (op) == CONSTRUCTOR
17323 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
17325 /* Don't add a wrapper to these. */
17326 op = copy_node (op);
17327 TREE_TYPE (op) = type;
17329 else
17330 /* Do add a wrapper otherwise (in particular, if op is
17331 another TEMPLATE_PARM_INDEX). */
17332 op = build1 (code, type, op);
17334 return op;
17336 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17337 else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17339 op = tsubst_copy (op, args, complain, in_decl);
17340 op = build1 (code, TREE_TYPE (op), op);
17341 REF_PARENTHESIZED_P (op) = true;
17342 return op;
17344 /* We shouldn't see any other uses of these in templates. */
17345 gcc_unreachable ();
17348 case CAST_EXPR:
17349 case REINTERPRET_CAST_EXPR:
17350 case CONST_CAST_EXPR:
17351 case STATIC_CAST_EXPR:
17352 case DYNAMIC_CAST_EXPR:
17353 case IMPLICIT_CONV_EXPR:
17354 CASE_CONVERT:
17356 tsubst_flags_t tcomplain = complain;
17357 if (code == CAST_EXPR)
17358 tcomplain |= tf_tst_ok;
17359 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17360 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17361 return build1 (code, type, op0);
17364 case BIT_CAST_EXPR:
17366 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17367 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17368 r = build_min (BIT_CAST_EXPR, type, op0);
17369 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17370 return r;
17373 case SIZEOF_EXPR:
17374 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17375 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17377 tree expanded, op = TREE_OPERAND (t, 0);
17378 int len = 0;
17380 if (SIZEOF_EXPR_TYPE_P (t))
17381 op = TREE_TYPE (op);
17383 ++cp_unevaluated_operand;
17384 ++c_inhibit_evaluation_warnings;
17385 /* We only want to compute the number of arguments. */
17386 if (PACK_EXPANSION_P (op))
17387 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17388 else
17389 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17390 args, complain, in_decl);
17391 --cp_unevaluated_operand;
17392 --c_inhibit_evaluation_warnings;
17394 if (TREE_CODE (expanded) == TREE_VEC)
17396 len = TREE_VEC_LENGTH (expanded);
17397 /* Set TREE_USED for the benefit of -Wunused. */
17398 for (int i = 0; i < len; i++)
17399 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17400 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17403 if (expanded == error_mark_node)
17404 return error_mark_node;
17405 else if (PACK_EXPANSION_P (expanded)
17406 || (TREE_CODE (expanded) == TREE_VEC
17407 && pack_expansion_args_count (expanded)))
17410 if (PACK_EXPANSION_P (expanded))
17411 /* OK. */;
17412 else if (TREE_VEC_LENGTH (expanded) == 1)
17413 expanded = TREE_VEC_ELT (expanded, 0);
17414 else
17415 expanded = make_argument_pack (expanded);
17417 if (TYPE_P (expanded))
17418 return cxx_sizeof_or_alignof_type (input_location,
17419 expanded, SIZEOF_EXPR,
17420 false,
17421 complain & tf_error);
17422 else
17423 return cxx_sizeof_or_alignof_expr (input_location,
17424 expanded, SIZEOF_EXPR,
17425 false,
17426 complain & tf_error);
17428 else
17429 return build_int_cst (size_type_node, len);
17431 if (SIZEOF_EXPR_TYPE_P (t))
17433 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17434 args, complain, in_decl);
17435 r = build1 (NOP_EXPR, r, error_mark_node);
17436 r = build1 (SIZEOF_EXPR,
17437 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17438 SIZEOF_EXPR_TYPE_P (r) = 1;
17439 return r;
17441 /* Fall through */
17443 case INDIRECT_REF:
17444 case NEGATE_EXPR:
17445 case TRUTH_NOT_EXPR:
17446 case BIT_NOT_EXPR:
17447 case ADDR_EXPR:
17448 case UNARY_PLUS_EXPR: /* Unary + */
17449 case ALIGNOF_EXPR:
17450 case AT_ENCODE_EXPR:
17451 case ARROW_EXPR:
17452 case THROW_EXPR:
17453 case TYPEID_EXPR:
17454 case REALPART_EXPR:
17455 case IMAGPART_EXPR:
17456 case PAREN_EXPR:
17458 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17459 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17460 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17461 if (code == ALIGNOF_EXPR)
17462 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17463 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17464 set for possible later diagnostics. */
17465 if (code == ADDR_EXPR
17466 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17467 && TREE_CODE (op0) == FUNCTION_DECL
17468 && DECL_IMMEDIATE_FUNCTION_P (op0))
17469 SET_EXPR_LOCATION (r, input_location);
17470 return r;
17473 case COMPONENT_REF:
17475 tree object;
17476 tree name;
17478 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17479 name = TREE_OPERAND (t, 1);
17480 if (TREE_CODE (name) == BIT_NOT_EXPR)
17482 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17483 complain, in_decl);
17484 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17486 else if (TREE_CODE (name) == SCOPE_REF
17487 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17489 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17490 complain, in_decl);
17491 name = TREE_OPERAND (name, 1);
17492 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17493 complain, in_decl);
17494 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17495 name = build_qualified_name (/*type=*/NULL_TREE,
17496 base, name,
17497 /*template_p=*/false);
17499 else if (BASELINK_P (name))
17500 name = tsubst_baselink (name,
17501 non_reference (TREE_TYPE (object)),
17502 args, complain,
17503 in_decl);
17504 else
17505 name = tsubst_copy (name, args, complain, in_decl);
17506 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17509 case PLUS_EXPR:
17510 case MINUS_EXPR:
17511 case MULT_EXPR:
17512 case TRUNC_DIV_EXPR:
17513 case CEIL_DIV_EXPR:
17514 case FLOOR_DIV_EXPR:
17515 case ROUND_DIV_EXPR:
17516 case EXACT_DIV_EXPR:
17517 case BIT_AND_EXPR:
17518 case BIT_IOR_EXPR:
17519 case BIT_XOR_EXPR:
17520 case TRUNC_MOD_EXPR:
17521 case FLOOR_MOD_EXPR:
17522 case TRUTH_ANDIF_EXPR:
17523 case TRUTH_ORIF_EXPR:
17524 case TRUTH_AND_EXPR:
17525 case TRUTH_OR_EXPR:
17526 case RSHIFT_EXPR:
17527 case LSHIFT_EXPR:
17528 case EQ_EXPR:
17529 case NE_EXPR:
17530 case MAX_EXPR:
17531 case MIN_EXPR:
17532 case LE_EXPR:
17533 case GE_EXPR:
17534 case LT_EXPR:
17535 case GT_EXPR:
17536 case COMPOUND_EXPR:
17537 case DOTSTAR_EXPR:
17538 case MEMBER_REF:
17539 case PREDECREMENT_EXPR:
17540 case PREINCREMENT_EXPR:
17541 case POSTDECREMENT_EXPR:
17542 case POSTINCREMENT_EXPR:
17544 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17545 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17546 return build_nt (code, op0, op1);
17549 case SCOPE_REF:
17551 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17552 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17553 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17554 QUALIFIED_NAME_IS_TEMPLATE (t));
17557 case ARRAY_REF:
17559 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17560 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17561 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17564 case CALL_EXPR:
17566 int n = VL_EXP_OPERAND_LENGTH (t);
17567 tree result = build_vl_exp (CALL_EXPR, n);
17568 int i;
17569 for (i = 0; i < n; i++)
17570 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17571 complain, in_decl);
17572 return result;
17575 case COND_EXPR:
17576 case MODOP_EXPR:
17577 case PSEUDO_DTOR_EXPR:
17578 case VEC_PERM_EXPR:
17580 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17581 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17582 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17583 r = build_nt (code, op0, op1, op2);
17584 copy_warning (r, t);
17585 return r;
17588 case NEW_EXPR:
17590 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17591 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17592 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17593 r = build_nt (code, op0, op1, op2);
17594 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17595 return r;
17598 case DELETE_EXPR:
17600 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17601 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17602 r = build_nt (code, op0, op1);
17603 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17604 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17605 return r;
17608 case TEMPLATE_ID_EXPR:
17610 /* Substituted template arguments */
17611 tree tmpl = TREE_OPERAND (t, 0);
17612 tree targs = TREE_OPERAND (t, 1);
17614 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17615 if (targs)
17616 targs = tsubst_template_args (targs, args, complain, in_decl);
17618 if (variable_template_p (tmpl))
17619 return lookup_template_variable (tmpl, targs);
17620 else
17621 return lookup_template_function (tmpl, targs);
17624 case TREE_LIST:
17626 tree purpose, value, chain;
17628 if (t == void_list_node)
17629 return t;
17631 purpose = TREE_PURPOSE (t);
17632 if (purpose)
17633 purpose = tsubst_copy (purpose, args, complain, in_decl);
17634 value = TREE_VALUE (t);
17635 if (value)
17636 value = tsubst_copy (value, args, complain, in_decl);
17637 chain = TREE_CHAIN (t);
17638 if (chain && chain != void_type_node)
17639 chain = tsubst_copy (chain, args, complain, in_decl);
17640 if (purpose == TREE_PURPOSE (t)
17641 && value == TREE_VALUE (t)
17642 && chain == TREE_CHAIN (t))
17643 return t;
17644 return tree_cons (purpose, value, chain);
17647 case RECORD_TYPE:
17648 case UNION_TYPE:
17649 case ENUMERAL_TYPE:
17650 case INTEGER_TYPE:
17651 case TEMPLATE_TYPE_PARM:
17652 case TEMPLATE_TEMPLATE_PARM:
17653 case BOUND_TEMPLATE_TEMPLATE_PARM:
17654 case TEMPLATE_PARM_INDEX:
17655 case POINTER_TYPE:
17656 case REFERENCE_TYPE:
17657 case OFFSET_TYPE:
17658 case FUNCTION_TYPE:
17659 case METHOD_TYPE:
17660 case ARRAY_TYPE:
17661 case TYPENAME_TYPE:
17662 case UNBOUND_CLASS_TEMPLATE:
17663 case TYPEOF_TYPE:
17664 case DECLTYPE_TYPE:
17665 case TYPE_DECL:
17666 return tsubst (t, args, complain, in_decl);
17668 case USING_DECL:
17669 t = DECL_NAME (t);
17670 /* Fall through. */
17671 case IDENTIFIER_NODE:
17672 if (IDENTIFIER_CONV_OP_P (t))
17674 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17675 return make_conv_op_name (new_type);
17677 else
17678 return t;
17680 case CONSTRUCTOR:
17681 /* This is handled by tsubst_copy_and_build. */
17682 gcc_unreachable ();
17684 case VA_ARG_EXPR:
17686 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17687 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17688 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17691 case CLEANUP_POINT_EXPR:
17692 /* We shouldn't have built any of these during initial template
17693 generation. Instead, they should be built during instantiation
17694 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17695 gcc_unreachable ();
17697 case OFFSET_REF:
17699 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17700 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17701 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17702 r = build2 (code, type, op0, op1);
17703 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17704 if (!mark_used (TREE_OPERAND (r, 1), complain)
17705 && !(complain & tf_error))
17706 return error_mark_node;
17707 return r;
17710 case EXPR_PACK_EXPANSION:
17711 error ("invalid use of pack expansion expression");
17712 return error_mark_node;
17714 case NONTYPE_ARGUMENT_PACK:
17715 error ("use %<...%> to expand argument pack");
17716 return error_mark_node;
17718 case VOID_CST:
17719 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17720 return t;
17722 case INTEGER_CST:
17723 case REAL_CST:
17724 case COMPLEX_CST:
17725 case VECTOR_CST:
17727 /* Instantiate any typedefs in the type. */
17728 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17729 r = fold_convert (type, t);
17730 gcc_assert (TREE_CODE (r) == code);
17731 return r;
17734 case STRING_CST:
17736 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17737 r = t;
17738 if (type != TREE_TYPE (t))
17740 r = copy_node (t);
17741 TREE_TYPE (r) = type;
17743 return r;
17746 case PTRMEM_CST:
17747 /* These can sometimes show up in a partial instantiation, but never
17748 involve template parms. */
17749 gcc_assert (!uses_template_parms (t));
17750 return t;
17752 case UNARY_LEFT_FOLD_EXPR:
17753 return tsubst_unary_left_fold (t, args, complain, in_decl);
17754 case UNARY_RIGHT_FOLD_EXPR:
17755 return tsubst_unary_right_fold (t, args, complain, in_decl);
17756 case BINARY_LEFT_FOLD_EXPR:
17757 return tsubst_binary_left_fold (t, args, complain, in_decl);
17758 case BINARY_RIGHT_FOLD_EXPR:
17759 return tsubst_binary_right_fold (t, args, complain, in_decl);
17760 case PREDICT_EXPR:
17761 return t;
17763 case DEBUG_BEGIN_STMT:
17764 /* ??? There's no point in copying it for now, but maybe some
17765 day it will contain more information, such as a pointer back
17766 to the containing function, inlined copy or so. */
17767 return t;
17769 case CO_AWAIT_EXPR:
17770 return tsubst_expr (t, args, complain, in_decl,
17771 /*integral_constant_expression_p=*/false);
17772 break;
17774 default:
17775 /* We shouldn't get here, but keep going if !flag_checking. */
17776 if (flag_checking)
17777 gcc_unreachable ();
17778 return t;
17782 /* Helper function for tsubst_omp_clauses, used for instantiation of
17783 OMP_CLAUSE_DECL of clauses. */
17785 static tree
17786 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17787 tree in_decl, tree *iterator_cache)
17789 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17790 return decl;
17792 /* Handle OpenMP iterators. */
17793 if (TREE_CODE (decl) == TREE_LIST
17794 && TREE_PURPOSE (decl)
17795 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17797 tree ret;
17798 if (iterator_cache[0] == TREE_PURPOSE (decl))
17799 ret = iterator_cache[1];
17800 else
17802 tree *tp = &ret;
17803 begin_scope (sk_omp, NULL);
17804 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17806 *tp = copy_node (it);
17807 TREE_VEC_ELT (*tp, 0)
17808 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17809 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17810 pushdecl (TREE_VEC_ELT (*tp, 0));
17811 TREE_VEC_ELT (*tp, 1)
17812 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17813 /*integral_constant_expression_p=*/false);
17814 TREE_VEC_ELT (*tp, 2)
17815 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17816 /*integral_constant_expression_p=*/false);
17817 TREE_VEC_ELT (*tp, 3)
17818 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17819 /*integral_constant_expression_p=*/false);
17820 TREE_CHAIN (*tp) = NULL_TREE;
17821 tp = &TREE_CHAIN (*tp);
17823 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17824 iterator_cache[0] = TREE_PURPOSE (decl);
17825 iterator_cache[1] = ret;
17827 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17828 args, complain,
17829 in_decl, NULL));
17832 /* Handle an OpenMP array section represented as a TREE_LIST (or
17833 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17834 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17835 TREE_LIST. We can handle it exactly the same as an array section
17836 (purpose, value, and a chain), even though the nomenclature
17837 (low_bound, length, etc) is different. */
17838 if (TREE_CODE (decl) == TREE_LIST)
17840 tree low_bound
17841 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17842 /*integral_constant_expression_p=*/false);
17843 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17844 /*integral_constant_expression_p=*/false);
17845 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17846 in_decl, NULL);
17847 if (TREE_PURPOSE (decl) == low_bound
17848 && TREE_VALUE (decl) == length
17849 && TREE_CHAIN (decl) == chain)
17850 return decl;
17851 tree ret = tree_cons (low_bound, length, chain);
17852 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17853 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17854 return ret;
17856 tree ret = tsubst_expr (decl, args, complain, in_decl,
17857 /*integral_constant_expression_p=*/false);
17858 /* Undo convert_from_reference tsubst_expr could have called. */
17859 if (decl
17860 && REFERENCE_REF_P (ret)
17861 && !REFERENCE_REF_P (decl))
17862 ret = TREE_OPERAND (ret, 0);
17863 return ret;
17866 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17868 static tree
17869 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17870 tree args, tsubst_flags_t complain, tree in_decl)
17872 tree new_clauses = NULL_TREE, nc, oc;
17873 tree linear_no_step = NULL_TREE;
17874 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17876 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17878 nc = copy_node (oc);
17879 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17880 new_clauses = nc;
17882 switch (OMP_CLAUSE_CODE (nc))
17884 case OMP_CLAUSE_LASTPRIVATE:
17885 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17887 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17888 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17889 in_decl, /*integral_constant_expression_p=*/false);
17890 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17891 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17893 /* FALLTHRU */
17894 case OMP_CLAUSE_PRIVATE:
17895 case OMP_CLAUSE_SHARED:
17896 case OMP_CLAUSE_FIRSTPRIVATE:
17897 case OMP_CLAUSE_COPYIN:
17898 case OMP_CLAUSE_COPYPRIVATE:
17899 case OMP_CLAUSE_UNIFORM:
17900 case OMP_CLAUSE_DEPEND:
17901 case OMP_CLAUSE_DOACROSS:
17902 case OMP_CLAUSE_AFFINITY:
17903 case OMP_CLAUSE_FROM:
17904 case OMP_CLAUSE_TO:
17905 case OMP_CLAUSE_MAP:
17906 case OMP_CLAUSE__CACHE_:
17907 case OMP_CLAUSE_NONTEMPORAL:
17908 case OMP_CLAUSE_USE_DEVICE_PTR:
17909 case OMP_CLAUSE_USE_DEVICE_ADDR:
17910 case OMP_CLAUSE_IS_DEVICE_PTR:
17911 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17912 case OMP_CLAUSE_INCLUSIVE:
17913 case OMP_CLAUSE_EXCLUSIVE:
17914 OMP_CLAUSE_DECL (nc)
17915 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17916 in_decl, iterator_cache);
17917 break;
17918 case OMP_CLAUSE_NUM_TEAMS:
17919 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17920 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17921 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17922 complain, in_decl,
17923 /*integral_constant_expression_p=*/false);
17924 /* FALLTHRU */
17925 case OMP_CLAUSE_TILE:
17926 case OMP_CLAUSE_IF:
17927 case OMP_CLAUSE_NUM_THREADS:
17928 case OMP_CLAUSE_SCHEDULE:
17929 case OMP_CLAUSE_COLLAPSE:
17930 case OMP_CLAUSE_FINAL:
17931 case OMP_CLAUSE_DEVICE:
17932 case OMP_CLAUSE_DIST_SCHEDULE:
17933 case OMP_CLAUSE_THREAD_LIMIT:
17934 case OMP_CLAUSE_SAFELEN:
17935 case OMP_CLAUSE_SIMDLEN:
17936 case OMP_CLAUSE_NUM_TASKS:
17937 case OMP_CLAUSE_GRAINSIZE:
17938 case OMP_CLAUSE_PRIORITY:
17939 case OMP_CLAUSE_ORDERED:
17940 case OMP_CLAUSE_HINT:
17941 case OMP_CLAUSE_FILTER:
17942 case OMP_CLAUSE_NUM_GANGS:
17943 case OMP_CLAUSE_NUM_WORKERS:
17944 case OMP_CLAUSE_VECTOR_LENGTH:
17945 case OMP_CLAUSE_WORKER:
17946 case OMP_CLAUSE_VECTOR:
17947 case OMP_CLAUSE_ASYNC:
17948 case OMP_CLAUSE_WAIT:
17949 case OMP_CLAUSE_DETACH:
17950 OMP_CLAUSE_OPERAND (nc, 0)
17951 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17952 in_decl, /*integral_constant_expression_p=*/false);
17953 break;
17954 case OMP_CLAUSE_REDUCTION:
17955 case OMP_CLAUSE_IN_REDUCTION:
17956 case OMP_CLAUSE_TASK_REDUCTION:
17957 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17959 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17960 if (TREE_CODE (placeholder) == SCOPE_REF)
17962 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17963 complain, in_decl);
17964 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17965 = build_qualified_name (NULL_TREE, scope,
17966 TREE_OPERAND (placeholder, 1),
17967 false);
17969 else
17970 gcc_assert (identifier_p (placeholder));
17972 OMP_CLAUSE_DECL (nc)
17973 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17974 in_decl, NULL);
17975 break;
17976 case OMP_CLAUSE_GANG:
17977 case OMP_CLAUSE_ALIGNED:
17978 OMP_CLAUSE_DECL (nc)
17979 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17980 in_decl, NULL);
17981 OMP_CLAUSE_OPERAND (nc, 1)
17982 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17983 in_decl, /*integral_constant_expression_p=*/false);
17984 break;
17985 case OMP_CLAUSE_ALLOCATE:
17986 OMP_CLAUSE_DECL (nc)
17987 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17988 in_decl, NULL);
17989 OMP_CLAUSE_OPERAND (nc, 1)
17990 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17991 in_decl, /*integral_constant_expression_p=*/false);
17992 OMP_CLAUSE_OPERAND (nc, 2)
17993 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain,
17994 in_decl, /*integral_constant_expression_p=*/false);
17995 break;
17996 case OMP_CLAUSE_LINEAR:
17997 OMP_CLAUSE_DECL (nc)
17998 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17999 in_decl, NULL);
18000 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
18002 gcc_assert (!linear_no_step);
18003 linear_no_step = nc;
18005 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
18006 OMP_CLAUSE_LINEAR_STEP (nc)
18007 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
18008 complain, in_decl, NULL);
18009 else
18010 OMP_CLAUSE_LINEAR_STEP (nc)
18011 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
18012 in_decl,
18013 /*integral_constant_expression_p=*/false);
18014 break;
18015 case OMP_CLAUSE_NOWAIT:
18016 case OMP_CLAUSE_DEFAULT:
18017 case OMP_CLAUSE_UNTIED:
18018 case OMP_CLAUSE_MERGEABLE:
18019 case OMP_CLAUSE_INBRANCH:
18020 case OMP_CLAUSE_NOTINBRANCH:
18021 case OMP_CLAUSE_PROC_BIND:
18022 case OMP_CLAUSE_FOR:
18023 case OMP_CLAUSE_PARALLEL:
18024 case OMP_CLAUSE_SECTIONS:
18025 case OMP_CLAUSE_TASKGROUP:
18026 case OMP_CLAUSE_NOGROUP:
18027 case OMP_CLAUSE_THREADS:
18028 case OMP_CLAUSE_SIMD:
18029 case OMP_CLAUSE_DEFAULTMAP:
18030 case OMP_CLAUSE_ORDER:
18031 case OMP_CLAUSE_BIND:
18032 case OMP_CLAUSE_INDEPENDENT:
18033 case OMP_CLAUSE_AUTO:
18034 case OMP_CLAUSE_SEQ:
18035 case OMP_CLAUSE_IF_PRESENT:
18036 case OMP_CLAUSE_FINALIZE:
18037 case OMP_CLAUSE_NOHOST:
18038 break;
18039 default:
18040 gcc_unreachable ();
18042 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18043 switch (OMP_CLAUSE_CODE (nc))
18045 case OMP_CLAUSE_SHARED:
18046 case OMP_CLAUSE_PRIVATE:
18047 case OMP_CLAUSE_FIRSTPRIVATE:
18048 case OMP_CLAUSE_LASTPRIVATE:
18049 case OMP_CLAUSE_COPYPRIVATE:
18050 case OMP_CLAUSE_LINEAR:
18051 case OMP_CLAUSE_REDUCTION:
18052 case OMP_CLAUSE_IN_REDUCTION:
18053 case OMP_CLAUSE_TASK_REDUCTION:
18054 case OMP_CLAUSE_USE_DEVICE_PTR:
18055 case OMP_CLAUSE_USE_DEVICE_ADDR:
18056 case OMP_CLAUSE_IS_DEVICE_PTR:
18057 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18058 case OMP_CLAUSE_INCLUSIVE:
18059 case OMP_CLAUSE_EXCLUSIVE:
18060 case OMP_CLAUSE_ALLOCATE:
18061 /* tsubst_expr on SCOPE_REF results in returning
18062 finish_non_static_data_member result. Undo that here. */
18063 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18064 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18065 == IDENTIFIER_NODE))
18067 tree t = OMP_CLAUSE_DECL (nc);
18068 tree v = t;
18069 while (v)
18070 switch (TREE_CODE (v))
18072 case COMPONENT_REF:
18073 case MEM_REF:
18074 case INDIRECT_REF:
18075 CASE_CONVERT:
18076 case POINTER_PLUS_EXPR:
18077 v = TREE_OPERAND (v, 0);
18078 continue;
18079 case PARM_DECL:
18080 if (DECL_CONTEXT (v) == current_function_decl
18081 && DECL_ARTIFICIAL (v)
18082 && DECL_NAME (v) == this_identifier)
18083 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18084 /* FALLTHRU */
18085 default:
18086 v = NULL_TREE;
18087 break;
18090 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18091 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18092 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18093 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18094 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18096 tree decl = OMP_CLAUSE_DECL (nc);
18097 if (VAR_P (decl))
18099 retrofit_lang_decl (decl);
18100 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18103 break;
18104 default:
18105 break;
18109 new_clauses = nreverse (new_clauses);
18110 if (ort != C_ORT_OMP_DECLARE_SIMD)
18112 new_clauses = finish_omp_clauses (new_clauses, ort);
18113 if (linear_no_step)
18114 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18115 if (nc == linear_no_step)
18117 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18118 break;
18121 return new_clauses;
18124 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18126 static tree
18127 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18128 tree in_decl)
18130 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18132 tree purpose, value, chain;
18134 if (t == NULL)
18135 return t;
18137 if (TREE_CODE (t) != TREE_LIST)
18138 return tsubst_copy_and_build (t, args, complain, in_decl,
18139 /*function_p=*/false,
18140 /*integral_constant_expression_p=*/false);
18142 if (t == void_list_node)
18143 return t;
18145 purpose = TREE_PURPOSE (t);
18146 if (purpose)
18147 purpose = RECUR (purpose);
18148 value = TREE_VALUE (t);
18149 if (value)
18151 if (TREE_CODE (value) != LABEL_DECL)
18152 value = RECUR (value);
18153 else
18155 value = lookup_label (DECL_NAME (value));
18156 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18157 TREE_USED (value) = 1;
18160 chain = TREE_CHAIN (t);
18161 if (chain && chain != void_type_node)
18162 chain = RECUR (chain);
18163 return tree_cons (purpose, value, chain);
18164 #undef RECUR
18167 /* Used to temporarily communicate the list of #pragma omp parallel
18168 clauses to #pragma omp for instantiation if they are combined
18169 together. */
18171 static tree *omp_parallel_combined_clauses;
18173 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18174 tree *, unsigned int *);
18176 /* Substitute one OMP_FOR iterator. */
18178 static bool
18179 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18180 tree initv, tree condv, tree incrv, tree *clauses,
18181 tree args, tsubst_flags_t complain, tree in_decl,
18182 bool integral_constant_expression_p)
18184 #define RECUR(NODE) \
18185 tsubst_expr ((NODE), args, complain, in_decl, \
18186 integral_constant_expression_p)
18187 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18188 bool ret = false;
18190 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18191 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18193 decl = TREE_OPERAND (init, 0);
18194 init = TREE_OPERAND (init, 1);
18195 tree decl_expr = NULL_TREE;
18196 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18197 if (range_for)
18199 bool decomp = false;
18200 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18202 tree v = DECL_VALUE_EXPR (decl);
18203 if (TREE_CODE (v) == ARRAY_REF
18204 && VAR_P (TREE_OPERAND (v, 0))
18205 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18207 tree decomp_first = NULL_TREE;
18208 unsigned decomp_cnt = 0;
18209 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18210 maybe_push_decl (d);
18211 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18212 in_decl, &decomp_first, &decomp_cnt);
18213 decomp = true;
18214 if (d == error_mark_node)
18215 decl = error_mark_node;
18216 else
18217 for (unsigned int i = 0; i < decomp_cnt; i++)
18219 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18221 tree v = build_nt (ARRAY_REF, d,
18222 size_int (decomp_cnt - i - 1),
18223 NULL_TREE, NULL_TREE);
18224 SET_DECL_VALUE_EXPR (decomp_first, v);
18225 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18227 fit_decomposition_lang_decl (decomp_first, d);
18228 decomp_first = DECL_CHAIN (decomp_first);
18232 decl = tsubst_decl (decl, args, complain);
18233 if (!decomp)
18234 maybe_push_decl (decl);
18236 else if (init && TREE_CODE (init) == DECL_EXPR)
18238 /* We need to jump through some hoops to handle declarations in the
18239 init-statement, since we might need to handle auto deduction,
18240 but we need to keep control of initialization. */
18241 decl_expr = init;
18242 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18243 decl = tsubst_decl (decl, args, complain);
18245 else
18247 if (TREE_CODE (decl) == SCOPE_REF)
18249 decl = RECUR (decl);
18250 if (TREE_CODE (decl) == COMPONENT_REF)
18252 tree v = decl;
18253 while (v)
18254 switch (TREE_CODE (v))
18256 case COMPONENT_REF:
18257 case MEM_REF:
18258 case INDIRECT_REF:
18259 CASE_CONVERT:
18260 case POINTER_PLUS_EXPR:
18261 v = TREE_OPERAND (v, 0);
18262 continue;
18263 case PARM_DECL:
18264 if (DECL_CONTEXT (v) == current_function_decl
18265 && DECL_ARTIFICIAL (v)
18266 && DECL_NAME (v) == this_identifier)
18268 decl = TREE_OPERAND (decl, 1);
18269 decl = omp_privatize_field (decl, false);
18271 /* FALLTHRU */
18272 default:
18273 v = NULL_TREE;
18274 break;
18278 else
18279 decl = RECUR (decl);
18281 if (init && TREE_CODE (init) == TREE_VEC)
18283 init = copy_node (init);
18284 TREE_VEC_ELT (init, 0)
18285 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18286 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18287 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18289 else
18290 init = RECUR (init);
18292 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18294 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18295 if (TREE_CODE (o) == TREE_LIST)
18296 TREE_VEC_ELT (orig_declv, i)
18297 = tree_cons (RECUR (TREE_PURPOSE (o)),
18298 RECUR (TREE_VALUE (o)),
18299 NULL_TREE);
18300 else
18301 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18304 if (range_for)
18306 tree this_pre_body = NULL_TREE;
18307 tree orig_init = NULL_TREE;
18308 tree orig_decl = NULL_TREE;
18309 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18310 orig_init, cond, incr);
18311 if (orig_decl)
18313 if (orig_declv == NULL_TREE)
18314 orig_declv = copy_node (declv);
18315 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18316 ret = true;
18318 else if (orig_declv)
18319 TREE_VEC_ELT (orig_declv, i) = decl;
18322 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18323 if (!range_for && auto_node && init)
18324 TREE_TYPE (decl)
18325 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18327 gcc_assert (!type_dependent_expression_p (decl));
18329 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18331 if (decl_expr)
18333 /* Declare the variable, but don't let that initialize it. */
18334 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18335 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18336 RECUR (decl_expr);
18337 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18340 if (!range_for)
18342 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18343 if (COMPARISON_CLASS_P (cond)
18344 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18346 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18347 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18348 TREE_VEC_ELT (rhs, 0)
18349 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18350 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18351 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18352 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18353 lhs, rhs);
18355 else
18356 cond = RECUR (cond);
18357 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18358 if (TREE_CODE (incr) == MODIFY_EXPR)
18360 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18361 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18362 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18363 NOP_EXPR, rhs, NULL_TREE, complain);
18365 else
18366 incr = RECUR (incr);
18367 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18368 TREE_VEC_ELT (orig_declv, i) = decl;
18370 TREE_VEC_ELT (declv, i) = decl;
18371 TREE_VEC_ELT (initv, i) = init;
18372 TREE_VEC_ELT (condv, i) = cond;
18373 TREE_VEC_ELT (incrv, i) = incr;
18374 return ret;
18377 if (decl_expr)
18379 /* Declare and initialize the variable. */
18380 RECUR (decl_expr);
18381 init = NULL_TREE;
18383 else if (init)
18385 tree *pc;
18386 int j;
18387 for (j = ((omp_parallel_combined_clauses == NULL
18388 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18390 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18392 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18393 && OMP_CLAUSE_DECL (*pc) == decl)
18394 break;
18395 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18396 && OMP_CLAUSE_DECL (*pc) == decl)
18398 if (j)
18399 break;
18400 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18401 tree c = *pc;
18402 *pc = OMP_CLAUSE_CHAIN (c);
18403 OMP_CLAUSE_CHAIN (c) = *clauses;
18404 *clauses = c;
18406 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18407 && OMP_CLAUSE_DECL (*pc) == decl)
18409 error ("iteration variable %qD should not be firstprivate",
18410 decl);
18411 *pc = OMP_CLAUSE_CHAIN (*pc);
18413 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18414 && OMP_CLAUSE_DECL (*pc) == decl)
18416 error ("iteration variable %qD should not be reduction",
18417 decl);
18418 *pc = OMP_CLAUSE_CHAIN (*pc);
18420 else
18421 pc = &OMP_CLAUSE_CHAIN (*pc);
18423 if (*pc)
18424 break;
18426 if (*pc == NULL_TREE)
18428 tree c = build_omp_clause (input_location,
18429 TREE_CODE (t) == OMP_LOOP
18430 ? OMP_CLAUSE_LASTPRIVATE
18431 : OMP_CLAUSE_PRIVATE);
18432 OMP_CLAUSE_DECL (c) = decl;
18433 c = finish_omp_clauses (c, C_ORT_OMP);
18434 if (c)
18436 OMP_CLAUSE_CHAIN (c) = *clauses;
18437 *clauses = c;
18441 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18442 if (COMPARISON_CLASS_P (cond))
18444 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18445 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18446 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18448 else
18449 cond = RECUR (cond);
18450 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18451 switch (TREE_CODE (incr))
18453 case PREINCREMENT_EXPR:
18454 case PREDECREMENT_EXPR:
18455 case POSTINCREMENT_EXPR:
18456 case POSTDECREMENT_EXPR:
18457 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18458 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18459 break;
18460 case MODIFY_EXPR:
18461 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18462 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18464 tree rhs = TREE_OPERAND (incr, 1);
18465 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18466 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18467 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18468 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18469 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18470 rhs0, rhs1));
18472 else
18473 incr = RECUR (incr);
18474 break;
18475 case MODOP_EXPR:
18476 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18477 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18479 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18480 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18481 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18482 TREE_TYPE (decl), lhs,
18483 RECUR (TREE_OPERAND (incr, 2))));
18485 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18486 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18487 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18489 tree rhs = TREE_OPERAND (incr, 2);
18490 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18491 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18492 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18493 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18494 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18495 rhs0, rhs1));
18497 else
18498 incr = RECUR (incr);
18499 break;
18500 default:
18501 incr = RECUR (incr);
18502 break;
18505 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18506 TREE_VEC_ELT (orig_declv, i) = decl;
18507 TREE_VEC_ELT (declv, i) = decl;
18508 TREE_VEC_ELT (initv, i) = init;
18509 TREE_VEC_ELT (condv, i) = cond;
18510 TREE_VEC_ELT (incrv, i) = incr;
18511 return false;
18512 #undef RECUR
18515 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18516 of OMP_TARGET's body. */
18518 static tree
18519 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18521 *walk_subtrees = 0;
18522 switch (TREE_CODE (*tp))
18524 case OMP_TEAMS:
18525 return *tp;
18526 case BIND_EXPR:
18527 case STATEMENT_LIST:
18528 *walk_subtrees = 1;
18529 break;
18530 default:
18531 break;
18533 return NULL_TREE;
18536 /* Helper function for tsubst_expr. For decomposition declaration
18537 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18538 also the corresponding decls representing the identifiers
18539 of the decomposition declaration. Return DECL if successful
18540 or error_mark_node otherwise, set *FIRST to the first decl
18541 in the list chained through DECL_CHAIN and *CNT to the number
18542 of such decls. */
18544 static tree
18545 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18546 tsubst_flags_t complain, tree in_decl, tree *first,
18547 unsigned int *cnt)
18549 tree decl2, decl3, prev = decl;
18550 *cnt = 0;
18551 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18552 for (decl2 = DECL_CHAIN (pattern_decl);
18553 decl2
18554 && VAR_P (decl2)
18555 && DECL_DECOMPOSITION_P (decl2)
18556 && DECL_NAME (decl2);
18557 decl2 = DECL_CHAIN (decl2))
18559 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18561 gcc_assert (errorcount);
18562 return error_mark_node;
18564 (*cnt)++;
18565 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18566 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18567 tree v = DECL_VALUE_EXPR (decl2);
18568 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18569 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18570 decl3 = tsubst (decl2, args, complain, in_decl);
18571 SET_DECL_VALUE_EXPR (decl2, v);
18572 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18573 if (VAR_P (decl3))
18574 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18575 else
18577 gcc_assert (errorcount);
18578 decl = error_mark_node;
18579 continue;
18581 maybe_push_decl (decl3);
18582 if (error_operand_p (decl3))
18583 decl = error_mark_node;
18584 else if (decl != error_mark_node
18585 && DECL_CHAIN (decl3) != prev
18586 && decl != prev)
18588 gcc_assert (errorcount);
18589 decl = error_mark_node;
18591 else
18592 prev = decl3;
18594 *first = prev;
18595 return decl;
18598 /* Return the proper local_specialization for init-capture pack DECL. */
18600 static tree
18601 lookup_init_capture_pack (tree decl)
18603 /* We handle normal pack captures by forwarding to the specialization of the
18604 captured parameter. We can't do that for pack init-captures; we need them
18605 to have their own local_specialization. We created the individual
18606 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18607 when we process the DECL_EXPR for the pack init-capture in the template.
18608 So, how do we find them? We don't know the capture proxy pack when
18609 building the individual resulting proxies, and we don't know the
18610 individual proxies when instantiating the pack. What we have in common is
18611 the FIELD_DECL.
18613 So...when we instantiate the FIELD_DECL, we stick the result in
18614 local_specializations. Then at the DECL_EXPR we look up that result, see
18615 how many elements it has, synthesize the names, and look them up. */
18617 tree cname = DECL_NAME (decl);
18618 tree val = DECL_VALUE_EXPR (decl);
18619 tree field = TREE_OPERAND (val, 1);
18620 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18621 tree fpack = retrieve_local_specialization (field);
18622 if (fpack == error_mark_node)
18623 return error_mark_node;
18625 int len = 1;
18626 tree vec = NULL_TREE;
18627 tree r = NULL_TREE;
18628 if (TREE_CODE (fpack) == TREE_VEC)
18630 len = TREE_VEC_LENGTH (fpack);
18631 vec = make_tree_vec (len);
18632 r = make_node (NONTYPE_ARGUMENT_PACK);
18633 ARGUMENT_PACK_ARGS (r) = vec;
18635 for (int i = 0; i < len; ++i)
18637 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18638 tree elt = lookup_name (ename);
18639 if (vec)
18640 TREE_VEC_ELT (vec, i) = elt;
18641 else
18642 r = elt;
18644 return r;
18647 /* T is an operand of a template tree being substituted. Return whether
18648 T is dependent such that we should suppress some warnings that would
18649 make sense if the substituted expression were written directly, like
18650 template <int I> bool f() { return I == 2; }
18651 We don't want to warn when instantiating f that comparing two constants
18652 always has the same value.
18654 This is a more limited concept of dependence than instantiation-dependent;
18655 here we don't care whether substitution could fail. */
18657 static bool
18658 dependent_operand_p (tree t)
18660 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18661 t = TREE_OPERAND (t, 0);
18662 ++processing_template_decl;
18663 bool r = (potential_constant_expression (t)
18664 ? value_dependent_expression_p (t)
18665 : type_dependent_expression_p (t));
18666 --processing_template_decl;
18667 return r;
18670 /* Like tsubst_copy for expressions, etc. but also does semantic
18671 processing. */
18673 tree
18674 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
18675 bool integral_constant_expression_p)
18677 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18678 #define RECUR(NODE) \
18679 tsubst_expr ((NODE), args, complain, in_decl, \
18680 integral_constant_expression_p)
18682 tree stmt, tmp;
18683 tree r;
18684 location_t loc;
18686 if (t == NULL_TREE || t == error_mark_node)
18687 return t;
18689 loc = input_location;
18690 if (location_t eloc = cp_expr_location (t))
18691 input_location = eloc;
18692 if (STATEMENT_CODE_P (TREE_CODE (t)))
18693 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18695 switch (TREE_CODE (t))
18697 case STATEMENT_LIST:
18699 for (tree stmt : tsi_range (t))
18700 RECUR (stmt);
18701 break;
18704 case CTOR_INITIALIZER:
18705 finish_mem_initializers (tsubst_initializer_list
18706 (TREE_OPERAND (t, 0), args));
18707 break;
18709 case RETURN_EXPR:
18710 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18711 break;
18713 case CO_RETURN_EXPR:
18714 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18715 break;
18717 case CO_YIELD_EXPR:
18718 stmt = finish_co_yield_expr (input_location,
18719 RECUR (TREE_OPERAND (t, 0)));
18720 RETURN (stmt);
18722 case CO_AWAIT_EXPR:
18723 stmt = finish_co_await_expr (input_location,
18724 RECUR (TREE_OPERAND (t, 0)));
18725 RETURN (stmt);
18727 case EXPR_STMT:
18728 tmp = RECUR (EXPR_STMT_EXPR (t));
18729 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18730 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18731 else
18732 finish_expr_stmt (tmp);
18733 break;
18735 case USING_STMT:
18736 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18737 break;
18739 case DECL_EXPR:
18741 tree decl, pattern_decl;
18742 tree init;
18744 pattern_decl = decl = DECL_EXPR_DECL (t);
18745 if (TREE_CODE (decl) == LABEL_DECL)
18746 finish_label_decl (DECL_NAME (decl));
18747 else if (TREE_CODE (decl) == USING_DECL)
18749 tree scope = USING_DECL_SCOPE (decl);
18750 if (DECL_DEPENDENT_P (decl))
18752 scope = tsubst (scope, args, complain, in_decl);
18753 if (!MAYBE_CLASS_TYPE_P (scope)
18754 && TREE_CODE (scope) != ENUMERAL_TYPE)
18756 if (complain & tf_error)
18757 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18758 "class, namespace, or enumeration", scope);
18759 return error_mark_node;
18761 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18763 else
18765 /* This is a non-dependent using-decl, and we'll have
18766 used the names it found during template parsing. We do
18767 not want to do the lookup again, because we might not
18768 find the things we found then. */
18769 gcc_checking_assert (scope == tsubst (scope, args,
18770 complain, in_decl));
18771 /* We still need to push the bindings so that we can look up
18772 this name later. */
18773 push_using_decl_bindings (DECL_NAME (decl),
18774 USING_DECL_DECLS (decl));
18777 else if (is_capture_proxy (decl)
18778 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18780 /* We're in tsubst_lambda_expr, we've already inserted a new
18781 capture proxy, so look it up and register it. */
18782 tree inst;
18783 if (!DECL_PACK_P (decl))
18785 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18786 LOOK_want::HIDDEN_LAMBDA);
18787 gcc_assert (inst != decl && is_capture_proxy (inst));
18789 else if (is_normal_capture_proxy (decl))
18791 inst = (retrieve_local_specialization
18792 (DECL_CAPTURED_VARIABLE (decl)));
18793 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18794 || DECL_PACK_P (inst));
18796 else
18797 inst = lookup_init_capture_pack (decl);
18799 register_local_specialization (inst, decl);
18800 break;
18802 else if (DECL_PRETTY_FUNCTION_P (decl))
18803 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18804 DECL_NAME (decl),
18805 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18806 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18807 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18808 /* Don't copy the old closure; we'll create a new one in
18809 tsubst_lambda_expr. */
18810 break;
18811 else
18813 init = DECL_INITIAL (decl);
18814 decl = tsubst (decl, args, complain, in_decl);
18815 if (decl != error_mark_node)
18817 /* By marking the declaration as instantiated, we avoid
18818 trying to instantiate it. Since instantiate_decl can't
18819 handle local variables, and since we've already done
18820 all that needs to be done, that's the right thing to
18821 do. */
18822 if (VAR_P (decl))
18823 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18824 if (VAR_P (decl) && !DECL_NAME (decl)
18825 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18826 /* Anonymous aggregates are a special case. */
18827 finish_anon_union (decl);
18828 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18830 DECL_CONTEXT (decl) = current_function_decl;
18831 if (DECL_NAME (decl) == this_identifier)
18833 tree lam = DECL_CONTEXT (current_function_decl);
18834 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18835 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18837 insert_capture_proxy (decl);
18839 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18840 /* We already did a pushtag. */;
18841 else if (VAR_OR_FUNCTION_DECL_P (decl)
18842 && DECL_LOCAL_DECL_P (decl))
18844 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18845 DECL_CONTEXT (decl) = NULL_TREE;
18846 decl = pushdecl (decl);
18847 if (TREE_CODE (decl) == FUNCTION_DECL
18848 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18849 && cp_check_omp_declare_reduction (decl))
18850 instantiate_body (pattern_decl, args, decl, true);
18852 else
18854 bool const_init = false;
18855 unsigned int cnt = 0;
18856 tree first = NULL_TREE, ndecl = error_mark_node;
18857 tree asmspec_tree = NULL_TREE;
18858 maybe_push_decl (decl);
18860 if (VAR_P (decl)
18861 && DECL_DECOMPOSITION_P (decl)
18862 && TREE_TYPE (pattern_decl) != error_mark_node)
18863 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18864 complain, in_decl, &first,
18865 &cnt);
18867 init = tsubst_init (init, decl, args, complain, in_decl);
18869 if (VAR_P (decl))
18870 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18871 (pattern_decl));
18873 if (ndecl != error_mark_node)
18874 cp_maybe_mangle_decomp (ndecl, first, cnt);
18876 /* In a non-template function, VLA type declarations are
18877 handled in grokdeclarator; for templates, handle them
18878 now. */
18879 predeclare_vla (decl);
18881 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18883 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18884 const char *asmspec = IDENTIFIER_POINTER (id);
18885 gcc_assert (asmspec[0] == '*');
18886 asmspec_tree
18887 = build_string (IDENTIFIER_LENGTH (id) - 1,
18888 asmspec + 1);
18889 TREE_TYPE (asmspec_tree) = char_array_type_node;
18892 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18894 if (ndecl != error_mark_node)
18895 cp_finish_decomp (ndecl, first, cnt);
18900 break;
18903 case FOR_STMT:
18904 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18905 RECUR (FOR_INIT_STMT (t));
18906 finish_init_stmt (stmt);
18907 tmp = RECUR (FOR_COND (t));
18908 finish_for_cond (tmp, stmt, false, 0);
18909 tmp = RECUR (FOR_EXPR (t));
18910 finish_for_expr (tmp, stmt);
18912 bool prev = note_iteration_stmt_body_start ();
18913 RECUR (FOR_BODY (t));
18914 note_iteration_stmt_body_end (prev);
18916 finish_for_stmt (stmt);
18917 break;
18919 case RANGE_FOR_STMT:
18921 /* Construct another range_for, if this is not a final
18922 substitution (for inside a generic lambda of a
18923 template). Otherwise convert to a regular for. */
18924 tree decl, expr;
18925 stmt = (processing_template_decl
18926 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18927 : begin_for_stmt (NULL_TREE, NULL_TREE));
18928 RECUR (RANGE_FOR_INIT_STMT (t));
18929 decl = RANGE_FOR_DECL (t);
18930 decl = tsubst (decl, args, complain, in_decl);
18931 maybe_push_decl (decl);
18932 expr = RECUR (RANGE_FOR_EXPR (t));
18934 tree decomp_first = NULL_TREE;
18935 unsigned decomp_cnt = 0;
18936 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18937 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18938 complain, in_decl,
18939 &decomp_first, &decomp_cnt);
18941 if (processing_template_decl)
18943 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18944 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18945 finish_range_for_decl (stmt, decl, expr);
18946 if (decomp_first && decl != error_mark_node)
18947 cp_finish_decomp (decl, decomp_first, decomp_cnt);
18949 else
18951 unsigned short unroll = (RANGE_FOR_UNROLL (t)
18952 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18953 stmt = cp_convert_range_for (stmt, decl, expr,
18954 decomp_first, decomp_cnt,
18955 RANGE_FOR_IVDEP (t), unroll);
18958 bool prev = note_iteration_stmt_body_start ();
18959 RECUR (RANGE_FOR_BODY (t));
18960 note_iteration_stmt_body_end (prev);
18961 finish_for_stmt (stmt);
18963 break;
18965 case WHILE_STMT:
18966 stmt = begin_while_stmt ();
18967 tmp = RECUR (WHILE_COND (t));
18968 finish_while_stmt_cond (tmp, stmt, false, 0);
18970 bool prev = note_iteration_stmt_body_start ();
18971 RECUR (WHILE_BODY (t));
18972 note_iteration_stmt_body_end (prev);
18974 finish_while_stmt (stmt);
18975 break;
18977 case DO_STMT:
18978 stmt = begin_do_stmt ();
18980 bool prev = note_iteration_stmt_body_start ();
18981 RECUR (DO_BODY (t));
18982 note_iteration_stmt_body_end (prev);
18984 finish_do_body (stmt);
18985 tmp = RECUR (DO_COND (t));
18986 finish_do_stmt (tmp, stmt, false, 0);
18987 break;
18989 case IF_STMT:
18990 stmt = begin_if_stmt ();
18991 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18992 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18993 if (IF_STMT_CONSTEXPR_P (t))
18994 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18996 tree cond = IF_COND (t);
18997 bool was_dep = dependent_operand_p (cond);
18998 cond = RECUR (cond);
18999 warning_sentinel s1(warn_address, was_dep);
19000 tmp = finish_if_stmt_cond (cond, stmt);
19002 if (IF_STMT_CONSTEXPR_P (t)
19003 && instantiation_dependent_expression_p (tmp))
19005 /* We're partially instantiating a generic lambda, but the condition
19006 of the constexpr if is still dependent. Don't substitute into the
19007 branches now, just remember the template arguments. */
19008 do_poplevel (IF_SCOPE (stmt));
19009 IF_COND (stmt) = IF_COND (t);
19010 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
19011 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
19012 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
19013 add_stmt (stmt);
19014 break;
19016 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
19017 /* Don't instantiate the THEN_CLAUSE. */;
19018 else if (IF_STMT_CONSTEVAL_P (t))
19020 bool save_in_consteval_if_p = in_consteval_if_p;
19021 in_consteval_if_p = true;
19022 RECUR (THEN_CLAUSE (t));
19023 in_consteval_if_p = save_in_consteval_if_p;
19025 else
19027 tree folded = fold_non_dependent_expr (tmp, complain);
19028 bool inhibit = integer_zerop (folded);
19029 if (inhibit)
19030 ++c_inhibit_evaluation_warnings;
19031 RECUR (THEN_CLAUSE (t));
19032 if (inhibit)
19033 --c_inhibit_evaluation_warnings;
19035 finish_then_clause (stmt);
19037 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19038 /* Don't instantiate the ELSE_CLAUSE. */;
19039 else if (ELSE_CLAUSE (t))
19041 tree folded = fold_non_dependent_expr (tmp, complain);
19042 bool inhibit = integer_nonzerop (folded);
19043 begin_else_clause (stmt);
19044 if (inhibit)
19045 ++c_inhibit_evaluation_warnings;
19046 RECUR (ELSE_CLAUSE (t));
19047 if (inhibit)
19048 --c_inhibit_evaluation_warnings;
19049 finish_else_clause (stmt);
19052 finish_if_stmt (stmt);
19053 break;
19055 case BIND_EXPR:
19056 if (BIND_EXPR_BODY_BLOCK (t))
19057 stmt = begin_function_body ();
19058 else
19059 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19060 ? BCS_TRY_BLOCK : 0);
19062 RECUR (BIND_EXPR_BODY (t));
19064 if (BIND_EXPR_BODY_BLOCK (t))
19065 finish_function_body (stmt);
19066 else
19067 finish_compound_stmt (stmt);
19068 break;
19070 case BREAK_STMT:
19071 finish_break_stmt ();
19072 break;
19074 case CONTINUE_STMT:
19075 finish_continue_stmt ();
19076 break;
19078 case SWITCH_STMT:
19079 stmt = begin_switch_stmt ();
19080 tmp = RECUR (SWITCH_STMT_COND (t));
19081 finish_switch_cond (tmp, stmt);
19082 RECUR (SWITCH_STMT_BODY (t));
19083 finish_switch_stmt (stmt);
19084 break;
19086 case CASE_LABEL_EXPR:
19088 tree decl = CASE_LABEL (t);
19089 tree low = RECUR (CASE_LOW (t));
19090 tree high = RECUR (CASE_HIGH (t));
19091 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19092 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19094 tree label = CASE_LABEL (l);
19095 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19096 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19097 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19100 break;
19102 case LABEL_EXPR:
19104 tree decl = LABEL_EXPR_LABEL (t);
19105 tree label;
19107 label = finish_label_stmt (DECL_NAME (decl));
19108 if (TREE_CODE (label) == LABEL_DECL)
19109 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19110 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19111 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19113 break;
19115 case GOTO_EXPR:
19116 tmp = GOTO_DESTINATION (t);
19117 if (TREE_CODE (tmp) != LABEL_DECL)
19118 /* Computed goto's must be tsubst'd into. On the other hand,
19119 non-computed gotos must not be; the identifier in question
19120 will have no binding. */
19121 tmp = RECUR (tmp);
19122 else
19123 tmp = DECL_NAME (tmp);
19124 finish_goto_stmt (tmp);
19125 break;
19127 case ASM_EXPR:
19129 tree string = RECUR (ASM_STRING (t));
19130 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19131 complain, in_decl);
19132 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19133 complain, in_decl);
19134 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19135 complain, in_decl);
19136 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19137 complain, in_decl);
19138 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19139 outputs, inputs, clobbers, labels,
19140 ASM_INLINE_P (t));
19141 tree asm_expr = tmp;
19142 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19143 asm_expr = TREE_OPERAND (asm_expr, 0);
19144 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19146 break;
19148 case TRY_BLOCK:
19149 if (CLEANUP_P (t))
19151 stmt = begin_try_block ();
19152 RECUR (TRY_STMTS (t));
19153 finish_cleanup_try_block (stmt);
19154 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19156 else
19158 tree compound_stmt = NULL_TREE;
19160 if (FN_TRY_BLOCK_P (t))
19161 stmt = begin_function_try_block (&compound_stmt);
19162 else
19163 stmt = begin_try_block ();
19165 RECUR (TRY_STMTS (t));
19167 if (FN_TRY_BLOCK_P (t))
19168 finish_function_try_block (stmt);
19169 else
19170 finish_try_block (stmt);
19172 RECUR (TRY_HANDLERS (t));
19173 if (FN_TRY_BLOCK_P (t))
19174 finish_function_handler_sequence (stmt, compound_stmt);
19175 else
19176 finish_handler_sequence (stmt);
19178 break;
19180 case HANDLER:
19182 tree decl = HANDLER_PARMS (t);
19184 if (decl)
19186 decl = tsubst (decl, args, complain, in_decl);
19187 /* Prevent instantiate_decl from trying to instantiate
19188 this variable. We've already done all that needs to be
19189 done. */
19190 if (decl != error_mark_node)
19191 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19193 stmt = begin_handler ();
19194 finish_handler_parms (decl, stmt);
19195 RECUR (HANDLER_BODY (t));
19196 finish_handler (stmt);
19198 break;
19200 case TAG_DEFN:
19201 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19202 if (CLASS_TYPE_P (tmp))
19204 /* Local classes are not independent templates; they are
19205 instantiated along with their containing function. And this
19206 way we don't have to deal with pushing out of one local class
19207 to instantiate a member of another local class. */
19208 /* Closures are handled by the LAMBDA_EXPR. */
19209 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19210 complete_type (tmp);
19211 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19212 if ((VAR_P (fld)
19213 || (TREE_CODE (fld) == FUNCTION_DECL
19214 && !DECL_ARTIFICIAL (fld)))
19215 && DECL_TEMPLATE_INSTANTIATION (fld))
19216 instantiate_decl (fld, /*defer_ok=*/false,
19217 /*expl_inst_class=*/false);
19219 break;
19221 case STATIC_ASSERT:
19223 tree condition;
19225 ++c_inhibit_evaluation_warnings;
19226 condition =
19227 tsubst_expr (STATIC_ASSERT_CONDITION (t),
19228 args,
19229 complain, in_decl,
19230 /*integral_constant_expression_p=*/true);
19231 --c_inhibit_evaluation_warnings;
19233 finish_static_assert (condition,
19234 STATIC_ASSERT_MESSAGE (t),
19235 STATIC_ASSERT_SOURCE_LOCATION (t),
19236 /*member_p=*/false, /*show_expr_p=*/true);
19238 break;
19240 case OACC_KERNELS:
19241 case OACC_PARALLEL:
19242 case OACC_SERIAL:
19243 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19244 in_decl);
19245 stmt = begin_omp_parallel ();
19246 RECUR (OMP_BODY (t));
19247 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19248 break;
19250 case OMP_PARALLEL:
19251 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19252 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19253 complain, in_decl);
19254 if (OMP_PARALLEL_COMBINED (t))
19255 omp_parallel_combined_clauses = &tmp;
19256 stmt = begin_omp_parallel ();
19257 RECUR (OMP_PARALLEL_BODY (t));
19258 gcc_assert (omp_parallel_combined_clauses == NULL);
19259 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19260 = OMP_PARALLEL_COMBINED (t);
19261 pop_omp_privatization_clauses (r);
19262 break;
19264 case OMP_TASK:
19265 if (OMP_TASK_BODY (t) == NULL_TREE)
19267 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19268 complain, in_decl);
19269 t = copy_node (t);
19270 OMP_TASK_CLAUSES (t) = tmp;
19271 add_stmt (t);
19272 break;
19274 r = push_omp_privatization_clauses (false);
19275 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19276 complain, in_decl);
19277 stmt = begin_omp_task ();
19278 RECUR (OMP_TASK_BODY (t));
19279 finish_omp_task (tmp, stmt);
19280 pop_omp_privatization_clauses (r);
19281 break;
19283 case OMP_FOR:
19284 case OMP_LOOP:
19285 case OMP_SIMD:
19286 case OMP_DISTRIBUTE:
19287 case OMP_TASKLOOP:
19288 case OACC_LOOP:
19290 tree clauses, body, pre_body;
19291 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19292 tree orig_declv = NULL_TREE;
19293 tree incrv = NULL_TREE;
19294 enum c_omp_region_type ort = C_ORT_OMP;
19295 bool any_range_for = false;
19296 int i;
19298 if (TREE_CODE (t) == OACC_LOOP)
19299 ort = C_ORT_ACC;
19301 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19302 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19303 in_decl);
19304 if (OMP_FOR_INIT (t) != NULL_TREE)
19306 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19307 if (OMP_FOR_ORIG_DECLS (t))
19308 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19309 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19310 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19311 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19314 keep_next_level (true);
19315 stmt = begin_omp_structured_block ();
19317 pre_body = push_stmt_list ();
19318 RECUR (OMP_FOR_PRE_BODY (t));
19319 pre_body = pop_stmt_list (pre_body);
19321 if (OMP_FOR_INIT (t) != NULL_TREE)
19322 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19323 any_range_for
19324 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19325 condv, incrv, &clauses, args,
19326 complain, in_decl,
19327 integral_constant_expression_p);
19328 omp_parallel_combined_clauses = NULL;
19330 if (any_range_for)
19332 gcc_assert (orig_declv);
19333 body = begin_omp_structured_block ();
19334 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19335 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19336 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19337 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19338 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19339 TREE_VEC_ELT (declv, i));
19341 else
19342 body = push_stmt_list ();
19343 RECUR (OMP_FOR_BODY (t));
19344 if (any_range_for)
19345 body = finish_omp_structured_block (body);
19346 else
19347 body = pop_stmt_list (body);
19349 if (OMP_FOR_INIT (t) != NULL_TREE)
19350 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19351 orig_declv, initv, condv, incrv, body, pre_body,
19352 NULL, clauses);
19353 else
19355 t = make_node (TREE_CODE (t));
19356 TREE_TYPE (t) = void_type_node;
19357 OMP_FOR_BODY (t) = body;
19358 OMP_FOR_PRE_BODY (t) = pre_body;
19359 OMP_FOR_CLAUSES (t) = clauses;
19360 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19361 add_stmt (t);
19364 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19365 t));
19366 pop_omp_privatization_clauses (r);
19368 break;
19370 case OMP_SECTIONS:
19371 case OMP_MASKED:
19372 omp_parallel_combined_clauses = NULL;
19373 /* FALLTHRU */
19374 case OMP_SINGLE:
19375 case OMP_SCOPE:
19376 case OMP_TEAMS:
19377 case OMP_CRITICAL:
19378 case OMP_TASKGROUP:
19379 case OMP_SCAN:
19380 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19381 && OMP_TEAMS_COMBINED (t));
19382 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19383 in_decl);
19384 if (TREE_CODE (t) == OMP_TEAMS)
19386 keep_next_level (true);
19387 stmt = begin_omp_structured_block ();
19388 RECUR (OMP_BODY (t));
19389 stmt = finish_omp_structured_block (stmt);
19391 else
19393 stmt = push_stmt_list ();
19394 RECUR (OMP_BODY (t));
19395 stmt = pop_stmt_list (stmt);
19398 if (TREE_CODE (t) == OMP_CRITICAL
19399 && tmp != NULL_TREE
19400 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19402 error_at (OMP_CLAUSE_LOCATION (tmp),
19403 "%<#pragma omp critical%> with %<hint%> clause requires "
19404 "a name, except when %<omp_sync_hint_none%> is used");
19405 RETURN (error_mark_node);
19407 t = copy_node (t);
19408 OMP_BODY (t) = stmt;
19409 OMP_CLAUSES (t) = tmp;
19410 add_stmt (t);
19411 pop_omp_privatization_clauses (r);
19412 break;
19414 case OMP_DEPOBJ:
19415 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19416 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19418 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19419 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19421 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19422 args, complain, in_decl);
19423 if (tmp == NULL_TREE)
19424 tmp = error_mark_node;
19426 else
19428 kind = (enum omp_clause_depend_kind)
19429 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19430 tmp = NULL_TREE;
19432 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19434 else
19435 finish_omp_depobj (EXPR_LOCATION (t), r,
19436 OMP_CLAUSE_DEPEND_INVALID,
19437 OMP_DEPOBJ_CLAUSES (t));
19438 break;
19440 case OACC_DATA:
19441 case OMP_TARGET_DATA:
19442 case OMP_TARGET:
19443 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19444 TREE_CODE (t) == OACC_DATA
19445 ? C_ORT_ACC
19446 : TREE_CODE (t) == OMP_TARGET
19447 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19448 args, complain, in_decl);
19449 keep_next_level (true);
19450 stmt = begin_omp_structured_block ();
19452 RECUR (OMP_BODY (t));
19453 stmt = finish_omp_structured_block (stmt);
19455 t = copy_node (t);
19456 OMP_BODY (t) = stmt;
19457 OMP_CLAUSES (t) = tmp;
19459 if (TREE_CODE (t) == OMP_TARGET)
19460 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19461 &OMP_CLAUSES (t));
19463 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19465 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19466 if (teams)
19467 /* For combined target teams, ensure the num_teams and
19468 thread_limit clause expressions are evaluated on the host,
19469 before entering the target construct. */
19470 for (tree c = OMP_TEAMS_CLAUSES (teams);
19471 c; c = OMP_CLAUSE_CHAIN (c))
19472 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19473 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19474 for (int i = 0;
19475 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19476 if (OMP_CLAUSE_OPERAND (c, i)
19477 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19479 tree expr = OMP_CLAUSE_OPERAND (c, i);
19480 expr = force_target_expr (TREE_TYPE (expr), expr,
19481 tf_none);
19482 if (expr == error_mark_node)
19483 continue;
19484 tmp = TARGET_EXPR_SLOT (expr);
19485 add_stmt (expr);
19486 OMP_CLAUSE_OPERAND (c, i) = expr;
19487 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19488 OMP_CLAUSE_FIRSTPRIVATE);
19489 OMP_CLAUSE_DECL (tc) = tmp;
19490 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19491 OMP_TARGET_CLAUSES (t) = tc;
19494 add_stmt (t);
19495 break;
19497 case OACC_DECLARE:
19498 t = copy_node (t);
19499 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19500 complain, in_decl);
19501 OACC_DECLARE_CLAUSES (t) = tmp;
19502 add_stmt (t);
19503 break;
19505 case OMP_TARGET_UPDATE:
19506 case OMP_TARGET_ENTER_DATA:
19507 case OMP_TARGET_EXIT_DATA:
19508 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19509 complain, in_decl);
19510 t = copy_node (t);
19511 OMP_STANDALONE_CLAUSES (t) = tmp;
19512 add_stmt (t);
19513 break;
19515 case OACC_CACHE:
19516 case OACC_ENTER_DATA:
19517 case OACC_EXIT_DATA:
19518 case OACC_UPDATE:
19519 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19520 complain, in_decl);
19521 t = copy_node (t);
19522 OMP_STANDALONE_CLAUSES (t) = tmp;
19523 add_stmt (t);
19524 break;
19526 case OMP_ORDERED:
19527 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19528 complain, in_decl);
19529 if (OMP_BODY (t))
19531 stmt = push_stmt_list ();
19532 RECUR (OMP_BODY (t));
19533 stmt = pop_stmt_list (stmt);
19535 else
19536 stmt = NULL_TREE;
19538 t = copy_node (t);
19539 OMP_BODY (t) = stmt;
19540 OMP_ORDERED_CLAUSES (t) = tmp;
19541 add_stmt (t);
19542 break;
19544 case OMP_MASTER:
19545 omp_parallel_combined_clauses = NULL;
19546 /* FALLTHRU */
19547 case OMP_SECTION:
19548 stmt = push_stmt_list ();
19549 RECUR (OMP_BODY (t));
19550 stmt = pop_stmt_list (stmt);
19552 t = copy_node (t);
19553 OMP_BODY (t) = stmt;
19554 add_stmt (t);
19555 break;
19557 case OMP_ATOMIC:
19558 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19559 tmp = NULL_TREE;
19560 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19561 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19562 complain, in_decl);
19563 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19565 tree op1 = TREE_OPERAND (t, 1);
19566 tree rhs1 = NULL_TREE;
19567 tree r = NULL_TREE;
19568 tree lhs, rhs;
19569 if (TREE_CODE (op1) == COMPOUND_EXPR)
19571 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19572 op1 = TREE_OPERAND (op1, 1);
19574 if (TREE_CODE (op1) == COND_EXPR)
19576 gcc_assert (rhs1 == NULL_TREE);
19577 tree c = TREE_OPERAND (op1, 0);
19578 if (TREE_CODE (c) == MODIFY_EXPR)
19580 r = RECUR (TREE_OPERAND (c, 0));
19581 c = TREE_OPERAND (c, 1);
19583 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19584 rhs = RECUR (TREE_OPERAND (c, 1));
19585 lhs = RECUR (TREE_OPERAND (op1, 2));
19586 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19588 else
19590 lhs = RECUR (TREE_OPERAND (op1, 0));
19591 rhs = RECUR (TREE_OPERAND (op1, 1));
19593 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19594 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19595 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19596 OMP_ATOMIC_WEAK (t));
19598 else
19600 tree op1 = TREE_OPERAND (t, 1);
19601 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19602 tree rhs1 = NULL_TREE, r = NULL_TREE;
19603 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19604 enum tree_code opcode = NOP_EXPR;
19605 if (code == OMP_ATOMIC_READ)
19607 v = RECUR (TREE_OPERAND (op1, 0));
19608 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19610 else if (code == OMP_ATOMIC_CAPTURE_OLD
19611 || code == OMP_ATOMIC_CAPTURE_NEW)
19613 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19614 v = RECUR (TREE_OPERAND (op1, 0));
19615 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19616 if (TREE_CODE (op11) == COMPOUND_EXPR)
19618 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19619 op11 = TREE_OPERAND (op11, 1);
19621 if (TREE_CODE (op11) == COND_EXPR)
19623 gcc_assert (rhs1 == NULL_TREE);
19624 tree c = TREE_OPERAND (op11, 0);
19625 if (TREE_CODE (c) == MODIFY_EXPR)
19627 r = RECUR (TREE_OPERAND (c, 0));
19628 c = TREE_OPERAND (c, 1);
19630 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19631 rhs = RECUR (TREE_OPERAND (c, 1));
19632 lhs = RECUR (TREE_OPERAND (op11, 2));
19633 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19635 else
19637 lhs = RECUR (TREE_OPERAND (op11, 0));
19638 rhs = RECUR (TREE_OPERAND (op11, 1));
19640 opcode = TREE_CODE (op11);
19641 if (opcode == MODIFY_EXPR)
19642 opcode = NOP_EXPR;
19644 else
19646 code = OMP_ATOMIC;
19647 lhs = RECUR (TREE_OPERAND (op1, 0));
19648 rhs = RECUR (TREE_OPERAND (op1, 1));
19650 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19651 lhs1, rhs1, r, tmp,
19652 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19654 break;
19656 case TRANSACTION_EXPR:
19658 int flags = 0;
19659 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19660 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19662 if (TRANSACTION_EXPR_IS_STMT (t))
19664 tree body = TRANSACTION_EXPR_BODY (t);
19665 tree noex = NULL_TREE;
19666 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19668 noex = MUST_NOT_THROW_COND (body);
19669 if (noex == NULL_TREE)
19670 noex = boolean_true_node;
19671 body = TREE_OPERAND (body, 0);
19673 stmt = begin_transaction_stmt (input_location, NULL, flags);
19674 RECUR (body);
19675 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19677 else
19679 stmt = build_transaction_expr (EXPR_LOCATION (t),
19680 RECUR (TRANSACTION_EXPR_BODY (t)),
19681 flags, NULL_TREE);
19682 RETURN (stmt);
19685 break;
19687 case MUST_NOT_THROW_EXPR:
19689 tree op0 = RECUR (TREE_OPERAND (t, 0));
19690 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19691 RETURN (build_must_not_throw_expr (op0, cond));
19694 case EXPR_PACK_EXPANSION:
19695 error ("invalid use of pack expansion expression");
19696 RETURN (error_mark_node);
19698 case NONTYPE_ARGUMENT_PACK:
19699 error ("use %<...%> to expand argument pack");
19700 RETURN (error_mark_node);
19702 case COMPOUND_EXPR:
19703 tmp = RECUR (TREE_OPERAND (t, 0));
19704 if (tmp == NULL_TREE)
19705 /* If the first operand was a statement, we're done with it. */
19706 RETURN (RECUR (TREE_OPERAND (t, 1)));
19707 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19708 RECUR (TREE_OPERAND (t, 1)),
19709 templated_operator_saved_lookups (t),
19710 complain));
19712 case ANNOTATE_EXPR:
19713 tmp = RECUR (TREE_OPERAND (t, 0));
19714 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19715 TREE_TYPE (tmp), tmp,
19716 RECUR (TREE_OPERAND (t, 1)),
19717 RECUR (TREE_OPERAND (t, 2))));
19719 case PREDICT_EXPR:
19720 RETURN (add_stmt (copy_node (t)));
19722 default:
19723 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19725 RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
19726 /*function_p=*/false,
19727 integral_constant_expression_p));
19730 RETURN (NULL_TREE);
19731 out:
19732 input_location = loc;
19733 return r;
19734 #undef RECUR
19735 #undef RETURN
19738 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19739 function. For description of the body see comment above
19740 cp_parser_omp_declare_reduction_exprs. */
19742 static void
19743 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19745 if (t == NULL_TREE || t == error_mark_node)
19746 return;
19748 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19750 tree_stmt_iterator tsi;
19751 int i;
19752 tree stmts[7];
19753 memset (stmts, 0, sizeof stmts);
19754 for (i = 0, tsi = tsi_start (t);
19755 i < 7 && !tsi_end_p (tsi);
19756 i++, tsi_next (&tsi))
19757 stmts[i] = tsi_stmt (tsi);
19758 gcc_assert (tsi_end_p (tsi));
19760 if (i >= 3)
19762 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19763 && TREE_CODE (stmts[1]) == DECL_EXPR);
19764 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19765 args, complain, in_decl);
19766 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19767 args, complain, in_decl);
19768 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19769 expect to be pushing it. */
19770 DECL_CONTEXT (omp_out) = current_function_decl;
19771 DECL_CONTEXT (omp_in) = current_function_decl;
19772 keep_next_level (true);
19773 tree block = begin_omp_structured_block ();
19774 tsubst_expr (stmts[2], args, complain, in_decl, false);
19775 block = finish_omp_structured_block (block);
19776 block = maybe_cleanup_point_expr_void (block);
19777 add_decl_expr (omp_out);
19778 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19779 add_decl_expr (omp_in);
19780 finish_expr_stmt (block);
19782 if (i >= 6)
19784 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19785 && TREE_CODE (stmts[4]) == DECL_EXPR);
19786 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19787 args, complain, in_decl);
19788 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19789 args, complain, in_decl);
19790 DECL_CONTEXT (omp_priv) = current_function_decl;
19791 DECL_CONTEXT (omp_orig) = current_function_decl;
19792 keep_next_level (true);
19793 tree block = begin_omp_structured_block ();
19794 tsubst_expr (stmts[5], args, complain, in_decl, false);
19795 block = finish_omp_structured_block (block);
19796 block = maybe_cleanup_point_expr_void (block);
19797 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19798 add_decl_expr (omp_priv);
19799 add_decl_expr (omp_orig);
19800 finish_expr_stmt (block);
19801 if (i == 7)
19802 add_decl_expr (omp_orig);
19806 /* T is a postfix-expression that is not being used in a function
19807 call. Return the substituted version of T. */
19809 static tree
19810 tsubst_non_call_postfix_expression (tree t, tree args,
19811 tsubst_flags_t complain,
19812 tree in_decl)
19814 if (TREE_CODE (t) == SCOPE_REF)
19815 t = tsubst_qualified_id (t, args, complain, in_decl,
19816 /*done=*/false, /*address_p=*/false);
19817 else
19818 t = tsubst_copy_and_build (t, args, complain, in_decl,
19819 /*function_p=*/false,
19820 /*integral_constant_expression_p=*/false);
19822 return t;
19825 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19826 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19827 dependent init-capture. */
19829 static void
19830 prepend_one_capture (tree field, tree init, tree &list,
19831 tsubst_flags_t complain)
19833 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19835 tree type = NULL_TREE;
19836 if (!init)
19838 if (complain & tf_error)
19839 error ("empty initializer in lambda init-capture");
19840 init = error_mark_node;
19842 else if (TREE_CODE (init) == TREE_LIST)
19843 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19844 if (!type)
19845 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19846 TREE_TYPE (field) = type;
19847 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19849 list = tree_cons (field, init, list);
19852 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19853 instantiation context. Instantiating a pack expansion containing a lambda
19854 might result in multiple lambdas all based on the same lambda in the
19855 template. */
19857 tree
19858 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19860 tree oldfn = lambda_function (t);
19861 in_decl = oldfn;
19863 tree r = build_lambda_expr ();
19865 LAMBDA_EXPR_LOCATION (r)
19866 = LAMBDA_EXPR_LOCATION (t);
19867 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19868 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19869 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19870 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19871 LAMBDA_EXPR_REGEN_INFO (r)
19872 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19873 preserve_args (args)));
19874 else
19875 LAMBDA_EXPR_REGEN_INFO (r)
19876 = build_template_info (t, preserve_args (args));
19878 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19879 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19881 vec<tree,va_gc>* field_packs = NULL;
19883 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19884 cap = TREE_CHAIN (cap))
19886 tree ofield = TREE_PURPOSE (cap);
19887 tree init = TREE_VALUE (cap);
19888 if (PACK_EXPANSION_P (init))
19889 init = tsubst_pack_expansion (init, args, complain, in_decl);
19890 else
19891 init = tsubst_copy_and_build (init, args, complain, in_decl,
19892 /*fn*/false, /*constexpr*/false);
19894 if (init == error_mark_node)
19895 return error_mark_node;
19897 if (init && TREE_CODE (init) == TREE_LIST)
19898 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19900 if (!processing_template_decl
19901 && init && TREE_CODE (init) != TREE_VEC
19902 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19904 /* For a VLA, simply tsubsting the field type won't work, we need to
19905 go through add_capture again. XXX do we want to do this for all
19906 captures? */
19907 tree name = (get_identifier
19908 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19909 tree ftype = TREE_TYPE (ofield);
19910 bool by_ref = (TYPE_REF_P (ftype)
19911 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19912 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19913 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19914 continue;
19917 if (PACK_EXPANSION_P (ofield))
19918 ofield = PACK_EXPANSION_PATTERN (ofield);
19919 tree field = tsubst_decl (ofield, args, complain);
19921 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19923 /* Remember these for when we've pushed local_specializations. */
19924 vec_safe_push (field_packs, ofield);
19925 vec_safe_push (field_packs, field);
19928 if (field == error_mark_node)
19929 return error_mark_node;
19931 if (TREE_CODE (field) == TREE_VEC)
19933 int len = TREE_VEC_LENGTH (field);
19934 gcc_assert (TREE_CODE (init) == TREE_VEC
19935 && TREE_VEC_LENGTH (init) == len);
19936 for (int i = 0; i < len; ++i)
19937 prepend_one_capture (TREE_VEC_ELT (field, i),
19938 TREE_VEC_ELT (init, i),
19939 LAMBDA_EXPR_CAPTURE_LIST (r),
19940 complain);
19942 else
19944 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19945 complain);
19947 if (id_equal (DECL_NAME (field), "__this"))
19948 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19952 tree type = begin_lambda_type (r);
19953 if (type == error_mark_node)
19954 return error_mark_node;
19956 if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19958 /* A lambda in a default argument outside a class gets no
19959 LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI. But
19960 tsubst_default_argument calls start_lambda_scope, so we need to
19961 specifically ignore it here, and use the global scope. */
19962 record_null_lambda_scope (r);
19964 /* If we're pushed into another scope (PR105652), fix it. */
19965 if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19966 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19967 = TYPE_CONTEXT (TREE_TYPE (t));
19969 else
19970 record_lambda_scope (r);
19972 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19973 determine_visibility (TYPE_NAME (type));
19975 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19977 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19978 ? DECL_TI_TEMPLATE (oldfn)
19979 : NULL_TREE);
19981 tree fntype = static_fn_type (oldfn);
19982 if (oldtmpl)
19983 ++processing_template_decl;
19984 fntype = tsubst (fntype, args, complain, in_decl);
19985 if (oldtmpl)
19986 --processing_template_decl;
19988 if (fntype == error_mark_node)
19989 r = error_mark_node;
19990 else
19992 /* The body of a lambda-expression is not a subexpression of the
19993 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19994 which would be skipped if cp_unevaluated_operand. */
19995 cp_evaluated ev;
19997 /* Fix the type of 'this'. */
19998 fntype = build_memfn_type (fntype, type,
19999 type_memfn_quals (fntype),
20000 type_memfn_rqual (fntype));
20001 tree fn, tmpl;
20002 if (oldtmpl)
20004 tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
20005 if (tmpl == error_mark_node)
20007 r = error_mark_node;
20008 goto out;
20010 fn = DECL_TEMPLATE_RESULT (tmpl);
20011 finish_member_declaration (tmpl);
20013 else
20015 tmpl = NULL_TREE;
20016 fn = tsubst_function_decl (oldfn, args, complain, fntype);
20017 if (fn == error_mark_node)
20019 r = error_mark_node;
20020 goto out;
20022 finish_member_declaration (fn);
20025 /* Let finish_function set this. */
20026 DECL_DECLARED_CONSTEXPR_P (fn) = false;
20028 bool nested = cfun;
20029 if (nested)
20030 push_function_context ();
20031 else
20032 /* Still increment function_depth so that we don't GC in the
20033 middle of an expression. */
20034 ++function_depth;
20036 local_specialization_stack s (lss_copy);
20038 bool save_in_consteval_if_p = in_consteval_if_p;
20039 in_consteval_if_p = false;
20041 tree body = start_lambda_function (fn, r);
20043 /* Now record them for lookup_init_capture_pack. */
20044 int fplen = vec_safe_length (field_packs);
20045 for (int i = 0; i < fplen; )
20047 tree pack = (*field_packs)[i++];
20048 tree inst = (*field_packs)[i++];
20049 register_local_specialization (inst, pack);
20051 release_tree_vector (field_packs);
20053 register_parameter_specializations (oldfn, fn);
20055 if (oldtmpl)
20057 /* We might not partially instantiate some parts of the function, so
20058 copy these flags from the original template. */
20059 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20060 current_function_returns_value = ol->returns_value;
20061 current_function_returns_null = ol->returns_null;
20062 current_function_returns_abnormally = ol->returns_abnormally;
20063 current_function_infinite_loop = ol->infinite_loop;
20066 /* [temp.deduct] A lambda-expression appearing in a function type or a
20067 template parameter is not considered part of the immediate context for
20068 the purposes of template argument deduction. */
20069 complain = tf_warning_or_error;
20071 tree saved = DECL_SAVED_TREE (oldfn);
20072 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20073 /* We already have a body block from start_lambda_function, we don't
20074 need another to confuse NRV (91217). */
20075 saved = BIND_EXPR_BODY (saved);
20077 tsubst_expr (saved, args, complain, r, /*constexpr*/false);
20079 finish_lambda_function (body);
20081 in_consteval_if_p = save_in_consteval_if_p;
20083 if (nested)
20084 pop_function_context ();
20085 else
20086 --function_depth;
20088 /* The capture list was built up in reverse order; fix that now. */
20089 LAMBDA_EXPR_CAPTURE_LIST (r)
20090 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20092 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20094 maybe_add_lambda_conv_op (type);
20097 out:
20098 finish_struct (type, /*attr*/NULL_TREE);
20100 insert_pending_capture_proxies ();
20102 return r;
20105 /* Subroutine of maybe_fold_fn_template_args. */
20107 static bool
20108 fold_targs_r (tree targs, tsubst_flags_t complain)
20110 int len = TREE_VEC_LENGTH (targs);
20111 for (int i = 0; i < len; ++i)
20113 tree &elt = TREE_VEC_ELT (targs, i);
20114 if (!elt || TYPE_P (elt)
20115 || TREE_CODE (elt) == TEMPLATE_DECL)
20116 continue;
20117 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20119 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20120 return false;
20122 else if (/* We can only safely preevaluate scalar prvalues. */
20123 SCALAR_TYPE_P (TREE_TYPE (elt))
20124 && !glvalue_p (elt)
20125 && !TREE_CONSTANT (elt))
20127 elt = cxx_constant_value_sfinae (elt, NULL_TREE, complain);
20128 if (elt == error_mark_node)
20129 return false;
20133 return true;
20136 /* Try to do constant evaluation of any explicit template arguments in FN
20137 before overload resolution, to get any errors only once. Return true iff
20138 we didn't have any problems folding. */
20140 static bool
20141 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20143 if (processing_template_decl || fn == NULL_TREE)
20144 return true;
20145 if (fn == error_mark_node)
20146 return false;
20147 if (TREE_CODE (fn) == OFFSET_REF
20148 || TREE_CODE (fn) == COMPONENT_REF)
20149 fn = TREE_OPERAND (fn, 1);
20150 if (BASELINK_P (fn))
20151 fn = BASELINK_FUNCTIONS (fn);
20152 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20153 return true;
20154 tree targs = TREE_OPERAND (fn, 1);
20155 if (targs == NULL_TREE)
20156 return true;
20157 if (targs == error_mark_node)
20158 return false;
20159 return fold_targs_r (targs, complain);
20162 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20163 handling. */
20165 static void
20166 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20167 tree in_decl,
20168 bool integral_constant_expression_p,
20169 releasing_vec &call_args)
20171 unsigned int nargs = call_expr_nargs (t);
20172 for (unsigned int i = 0; i < nargs; ++i)
20174 tree arg = CALL_EXPR_ARG (t, i);
20176 if (!PACK_EXPANSION_P (arg))
20177 vec_safe_push (call_args,
20178 tsubst_copy_and_build (arg, args, complain, in_decl,
20179 /*function_p=*/false,
20180 integral_constant_expression_p));
20181 else
20183 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20184 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20185 if (TREE_CODE (arg) == TREE_VEC)
20187 unsigned int len, j;
20189 len = TREE_VEC_LENGTH (arg);
20190 for (j = 0; j < len; ++j)
20192 tree value = TREE_VEC_ELT (arg, j);
20193 if (value != NULL_TREE)
20194 value = convert_from_reference (value);
20195 vec_safe_push (call_args, value);
20198 else
20199 /* A partial substitution. Add one entry. */
20200 vec_safe_push (call_args, arg);
20205 /* Like tsubst but deals with expressions and performs semantic
20206 analysis. FUNCTION_P is true if T is the "F" in "F (ARGS)" or
20207 "F<TARGS> (ARGS)". */
20209 tree
20210 tsubst_copy_and_build (tree t,
20211 tree args,
20212 tsubst_flags_t complain,
20213 tree in_decl,
20214 bool function_p,
20215 bool integral_constant_expression_p)
20217 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20218 #define RECUR(NODE) \
20219 tsubst_copy_and_build (NODE, args, complain, in_decl, \
20220 /*function_p=*/false, \
20221 integral_constant_expression_p)
20223 tree retval, op1;
20224 location_t save_loc;
20226 if (t == NULL_TREE || t == error_mark_node)
20227 return t;
20229 save_loc = input_location;
20230 if (location_t eloc = cp_expr_location (t))
20231 input_location = eloc;
20233 /* N3276 decltype magic only applies to calls at the top level or on the
20234 right side of a comma. */
20235 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20236 complain &= ~tf_decltype;
20238 switch (TREE_CODE (t))
20240 case USING_DECL:
20241 t = DECL_NAME (t);
20242 /* Fall through. */
20243 case IDENTIFIER_NODE:
20245 tree decl;
20246 cp_id_kind idk;
20247 bool non_integral_constant_expression_p;
20248 const char *error_msg;
20250 if (IDENTIFIER_CONV_OP_P (t))
20252 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20253 t = make_conv_op_name (new_type);
20256 /* Look up the name. */
20257 decl = lookup_name (t);
20259 /* By convention, expressions use ERROR_MARK_NODE to indicate
20260 failure, not NULL_TREE. */
20261 if (decl == NULL_TREE)
20262 decl = error_mark_node;
20264 decl = finish_id_expression (t, decl, NULL_TREE,
20265 &idk,
20266 integral_constant_expression_p,
20267 /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
20268 &non_integral_constant_expression_p,
20269 /*template_p=*/false,
20270 /*done=*/true,
20271 /*address_p=*/false,
20272 /*template_arg_p=*/false,
20273 &error_msg,
20274 input_location);
20275 if (error_msg)
20276 error (error_msg);
20277 if (!function_p && identifier_p (decl))
20279 if (complain & tf_error)
20280 unqualified_name_lookup_error (decl);
20281 decl = error_mark_node;
20283 RETURN (decl);
20286 case TEMPLATE_ID_EXPR:
20288 tree object;
20289 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20290 complain, in_decl,
20291 function_p,
20292 integral_constant_expression_p);
20293 tree targs = TREE_OPERAND (t, 1);
20295 if (targs)
20296 targs = tsubst_template_args (targs, args, complain, in_decl);
20297 if (targs == error_mark_node)
20298 RETURN (error_mark_node);
20300 if (TREE_CODE (templ) == SCOPE_REF)
20302 tree name = TREE_OPERAND (templ, 1);
20303 tree tid = lookup_template_function (name, targs);
20304 TREE_OPERAND (templ, 1) = tid;
20305 RETURN (templ);
20308 if (concept_definition_p (templ))
20310 tree check = build_concept_check (templ, targs, complain);
20311 if (check == error_mark_node)
20312 RETURN (error_mark_node);
20314 tree id = unpack_concept_check (check);
20316 /* If we built a function concept check, return the underlying
20317 template-id. So we can evaluate it as a function call. */
20318 if (function_concept_p (TREE_OPERAND (id, 0)))
20319 RETURN (id);
20321 RETURN (check);
20324 if (variable_template_p (templ))
20326 tree r = lookup_and_finish_template_variable (templ, targs,
20327 complain);
20328 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20329 RETURN (r);
20332 if (TREE_CODE (templ) == COMPONENT_REF)
20334 object = TREE_OPERAND (templ, 0);
20335 templ = TREE_OPERAND (templ, 1);
20337 else
20338 object = NULL_TREE;
20340 tree tid = lookup_template_function (templ, targs);
20341 protected_set_expr_location (tid, EXPR_LOCATION (t));
20343 if (object)
20344 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20345 object, tid, NULL_TREE));
20346 else if (identifier_p (templ))
20348 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20349 name lookup found nothing when parsing the template name. */
20350 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20351 RETURN (tid);
20353 else
20354 RETURN (baselink_for_fns (tid));
20357 case INDIRECT_REF:
20359 tree r = RECUR (TREE_OPERAND (t, 0));
20361 if (REFERENCE_REF_P (t))
20363 /* A type conversion to reference type will be enclosed in
20364 such an indirect ref, but the substitution of the cast
20365 will have also added such an indirect ref. */
20366 r = convert_from_reference (r);
20368 else
20369 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20370 templated_operator_saved_lookups (t),
20371 complain|decltype_flag);
20373 if (REF_PARENTHESIZED_P (t))
20374 r = force_paren_expr (r);
20376 RETURN (r);
20379 case NOP_EXPR:
20381 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20382 tree op0 = RECUR (TREE_OPERAND (t, 0));
20383 RETURN (build_nop (type, op0));
20386 case IMPLICIT_CONV_EXPR:
20388 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20389 tree expr = RECUR (TREE_OPERAND (t, 0));
20390 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20392 retval = copy_node (t);
20393 TREE_TYPE (retval) = type;
20394 TREE_OPERAND (retval, 0) = expr;
20395 RETURN (retval);
20397 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20398 /* We'll pass this to convert_nontype_argument again, we don't need
20399 to actually perform any conversion here. */
20400 RETURN (expr);
20401 int flags = LOOKUP_IMPLICIT;
20402 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20403 flags = LOOKUP_NORMAL;
20404 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20405 flags |= LOOKUP_NO_NARROWING;
20406 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20407 flags));
20410 case CONVERT_EXPR:
20412 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20413 tree op0 = RECUR (TREE_OPERAND (t, 0));
20414 if (op0 == error_mark_node)
20415 RETURN (error_mark_node);
20416 RETURN (build1 (CONVERT_EXPR, type, op0));
20419 case CAST_EXPR:
20420 case REINTERPRET_CAST_EXPR:
20421 case CONST_CAST_EXPR:
20422 case DYNAMIC_CAST_EXPR:
20423 case STATIC_CAST_EXPR:
20425 tree type;
20426 tree op, r = NULL_TREE;
20428 tsubst_flags_t tcomplain = complain;
20429 if (TREE_CODE (t) == CAST_EXPR)
20430 tcomplain |= tf_tst_ok;
20431 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20432 if (integral_constant_expression_p
20433 && !cast_valid_in_integral_constant_expression_p (type))
20435 if (complain & tf_error)
20436 error ("a cast to a type other than an integral or "
20437 "enumeration type cannot appear in a constant-expression");
20438 RETURN (error_mark_node);
20441 op = RECUR (TREE_OPERAND (t, 0));
20443 warning_sentinel s(warn_useless_cast);
20444 warning_sentinel s2(warn_ignored_qualifiers);
20445 warning_sentinel s3(warn_int_in_bool_context);
20446 switch (TREE_CODE (t))
20448 case CAST_EXPR:
20449 r = build_functional_cast (input_location, type, op, complain);
20450 break;
20451 case REINTERPRET_CAST_EXPR:
20452 r = build_reinterpret_cast (input_location, type, op, complain);
20453 break;
20454 case CONST_CAST_EXPR:
20455 r = build_const_cast (input_location, type, op, complain);
20456 break;
20457 case DYNAMIC_CAST_EXPR:
20458 r = build_dynamic_cast (input_location, type, op, complain);
20459 break;
20460 case STATIC_CAST_EXPR:
20461 r = build_static_cast (input_location, type, op, complain);
20462 if (IMPLICIT_RVALUE_P (t))
20463 set_implicit_rvalue_p (r);
20464 break;
20465 default:
20466 gcc_unreachable ();
20469 RETURN (r);
20472 case BIT_CAST_EXPR:
20474 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20475 tree op0 = RECUR (TREE_OPERAND (t, 0));
20476 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20479 case POSTDECREMENT_EXPR:
20480 case POSTINCREMENT_EXPR:
20481 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20482 args, complain, in_decl);
20483 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20484 templated_operator_saved_lookups (t),
20485 complain|decltype_flag));
20487 case PREDECREMENT_EXPR:
20488 case PREINCREMENT_EXPR:
20489 case NEGATE_EXPR:
20490 case BIT_NOT_EXPR:
20491 case ABS_EXPR:
20492 case TRUTH_NOT_EXPR:
20493 case UNARY_PLUS_EXPR: /* Unary + */
20494 case REALPART_EXPR:
20495 case IMAGPART_EXPR:
20496 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20497 RECUR (TREE_OPERAND (t, 0)),
20498 templated_operator_saved_lookups (t),
20499 complain|decltype_flag));
20501 case FIX_TRUNC_EXPR:
20502 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20503 gcc_unreachable ();
20505 case ADDR_EXPR:
20506 op1 = TREE_OPERAND (t, 0);
20507 if (TREE_CODE (op1) == LABEL_DECL)
20508 RETURN (finish_label_address_expr (DECL_NAME (op1),
20509 EXPR_LOCATION (op1)));
20510 if (TREE_CODE (op1) == SCOPE_REF)
20511 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20512 /*done=*/true, /*address_p=*/true);
20513 else
20514 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20515 in_decl);
20516 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20517 templated_operator_saved_lookups (t),
20518 complain|decltype_flag));
20520 case PLUS_EXPR:
20521 case MINUS_EXPR:
20522 case MULT_EXPR:
20523 case TRUNC_DIV_EXPR:
20524 case CEIL_DIV_EXPR:
20525 case FLOOR_DIV_EXPR:
20526 case ROUND_DIV_EXPR:
20527 case EXACT_DIV_EXPR:
20528 case BIT_AND_EXPR:
20529 case BIT_IOR_EXPR:
20530 case BIT_XOR_EXPR:
20531 case TRUNC_MOD_EXPR:
20532 case FLOOR_MOD_EXPR:
20533 case TRUTH_ANDIF_EXPR:
20534 case TRUTH_ORIF_EXPR:
20535 case TRUTH_AND_EXPR:
20536 case TRUTH_OR_EXPR:
20537 case RSHIFT_EXPR:
20538 case LSHIFT_EXPR:
20539 case EQ_EXPR:
20540 case NE_EXPR:
20541 case MAX_EXPR:
20542 case MIN_EXPR:
20543 case LE_EXPR:
20544 case GE_EXPR:
20545 case LT_EXPR:
20546 case GT_EXPR:
20547 case SPACESHIP_EXPR:
20548 case MEMBER_REF:
20549 case DOTSTAR_EXPR:
20551 /* If either OP0 or OP1 was value- or type-dependent, suppress
20552 warnings that depend on the range of the types involved. */
20553 tree op0 = TREE_OPERAND (t, 0);
20554 tree op1 = TREE_OPERAND (t, 1);
20555 const bool was_dep = (dependent_operand_p (op0)
20556 || dependent_operand_p (op1));
20557 op0 = RECUR (op0);
20558 op1 = RECUR (op1);
20560 warning_sentinel s1(warn_type_limits, was_dep);
20561 warning_sentinel s2(warn_div_by_zero, was_dep);
20562 warning_sentinel s3(warn_logical_op, was_dep);
20563 warning_sentinel s4(warn_tautological_compare, was_dep);
20564 warning_sentinel s5(warn_address, was_dep);
20566 tree r = build_x_binary_op
20567 (input_location, TREE_CODE (t),
20568 op0,
20569 (warning_suppressed_p (TREE_OPERAND (t, 0))
20570 ? ERROR_MARK
20571 : TREE_CODE (TREE_OPERAND (t, 0))),
20572 op1,
20573 (warning_suppressed_p (TREE_OPERAND (t, 1))
20574 ? ERROR_MARK
20575 : TREE_CODE (TREE_OPERAND (t, 1))),
20576 templated_operator_saved_lookups (t),
20577 /*overload=*/NULL,
20578 complain|decltype_flag);
20579 if (EXPR_P (r))
20580 copy_warning (r, t);
20582 RETURN (r);
20585 case POINTER_PLUS_EXPR:
20587 tree op0 = RECUR (TREE_OPERAND (t, 0));
20588 if (op0 == error_mark_node)
20589 RETURN (error_mark_node);
20590 tree op1 = RECUR (TREE_OPERAND (t, 1));
20591 if (op1 == error_mark_node)
20592 RETURN (error_mark_node);
20593 RETURN (fold_build_pointer_plus (op0, op1));
20596 case SCOPE_REF:
20597 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20598 /*address_p=*/false));
20600 case BASELINK:
20601 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20602 args, complain, in_decl));
20604 case ARRAY_REF:
20605 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20606 args, complain, in_decl);
20607 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20608 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20609 == ovl_op_identifier (ARRAY_REF)))
20611 tree c = TREE_OPERAND (t, 1);
20612 releasing_vec index_exp_list;
20613 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20614 integral_constant_expression_p,
20615 index_exp_list);
20617 tree r;
20618 if (vec_safe_length (index_exp_list) == 1
20619 && !PACK_EXPANSION_P (index_exp_list[0]))
20620 r = grok_array_decl (EXPR_LOCATION (t), op1,
20621 index_exp_list[0], NULL,
20622 complain | decltype_flag);
20623 else
20624 r = grok_array_decl (EXPR_LOCATION (t), op1,
20625 NULL_TREE, &index_exp_list,
20626 complain | decltype_flag);
20627 RETURN (r);
20629 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20630 RECUR (TREE_OPERAND (t, 1)),
20631 complain|decltype_flag));
20633 case SIZEOF_EXPR:
20634 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20635 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20636 RETURN (tsubst_copy (t, args, complain, in_decl));
20637 /* Fall through */
20639 case ALIGNOF_EXPR:
20641 tree r;
20643 op1 = TREE_OPERAND (t, 0);
20644 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20645 op1 = TREE_TYPE (op1);
20646 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20647 && ALIGNOF_EXPR_STD_P (t));
20648 if (!args)
20650 /* When there are no ARGS, we are trying to evaluate a
20651 non-dependent expression from the parser. Trying to do
20652 the substitutions may not work. */
20653 if (!TYPE_P (op1))
20654 op1 = TREE_TYPE (op1);
20656 else
20658 ++cp_unevaluated_operand;
20659 ++c_inhibit_evaluation_warnings;
20660 if (TYPE_P (op1))
20661 op1 = tsubst (op1, args, complain, in_decl);
20662 else
20663 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20664 /*function_p=*/false,
20665 /*integral_constant_expression_p=*/
20666 false);
20667 --cp_unevaluated_operand;
20668 --c_inhibit_evaluation_warnings;
20670 if (TYPE_P (op1))
20671 r = cxx_sizeof_or_alignof_type (input_location,
20672 op1, TREE_CODE (t), std_alignof,
20673 complain & tf_error);
20674 else
20675 r = cxx_sizeof_or_alignof_expr (input_location,
20676 op1, TREE_CODE (t), std_alignof,
20677 complain & tf_error);
20678 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20680 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20682 if (!processing_template_decl && TYPE_P (op1))
20684 r = build_min (SIZEOF_EXPR, size_type_node,
20685 build1 (NOP_EXPR, op1, error_mark_node));
20686 SIZEOF_EXPR_TYPE_P (r) = 1;
20688 else
20689 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20690 TREE_SIDE_EFFECTS (r) = 0;
20691 TREE_READONLY (r) = 1;
20693 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20695 RETURN (r);
20698 case AT_ENCODE_EXPR:
20700 op1 = TREE_OPERAND (t, 0);
20701 ++cp_unevaluated_operand;
20702 ++c_inhibit_evaluation_warnings;
20703 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20704 /*function_p=*/false,
20705 /*integral_constant_expression_p=*/false);
20706 --cp_unevaluated_operand;
20707 --c_inhibit_evaluation_warnings;
20708 RETURN (objc_build_encode_expr (op1));
20711 case NOEXCEPT_EXPR:
20712 op1 = TREE_OPERAND (t, 0);
20713 ++cp_unevaluated_operand;
20714 ++c_inhibit_evaluation_warnings;
20715 ++cp_noexcept_operand;
20716 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20717 /*function_p=*/false,
20718 /*integral_constant_expression_p=*/false);
20719 --cp_unevaluated_operand;
20720 --c_inhibit_evaluation_warnings;
20721 --cp_noexcept_operand;
20722 RETURN (finish_noexcept_expr (op1, complain));
20724 case MODOP_EXPR:
20726 warning_sentinel s(warn_div_by_zero);
20727 tree lhs = RECUR (TREE_OPERAND (t, 0));
20728 tree rhs = RECUR (TREE_OPERAND (t, 2));
20730 tree r = build_x_modify_expr
20731 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20732 templated_operator_saved_lookups (t),
20733 complain|decltype_flag);
20734 /* TREE_NO_WARNING must be set if either the expression was
20735 parenthesized or it uses an operator such as >>= rather
20736 than plain assignment. In the former case, it was already
20737 set and must be copied. In the latter case,
20738 build_x_modify_expr sets it and it must not be reset
20739 here. */
20740 if (warning_suppressed_p (t, OPT_Wparentheses))
20741 suppress_warning (r, OPT_Wparentheses);
20743 RETURN (r);
20746 case ARROW_EXPR:
20747 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20748 args, complain, in_decl);
20749 /* Remember that there was a reference to this entity. */
20750 if (DECL_P (op1)
20751 && !mark_used (op1, complain) && !(complain & tf_error))
20752 RETURN (error_mark_node);
20753 RETURN (build_x_arrow (input_location, op1, complain));
20755 case NEW_EXPR:
20757 tree placement = RECUR (TREE_OPERAND (t, 0));
20758 tree init = RECUR (TREE_OPERAND (t, 3));
20759 vec<tree, va_gc> *placement_vec;
20760 vec<tree, va_gc> *init_vec;
20761 tree ret;
20762 location_t loc = EXPR_LOCATION (t);
20764 if (placement == NULL_TREE)
20765 placement_vec = NULL;
20766 else if (placement == error_mark_node)
20767 RETURN (error_mark_node);
20768 else
20770 placement_vec = make_tree_vector ();
20771 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20772 vec_safe_push (placement_vec, TREE_VALUE (placement));
20775 /* If there was an initializer in the original tree, but it
20776 instantiated to an empty list, then we should pass a
20777 non-NULL empty vector to tell build_new that it was an
20778 empty initializer() rather than no initializer. This can
20779 only happen when the initializer is a pack expansion whose
20780 parameter packs are of length zero. */
20781 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20782 init_vec = NULL;
20783 else if (init == error_mark_node)
20784 RETURN (error_mark_node);
20785 else
20787 init_vec = make_tree_vector ();
20788 if (init == void_node)
20789 gcc_assert (init_vec != NULL);
20790 else
20792 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20793 vec_safe_push (init_vec, TREE_VALUE (init));
20797 /* Avoid passing an enclosing decl to valid_array_size_p. */
20798 in_decl = NULL_TREE;
20800 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20801 tree op2 = RECUR (TREE_OPERAND (t, 2));
20802 ret = build_new (loc, &placement_vec, op1, op2,
20803 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20804 complain);
20806 if (placement_vec != NULL)
20807 release_tree_vector (placement_vec);
20808 if (init_vec != NULL)
20809 release_tree_vector (init_vec);
20811 RETURN (ret);
20814 case DELETE_EXPR:
20816 tree op0 = RECUR (TREE_OPERAND (t, 0));
20817 tree op1 = RECUR (TREE_OPERAND (t, 1));
20818 RETURN (delete_sanity (input_location, op0, op1,
20819 DELETE_EXPR_USE_VEC (t),
20820 DELETE_EXPR_USE_GLOBAL (t),
20821 complain));
20824 case COMPOUND_EXPR:
20826 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20827 complain & ~tf_decltype, in_decl,
20828 /*function_p=*/false,
20829 integral_constant_expression_p);
20830 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20831 op0,
20832 RECUR (TREE_OPERAND (t, 1)),
20833 templated_operator_saved_lookups (t),
20834 complain|decltype_flag));
20837 case CALL_EXPR:
20839 tree function;
20840 unsigned int nargs;
20841 bool qualified_p;
20842 bool koenig_p;
20843 tree ret;
20845 function = CALL_EXPR_FN (t);
20846 /* Internal function with no arguments. */
20847 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20848 RETURN (t);
20850 /* When we parsed the expression, we determined whether or
20851 not Koenig lookup should be performed. */
20852 koenig_p = KOENIG_LOOKUP_P (t);
20853 if (function == NULL_TREE)
20855 koenig_p = false;
20856 qualified_p = false;
20858 else if (TREE_CODE (function) == SCOPE_REF)
20860 qualified_p = true;
20861 function = tsubst_qualified_id (function, args, complain, in_decl,
20862 /*done=*/false,
20863 /*address_p=*/false);
20865 else if (koenig_p
20866 && (identifier_p (function)
20867 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20868 && identifier_p (TREE_OPERAND (function, 0)))))
20870 /* Do nothing; calling tsubst_copy_and_build on an identifier
20871 would incorrectly perform unqualified lookup again.
20873 Note that we can also have an IDENTIFIER_NODE if the earlier
20874 unqualified lookup found a member function; in that case
20875 koenig_p will be false and we do want to do the lookup
20876 again to find the instantiated member function.
20878 FIXME but doing that causes c++/15272, so we need to stop
20879 using IDENTIFIER_NODE in that situation. */
20880 qualified_p = false;
20882 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20883 /* Use tsubst_copy to substitute through the template arguments
20884 of the template-id without performing unqualified lookup of
20885 the template name. */
20886 function = tsubst_copy (function, args, complain, in_decl);
20888 else
20890 if (TREE_CODE (function) == COMPONENT_REF)
20892 tree op = TREE_OPERAND (function, 1);
20894 qualified_p = (TREE_CODE (op) == SCOPE_REF
20895 || (BASELINK_P (op)
20896 && BASELINK_QUALIFIED_P (op)));
20898 else
20899 qualified_p = false;
20901 if (TREE_CODE (function) == ADDR_EXPR
20902 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20903 /* Avoid error about taking the address of a constructor. */
20904 function = TREE_OPERAND (function, 0);
20906 tsubst_flags_t subcomplain = complain;
20907 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20908 /* When KOENIG_P, we don't want to mark_used the callee before
20909 augmenting the overload set via ADL, so during this initial
20910 substitution we disable mark_used by setting tf_conv (68942). */
20911 subcomplain |= tf_conv;
20912 function = tsubst_copy_and_build (function, args, subcomplain,
20913 in_decl,
20914 !qualified_p,
20915 integral_constant_expression_p);
20917 if (BASELINK_P (function))
20918 qualified_p = true;
20921 nargs = call_expr_nargs (t);
20922 releasing_vec call_args;
20923 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
20924 integral_constant_expression_p,
20925 call_args);
20927 /* Stripped-down processing for a call in a thunk. Specifically, in
20928 the thunk template for a generic lambda. */
20929 if (call_from_lambda_thunk_p (t))
20931 /* Now that we've expanded any packs, the number of call args
20932 might be different. */
20933 unsigned int cargs = call_args->length ();
20934 tree thisarg = NULL_TREE;
20935 if (TREE_CODE (function) == COMPONENT_REF)
20937 thisarg = TREE_OPERAND (function, 0);
20938 if (TREE_CODE (thisarg) == INDIRECT_REF)
20939 thisarg = TREE_OPERAND (thisarg, 0);
20940 function = TREE_OPERAND (function, 1);
20941 if (TREE_CODE (function) == BASELINK)
20942 function = BASELINK_FUNCTIONS (function);
20944 /* We aren't going to do normal overload resolution, so force the
20945 template-id to resolve. */
20946 function = resolve_nondeduced_context (function, complain);
20947 for (unsigned i = 0; i < cargs; ++i)
20949 /* In a thunk, pass through args directly, without any
20950 conversions. */
20951 tree arg = (*call_args)[i];
20952 while (TREE_CODE (arg) != PARM_DECL)
20953 arg = TREE_OPERAND (arg, 0);
20954 (*call_args)[i] = arg;
20956 if (thisarg)
20958 /* If there are no other args, just push 'this'. */
20959 if (cargs == 0)
20960 vec_safe_push (call_args, thisarg);
20961 else
20963 /* Otherwise, shift the other args over to make room. */
20964 tree last = (*call_args)[cargs - 1];
20965 vec_safe_push (call_args, last);
20966 for (int i = cargs - 1; i > 0; --i)
20967 (*call_args)[i] = (*call_args)[i - 1];
20968 (*call_args)[0] = thisarg;
20971 ret = build_call_a (function, call_args->length (),
20972 call_args->address ());
20973 /* The thunk location is not interesting. */
20974 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20975 CALL_FROM_THUNK_P (ret) = true;
20976 if (CLASS_TYPE_P (TREE_TYPE (ret)))
20977 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20979 RETURN (ret);
20982 /* We do not perform argument-dependent lookup if normal
20983 lookup finds a non-function, in accordance with the
20984 resolution of DR 218. */
20985 if (koenig_p
20986 && ((is_overloaded_fn (function)
20987 /* If lookup found a member function, the Koenig lookup is
20988 not appropriate, even if an unqualified-name was used
20989 to denote the function. */
20990 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20991 || identifier_p (function)
20992 /* C++20 P0846: Lookup found nothing. */
20993 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20994 && identifier_p (TREE_OPERAND (function, 0))))
20995 /* Only do this when substitution turns a dependent call
20996 into a non-dependent call. */
20997 && type_dependent_expression_p_push (t)
20998 && !any_type_dependent_arguments_p (call_args))
20999 function = perform_koenig_lookup (function, call_args, tf_none);
21001 if (function != NULL_TREE
21002 && (identifier_p (function)
21003 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21004 && identifier_p (TREE_OPERAND (function, 0))
21005 && !any_dependent_template_arguments_p (TREE_OPERAND
21006 (function, 1))))
21007 && !any_type_dependent_arguments_p (call_args))
21009 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21010 if (template_id_p)
21011 function = TREE_OPERAND (function, 0);
21012 if (koenig_p && (complain & tf_warning_or_error))
21014 /* For backwards compatibility and good diagnostics, try
21015 the unqualified lookup again if we aren't in SFINAE
21016 context. */
21017 tree unq = (tsubst_copy_and_build
21018 (function, args, complain, in_decl, true,
21019 integral_constant_expression_p));
21020 if (unq == error_mark_node)
21021 RETURN (error_mark_node);
21023 if (unq != function)
21025 char const *const msg
21026 = G_("%qD was not declared in this scope, "
21027 "and no declarations were found by "
21028 "argument-dependent lookup at the point "
21029 "of instantiation");
21031 bool in_lambda = (current_class_type
21032 && LAMBDA_TYPE_P (current_class_type));
21033 /* In a lambda fn, we have to be careful to not
21034 introduce new this captures. Legacy code can't
21035 be using lambdas anyway, so it's ok to be
21036 stricter. Be strict with C++20 template-id ADL too. */
21037 bool strict = in_lambda || template_id_p;
21038 bool diag = true;
21039 if (strict)
21040 error_at (cp_expr_loc_or_input_loc (t),
21041 msg, function);
21042 else
21043 diag = permerror (cp_expr_loc_or_input_loc (t),
21044 msg, function);
21045 if (diag)
21047 tree fn = unq;
21049 if (INDIRECT_REF_P (fn))
21050 fn = TREE_OPERAND (fn, 0);
21051 if (is_overloaded_fn (fn))
21052 fn = get_first_fn (fn);
21054 if (!DECL_P (fn))
21055 /* Can't say anything more. */;
21056 else if (DECL_CLASS_SCOPE_P (fn))
21058 location_t loc = cp_expr_loc_or_input_loc (t);
21059 inform (loc,
21060 "declarations in dependent base %qT are "
21061 "not found by unqualified lookup",
21062 DECL_CLASS_CONTEXT (fn));
21063 if (current_class_ptr)
21064 inform (loc,
21065 "use %<this->%D%> instead", function);
21066 else
21067 inform (loc,
21068 "use %<%T::%D%> instead",
21069 current_class_name, function);
21071 else
21072 inform (DECL_SOURCE_LOCATION (fn),
21073 "%qD declared here, later in the "
21074 "translation unit", fn);
21075 if (strict)
21076 RETURN (error_mark_node);
21079 function = unq;
21082 if (identifier_p (function))
21084 if (complain & tf_error)
21085 unqualified_name_lookup_error (function);
21086 RETURN (error_mark_node);
21090 /* Remember that there was a reference to this entity. */
21091 if (function != NULL_TREE)
21093 tree inner = function;
21094 if (TREE_CODE (inner) == ADDR_EXPR
21095 && TREE_CODE (TREE_OPERAND (inner, 0)) == FUNCTION_DECL)
21096 /* We should already have called mark_used when taking the
21097 address of this function, but do so again anyway to make
21098 sure it's odr-used: at worst this is a no-op, but if we
21099 obtained this FUNCTION_DECL as part of ahead-of-time overload
21100 resolution then that call to mark_used wouldn't have marked it
21101 odr-used yet (53164). */
21102 inner = TREE_OPERAND (inner, 0);
21103 if (DECL_P (inner)
21104 && !mark_used (inner, complain) && !(complain & tf_error))
21105 RETURN (error_mark_node);
21108 if (!maybe_fold_fn_template_args (function, complain))
21109 return error_mark_node;
21111 /* Put back tf_decltype for the actual call. */
21112 complain |= decltype_flag;
21114 if (function == NULL_TREE)
21115 switch (CALL_EXPR_IFN (t))
21117 case IFN_LAUNDER:
21118 gcc_assert (nargs == 1);
21119 if (vec_safe_length (call_args) != 1)
21121 error_at (cp_expr_loc_or_input_loc (t),
21122 "wrong number of arguments to "
21123 "%<__builtin_launder%>");
21124 ret = error_mark_node;
21126 else
21127 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21128 (*call_args)[0], complain);
21129 break;
21131 case IFN_VEC_CONVERT:
21132 gcc_assert (nargs == 1);
21133 if (vec_safe_length (call_args) != 1)
21135 error_at (cp_expr_loc_or_input_loc (t),
21136 "wrong number of arguments to "
21137 "%<__builtin_convertvector%>");
21138 ret = error_mark_node;
21139 break;
21141 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21142 tsubst (TREE_TYPE (t), args,
21143 complain, in_decl),
21144 complain);
21145 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21146 RETURN (ret);
21147 break;
21149 case IFN_SHUFFLEVECTOR:
21151 ret = build_x_shufflevector (input_location, call_args,
21152 complain);
21153 if (ret != error_mark_node)
21154 RETURN (ret);
21155 break;
21158 default:
21159 /* Unsupported internal function with arguments. */
21160 gcc_unreachable ();
21162 else if (TREE_CODE (function) == OFFSET_REF
21163 || TREE_CODE (function) == DOTSTAR_EXPR
21164 || TREE_CODE (function) == MEMBER_REF)
21165 ret = build_offset_ref_call_from_tree (function, &call_args,
21166 complain);
21167 else if (TREE_CODE (function) == COMPONENT_REF)
21169 tree instance = TREE_OPERAND (function, 0);
21170 tree fn = TREE_OPERAND (function, 1);
21172 if (processing_template_decl
21173 && (type_dependent_expression_p (instance)
21174 || (!BASELINK_P (fn)
21175 && TREE_CODE (fn) != FIELD_DECL)
21176 || type_dependent_expression_p (fn)
21177 || any_type_dependent_arguments_p (call_args)))
21178 ret = build_min_nt_call_vec (function, call_args);
21179 else if (!BASELINK_P (fn))
21180 ret = finish_call_expr (function, &call_args,
21181 /*disallow_virtual=*/false,
21182 /*koenig_p=*/false,
21183 complain);
21184 else
21185 ret = (build_new_method_call
21186 (instance, fn,
21187 &call_args, NULL_TREE,
21188 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21189 /*fn_p=*/NULL,
21190 complain));
21192 else if (concept_check_p (function))
21194 /* FUNCTION is a template-id referring to a concept definition. */
21195 tree id = unpack_concept_check (function);
21196 tree tmpl = TREE_OPERAND (id, 0);
21197 tree args = TREE_OPERAND (id, 1);
21199 /* Calls to standard and variable concepts should have been
21200 previously diagnosed. */
21201 gcc_assert (function_concept_p (tmpl));
21203 /* Ensure the result is wrapped as a call expression. */
21204 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21206 else
21207 ret = finish_call_expr (function, &call_args,
21208 /*disallow_virtual=*/qualified_p,
21209 koenig_p,
21210 complain);
21212 if (ret != error_mark_node)
21214 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21215 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21216 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21217 if (op || ord || rev)
21218 if (tree call = extract_call_expr (ret))
21220 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21221 CALL_EXPR_ORDERED_ARGS (call) = ord;
21222 CALL_EXPR_REVERSE_ARGS (call) = rev;
21224 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21225 /* This also suppresses -Wredundant-move. */
21226 suppress_warning (ret, OPT_Wpessimizing_move);
21229 RETURN (ret);
21232 case COND_EXPR:
21234 tree cond = RECUR (TREE_OPERAND (t, 0));
21235 cond = mark_rvalue_use (cond);
21236 tree folded_cond = fold_non_dependent_expr (cond, complain);
21237 tree exp1, exp2;
21239 if (TREE_CODE (folded_cond) == INTEGER_CST)
21241 if (integer_zerop (folded_cond))
21243 ++c_inhibit_evaluation_warnings;
21244 exp1 = RECUR (TREE_OPERAND (t, 1));
21245 --c_inhibit_evaluation_warnings;
21246 exp2 = RECUR (TREE_OPERAND (t, 2));
21248 else
21250 exp1 = RECUR (TREE_OPERAND (t, 1));
21251 ++c_inhibit_evaluation_warnings;
21252 exp2 = RECUR (TREE_OPERAND (t, 2));
21253 --c_inhibit_evaluation_warnings;
21255 cond = folded_cond;
21257 else
21259 exp1 = RECUR (TREE_OPERAND (t, 1));
21260 exp2 = RECUR (TREE_OPERAND (t, 2));
21263 warning_sentinel s(warn_duplicated_branches);
21264 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21265 cond, exp1, exp2, complain));
21268 case PSEUDO_DTOR_EXPR:
21270 tree op0 = RECUR (TREE_OPERAND (t, 0));
21271 tree op1 = RECUR (TREE_OPERAND (t, 1));
21272 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21273 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21274 input_location));
21277 case TREE_LIST:
21278 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21280 case COMPONENT_REF:
21282 tree object;
21283 tree object_type;
21284 tree member;
21285 tree r;
21287 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21288 args, complain, in_decl);
21289 /* Remember that there was a reference to this entity. */
21290 if (DECL_P (object)
21291 && !mark_used (object, complain) && !(complain & tf_error))
21292 RETURN (error_mark_node);
21293 object_type = TREE_TYPE (object);
21295 member = TREE_OPERAND (t, 1);
21296 if (BASELINK_P (member))
21297 member = tsubst_baselink (member,
21298 non_reference (TREE_TYPE (object)),
21299 args, complain, in_decl);
21300 else
21301 member = tsubst_copy (member, args, complain, in_decl);
21302 if (member == error_mark_node)
21303 RETURN (error_mark_node);
21305 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21306 && TREE_CODE (member) == FIELD_DECL)
21308 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21309 RETURN (r);
21311 else if (TREE_CODE (member) == FIELD_DECL)
21313 r = finish_non_static_data_member (member, object, NULL_TREE,
21314 complain);
21315 if (TREE_CODE (r) == COMPONENT_REF)
21316 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21317 RETURN (r);
21319 else if (type_dependent_expression_p (object))
21320 /* We can't do much here. */;
21321 else if (!CLASS_TYPE_P (object_type))
21323 if (scalarish_type_p (object_type))
21325 tree s = NULL_TREE;
21326 tree dtor = member;
21328 if (TREE_CODE (dtor) == SCOPE_REF)
21330 s = TREE_OPERAND (dtor, 0);
21331 dtor = TREE_OPERAND (dtor, 1);
21333 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21335 dtor = TREE_OPERAND (dtor, 0);
21336 if (TYPE_P (dtor))
21337 RETURN (finish_pseudo_destructor_expr
21338 (object, s, dtor, input_location));
21342 else if (TREE_CODE (member) == SCOPE_REF
21343 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21345 /* Lookup the template functions now that we know what the
21346 scope is. */
21347 tree scope = TREE_OPERAND (member, 0);
21348 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21349 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21350 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21351 /*complain=*/false);
21352 if (BASELINK_P (member))
21354 BASELINK_FUNCTIONS (member)
21355 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21356 args);
21357 member = (adjust_result_of_qualified_name_lookup
21358 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21359 object_type));
21361 else
21363 qualified_name_lookup_error (scope, tmpl, member,
21364 input_location);
21365 RETURN (error_mark_node);
21368 else if (TREE_CODE (member) == SCOPE_REF
21369 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21370 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21372 if (complain & tf_error)
21374 if (TYPE_P (TREE_OPERAND (member, 0)))
21375 error ("%qT is not a class or namespace",
21376 TREE_OPERAND (member, 0));
21377 else
21378 error ("%qD is not a class or namespace",
21379 TREE_OPERAND (member, 0));
21381 RETURN (error_mark_node);
21384 r = finish_class_member_access_expr (object, member,
21385 /*template_p=*/false,
21386 complain);
21387 if (TREE_CODE (r) == COMPONENT_REF)
21388 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21389 RETURN (r);
21392 case THROW_EXPR:
21393 RETURN (build_throw
21394 (input_location, RECUR (TREE_OPERAND (t, 0))));
21396 case CONSTRUCTOR:
21398 vec<constructor_elt, va_gc> *n;
21399 constructor_elt *ce;
21400 unsigned HOST_WIDE_INT idx;
21401 bool process_index_p;
21402 int newlen;
21403 bool need_copy_p = false;
21404 tree r;
21406 tsubst_flags_t tcomplain = complain;
21407 if (COMPOUND_LITERAL_P (t))
21408 tcomplain |= tf_tst_ok;
21409 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21410 if (type == error_mark_node)
21411 RETURN (error_mark_node);
21413 /* We do not want to process the index of aggregate
21414 initializers as they are identifier nodes which will be
21415 looked up by digest_init. */
21416 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21418 if (null_member_pointer_value_p (t))
21420 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21421 RETURN (t);
21424 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21425 newlen = vec_safe_length (n);
21426 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21428 if (ce->index && process_index_p
21429 /* An identifier index is looked up in the type
21430 being initialized, not the current scope. */
21431 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21432 ce->index = RECUR (ce->index);
21434 if (PACK_EXPANSION_P (ce->value))
21436 /* Substitute into the pack expansion. */
21437 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21438 in_decl);
21440 if (ce->value == error_mark_node
21441 || PACK_EXPANSION_P (ce->value))
21443 else if (TREE_VEC_LENGTH (ce->value) == 1)
21444 /* Just move the argument into place. */
21445 ce->value = TREE_VEC_ELT (ce->value, 0);
21446 else
21448 /* Update the length of the final CONSTRUCTOR
21449 arguments vector, and note that we will need to
21450 copy.*/
21451 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21452 need_copy_p = true;
21455 else
21456 ce->value = RECUR (ce->value);
21459 if (need_copy_p)
21461 vec<constructor_elt, va_gc> *old_n = n;
21463 vec_alloc (n, newlen);
21464 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21466 if (TREE_CODE (ce->value) == TREE_VEC)
21468 int i, len = TREE_VEC_LENGTH (ce->value);
21469 for (i = 0; i < len; ++i)
21470 CONSTRUCTOR_APPEND_ELT (n, 0,
21471 TREE_VEC_ELT (ce->value, i));
21473 else
21474 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21478 r = build_constructor (init_list_type_node, n);
21479 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21480 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21481 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21483 if (TREE_HAS_CONSTRUCTOR (t))
21485 fcl_t cl = fcl_functional;
21486 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21487 cl = fcl_c99;
21488 RETURN (finish_compound_literal (type, r, complain, cl));
21491 TREE_TYPE (r) = type;
21492 RETURN (r);
21495 case TYPEID_EXPR:
21497 tree operand_0 = TREE_OPERAND (t, 0);
21498 if (TYPE_P (operand_0))
21500 operand_0 = tsubst (operand_0, args, complain, in_decl);
21501 RETURN (get_typeid (operand_0, complain));
21503 else
21505 operand_0 = RECUR (operand_0);
21506 RETURN (build_typeid (operand_0, complain));
21510 case VAR_DECL:
21511 if (!args)
21512 RETURN (t);
21513 /* Fall through */
21515 case PARM_DECL:
21517 tree r = tsubst_copy (t, args, complain, in_decl);
21518 /* ??? We're doing a subset of finish_id_expression here. */
21519 if (tree wrap = maybe_get_tls_wrapper_call (r))
21520 /* Replace an evaluated use of the thread_local variable with
21521 a call to its wrapper. */
21522 r = wrap;
21523 else if (outer_automatic_var_p (r))
21524 r = process_outer_var_ref (r, complain);
21526 if (!TYPE_REF_P (TREE_TYPE (t)))
21527 /* If the original type was a reference, we'll be wrapped in
21528 the appropriate INDIRECT_REF. */
21529 r = convert_from_reference (r);
21530 RETURN (r);
21533 case VA_ARG_EXPR:
21535 tree op0 = RECUR (TREE_OPERAND (t, 0));
21536 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21537 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21540 case OFFSETOF_EXPR:
21542 tree object_ptr
21543 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
21544 in_decl, /*function_p=*/false,
21545 /*integral_constant_expression_p=*/false);
21546 RETURN (finish_offsetof (object_ptr,
21547 RECUR (TREE_OPERAND (t, 0)),
21548 EXPR_LOCATION (t)));
21551 case ADDRESSOF_EXPR:
21552 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21553 RECUR (TREE_OPERAND (t, 0)), complain));
21555 case TRAIT_EXPR:
21557 tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
21558 complain, in_decl);
21559 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21560 complain, in_decl);
21561 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21562 TRAIT_EXPR_KIND (t), type1, type2));
21565 case STMT_EXPR:
21567 tree old_stmt_expr = cur_stmt_expr;
21568 tree stmt_expr = begin_stmt_expr ();
21570 cur_stmt_expr = stmt_expr;
21571 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
21572 integral_constant_expression_p);
21573 stmt_expr = finish_stmt_expr (stmt_expr, false);
21574 cur_stmt_expr = old_stmt_expr;
21576 /* If the resulting list of expression statement is empty,
21577 fold it further into void_node. */
21578 if (empty_expr_stmt_p (stmt_expr))
21579 stmt_expr = void_node;
21581 RETURN (stmt_expr);
21584 case LAMBDA_EXPR:
21586 if (complain & tf_partial)
21588 /* We don't have a full set of template arguments yet; don't touch
21589 the lambda at all. */
21590 gcc_assert (processing_template_decl);
21591 return t;
21593 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21595 RETURN (build_lambda_object (r));
21598 case TRANSACTION_EXPR:
21599 RETURN (tsubst_expr(t, args, complain, in_decl,
21600 integral_constant_expression_p));
21602 case PAREN_EXPR:
21603 if (REF_PARENTHESIZED_P (t))
21604 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21605 else
21606 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21608 tree op0 = RECUR (TREE_OPERAND (t, 0));
21609 RETURN (build1_loc (input_location, PAREN_EXPR,
21610 TREE_TYPE (op0), op0));
21613 case VEC_PERM_EXPR:
21615 tree op0 = RECUR (TREE_OPERAND (t, 0));
21616 tree op1 = RECUR (TREE_OPERAND (t, 1));
21617 tree op2 = RECUR (TREE_OPERAND (t, 2));
21618 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21619 complain));
21622 case REQUIRES_EXPR:
21624 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21625 RETURN (r);
21628 case RANGE_EXPR:
21629 /* No need to substitute further, a RANGE_EXPR will always be built
21630 with constant operands. */
21631 RETURN (t);
21633 case NON_LVALUE_EXPR:
21634 case VIEW_CONVERT_EXPR:
21635 if (location_wrapper_p (t))
21636 /* We need to do this here as well as in tsubst_copy so we get the
21637 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21638 RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
21639 EXPR_LOCATION (t)));
21640 /* fallthrough. */
21642 default:
21643 /* Handle Objective-C++ constructs, if appropriate. */
21645 tree subst
21646 = objcp_tsubst_copy_and_build (t, args, complain,
21647 in_decl, /*function_p=*/false);
21648 if (subst)
21649 RETURN (subst);
21651 RETURN (tsubst_copy (t, args, complain, in_decl));
21654 #undef RECUR
21655 #undef RETURN
21656 out:
21657 input_location = save_loc;
21658 return retval;
21661 /* Verify that the instantiated ARGS are valid. For type arguments,
21662 make sure that the type's linkage is ok. For non-type arguments,
21663 make sure they are constants if they are integral or enumerations.
21664 Emit an error under control of COMPLAIN, and return TRUE on error. */
21666 static bool
21667 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21669 if (dependent_template_arg_p (t))
21670 return false;
21671 if (ARGUMENT_PACK_P (t))
21673 tree vec = ARGUMENT_PACK_ARGS (t);
21674 int len = TREE_VEC_LENGTH (vec);
21675 bool result = false;
21676 int i;
21678 for (i = 0; i < len; ++i)
21679 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21680 result = true;
21681 return result;
21683 else if (TYPE_P (t))
21685 /* [basic.link]: A name with no linkage (notably, the name
21686 of a class or enumeration declared in a local scope)
21687 shall not be used to declare an entity with linkage.
21688 This implies that names with no linkage cannot be used as
21689 template arguments
21691 DR 757 relaxes this restriction for C++0x. */
21692 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21693 : no_linkage_check (t, /*relaxed_p=*/false));
21695 if (nt)
21697 /* DR 488 makes use of a type with no linkage cause
21698 type deduction to fail. */
21699 if (complain & tf_error)
21701 if (TYPE_UNNAMED_P (nt))
21702 error ("%qT is/uses unnamed type", t);
21703 else
21704 error ("template argument for %qD uses local type %qT",
21705 tmpl, t);
21707 return true;
21709 /* In order to avoid all sorts of complications, we do not
21710 allow variably-modified types as template arguments. */
21711 else if (variably_modified_type_p (t, NULL_TREE))
21713 if (complain & tf_error)
21714 error ("%qT is a variably modified type", t);
21715 return true;
21718 /* Class template and alias template arguments should be OK. */
21719 else if (DECL_TYPE_TEMPLATE_P (t))
21721 /* A non-type argument of integral or enumerated type must be a
21722 constant. */
21723 else if (TREE_TYPE (t)
21724 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21725 && !REFERENCE_REF_P (t)
21726 && !TREE_CONSTANT (t))
21728 if (complain & tf_error)
21729 error ("integral expression %qE is not constant", t);
21730 return true;
21732 return false;
21735 static bool
21736 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21738 int ix, len = DECL_NTPARMS (tmpl);
21739 bool result = false;
21741 for (ix = 0; ix != len; ix++)
21743 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21744 result = true;
21746 if (result && (complain & tf_error))
21747 error (" trying to instantiate %qD", tmpl);
21748 return result;
21751 /* We're out of SFINAE context now, so generate diagnostics for the access
21752 errors we saw earlier when instantiating D from TMPL and ARGS. */
21754 static void
21755 recheck_decl_substitution (tree d, tree tmpl, tree args)
21757 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21758 tree type = TREE_TYPE (pattern);
21759 location_t loc = input_location;
21761 push_access_scope (d);
21762 push_deferring_access_checks (dk_no_deferred);
21763 input_location = DECL_SOURCE_LOCATION (pattern);
21764 tsubst (type, args, tf_warning_or_error, d);
21765 input_location = loc;
21766 pop_deferring_access_checks ();
21767 pop_access_scope (d);
21770 /* Instantiate the indicated variable, function, or alias template TMPL with
21771 the template arguments in TARG_PTR. */
21773 tree
21774 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21776 auto_timevar tv (TV_TEMPLATE_INST);
21778 tree targ_ptr = orig_args;
21779 tree fndecl;
21780 tree gen_tmpl;
21781 tree spec;
21782 bool access_ok = true;
21784 if (tmpl == error_mark_node)
21785 return error_mark_node;
21787 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21789 if (modules_p ())
21790 lazy_load_pendings (tmpl);
21792 /* If this function is a clone, handle it specially. */
21793 if (DECL_CLONED_FUNCTION_P (tmpl))
21795 tree spec;
21796 tree clone;
21798 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21799 DECL_CLONED_FUNCTION. */
21800 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21801 targ_ptr, complain);
21802 if (spec == error_mark_node)
21803 return error_mark_node;
21805 /* Look for the clone. */
21806 FOR_EACH_CLONE (clone, spec)
21807 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21808 return clone;
21809 /* We should always have found the clone by now. */
21810 gcc_unreachable ();
21811 return NULL_TREE;
21814 if (targ_ptr == error_mark_node)
21815 return error_mark_node;
21817 /* Check to see if we already have this specialization. */
21818 gen_tmpl = most_general_template (tmpl);
21819 if (TMPL_ARGS_DEPTH (targ_ptr)
21820 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21821 /* targ_ptr only has the innermost template args, so add the outer ones
21822 from tmpl, which could be either a partial instantiation or gen_tmpl (in
21823 the case of a non-dependent call within a template definition). */
21824 targ_ptr = (add_outermost_template_args
21825 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21826 targ_ptr));
21828 /* It would be nice to avoid hashing here and then again in tsubst_decl,
21829 but it doesn't seem to be on the hot path. */
21830 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21832 gcc_checking_assert (tmpl == gen_tmpl
21833 || ((fndecl
21834 = retrieve_specialization (tmpl, orig_args, 0))
21835 == spec)
21836 || fndecl == NULL_TREE);
21838 if (spec != NULL_TREE)
21840 if (FNDECL_HAS_ACCESS_ERRORS (spec))
21842 if (complain & tf_error)
21843 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21844 return error_mark_node;
21846 return spec;
21849 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21850 complain))
21851 return error_mark_node;
21853 /* We are building a FUNCTION_DECL, during which the access of its
21854 parameters and return types have to be checked. However this
21855 FUNCTION_DECL which is the desired context for access checking
21856 is not built yet. We solve this chicken-and-egg problem by
21857 deferring all checks until we have the FUNCTION_DECL. */
21858 push_deferring_access_checks (dk_deferred);
21860 /* Instantiation of the function happens in the context of the function
21861 template, not the context of the overload resolution we're doing. */
21862 push_to_top_level ();
21863 /* If there are dependent arguments, e.g. because we're doing partial
21864 ordering, make sure processing_template_decl stays set. */
21865 if (uses_template_parms (targ_ptr))
21866 ++processing_template_decl;
21867 if (DECL_CLASS_SCOPE_P (gen_tmpl))
21869 tree ctx;
21870 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
21871 /* If the context of the partially instantiated template is
21872 already non-dependent, then we might as well use it. */
21873 ctx = DECL_CONTEXT (tmpl);
21874 else
21875 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21876 complain, gen_tmpl, true);
21877 push_nested_class (ctx);
21880 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21882 fndecl = NULL_TREE;
21883 if (VAR_P (pattern))
21885 /* We need to determine if we're using a partial or explicit
21886 specialization now, because the type of the variable could be
21887 different. */
21888 tree tid = lookup_template_variable (tmpl, targ_ptr);
21889 tree elt = most_specialized_partial_spec (tid, complain);
21890 if (elt == error_mark_node)
21891 pattern = error_mark_node;
21892 else if (elt)
21894 tree partial_tmpl = TREE_VALUE (elt);
21895 tree partial_args = TREE_PURPOSE (elt);
21896 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21897 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21901 /* Substitute template parameters to obtain the specialization. */
21902 if (fndecl == NULL_TREE)
21903 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21904 if (DECL_CLASS_SCOPE_P (gen_tmpl))
21905 pop_nested_class ();
21906 pop_from_top_level ();
21908 if (fndecl == error_mark_node)
21910 pop_deferring_access_checks ();
21911 return error_mark_node;
21914 /* The DECL_TI_TEMPLATE should always be the immediate parent
21915 template, not the most general template. */
21916 DECL_TI_TEMPLATE (fndecl) = tmpl;
21917 DECL_TI_ARGS (fndecl) = targ_ptr;
21919 set_instantiating_module (fndecl);
21921 /* Now we know the specialization, compute access previously
21922 deferred. Do no access control for inheriting constructors,
21923 as we already checked access for the inherited constructor. */
21924 if (!(flag_new_inheriting_ctors
21925 && DECL_INHERITED_CTOR (fndecl)))
21927 push_access_scope (fndecl);
21928 if (!perform_deferred_access_checks (complain))
21929 access_ok = false;
21930 pop_access_scope (fndecl);
21932 pop_deferring_access_checks ();
21934 /* If we've just instantiated the main entry point for a function,
21935 instantiate all the alternate entry points as well. We do this
21936 by cloning the instantiation of the main entry point, not by
21937 instantiating the template clones. */
21938 if (tree chain = DECL_CHAIN (gen_tmpl))
21939 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21940 clone_cdtor (fndecl, /*update_methods=*/false);
21942 if (!access_ok)
21944 if (!(complain & tf_error))
21946 /* Remember to reinstantiate when we're out of SFINAE so the user
21947 can see the errors. */
21948 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21950 return error_mark_node;
21952 return fndecl;
21955 /* Instantiate the alias template TMPL with ARGS. Also push a template
21956 instantiation level, which instantiate_template doesn't do because
21957 functions and variables have sufficient context established by the
21958 callers. */
21960 static tree
21961 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21963 if (tmpl == error_mark_node || args == error_mark_node)
21964 return error_mark_node;
21966 args =
21967 coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21968 args, tmpl, complain,
21969 /*require_all_args=*/true,
21970 /*use_default_args=*/true);
21972 /* FIXME check for satisfaction in check_instantiated_args. */
21973 if (flag_concepts
21974 && !any_dependent_template_arguments_p (args)
21975 && !constraints_satisfied_p (tmpl, args))
21977 if (complain & tf_error)
21979 auto_diagnostic_group d;
21980 error ("template constraint failure for %qD", tmpl);
21981 diagnose_constraints (input_location, tmpl, args);
21983 return error_mark_node;
21986 if (!push_tinst_level (tmpl, args))
21987 return error_mark_node;
21988 tree r = instantiate_template (tmpl, args, complain);
21989 pop_tinst_level ();
21991 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21993 /* An alias template specialization can be dependent
21994 even if its underlying type is not. */
21995 TYPE_DEPENDENT_P (d) = true;
21996 TYPE_DEPENDENT_P_VALID (d) = true;
21997 /* Sometimes a dependent alias spec is equivalent to its expansion,
21998 sometimes not. So always use structural_comptypes. */
21999 SET_TYPE_STRUCTURAL_EQUALITY (d);
22002 return r;
22005 /* PARM is a template parameter pack for FN. Returns true iff
22006 PARM is used in a deducible way in the argument list of FN. */
22008 static bool
22009 pack_deducible_p (tree parm, tree fn)
22011 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22012 for (; t; t = TREE_CHAIN (t))
22014 tree type = TREE_VALUE (t);
22015 tree packs;
22016 if (!PACK_EXPANSION_P (type))
22017 continue;
22018 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22019 packs; packs = TREE_CHAIN (packs))
22020 if (template_args_equal (TREE_VALUE (packs), parm))
22022 /* The template parameter pack is used in a function parameter
22023 pack. If this is the end of the parameter list, the
22024 template parameter pack is deducible. */
22025 if (TREE_CHAIN (t) == void_list_node)
22026 return true;
22027 else
22028 /* Otherwise, not. Well, it could be deduced from
22029 a non-pack parameter, but doing so would end up with
22030 a deduction mismatch, so don't bother. */
22031 return false;
22034 /* The template parameter pack isn't used in any function parameter
22035 packs, but it might be used deeper, e.g. tuple<Args...>. */
22036 return true;
22039 /* Subroutine of fn_type_unification: check non-dependent parms for
22040 convertibility. */
22042 static int
22043 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22044 tree fn, unification_kind_t strict, int flags,
22045 struct conversion **convs, bool explain_p)
22047 /* Non-constructor methods need to leave a conversion for 'this', which
22048 isn't included in nargs here. */
22049 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22050 && !DECL_CONSTRUCTOR_P (fn));
22052 for (unsigned ia = 0;
22053 parms && parms != void_list_node && ia < nargs; )
22055 tree parm = TREE_VALUE (parms);
22057 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22058 && (!TREE_CHAIN (parms)
22059 || TREE_CHAIN (parms) == void_list_node))
22060 /* For a function parameter pack that occurs at the end of the
22061 parameter-declaration-list, the type A of each remaining
22062 argument of the call is compared with the type P of the
22063 declarator-id of the function parameter pack. */
22064 break;
22066 parms = TREE_CHAIN (parms);
22068 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22069 /* For a function parameter pack that does not occur at the
22070 end of the parameter-declaration-list, the type of the
22071 parameter pack is a non-deduced context. */
22072 continue;
22074 if (!uses_template_parms (parm))
22076 tree arg = args[ia];
22077 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22078 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22080 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22081 conv_p, explain_p))
22082 return 1;
22085 ++ia;
22088 return 0;
22091 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22092 NARGS elements of the arguments that are being used when calling
22093 it. TARGS is a vector into which the deduced template arguments
22094 are placed.
22096 Returns either a FUNCTION_DECL for the matching specialization of FN or
22097 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22098 true, diagnostics will be printed to explain why it failed.
22100 If FN is a conversion operator, or we are trying to produce a specific
22101 specialization, RETURN_TYPE is the return type desired.
22103 The EXPLICIT_TARGS are explicit template arguments provided via a
22104 template-id.
22106 The parameter STRICT is one of:
22108 DEDUCE_CALL:
22109 We are deducing arguments for a function call, as in
22110 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22111 deducing arguments for a call to the result of a conversion
22112 function template, as in [over.call.object].
22114 DEDUCE_CONV:
22115 We are deducing arguments for a conversion function, as in
22116 [temp.deduct.conv].
22118 DEDUCE_EXACT:
22119 We are deducing arguments when doing an explicit instantiation
22120 as in [temp.explicit], when determining an explicit specialization
22121 as in [temp.expl.spec], or when taking the address of a function
22122 template, as in [temp.deduct.funcaddr]. */
22124 tree
22125 fn_type_unification (tree fn,
22126 tree explicit_targs,
22127 tree targs,
22128 const tree *args,
22129 unsigned int nargs,
22130 tree return_type,
22131 unification_kind_t strict,
22132 int flags,
22133 struct conversion **convs,
22134 bool explain_p,
22135 bool decltype_p)
22137 tree parms;
22138 tree fntype;
22139 tree decl = NULL_TREE;
22140 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22141 bool ok;
22142 static int deduction_depth;
22143 /* type_unification_real will pass back any access checks from default
22144 template argument substitution. */
22145 vec<deferred_access_check, va_gc> *checks = NULL;
22146 /* We don't have all the template args yet. */
22147 bool incomplete = true;
22149 tree orig_fn = fn;
22150 if (flag_new_inheriting_ctors)
22151 fn = strip_inheriting_ctors (fn);
22153 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22154 tree r = error_mark_node;
22156 tree full_targs = targs;
22157 if (TMPL_ARGS_DEPTH (targs)
22158 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22159 full_targs = (add_outermost_template_args
22160 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22161 targs));
22163 if (decltype_p)
22164 complain |= tf_decltype;
22166 /* In C++0x, it's possible to have a function template whose type depends
22167 on itself recursively. This is most obvious with decltype, but can also
22168 occur with enumeration scope (c++/48969). So we need to catch infinite
22169 recursion and reject the substitution at deduction time; this function
22170 will return error_mark_node for any repeated substitution.
22172 This also catches excessive recursion such as when f<N> depends on
22173 f<N-1> across all integers, and returns error_mark_node for all the
22174 substitutions back up to the initial one.
22176 This is, of course, not reentrant. */
22177 if (excessive_deduction_depth)
22178 return error_mark_node;
22179 ++deduction_depth;
22181 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22183 fntype = TREE_TYPE (fn);
22184 if (explicit_targs)
22186 /* [temp.deduct]
22188 The specified template arguments must match the template
22189 parameters in kind (i.e., type, nontype, template), and there
22190 must not be more arguments than there are parameters;
22191 otherwise type deduction fails.
22193 Nontype arguments must match the types of the corresponding
22194 nontype template parameters, or must be convertible to the
22195 types of the corresponding nontype parameters as specified in
22196 _temp.arg.nontype_, otherwise type deduction fails.
22198 All references in the function type of the function template
22199 to the corresponding template parameters are replaced by the
22200 specified template argument values. If a substitution in a
22201 template parameter or in the function type of the function
22202 template results in an invalid type, type deduction fails. */
22203 int i, len = TREE_VEC_LENGTH (tparms);
22204 location_t loc = input_location;
22205 incomplete = false;
22207 if (explicit_targs == error_mark_node)
22208 goto fail;
22210 if (TMPL_ARGS_DEPTH (explicit_targs)
22211 < TMPL_ARGS_DEPTH (full_targs))
22212 explicit_targs = add_outermost_template_args (full_targs,
22213 explicit_targs);
22215 /* Adjust any explicit template arguments before entering the
22216 substitution context. */
22217 explicit_targs
22218 = (coerce_template_parms (tparms, explicit_targs, fn,
22219 complain|tf_partial,
22220 /*require_all_args=*/false,
22221 /*use_default_args=*/false));
22222 if (explicit_targs == error_mark_node)
22223 goto fail;
22225 /* Substitute the explicit args into the function type. This is
22226 necessary so that, for instance, explicitly declared function
22227 arguments can match null pointed constants. If we were given
22228 an incomplete set of explicit args, we must not do semantic
22229 processing during substitution as we could create partial
22230 instantiations. */
22231 for (i = 0; i < len; i++)
22233 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22234 bool parameter_pack = false;
22235 tree targ = TREE_VEC_ELT (explicit_targs, i);
22237 /* Dig out the actual parm. */
22238 if (TREE_CODE (parm) == TYPE_DECL
22239 || TREE_CODE (parm) == TEMPLATE_DECL)
22241 parm = TREE_TYPE (parm);
22242 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22244 else if (TREE_CODE (parm) == PARM_DECL)
22246 parm = DECL_INITIAL (parm);
22247 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22250 if (targ == NULL_TREE)
22251 /* No explicit argument for this template parameter. */
22252 incomplete = true;
22253 else if (parameter_pack && pack_deducible_p (parm, fn))
22255 /* Mark the argument pack as "incomplete". We could
22256 still deduce more arguments during unification.
22257 We remove this mark in type_unification_real. */
22258 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22259 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22260 = ARGUMENT_PACK_ARGS (targ);
22262 /* We have some incomplete argument packs. */
22263 incomplete = true;
22267 if (incomplete)
22269 if (!push_tinst_level (fn, explicit_targs))
22271 excessive_deduction_depth = true;
22272 goto fail;
22274 ++processing_template_decl;
22275 input_location = DECL_SOURCE_LOCATION (fn);
22276 /* Ignore any access checks; we'll see them again in
22277 instantiate_template and they might have the wrong
22278 access path at this point. */
22279 push_deferring_access_checks (dk_deferred);
22280 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22281 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22282 pop_deferring_access_checks ();
22283 input_location = loc;
22284 --processing_template_decl;
22285 pop_tinst_level ();
22287 if (fntype == error_mark_node)
22288 goto fail;
22291 /* Place the explicitly specified arguments in TARGS. */
22292 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22293 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22294 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22295 if (!incomplete && CHECKING_P
22296 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22297 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22298 (targs, NUM_TMPL_ARGS (explicit_targs));
22301 if (return_type && strict != DEDUCE_CALL)
22303 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22304 new_args[0] = return_type;
22305 memcpy (new_args + 1, args, nargs * sizeof (tree));
22306 args = new_args;
22307 ++nargs;
22310 if (!incomplete)
22311 goto deduced;
22313 /* Never do unification on the 'this' parameter. */
22314 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22316 if (return_type && strict == DEDUCE_CALL)
22318 /* We're deducing for a call to the result of a template conversion
22319 function. The parms we really want are in return_type. */
22320 if (INDIRECT_TYPE_P (return_type))
22321 return_type = TREE_TYPE (return_type);
22322 parms = TYPE_ARG_TYPES (return_type);
22324 else if (return_type)
22326 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22329 /* We allow incomplete unification without an error message here
22330 because the standard doesn't seem to explicitly prohibit it. Our
22331 callers must be ready to deal with unification failures in any
22332 event. */
22334 /* If we aren't explaining yet, push tinst context so we can see where
22335 any errors (e.g. from class instantiations triggered by instantiation
22336 of default template arguments) come from. If we are explaining, this
22337 context is redundant. */
22338 if (!explain_p && !push_tinst_level (fn, targs))
22340 excessive_deduction_depth = true;
22341 goto fail;
22344 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22345 full_targs, parms, args, nargs, /*subr=*/0,
22346 strict, &checks, explain_p);
22347 if (!explain_p)
22348 pop_tinst_level ();
22349 if (!ok)
22350 goto fail;
22352 /* Now that we have bindings for all of the template arguments,
22353 ensure that the arguments deduced for the template template
22354 parameters have compatible template parameter lists. We cannot
22355 check this property before we have deduced all template
22356 arguments, because the template parameter types of a template
22357 template parameter might depend on prior template parameters
22358 deduced after the template template parameter. The following
22359 ill-formed example illustrates this issue:
22361 template<typename T, template<T> class C> void f(C<5>, T);
22363 template<int N> struct X {};
22365 void g() {
22366 f(X<5>(), 5l); // error: template argument deduction fails
22369 The template parameter list of 'C' depends on the template type
22370 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22371 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22372 time that we deduce 'C'. */
22373 if (!template_template_parm_bindings_ok_p
22374 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22376 unify_inconsistent_template_template_parameters (explain_p);
22377 goto fail;
22380 deduced:
22382 /* CWG2369: Check satisfaction before non-deducible conversions. */
22383 if (!constraints_satisfied_p (fn, targs))
22385 if (explain_p)
22386 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22387 goto fail;
22390 /* DR 1391: All parameters have args, now check non-dependent parms for
22391 convertibility. We don't do this if all args were explicitly specified,
22392 as the standard says that we substitute explicit args immediately. */
22393 if (incomplete
22394 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22395 convs, explain_p))
22396 goto fail;
22398 /* All is well so far. Now, check:
22400 [temp.deduct]
22402 When all template arguments have been deduced, all uses of
22403 template parameters in nondeduced contexts are replaced with
22404 the corresponding deduced argument values. If the
22405 substitution results in an invalid type, as described above,
22406 type deduction fails. */
22407 if (!push_tinst_level (fn, targs))
22409 excessive_deduction_depth = true;
22410 goto fail;
22413 /* Also collect access checks from the instantiation. */
22414 reopen_deferring_access_checks (checks);
22416 decl = instantiate_template (fn, targs, complain);
22418 checks = get_deferred_access_checks ();
22419 pop_deferring_access_checks ();
22421 pop_tinst_level ();
22423 if (decl == error_mark_node)
22424 goto fail;
22426 /* Now perform any access checks encountered during substitution. */
22427 push_access_scope (decl);
22428 ok = perform_access_checks (checks, complain);
22429 pop_access_scope (decl);
22430 if (!ok)
22431 goto fail;
22433 /* If we're looking for an exact match, check that what we got
22434 is indeed an exact match. It might not be if some template
22435 parameters are used in non-deduced contexts. But don't check
22436 for an exact match if we have dependent template arguments;
22437 in that case we're doing partial ordering, and we already know
22438 that we have two candidates that will provide the actual type. */
22439 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22441 tree substed = TREE_TYPE (decl);
22442 unsigned int i;
22444 tree sarg
22445 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22446 if (return_type)
22447 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22448 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22449 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22451 unify_type_mismatch (explain_p, args[i],
22452 TREE_VALUE (sarg));
22453 goto fail;
22455 if ((i < nargs || sarg)
22456 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22457 doesn't contain the trailing void, and conv fns are always (). */
22458 && !DECL_CONV_FN_P (decl))
22460 unsigned nsargs = i + list_length (sarg);
22461 unify_arity (explain_p, nargs, nsargs);
22462 goto fail;
22466 /* After doing deduction with the inherited constructor, actually return an
22467 instantiation of the inheriting constructor. */
22468 if (orig_fn != fn)
22469 decl = instantiate_template (orig_fn, targs, complain);
22471 r = decl;
22473 fail:
22474 --deduction_depth;
22475 if (excessive_deduction_depth)
22477 if (deduction_depth == 0)
22478 /* Reset once we're all the way out. */
22479 excessive_deduction_depth = false;
22482 return r;
22485 /* Returns true iff PARM is a forwarding reference in the context of
22486 template argument deduction for TMPL. */
22488 static bool
22489 forwarding_reference_p (tree parm, tree tmpl)
22491 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22492 cv-unqualified template parameter ..." */
22493 if (TYPE_REF_P (parm)
22494 && TYPE_REF_IS_RVALUE (parm)
22495 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22496 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22498 parm = TREE_TYPE (parm);
22499 /* [temp.deduct.call], "... that does not represent a template parameter
22500 of a class template (during class template argument deduction)." */
22501 if (tmpl
22502 && deduction_guide_p (tmpl)
22503 && DECL_ARTIFICIAL (tmpl))
22505 /* Since the template parameters of a synthesized guide consist of
22506 the template parameters of the class template followed by those of
22507 the constructor (if any), we can tell if PARM represents a template
22508 parameter of the class template by comparing its index with the
22509 arity of the class template. */
22510 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22511 if (TEMPLATE_TYPE_IDX (parm)
22512 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22513 return false;
22515 return true;
22517 return false;
22520 /* Adjust types before performing type deduction, as described in
22521 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22522 sections are symmetric. PARM is the type of a function parameter
22523 or the return type of the conversion function. ARG is the type of
22524 the argument passed to the call, or the type of the value
22525 initialized with the result of the conversion function.
22526 ARG_EXPR is the original argument expression, which may be null. */
22528 static int
22529 maybe_adjust_types_for_deduction (tree tparms,
22530 unification_kind_t strict,
22531 tree* parm,
22532 tree* arg,
22533 tree arg_expr)
22535 int result = 0;
22537 switch (strict)
22539 case DEDUCE_CALL:
22540 break;
22542 case DEDUCE_CONV:
22543 /* Swap PARM and ARG throughout the remainder of this
22544 function; the handling is precisely symmetric since PARM
22545 will initialize ARG rather than vice versa. */
22546 std::swap (parm, arg);
22547 break;
22549 case DEDUCE_EXACT:
22550 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22551 too, but here handle it by stripping the reference from PARM
22552 rather than by adding it to ARG. */
22553 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22554 && TYPE_REF_P (*arg)
22555 && !TYPE_REF_IS_RVALUE (*arg))
22556 *parm = TREE_TYPE (*parm);
22557 /* Nothing else to do in this case. */
22558 return 0;
22560 default:
22561 gcc_unreachable ();
22564 if (!TYPE_REF_P (*parm))
22566 /* [temp.deduct.call]
22568 If P is not a reference type:
22570 --If A is an array type, the pointer type produced by the
22571 array-to-pointer standard conversion (_conv.array_) is
22572 used in place of A for type deduction; otherwise,
22574 --If A is a function type, the pointer type produced by
22575 the function-to-pointer standard conversion
22576 (_conv.func_) is used in place of A for type deduction;
22577 otherwise,
22579 --If A is a cv-qualified type, the top level
22580 cv-qualifiers of A's type are ignored for type
22581 deduction. */
22582 if (TREE_CODE (*arg) == ARRAY_TYPE)
22583 *arg = build_pointer_type (TREE_TYPE (*arg));
22584 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22585 *arg = build_pointer_type (*arg);
22586 else
22587 *arg = TYPE_MAIN_VARIANT (*arg);
22590 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22591 an lvalue, the type 'lvalue reference to A' is used in place of A for
22592 type deduction." */
22593 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22594 && (arg_expr ? lvalue_p (arg_expr)
22595 /* try_one_overload doesn't provide an arg_expr, but
22596 functions are always lvalues. */
22597 : TREE_CODE (*arg) == FUNCTION_TYPE))
22598 *arg = build_reference_type (*arg);
22600 /* [temp.deduct.call]
22602 If P is a cv-qualified type, the top level cv-qualifiers
22603 of P's type are ignored for type deduction. If P is a
22604 reference type, the type referred to by P is used for
22605 type deduction. */
22606 *parm = TYPE_MAIN_VARIANT (*parm);
22607 if (TYPE_REF_P (*parm))
22609 *parm = TREE_TYPE (*parm);
22610 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22613 /* DR 322. For conversion deduction, remove a reference type on parm
22614 too (which has been swapped into ARG). */
22615 if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
22616 *arg = TREE_TYPE (*arg);
22618 return result;
22621 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22622 template which doesn't contain any deducible template parameters; check if
22623 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22624 unify_one_argument. */
22626 static int
22627 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22628 int flags, struct conversion **conv_p,
22629 bool explain_p)
22631 tree type;
22633 if (!TYPE_P (arg))
22634 type = TREE_TYPE (arg);
22635 else
22636 type = arg;
22638 if (same_type_p (parm, type))
22639 return unify_success (explain_p);
22641 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22642 if (strict == DEDUCE_CONV)
22644 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22645 return unify_success (explain_p);
22647 else if (strict == DEDUCE_CALL)
22649 bool ok = false;
22650 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22651 if (conv_p)
22652 /* Avoid recalculating this in add_function_candidate. */
22653 ok = (*conv_p
22654 = good_conversion (parm, type, conv_arg, flags, complain));
22655 else
22656 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22657 if (ok)
22658 return unify_success (explain_p);
22661 if (strict == DEDUCE_EXACT)
22662 return unify_type_mismatch (explain_p, parm, arg);
22663 else
22664 return unify_arg_conversion (explain_p, parm, type, arg);
22667 static bool uses_deducible_template_parms (tree type);
22669 /* Returns true iff the expression EXPR is one from which a template
22670 argument can be deduced. In other words, if it's an undecorated
22671 use of a template non-type parameter. */
22673 static bool
22674 deducible_expression (tree expr)
22676 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22677 while (CONVERT_EXPR_P (expr)
22678 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22679 || REFERENCE_REF_P (expr))
22680 expr = TREE_OPERAND (expr, 0);
22681 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22684 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22685 deducible way; that is, if it has a max value of <PARM> - 1. */
22687 static bool
22688 deducible_array_bound (tree domain)
22690 if (domain == NULL_TREE)
22691 return false;
22693 tree max = TYPE_MAX_VALUE (domain);
22694 if (TREE_CODE (max) != MINUS_EXPR)
22695 return false;
22697 return deducible_expression (TREE_OPERAND (max, 0));
22700 /* Returns true iff the template arguments ARGS use a template parameter
22701 in a deducible way. */
22703 static bool
22704 deducible_template_args (tree args)
22706 for (tree elt : tree_vec_range (args))
22708 bool deducible;
22709 if (ARGUMENT_PACK_P (elt))
22710 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22711 else
22713 if (PACK_EXPANSION_P (elt))
22714 elt = PACK_EXPANSION_PATTERN (elt);
22715 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22716 deducible = true;
22717 else if (TYPE_P (elt))
22718 deducible = uses_deducible_template_parms (elt);
22719 else
22720 deducible = deducible_expression (elt);
22722 if (deducible)
22723 return true;
22725 return false;
22728 /* Returns true iff TYPE contains any deducible references to template
22729 parameters, as per 14.8.2.5. */
22731 static bool
22732 uses_deducible_template_parms (tree type)
22734 if (PACK_EXPANSION_P (type))
22735 type = PACK_EXPANSION_PATTERN (type);
22737 /* T
22738 cv-list T
22739 TT<T>
22740 TT<i>
22741 TT<> */
22742 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22743 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22744 return true;
22746 /* T*
22748 T&& */
22749 if (INDIRECT_TYPE_P (type))
22750 return uses_deducible_template_parms (TREE_TYPE (type));
22752 /* T[integer-constant ]
22753 type [i] */
22754 if (TREE_CODE (type) == ARRAY_TYPE)
22755 return (uses_deducible_template_parms (TREE_TYPE (type))
22756 || deducible_array_bound (TYPE_DOMAIN (type)));
22758 /* T type ::*
22759 type T::*
22760 T T::*
22761 T (type ::*)()
22762 type (T::*)()
22763 type (type ::*)(T)
22764 type (T::*)(T)
22765 T (type ::*)(T)
22766 T (T::*)()
22767 T (T::*)(T) */
22768 if (TYPE_PTRMEM_P (type))
22769 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22770 || (uses_deducible_template_parms
22771 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22773 /* template-name <T> (where template-name refers to a class template)
22774 template-name <i> (where template-name refers to a class template) */
22775 if (CLASS_TYPE_P (type)
22776 && CLASSTYPE_TEMPLATE_INFO (type)
22777 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22778 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22779 (CLASSTYPE_TI_ARGS (type)));
22781 /* type (T)
22783 T(T) */
22784 if (FUNC_OR_METHOD_TYPE_P (type))
22786 if (uses_deducible_template_parms (TREE_TYPE (type)))
22787 return true;
22788 tree parm = TYPE_ARG_TYPES (type);
22789 if (TREE_CODE (type) == METHOD_TYPE)
22790 parm = TREE_CHAIN (parm);
22791 for (; parm; parm = TREE_CHAIN (parm))
22792 if (uses_deducible_template_parms (TREE_VALUE (parm)))
22793 return true;
22794 if (flag_noexcept_type
22795 && TYPE_RAISES_EXCEPTIONS (type)
22796 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22797 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22798 return true;
22801 return false;
22804 /* Subroutine of type_unification_real and unify_pack_expansion to
22805 handle unification of a single P/A pair. Parameters are as
22806 for those functions. */
22808 static int
22809 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22810 int subr, unification_kind_t strict,
22811 bool explain_p)
22813 tree arg_expr = NULL_TREE;
22814 int arg_strict;
22816 if (arg == error_mark_node || parm == error_mark_node)
22817 return unify_invalid (explain_p);
22818 if (arg == unknown_type_node)
22819 /* We can't deduce anything from this, but we might get all the
22820 template args from other function args. */
22821 return unify_success (explain_p);
22823 /* Implicit conversions (Clause 4) will be performed on a function
22824 argument to convert it to the type of the corresponding function
22825 parameter if the parameter type contains no template-parameters that
22826 participate in template argument deduction. */
22827 if (strict != DEDUCE_EXACT
22828 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22829 /* For function parameters with no deducible template parameters,
22830 just return. We'll check non-dependent conversions later. */
22831 return unify_success (explain_p);
22833 switch (strict)
22835 case DEDUCE_CALL:
22836 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22837 | UNIFY_ALLOW_MORE_CV_QUAL
22838 | UNIFY_ALLOW_DERIVED);
22839 break;
22841 case DEDUCE_CONV:
22842 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22843 break;
22845 case DEDUCE_EXACT:
22846 arg_strict = UNIFY_ALLOW_NONE;
22847 break;
22849 default:
22850 gcc_unreachable ();
22853 /* We only do these transformations if this is the top-level
22854 parameter_type_list in a call or declaration matching; in other
22855 situations (nested function declarators, template argument lists) we
22856 won't be comparing a type to an expression, and we don't do any type
22857 adjustments. */
22858 if (!subr)
22860 if (!TYPE_P (arg))
22862 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22863 if (type_unknown_p (arg))
22865 /* [temp.deduct.type] A template-argument can be
22866 deduced from a pointer to function or pointer
22867 to member function argument if the set of
22868 overloaded functions does not contain function
22869 templates and at most one of a set of
22870 overloaded functions provides a unique
22871 match. */
22872 resolve_overloaded_unification (tparms, targs, parm,
22873 arg, strict,
22874 arg_strict, explain_p);
22875 /* If a unique match was not found, this is a
22876 non-deduced context, so we still succeed. */
22877 return unify_success (explain_p);
22880 arg_expr = arg;
22881 arg = unlowered_expr_type (arg);
22882 if (arg == error_mark_node)
22883 return unify_invalid (explain_p);
22886 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
22887 &parm, &arg, arg_expr);
22889 else
22890 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22891 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22892 return unify_template_argument_mismatch (explain_p, parm, arg);
22894 /* For deduction from an init-list we need the actual list. */
22895 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22896 arg = arg_expr;
22897 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22900 /* for_each_template_parm callback that always returns 0. */
22902 static int
22903 zero_r (tree, void *)
22905 return 0;
22908 /* for_each_template_parm any_fn callback to handle deduction of a template
22909 type argument from the type of an array bound. */
22911 static int
22912 array_deduction_r (tree t, void *data)
22914 tree_pair_p d = (tree_pair_p)data;
22915 tree &tparms = d->purpose;
22916 tree &targs = d->value;
22918 if (TREE_CODE (t) == ARRAY_TYPE)
22919 if (tree dom = TYPE_DOMAIN (t))
22920 if (tree max = TYPE_MAX_VALUE (dom))
22922 if (TREE_CODE (max) == MINUS_EXPR)
22923 max = TREE_OPERAND (max, 0);
22924 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22925 unify (tparms, targs, TREE_TYPE (max), size_type_node,
22926 UNIFY_ALLOW_NONE, /*explain*/false);
22929 /* Keep walking. */
22930 return 0;
22933 /* Try to deduce any not-yet-deduced template type arguments from the type of
22934 an array bound. This is handled separately from unify because 14.8.2.5 says
22935 "The type of a type parameter is only deduced from an array bound if it is
22936 not otherwise deduced." */
22938 static void
22939 try_array_deduction (tree tparms, tree targs, tree parm)
22941 tree_pair_s data = { tparms, targs };
22942 hash_set<tree> visited;
22943 for_each_template_parm (parm, zero_r, &data, &visited,
22944 /*nondeduced*/false, array_deduction_r);
22947 /* Most parms like fn_type_unification.
22949 If SUBR is 1, we're being called recursively (to unify the
22950 arguments of a function or method parameter of a function
22951 template).
22953 CHECKS is a pointer to a vector of access checks encountered while
22954 substituting default template arguments. */
22956 static int
22957 type_unification_real (tree tparms,
22958 tree full_targs,
22959 tree xparms,
22960 const tree *xargs,
22961 unsigned int xnargs,
22962 int subr,
22963 unification_kind_t strict,
22964 vec<deferred_access_check, va_gc> **checks,
22965 bool explain_p)
22967 tree parm, arg;
22968 int i;
22969 int ntparms = TREE_VEC_LENGTH (tparms);
22970 int saw_undeduced = 0;
22971 tree parms;
22972 const tree *args;
22973 unsigned int nargs;
22974 unsigned int ia;
22976 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22977 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22978 gcc_assert (ntparms > 0);
22980 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22982 /* Reset the number of non-defaulted template arguments contained
22983 in TARGS. */
22984 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22986 again:
22987 parms = xparms;
22988 args = xargs;
22989 nargs = xnargs;
22991 /* Only fn_type_unification cares about terminal void. */
22992 if (nargs && args[nargs-1] == void_type_node)
22993 --nargs;
22995 ia = 0;
22996 while (parms && parms != void_list_node
22997 && ia < nargs)
22999 parm = TREE_VALUE (parms);
23001 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23002 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23003 /* For a function parameter pack that occurs at the end of the
23004 parameter-declaration-list, the type A of each remaining
23005 argument of the call is compared with the type P of the
23006 declarator-id of the function parameter pack. */
23007 break;
23009 parms = TREE_CHAIN (parms);
23011 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23012 /* For a function parameter pack that does not occur at the
23013 end of the parameter-declaration-list, the type of the
23014 parameter pack is a non-deduced context. */
23015 continue;
23017 arg = args[ia];
23018 ++ia;
23020 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23021 explain_p))
23022 return 1;
23025 if (parms
23026 && parms != void_list_node
23027 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23029 /* Unify the remaining arguments with the pack expansion type. */
23030 tree argvec;
23031 tree parmvec = make_tree_vec (1);
23033 /* Allocate a TREE_VEC and copy in all of the arguments */
23034 argvec = make_tree_vec (nargs - ia);
23035 for (i = 0; ia < nargs; ++ia, ++i)
23036 TREE_VEC_ELT (argvec, i) = args[ia];
23038 /* Copy the parameter into parmvec. */
23039 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23040 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23041 /*subr=*/subr, explain_p))
23042 return 1;
23044 /* Advance to the end of the list of parameters. */
23045 parms = TREE_CHAIN (parms);
23048 /* Fail if we've reached the end of the parm list, and more args
23049 are present, and the parm list isn't variadic. */
23050 if (ia < nargs && parms == void_list_node)
23051 return unify_too_many_arguments (explain_p, nargs, ia);
23052 /* Fail if parms are left and they don't have default values and
23053 they aren't all deduced as empty packs (c++/57397). This is
23054 consistent with sufficient_parms_p. */
23055 if (parms && parms != void_list_node
23056 && TREE_PURPOSE (parms) == NULL_TREE)
23058 unsigned int count = nargs;
23059 tree p = parms;
23060 bool type_pack_p;
23063 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23064 if (!type_pack_p)
23065 count++;
23066 p = TREE_CHAIN (p);
23068 while (p && p != void_list_node);
23069 if (count != nargs)
23070 return unify_too_few_arguments (explain_p, ia, count,
23071 type_pack_p);
23074 if (!subr)
23076 tsubst_flags_t complain = (explain_p
23077 ? tf_warning_or_error
23078 : tf_none);
23079 bool tried_array_deduction = (cxx_dialect < cxx17);
23081 for (i = 0; i < ntparms; i++)
23083 tree targ = TREE_VEC_ELT (targs, i);
23084 tree tparm = TREE_VEC_ELT (tparms, i);
23086 /* Clear the "incomplete" flags on all argument packs now so that
23087 substituting them into later default arguments works. */
23088 if (targ && ARGUMENT_PACK_P (targ))
23090 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23091 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23094 if (targ || tparm == error_mark_node)
23095 continue;
23096 tparm = TREE_VALUE (tparm);
23098 if (TREE_CODE (tparm) == TYPE_DECL
23099 && !tried_array_deduction)
23101 try_array_deduction (tparms, targs, xparms);
23102 tried_array_deduction = true;
23103 if (TREE_VEC_ELT (targs, i))
23104 continue;
23107 /* If this is an undeduced nontype parameter that depends on
23108 a type parameter, try another pass; its type may have been
23109 deduced from a later argument than the one from which
23110 this parameter can be deduced. */
23111 if (TREE_CODE (tparm) == PARM_DECL
23112 && !is_auto (TREE_TYPE (tparm))
23113 && uses_template_parms (TREE_TYPE (tparm))
23114 && saw_undeduced < 2)
23116 saw_undeduced = 1;
23117 continue;
23120 /* Core issue #226 (C++0x) [temp.deduct]:
23122 If a template argument has not been deduced, its
23123 default template argument, if any, is used.
23125 When we are in C++98 mode, TREE_PURPOSE will either
23126 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23127 to explicitly check cxx_dialect here. */
23128 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23129 /* OK, there is a default argument. Wait until after the
23130 conversion check to do substitution. */
23131 continue;
23133 /* If the type parameter is a parameter pack, then it will
23134 be deduced to an empty parameter pack. */
23135 if (template_parameter_pack_p (tparm))
23137 tree arg;
23139 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23141 arg = make_node (NONTYPE_ARGUMENT_PACK);
23142 TREE_CONSTANT (arg) = 1;
23144 else
23145 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23147 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23149 TREE_VEC_ELT (targs, i) = arg;
23150 continue;
23153 return unify_parameter_deduction_failure (explain_p, tparm);
23156 /* Now substitute into the default template arguments. */
23157 for (i = 0; i < ntparms; i++)
23159 tree targ = TREE_VEC_ELT (targs, i);
23160 tree tparm = TREE_VEC_ELT (tparms, i);
23162 if (targ || tparm == error_mark_node)
23163 continue;
23164 tree parm = TREE_VALUE (tparm);
23165 tree arg = TREE_PURPOSE (tparm);
23166 reopen_deferring_access_checks (*checks);
23167 location_t save_loc = input_location;
23168 if (DECL_P (parm))
23169 input_location = DECL_SOURCE_LOCATION (parm);
23171 if (saw_undeduced == 1
23172 && TREE_CODE (parm) == PARM_DECL
23173 && !is_auto (TREE_TYPE (parm))
23174 && uses_template_parms (TREE_TYPE (parm)))
23176 /* The type of this non-type parameter depends on undeduced
23177 parameters. Don't try to use its default argument yet,
23178 since we might deduce an argument for it on the next pass,
23179 but do check whether the arguments we already have cause
23180 substitution failure, so that that happens before we try
23181 later default arguments (78489). */
23182 ++processing_template_decl;
23183 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23184 NULL_TREE);
23185 --processing_template_decl;
23186 if (type == error_mark_node)
23187 arg = error_mark_node;
23188 else
23189 arg = NULL_TREE;
23191 else
23193 /* Even if the call is happening in template context, getting
23194 here means it's non-dependent, and a default argument is
23195 considered a separate definition under [temp.decls], so we can
23196 do this substitution without processing_template_decl. This
23197 is important if the default argument contains something that
23198 might be instantiation-dependent like access (87480). */
23199 processing_template_decl_sentinel s;
23200 tree substed = NULL_TREE;
23201 if (saw_undeduced == 1)
23203 /* First instatiate in template context, in case we still
23204 depend on undeduced template parameters. */
23205 ++processing_template_decl;
23206 substed = tsubst_template_arg (arg, full_targs, complain,
23207 NULL_TREE);
23208 --processing_template_decl;
23209 if (substed != error_mark_node
23210 && !uses_template_parms (substed))
23211 /* We replaced all the tparms, substitute again out of
23212 template context. */
23213 substed = NULL_TREE;
23215 if (!substed)
23216 substed = tsubst_template_arg (arg, full_targs, complain,
23217 NULL_TREE);
23219 if (!uses_template_parms (substed))
23220 arg = convert_template_argument (parm, substed, full_targs,
23221 complain, i, NULL_TREE);
23222 else if (saw_undeduced == 1)
23223 arg = NULL_TREE;
23224 else
23225 arg = error_mark_node;
23228 input_location = save_loc;
23229 *checks = get_deferred_access_checks ();
23230 pop_deferring_access_checks ();
23232 if (arg == error_mark_node)
23233 return 1;
23234 else if (arg)
23236 TREE_VEC_ELT (targs, i) = arg;
23237 /* The position of the first default template argument,
23238 is also the number of non-defaulted arguments in TARGS.
23239 Record that. */
23240 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23241 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23245 if (saw_undeduced++ == 1)
23246 goto again;
23249 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23250 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23252 return unify_success (explain_p);
23255 /* Subroutine of type_unification_real. Args are like the variables
23256 at the call site. ARG is an overloaded function (or template-id);
23257 we try deducing template args from each of the overloads, and if
23258 only one succeeds, we go with that. Modifies TARGS and returns
23259 true on success. */
23261 static bool
23262 resolve_overloaded_unification (tree tparms,
23263 tree targs,
23264 tree parm,
23265 tree arg,
23266 unification_kind_t strict,
23267 int sub_strict,
23268 bool explain_p)
23270 tree tempargs = copy_node (targs);
23271 int good = 0;
23272 tree goodfn = NULL_TREE;
23273 bool addr_p;
23275 if (TREE_CODE (arg) == ADDR_EXPR)
23277 arg = TREE_OPERAND (arg, 0);
23278 addr_p = true;
23280 else
23281 addr_p = false;
23283 if (TREE_CODE (arg) == COMPONENT_REF)
23284 /* Handle `&x' where `x' is some static or non-static member
23285 function name. */
23286 arg = TREE_OPERAND (arg, 1);
23288 if (TREE_CODE (arg) == OFFSET_REF)
23289 arg = TREE_OPERAND (arg, 1);
23291 /* Strip baselink information. */
23292 if (BASELINK_P (arg))
23293 arg = BASELINK_FUNCTIONS (arg);
23295 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23297 /* If we got some explicit template args, we need to plug them into
23298 the affected templates before we try to unify, in case the
23299 explicit args will completely resolve the templates in question. */
23301 int ok = 0;
23302 tree expl_subargs = TREE_OPERAND (arg, 1);
23303 arg = TREE_OPERAND (arg, 0);
23305 for (lkp_iterator iter (arg); iter; ++iter)
23307 tree fn = *iter;
23308 tree subargs, elem;
23310 if (TREE_CODE (fn) != TEMPLATE_DECL)
23311 continue;
23313 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23314 expl_subargs, NULL_TREE, tf_none,
23315 /*require_all_args=*/true,
23316 /*use_default_args=*/true);
23317 if (subargs != error_mark_node
23318 && !any_dependent_template_arguments_p (subargs))
23320 fn = instantiate_template (fn, subargs, tf_none);
23321 if (!constraints_satisfied_p (fn))
23322 continue;
23323 if (undeduced_auto_decl (fn))
23325 /* Instantiate the function to deduce its return type. */
23326 ++function_depth;
23327 instantiate_decl (fn, /*defer*/false, /*class*/false);
23328 --function_depth;
23331 if (flag_noexcept_type)
23332 maybe_instantiate_noexcept (fn, tf_none);
23334 elem = TREE_TYPE (fn);
23335 if (try_one_overload (tparms, targs, tempargs, parm,
23336 elem, strict, sub_strict, addr_p, explain_p)
23337 && (!goodfn || !same_type_p (goodfn, elem)))
23339 goodfn = elem;
23340 ++good;
23343 else if (subargs)
23344 ++ok;
23346 /* If no templates (or more than one) are fully resolved by the
23347 explicit arguments, this template-id is a non-deduced context; it
23348 could still be OK if we deduce all template arguments for the
23349 enclosing call through other arguments. */
23350 if (good != 1)
23351 good = ok;
23353 else if (!OVL_P (arg))
23354 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23355 -- but the deduction does not succeed because the expression is
23356 not just the function on its own. */
23357 return false;
23358 else
23359 for (lkp_iterator iter (arg); iter; ++iter)
23361 tree fn = *iter;
23362 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23363 strict, sub_strict, addr_p, explain_p)
23364 && (!goodfn || !decls_match (goodfn, fn)))
23366 goodfn = fn;
23367 ++good;
23371 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23372 to function or pointer to member function argument if the set of
23373 overloaded functions does not contain function templates and at most
23374 one of a set of overloaded functions provides a unique match.
23376 So if we found multiple possibilities, we return success but don't
23377 deduce anything. */
23379 if (good == 1)
23381 int i = TREE_VEC_LENGTH (targs);
23382 for (; i--; )
23383 if (TREE_VEC_ELT (tempargs, i))
23385 tree old = TREE_VEC_ELT (targs, i);
23386 tree new_ = TREE_VEC_ELT (tempargs, i);
23387 if (new_ && old && ARGUMENT_PACK_P (old)
23388 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23389 /* Don't forget explicit template arguments in a pack. */
23390 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23391 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23392 TREE_VEC_ELT (targs, i) = new_;
23395 if (good)
23396 return true;
23398 return false;
23401 /* Core DR 115: In contexts where deduction is done and fails, or in
23402 contexts where deduction is not done, if a template argument list is
23403 specified and it, along with any default template arguments, identifies
23404 a single function template specialization, then the template-id is an
23405 lvalue for the function template specialization. */
23407 tree
23408 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23410 tree expr, offset, baselink;
23411 bool addr;
23413 if (!type_unknown_p (orig_expr))
23414 return orig_expr;
23416 expr = orig_expr;
23417 addr = false;
23418 offset = NULL_TREE;
23419 baselink = NULL_TREE;
23421 if (TREE_CODE (expr) == ADDR_EXPR)
23423 expr = TREE_OPERAND (expr, 0);
23424 addr = true;
23426 if (TREE_CODE (expr) == OFFSET_REF)
23428 offset = expr;
23429 expr = TREE_OPERAND (expr, 1);
23431 if (BASELINK_P (expr))
23433 baselink = expr;
23434 expr = BASELINK_FUNCTIONS (expr);
23437 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23439 int good = 0;
23440 tree goodfn = NULL_TREE;
23442 /* If we got some explicit template args, we need to plug them into
23443 the affected templates before we try to unify, in case the
23444 explicit args will completely resolve the templates in question. */
23446 tree expl_subargs = TREE_OPERAND (expr, 1);
23447 tree arg = TREE_OPERAND (expr, 0);
23448 tree badfn = NULL_TREE;
23449 tree badargs = NULL_TREE;
23451 for (lkp_iterator iter (arg); iter; ++iter)
23453 tree fn = *iter;
23454 tree subargs, elem;
23456 if (TREE_CODE (fn) != TEMPLATE_DECL)
23457 continue;
23459 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23460 expl_subargs, NULL_TREE, tf_none,
23461 /*require_all_args=*/true,
23462 /*use_default_args=*/true);
23463 if (subargs != error_mark_node
23464 && !any_dependent_template_arguments_p (subargs))
23466 elem = instantiate_template (fn, subargs, tf_none);
23467 if (elem == error_mark_node)
23469 badfn = fn;
23470 badargs = subargs;
23472 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23473 && constraints_satisfied_p (elem))
23475 goodfn = elem;
23476 ++good;
23480 if (good == 1)
23482 mark_used (goodfn);
23483 expr = goodfn;
23484 if (baselink)
23485 expr = build_baselink (BASELINK_BINFO (baselink),
23486 BASELINK_ACCESS_BINFO (baselink),
23487 expr, BASELINK_OPTYPE (baselink));
23488 if (offset)
23490 tree base
23491 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23492 expr = build_offset_ref (base, expr, addr, complain);
23494 if (addr)
23495 expr = cp_build_addr_expr (expr, complain);
23496 return expr;
23498 else if (good == 0 && badargs && (complain & tf_error))
23499 /* There were no good options and at least one bad one, so let the
23500 user know what the problem is. */
23501 instantiate_template (badfn, badargs, complain);
23503 return orig_expr;
23506 /* As above, but error out if the expression remains overloaded. */
23508 tree
23509 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23511 exp = resolve_nondeduced_context (exp, complain);
23512 if (type_unknown_p (exp))
23514 if (complain & tf_error)
23515 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23516 return error_mark_node;
23518 return exp;
23521 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23522 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23523 different overloads deduce different arguments for a given parm.
23524 ADDR_P is true if the expression for which deduction is being
23525 performed was of the form "& fn" rather than simply "fn".
23527 Returns 1 on success. */
23529 static int
23530 try_one_overload (tree tparms,
23531 tree orig_targs,
23532 tree targs,
23533 tree parm,
23534 tree arg,
23535 unification_kind_t strict,
23536 int sub_strict,
23537 bool addr_p,
23538 bool explain_p)
23540 int nargs;
23541 tree tempargs;
23542 int i;
23544 if (arg == error_mark_node)
23545 return 0;
23547 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23548 to function or pointer to member function argument if the set of
23549 overloaded functions does not contain function templates and at most
23550 one of a set of overloaded functions provides a unique match.
23552 So if this is a template, just return success. */
23554 if (uses_template_parms (arg))
23555 return 1;
23557 if (TREE_CODE (arg) == METHOD_TYPE)
23558 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23559 else if (addr_p)
23560 arg = build_pointer_type (arg);
23562 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23563 &parm, &arg, NULL_TREE);
23565 /* We don't copy orig_targs for this because if we have already deduced
23566 some template args from previous args, unify would complain when we
23567 try to deduce a template parameter for the same argument, even though
23568 there isn't really a conflict. */
23569 nargs = TREE_VEC_LENGTH (targs);
23570 tempargs = make_tree_vec (nargs);
23572 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23573 return 0;
23575 /* First make sure we didn't deduce anything that conflicts with
23576 explicitly specified args. */
23577 for (i = nargs; i--; )
23579 tree elt = TREE_VEC_ELT (tempargs, i);
23580 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23582 if (!elt)
23583 /*NOP*/;
23584 else if (uses_template_parms (elt))
23585 /* Since we're unifying against ourselves, we will fill in
23586 template args used in the function parm list with our own
23587 template parms. Discard them. */
23588 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23589 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23591 /* Check that the argument at each index of the deduced argument pack
23592 is equivalent to the corresponding explicitly specified argument.
23593 We may have deduced more arguments than were explicitly specified,
23594 and that's OK. */
23596 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23597 that's wrong if we deduce the same argument pack from multiple
23598 function arguments: it's only incomplete the first time. */
23600 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23601 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23603 if (TREE_VEC_LENGTH (deduced_pack)
23604 < TREE_VEC_LENGTH (explicit_pack))
23605 return 0;
23607 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23608 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23609 TREE_VEC_ELT (deduced_pack, j)))
23610 return 0;
23612 else if (oldelt && !template_args_equal (oldelt, elt))
23613 return 0;
23616 for (i = nargs; i--; )
23618 tree elt = TREE_VEC_ELT (tempargs, i);
23620 if (elt)
23621 TREE_VEC_ELT (targs, i) = elt;
23624 return 1;
23627 /* PARM is a template class (perhaps with unbound template
23628 parameters). ARG is a fully instantiated type. If ARG can be
23629 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23630 TARGS are as for unify. */
23632 static tree
23633 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23634 bool explain_p)
23636 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23637 return NULL_TREE;
23638 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23639 /* Matches anything. */;
23640 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23641 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23642 return NULL_TREE;
23644 /* We need to make a new template argument vector for the call to
23645 unify. If we used TARGS, we'd clutter it up with the result of
23646 the attempted unification, even if this class didn't work out.
23647 We also don't want to commit ourselves to all the unifications
23648 we've already done, since unification is supposed to be done on
23649 an argument-by-argument basis. In other words, consider the
23650 following pathological case:
23652 template <int I, int J, int K>
23653 struct S {};
23655 template <int I, int J>
23656 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23658 template <int I, int J, int K>
23659 void f(S<I, J, K>, S<I, I, I>);
23661 void g() {
23662 S<0, 0, 0> s0;
23663 S<0, 1, 2> s2;
23665 f(s0, s2);
23668 Now, by the time we consider the unification involving `s2', we
23669 already know that we must have `f<0, 0, 0>'. But, even though
23670 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23671 because there are two ways to unify base classes of S<0, 1, 2>
23672 with S<I, I, I>. If we kept the already deduced knowledge, we
23673 would reject the possibility I=1. */
23674 targs = copy_template_args (targs);
23675 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23676 targ = NULL_TREE;
23678 int err;
23679 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23680 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23681 else
23682 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23683 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23685 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
23686 for (tree level : tree_vec_range (targs))
23687 ggc_free (level);
23688 ggc_free (targs);
23690 return err ? NULL_TREE : arg;
23693 /* Given a template type PARM and a class type ARG, find the unique
23694 base type in ARG that is an instance of PARM. We do not examine
23695 ARG itself; only its base-classes. If there is not exactly one
23696 appropriate base class, return NULL_TREE. PARM may be the type of
23697 a partial specialization, as well as a plain template type. Used
23698 by unify. */
23700 static enum template_base_result
23701 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23702 bool explain_p, tree *result)
23704 tree rval = NULL_TREE;
23705 tree binfo;
23707 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23709 binfo = TYPE_BINFO (complete_type (arg));
23710 if (!binfo)
23712 /* The type could not be completed. */
23713 *result = NULL_TREE;
23714 return tbr_incomplete_type;
23717 /* Walk in inheritance graph order. The search order is not
23718 important, and this avoids multiple walks of virtual bases. */
23719 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23721 tree r = try_class_unification (tparms, targs, parm,
23722 BINFO_TYPE (binfo), explain_p);
23724 if (r)
23726 /* If there is more than one satisfactory baseclass, then:
23728 [temp.deduct.call]
23730 If they yield more than one possible deduced A, the type
23731 deduction fails.
23733 applies. */
23734 if (rval && !same_type_p (r, rval))
23736 /* [temp.deduct.call]/4.3: If there is a class C that is a
23737 (direct or indirect) base class of D and derived (directly or
23738 indirectly) from a class B and that would be a valid deduced
23739 A, the deduced A cannot be B or pointer to B, respectively. */
23740 if (DERIVED_FROM_P (r, rval))
23741 /* Ignore r. */
23742 continue;
23743 else if (DERIVED_FROM_P (rval, r))
23744 /* Ignore rval. */;
23745 else
23747 *result = NULL_TREE;
23748 return tbr_ambiguous_baseclass;
23752 rval = r;
23756 *result = rval;
23757 return tbr_success;
23760 /* Returns the level of DECL, which declares a template parameter. */
23762 static int
23763 template_decl_level (tree decl)
23765 switch (TREE_CODE (decl))
23767 case TYPE_DECL:
23768 case TEMPLATE_DECL:
23769 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23771 case PARM_DECL:
23772 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23774 default:
23775 gcc_unreachable ();
23777 return 0;
23780 /* Decide whether ARG can be unified with PARM, considering only the
23781 cv-qualifiers of each type, given STRICT as documented for unify.
23782 Returns nonzero iff the unification is OK on that basis. */
23784 static int
23785 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23787 int arg_quals = cp_type_quals (arg);
23788 int parm_quals = cp_type_quals (parm);
23790 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23791 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23793 /* Although a CVR qualifier is ignored when being applied to a
23794 substituted template parameter ([8.3.2]/1 for example), that
23795 does not allow us to unify "const T" with "int&" because both
23796 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23797 It is ok when we're allowing additional CV qualifiers
23798 at the outer level [14.8.2.1]/3,1st bullet. */
23799 if ((TYPE_REF_P (arg)
23800 || FUNC_OR_METHOD_TYPE_P (arg))
23801 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23802 return 0;
23804 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23805 && (parm_quals & TYPE_QUAL_RESTRICT))
23806 return 0;
23809 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23810 && (arg_quals & parm_quals) != parm_quals)
23811 return 0;
23813 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23814 && (parm_quals & arg_quals) != arg_quals)
23815 return 0;
23817 return 1;
23820 /* Determines the LEVEL and INDEX for the template parameter PARM. */
23821 void
23822 template_parm_level_and_index (tree parm, int* level, int* index)
23824 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23825 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23826 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23828 *index = TEMPLATE_TYPE_IDX (parm);
23829 *level = TEMPLATE_TYPE_LEVEL (parm);
23831 else
23833 *index = TEMPLATE_PARM_IDX (parm);
23834 *level = TEMPLATE_PARM_LEVEL (parm);
23838 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
23839 do { \
23840 if (unify (TP, TA, P, A, S, EP)) \
23841 return 1; \
23842 } while (0)
23844 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23845 expansion at the end of PACKED_PARMS. Returns 0 if the type
23846 deduction succeeds, 1 otherwise. STRICT is the same as in
23847 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23848 function call argument list. We'll need to adjust the arguments to make them
23849 types. SUBR tells us if this is from a recursive call to
23850 type_unification_real, or for comparing two template argument
23851 lists. */
23853 static int
23854 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23855 tree packed_args, unification_kind_t strict,
23856 bool subr, bool explain_p)
23858 tree parm
23859 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23860 tree pattern = PACK_EXPANSION_PATTERN (parm);
23861 tree pack, packs = NULL_TREE;
23862 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23864 /* Add in any args remembered from an earlier partial instantiation. */
23865 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23866 int levels = TMPL_ARGS_DEPTH (targs);
23868 packed_args = expand_template_argument_pack (packed_args);
23870 int len = TREE_VEC_LENGTH (packed_args);
23872 /* Determine the parameter packs we will be deducing from the
23873 pattern, and record their current deductions. */
23874 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23875 pack; pack = TREE_CHAIN (pack))
23877 tree parm_pack = TREE_VALUE (pack);
23878 int idx, level;
23880 /* Only template parameter packs can be deduced, not e.g. function
23881 parameter packs or __bases or __integer_pack. */
23882 if (!TEMPLATE_PARM_P (parm_pack))
23883 continue;
23885 /* Determine the index and level of this parameter pack. */
23886 template_parm_level_and_index (parm_pack, &level, &idx);
23887 if (level > levels)
23888 continue;
23890 /* Keep track of the parameter packs and their corresponding
23891 argument packs. */
23892 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23893 TREE_TYPE (packs) = make_tree_vec (len - start);
23896 /* Loop through all of the arguments that have not yet been
23897 unified and unify each with the pattern. */
23898 for (i = start; i < len; i++)
23900 tree parm;
23901 bool any_explicit = false;
23902 tree arg = TREE_VEC_ELT (packed_args, i);
23904 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23905 or the element of its argument pack at the current index if
23906 this argument was explicitly specified. */
23907 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23909 int idx, level;
23910 tree arg, pargs;
23911 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23913 arg = NULL_TREE;
23914 if (TREE_VALUE (pack)
23915 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23916 && (i - start < TREE_VEC_LENGTH (pargs)))
23918 any_explicit = true;
23919 arg = TREE_VEC_ELT (pargs, i - start);
23921 TMPL_ARG (targs, level, idx) = arg;
23924 /* If we had explicit template arguments, substitute them into the
23925 pattern before deduction. */
23926 if (any_explicit)
23928 /* Some arguments might still be unspecified or dependent. */
23929 bool dependent;
23930 ++processing_template_decl;
23931 dependent = any_dependent_template_arguments_p (targs);
23932 if (!dependent)
23933 --processing_template_decl;
23934 parm = tsubst (pattern, targs,
23935 explain_p ? tf_warning_or_error : tf_none,
23936 NULL_TREE);
23937 if (dependent)
23938 --processing_template_decl;
23939 if (parm == error_mark_node)
23940 return 1;
23942 else
23943 parm = pattern;
23945 /* Unify the pattern with the current argument. */
23946 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23947 explain_p))
23948 return 1;
23950 /* For each parameter pack, collect the deduced value. */
23951 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23953 int idx, level;
23954 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23956 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23957 TMPL_ARG (targs, level, idx);
23961 /* Verify that the results of unification with the parameter packs
23962 produce results consistent with what we've seen before, and make
23963 the deduced argument packs available. */
23964 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23966 tree old_pack = TREE_VALUE (pack);
23967 tree new_args = TREE_TYPE (pack);
23968 int i, len = TREE_VEC_LENGTH (new_args);
23969 int idx, level;
23970 bool nondeduced_p = false;
23972 /* By default keep the original deduced argument pack.
23973 If necessary, more specific code is going to update the
23974 resulting deduced argument later down in this function. */
23975 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23976 TMPL_ARG (targs, level, idx) = old_pack;
23978 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23979 actually deduce anything. */
23980 for (i = 0; i < len && !nondeduced_p; ++i)
23981 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23982 nondeduced_p = true;
23983 if (nondeduced_p)
23984 continue;
23986 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23988 /* If we had fewer function args than explicit template args,
23989 just use the explicits. */
23990 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23991 int explicit_len = TREE_VEC_LENGTH (explicit_args);
23992 if (len < explicit_len)
23993 new_args = explicit_args;
23996 if (!old_pack)
23998 tree result;
23999 /* Build the deduced *_ARGUMENT_PACK. */
24000 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24002 result = make_node (NONTYPE_ARGUMENT_PACK);
24003 TREE_CONSTANT (result) = 1;
24005 else
24006 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24008 ARGUMENT_PACK_ARGS (result) = new_args;
24010 /* Note the deduced argument packs for this parameter
24011 pack. */
24012 TMPL_ARG (targs, level, idx) = result;
24014 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24015 && (ARGUMENT_PACK_ARGS (old_pack)
24016 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24018 /* We only had the explicitly-provided arguments before, but
24019 now we have a complete set of arguments. */
24020 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24022 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24023 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24024 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24026 else
24028 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24029 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24030 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24031 /* During template argument deduction for the aggregate deduction
24032 candidate, the number of elements in a trailing parameter pack
24033 is only deduced from the number of remaining function
24034 arguments if it is not otherwise deduced. */
24035 if (cxx_dialect >= cxx20
24036 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24037 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24038 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24039 if (!comp_template_args (old_args, new_args,
24040 &bad_old_arg, &bad_new_arg))
24041 /* Inconsistent unification of this parameter pack. */
24042 return unify_parameter_pack_inconsistent (explain_p,
24043 bad_old_arg,
24044 bad_new_arg);
24048 return unify_success (explain_p);
24051 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24052 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24053 parameters and return value are as for unify. */
24055 static int
24056 unify_array_domain (tree tparms, tree targs,
24057 tree parm_dom, tree arg_dom,
24058 bool explain_p)
24060 tree parm_max;
24061 tree arg_max;
24062 bool parm_cst;
24063 bool arg_cst;
24065 /* Our representation of array types uses "N - 1" as the
24066 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24067 not an integer constant. We cannot unify arbitrarily
24068 complex expressions, so we eliminate the MINUS_EXPRs
24069 here. */
24070 parm_max = TYPE_MAX_VALUE (parm_dom);
24071 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24072 if (!parm_cst)
24074 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24075 parm_max = TREE_OPERAND (parm_max, 0);
24077 arg_max = TYPE_MAX_VALUE (arg_dom);
24078 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24079 if (!arg_cst)
24081 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24082 trying to unify the type of a variable with the type
24083 of a template parameter. For example:
24085 template <unsigned int N>
24086 void f (char (&) [N]);
24087 int g();
24088 void h(int i) {
24089 char a[g(i)];
24090 f(a);
24093 Here, the type of the ARG will be "int [g(i)]", and
24094 may be a SAVE_EXPR, etc. */
24095 if (TREE_CODE (arg_max) != MINUS_EXPR)
24096 return unify_vla_arg (explain_p, arg_dom);
24097 arg_max = TREE_OPERAND (arg_max, 0);
24100 /* If only one of the bounds used a MINUS_EXPR, compensate
24101 by adding one to the other bound. */
24102 if (parm_cst && !arg_cst)
24103 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24104 integer_type_node,
24105 parm_max,
24106 integer_one_node);
24107 else if (arg_cst && !parm_cst)
24108 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24109 integer_type_node,
24110 arg_max,
24111 integer_one_node);
24113 return unify (tparms, targs, parm_max, arg_max,
24114 UNIFY_ALLOW_INTEGER, explain_p);
24117 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24119 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24121 static pa_kind_t
24122 pa_kind (tree t)
24124 if (PACK_EXPANSION_P (t))
24125 t = PACK_EXPANSION_PATTERN (t);
24126 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24127 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24128 || DECL_TYPE_TEMPLATE_P (t))
24129 return pa_tmpl;
24130 else if (TYPE_P (t))
24131 return pa_type;
24132 else
24133 return pa_expr;
24136 /* Deduce the value of template parameters. TPARMS is the (innermost)
24137 set of template parameters to a template. TARGS is the bindings
24138 for those template parameters, as determined thus far; TARGS may
24139 include template arguments for outer levels of template parameters
24140 as well. PARM is a parameter to a template function, or a
24141 subcomponent of that parameter; ARG is the corresponding argument.
24142 This function attempts to match PARM with ARG in a manner
24143 consistent with the existing assignments in TARGS. If more values
24144 are deduced, then TARGS is updated.
24146 Returns 0 if the type deduction succeeds, 1 otherwise. The
24147 parameter STRICT is a bitwise or of the following flags:
24149 UNIFY_ALLOW_NONE:
24150 Require an exact match between PARM and ARG.
24151 UNIFY_ALLOW_MORE_CV_QUAL:
24152 Allow the deduced ARG to be more cv-qualified (by qualification
24153 conversion) than ARG.
24154 UNIFY_ALLOW_LESS_CV_QUAL:
24155 Allow the deduced ARG to be less cv-qualified than ARG.
24156 UNIFY_ALLOW_DERIVED:
24157 Allow the deduced ARG to be a template base class of ARG,
24158 or a pointer to a template base class of the type pointed to by
24159 ARG.
24160 UNIFY_ALLOW_INTEGER:
24161 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24162 case for more information.
24163 UNIFY_ALLOW_OUTER_LEVEL:
24164 This is the outermost level of a deduction. Used to determine validity
24165 of qualification conversions. A valid qualification conversion must
24166 have const qualified pointers leading up to the inner type which
24167 requires additional CV quals, except at the outer level, where const
24168 is not required [conv.qual]. It would be normal to set this flag in
24169 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24170 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24171 This is the outermost level of a deduction, and PARM can be more CV
24172 qualified at this point.
24173 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24174 This is the outermost level of a deduction, and PARM can be less CV
24175 qualified at this point. */
24177 static int
24178 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24179 bool explain_p)
24181 int idx;
24182 tree targ;
24183 tree tparm;
24184 int strict_in = strict;
24185 tsubst_flags_t complain = (explain_p
24186 ? tf_warning_or_error
24187 : tf_none);
24189 /* I don't think this will do the right thing with respect to types.
24190 But the only case I've seen it in so far has been array bounds, where
24191 signedness is the only information lost, and I think that will be
24192 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24193 finish_id_expression_1, and are also OK. */
24194 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24195 parm = TREE_OPERAND (parm, 0);
24197 if (arg == error_mark_node)
24198 return unify_invalid (explain_p);
24199 if (arg == unknown_type_node
24200 || arg == init_list_type_node)
24201 /* We can't deduce anything from this, but we might get all the
24202 template args from other function args. */
24203 return unify_success (explain_p);
24205 if (parm == any_targ_node || arg == any_targ_node)
24206 return unify_success (explain_p);
24208 /* If PARM uses template parameters, then we can't bail out here,
24209 even if ARG == PARM, since we won't record unifications for the
24210 template parameters. We might need them if we're trying to
24211 figure out which of two things is more specialized. */
24212 if (arg == parm && !uses_template_parms (parm))
24213 return unify_success (explain_p);
24215 /* Handle init lists early, so the rest of the function can assume
24216 we're dealing with a type. */
24217 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24219 tree elttype;
24220 tree orig_parm = parm;
24222 if (!is_std_init_list (parm)
24223 && TREE_CODE (parm) != ARRAY_TYPE)
24224 /* We can only deduce from an initializer list argument if the
24225 parameter is std::initializer_list or an array; otherwise this
24226 is a non-deduced context. */
24227 return unify_success (explain_p);
24229 if (TREE_CODE (parm) == ARRAY_TYPE)
24230 elttype = TREE_TYPE (parm);
24231 else
24233 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24234 /* Deduction is defined in terms of a single type, so just punt
24235 on the (bizarre) std::initializer_list<T...>. */
24236 if (PACK_EXPANSION_P (elttype))
24237 return unify_success (explain_p);
24240 if (strict != DEDUCE_EXACT
24241 && TYPE_P (elttype)
24242 && !uses_deducible_template_parms (elttype))
24243 /* If ELTTYPE has no deducible template parms, skip deduction from
24244 the list elements. */;
24245 else
24246 for (auto &e: CONSTRUCTOR_ELTS (arg))
24248 tree elt = e.value;
24249 int elt_strict = strict;
24251 if (elt == error_mark_node)
24252 return unify_invalid (explain_p);
24254 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24256 tree type = TREE_TYPE (elt);
24257 if (type == error_mark_node)
24258 return unify_invalid (explain_p);
24259 /* It should only be possible to get here for a call. */
24260 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24261 elt_strict |= maybe_adjust_types_for_deduction
24262 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24263 elt = type;
24266 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24267 explain_p);
24270 if (TREE_CODE (parm) == ARRAY_TYPE
24271 && deducible_array_bound (TYPE_DOMAIN (parm)))
24273 /* Also deduce from the length of the initializer list. */
24274 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24275 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24276 if (idx == error_mark_node)
24277 return unify_invalid (explain_p);
24278 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24279 idx, explain_p);
24282 /* If the std::initializer_list<T> deduction worked, replace the
24283 deduced A with std::initializer_list<A>. */
24284 if (orig_parm != parm)
24286 idx = TEMPLATE_TYPE_IDX (orig_parm);
24287 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24288 targ = listify (targ);
24289 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24291 return unify_success (explain_p);
24294 /* If parm and arg aren't the same kind of thing (template, type, or
24295 expression), fail early. */
24296 if (pa_kind (parm) != pa_kind (arg))
24297 return unify_invalid (explain_p);
24299 /* Immediately reject some pairs that won't unify because of
24300 cv-qualification mismatches. */
24301 if (TREE_CODE (arg) == TREE_CODE (parm)
24302 && TYPE_P (arg)
24303 /* It is the elements of the array which hold the cv quals of an array
24304 type, and the elements might be template type parms. We'll check
24305 when we recurse. */
24306 && TREE_CODE (arg) != ARRAY_TYPE
24307 /* We check the cv-qualifiers when unifying with template type
24308 parameters below. We want to allow ARG `const T' to unify with
24309 PARM `T' for example, when computing which of two templates
24310 is more specialized, for example. */
24311 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24312 && !check_cv_quals_for_unify (strict_in, arg, parm))
24313 return unify_cv_qual_mismatch (explain_p, parm, arg);
24315 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24316 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
24317 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24318 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24319 strict &= ~UNIFY_ALLOW_DERIVED;
24320 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24321 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24323 switch (TREE_CODE (parm))
24325 case TYPENAME_TYPE:
24326 case SCOPE_REF:
24327 case UNBOUND_CLASS_TEMPLATE:
24328 /* In a type which contains a nested-name-specifier, template
24329 argument values cannot be deduced for template parameters used
24330 within the nested-name-specifier. */
24331 return unify_success (explain_p);
24333 case TEMPLATE_TYPE_PARM:
24334 case TEMPLATE_TEMPLATE_PARM:
24335 case BOUND_TEMPLATE_TEMPLATE_PARM:
24336 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24337 if (error_operand_p (tparm))
24338 return unify_invalid (explain_p);
24340 if (TEMPLATE_TYPE_LEVEL (parm)
24341 != template_decl_level (tparm))
24342 /* The PARM is not one we're trying to unify. Just check
24343 to see if it matches ARG. */
24345 if (TREE_CODE (arg) == TREE_CODE (parm)
24346 && (is_auto (parm) ? is_auto (arg)
24347 : same_type_p (parm, arg)))
24348 return unify_success (explain_p);
24349 else
24350 return unify_type_mismatch (explain_p, parm, arg);
24352 idx = TEMPLATE_TYPE_IDX (parm);
24353 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24354 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24355 if (error_operand_p (tparm))
24356 return unify_invalid (explain_p);
24358 /* Check for mixed types and values. */
24359 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24360 && TREE_CODE (tparm) != TYPE_DECL)
24361 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24362 && TREE_CODE (tparm) != TEMPLATE_DECL))
24363 gcc_unreachable ();
24365 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24367 if ((strict_in & UNIFY_ALLOW_DERIVED)
24368 && CLASS_TYPE_P (arg))
24370 /* First try to match ARG directly. */
24371 tree t = try_class_unification (tparms, targs, parm, arg,
24372 explain_p);
24373 if (!t)
24375 /* Otherwise, look for a suitable base of ARG, as below. */
24376 enum template_base_result r;
24377 r = get_template_base (tparms, targs, parm, arg,
24378 explain_p, &t);
24379 if (!t)
24380 return unify_no_common_base (explain_p, r, parm, arg);
24381 arg = t;
24384 /* ARG must be constructed from a template class or a template
24385 template parameter. */
24386 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24387 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24388 return unify_template_deduction_failure (explain_p, parm, arg);
24390 /* Deduce arguments T, i from TT<T> or TT<i>. */
24391 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24392 return 1;
24394 arg = TYPE_TI_TEMPLATE (arg);
24395 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24396 /* If the template is a template template parameter, use the
24397 TEMPLATE_TEMPLATE_PARM for matching. */
24398 arg = TREE_TYPE (arg);
24400 /* Fall through to deduce template name. */
24403 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24404 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24406 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24408 /* Simple cases: Value already set, does match or doesn't. */
24409 if (targ != NULL_TREE && template_args_equal (targ, arg))
24410 return unify_success (explain_p);
24411 else if (targ)
24412 return unify_inconsistency (explain_p, parm, targ, arg);
24414 else
24416 /* If PARM is `const T' and ARG is only `int', we don't have
24417 a match unless we are allowing additional qualification.
24418 If ARG is `const int' and PARM is just `T' that's OK;
24419 that binds `const int' to `T'. */
24420 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24421 arg, parm))
24422 return unify_cv_qual_mismatch (explain_p, parm, arg);
24424 /* Consider the case where ARG is `const volatile int' and
24425 PARM is `const T'. Then, T should be `volatile int'. */
24426 arg = cp_build_qualified_type
24427 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24428 if (arg == error_mark_node)
24429 return unify_invalid (explain_p);
24431 /* Simple cases: Value already set, does match or doesn't. */
24432 if (targ != NULL_TREE && same_type_p (targ, arg))
24433 return unify_success (explain_p);
24434 else if (targ)
24435 return unify_inconsistency (explain_p, parm, targ, arg);
24437 /* Make sure that ARG is not a variable-sized array. (Note
24438 that were talking about variable-sized arrays (like
24439 `int[n]'), rather than arrays of unknown size (like
24440 `int[]').) We'll get very confused by such a type since
24441 the bound of the array is not constant, and therefore
24442 not mangleable. Besides, such types are not allowed in
24443 ISO C++, so we can do as we please here. We do allow
24444 them for 'auto' deduction, since that isn't ABI-exposed. */
24445 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24446 return unify_vla_arg (explain_p, arg);
24448 /* Strip typedefs as in convert_template_argument. */
24449 arg = canonicalize_type_argument (arg, tf_none);
24452 /* If ARG is a parameter pack or an expansion, we cannot unify
24453 against it unless PARM is also a parameter pack. */
24454 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24455 && !template_parameter_pack_p (parm))
24456 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24458 /* If the argument deduction results is a METHOD_TYPE,
24459 then there is a problem.
24460 METHOD_TYPE doesn't map to any real C++ type the result of
24461 the deduction cannot be of that type. */
24462 if (TREE_CODE (arg) == METHOD_TYPE)
24463 return unify_method_type_error (explain_p, arg);
24465 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24466 return unify_success (explain_p);
24468 case TEMPLATE_PARM_INDEX:
24469 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24470 if (error_operand_p (tparm))
24471 return unify_invalid (explain_p);
24473 if (TEMPLATE_PARM_LEVEL (parm)
24474 != template_decl_level (tparm))
24476 /* The PARM is not one we're trying to unify. Just check
24477 to see if it matches ARG. */
24478 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24479 && cp_tree_equal (parm, arg));
24480 if (result)
24481 unify_expression_unequal (explain_p, parm, arg);
24482 return result;
24485 idx = TEMPLATE_PARM_IDX (parm);
24486 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24488 if (targ)
24490 if ((strict & UNIFY_ALLOW_INTEGER)
24491 && TREE_TYPE (targ) && TREE_TYPE (arg)
24492 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24493 /* We're deducing from an array bound, the type doesn't matter. */
24494 arg = fold_convert (TREE_TYPE (targ), arg);
24495 int x = !cp_tree_equal (targ, arg);
24496 if (x)
24497 unify_inconsistency (explain_p, parm, targ, arg);
24498 return x;
24501 /* [temp.deduct.type] If, in the declaration of a function template
24502 with a non-type template-parameter, the non-type
24503 template-parameter is used in an expression in the function
24504 parameter-list and, if the corresponding template-argument is
24505 deduced, the template-argument type shall match the type of the
24506 template-parameter exactly, except that a template-argument
24507 deduced from an array bound may be of any integral type.
24508 The non-type parameter might use already deduced type parameters. */
24509 tparm = TREE_TYPE (parm);
24510 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24511 /* We don't have enough levels of args to do any substitution. This
24512 can happen in the context of -fnew-ttp-matching. */;
24513 else
24515 ++processing_template_decl;
24516 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24517 --processing_template_decl;
24519 if (tree a = type_uses_auto (tparm))
24521 tparm = do_auto_deduction (tparm, arg, a,
24522 complain, adc_unify, targs);
24523 if (tparm == error_mark_node)
24524 return 1;
24528 if (!TREE_TYPE (arg)
24529 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24530 /* Template-parameter dependent expression. Just accept it for now.
24531 It will later be processed in convert_template_argument. */
24533 else if (same_type_ignoring_top_level_qualifiers_p
24534 (non_reference (TREE_TYPE (arg)),
24535 non_reference (tparm)))
24536 /* OK. Ignore top-level quals here because a class-type template
24537 parameter object is const. */;
24538 else if ((strict & UNIFY_ALLOW_INTEGER)
24539 && CP_INTEGRAL_TYPE_P (tparm))
24540 /* Convert the ARG to the type of PARM; the deduced non-type
24541 template argument must exactly match the types of the
24542 corresponding parameter. */
24543 arg = fold (build_nop (tparm, arg));
24544 else if (uses_template_parms (tparm))
24546 /* We haven't deduced the type of this parameter yet. */
24547 if (cxx_dialect >= cxx17
24548 /* We deduce from array bounds in try_array_deduction. */
24549 && !(strict & UNIFY_ALLOW_INTEGER)
24550 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24552 /* Deduce it from the non-type argument. As above, ignore
24553 top-level quals here too. */
24554 tree atype = cv_unqualified (TREE_TYPE (arg));
24555 RECUR_AND_CHECK_FAILURE (tparms, targs,
24556 tparm, atype,
24557 UNIFY_ALLOW_NONE, explain_p);
24558 /* Now check whether the type of this parameter is still
24559 dependent, and give up if so. */
24560 ++processing_template_decl;
24561 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24562 --processing_template_decl;
24563 if (uses_template_parms (tparm))
24564 return unify_success (explain_p);
24566 else
24567 /* Try again later. */
24568 return unify_success (explain_p);
24570 else
24571 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24573 /* If ARG is a parameter pack or an expansion, we cannot unify
24574 against it unless PARM is also a parameter pack. */
24575 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24576 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24577 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24580 bool removed_attr = false;
24581 arg = strip_typedefs_expr (arg, &removed_attr);
24583 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24584 return unify_success (explain_p);
24586 case PTRMEM_CST:
24588 /* A pointer-to-member constant can be unified only with
24589 another constant. */
24590 if (TREE_CODE (arg) != PTRMEM_CST)
24591 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24593 /* Just unify the class member. It would be useless (and possibly
24594 wrong, depending on the strict flags) to unify also
24595 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24596 arg refer to the same variable, even if through different
24597 classes. For instance:
24599 struct A { int x; };
24600 struct B : A { };
24602 Unification of &A::x and &B::x must succeed. */
24603 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24604 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24607 case POINTER_TYPE:
24609 if (!TYPE_PTR_P (arg))
24610 return unify_type_mismatch (explain_p, parm, arg);
24612 /* [temp.deduct.call]
24614 A can be another pointer or pointer to member type that can
24615 be converted to the deduced A via a qualification
24616 conversion (_conv.qual_).
24618 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24619 This will allow for additional cv-qualification of the
24620 pointed-to types if appropriate. */
24622 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24623 /* The derived-to-base conversion only persists through one
24624 level of pointers. */
24625 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24627 return unify (tparms, targs, TREE_TYPE (parm),
24628 TREE_TYPE (arg), strict, explain_p);
24631 case REFERENCE_TYPE:
24632 if (!TYPE_REF_P (arg))
24633 return unify_type_mismatch (explain_p, parm, arg);
24634 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24635 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24637 case ARRAY_TYPE:
24638 if (TREE_CODE (arg) != ARRAY_TYPE)
24639 return unify_type_mismatch (explain_p, parm, arg);
24640 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24641 != (TYPE_DOMAIN (arg) == NULL_TREE))
24642 return unify_type_mismatch (explain_p, parm, arg);
24643 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24644 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24645 if (TYPE_DOMAIN (parm) != NULL_TREE)
24646 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24647 TYPE_DOMAIN (arg), explain_p);
24648 return unify_success (explain_p);
24650 case REAL_TYPE:
24651 case COMPLEX_TYPE:
24652 case VECTOR_TYPE:
24653 case INTEGER_TYPE:
24654 case BOOLEAN_TYPE:
24655 case ENUMERAL_TYPE:
24656 case VOID_TYPE:
24657 case OPAQUE_TYPE:
24658 case NULLPTR_TYPE:
24659 if (TREE_CODE (arg) != TREE_CODE (parm))
24660 return unify_type_mismatch (explain_p, parm, arg);
24662 /* We have already checked cv-qualification at the top of the
24663 function. */
24664 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24665 return unify_type_mismatch (explain_p, parm, arg);
24667 /* As far as unification is concerned, this wins. Later checks
24668 will invalidate it if necessary. */
24669 return unify_success (explain_p);
24671 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24672 /* Type INTEGER_CST can come from ordinary constant template args. */
24673 case INTEGER_CST:
24674 while (CONVERT_EXPR_P (arg))
24675 arg = TREE_OPERAND (arg, 0);
24677 if (TREE_CODE (arg) != INTEGER_CST)
24678 return unify_template_argument_mismatch (explain_p, parm, arg);
24679 return (tree_int_cst_equal (parm, arg)
24680 ? unify_success (explain_p)
24681 : unify_template_argument_mismatch (explain_p, parm, arg));
24683 case TREE_VEC:
24685 int i, len, argslen;
24686 int parm_variadic_p = 0;
24688 if (TREE_CODE (arg) != TREE_VEC)
24689 return unify_template_argument_mismatch (explain_p, parm, arg);
24691 len = TREE_VEC_LENGTH (parm);
24692 argslen = TREE_VEC_LENGTH (arg);
24694 /* Check for pack expansions in the parameters. */
24695 for (i = 0; i < len; ++i)
24697 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24699 if (i == len - 1)
24700 /* We can unify against something with a trailing
24701 parameter pack. */
24702 parm_variadic_p = 1;
24703 else
24704 /* [temp.deduct.type]/9: If the template argument list of
24705 P contains a pack expansion that is not the last
24706 template argument, the entire template argument list
24707 is a non-deduced context. */
24708 return unify_success (explain_p);
24712 /* If we don't have enough arguments to satisfy the parameters
24713 (not counting the pack expression at the end), or we have
24714 too many arguments for a parameter list that doesn't end in
24715 a pack expression, we can't unify. */
24716 if (parm_variadic_p
24717 ? argslen < len - parm_variadic_p
24718 : argslen != len)
24719 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24721 /* Unify all of the parameters that precede the (optional)
24722 pack expression. */
24723 for (i = 0; i < len - parm_variadic_p; ++i)
24725 RECUR_AND_CHECK_FAILURE (tparms, targs,
24726 TREE_VEC_ELT (parm, i),
24727 TREE_VEC_ELT (arg, i),
24728 UNIFY_ALLOW_NONE, explain_p);
24730 if (parm_variadic_p)
24731 return unify_pack_expansion (tparms, targs, parm, arg,
24732 DEDUCE_EXACT,
24733 /*subr=*/true, explain_p);
24734 return unify_success (explain_p);
24737 case RECORD_TYPE:
24738 case UNION_TYPE:
24739 if (TREE_CODE (arg) != TREE_CODE (parm))
24740 return unify_type_mismatch (explain_p, parm, arg);
24742 if (TYPE_PTRMEMFUNC_P (parm))
24744 if (!TYPE_PTRMEMFUNC_P (arg))
24745 return unify_type_mismatch (explain_p, parm, arg);
24747 return unify (tparms, targs,
24748 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24749 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24750 strict, explain_p);
24752 else if (TYPE_PTRMEMFUNC_P (arg))
24753 return unify_type_mismatch (explain_p, parm, arg);
24755 if (CLASSTYPE_TEMPLATE_INFO (parm))
24757 tree t = NULL_TREE;
24759 if (strict_in & UNIFY_ALLOW_DERIVED)
24761 /* First, we try to unify the PARM and ARG directly. */
24762 t = try_class_unification (tparms, targs,
24763 parm, arg, explain_p);
24765 if (!t)
24767 /* Fallback to the special case allowed in
24768 [temp.deduct.call]:
24770 If P is a class, and P has the form
24771 template-id, then A can be a derived class of
24772 the deduced A. Likewise, if P is a pointer to
24773 a class of the form template-id, A can be a
24774 pointer to a derived class pointed to by the
24775 deduced A. */
24776 enum template_base_result r;
24777 r = get_template_base (tparms, targs, parm, arg,
24778 explain_p, &t);
24780 if (!t)
24782 /* Don't give the derived diagnostic if we're
24783 already dealing with the same template. */
24784 bool same_template
24785 = (CLASSTYPE_TEMPLATE_INFO (arg)
24786 && (CLASSTYPE_TI_TEMPLATE (parm)
24787 == CLASSTYPE_TI_TEMPLATE (arg)));
24788 return unify_no_common_base (explain_p && !same_template,
24789 r, parm, arg);
24793 else if (CLASSTYPE_TEMPLATE_INFO (arg)
24794 && (CLASSTYPE_TI_TEMPLATE (parm)
24795 == CLASSTYPE_TI_TEMPLATE (arg)))
24796 /* Perhaps PARM is something like S<U> and ARG is S<int>.
24797 Then, we should unify `int' and `U'. */
24798 t = arg;
24799 else
24800 /* There's no chance of unification succeeding. */
24801 return unify_type_mismatch (explain_p, parm, arg);
24803 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24804 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24806 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24807 return unify_type_mismatch (explain_p, parm, arg);
24808 return unify_success (explain_p);
24810 case METHOD_TYPE:
24811 case FUNCTION_TYPE:
24813 unsigned int nargs;
24814 tree *args;
24815 tree a;
24816 unsigned int i;
24818 if (TREE_CODE (arg) != TREE_CODE (parm))
24819 return unify_type_mismatch (explain_p, parm, arg);
24821 /* CV qualifications for methods can never be deduced, they must
24822 match exactly. We need to check them explicitly here,
24823 because type_unification_real treats them as any other
24824 cv-qualified parameter. */
24825 if (TREE_CODE (parm) == METHOD_TYPE
24826 && (!check_cv_quals_for_unify
24827 (UNIFY_ALLOW_NONE,
24828 class_of_this_parm (arg),
24829 class_of_this_parm (parm))))
24830 return unify_cv_qual_mismatch (explain_p, parm, arg);
24831 if (TREE_CODE (arg) == FUNCTION_TYPE
24832 && type_memfn_quals (parm) != type_memfn_quals (arg))
24833 return unify_cv_qual_mismatch (explain_p, parm, arg);
24834 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24835 return unify_type_mismatch (explain_p, parm, arg);
24837 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24838 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24840 nargs = list_length (TYPE_ARG_TYPES (arg));
24841 args = XALLOCAVEC (tree, nargs);
24842 for (a = TYPE_ARG_TYPES (arg), i = 0;
24843 a != NULL_TREE && a != void_list_node;
24844 a = TREE_CHAIN (a), ++i)
24845 args[i] = TREE_VALUE (a);
24846 nargs = i;
24848 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24849 args, nargs, 1, DEDUCE_EXACT,
24850 NULL, explain_p))
24851 return 1;
24853 if (flag_noexcept_type)
24855 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24856 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24857 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24858 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24859 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24860 && uses_template_parms (TREE_PURPOSE (pspec)))
24861 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24862 TREE_PURPOSE (aspec),
24863 UNIFY_ALLOW_NONE, explain_p);
24864 else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24865 return unify_type_mismatch (explain_p, parm, arg);
24868 return 0;
24871 case OFFSET_TYPE:
24872 /* Unify a pointer to member with a pointer to member function, which
24873 deduces the type of the member as a function type. */
24874 if (TYPE_PTRMEMFUNC_P (arg))
24876 /* Check top-level cv qualifiers */
24877 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24878 return unify_cv_qual_mismatch (explain_p, parm, arg);
24880 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24881 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24882 UNIFY_ALLOW_NONE, explain_p);
24884 /* Determine the type of the function we are unifying against. */
24885 tree fntype = static_fn_type (arg);
24887 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24890 if (TREE_CODE (arg) != OFFSET_TYPE)
24891 return unify_type_mismatch (explain_p, parm, arg);
24892 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24893 TYPE_OFFSET_BASETYPE (arg),
24894 UNIFY_ALLOW_NONE, explain_p);
24895 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24896 strict, explain_p);
24898 case CONST_DECL:
24899 if (DECL_TEMPLATE_PARM_P (parm))
24900 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24901 if (arg != scalar_constant_value (parm))
24902 return unify_template_argument_mismatch (explain_p, parm, arg);
24903 return unify_success (explain_p);
24905 case FIELD_DECL:
24906 case TEMPLATE_DECL:
24907 /* Matched cases are handled by the ARG == PARM test above. */
24908 return unify_template_argument_mismatch (explain_p, parm, arg);
24910 case VAR_DECL:
24911 /* We might get a variable as a non-type template argument in parm if the
24912 corresponding parameter is type-dependent. Make any necessary
24913 adjustments based on whether arg is a reference. */
24914 if (CONSTANT_CLASS_P (arg))
24915 parm = fold_non_dependent_expr (parm, complain);
24916 else if (REFERENCE_REF_P (arg))
24918 tree sub = TREE_OPERAND (arg, 0);
24919 STRIP_NOPS (sub);
24920 if (TREE_CODE (sub) == ADDR_EXPR)
24921 arg = TREE_OPERAND (sub, 0);
24923 /* Now use the normal expression code to check whether they match. */
24924 goto expr;
24926 case TYPE_ARGUMENT_PACK:
24927 case NONTYPE_ARGUMENT_PACK:
24928 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24929 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24931 case TYPEOF_TYPE:
24932 case DECLTYPE_TYPE:
24933 case UNDERLYING_TYPE:
24934 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24935 or UNDERLYING_TYPE nodes. */
24936 return unify_success (explain_p);
24938 case ERROR_MARK:
24939 /* Unification fails if we hit an error node. */
24940 return unify_invalid (explain_p);
24942 case INDIRECT_REF:
24943 if (REFERENCE_REF_P (parm))
24945 bool pexp = PACK_EXPANSION_P (arg);
24946 if (pexp)
24947 arg = PACK_EXPANSION_PATTERN (arg);
24948 if (REFERENCE_REF_P (arg))
24949 arg = TREE_OPERAND (arg, 0);
24950 if (pexp)
24951 arg = make_pack_expansion (arg, complain);
24952 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24953 strict, explain_p);
24955 /* FALLTHRU */
24957 default:
24958 /* An unresolved overload is a nondeduced context. */
24959 if (is_overloaded_fn (parm) || type_unknown_p (parm))
24960 return unify_success (explain_p);
24961 gcc_assert (EXPR_P (parm)
24962 || COMPOUND_LITERAL_P (parm)
24963 || TREE_CODE (parm) == TRAIT_EXPR);
24964 expr:
24965 /* We must be looking at an expression. This can happen with
24966 something like:
24968 template <int I>
24969 void foo(S<I>, S<I + 2>);
24973 template<typename T>
24974 void foo(A<T, T{}>);
24976 This is a "non-deduced context":
24978 [deduct.type]
24980 The non-deduced contexts are:
24982 --A non-type template argument or an array bound in which
24983 a subexpression references a template parameter.
24985 In these cases, we assume deduction succeeded, but don't
24986 actually infer any unifications. */
24988 if (!uses_template_parms (parm)
24989 && !template_args_equal (parm, arg))
24990 return unify_expression_unequal (explain_p, parm, arg);
24991 else
24992 return unify_success (explain_p);
24995 #undef RECUR_AND_CHECK_FAILURE
24997 /* Note that DECL can be defined in this translation unit, if
24998 required. */
25000 static void
25001 mark_definable (tree decl)
25003 tree clone;
25004 DECL_NOT_REALLY_EXTERN (decl) = 1;
25005 FOR_EACH_CLONE (clone, decl)
25006 DECL_NOT_REALLY_EXTERN (clone) = 1;
25009 /* Called if RESULT is explicitly instantiated, or is a member of an
25010 explicitly instantiated class. */
25012 void
25013 mark_decl_instantiated (tree result, int extern_p)
25015 SET_DECL_EXPLICIT_INSTANTIATION (result);
25017 /* If this entity has already been written out, it's too late to
25018 make any modifications. */
25019 if (TREE_ASM_WRITTEN (result))
25020 return;
25022 /* consteval functions are never emitted. */
25023 if (TREE_CODE (result) == FUNCTION_DECL
25024 && DECL_IMMEDIATE_FUNCTION_P (result))
25025 return;
25027 /* For anonymous namespace we don't need to do anything. */
25028 if (decl_internal_context_p (result))
25030 gcc_assert (!TREE_PUBLIC (result));
25031 return;
25034 if (TREE_CODE (result) != FUNCTION_DECL)
25035 /* The TREE_PUBLIC flag for function declarations will have been
25036 set correctly by tsubst. */
25037 TREE_PUBLIC (result) = 1;
25039 if (extern_p)
25041 DECL_EXTERNAL (result) = 1;
25042 DECL_NOT_REALLY_EXTERN (result) = 0;
25044 else
25046 mark_definable (result);
25047 mark_needed (result);
25048 /* Always make artificials weak. */
25049 if (DECL_ARTIFICIAL (result) && flag_weak)
25050 comdat_linkage (result);
25051 /* For WIN32 we also want to put explicit instantiations in
25052 linkonce sections. */
25053 else if (TREE_PUBLIC (result))
25054 maybe_make_one_only (result);
25055 if (TREE_CODE (result) == FUNCTION_DECL
25056 && DECL_TEMPLATE_INSTANTIATED (result))
25057 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25058 since start_preparsed_function wouldn't have if we had an earlier
25059 extern explicit instantiation. */
25060 DECL_EXTERNAL (result) = 0;
25063 /* If EXTERN_P, then this function will not be emitted -- unless
25064 followed by an explicit instantiation, at which point its linkage
25065 will be adjusted. If !EXTERN_P, then this function will be
25066 emitted here. In neither circumstance do we want
25067 import_export_decl to adjust the linkage. */
25068 DECL_INTERFACE_KNOWN (result) = 1;
25071 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25072 important template arguments. If any are missing, we check whether
25073 they're important by using error_mark_node for substituting into any
25074 args that were used for partial ordering (the ones between ARGS and END)
25075 and seeing if it bubbles up. */
25077 static bool
25078 check_undeduced_parms (tree targs, tree args, tree end)
25080 bool found = false;
25081 for (tree& targ : tree_vec_range (targs))
25082 if (targ == NULL_TREE)
25084 found = true;
25085 targ = error_mark_node;
25087 if (found)
25089 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25090 if (substed == error_mark_node)
25091 return true;
25093 return false;
25096 /* Given two function templates PAT1 and PAT2, return:
25098 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25099 -1 if PAT2 is more specialized than PAT1.
25100 0 if neither is more specialized.
25102 LEN indicates the number of parameters we should consider
25103 (defaulted parameters should not be considered).
25105 The 1998 std underspecified function template partial ordering, and
25106 DR214 addresses the issue. We take pairs of arguments, one from
25107 each of the templates, and deduce them against each other. One of
25108 the templates will be more specialized if all the *other*
25109 template's arguments deduce against its arguments and at least one
25110 of its arguments *does* *not* deduce against the other template's
25111 corresponding argument. Deduction is done as for class templates.
25112 The arguments used in deduction have reference and top level cv
25113 qualifiers removed. Iff both arguments were originally reference
25114 types *and* deduction succeeds in both directions, an lvalue reference
25115 wins against an rvalue reference and otherwise the template
25116 with the more cv-qualified argument wins for that pairing (if
25117 neither is more cv-qualified, they both are equal). Unlike regular
25118 deduction, after all the arguments have been deduced in this way,
25119 we do *not* verify the deduced template argument values can be
25120 substituted into non-deduced contexts.
25122 The logic can be a bit confusing here, because we look at deduce1 and
25123 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25124 can find template arguments for pat1 to make arg1 look like arg2, that
25125 means that arg2 is at least as specialized as arg1. */
25128 more_specialized_fn (tree pat1, tree pat2, int len)
25130 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25131 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25132 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25133 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25134 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25135 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25136 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25137 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25138 tree origs1, origs2;
25139 bool lose1 = false;
25140 bool lose2 = false;
25142 /* Remove the this parameter from non-static member functions. If
25143 one is a non-static member function and the other is not a static
25144 member function, remove the first parameter from that function
25145 also. This situation occurs for operator functions where we
25146 locate both a member function (with this pointer) and non-member
25147 operator (with explicit first operand). */
25148 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25150 len--; /* LEN is the number of significant arguments for DECL1 */
25151 args1 = TREE_CHAIN (args1);
25152 if (!DECL_STATIC_FUNCTION_P (decl2))
25153 args2 = TREE_CHAIN (args2);
25155 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25157 args2 = TREE_CHAIN (args2);
25158 if (!DECL_STATIC_FUNCTION_P (decl1))
25160 len--;
25161 args1 = TREE_CHAIN (args1);
25165 /* If only one is a conversion operator, they are unordered. */
25166 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25167 return 0;
25169 /* Consider the return type for a conversion function */
25170 if (DECL_CONV_FN_P (decl1))
25172 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25173 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25174 len++;
25177 processing_template_decl++;
25179 origs1 = args1;
25180 origs2 = args2;
25182 while (len--
25183 /* Stop when an ellipsis is seen. */
25184 && args1 != NULL_TREE && args2 != NULL_TREE)
25186 tree arg1 = TREE_VALUE (args1);
25187 tree arg2 = TREE_VALUE (args2);
25188 int deduce1, deduce2;
25189 int quals1 = -1;
25190 int quals2 = -1;
25191 int ref1 = 0;
25192 int ref2 = 0;
25194 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25195 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25197 /* When both arguments are pack expansions, we need only
25198 unify the patterns themselves. */
25199 arg1 = PACK_EXPANSION_PATTERN (arg1);
25200 arg2 = PACK_EXPANSION_PATTERN (arg2);
25202 /* This is the last comparison we need to do. */
25203 len = 0;
25206 if (TYPE_REF_P (arg1))
25208 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25209 arg1 = TREE_TYPE (arg1);
25210 quals1 = cp_type_quals (arg1);
25213 if (TYPE_REF_P (arg2))
25215 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25216 arg2 = TREE_TYPE (arg2);
25217 quals2 = cp_type_quals (arg2);
25220 arg1 = TYPE_MAIN_VARIANT (arg1);
25221 arg2 = TYPE_MAIN_VARIANT (arg2);
25223 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25225 int i, len2 = remaining_arguments (args2);
25226 tree parmvec = make_tree_vec (1);
25227 tree argvec = make_tree_vec (len2);
25228 tree ta = args2;
25230 /* Setup the parameter vector, which contains only ARG1. */
25231 TREE_VEC_ELT (parmvec, 0) = arg1;
25233 /* Setup the argument vector, which contains the remaining
25234 arguments. */
25235 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25236 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25238 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25239 argvec, DEDUCE_EXACT,
25240 /*subr=*/true, /*explain_p=*/false)
25241 == 0);
25243 /* We cannot deduce in the other direction, because ARG1 is
25244 a pack expansion but ARG2 is not. */
25245 deduce2 = 0;
25247 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25249 int i, len1 = remaining_arguments (args1);
25250 tree parmvec = make_tree_vec (1);
25251 tree argvec = make_tree_vec (len1);
25252 tree ta = args1;
25254 /* Setup the parameter vector, which contains only ARG1. */
25255 TREE_VEC_ELT (parmvec, 0) = arg2;
25257 /* Setup the argument vector, which contains the remaining
25258 arguments. */
25259 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25260 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25262 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25263 argvec, DEDUCE_EXACT,
25264 /*subr=*/true, /*explain_p=*/false)
25265 == 0);
25267 /* We cannot deduce in the other direction, because ARG2 is
25268 a pack expansion but ARG1 is not.*/
25269 deduce1 = 0;
25272 else
25274 /* The normal case, where neither argument is a pack
25275 expansion. */
25276 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25277 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25278 == 0);
25279 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25280 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25281 == 0);
25284 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25285 arg2, then arg2 is not as specialized as arg1. */
25286 if (!deduce1)
25287 lose2 = true;
25288 if (!deduce2)
25289 lose1 = true;
25291 /* "If, for a given type, deduction succeeds in both directions
25292 (i.e., the types are identical after the transformations above)
25293 and both P and A were reference types (before being replaced with
25294 the type referred to above):
25295 - if the type from the argument template was an lvalue reference and
25296 the type from the parameter template was not, the argument type is
25297 considered to be more specialized than the other; otherwise,
25298 - if the type from the argument template is more cv-qualified
25299 than the type from the parameter template (as described above),
25300 the argument type is considered to be more specialized than the other;
25301 otherwise,
25302 - neither type is more specialized than the other." */
25304 if (deduce1 && deduce2)
25306 if (ref1 && ref2 && ref1 != ref2)
25308 if (ref1 > ref2)
25309 lose1 = true;
25310 else
25311 lose2 = true;
25313 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25315 if ((quals1 & quals2) == quals2)
25316 lose2 = true;
25317 if ((quals1 & quals2) == quals1)
25318 lose1 = true;
25322 if (lose1 && lose2)
25323 /* We've failed to deduce something in either direction.
25324 These must be unordered. */
25325 break;
25327 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25328 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25329 /* We have already processed all of the arguments in our
25330 handing of the pack expansion type. */
25331 len = 0;
25333 args1 = TREE_CHAIN (args1);
25334 args2 = TREE_CHAIN (args2);
25337 /* "In most cases, all template parameters must have values in order for
25338 deduction to succeed, but for partial ordering purposes a template
25339 parameter may remain without a value provided it is not used in the
25340 types being used for partial ordering."
25342 Thus, if we are missing any of the targs1 we need to substitute into
25343 origs1, then pat2 is not as specialized as pat1. This can happen when
25344 there is a nondeduced context. */
25345 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25346 lose2 = true;
25347 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25348 lose1 = true;
25350 processing_template_decl--;
25352 /* If both deductions succeed, the partial ordering selects the more
25353 constrained template. */
25354 /* P2113: If the corresponding template-parameters of the
25355 template-parameter-lists are not equivalent ([temp.over.link]) or if
25356 the function parameters that positionally correspond between the two
25357 templates are not of the same type, neither template is more
25358 specialized than the other. */
25359 if (!lose1 && !lose2
25360 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25361 DECL_TEMPLATE_PARMS (pat2))
25362 && compparms (origs1, origs2))
25364 int winner = more_constrained (decl1, decl2);
25365 if (winner > 0)
25366 lose2 = true;
25367 else if (winner < 0)
25368 lose1 = true;
25371 /* All things being equal, if the next argument is a pack expansion
25372 for one function but not for the other, prefer the
25373 non-variadic function. FIXME this is bogus; see c++/41958. */
25374 if (lose1 == lose2
25375 && args1 && TREE_VALUE (args1)
25376 && args2 && TREE_VALUE (args2))
25378 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25379 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25382 if (lose1 == lose2)
25383 return 0;
25384 else if (!lose1)
25385 return 1;
25386 else
25387 return -1;
25390 /* Determine which of two partial specializations of TMPL is more
25391 specialized.
25393 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25394 to the first partial specialization. The TREE_PURPOSE is the
25395 innermost set of template parameters for the partial
25396 specialization. PAT2 is similar, but for the second template.
25398 Return 1 if the first partial specialization is more specialized;
25399 -1 if the second is more specialized; 0 if neither is more
25400 specialized.
25402 See [temp.class.order] for information about determining which of
25403 two templates is more specialized. */
25405 static int
25406 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25408 tree targs;
25409 int winner = 0;
25410 bool any_deductions = false;
25412 tree tmpl1 = TREE_VALUE (pat1);
25413 tree tmpl2 = TREE_VALUE (pat2);
25414 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25415 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25417 /* Just like what happens for functions, if we are ordering between
25418 different template specializations, we may encounter dependent
25419 types in the arguments, and we need our dependency check functions
25420 to behave correctly. */
25421 ++processing_template_decl;
25422 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25423 if (targs)
25425 --winner;
25426 any_deductions = true;
25429 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25430 if (targs)
25432 ++winner;
25433 any_deductions = true;
25435 --processing_template_decl;
25437 /* If both deductions succeed, the partial ordering selects the more
25438 constrained template. */
25439 if (!winner && any_deductions)
25440 winner = more_constrained (tmpl1, tmpl2);
25442 /* In the case of a tie where at least one of the templates
25443 has a parameter pack at the end, the template with the most
25444 non-packed parameters wins. */
25445 if (winner == 0
25446 && any_deductions
25447 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25448 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25450 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25451 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25452 int len1 = TREE_VEC_LENGTH (args1);
25453 int len2 = TREE_VEC_LENGTH (args2);
25455 /* We don't count the pack expansion at the end. */
25456 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25457 --len1;
25458 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25459 --len2;
25461 if (len1 > len2)
25462 return 1;
25463 else if (len1 < len2)
25464 return -1;
25467 return winner;
25470 /* Return the template arguments that will produce the function signature
25471 DECL from the function template FN, with the explicit template
25472 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25473 also match. Return NULL_TREE if no satisfactory arguments could be
25474 found. */
25476 static tree
25477 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25479 int ntparms = DECL_NTPARMS (fn);
25480 tree targs = make_tree_vec (ntparms);
25481 tree decl_type = TREE_TYPE (decl);
25482 tree decl_arg_types;
25483 tree *args;
25484 unsigned int nargs, ix;
25485 tree arg;
25487 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25489 /* Never do unification on the 'this' parameter. */
25490 decl_arg_types = skip_artificial_parms_for (decl,
25491 TYPE_ARG_TYPES (decl_type));
25493 nargs = list_length (decl_arg_types);
25494 args = XALLOCAVEC (tree, nargs);
25495 for (arg = decl_arg_types, ix = 0;
25496 arg != NULL_TREE;
25497 arg = TREE_CHAIN (arg), ++ix)
25498 args[ix] = TREE_VALUE (arg);
25500 if (fn_type_unification (fn, explicit_args, targs,
25501 args, ix,
25502 (check_rettype || DECL_CONV_FN_P (fn)
25503 ? TREE_TYPE (decl_type) : NULL_TREE),
25504 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25505 /*explain_p=*/false,
25506 /*decltype*/false)
25507 == error_mark_node)
25508 return NULL_TREE;
25510 return targs;
25513 /* Return the innermost template arguments that, when applied to a partial
25514 specialization SPEC_TMPL of TMPL, yield the ARGS.
25516 For example, suppose we have:
25518 template <class T, class U> struct S {};
25519 template <class T> struct S<T*, int> {};
25521 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25522 partial specialization and the ARGS will be {double*, int}. The resulting
25523 vector will be {double}, indicating that `T' is bound to `double'. */
25525 static tree
25526 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25528 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25529 tree spec_args
25530 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25531 int i, ntparms = TREE_VEC_LENGTH (tparms);
25532 tree deduced_args;
25533 tree innermost_deduced_args;
25535 innermost_deduced_args = make_tree_vec (ntparms);
25536 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25538 deduced_args = copy_node (args);
25539 SET_TMPL_ARGS_LEVEL (deduced_args,
25540 TMPL_ARGS_DEPTH (deduced_args),
25541 innermost_deduced_args);
25543 else
25544 deduced_args = innermost_deduced_args;
25546 bool tried_array_deduction = (cxx_dialect < cxx17);
25547 again:
25548 if (unify (tparms, deduced_args,
25549 INNERMOST_TEMPLATE_ARGS (spec_args),
25550 INNERMOST_TEMPLATE_ARGS (args),
25551 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25552 return NULL_TREE;
25554 for (i = 0; i < ntparms; ++i)
25555 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25557 if (!tried_array_deduction)
25559 try_array_deduction (tparms, innermost_deduced_args,
25560 INNERMOST_TEMPLATE_ARGS (spec_args));
25561 tried_array_deduction = true;
25562 if (TREE_VEC_ELT (innermost_deduced_args, i))
25563 goto again;
25565 return NULL_TREE;
25568 if (!push_tinst_level (spec_tmpl, deduced_args))
25570 excessive_deduction_depth = true;
25571 return NULL_TREE;
25574 /* Verify that nondeduced template arguments agree with the type
25575 obtained from argument deduction.
25577 For example:
25579 struct A { typedef int X; };
25580 template <class T, class U> struct C {};
25581 template <class T> struct C<T, typename T::X> {};
25583 Then with the instantiation `C<A, int>', we can deduce that
25584 `T' is `A' but unify () does not check whether `typename T::X'
25585 is `int'. */
25586 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25588 if (spec_args != error_mark_node)
25589 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25590 INNERMOST_TEMPLATE_ARGS (spec_args),
25591 tmpl, tf_none, false, false);
25593 pop_tinst_level ();
25595 if (spec_args == error_mark_node
25596 /* We only need to check the innermost arguments; the other
25597 arguments will always agree. */
25598 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25599 INNERMOST_TEMPLATE_ARGS (args)))
25600 return NULL_TREE;
25602 /* Now that we have bindings for all of the template arguments,
25603 ensure that the arguments deduced for the template template
25604 parameters have compatible template parameter lists. See the use
25605 of template_template_parm_bindings_ok_p in fn_type_unification
25606 for more information. */
25607 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25608 return NULL_TREE;
25610 return deduced_args;
25613 // Compare two function templates T1 and T2 by deducing bindings
25614 // from one against the other. If both deductions succeed, compare
25615 // constraints to see which is more constrained.
25616 static int
25617 more_specialized_inst (tree t1, tree t2)
25619 int fate = 0;
25620 int count = 0;
25622 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25624 --fate;
25625 ++count;
25628 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25630 ++fate;
25631 ++count;
25634 // If both deductions succeed, then one may be more constrained.
25635 if (count == 2 && fate == 0)
25636 fate = more_constrained (t1, t2);
25638 return fate;
25641 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25642 Return the TREE_LIST node with the most specialized template, if
25643 any. If there is no most specialized template, the error_mark_node
25644 is returned.
25646 Note that this function does not look at, or modify, the
25647 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25648 returned is one of the elements of INSTANTIATIONS, callers may
25649 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25650 and retrieve it from the value returned. */
25652 tree
25653 most_specialized_instantiation (tree templates)
25655 tree fn, champ;
25657 ++processing_template_decl;
25659 champ = templates;
25660 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25662 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25663 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25664 if (fate == -1)
25665 champ = fn;
25666 else if (!fate)
25668 /* Equally specialized, move to next function. If there
25669 is no next function, nothing's most specialized. */
25670 fn = TREE_CHAIN (fn);
25671 champ = fn;
25672 if (!fn)
25673 break;
25677 if (champ)
25678 /* Now verify that champ is better than everything earlier in the
25679 instantiation list. */
25680 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25681 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25683 champ = NULL_TREE;
25684 break;
25688 processing_template_decl--;
25690 if (!champ)
25691 return error_mark_node;
25693 return champ;
25696 /* If DECL is a specialization of some template, return the most
25697 general such template. Otherwise, returns NULL_TREE.
25699 For example, given:
25701 template <class T> struct S { template <class U> void f(U); };
25703 if TMPL is `template <class U> void S<int>::f(U)' this will return
25704 the full template. This function will not trace past partial
25705 specializations, however. For example, given in addition:
25707 template <class T> struct S<T*> { template <class U> void f(U); };
25709 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25710 `template <class T> template <class U> S<T*>::f(U)'. */
25712 tree
25713 most_general_template (tree decl)
25715 if (TREE_CODE (decl) != TEMPLATE_DECL)
25717 if (tree tinfo = get_template_info (decl))
25718 decl = TI_TEMPLATE (tinfo);
25719 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25720 template friend, or a FIELD_DECL for a capture pack. */
25721 if (TREE_CODE (decl) != TEMPLATE_DECL)
25722 return NULL_TREE;
25725 /* Look for more and more general templates. */
25726 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25728 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25729 (See cp-tree.h for details.) */
25730 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25731 break;
25733 if (CLASS_TYPE_P (TREE_TYPE (decl))
25734 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25735 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25736 break;
25738 /* Stop if we run into an explicitly specialized class template. */
25739 if (!DECL_NAMESPACE_SCOPE_P (decl)
25740 && DECL_CONTEXT (decl)
25741 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25742 break;
25744 decl = DECL_TI_TEMPLATE (decl);
25747 return decl;
25750 /* Return the most specialized of the template partial specializations
25751 which can produce TARGET, a specialization of some class or variable
25752 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
25753 a TEMPLATE_DECL node corresponding to the partial specialization, while
25754 the TREE_PURPOSE is the set of template arguments that must be
25755 substituted into the template pattern in order to generate TARGET.
25757 If the choice of partial specialization is ambiguous, a diagnostic
25758 is issued, and the error_mark_node is returned. If there are no
25759 partial specializations matching TARGET, then NULL_TREE is
25760 returned, indicating that the primary template should be used. */
25762 tree
25763 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25765 tree list = NULL_TREE;
25766 tree t;
25767 tree champ;
25768 int fate;
25769 bool ambiguous_p;
25770 tree outer_args = NULL_TREE;
25771 tree tmpl, args;
25773 tree decl;
25774 if (TYPE_P (target))
25776 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25777 tmpl = TI_TEMPLATE (tinfo);
25778 args = TI_ARGS (tinfo);
25779 decl = TYPE_NAME (target);
25781 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25783 tmpl = TREE_OPERAND (target, 0);
25784 args = TREE_OPERAND (target, 1);
25785 decl = DECL_TEMPLATE_RESULT (tmpl);
25787 else if (VAR_P (target))
25789 tree tinfo = DECL_TEMPLATE_INFO (target);
25790 tmpl = TI_TEMPLATE (tinfo);
25791 args = TI_ARGS (tinfo);
25792 decl = target;
25794 else
25795 gcc_unreachable ();
25797 push_access_scope_guard pas (decl);
25798 deferring_access_check_sentinel acs (dk_no_deferred);
25800 tree main_tmpl = most_general_template (tmpl);
25802 /* For determining which partial specialization to use, only the
25803 innermost args are interesting. */
25804 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25806 outer_args = strip_innermost_template_args (args, 1);
25807 args = INNERMOST_TEMPLATE_ARGS (args);
25810 /* The caller hasn't called push_to_top_level yet, but we need
25811 get_partial_spec_bindings to be done in non-template context so that we'll
25812 fully resolve everything. */
25813 processing_template_decl_sentinel ptds;
25815 for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25817 const tree ospec_tmpl = TREE_VALUE (t);
25819 tree spec_tmpl;
25820 if (outer_args)
25822 /* Substitute in the template args from the enclosing class. */
25823 ++processing_template_decl;
25824 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25825 --processing_template_decl;
25826 if (spec_tmpl == error_mark_node)
25827 return error_mark_node;
25829 else
25830 spec_tmpl = ospec_tmpl;
25832 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25833 if (spec_args)
25835 if (outer_args)
25836 spec_args = add_to_template_args (outer_args, spec_args);
25838 /* Keep the candidate only if the constraints are satisfied,
25839 or if we're not compiling with concepts. */
25840 if (!flag_concepts
25841 || constraints_satisfied_p (ospec_tmpl, spec_args))
25843 list = tree_cons (spec_args, ospec_tmpl, list);
25844 TREE_TYPE (list) = TREE_TYPE (t);
25849 if (! list)
25850 return NULL_TREE;
25852 ambiguous_p = false;
25853 t = list;
25854 champ = t;
25855 t = TREE_CHAIN (t);
25856 for (; t; t = TREE_CHAIN (t))
25858 fate = more_specialized_partial_spec (tmpl, champ, t);
25859 if (fate == 1)
25861 else
25863 if (fate == 0)
25865 t = TREE_CHAIN (t);
25866 if (! t)
25868 ambiguous_p = true;
25869 break;
25872 champ = t;
25876 if (!ambiguous_p)
25877 for (t = list; t && t != champ; t = TREE_CHAIN (t))
25879 fate = more_specialized_partial_spec (tmpl, champ, t);
25880 if (fate != 1)
25882 ambiguous_p = true;
25883 break;
25887 if (ambiguous_p)
25889 const char *str;
25890 char *spaces = NULL;
25891 if (!(complain & tf_error))
25892 return error_mark_node;
25893 if (TYPE_P (target))
25894 error ("ambiguous template instantiation for %q#T", target);
25895 else
25896 error ("ambiguous template instantiation for %q#D", target);
25897 str = ngettext ("candidate is:", "candidates are:", list_length (list));
25898 for (t = list; t; t = TREE_CHAIN (t))
25900 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25901 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25902 "%s %#qS", spaces ? spaces : str, subst);
25903 spaces = spaces ? spaces : get_spaces (str);
25905 free (spaces);
25906 return error_mark_node;
25909 return champ;
25912 /* Explicitly instantiate DECL. */
25914 void
25915 do_decl_instantiation (tree decl, tree storage)
25917 tree result = NULL_TREE;
25918 int extern_p = 0;
25920 if (!decl || decl == error_mark_node)
25921 /* An error occurred, for which grokdeclarator has already issued
25922 an appropriate message. */
25923 return;
25924 else if (! DECL_LANG_SPECIFIC (decl))
25926 error ("explicit instantiation of non-template %q#D", decl);
25927 return;
25929 else if (DECL_DECLARED_CONCEPT_P (decl))
25931 if (VAR_P (decl))
25932 error ("explicit instantiation of variable concept %q#D", decl);
25933 else
25934 error ("explicit instantiation of function concept %q#D", decl);
25935 return;
25938 bool var_templ = (DECL_TEMPLATE_INFO (decl)
25939 && variable_template_p (DECL_TI_TEMPLATE (decl)));
25941 if (VAR_P (decl) && !var_templ)
25943 /* There is an asymmetry here in the way VAR_DECLs and
25944 FUNCTION_DECLs are handled by grokdeclarator. In the case of
25945 the latter, the DECL we get back will be marked as a
25946 template instantiation, and the appropriate
25947 DECL_TEMPLATE_INFO will be set up. This does not happen for
25948 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
25949 should handle VAR_DECLs as it currently handles
25950 FUNCTION_DECLs. */
25951 if (!DECL_CLASS_SCOPE_P (decl))
25953 error ("%qD is not a static data member of a class template", decl);
25954 return;
25956 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25957 if (!result || !VAR_P (result))
25959 error ("no matching template for %qD found", decl);
25960 return;
25962 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25964 error ("type %qT for explicit instantiation %qD does not match "
25965 "declared type %qT", TREE_TYPE (result), decl,
25966 TREE_TYPE (decl));
25967 return;
25970 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25972 error ("explicit instantiation of %q#D", decl);
25973 return;
25975 else
25976 result = decl;
25978 /* Check for various error cases. Note that if the explicit
25979 instantiation is valid the RESULT will currently be marked as an
25980 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25981 until we get here. */
25983 if (DECL_TEMPLATE_SPECIALIZATION (result))
25985 /* DR 259 [temp.spec].
25987 Both an explicit instantiation and a declaration of an explicit
25988 specialization shall not appear in a program unless the explicit
25989 instantiation follows a declaration of the explicit specialization.
25991 For a given set of template parameters, if an explicit
25992 instantiation of a template appears after a declaration of an
25993 explicit specialization for that template, the explicit
25994 instantiation has no effect. */
25995 return;
25997 else if (DECL_EXPLICIT_INSTANTIATION (result))
25999 /* [temp.spec]
26001 No program shall explicitly instantiate any template more
26002 than once.
26004 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26005 the first instantiation was `extern' and the second is not,
26006 and EXTERN_P for the opposite case. */
26007 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26008 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26009 /* If an "extern" explicit instantiation follows an ordinary
26010 explicit instantiation, the template is instantiated. */
26011 if (extern_p)
26012 return;
26014 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26016 error ("no matching template for %qD found", result);
26017 return;
26019 else if (!DECL_TEMPLATE_INFO (result))
26021 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26022 return;
26025 if (storage == NULL_TREE)
26027 else if (storage == ridpointers[(int) RID_EXTERN])
26029 if (cxx_dialect == cxx98)
26030 pedwarn (input_location, OPT_Wpedantic,
26031 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26032 "instantiations");
26033 extern_p = 1;
26035 else
26036 error ("storage class %qD applied to template instantiation", storage);
26038 check_explicit_instantiation_namespace (result);
26039 mark_decl_instantiated (result, extern_p);
26040 if (! extern_p)
26041 instantiate_decl (result, /*defer_ok=*/true,
26042 /*expl_inst_class_mem_p=*/false);
26045 static void
26046 mark_class_instantiated (tree t, int extern_p)
26048 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26049 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26050 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26051 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26052 if (! extern_p)
26054 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26055 rest_of_type_compilation (t, 1);
26059 /* Perform an explicit instantiation of template class T. STORAGE, if
26060 non-null, is the RID for extern, inline or static. COMPLAIN is
26061 nonzero if this is called from the parser, zero if called recursively,
26062 since the standard is unclear (as detailed below). */
26064 void
26065 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26067 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26069 if (tree ti = TYPE_TEMPLATE_INFO (t))
26070 error ("explicit instantiation of non-class template %qD",
26071 TI_TEMPLATE (ti));
26072 else
26073 error ("explicit instantiation of non-template type %qT", t);
26074 return;
26077 complete_type (t);
26079 if (!COMPLETE_TYPE_P (t))
26081 if (complain & tf_error)
26082 error ("explicit instantiation of %q#T before definition of template",
26084 return;
26087 /* At most one of these will be true. */
26088 bool extern_p = false;
26089 bool nomem_p = false;
26090 bool static_p = false;
26092 if (storage != NULL_TREE)
26094 if (storage == ridpointers[(int) RID_EXTERN])
26096 if (cxx_dialect == cxx98)
26097 pedwarn (input_location, OPT_Wpedantic,
26098 "ISO C++ 1998 forbids the use of %<extern%> on "
26099 "explicit instantiations");
26101 else
26102 pedwarn (input_location, OPT_Wpedantic,
26103 "ISO C++ forbids the use of %qE"
26104 " on explicit instantiations", storage);
26106 if (storage == ridpointers[(int) RID_INLINE])
26107 nomem_p = true;
26108 else if (storage == ridpointers[(int) RID_EXTERN])
26109 extern_p = true;
26110 else if (storage == ridpointers[(int) RID_STATIC])
26111 static_p = true;
26112 else
26113 error ("storage class %qD applied to template instantiation",
26114 storage);
26117 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26118 /* DR 259 [temp.spec].
26120 Both an explicit instantiation and a declaration of an explicit
26121 specialization shall not appear in a program unless the
26122 explicit instantiation follows a declaration of the explicit
26123 specialization.
26125 For a given set of template parameters, if an explicit
26126 instantiation of a template appears after a declaration of an
26127 explicit specialization for that template, the explicit
26128 instantiation has no effect. */
26129 return;
26131 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26133 /* We've already instantiated the template. */
26135 /* [temp.spec]
26137 No program shall explicitly instantiate any template more
26138 than once.
26140 If EXTERN_P then this is ok. */
26141 if (!extern_p && (complain & tf_error))
26142 permerror (input_location,
26143 "duplicate explicit instantiation of %q#T", t);
26145 return;
26148 check_explicit_instantiation_namespace (TYPE_NAME (t));
26149 mark_class_instantiated (t, extern_p);
26151 if (nomem_p)
26152 return;
26154 /* In contrast to implicit instantiation, where only the
26155 declarations, and not the definitions, of members are
26156 instantiated, we have here:
26158 [temp.explicit]
26160 An explicit instantiation that names a class template
26161 specialization is also an explicit instantiation of the same
26162 kind (declaration or definition) of each of its members (not
26163 including members inherited from base classes and members
26164 that are templates) that has not been previously explicitly
26165 specialized in the translation unit containing the explicit
26166 instantiation, provided that the associated constraints, if
26167 any, of that member are satisfied by the template arguments
26168 of the explicit instantiation. */
26169 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26170 if ((VAR_P (fld)
26171 || (TREE_CODE (fld) == FUNCTION_DECL
26172 && !static_p
26173 && user_provided_p (fld)))
26174 && DECL_TEMPLATE_INSTANTIATION (fld)
26175 && constraints_satisfied_p (fld))
26177 mark_decl_instantiated (fld, extern_p);
26178 if (! extern_p)
26179 instantiate_decl (fld, /*defer_ok=*/true,
26180 /*expl_inst_class_mem_p=*/true);
26182 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26184 tree type = TREE_TYPE (fld);
26186 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26187 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26188 do_type_instantiation (type, storage, 0);
26192 /* Given a function DECL, which is a specialization of TMPL, modify
26193 DECL to be a re-instantiation of TMPL with the same template
26194 arguments. TMPL should be the template into which tsubst'ing
26195 should occur for DECL, not the most general template.
26197 One reason for doing this is a scenario like this:
26199 template <class T>
26200 void f(const T&, int i);
26202 void g() { f(3, 7); }
26204 template <class T>
26205 void f(const T& t, const int i) { }
26207 Note that when the template is first instantiated, with
26208 instantiate_template, the resulting DECL will have no name for the
26209 first parameter, and the wrong type for the second. So, when we go
26210 to instantiate the DECL, we regenerate it. */
26212 static void
26213 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26215 /* The arguments used to instantiate DECL, from the most general
26216 template. */
26217 tree code_pattern;
26219 code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26221 /* Make sure that we can see identifiers, and compute access
26222 correctly. */
26223 push_access_scope (decl);
26225 if (TREE_CODE (decl) == FUNCTION_DECL)
26227 tree specs;
26228 int args_depth;
26229 int parms_depth;
26231 /* Use the source location of the definition. */
26232 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26234 args_depth = TMPL_ARGS_DEPTH (args);
26235 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26236 if (args_depth > parms_depth)
26237 args = get_innermost_template_args (args, parms_depth);
26239 /* Instantiate a dynamic exception-specification. noexcept will be
26240 handled below. */
26241 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26242 if (TREE_VALUE (raises))
26244 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26245 args, tf_error, NULL_TREE,
26246 /*defer_ok*/false);
26247 if (specs && specs != error_mark_node)
26248 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26249 specs);
26252 /* Merge parameter declarations. */
26253 if (tree pattern_parm
26254 = skip_artificial_parms_for (code_pattern,
26255 DECL_ARGUMENTS (code_pattern)))
26257 tree *p = &DECL_ARGUMENTS (decl);
26258 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26259 p = &DECL_CHAIN (*p);
26260 *p = tsubst_decl (pattern_parm, args, tf_error);
26261 for (tree t = *p; t; t = DECL_CHAIN (t))
26262 DECL_CONTEXT (t) = decl;
26265 /* Merge additional specifiers from the CODE_PATTERN. */
26266 if (DECL_DECLARED_INLINE_P (code_pattern)
26267 && !DECL_DECLARED_INLINE_P (decl))
26268 DECL_DECLARED_INLINE_P (decl) = 1;
26270 maybe_instantiate_noexcept (decl, tf_error);
26272 else if (VAR_P (decl))
26274 start_lambda_scope (decl);
26275 DECL_INITIAL (decl) =
26276 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26277 tf_error, DECL_TI_TEMPLATE (decl));
26278 finish_lambda_scope ();
26279 if (VAR_HAD_UNKNOWN_BOUND (decl))
26280 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26281 tf_error, DECL_TI_TEMPLATE (decl));
26283 else
26284 gcc_unreachable ();
26286 pop_access_scope (decl);
26289 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26290 substituted to get DECL. */
26292 tree
26293 template_for_substitution (tree decl)
26295 tree tmpl = DECL_TI_TEMPLATE (decl);
26297 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26298 for the instantiation. This is not always the most general
26299 template. Consider, for example:
26301 template <class T>
26302 struct S { template <class U> void f();
26303 template <> void f<int>(); };
26305 and an instantiation of S<double>::f<int>. We want TD to be the
26306 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26307 while (/* An instantiation cannot have a definition, so we need a
26308 more general template. */
26309 DECL_TEMPLATE_INSTANTIATION (tmpl)
26310 /* We must also deal with friend templates. Given:
26312 template <class T> struct S {
26313 template <class U> friend void f() {};
26316 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26317 so far as the language is concerned, but that's still
26318 where we get the pattern for the instantiation from. On
26319 other hand, if the definition comes outside the class, say:
26321 template <class T> struct S {
26322 template <class U> friend void f();
26324 template <class U> friend void f() {}
26326 we don't need to look any further. That's what the check for
26327 DECL_INITIAL is for. */
26328 || (TREE_CODE (decl) == FUNCTION_DECL
26329 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26330 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26332 /* The present template, TD, should not be a definition. If it
26333 were a definition, we should be using it! Note that we
26334 cannot restructure the loop to just keep going until we find
26335 a template with a definition, since that might go too far if
26336 a specialization was declared, but not defined. */
26338 /* Fetch the more general template. */
26339 tmpl = DECL_TI_TEMPLATE (tmpl);
26342 return tmpl;
26345 /* Returns true if we need to instantiate this template instance even if we
26346 know we aren't going to emit it. */
26348 bool
26349 always_instantiate_p (tree decl)
26351 /* We always instantiate inline functions so that we can inline them. An
26352 explicit instantiation declaration prohibits implicit instantiation of
26353 non-inline functions. With high levels of optimization, we would
26354 normally inline non-inline functions -- but we're not allowed to do
26355 that for "extern template" functions. Therefore, we check
26356 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26357 return ((TREE_CODE (decl) == FUNCTION_DECL
26358 && (DECL_DECLARED_INLINE_P (decl)
26359 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26360 /* And we need to instantiate static data members so that
26361 their initializers are available in integral constant
26362 expressions. */
26363 || (VAR_P (decl)
26364 && decl_maybe_constant_var_p (decl)));
26367 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26368 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26369 error, true otherwise. */
26371 bool
26372 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26374 if (fn == error_mark_node)
26375 return false;
26377 /* Don't instantiate a noexcept-specification from template context. */
26378 if (processing_template_decl
26379 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26380 return true;
26382 tree fntype = TREE_TYPE (fn);
26383 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26385 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26386 && DECL_MAYBE_DELETED (fn))
26388 if (fn == current_function_decl)
26389 /* We're in start_preparsed_function, keep going. */
26390 return true;
26392 ++function_depth;
26393 maybe_synthesize_method (fn);
26394 --function_depth;
26395 return !DECL_DELETED_FN (fn);
26398 if (!spec || !TREE_PURPOSE (spec))
26399 return true;
26401 tree noex = TREE_PURPOSE (spec);
26402 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26403 && TREE_CODE (noex) != DEFERRED_PARSE)
26404 return true;
26406 tree orig_fn = NULL_TREE;
26407 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26408 its FUNCTION_DECL for the rest of this function -- push_access_scope
26409 doesn't accept TEMPLATE_DECLs. */
26410 if (DECL_FUNCTION_TEMPLATE_P (fn))
26412 orig_fn = fn;
26413 fn = DECL_TEMPLATE_RESULT (fn);
26416 if (DECL_CLONED_FUNCTION_P (fn))
26418 tree prime = DECL_CLONED_FUNCTION (fn);
26419 if (!maybe_instantiate_noexcept (prime, complain))
26420 return false;
26421 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26423 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26425 static hash_set<tree>* fns = new hash_set<tree>;
26426 bool added = false;
26427 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26429 spec = get_defaulted_eh_spec (fn, complain);
26430 if (spec == error_mark_node)
26431 /* This might have failed because of an unparsed DMI, so
26432 let's try again later. */
26433 return false;
26435 else if (!(added = !fns->add (fn)))
26437 /* If hash_set::add returns true, the element was already there. */
26438 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26439 DECL_SOURCE_LOCATION (fn));
26440 error_at (loc,
26441 "exception specification of %qD depends on itself",
26442 fn);
26443 spec = noexcept_false_spec;
26445 else if (push_tinst_level (fn))
26447 push_to_top_level ();
26448 push_access_scope (fn);
26449 push_deferring_access_checks (dk_no_deferred);
26450 input_location = DECL_SOURCE_LOCATION (fn);
26452 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26453 && !DECL_LOCAL_DECL_P (fn))
26455 /* If needed, set current_class_ptr for the benefit of
26456 tsubst_copy/PARM_DECL. */
26457 tree this_parm = DECL_ARGUMENTS (fn);
26458 current_class_ptr = NULL_TREE;
26459 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26460 current_class_ptr = this_parm;
26463 /* If this function is represented by a TEMPLATE_DECL, then
26464 the deferred noexcept-specification might still contain
26465 dependent types, even after substitution. And we need the
26466 dependency check functions to work in build_noexcept_spec. */
26467 if (orig_fn)
26468 ++processing_template_decl;
26470 /* Do deferred instantiation of the noexcept-specifier. */
26471 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26472 DEFERRED_NOEXCEPT_ARGS (noex),
26473 tf_warning_or_error, fn,
26474 /*function_p=*/false,
26475 /*i_c_e_p=*/true);
26477 /* Build up the noexcept-specification. */
26478 spec = build_noexcept_spec (noex, tf_warning_or_error);
26480 if (orig_fn)
26481 --processing_template_decl;
26483 pop_deferring_access_checks ();
26484 pop_access_scope (fn);
26485 pop_tinst_level ();
26486 pop_from_top_level ();
26488 else
26489 spec = noexcept_false_spec;
26491 if (added)
26492 fns->remove (fn);
26495 if (spec == error_mark_node)
26497 /* This failed with a hard error, so let's go with false. */
26498 gcc_assert (seen_error ());
26499 spec = noexcept_false_spec;
26502 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26503 if (orig_fn)
26504 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26506 return true;
26509 /* We're starting to process the function INST, an instantiation of PATTERN;
26510 add their parameters to local_specializations. */
26512 static void
26513 register_parameter_specializations (tree pattern, tree inst)
26515 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26516 tree spec_parm = DECL_ARGUMENTS (inst);
26517 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26519 register_local_specialization (spec_parm, tmpl_parm);
26520 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26521 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26523 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26525 if (!DECL_PACK_P (tmpl_parm))
26527 register_local_specialization (spec_parm, tmpl_parm);
26528 spec_parm = DECL_CHAIN (spec_parm);
26530 else
26532 /* Register the (value) argument pack as a specialization of
26533 TMPL_PARM, then move on. */
26534 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26535 register_local_specialization (argpack, tmpl_parm);
26538 gcc_assert (!spec_parm);
26541 /* Instantiate the body of D using PATTERN with ARGS. We have
26542 already determined PATTERN is the correct template to use.
26543 NESTED_P is true if this is a nested function, in which case
26544 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26546 static void
26547 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26549 tree td = NULL_TREE;
26550 tree code_pattern = pattern;
26552 if (!nested_p)
26554 td = pattern;
26555 code_pattern = DECL_TEMPLATE_RESULT (td);
26557 else
26558 /* Only OMP reductions are nested. */
26559 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26561 vec<tree> omp_privatization_save;
26562 if (current_function_decl)
26563 save_omp_privatization_clauses (omp_privatization_save);
26565 bool push_to_top
26566 = !(current_function_decl
26567 && !LAMBDA_FUNCTION_P (d)
26568 && decl_function_context (d) == current_function_decl);
26570 if (push_to_top)
26571 push_to_top_level ();
26572 else
26574 gcc_assert (!processing_template_decl);
26575 push_function_context ();
26576 cp_unevaluated_operand = 0;
26577 c_inhibit_evaluation_warnings = 0;
26580 if (VAR_P (d))
26582 /* The variable might be a lambda's extra scope, and that
26583 lambda's visibility depends on D's. */
26584 maybe_commonize_var (d);
26585 determine_visibility (d);
26588 /* Mark D as instantiated so that recursive calls to
26589 instantiate_decl do not try to instantiate it again. */
26590 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26592 if (td)
26593 /* Regenerate the declaration in case the template has been modified
26594 by a subsequent redeclaration. */
26595 regenerate_decl_from_template (d, td, args);
26597 /* We already set the file and line above. Reset them now in case
26598 they changed as a result of calling regenerate_decl_from_template. */
26599 input_location = DECL_SOURCE_LOCATION (d);
26601 if (VAR_P (d))
26603 /* Clear out DECL_RTL; whatever was there before may not be right
26604 since we've reset the type of the declaration. */
26605 SET_DECL_RTL (d, NULL);
26606 DECL_IN_AGGR_P (d) = 0;
26608 /* The initializer is placed in DECL_INITIAL by
26609 regenerate_decl_from_template so we don't need to
26610 push/pop_access_scope again here. Pull it out so that
26611 cp_finish_decl can process it. */
26612 bool const_init = false;
26613 tree init = DECL_INITIAL (d);
26614 DECL_INITIAL (d) = NULL_TREE;
26615 DECL_INITIALIZED_P (d) = 0;
26617 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26618 initializer. That function will defer actual emission until
26619 we have a chance to determine linkage. */
26620 DECL_EXTERNAL (d) = 0;
26622 /* Enter the scope of D so that access-checking works correctly. */
26623 bool enter_context = DECL_CLASS_SCOPE_P (d);
26624 if (enter_context)
26625 push_nested_class (DECL_CONTEXT (d));
26627 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26628 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26630 if (enter_context)
26631 pop_nested_class ();
26633 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26634 synthesize_method (d);
26635 else if (TREE_CODE (d) == FUNCTION_DECL)
26637 /* Set up the list of local specializations. */
26638 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26639 tree block = NULL_TREE;
26641 /* Set up context. */
26642 if (nested_p)
26643 block = push_stmt_list ();
26644 else
26646 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26648 perform_instantiation_time_access_checks (code_pattern, args);
26651 /* Create substitution entries for the parameters. */
26652 register_parameter_specializations (code_pattern, d);
26654 /* Substitute into the body of the function. */
26655 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26656 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26657 tf_warning_or_error, d);
26658 else
26660 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26661 tf_warning_or_error, DECL_TI_TEMPLATE (d),
26662 /*integral_constant_expression_p=*/false);
26664 /* Set the current input_location to the end of the function
26665 so that finish_function knows where we are. */
26666 input_location
26667 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26669 /* Remember if we saw an infinite loop in the template. */
26670 current_function_infinite_loop
26671 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26674 /* Finish the function. */
26675 if (nested_p)
26676 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26677 else
26679 d = finish_function (/*inline_p=*/false);
26680 expand_or_defer_fn (d);
26683 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26684 cp_check_omp_declare_reduction (d);
26687 /* We're not deferring instantiation any more. */
26688 if (!nested_p)
26689 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26691 if (push_to_top)
26692 pop_from_top_level ();
26693 else
26694 pop_function_context ();
26696 if (current_function_decl)
26697 restore_omp_privatization_clauses (omp_privatization_save);
26700 /* Produce the definition of D, a _DECL generated from a template. If
26701 DEFER_OK is true, then we don't have to actually do the
26702 instantiation now; we just have to do it sometime. Normally it is
26703 an error if this is an explicit instantiation but D is undefined.
26704 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26705 instantiated class template. */
26707 tree
26708 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26710 tree tmpl = DECL_TI_TEMPLATE (d);
26711 tree gen_args;
26712 tree args;
26713 tree td;
26714 tree code_pattern;
26715 tree spec;
26716 tree gen_tmpl;
26717 bool pattern_defined;
26718 location_t saved_loc = input_location;
26719 int saved_unevaluated_operand = cp_unevaluated_operand;
26720 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26721 bool external_p;
26722 bool deleted_p;
26724 /* This function should only be used to instantiate templates for
26725 functions and static member variables. */
26726 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26728 /* A concept is never instantiated. */
26729 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26731 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26733 if (modules_p ())
26734 /* We may have a pending instantiation of D itself. */
26735 lazy_load_pendings (d);
26737 /* Variables are never deferred; if instantiation is required, they
26738 are instantiated right away. That allows for better code in the
26739 case that an expression refers to the value of the variable --
26740 if the variable has a constant value the referring expression can
26741 take advantage of that fact. */
26742 if (VAR_P (d))
26743 defer_ok = false;
26745 /* Don't instantiate cloned functions. Instead, instantiate the
26746 functions they cloned. */
26747 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26748 d = DECL_CLONED_FUNCTION (d);
26750 if (DECL_TEMPLATE_INSTANTIATED (d)
26751 || TREE_TYPE (d) == error_mark_node
26752 || (TREE_CODE (d) == FUNCTION_DECL
26753 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26754 || DECL_TEMPLATE_SPECIALIZATION (d))
26755 /* D has already been instantiated or explicitly specialized, so
26756 there's nothing for us to do here.
26758 It might seem reasonable to check whether or not D is an explicit
26759 instantiation, and, if so, stop here. But when an explicit
26760 instantiation is deferred until the end of the compilation,
26761 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26762 the instantiation. */
26763 return d;
26765 /* Check to see whether we know that this template will be
26766 instantiated in some other file, as with "extern template"
26767 extension. */
26768 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26770 /* In general, we do not instantiate such templates. */
26771 if (external_p && !always_instantiate_p (d))
26772 return d;
26774 gen_tmpl = most_general_template (tmpl);
26775 gen_args = DECL_TI_ARGS (d);
26777 /* We should already have the extra args. */
26778 gcc_checking_assert (tmpl == gen_tmpl
26779 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26780 == TMPL_ARGS_DEPTH (gen_args)));
26781 /* And what's in the hash table should match D. */
26782 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26783 == d
26784 || spec == NULL_TREE);
26786 /* This needs to happen before any tsubsting. */
26787 if (! push_tinst_level (d))
26788 return d;
26790 auto_timevar tv (TV_TEMPLATE_INST);
26792 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26793 for the instantiation. */
26794 td = template_for_substitution (d);
26795 args = gen_args;
26797 if (variable_template_specialization_p (d))
26799 /* Look up an explicit specialization, if any. */
26800 tree elt = most_specialized_partial_spec (d, tf_warning_or_error);
26801 if (elt && elt != error_mark_node)
26803 td = TREE_VALUE (elt);
26804 args = TREE_PURPOSE (elt);
26808 code_pattern = DECL_TEMPLATE_RESULT (td);
26810 /* We should never be trying to instantiate a member of a class
26811 template or partial specialization. */
26812 gcc_assert (d != code_pattern);
26814 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26815 || DECL_TEMPLATE_SPECIALIZATION (td))
26816 /* In the case of a friend template whose definition is provided
26817 outside the class, we may have too many arguments. Drop the
26818 ones we don't need. The same is true for specializations. */
26819 args = get_innermost_template_args
26820 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26822 if (TREE_CODE (d) == FUNCTION_DECL)
26824 deleted_p = DECL_DELETED_FN (code_pattern);
26825 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26826 && DECL_INITIAL (code_pattern) != error_mark_node)
26827 || DECL_DEFAULTED_FN (code_pattern)
26828 || deleted_p);
26830 else
26832 deleted_p = false;
26833 if (DECL_CLASS_SCOPE_P (code_pattern))
26834 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26835 else
26836 pattern_defined = ! DECL_EXTERNAL (code_pattern);
26839 /* We may be in the middle of deferred access check. Disable it now. */
26840 push_deferring_access_checks (dk_no_deferred);
26842 /* Unless an explicit instantiation directive has already determined
26843 the linkage of D, remember that a definition is available for
26844 this entity. */
26845 if (pattern_defined
26846 && !DECL_INTERFACE_KNOWN (d)
26847 && !DECL_NOT_REALLY_EXTERN (d))
26848 mark_definable (d);
26850 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26851 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26852 input_location = DECL_SOURCE_LOCATION (d);
26854 /* If D is a member of an explicitly instantiated class template,
26855 and no definition is available, treat it like an implicit
26856 instantiation. */
26857 if (!pattern_defined && expl_inst_class_mem_p
26858 && DECL_EXPLICIT_INSTANTIATION (d))
26860 /* Leave linkage flags alone on instantiations with anonymous
26861 visibility. */
26862 if (TREE_PUBLIC (d))
26864 DECL_NOT_REALLY_EXTERN (d) = 0;
26865 DECL_INTERFACE_KNOWN (d) = 0;
26867 SET_DECL_IMPLICIT_INSTANTIATION (d);
26870 /* Defer all other templates, unless we have been explicitly
26871 forbidden from doing so. */
26872 if (/* If there is no definition, we cannot instantiate the
26873 template. */
26874 ! pattern_defined
26875 /* If it's OK to postpone instantiation, do so. */
26876 || defer_ok
26877 /* If this is a static data member that will be defined
26878 elsewhere, we don't want to instantiate the entire data
26879 member, but we do want to instantiate the initializer so that
26880 we can substitute that elsewhere. */
26881 || (external_p && VAR_P (d))
26882 /* Handle here a deleted function too, avoid generating
26883 its body (c++/61080). */
26884 || deleted_p)
26886 /* The definition of the static data member is now required so
26887 we must substitute the initializer. */
26888 if (VAR_P (d)
26889 && !DECL_INITIAL (d)
26890 && DECL_INITIAL (code_pattern))
26892 tree ns;
26893 tree init;
26894 bool const_init = false;
26895 bool enter_context = DECL_CLASS_SCOPE_P (d);
26897 ns = decl_namespace_context (d);
26898 push_nested_namespace (ns);
26899 if (enter_context)
26900 push_nested_class (DECL_CONTEXT (d));
26901 init = tsubst_expr (DECL_INITIAL (code_pattern),
26902 args,
26903 tf_warning_or_error, NULL_TREE,
26904 /*integral_constant_expression_p=*/false);
26905 /* If instantiating the initializer involved instantiating this
26906 again, don't call cp_finish_decl twice. */
26907 if (!DECL_INITIAL (d))
26909 /* Make sure the initializer is still constant, in case of
26910 circular dependency (template/instantiate6.C). */
26911 const_init
26912 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26913 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26914 /*asmspec_tree=*/NULL_TREE, 0);
26916 if (enter_context)
26917 pop_nested_class ();
26918 pop_nested_namespace (ns);
26921 /* We restore the source position here because it's used by
26922 add_pending_template. */
26923 input_location = saved_loc;
26925 if (at_eof && !pattern_defined
26926 && DECL_EXPLICIT_INSTANTIATION (d)
26927 && DECL_NOT_REALLY_EXTERN (d))
26928 /* [temp.explicit]
26930 The definition of a non-exported function template, a
26931 non-exported member function template, or a non-exported
26932 member function or static data member of a class template
26933 shall be present in every translation unit in which it is
26934 explicitly instantiated. */
26935 permerror (input_location, "explicit instantiation of %qD "
26936 "but no definition available", d);
26938 /* If we're in unevaluated context, we just wanted to get the
26939 constant value; this isn't an odr use, so don't queue
26940 a full instantiation. */
26941 if (!cp_unevaluated_operand
26942 /* ??? Historically, we have instantiated inline functions, even
26943 when marked as "extern template". */
26944 && !(external_p && VAR_P (d)))
26945 add_pending_template (d);
26947 else
26949 set_instantiating_module (d);
26950 if (variable_template_p (gen_tmpl))
26951 note_variable_template_instantiation (d);
26952 instantiate_body (td, args, d, false);
26955 pop_deferring_access_checks ();
26956 pop_tinst_level ();
26957 input_location = saved_loc;
26958 cp_unevaluated_operand = saved_unevaluated_operand;
26959 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26961 return d;
26964 /* Run through the list of templates that we wish we could
26965 instantiate, and instantiate any we can. RETRIES is the
26966 number of times we retry pending template instantiation. */
26968 void
26969 instantiate_pending_templates (int retries)
26971 int reconsider;
26972 location_t saved_loc = input_location;
26974 /* Instantiating templates may trigger vtable generation. This in turn
26975 may require further template instantiations. We place a limit here
26976 to avoid infinite loop. */
26977 if (pending_templates && retries >= max_tinst_depth)
26979 tree decl = pending_templates->tinst->maybe_get_node ();
26981 fatal_error (input_location,
26982 "template instantiation depth exceeds maximum of %d"
26983 " instantiating %q+D, possibly from virtual table generation"
26984 " (use %<-ftemplate-depth=%> to increase the maximum)",
26985 max_tinst_depth, decl);
26986 if (TREE_CODE (decl) == FUNCTION_DECL)
26987 /* Pretend that we defined it. */
26988 DECL_INITIAL (decl) = error_mark_node;
26989 return;
26994 struct pending_template **t = &pending_templates;
26995 struct pending_template *last = NULL;
26996 reconsider = 0;
26997 while (*t)
26999 tree instantiation = reopen_tinst_level ((*t)->tinst);
27000 bool complete = false;
27002 if (TYPE_P (instantiation))
27004 if (!COMPLETE_TYPE_P (instantiation))
27006 instantiate_class_template (instantiation);
27007 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27008 for (tree fld = TYPE_FIELDS (instantiation);
27009 fld; fld = TREE_CHAIN (fld))
27010 if ((VAR_P (fld)
27011 || (TREE_CODE (fld) == FUNCTION_DECL
27012 && !DECL_ARTIFICIAL (fld)))
27013 && DECL_TEMPLATE_INSTANTIATION (fld))
27014 instantiate_decl (fld,
27015 /*defer_ok=*/false,
27016 /*expl_inst_class_mem_p=*/false);
27018 if (COMPLETE_TYPE_P (instantiation))
27019 reconsider = 1;
27022 complete = COMPLETE_TYPE_P (instantiation);
27024 else
27026 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27027 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27029 instantiation
27030 = instantiate_decl (instantiation,
27031 /*defer_ok=*/false,
27032 /*expl_inst_class_mem_p=*/false);
27033 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27034 reconsider = 1;
27037 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27038 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27041 if (complete)
27043 /* If INSTANTIATION has been instantiated, then we don't
27044 need to consider it again in the future. */
27045 struct pending_template *drop = *t;
27046 *t = (*t)->next;
27047 set_refcount_ptr (drop->tinst);
27048 pending_template_freelist ().free (drop);
27050 else
27052 last = *t;
27053 t = &(*t)->next;
27055 tinst_depth = 0;
27056 set_refcount_ptr (current_tinst_level);
27058 last_pending_template = last;
27060 while (reconsider);
27062 input_location = saved_loc;
27065 /* Substitute ARGVEC into T, which is a list of initializers for
27066 either base class or a non-static data member. The TREE_PURPOSEs
27067 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27068 instantiate_decl. */
27070 static tree
27071 tsubst_initializer_list (tree t, tree argvec)
27073 tree inits = NULL_TREE;
27074 tree target_ctor = error_mark_node;
27076 for (; t; t = TREE_CHAIN (t))
27078 tree decl;
27079 tree init;
27080 tree expanded_bases = NULL_TREE;
27081 tree expanded_arguments = NULL_TREE;
27082 int i, len = 1;
27084 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27086 tree expr;
27087 tree arg;
27089 /* Expand the base class expansion type into separate base
27090 classes. */
27091 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27092 tf_warning_or_error,
27093 NULL_TREE);
27094 if (expanded_bases == error_mark_node)
27095 continue;
27097 /* We'll be building separate TREE_LISTs of arguments for
27098 each base. */
27099 len = TREE_VEC_LENGTH (expanded_bases);
27100 expanded_arguments = make_tree_vec (len);
27101 for (i = 0; i < len; i++)
27102 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27104 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27105 expand each argument in the TREE_VALUE of t. */
27106 expr = make_node (EXPR_PACK_EXPANSION);
27107 PACK_EXPANSION_LOCAL_P (expr) = true;
27108 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27109 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27111 if (TREE_VALUE (t) == void_type_node)
27112 /* VOID_TYPE_NODE is used to indicate
27113 value-initialization. */
27115 for (i = 0; i < len; i++)
27116 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27118 else
27120 /* Substitute parameter packs into each argument in the
27121 TREE_LIST. */
27122 in_base_initializer = 1;
27123 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27125 tree expanded_exprs;
27127 /* Expand the argument. */
27128 tree value;
27129 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27130 value = TREE_VALUE (arg);
27131 else
27133 value = expr;
27134 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27136 expanded_exprs
27137 = tsubst_pack_expansion (value, argvec,
27138 tf_warning_or_error,
27139 NULL_TREE);
27140 if (expanded_exprs == error_mark_node)
27141 continue;
27143 /* Prepend each of the expanded expressions to the
27144 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27145 for (i = 0; i < len; i++)
27146 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27147 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27148 TREE_VEC_ELT (expanded_arguments, i)
27149 = tree_cons (NULL_TREE,
27150 TREE_VEC_ELT (expanded_exprs, j),
27151 TREE_VEC_ELT (expanded_arguments, i));
27152 else
27153 TREE_VEC_ELT (expanded_arguments, i)
27154 = tree_cons (NULL_TREE,
27155 TREE_VEC_ELT (expanded_exprs, i),
27156 TREE_VEC_ELT (expanded_arguments, i));
27158 in_base_initializer = 0;
27160 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27161 since we built them backwards. */
27162 for (i = 0; i < len; i++)
27164 TREE_VEC_ELT (expanded_arguments, i) =
27165 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27170 for (i = 0; i < len; ++i)
27172 if (expanded_bases)
27174 decl = TREE_VEC_ELT (expanded_bases, i);
27175 decl = expand_member_init (decl);
27176 init = TREE_VEC_ELT (expanded_arguments, i);
27178 else
27180 tree tmp;
27181 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27182 tf_warning_or_error, NULL_TREE);
27184 decl = expand_member_init (decl);
27185 if (decl && !DECL_P (decl))
27186 in_base_initializer = 1;
27188 init = TREE_VALUE (t);
27189 tmp = init;
27190 if (init != void_type_node)
27191 init = tsubst_expr (init, argvec,
27192 tf_warning_or_error, NULL_TREE,
27193 /*integral_constant_expression_p=*/false);
27194 if (init == NULL_TREE && tmp != NULL_TREE)
27195 /* If we had an initializer but it instantiated to nothing,
27196 value-initialize the object. This will only occur when
27197 the initializer was a pack expansion where the parameter
27198 packs used in that expansion were of length zero. */
27199 init = void_type_node;
27200 in_base_initializer = 0;
27203 if (target_ctor != error_mark_node
27204 && init != error_mark_node)
27206 error ("mem-initializer for %qD follows constructor delegation",
27207 decl);
27208 return inits;
27210 /* Look for a target constructor. */
27211 if (init != error_mark_node
27212 && decl && CLASS_TYPE_P (decl)
27213 && same_type_p (decl, current_class_type))
27215 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27216 if (inits)
27218 error ("constructor delegation follows mem-initializer for %qD",
27219 TREE_PURPOSE (inits));
27220 continue;
27222 target_ctor = init;
27225 if (decl)
27227 init = build_tree_list (decl, init);
27228 /* Carry over the dummy TREE_TYPE node containing the source
27229 location. */
27230 TREE_TYPE (init) = TREE_TYPE (t);
27231 TREE_CHAIN (init) = inits;
27232 inits = init;
27236 return inits;
27239 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27240 is the instantiation (which should have been created with
27241 start_enum) and ARGS are the template arguments to use. */
27243 static void
27244 tsubst_enum (tree tag, tree newtag, tree args)
27246 tree e;
27248 if (SCOPED_ENUM_P (newtag))
27249 begin_scope (sk_scoped_enum, newtag);
27251 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27253 tree value;
27254 tree decl = TREE_VALUE (e);
27256 /* Note that in a template enum, the TREE_VALUE is the
27257 CONST_DECL, not the corresponding INTEGER_CST. */
27258 value = tsubst_expr (DECL_INITIAL (decl),
27259 args, tf_warning_or_error, NULL_TREE,
27260 /*integral_constant_expression_p=*/true);
27262 /* Give this enumeration constant the correct access. */
27263 set_current_access_from_decl (decl);
27265 /* Actually build the enumerator itself. Here we're assuming that
27266 enumerators can't have dependent attributes. */
27267 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27268 DECL_ATTRIBUTES (decl),
27269 DECL_SOURCE_LOCATION (decl));
27270 /* Attribute deprecated without an argument isn't sticky: it'll
27271 melt into a tree flag, so we need to propagate the flag here,
27272 since we just created a new enumerator. */
27273 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27274 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27277 if (SCOPED_ENUM_P (newtag))
27278 finish_scope ();
27280 finish_enum_value_list (newtag);
27281 finish_enum (newtag);
27283 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27284 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27285 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27286 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27289 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27290 its type -- but without substituting the innermost set of template
27291 arguments. So, innermost set of template parameters will appear in
27292 the type. */
27294 tree
27295 get_mostly_instantiated_function_type (tree decl)
27297 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27298 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27301 /* Return truthvalue if we're processing a template different from
27302 the last one involved in diagnostics. */
27303 bool
27304 problematic_instantiation_changed (void)
27306 return current_tinst_level != last_error_tinst_level;
27309 /* Remember current template involved in diagnostics. */
27310 void
27311 record_last_problematic_instantiation (void)
27313 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27316 struct tinst_level *
27317 current_instantiation (void)
27319 return current_tinst_level;
27322 /* Return TRUE if current_function_decl is being instantiated, false
27323 otherwise. */
27325 bool
27326 instantiating_current_function_p (void)
27328 return (current_instantiation ()
27329 && (current_instantiation ()->maybe_get_node ()
27330 == current_function_decl));
27333 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27334 type. Return false for ok, true for disallowed. Issue error and
27335 inform messages under control of COMPLAIN. */
27337 static bool
27338 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27340 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27341 return false;
27342 else if (TYPE_PTR_P (type))
27343 return false;
27344 else if (TYPE_REF_P (type)
27345 && !TYPE_REF_IS_RVALUE (type))
27346 return false;
27347 else if (TYPE_PTRMEM_P (type))
27348 return false;
27349 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27351 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27353 if (complain & tf_error)
27354 error ("non-type template parameters of deduced class type only "
27355 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27356 return true;
27358 return false;
27360 else if (TREE_CODE (type) == NULLPTR_TYPE)
27361 return false;
27362 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27363 && cxx_dialect < cxx11)
27364 /* Fall through; before C++11 alias templates, a bound ttp
27365 always instantiates into a class type. */;
27366 else if (WILDCARD_TYPE_P (type))
27367 /* Any other wildcard type not already handled above is allowed. */
27368 return false;
27369 else if (TREE_CODE (type) == COMPLEX_TYPE)
27370 /* Fall through. */;
27371 else if (VOID_TYPE_P (type))
27372 /* Fall through. */;
27373 else if (cxx_dialect >= cxx20)
27375 if (dependent_type_p (type))
27376 return false;
27377 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27378 return true;
27379 if (structural_type_p (type))
27380 return false;
27381 if (complain & tf_error)
27383 auto_diagnostic_group d;
27384 error ("%qT is not a valid type for a template non-type "
27385 "parameter because it is not structural", type);
27386 structural_type_p (type, true);
27388 return true;
27390 else if (CLASS_TYPE_P (type))
27392 if (complain & tf_error)
27393 error ("non-type template parameters of class type only available "
27394 "with %<-std=c++20%> or %<-std=gnu++20%>");
27395 return true;
27398 if (complain & tf_error)
27400 if (type == error_mark_node)
27401 inform (input_location, "invalid template non-type parameter");
27402 else
27403 error ("%q#T is not a valid type for a template non-type parameter",
27404 type);
27406 return true;
27409 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27411 static bool
27412 value_dependent_noexcept_spec_p (tree type)
27414 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27415 if (tree noex = TREE_PURPOSE (spec))
27416 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27417 affect overload resolution and treating it as dependent breaks
27418 things. Same for an unparsed noexcept expression. */
27419 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27420 && TREE_CODE (noex) != DEFERRED_PARSE
27421 && value_dependent_expression_p (noex))
27422 return true;
27424 return false;
27427 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27428 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27430 static bool
27431 dependent_type_p_r (tree type)
27433 tree scope;
27435 /* [temp.dep.type]
27437 A type is dependent if it is:
27439 -- a template parameter. Template template parameters are types
27440 for us (since TYPE_P holds true for them) so we handle
27441 them here. */
27442 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27443 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27444 return true;
27445 /* -- a qualified-id with a nested-name-specifier which contains a
27446 class-name that names a dependent type or whose unqualified-id
27447 names a dependent type. */
27448 if (TREE_CODE (type) == TYPENAME_TYPE)
27449 return true;
27451 /* An alias template specialization can be dependent even if the
27452 resulting type is not. */
27453 if (dependent_alias_template_spec_p (type, nt_transparent))
27454 return true;
27456 /* -- a cv-qualified type where the cv-unqualified type is
27457 dependent.
27458 No code is necessary for this bullet; the code below handles
27459 cv-qualified types, and we don't want to strip aliases with
27460 TYPE_MAIN_VARIANT because of DR 1558. */
27461 /* -- a compound type constructed from any dependent type. */
27462 if (TYPE_PTRMEM_P (type))
27463 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27464 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27465 (type)));
27466 else if (INDIRECT_TYPE_P (type))
27467 return dependent_type_p (TREE_TYPE (type));
27468 else if (FUNC_OR_METHOD_TYPE_P (type))
27470 tree arg_type;
27472 if (dependent_type_p (TREE_TYPE (type)))
27473 return true;
27474 for (arg_type = TYPE_ARG_TYPES (type);
27475 arg_type;
27476 arg_type = TREE_CHAIN (arg_type))
27477 if (dependent_type_p (TREE_VALUE (arg_type)))
27478 return true;
27479 if (cxx_dialect >= cxx17
27480 && value_dependent_noexcept_spec_p (type))
27481 /* A value-dependent noexcept-specifier makes the type dependent. */
27482 return true;
27483 return false;
27485 /* -- an array type constructed from any dependent type or whose
27486 size is specified by a constant expression that is
27487 value-dependent.
27489 We checked for type- and value-dependence of the bounds in
27490 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27491 if (TREE_CODE (type) == ARRAY_TYPE)
27493 if (TYPE_DOMAIN (type)
27494 && dependent_type_p (TYPE_DOMAIN (type)))
27495 return true;
27496 return dependent_type_p (TREE_TYPE (type));
27499 /* -- a template-id in which either the template name is a template
27500 parameter ... */
27501 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27502 return true;
27503 /* ... or any of the template arguments is a dependent type or
27504 an expression that is type-dependent or value-dependent. */
27505 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27506 && (any_dependent_template_arguments_p
27507 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27508 return true;
27510 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
27511 dependent; if the argument of the `typeof' expression is not
27512 type-dependent, then it should already been have resolved. */
27513 if (TREE_CODE (type) == TYPEOF_TYPE
27514 || TREE_CODE (type) == DECLTYPE_TYPE
27515 || TREE_CODE (type) == UNDERLYING_TYPE)
27516 return true;
27518 /* A template argument pack is dependent if any of its packed
27519 arguments are. */
27520 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27522 tree args = ARGUMENT_PACK_ARGS (type);
27523 for (tree arg : tree_vec_range (args))
27524 if (dependent_template_arg_p (arg))
27525 return true;
27528 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27529 be template parameters. */
27530 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27531 return true;
27533 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27534 return true;
27536 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27537 return true;
27539 /* The standard does not specifically mention types that are local
27540 to template functions or local classes, but they should be
27541 considered dependent too. For example:
27543 template <int I> void f() {
27544 enum E { a = I };
27545 S<sizeof (E)> s;
27548 The size of `E' cannot be known until the value of `I' has been
27549 determined. Therefore, `E' must be considered dependent. */
27550 scope = TYPE_CONTEXT (type);
27551 if (scope && TYPE_P (scope))
27552 return dependent_type_p (scope);
27553 /* Don't use type_dependent_expression_p here, as it can lead
27554 to infinite recursion trying to determine whether a lambda
27555 nested in a lambda is dependent (c++/47687). */
27556 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27557 && DECL_LANG_SPECIFIC (scope)
27558 && DECL_TEMPLATE_INFO (scope)
27559 && (any_dependent_template_arguments_p
27560 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27561 return true;
27563 /* Other types are non-dependent. */
27564 return false;
27567 /* Returns TRUE if TYPE is dependent, in the sense of
27568 [temp.dep.type]. Note that a NULL type is considered dependent. */
27570 bool
27571 dependent_type_p (tree type)
27573 /* If there are no template parameters in scope, then there can't be
27574 any dependent types. */
27575 if (!processing_template_decl)
27577 /* If we are not processing a template, then nobody should be
27578 providing us with a dependent type. */
27579 gcc_assert (type);
27580 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27581 return false;
27584 /* If the type is NULL, we have not computed a type for the entity
27585 in question; in that case, the type is dependent. */
27586 if (!type)
27587 return true;
27589 /* Erroneous types can be considered non-dependent. */
27590 if (type == error_mark_node)
27591 return false;
27593 /* If we have not already computed the appropriate value for TYPE,
27594 do so now. */
27595 if (!TYPE_DEPENDENT_P_VALID (type))
27597 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27598 TYPE_DEPENDENT_P_VALID (type) = 1;
27601 return TYPE_DEPENDENT_P (type);
27604 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27605 lookup. In other words, a dependent type that is not the current
27606 instantiation. */
27608 bool
27609 dependent_scope_p (tree scope)
27611 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27612 && !currently_open_class (scope));
27615 /* True if we might find more declarations in SCOPE during instantiation than
27616 we can when parsing the template. */
27618 bool
27619 dependentish_scope_p (tree scope)
27621 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27624 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27625 an unknown base of 'this' (and is therefore instantiation-dependent). */
27627 static bool
27628 unknown_base_ref_p (tree t)
27630 if (!current_class_ptr)
27631 return false;
27633 tree mem = TREE_OPERAND (t, 1);
27634 if (shared_member_p (mem))
27635 return false;
27637 tree cur = current_nonlambda_class_type ();
27638 if (!any_dependent_bases_p (cur))
27639 return false;
27641 tree ctx = TREE_OPERAND (t, 0);
27642 if (DERIVED_FROM_P (ctx, cur))
27643 return false;
27645 return true;
27648 /* T is a SCOPE_REF; return whether we need to consider it
27649 instantiation-dependent so that we can check access at instantiation
27650 time even though we know which member it resolves to. */
27652 static bool
27653 instantiation_dependent_scope_ref_p (tree t)
27655 if (DECL_P (TREE_OPERAND (t, 1))
27656 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27657 && !dependent_scope_p (TREE_OPERAND (t, 0))
27658 && !unknown_base_ref_p (t)
27659 && accessible_in_template_p (TREE_OPERAND (t, 0),
27660 TREE_OPERAND (t, 1)))
27661 return false;
27662 else
27663 return true;
27666 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27667 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27668 expression. */
27670 /* Note that this predicate is not appropriate for general expressions;
27671 only constant expressions (that satisfy potential_constant_expression)
27672 can be tested for value dependence. */
27674 bool
27675 value_dependent_expression_p (tree expression)
27677 if (!processing_template_decl || expression == NULL_TREE)
27678 return false;
27680 /* A type-dependent expression is also value-dependent. */
27681 if (type_dependent_expression_p (expression))
27682 return true;
27684 switch (TREE_CODE (expression))
27686 case BASELINK:
27687 /* A dependent member function of the current instantiation. */
27688 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27690 case FUNCTION_DECL:
27691 /* A dependent member function of the current instantiation. */
27692 if (DECL_CLASS_SCOPE_P (expression)
27693 && dependent_type_p (DECL_CONTEXT (expression)))
27694 return true;
27695 break;
27697 case IDENTIFIER_NODE:
27698 /* A name that has not been looked up -- must be dependent. */
27699 return true;
27701 case TEMPLATE_PARM_INDEX:
27702 /* A non-type template parm. */
27703 return true;
27705 case CONST_DECL:
27706 /* A non-type template parm. */
27707 if (DECL_TEMPLATE_PARM_P (expression))
27708 return true;
27709 return value_dependent_expression_p (DECL_INITIAL (expression));
27711 case VAR_DECL:
27712 /* A constant with literal type and is initialized
27713 with an expression that is value-dependent. */
27714 if (DECL_DEPENDENT_INIT_P (expression)
27715 /* FIXME cp_finish_decl doesn't fold reference initializers. */
27716 || TYPE_REF_P (TREE_TYPE (expression)))
27717 return true;
27718 if (DECL_HAS_VALUE_EXPR_P (expression))
27720 tree value_expr = DECL_VALUE_EXPR (expression);
27721 if (value_dependent_expression_p (value_expr)
27722 /* __PRETTY_FUNCTION__ inside a template function is dependent
27723 on the name of the function. */
27724 || (DECL_PRETTY_FUNCTION_P (expression)
27725 /* It might be used in a template, but not a template
27726 function, in which case its DECL_VALUE_EXPR will be
27727 "top level". */
27728 && value_expr == error_mark_node))
27729 return true;
27731 return false;
27733 case DYNAMIC_CAST_EXPR:
27734 case STATIC_CAST_EXPR:
27735 case CONST_CAST_EXPR:
27736 case REINTERPRET_CAST_EXPR:
27737 case CAST_EXPR:
27738 case IMPLICIT_CONV_EXPR:
27739 /* These expressions are value-dependent if the type to which
27740 the cast occurs is dependent or the expression being casted
27741 is value-dependent. */
27743 tree type = TREE_TYPE (expression);
27745 if (dependent_type_p (type))
27746 return true;
27748 /* A functional cast has a list of operands. */
27749 expression = TREE_OPERAND (expression, 0);
27750 if (!expression)
27752 /* If there are no operands, it must be an expression such
27753 as "int()". This should not happen for aggregate types
27754 because it would form non-constant expressions. */
27755 gcc_assert (cxx_dialect >= cxx11
27756 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27758 return false;
27761 if (TREE_CODE (expression) == TREE_LIST)
27762 return any_value_dependent_elements_p (expression);
27764 if (TREE_CODE (type) == REFERENCE_TYPE
27765 && has_value_dependent_address (expression))
27766 return true;
27768 return value_dependent_expression_p (expression);
27771 case SIZEOF_EXPR:
27772 if (SIZEOF_EXPR_TYPE_P (expression))
27773 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27774 /* FALLTHRU */
27775 case ALIGNOF_EXPR:
27776 case TYPEID_EXPR:
27777 /* A `sizeof' expression is value-dependent if the operand is
27778 type-dependent or is a pack expansion. */
27779 expression = TREE_OPERAND (expression, 0);
27780 if (PACK_EXPANSION_P (expression))
27781 return true;
27782 else if (TYPE_P (expression))
27783 return dependent_type_p (expression);
27784 return instantiation_dependent_uneval_expression_p (expression);
27786 case AT_ENCODE_EXPR:
27787 /* An 'encode' expression is value-dependent if the operand is
27788 type-dependent. */
27789 expression = TREE_OPERAND (expression, 0);
27790 return dependent_type_p (expression);
27792 case NOEXCEPT_EXPR:
27793 expression = TREE_OPERAND (expression, 0);
27794 return instantiation_dependent_uneval_expression_p (expression);
27796 case SCOPE_REF:
27797 /* All instantiation-dependent expressions should also be considered
27798 value-dependent. */
27799 return instantiation_dependent_scope_ref_p (expression);
27801 case COMPONENT_REF:
27802 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27803 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
27805 case NONTYPE_ARGUMENT_PACK:
27806 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
27807 is value-dependent. */
27808 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
27809 if (value_dependent_expression_p (arg))
27810 return true;
27811 return false;
27813 case TRAIT_EXPR:
27815 tree type2 = TRAIT_EXPR_TYPE2 (expression);
27817 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27818 return true;
27820 if (!type2)
27821 return false;
27823 if (TREE_CODE (type2) != TREE_LIST)
27824 return dependent_type_p (type2);
27826 for (; type2; type2 = TREE_CHAIN (type2))
27827 if (dependent_type_p (TREE_VALUE (type2)))
27828 return true;
27830 return false;
27833 case MODOP_EXPR:
27834 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27835 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27837 case ARRAY_REF:
27838 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27839 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27841 case ADDR_EXPR:
27843 tree op = TREE_OPERAND (expression, 0);
27844 return (value_dependent_expression_p (op)
27845 || has_value_dependent_address (op));
27848 case REQUIRES_EXPR:
27849 /* Treat all requires-expressions as value-dependent so
27850 we don't try to fold them. */
27851 return true;
27853 case TYPE_REQ:
27854 return dependent_type_p (TREE_OPERAND (expression, 0));
27856 case CALL_EXPR:
27858 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27859 return true;
27860 tree fn = get_callee_fndecl (expression);
27861 int i, nargs;
27862 nargs = call_expr_nargs (expression);
27863 for (i = 0; i < nargs; ++i)
27865 tree op = CALL_EXPR_ARG (expression, i);
27866 /* In a call to a constexpr member function, look through the
27867 implicit ADDR_EXPR on the object argument so that it doesn't
27868 cause the call to be considered value-dependent. We also
27869 look through it in potential_constant_expression. */
27870 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27871 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27872 && TREE_CODE (op) == ADDR_EXPR)
27873 op = TREE_OPERAND (op, 0);
27874 if (value_dependent_expression_p (op))
27875 return true;
27877 return false;
27880 case TEMPLATE_ID_EXPR:
27881 return concept_definition_p (TREE_OPERAND (expression, 0))
27882 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
27884 case CONSTRUCTOR:
27886 unsigned ix;
27887 tree val;
27888 if (dependent_type_p (TREE_TYPE (expression)))
27889 return true;
27890 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27891 if (value_dependent_expression_p (val))
27892 return true;
27893 return false;
27896 case STMT_EXPR:
27897 /* Treat a GNU statement expression as dependent to avoid crashing
27898 under instantiate_non_dependent_expr; it can't be constant. */
27899 return true;
27901 case NEW_EXPR:
27902 case VEC_NEW_EXPR:
27903 /* The second operand is a type, which type_dependent_expression_p
27904 (and therefore value_dependent_expression_p) doesn't want to see. */
27905 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27906 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
27907 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
27909 default:
27910 /* A constant expression is value-dependent if any subexpression is
27911 value-dependent. */
27912 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27914 case tcc_reference:
27915 case tcc_unary:
27916 case tcc_comparison:
27917 case tcc_binary:
27918 case tcc_expression:
27919 case tcc_vl_exp:
27921 int i, len = cp_tree_operand_length (expression);
27923 for (i = 0; i < len; i++)
27925 tree t = TREE_OPERAND (expression, i);
27927 /* In some cases, some of the operands may be missing.
27928 (For example, in the case of PREDECREMENT_EXPR, the
27929 amount to increment by may be missing.) That doesn't
27930 make the expression dependent. */
27931 if (t && value_dependent_expression_p (t))
27932 return true;
27935 break;
27936 default:
27937 break;
27939 break;
27942 /* The expression is not value-dependent. */
27943 return false;
27946 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27947 [temp.dep.expr]. Note that an expression with no type is
27948 considered dependent. Other parts of the compiler arrange for an
27949 expression with type-dependent subexpressions to have no type, so
27950 this function doesn't have to be fully recursive. */
27952 bool
27953 type_dependent_expression_p (tree expression)
27955 if (!processing_template_decl)
27956 return false;
27958 if (expression == NULL_TREE || expression == error_mark_node)
27959 return false;
27961 gcc_checking_assert (!TYPE_P (expression));
27963 STRIP_ANY_LOCATION_WRAPPER (expression);
27965 /* An unresolved name is always dependent. */
27966 if (identifier_p (expression)
27967 || TREE_CODE (expression) == USING_DECL
27968 || TREE_CODE (expression) == WILDCARD_DECL)
27969 return true;
27971 /* A lambda-expression in template context is dependent. dependent_type_p is
27972 true for a lambda in the scope of a class or function template, but that
27973 doesn't cover all template contexts, like a default template argument. */
27974 if (TREE_CODE (expression) == LAMBDA_EXPR)
27975 return true;
27977 /* A fold expression is type-dependent. */
27978 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27979 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27980 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27981 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27982 return true;
27984 /* Some expression forms are never type-dependent. */
27985 if (TREE_CODE (expression) == SIZEOF_EXPR
27986 || TREE_CODE (expression) == ALIGNOF_EXPR
27987 || TREE_CODE (expression) == AT_ENCODE_EXPR
27988 || TREE_CODE (expression) == NOEXCEPT_EXPR
27989 || TREE_CODE (expression) == TRAIT_EXPR
27990 || TREE_CODE (expression) == TYPEID_EXPR
27991 || TREE_CODE (expression) == DELETE_EXPR
27992 || TREE_CODE (expression) == VEC_DELETE_EXPR
27993 || TREE_CODE (expression) == THROW_EXPR
27994 || TREE_CODE (expression) == REQUIRES_EXPR)
27995 return false;
27997 /* The types of these expressions depends only on the type to which
27998 the cast occurs. */
27999 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28000 || TREE_CODE (expression) == STATIC_CAST_EXPR
28001 || TREE_CODE (expression) == CONST_CAST_EXPR
28002 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28003 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28004 || TREE_CODE (expression) == CAST_EXPR)
28005 return dependent_type_p (TREE_TYPE (expression));
28007 /* The types of these expressions depends only on the type created
28008 by the expression. */
28009 if (TREE_CODE (expression) == NEW_EXPR
28010 || TREE_CODE (expression) == VEC_NEW_EXPR)
28012 /* For NEW_EXPR tree nodes created inside a template, either
28013 the object type itself or a TREE_LIST may appear as the
28014 operand 1. */
28015 tree type = TREE_OPERAND (expression, 1);
28016 if (TREE_CODE (type) == TREE_LIST)
28017 /* This is an array type. We need to check array dimensions
28018 as well. */
28019 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28020 || value_dependent_expression_p
28021 (TREE_OPERAND (TREE_VALUE (type), 1));
28022 /* Array type whose dimension has to be deduced. */
28023 else if (TREE_CODE (type) == ARRAY_TYPE
28024 && TREE_OPERAND (expression, 2) == NULL_TREE)
28025 return true;
28026 else
28027 return dependent_type_p (type);
28030 if (TREE_CODE (expression) == SCOPE_REF)
28032 tree scope = TREE_OPERAND (expression, 0);
28033 tree name = TREE_OPERAND (expression, 1);
28035 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28036 contains an identifier associated by name lookup with one or more
28037 declarations declared with a dependent type, or...a
28038 nested-name-specifier or qualified-id that names a member of an
28039 unknown specialization. */
28040 return (type_dependent_expression_p (name)
28041 || dependent_scope_p (scope));
28044 if (TREE_CODE (expression) == TEMPLATE_DECL
28045 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28046 return uses_outer_template_parms (expression);
28048 if (TREE_CODE (expression) == STMT_EXPR)
28049 expression = stmt_expr_value_expr (expression);
28051 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28053 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28054 if (type_dependent_expression_p (elt.value))
28055 return true;
28056 return false;
28059 /* A static data member of the current instantiation with incomplete
28060 array type is type-dependent, as the definition and specializations
28061 can have different bounds. */
28062 if (VAR_P (expression)
28063 && DECL_CLASS_SCOPE_P (expression)
28064 && dependent_type_p (DECL_CONTEXT (expression))
28065 && VAR_HAD_UNKNOWN_BOUND (expression))
28066 return true;
28068 /* An array of unknown bound depending on a variadic parameter, eg:
28070 template<typename... Args>
28071 void foo (Args... args)
28073 int arr[] = { args... };
28076 template<int... vals>
28077 void bar ()
28079 int arr[] = { vals... };
28082 If the array has no length and has an initializer, it must be that
28083 we couldn't determine its length in cp_complete_array_type because
28084 it is dependent. */
28085 if (((VAR_P (expression) && DECL_INITIAL (expression))
28086 || COMPOUND_LITERAL_P (expression))
28087 && TREE_TYPE (expression) != NULL_TREE
28088 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28089 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28090 return true;
28092 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28093 if (BASELINK_P (expression))
28095 if (BASELINK_OPTYPE (expression)
28096 && dependent_type_p (BASELINK_OPTYPE (expression)))
28097 return true;
28098 expression = BASELINK_FUNCTIONS (expression);
28101 /* A function or variable template-id is type-dependent if it has any
28102 dependent template arguments. */
28103 if (VAR_OR_FUNCTION_DECL_P (expression)
28104 && DECL_LANG_SPECIFIC (expression)
28105 && DECL_TEMPLATE_INFO (expression))
28107 /* Consider the innermost template arguments, since those are the ones
28108 that come from the template-id; the template arguments for the
28109 enclosing class do not make it type-dependent unless they are used in
28110 the type of the decl. */
28111 if (instantiates_primary_template_p (expression)
28112 && (any_dependent_template_arguments_p
28113 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28114 return true;
28117 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28118 type-dependent. Checking this is important for functions with auto return
28119 type, which looks like a dependent type. */
28120 if (TREE_CODE (expression) == FUNCTION_DECL
28121 && !(DECL_CLASS_SCOPE_P (expression)
28122 && dependent_type_p (DECL_CONTEXT (expression)))
28123 && !(DECL_LANG_SPECIFIC (expression)
28124 && DECL_UNIQUE_FRIEND_P (expression)
28125 && (!DECL_FRIEND_CONTEXT (expression)
28126 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28127 && !DECL_LOCAL_DECL_P (expression))
28129 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28130 || undeduced_auto_decl (expression));
28131 return false;
28134 /* Otherwise, its constraints could still depend on outer template parameters
28135 from its (dependent) scope. */
28136 if (TREE_CODE (expression) == FUNCTION_DECL
28137 /* As an optimization, check this cheaper sufficient condition first.
28138 (At this point we've established that we're looking at a member of
28139 a dependent class, so it makes sense to start treating say undeduced
28140 auto as dependent.) */
28141 && !dependent_type_p (TREE_TYPE (expression))
28142 && uses_outer_template_parms_in_constraints (expression))
28143 return true;
28145 /* Always dependent, on the number of arguments if nothing else. */
28146 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28147 return true;
28149 if (TREE_TYPE (expression) == unknown_type_node)
28151 if (TREE_CODE (expression) == ADDR_EXPR)
28152 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28153 if (TREE_CODE (expression) == COMPONENT_REF
28154 || TREE_CODE (expression) == OFFSET_REF)
28156 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28157 return true;
28158 expression = TREE_OPERAND (expression, 1);
28159 if (identifier_p (expression))
28160 return false;
28162 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28163 if (TREE_CODE (expression) == SCOPE_REF)
28164 return false;
28166 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28167 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28168 || TREE_CODE (expression) == CO_YIELD_EXPR)
28169 return true;
28171 if (BASELINK_P (expression))
28173 if (BASELINK_OPTYPE (expression)
28174 && dependent_type_p (BASELINK_OPTYPE (expression)))
28175 return true;
28176 expression = BASELINK_FUNCTIONS (expression);
28179 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28181 if (any_dependent_template_arguments_p
28182 (TREE_OPERAND (expression, 1)))
28183 return true;
28184 expression = TREE_OPERAND (expression, 0);
28185 if (identifier_p (expression))
28186 return true;
28189 gcc_assert (OVL_P (expression));
28191 for (lkp_iterator iter (expression); iter; ++iter)
28192 if (type_dependent_expression_p (*iter))
28193 return true;
28195 return false;
28198 /* The type of a non-type template parm declared with a placeholder type
28199 depends on the corresponding template argument, even though
28200 placeholders are not normally considered dependent. */
28201 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28202 && is_auto (TREE_TYPE (expression)))
28203 return true;
28205 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28207 /* Dependent type attributes might not have made it from the decl to
28208 the type yet. */
28209 if (DECL_P (expression)
28210 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28211 return true;
28213 return (dependent_type_p (TREE_TYPE (expression)));
28216 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28217 type-dependent if the expression refers to a member of the current
28218 instantiation and the type of the referenced member is dependent, or the
28219 class member access expression refers to a member of an unknown
28220 specialization.
28222 This function returns true if the OBJECT in such a class member access
28223 expression is of an unknown specialization. */
28225 bool
28226 type_dependent_object_expression_p (tree object)
28228 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28229 dependent. */
28230 if (TREE_CODE (object) == IDENTIFIER_NODE)
28231 return true;
28232 tree scope = TREE_TYPE (object);
28233 return (!scope || dependent_scope_p (scope));
28236 /* walk_tree callback function for instantiation_dependent_expression_p,
28237 below. Returns non-zero if a dependent subexpression is found. */
28239 static tree
28240 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28241 void * /*data*/)
28243 if (TYPE_P (*tp))
28245 /* We don't have to worry about decltype currently because decltype
28246 of an instantiation-dependent expr is a dependent type. This
28247 might change depending on the resolution of DR 1172. */
28248 *walk_subtrees = false;
28249 return NULL_TREE;
28251 enum tree_code code = TREE_CODE (*tp);
28252 switch (code)
28254 /* Don't treat an argument list as dependent just because it has no
28255 TREE_TYPE. */
28256 case TREE_LIST:
28257 case TREE_VEC:
28258 case NONTYPE_ARGUMENT_PACK:
28259 return NULL_TREE;
28261 case TEMPLATE_PARM_INDEX:
28262 if (dependent_type_p (TREE_TYPE (*tp)))
28263 return *tp;
28264 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28265 return *tp;
28266 /* We'll check value-dependence separately. */
28267 return NULL_TREE;
28269 /* Handle expressions with type operands. */
28270 case SIZEOF_EXPR:
28271 case ALIGNOF_EXPR:
28272 case TYPEID_EXPR:
28273 case AT_ENCODE_EXPR:
28275 tree op = TREE_OPERAND (*tp, 0);
28276 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28277 op = TREE_TYPE (op);
28278 if (TYPE_P (op))
28280 if (dependent_type_p (op))
28281 return *tp;
28282 else
28284 *walk_subtrees = false;
28285 return NULL_TREE;
28288 break;
28291 case COMPONENT_REF:
28292 if (identifier_p (TREE_OPERAND (*tp, 1)))
28293 /* In a template, finish_class_member_access_expr creates a
28294 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28295 type-dependent, so that we can check access control at
28296 instantiation time (PR 42277). See also Core issue 1273. */
28297 return *tp;
28298 break;
28300 case SCOPE_REF:
28301 if (instantiation_dependent_scope_ref_p (*tp))
28302 return *tp;
28303 else
28304 break;
28306 /* Treat statement-expressions as dependent. */
28307 case BIND_EXPR:
28308 return *tp;
28310 /* Treat requires-expressions as dependent. */
28311 case REQUIRES_EXPR:
28312 return *tp;
28314 case CONSTRUCTOR:
28315 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28316 return *tp;
28317 break;
28319 case TEMPLATE_DECL:
28320 case FUNCTION_DECL:
28321 /* Before C++17, a noexcept-specifier isn't part of the function type
28322 so it doesn't affect type dependence, but we still want to consider it
28323 for instantiation dependence. */
28324 if (cxx_dialect < cxx17
28325 && DECL_DECLARES_FUNCTION_P (*tp)
28326 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28327 return *tp;
28328 break;
28330 default:
28331 break;
28334 if (type_dependent_expression_p (*tp))
28335 return *tp;
28336 else
28337 return NULL_TREE;
28340 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28341 sense defined by the ABI:
28343 "An expression is instantiation-dependent if it is type-dependent
28344 or value-dependent, or it has a subexpression that is type-dependent
28345 or value-dependent."
28347 Except don't actually check value-dependence for unevaluated expressions,
28348 because in sizeof(i) we don't care about the value of i. Checking
28349 type-dependence will in turn check value-dependence of array bounds/template
28350 arguments as needed. */
28352 bool
28353 instantiation_dependent_uneval_expression_p (tree expression)
28355 tree result;
28357 if (!processing_template_decl)
28358 return false;
28360 if (expression == error_mark_node)
28361 return false;
28363 result = cp_walk_tree_without_duplicates (&expression,
28364 instantiation_dependent_r, NULL);
28365 return result != NULL_TREE;
28368 /* As above, but also check value-dependence of the expression as a whole. */
28370 bool
28371 instantiation_dependent_expression_p (tree expression)
28373 return (instantiation_dependent_uneval_expression_p (expression)
28374 || (processing_template_decl
28375 && potential_constant_expression (expression)
28376 && value_dependent_expression_p (expression)));
28379 /* Like type_dependent_expression_p, but it also works while not processing
28380 a template definition, i.e. during substitution or mangling. */
28382 bool
28383 type_dependent_expression_p_push (tree expr)
28385 bool b;
28386 ++processing_template_decl;
28387 b = type_dependent_expression_p (expr);
28388 --processing_template_decl;
28389 return b;
28392 /* Returns TRUE if ARGS contains a type-dependent expression. */
28394 bool
28395 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28397 unsigned int i;
28398 tree arg;
28400 FOR_EACH_VEC_SAFE_ELT (args, i, arg)
28402 if (type_dependent_expression_p (arg))
28403 return true;
28405 return false;
28408 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28409 expressions) contains any type-dependent expressions. */
28411 bool
28412 any_type_dependent_elements_p (const_tree list)
28414 for (; list; list = TREE_CHAIN (list))
28415 if (type_dependent_expression_p (TREE_VALUE (list)))
28416 return true;
28418 return false;
28421 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28422 expressions) contains any value-dependent expressions. */
28424 bool
28425 any_value_dependent_elements_p (const_tree list)
28427 for (; list; list = TREE_CHAIN (list))
28428 if (value_dependent_expression_p (TREE_VALUE (list)))
28429 return true;
28431 return false;
28434 /* Returns TRUE if the ARG (a template argument) is dependent. */
28436 bool
28437 dependent_template_arg_p (tree arg)
28439 if (!processing_template_decl)
28440 return false;
28442 /* Assume a template argument that was wrongly written by the user
28443 is dependent. This is consistent with what
28444 any_dependent_template_arguments_p [that calls this function]
28445 does. */
28446 if (!arg || arg == error_mark_node)
28447 return true;
28449 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28450 arg = argument_pack_select_arg (arg);
28452 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28453 return true;
28454 if (TREE_CODE (arg) == TEMPLATE_DECL)
28456 if (DECL_TEMPLATE_PARM_P (arg))
28457 return true;
28458 /* A member template of a dependent class is not necessarily
28459 type-dependent, but it is a dependent template argument because it
28460 will be a member of an unknown specialization to that template. */
28461 tree scope = CP_DECL_CONTEXT (arg);
28462 return TYPE_P (scope) && dependent_type_p (scope);
28464 else if (ARGUMENT_PACK_P (arg))
28466 tree args = ARGUMENT_PACK_ARGS (arg);
28467 for (tree arg : tree_vec_range (args))
28468 if (dependent_template_arg_p (arg))
28469 return true;
28470 return false;
28472 else if (TYPE_P (arg))
28473 return dependent_type_p (arg);
28474 else
28475 return value_dependent_expression_p (arg);
28478 /* Identify any expressions that use function parms. */
28480 static tree
28481 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28483 tree t = *tp;
28484 if (TREE_CODE (t) == PARM_DECL)
28486 *walk_subtrees = 0;
28487 return t;
28489 return NULL_TREE;
28492 /* Returns true if a type specialization formed using the template
28493 arguments ARGS needs to use structural equality. */
28495 bool
28496 any_template_arguments_need_structural_equality_p (tree args)
28498 int i;
28499 int j;
28501 if (!args)
28502 return false;
28503 if (args == error_mark_node)
28504 return true;
28506 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28508 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28509 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28511 tree arg = TREE_VEC_ELT (level, j);
28512 tree packed_args = NULL_TREE;
28513 int k, len = 1;
28515 if (ARGUMENT_PACK_P (arg))
28517 /* Look inside the argument pack. */
28518 packed_args = ARGUMENT_PACK_ARGS (arg);
28519 len = TREE_VEC_LENGTH (packed_args);
28522 for (k = 0; k < len; ++k)
28524 if (packed_args)
28525 arg = TREE_VEC_ELT (packed_args, k);
28527 if (error_operand_p (arg))
28528 return true;
28529 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28530 continue;
28531 else if (arg == any_targ_node)
28532 /* An any_targ_node argument (added by add_defaults_to_ttp)
28533 makes the corresponding specialization not canonicalizable,
28534 since template_args_equal always return true for it. We
28535 may see this when called from bind_template_template_parm. */
28536 return true;
28537 /* Checking current_function_decl because this structural
28538 comparison is only necessary for redeclaration. */
28539 else if (!current_function_decl
28540 && dependent_template_arg_p (arg)
28541 && (cp_walk_tree_without_duplicates
28542 (&arg, find_parm_usage_r, NULL)))
28543 /* The identity of a class template specialization that uses
28544 a function parameter depends on the identity of the function.
28545 And if this specialization appeared in the trailing return
28546 type thereof, we don't know the identity of the function
28547 (e.g. if it's a redeclaration or a new function) until we
28548 form its signature and go through duplicate_decls. Thus
28549 it's unsafe to decide on a canonical type now (which depends
28550 on the DECL_CONTEXT of the function parameter, which can get
28551 mutated after the fact by duplicate_decls), so just require
28552 structural equality in this case (PR52830). */
28553 return true;
28558 return false;
28561 /* Returns true if ARGS (a collection of template arguments) contains
28562 any dependent arguments. */
28564 bool
28565 any_dependent_template_arguments_p (const_tree args)
28567 int i;
28568 int j;
28570 if (!args)
28571 return false;
28572 if (args == error_mark_node)
28573 return true;
28575 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28577 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28578 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28579 if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
28580 return true;
28583 return false;
28586 /* Returns true if ARGS contains any errors. */
28588 bool
28589 any_erroneous_template_args_p (const_tree args)
28591 int i;
28592 int j;
28594 if (args == error_mark_node)
28595 return true;
28597 if (args && TREE_CODE (args) != TREE_VEC)
28599 if (tree ti = get_template_info (args))
28600 args = TI_ARGS (ti);
28601 else
28602 args = NULL_TREE;
28605 if (!args)
28606 return false;
28608 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28610 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28611 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28612 if (error_operand_p (TREE_VEC_ELT (level, j)))
28613 return true;
28616 return false;
28619 /* Returns TRUE if the template TMPL is type-dependent. */
28621 bool
28622 dependent_template_p (tree tmpl)
28624 if (TREE_CODE (tmpl) == OVERLOAD)
28626 for (lkp_iterator iter (tmpl); iter; ++iter)
28627 if (dependent_template_p (*iter))
28628 return true;
28629 return false;
28632 /* Template template parameters are dependent. */
28633 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28634 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28635 return true;
28636 /* So are names that have not been looked up. */
28637 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28638 return true;
28639 return false;
28642 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28644 bool
28645 dependent_template_id_p (tree tmpl, tree args)
28647 return (dependent_template_p (tmpl)
28648 || any_dependent_template_arguments_p (args));
28651 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28652 are dependent. */
28654 bool
28655 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28657 int i;
28659 if (!processing_template_decl)
28660 return false;
28662 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28664 tree decl = TREE_VEC_ELT (declv, i);
28665 tree init = TREE_VEC_ELT (initv, i);
28666 tree cond = TREE_VEC_ELT (condv, i);
28667 tree incr = TREE_VEC_ELT (incrv, i);
28669 if (type_dependent_expression_p (decl)
28670 || TREE_CODE (decl) == SCOPE_REF)
28671 return true;
28673 if (init && type_dependent_expression_p (init))
28674 return true;
28676 if (cond == global_namespace)
28677 return true;
28679 if (type_dependent_expression_p (cond))
28680 return true;
28682 if (COMPARISON_CLASS_P (cond)
28683 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28684 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28685 return true;
28687 if (TREE_CODE (incr) == MODOP_EXPR)
28689 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28690 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28691 return true;
28693 else if (type_dependent_expression_p (incr))
28694 return true;
28695 else if (TREE_CODE (incr) == MODIFY_EXPR)
28697 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28698 return true;
28699 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28701 tree t = TREE_OPERAND (incr, 1);
28702 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28703 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28704 return true;
28706 /* If this loop has a class iterator with != comparison
28707 with increment other than i++/++i/i--/--i, make sure the
28708 increment is constant. */
28709 if (CLASS_TYPE_P (TREE_TYPE (decl))
28710 && TREE_CODE (cond) == NE_EXPR)
28712 if (TREE_OPERAND (t, 0) == decl)
28713 t = TREE_OPERAND (t, 1);
28714 else
28715 t = TREE_OPERAND (t, 0);
28716 if (TREE_CODE (t) != INTEGER_CST)
28717 return true;
28723 return false;
28726 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28727 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
28728 no such TYPE can be found. Note that this function peers inside
28729 uninstantiated templates and therefore should be used only in
28730 extremely limited situations. ONLY_CURRENT_P restricts this
28731 peering to the currently open classes hierarchy (which is required
28732 when comparing types). */
28734 tree
28735 resolve_typename_type (tree type, bool only_current_p)
28737 tree scope;
28738 tree name;
28739 tree decl;
28740 int quals;
28741 tree pushed_scope;
28742 tree result;
28744 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28746 scope = TYPE_CONTEXT (type);
28747 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
28748 gcc_checking_assert (uses_template_parms (scope));
28750 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28751 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28752 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28753 representing the typedef. In that case TYPE_IDENTIFIER (type) is
28754 not the non-qualified identifier of the TYPENAME_TYPE anymore.
28755 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28756 the TYPENAME_TYPE instead, we avoid messing up with a possible
28757 typedef variant case. */
28758 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28760 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28761 it first before we can figure out what NAME refers to. */
28762 if (TREE_CODE (scope) == TYPENAME_TYPE)
28764 if (TYPENAME_IS_RESOLVING_P (scope))
28765 /* Given a class template A with a dependent base with nested type C,
28766 typedef typename A::C::C C will land us here, as trying to resolve
28767 the initial A::C leads to the local C typedef, which leads back to
28768 A::C::C. So we break the recursion now. */
28769 return type;
28770 else
28771 scope = resolve_typename_type (scope, only_current_p);
28773 /* If we don't know what SCOPE refers to, then we cannot resolve the
28774 TYPENAME_TYPE. */
28775 if (!CLASS_TYPE_P (scope))
28776 return type;
28777 /* If this is a typedef, we don't want to look inside (c++/11987). */
28778 if (typedef_variant_p (type))
28779 return type;
28780 /* If SCOPE isn't the template itself, it will not have a valid
28781 TYPE_FIELDS list. */
28782 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
28783 /* scope is either the template itself or a compatible instantiation
28784 like X<T>, so look up the name in the original template. */
28785 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
28786 /* If scope has no fields, it can't be a current instantiation. Check this
28787 before currently_open_class to avoid infinite recursion (71515). */
28788 if (!TYPE_FIELDS (scope))
28789 return type;
28790 /* If the SCOPE is not the current instantiation, there's no reason
28791 to look inside it. */
28792 if (only_current_p && !currently_open_class (scope))
28793 return type;
28794 /* Enter the SCOPE so that name lookup will be resolved as if we
28795 were in the class definition. In particular, SCOPE will no
28796 longer be considered a dependent type. */
28797 pushed_scope = push_scope (scope);
28798 /* Look up the declaration. */
28799 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
28800 tf_warning_or_error);
28802 result = NULL_TREE;
28804 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
28805 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
28806 tree fullname = TYPENAME_TYPE_FULLNAME (type);
28807 if (!decl)
28808 /*nop*/;
28809 else if (identifier_p (fullname)
28810 && TREE_CODE (decl) == TYPE_DECL)
28812 result = TREE_TYPE (decl);
28813 if (result == error_mark_node)
28814 result = NULL_TREE;
28816 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
28817 && DECL_CLASS_TEMPLATE_P (decl))
28819 /* Obtain the template and the arguments. */
28820 tree tmpl = TREE_OPERAND (fullname, 0);
28821 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
28823 /* We get here with a plain identifier because a previous tentative
28824 parse of the nested-name-specifier as part of a ptr-operator saw
28825 ::template X<A>. The use of ::template is necessary in a
28826 ptr-operator, but wrong in a declarator-id.
28828 [temp.names]: In a qualified-id of a declarator-id, the keyword
28829 template shall not appear at the top level. */
28830 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
28831 "keyword %<template%> not allowed in declarator-id");
28832 tmpl = decl;
28834 tree args = TREE_OPERAND (fullname, 1);
28835 /* Instantiate the template. */
28836 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
28837 /*entering_scope=*/true,
28838 tf_error | tf_user);
28839 if (result == error_mark_node)
28840 result = NULL_TREE;
28843 /* Leave the SCOPE. */
28844 if (pushed_scope)
28845 pop_scope (pushed_scope);
28847 /* If we failed to resolve it, return the original typename. */
28848 if (!result)
28849 return type;
28851 /* If lookup found a typename type, resolve that too. */
28852 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
28854 /* Ill-formed programs can cause infinite recursion here, so we
28855 must catch that. */
28856 TYPENAME_IS_RESOLVING_P (result) = 1;
28857 result = resolve_typename_type (result, only_current_p);
28858 TYPENAME_IS_RESOLVING_P (result) = 0;
28861 /* Qualify the resulting type. */
28862 quals = cp_type_quals (type);
28863 if (quals)
28864 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
28866 return result;
28869 /* EXPR is an expression which is not type-dependent. Return a proxy
28870 for EXPR that can be used to compute the types of larger
28871 expressions containing EXPR. */
28873 tree
28874 build_non_dependent_expr (tree expr)
28876 tree orig_expr = expr;
28877 tree inner_expr;
28879 /* When checking, try to get a constant value for all non-dependent
28880 expressions in order to expose bugs in *_dependent_expression_p
28881 and constexpr. This can affect code generation, see PR70704, so
28882 only do this for -fchecking=2. */
28883 if (flag_checking > 1
28884 && cxx_dialect >= cxx11
28885 /* Don't do this during nsdmi parsing as it can lead to
28886 unexpected recursive instantiations. */
28887 && !parsing_nsdmi ()
28888 /* Don't do this during concept processing either and for
28889 the same reason. */
28890 && !processing_constraint_expression_p ())
28891 fold_non_dependent_expr (expr, tf_none);
28893 STRIP_ANY_LOCATION_WRAPPER (expr);
28895 /* Preserve OVERLOADs; the functions must be available to resolve
28896 types. */
28897 inner_expr = expr;
28898 if (TREE_CODE (inner_expr) == STMT_EXPR)
28899 inner_expr = stmt_expr_value_expr (inner_expr);
28900 if (TREE_CODE (inner_expr) == ADDR_EXPR)
28901 inner_expr = TREE_OPERAND (inner_expr, 0);
28902 if (TREE_CODE (inner_expr) == COMPONENT_REF)
28903 inner_expr = TREE_OPERAND (inner_expr, 1);
28904 if (is_overloaded_fn (inner_expr)
28905 || TREE_CODE (inner_expr) == OFFSET_REF)
28906 return orig_expr;
28907 /* There is no need to return a proxy for a variable, parameter
28908 or enumerator. */
28909 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
28910 || TREE_CODE (expr) == CONST_DECL)
28911 return orig_expr;
28912 /* Preserve string constants; conversions from string constants to
28913 "char *" are allowed, even though normally a "const char *"
28914 cannot be used to initialize a "char *". */
28915 if (TREE_CODE (expr) == STRING_CST)
28916 return orig_expr;
28917 /* Preserve void and arithmetic constants, as an optimization -- there is no
28918 reason to create a new node. */
28919 if (TREE_CODE (expr) == VOID_CST
28920 || TREE_CODE (expr) == INTEGER_CST
28921 || TREE_CODE (expr) == REAL_CST)
28922 return orig_expr;
28923 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28924 There is at least one place where we want to know that a
28925 particular expression is a throw-expression: when checking a ?:
28926 expression, there are special rules if the second or third
28927 argument is a throw-expression. */
28928 if (TREE_CODE (expr) == THROW_EXPR)
28929 return orig_expr;
28931 /* Don't wrap an initializer list, we need to be able to look inside. */
28932 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28933 return orig_expr;
28935 /* Don't wrap a dummy object, we need to be able to test for it. */
28936 if (is_dummy_object (expr))
28937 return orig_expr;
28939 if (TREE_CODE (expr) == COND_EXPR)
28940 return build3 (COND_EXPR,
28941 TREE_TYPE (expr),
28942 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28943 (TREE_OPERAND (expr, 1)
28944 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28945 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28946 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28947 if (TREE_CODE (expr) == COMPOUND_EXPR)
28948 return build2 (COMPOUND_EXPR,
28949 TREE_TYPE (expr),
28950 TREE_OPERAND (expr, 0),
28951 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28953 /* If the type is unknown, it can't really be non-dependent */
28954 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28956 /* Otherwise, build a NON_DEPENDENT_EXPR. */
28957 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28958 TREE_TYPE (expr), expr);
28961 /* ARGS is a vector of expressions as arguments to a function call.
28962 Replace the arguments with equivalent non-dependent expressions.
28963 This modifies ARGS in place. */
28965 void
28966 make_args_non_dependent (vec<tree, va_gc> *args)
28968 unsigned int ix;
28969 tree arg;
28971 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28973 tree newarg = build_non_dependent_expr (arg);
28974 if (newarg != arg)
28975 (*args)[ix] = newarg;
28979 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
28980 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
28981 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
28983 static tree
28984 make_auto_1 (tree name, bool set_canonical, int level = -1)
28986 if (level == -1)
28987 level = current_template_depth + 1;
28988 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28989 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28990 TYPE_STUB_DECL (au) = TYPE_NAME (au);
28991 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28992 (0, level, level, TYPE_NAME (au), NULL_TREE);
28993 if (set_canonical)
28994 TYPE_CANONICAL (au) = canonical_type_parameter (au);
28995 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28996 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28997 if (name == decltype_auto_identifier)
28998 AUTO_IS_DECLTYPE (au) = true;
29000 return au;
29003 tree
29004 make_decltype_auto (void)
29006 return make_auto_1 (decltype_auto_identifier, true);
29009 tree
29010 make_auto (void)
29012 return make_auto_1 (auto_identifier, true);
29015 /* Return a C++17 deduction placeholder for class template TMPL.
29016 There are represented as an 'auto' with the special level 0 and
29017 CLASS_PLACEHOLDER_TEMPLATE set. */
29019 tree
29020 make_template_placeholder (tree tmpl)
29022 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29023 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29024 /* Our canonical type depends on the placeholder. */
29025 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29026 return t;
29029 /* True iff T is a C++17 class template deduction placeholder. */
29031 bool
29032 template_placeholder_p (tree t)
29034 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29037 /* Make a "constrained auto" type-specifier. This is an auto or
29038 decltype(auto) type with constraints that must be associated after
29039 deduction. The constraint is formed from the given concept CON
29040 and its optional sequence of template arguments ARGS.
29042 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29044 static tree
29045 make_constrained_placeholder_type (tree type, tree con, tree args)
29047 /* Build the constraint. */
29048 tree tmpl = DECL_TI_TEMPLATE (con);
29049 tree expr = tmpl;
29050 if (TREE_CODE (con) == FUNCTION_DECL)
29051 expr = ovl_make (tmpl);
29052 ++processing_template_decl;
29053 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29054 --processing_template_decl;
29056 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29057 = build_tree_list (current_template_parms, expr);
29059 /* Our canonical type depends on the constraint. */
29060 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29062 /* Attach the constraint to the type declaration. */
29063 return TYPE_NAME (type);
29066 /* Make a "constrained auto" type-specifier. */
29068 tree
29069 make_constrained_auto (tree con, tree args)
29071 tree type = make_auto_1 (auto_identifier, false);
29072 return make_constrained_placeholder_type (type, con, args);
29075 /* Make a "constrained decltype(auto)" type-specifier. */
29077 tree
29078 make_constrained_decltype_auto (tree con, tree args)
29080 tree type = make_auto_1 (decltype_auto_identifier, false);
29081 return make_constrained_placeholder_type (type, con, args);
29084 /* Returns true if the placeholder type constraint T has any dependent
29085 (explicit) template arguments. */
29087 static bool
29088 placeholder_type_constraint_dependent_p (tree t)
29090 tree id = unpack_concept_check (t);
29091 tree args = TREE_OPERAND (id, 1);
29092 tree first = TREE_VEC_ELT (args, 0);
29093 if (ARGUMENT_PACK_P (first))
29095 args = expand_template_argument_pack (args);
29096 first = TREE_VEC_ELT (args, 0);
29098 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29099 || is_auto (first));
29100 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29101 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29102 return true;
29103 return false;
29106 /* Build and return a concept definition. Like other templates, the
29107 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29108 the TEMPLATE_DECL. */
29110 tree
29111 finish_concept_definition (cp_expr id, tree init)
29113 gcc_assert (identifier_p (id));
29114 gcc_assert (processing_template_decl);
29116 location_t loc = id.get_location();
29118 /* A concept-definition shall not have associated constraints. */
29119 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29121 error_at (loc, "a concept cannot be constrained");
29122 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29125 /* A concept-definition shall appear in namespace scope. Templates
29126 aren't allowed in block scope, so we only need to check for class
29127 scope. */
29128 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29130 error_at (loc, "concept %qE not in namespace scope", *id);
29131 return error_mark_node;
29134 if (current_template_depth > 1)
29136 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29137 return error_mark_node;
29140 /* Initially build the concept declaration; its type is bool. */
29141 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29142 DECL_CONTEXT (decl) = current_scope ();
29143 DECL_INITIAL (decl) = init;
29145 set_originating_module (decl, false);
29147 /* Push the enclosing template. */
29148 return push_template_decl (decl);
29151 /* Given type ARG, return std::initializer_list<ARG>. */
29153 static tree
29154 listify (tree arg)
29156 tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
29158 if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
29160 gcc_rich_location richloc (input_location);
29161 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29162 error_at (&richloc,
29163 "deducing from brace-enclosed initializer list"
29164 " requires %<#include <initializer_list>%>");
29166 return error_mark_node;
29168 tree argvec = make_tree_vec (1);
29169 TREE_VEC_ELT (argvec, 0) = arg;
29171 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29172 NULL_TREE, 0, tf_warning_or_error);
29175 /* Replace auto in TYPE with std::initializer_list<auto>. */
29177 static tree
29178 listify_autos (tree type, tree auto_node)
29180 tree init_auto = listify (strip_top_quals (auto_node));
29181 tree argvec = make_tree_vec (1);
29182 TREE_VEC_ELT (argvec, 0) = init_auto;
29183 if (processing_template_decl)
29184 argvec = add_to_template_args (current_template_args (), argvec);
29185 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29188 /* Hash traits for hashing possibly constrained 'auto'
29189 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29191 struct auto_hash : default_hash_traits<tree>
29193 static inline hashval_t hash (tree);
29194 static inline bool equal (tree, tree);
29197 /* Hash the 'auto' T. */
29199 inline hashval_t
29200 auto_hash::hash (tree t)
29202 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29203 /* Matching constrained-type-specifiers denote the same template
29204 parameter, so hash the constraint. */
29205 return hash_placeholder_constraint (c);
29206 else
29207 /* But unconstrained autos are all separate, so just hash the pointer. */
29208 return iterative_hash_object (t, 0);
29211 /* Compare two 'auto's. */
29213 inline bool
29214 auto_hash::equal (tree t1, tree t2)
29216 if (t1 == t2)
29217 return true;
29219 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29220 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29222 /* Two unconstrained autos are distinct. */
29223 if (!c1 || !c2)
29224 return false;
29226 return equivalent_placeholder_constraints (c1, c2);
29229 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29230 constrained) auto, add it to the vector. */
29232 static int
29233 extract_autos_r (tree t, void *data)
29235 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29236 if (is_auto (t) && !template_placeholder_p (t))
29238 /* All the autos were built with index 0; fix that up now. */
29239 tree *p = hash.find_slot (t, INSERT);
29240 unsigned idx;
29241 if (*p)
29242 /* If this is a repeated constrained-type-specifier, use the index we
29243 chose before. */
29244 idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
29245 else
29247 /* Otherwise this is new, so use the current count. */
29248 *p = t;
29249 idx = hash.elements () - 1;
29251 TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
29254 /* Always keep walking. */
29255 return 0;
29258 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29259 says they can appear anywhere in the type. */
29261 static tree
29262 extract_autos (tree type)
29264 hash_set<tree> visited;
29265 hash_table<auto_hash> hash (2);
29267 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29269 tree tree_vec = make_tree_vec (hash.elements());
29270 for (tree elt : hash)
29272 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29273 TREE_VEC_ELT (tree_vec, i)
29274 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29277 return tree_vec;
29280 /* The stem for deduction guide names. */
29281 const char *const dguide_base = "__dguide_";
29283 /* Return the name for a deduction guide for class template TMPL. */
29285 tree
29286 dguide_name (tree tmpl)
29288 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29289 tree tname = TYPE_IDENTIFIER (type);
29290 char *buf = (char *) alloca (1 + strlen (dguide_base)
29291 + IDENTIFIER_LENGTH (tname));
29292 memcpy (buf, dguide_base, strlen (dguide_base));
29293 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29294 IDENTIFIER_LENGTH (tname) + 1);
29295 tree dname = get_identifier (buf);
29296 TREE_TYPE (dname) = type;
29297 return dname;
29300 /* True if NAME is the name of a deduction guide. */
29302 bool
29303 dguide_name_p (tree name)
29305 return (TREE_CODE (name) == IDENTIFIER_NODE
29306 && TREE_TYPE (name)
29307 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29310 /* True if FN is a deduction guide. */
29312 bool
29313 deduction_guide_p (const_tree fn)
29315 if (DECL_P (fn))
29316 if (tree name = DECL_NAME (fn))
29317 return dguide_name_p (name);
29318 return false;
29321 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29323 bool
29324 copy_guide_p (const_tree fn)
29326 gcc_assert (deduction_guide_p (fn));
29327 if (!DECL_ARTIFICIAL (fn))
29328 return false;
29329 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29330 return (TREE_CHAIN (parms) == void_list_node
29331 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29334 /* True if FN is a guide generated from a constructor template. */
29336 bool
29337 template_guide_p (const_tree fn)
29339 gcc_assert (deduction_guide_p (fn));
29340 if (!DECL_ARTIFICIAL (fn))
29341 return false;
29342 tree tmpl = DECL_TI_TEMPLATE (fn);
29343 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29344 return PRIMARY_TEMPLATE_P (org);
29345 return false;
29348 /* True if FN is an aggregate initialization guide or the copy deduction
29349 guide. */
29351 bool
29352 builtin_guide_p (const_tree fn)
29354 if (!deduction_guide_p (fn))
29355 return false;
29356 if (!DECL_ARTIFICIAL (fn))
29357 /* Explicitly declared. */
29358 return false;
29359 if (DECL_ABSTRACT_ORIGIN (fn))
29360 /* Derived from a constructor. */
29361 return false;
29362 return true;
29365 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29366 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29367 template parameter types. Note that the handling of template template
29368 parameters relies on current_template_parms being set appropriately for the
29369 new template. */
29371 static tree
29372 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29373 tree tsubst_args, tsubst_flags_t complain)
29375 if (olddecl == error_mark_node)
29376 return error_mark_node;
29378 tree oldidx = get_template_parm_index (olddecl);
29380 tree newtype;
29381 if (TREE_CODE (olddecl) == TYPE_DECL
29382 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29384 tree oldtype = TREE_TYPE (olddecl);
29385 newtype = cxx_make_type (TREE_CODE (oldtype));
29386 TYPE_MAIN_VARIANT (newtype) = newtype;
29388 else
29390 newtype = TREE_TYPE (olddecl);
29391 if (type_uses_auto (newtype))
29393 // Substitute once to fix references to other template parameters.
29394 newtype = tsubst (newtype, tsubst_args,
29395 complain|tf_partial, NULL_TREE);
29396 // Now substitute again to reduce the level of the auto.
29397 newtype = tsubst (newtype, current_template_args (),
29398 complain, NULL_TREE);
29400 else
29401 newtype = tsubst (newtype, tsubst_args,
29402 complain, NULL_TREE);
29405 tree newdecl
29406 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29407 DECL_NAME (olddecl), newtype);
29408 SET_DECL_TEMPLATE_PARM_P (newdecl);
29410 tree newidx;
29411 if (TREE_CODE (olddecl) == TYPE_DECL
29412 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29414 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29415 = build_template_parm_index (index, level, level,
29416 newdecl, newtype);
29417 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29418 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29419 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29421 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29423 DECL_TEMPLATE_RESULT (newdecl)
29424 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29425 DECL_NAME (olddecl), newtype);
29426 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29427 // First create a copy (ttargs) of tsubst_args with an
29428 // additional level for the template template parameter's own
29429 // template parameters (ttparms).
29430 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29431 (DECL_TEMPLATE_PARMS (olddecl)));
29432 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29433 tree ttargs = make_tree_vec (depth + 1);
29434 for (int i = 0; i < depth; ++i)
29435 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29436 TREE_VEC_ELT (ttargs, depth)
29437 = template_parms_level_to_args (ttparms);
29438 // Substitute ttargs into ttparms to fix references to
29439 // other template parameters.
29440 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29441 complain|tf_partial);
29442 // Now substitute again with args based on tparms, to reduce
29443 // the level of the ttparms.
29444 ttargs = current_template_args ();
29445 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29446 complain);
29447 // Finally, tack the adjusted parms onto tparms.
29448 ttparms = tree_cons (size_int (level + 1), ttparms,
29449 copy_node (current_template_parms));
29450 // As with all template template parms, the parameter list captured
29451 // by this template template parm that corresponds to its own level
29452 // should be empty. This avoids infinite recursion when structurally
29453 // comparing two such rewritten template template parms (PR102479).
29454 gcc_assert (!TREE_VEC_LENGTH
29455 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29456 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29457 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29458 // All done.
29459 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29462 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29463 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29464 else
29465 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29467 else
29469 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29470 tree newconst
29471 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29472 TREE_CODE (oldconst),
29473 DECL_NAME (oldconst), newtype);
29474 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29475 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29476 SET_DECL_TEMPLATE_PARM_P (newconst);
29477 newidx = build_template_parm_index (index, level, level,
29478 newconst, newtype);
29479 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29480 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29481 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29484 return newdecl;
29487 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29488 template parameter. */
29490 static tree
29491 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29492 tree targs, unsigned targs_index, tsubst_flags_t complain)
29494 tree olddecl = TREE_VALUE (oldelt);
29495 tree newdecl = rewrite_template_parm (olddecl, index, level,
29496 targs, complain);
29497 if (newdecl == error_mark_node)
29498 return error_mark_node;
29499 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29500 targs, complain, NULL_TREE);
29501 tree list = build_tree_list (newdef, newdecl);
29502 TEMPLATE_PARM_CONSTRAINTS (list)
29503 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29504 targs, complain, NULL_TREE);
29505 int depth = TMPL_ARGS_DEPTH (targs);
29506 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29507 return list;
29510 /* Returns a C++17 class deduction guide template based on the constructor
29511 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29512 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29513 aggregate initialization guide. OUTER_ARGS are the template arguments
29514 for the enclosing scope of the class. */
29516 static tree
29517 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29519 tree tparms, targs, fparms, fargs, ci;
29520 bool memtmpl = false;
29521 bool explicit_p;
29522 location_t loc;
29523 tree fn_tmpl = NULL_TREE;
29525 if (outer_args)
29527 ++processing_template_decl;
29528 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29529 --processing_template_decl;
29532 if (!DECL_DECLARES_FUNCTION_P (ctor))
29534 if (TYPE_P (ctor))
29536 bool copy_p = TYPE_REF_P (ctor);
29537 if (copy_p)
29538 fparms = tree_cons (NULL_TREE, type, void_list_node);
29539 else
29540 fparms = void_list_node;
29542 else if (TREE_CODE (ctor) == TREE_LIST)
29543 fparms = ctor;
29544 else
29545 gcc_unreachable ();
29547 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29548 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29549 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29550 ci = NULL_TREE;
29551 fargs = NULL_TREE;
29552 loc = DECL_SOURCE_LOCATION (ctmpl);
29553 explicit_p = false;
29555 else
29557 ++processing_template_decl;
29558 bool ok = true;
29560 complain |= tf_dguide;
29562 fn_tmpl
29563 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29564 : DECL_TI_TEMPLATE (ctor));
29565 if (outer_args)
29566 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29567 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29569 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29570 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29571 fully specialized args for the enclosing class. Strip those off, as
29572 the deduction guide won't have those template parameters. */
29573 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29574 TMPL_PARMS_DEPTH (tparms));
29575 /* Discard the 'this' parameter. */
29576 fparms = FUNCTION_ARG_CHAIN (ctor);
29577 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29578 ci = get_constraints (ctor);
29579 loc = DECL_SOURCE_LOCATION (ctor);
29580 explicit_p = DECL_NONCONVERTING_P (ctor);
29582 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29584 memtmpl = true;
29586 /* For a member template constructor, we need to flatten the two
29587 template parameter lists into one, and then adjust the function
29588 signature accordingly. This gets...complicated. */
29589 tree save_parms = current_template_parms;
29591 /* For a member template we should have two levels of parms/args, one
29592 for the class and one for the constructor. We stripped
29593 specialized args for further enclosing classes above. */
29594 const int depth = 2;
29595 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29597 /* Template args for translating references to the two-level template
29598 parameters into references to the one-level template parameters we
29599 are creating. */
29600 tree tsubst_args = copy_node (targs);
29601 TMPL_ARGS_LEVEL (tsubst_args, depth)
29602 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29604 /* Template parms for the constructor template. */
29605 tree ftparms = TREE_VALUE (tparms);
29606 unsigned flen = TREE_VEC_LENGTH (ftparms);
29607 /* Template parms for the class template. */
29608 tparms = TREE_CHAIN (tparms);
29609 tree ctparms = TREE_VALUE (tparms);
29610 unsigned clen = TREE_VEC_LENGTH (ctparms);
29611 /* Template parms for the deduction guide start as a copy of the
29612 template parms for the class. We set current_template_parms for
29613 lookup_template_class_1. */
29614 current_template_parms = tparms = copy_node (tparms);
29615 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29616 for (unsigned i = 0; i < clen; ++i)
29617 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29619 /* Now we need to rewrite the constructor parms to append them to the
29620 class parms. */
29621 for (unsigned i = 0; i < flen; ++i)
29623 unsigned index = i + clen;
29624 unsigned level = 1;
29625 tree oldelt = TREE_VEC_ELT (ftparms, i);
29626 tree newelt
29627 = rewrite_tparm_list (oldelt, index, level,
29628 tsubst_args, i, complain);
29629 if (newelt == error_mark_node)
29630 ok = false;
29631 TREE_VEC_ELT (new_vec, index) = newelt;
29634 /* Now we have a final set of template parms to substitute into the
29635 function signature. */
29636 targs = template_parms_to_args (tparms);
29637 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29638 complain, ctor);
29639 if (fparms == error_mark_node)
29640 ok = false;
29641 if (ci)
29643 if (outer_args)
29644 /* FIXME: We'd like to avoid substituting outer template
29645 arguments into the constraint ahead of time, but the
29646 construction of tsubst_args assumes that outer arguments
29647 are already substituted in. */
29648 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29649 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29652 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29653 cp_unevaluated_operand. */
29654 cp_evaluated ev;
29655 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29656 current_template_parms = save_parms;
29658 else
29660 /* Substitute in the same arguments to rewrite class members into
29661 references to members of an unknown specialization. */
29662 cp_evaluated ev;
29663 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29664 fargs = tsubst (fargs, targs, complain, ctor);
29665 if (ci)
29667 if (outer_args)
29668 /* FIXME: As above. */
29669 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29670 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29674 --processing_template_decl;
29675 if (!ok)
29676 return error_mark_node;
29679 if (!memtmpl)
29681 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29682 tparms = copy_node (tparms);
29683 INNERMOST_TEMPLATE_PARMS (tparms)
29684 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29687 tree fntype = build_function_type (type, fparms);
29688 tree ded_fn = build_lang_decl_loc (loc,
29689 FUNCTION_DECL,
29690 dguide_name (type), fntype);
29691 DECL_ARGUMENTS (ded_fn) = fargs;
29692 DECL_ARTIFICIAL (ded_fn) = true;
29693 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29694 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29695 DECL_ARTIFICIAL (ded_tmpl) = true;
29696 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29697 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29698 if (DECL_P (ctor))
29699 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29700 if (ci)
29701 set_constraints (ded_tmpl, ci);
29703 return ded_tmpl;
29706 /* Add to LIST the member types for the reshaped initializer CTOR. */
29708 static tree
29709 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29711 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29712 tree idx, val; unsigned i;
29713 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29715 tree ftype = elt ? elt : TREE_TYPE (idx);
29716 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29717 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29719 tree subelt = NULL_TREE;
29720 if (TREE_CODE (ftype) == ARRAY_TYPE)
29721 subelt = TREE_TYPE (ftype);
29722 list = collect_ctor_idx_types (val, list, subelt);
29723 continue;
29725 tree arg = NULL_TREE;
29726 if (i == v->length() - 1
29727 && PACK_EXPANSION_P (ftype))
29728 /* Give the trailing pack expansion parameter a default argument to
29729 match aggregate initialization behavior, even if we deduce the
29730 length of the pack separately to more than we have initializers. */
29731 arg = build_constructor (init_list_type_node, NULL);
29732 /* if ei is of array type and xi is a braced-init-list or string literal,
29733 Ti is an rvalue reference to the declared type of ei */
29734 STRIP_ANY_LOCATION_WRAPPER (val);
29735 if (TREE_CODE (ftype) == ARRAY_TYPE
29736 && (BRACE_ENCLOSED_INITIALIZER_P (val)
29737 || TREE_CODE (val) == STRING_CST))
29739 if (TREE_CODE (val) == STRING_CST)
29740 ftype = cp_build_qualified_type
29741 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29742 ftype = (cp_build_reference_type
29743 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29745 list = tree_cons (arg, ftype, list);
29748 return list;
29751 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
29753 static bool
29754 is_spec_or_derived (tree etype, tree tmpl)
29756 if (!etype || !CLASS_TYPE_P (etype))
29757 return false;
29759 etype = cv_unqualified (etype);
29760 tree type = TREE_TYPE (tmpl);
29761 tree tparms = (INNERMOST_TEMPLATE_PARMS
29762 (DECL_TEMPLATE_PARMS (tmpl)));
29763 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29764 int err = unify (tparms, targs, type, etype,
29765 UNIFY_ALLOW_DERIVED, /*explain*/false);
29766 ggc_free (targs);
29767 return !err;
29770 static tree alias_ctad_tweaks (tree, tree);
29772 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
29773 INIT. */
29775 static tree
29776 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
29778 if (cxx_dialect < cxx20)
29779 return NULL_TREE;
29781 if (init == NULL_TREE)
29782 return NULL_TREE;
29784 if (DECL_ALIAS_TEMPLATE_P (tmpl))
29786 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29787 tree tinfo = get_template_info (under);
29788 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
29789 return alias_ctad_tweaks (tmpl, guide);
29790 return NULL_TREE;
29793 /* We might be creating a guide for a class member template, e.g.,
29795 template<typename U> struct A {
29796 template<typename T> struct B { T t; };
29799 At this point, A will have been instantiated. Below, we need to
29800 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
29801 const bool member_template_p
29802 = (DECL_TEMPLATE_INFO (tmpl)
29803 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
29804 tree type = TREE_TYPE (tmpl);
29805 tree template_type = (member_template_p
29806 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
29807 : type);
29808 if (!CP_AGGREGATE_TYPE_P (template_type))
29809 return NULL_TREE;
29811 /* No aggregate candidate for copy-initialization. */
29812 if (args->length() == 1)
29814 tree val = (*args)[0];
29815 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
29816 return NULL_TREE;
29819 /* If we encounter a problem, we just won't add the candidate. */
29820 tsubst_flags_t complain = tf_none;
29822 tree parms = NULL_TREE;
29823 if (BRACE_ENCLOSED_INITIALIZER_P (init))
29825 init = reshape_init (template_type, init, complain);
29826 if (init == error_mark_node)
29827 return NULL_TREE;
29828 parms = collect_ctor_idx_types (init, parms);
29829 /* If we're creating a deduction guide for a member class template,
29830 we've used the original template pattern type for the reshape_init
29831 above; this is done because we want PARMS to be a template parameter
29832 type, something that can be deduced when used as a function template
29833 parameter. At this point the outer class template has already been
29834 partially instantiated (we deferred the deduction until the enclosing
29835 scope is non-dependent). Therefore we have to partially instantiate
29836 PARMS, so that its template level is properly reduced and we don't get
29837 mismatches when deducing types using the guide with PARMS. */
29838 if (member_template_p)
29840 ++processing_template_decl;
29841 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
29842 --processing_template_decl;
29845 else if (TREE_CODE (init) == TREE_LIST)
29847 int len = list_length (init);
29848 for (tree field = TYPE_FIELDS (type);
29849 len;
29850 --len, field = DECL_CHAIN (field))
29852 field = next_aggregate_field (field);
29853 if (!field)
29854 return NULL_TREE;
29855 tree ftype = finish_decltype_type (field, true, complain);
29856 parms = tree_cons (NULL_TREE, ftype, parms);
29859 else
29860 /* Aggregate initialization doesn't apply to an initializer expression. */
29861 return NULL_TREE;
29863 if (parms)
29865 tree last = parms;
29866 parms = nreverse (parms);
29867 TREE_CHAIN (last) = void_list_node;
29868 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
29869 return guide;
29872 return NULL_TREE;
29875 /* UGUIDES are the deduction guides for the underlying template of alias
29876 template TMPL; adjust them to be deduction guides for TMPL. */
29878 static tree
29879 alias_ctad_tweaks (tree tmpl, tree uguides)
29881 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
29882 class type (9.2.8.2) where the template-name names an alias template A,
29883 the defining-type-id of A must be of the form
29885 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29887 as specified in 9.2.8.2. The guides of A are the set of functions or
29888 function templates formed as follows. For each function or function
29889 template f in the guides of the template named by the simple-template-id
29890 of the defining-type-id, the template arguments of the return type of f
29891 are deduced from the defining-type-id of A according to the process in
29892 13.10.2.5 with the exception that deduction does not fail if not all
29893 template arguments are deduced. Let g denote the result of substituting
29894 these deductions into f. If substitution succeeds, form a function or
29895 function template f' with the following properties and add it to the set
29896 of guides of A:
29898 * The function type of f' is the function type of g.
29900 * If f is a function template, f' is a function template whose template
29901 parameter list consists of all the template parameters of A (including
29902 their default template arguments) that appear in the above deductions or
29903 (recursively) in their default template arguments, followed by the
29904 template parameters of f that were not deduced (including their default
29905 template arguments), otherwise f' is not a function template.
29907 * The associated constraints (13.5.2) are the conjunction of the
29908 associated constraints of g and a constraint that is satisfied if and only
29909 if the arguments of A are deducible (see below) from the return type.
29911 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29912 be so as well.
29914 * If f was generated from a deduction-guide (12.4.1.8), then f' is
29915 considered to be so as well.
29917 * The explicit-specifier of f' is the explicit-specifier of g (if
29918 any). */
29920 /* This implementation differs from the above in two significant ways:
29922 1) We include all template parameters of A, not just some.
29923 2) The added constraint is same_type instead of deducible.
29925 I believe that while it's probably possible to construct a testcase that
29926 behaves differently with this simplification, it should have the same
29927 effect for real uses. Including all template parameters means that we
29928 deduce all parameters of A when resolving the call, so when we're in the
29929 constraint we don't need to deduce them again, we can just check whether
29930 the deduction produced the desired result. */
29932 tsubst_flags_t complain = tf_warning_or_error;
29933 tree atype = TREE_TYPE (tmpl);
29934 tree aguides = NULL_TREE;
29935 tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29936 unsigned natparms = TREE_VEC_LENGTH (atparms);
29937 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29938 for (ovl_iterator iter (uguides); iter; ++iter)
29940 tree f = *iter;
29941 tree in_decl = f;
29942 location_t loc = DECL_SOURCE_LOCATION (f);
29943 tree ret = TREE_TYPE (TREE_TYPE (f));
29944 tree fprime = f;
29945 if (TREE_CODE (f) == TEMPLATE_DECL)
29947 processing_template_decl_sentinel ptds (/*reset*/false);
29948 ++processing_template_decl;
29950 /* Deduce template arguments for f from the type-id of A. */
29951 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29952 unsigned len = TREE_VEC_LENGTH (ftparms);
29953 tree targs = make_tree_vec (len);
29954 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29955 if (err)
29956 continue;
29958 /* The number of parms for f' is the number of parms for A plus
29959 non-deduced parms of f. */
29960 unsigned ndlen = 0;
29961 unsigned j;
29962 for (unsigned i = 0; i < len; ++i)
29963 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29964 ++ndlen;
29965 tree gtparms = make_tree_vec (natparms + ndlen);
29967 /* Set current_template_parms as in build_deduction_guide. */
29968 auto ctp = make_temp_override (current_template_parms);
29969 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
29970 TREE_VALUE (current_template_parms) = gtparms;
29972 /* First copy over the parms of A. */
29973 for (j = 0; j < natparms; ++j)
29974 TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29975 /* Now rewrite the non-deduced parms of f. */
29976 for (unsigned i = 0; ndlen && i < len; ++i)
29977 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29979 --ndlen;
29980 unsigned index = j++;
29981 unsigned level = 1;
29982 tree oldlist = TREE_VEC_ELT (ftparms, i);
29983 tree list = rewrite_tparm_list (oldlist, index, level,
29984 targs, i, complain);
29985 TREE_VEC_ELT (gtparms, index) = list;
29987 gtparms = build_tree_list (size_one_node, gtparms);
29989 /* Substitute the deduced arguments plus the rewritten template
29990 parameters into f to get g. This covers the type, copyness,
29991 guideness, and explicit-specifier. */
29992 tree g;
29994 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29995 if cp_unevaluated_operand. */
29996 cp_evaluated ev;
29997 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29999 if (g == error_mark_node)
30000 continue;
30001 DECL_USE_TEMPLATE (g) = 0;
30002 fprime = build_template_decl (g, gtparms, false);
30003 DECL_TEMPLATE_RESULT (fprime) = g;
30004 TREE_TYPE (fprime) = TREE_TYPE (g);
30005 tree gtargs = template_parms_to_args (gtparms);
30006 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30007 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30009 /* Substitute the associated constraints. */
30010 tree ci = get_constraints (f);
30011 if (ci)
30012 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30013 if (ci == error_mark_node)
30014 continue;
30016 /* Add a constraint that the return type matches the instantiation of
30017 A with the same template arguments. */
30018 ret = TREE_TYPE (TREE_TYPE (fprime));
30019 if (!same_type_p (atype, ret)
30020 /* FIXME this should mean they don't compare as equivalent. */
30021 || dependent_alias_template_spec_p (atype, nt_opaque))
30023 tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
30024 ci = append_constraint (ci, same);
30027 if (ci)
30029 remove_constraints (fprime);
30030 set_constraints (fprime, ci);
30033 else
30035 /* For a non-template deduction guide, if the arguments of A aren't
30036 deducible from the return type, don't add the candidate. */
30037 tree targs = make_tree_vec (natparms);
30038 int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
30039 for (unsigned i = 0; !err && i < natparms; ++i)
30040 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30041 err = true;
30042 if (err)
30043 continue;
30046 aguides = lookup_add (fprime, aguides);
30049 return aguides;
30052 /* Return artificial deduction guides built from the constructors of class
30053 template TMPL. */
30055 static tree
30056 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30058 tree type = TREE_TYPE (tmpl);
30059 tree outer_args = NULL_TREE;
30060 if (DECL_CLASS_SCOPE_P (tmpl)
30061 && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
30063 outer_args = copy_node (CLASSTYPE_TI_ARGS (type));
30064 gcc_assert (TMPL_ARGS_DEPTH (outer_args) > 1);
30065 --TREE_VEC_LENGTH (outer_args);
30066 type = TREE_TYPE (most_general_template (tmpl));
30069 tree cands = NULL_TREE;
30071 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30073 /* Skip inherited constructors. */
30074 if (iter.using_p ())
30075 continue;
30077 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30078 cands = lookup_add (guide, cands);
30081 /* Add implicit default constructor deduction guide. */
30082 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30084 tree guide = build_deduction_guide (type, type, outer_args,
30085 complain);
30086 cands = lookup_add (guide, cands);
30089 /* Add copy guide. */
30091 tree gtype = build_reference_type (type);
30092 tree guide = build_deduction_guide (type, gtype, outer_args,
30093 complain);
30094 cands = lookup_add (guide, cands);
30097 return cands;
30100 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30102 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30103 aggregate candidate is added separately because it depends on the
30104 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30105 guide. */
30107 static tree
30108 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30110 tree guides = NULL_TREE;
30111 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30113 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30114 tree tinfo = get_template_info (under);
30115 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30116 complain);
30118 else
30120 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30121 dguide_name (tmpl),
30122 LOOK_want::NORMAL, /*complain*/false);
30123 if (guides == error_mark_node)
30124 guides = NULL_TREE;
30125 else
30126 any_dguides_p = true;
30129 /* Cache the deduction guides for a template. We also remember the result of
30130 lookup, and rebuild everything if it changes; should be very rare. */
30131 tree_pair_p cache = NULL;
30132 if (tree_pair_p &r
30133 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30135 cache = r;
30136 if (cache->purpose == guides)
30137 return cache->value;
30139 else
30141 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30142 cache->purpose = guides;
30145 tree cands = NULL_TREE;
30146 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30147 cands = alias_ctad_tweaks (tmpl, guides);
30148 else
30150 cands = ctor_deduction_guides_for (tmpl, complain);
30151 for (ovl_iterator it (guides); it; ++it)
30152 cands = lookup_add (*it, cands);
30155 cache->value = cands;
30156 return cands;
30159 /* Return whether TMPL is a (class template argument-) deducible template. */
30161 bool
30162 ctad_template_p (tree tmpl)
30164 /* A deducible template is either a class template or is an alias template
30165 whose defining-type-id is of the form
30167 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30169 where the nested-name-specifier (if any) is non-dependent and the
30170 template-name of the simple-template-id names a deducible template. */
30172 if (DECL_CLASS_TEMPLATE_P (tmpl)
30173 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30174 return true;
30175 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30176 return false;
30177 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30178 if (tree tinfo = get_template_info (orig))
30179 return ctad_template_p (TI_TEMPLATE (tinfo));
30180 return false;
30183 /* Deduce template arguments for the class template placeholder PTYPE for
30184 template TMPL based on the initializer INIT, and return the resulting
30185 type. */
30187 static tree
30188 do_class_deduction (tree ptype, tree tmpl, tree init,
30189 int flags, tsubst_flags_t complain)
30191 /* We should have handled this in the caller. */
30192 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30193 return ptype;
30195 /* If the class was erroneous, don't try to deduce, because that
30196 can generate a lot of diagnostic. */
30197 if (TREE_TYPE (tmpl)
30198 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30199 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30200 return ptype;
30202 /* Wait until the enclosing scope is non-dependent. */
30203 if (DECL_CLASS_SCOPE_P (tmpl)
30204 && dependent_type_p (DECL_CONTEXT (tmpl)))
30205 return ptype;
30207 /* Initializing one placeholder from another. */
30208 if (init
30209 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30210 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30211 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30212 == TEMPLATE_PARM_INDEX)))
30213 && is_auto (TREE_TYPE (init))
30214 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30215 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30217 if (!ctad_template_p (tmpl))
30219 if (complain & tf_error)
30220 error ("non-deducible template %qT used without template arguments", tmpl);
30221 return error_mark_node;
30223 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30225 if (complain & tf_error)
30227 /* Be permissive with equivalent alias templates. */
30228 tree u = get_underlying_template (tmpl);
30229 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30230 bool complained
30231 = emit_diagnostic (dk, input_location, 0,
30232 "alias template deduction only available "
30233 "with %<-std=c++20%> or %<-std=gnu++20%>");
30234 if (u == tmpl)
30235 return error_mark_node;
30236 else if (complained)
30238 inform (input_location, "use %qD directly instead", u);
30239 tmpl = u;
30242 else
30243 return error_mark_node;
30246 /* Wait until the initializer is non-dependent. */
30247 if (type_dependent_expression_p (init))
30248 return ptype;
30250 /* Don't bother with the alias rules for an equivalent template. */
30251 tmpl = get_underlying_template (tmpl);
30253 tree type = TREE_TYPE (tmpl);
30255 bool try_list_cand = false;
30256 bool list_init_p = false;
30258 releasing_vec rv_args = NULL;
30259 vec<tree,va_gc> *&args = *&rv_args;
30260 if (init == NULL_TREE)
30261 args = make_tree_vector ();
30262 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30264 list_init_p = true;
30265 try_list_cand = true;
30266 if (CONSTRUCTOR_NELTS (init) == 1
30267 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30269 /* As an exception, the first phase in 16.3.1.7 (considering the
30270 initializer list as a single argument) is omitted if the
30271 initializer list consists of a single expression of type cv U,
30272 where U is a specialization of C or a class derived from a
30273 specialization of C. */
30274 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30275 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30276 try_list_cand = false;
30278 if (try_list_cand || is_std_init_list (type))
30279 args = make_tree_vector_single (init);
30280 else
30281 args = make_tree_vector_from_ctor (init);
30283 else if (TREE_CODE (init) == TREE_LIST)
30284 args = make_tree_vector_from_list (init);
30285 else
30286 args = make_tree_vector_single (init);
30288 /* Do this now to avoid problems with erroneous args later on. */
30289 args = resolve_args (args, complain);
30290 if (args == NULL)
30291 return error_mark_node;
30293 bool any_dguides_p = false;
30294 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30295 if (cands == error_mark_node)
30296 return error_mark_node;
30298 /* Prune explicit deduction guides in copy-initialization context (but
30299 not copy-list-initialization). */
30300 bool elided = false;
30301 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30303 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30304 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30305 elided = true;
30307 if (elided)
30309 /* Found a nonconverting guide, prune the candidates. */
30310 tree pruned = NULL_TREE;
30311 for (lkp_iterator iter (cands); iter; ++iter)
30312 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30313 pruned = lookup_add (*iter, pruned);
30315 cands = pruned;
30319 if (!any_dguides_p)
30320 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30321 cands = lookup_add (guide, cands);
30323 tree fndecl = error_mark_node;
30325 /* If this is list-initialization and the class has a list guide, first
30326 try deducing from the list as a single argument, as [over.match.list]. */
30327 if (try_list_cand)
30329 tree list_cands = NULL_TREE;
30330 for (tree dg : lkp_range (cands))
30331 if (is_list_ctor (dg))
30332 list_cands = lookup_add (dg, list_cands);
30333 if (list_cands)
30334 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30335 if (fndecl == error_mark_node)
30337 /* That didn't work, now try treating the list as a sequence of
30338 arguments. */
30339 release_tree_vector (args);
30340 args = make_tree_vector_from_ctor (init);
30341 args = resolve_args (args, complain);
30342 if (args == NULL)
30343 return error_mark_node;
30347 if (elided && !cands)
30349 error ("cannot deduce template arguments for copy-initialization"
30350 " of %qT, as it has no non-explicit deduction guides or "
30351 "user-declared constructors", type);
30352 return error_mark_node;
30354 else if (!cands && fndecl == error_mark_node)
30356 error ("cannot deduce template arguments of %qT, as it has no viable "
30357 "deduction guides", type);
30358 return error_mark_node;
30361 if (fndecl == error_mark_node)
30362 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30364 if (fndecl == error_mark_node)
30366 if (complain & tf_warning_or_error)
30368 error ("class template argument deduction failed:");
30369 perform_dguide_overload_resolution (cands, args, complain);
30370 if (elided)
30371 inform (input_location, "explicit deduction guides not considered "
30372 "for copy-initialization");
30374 return error_mark_node;
30376 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30377 constructor is chosen, the initialization is ill-formed. */
30378 else if (flags & LOOKUP_ONLYCONVERTING)
30380 if (DECL_NONCONVERTING_P (fndecl))
30382 if (complain & tf_warning_or_error)
30384 // TODO: Pass down location from cp_finish_decl.
30385 error ("class template argument deduction for %qT failed: "
30386 "explicit deduction guide selected in "
30387 "copy-list-initialization", type);
30388 inform (DECL_SOURCE_LOCATION (fndecl),
30389 "explicit deduction guide declared here");
30392 return error_mark_node;
30396 /* If CTAD succeeded but the type doesn't have any explicit deduction
30397 guides, this deduction might not be what the user intended. */
30398 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30400 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30401 || global_dc->dc_warn_system_headers)
30402 && warning (OPT_Wctad_maybe_unsupported,
30403 "%qT may not intend to support class template argument "
30404 "deduction", type))
30405 inform (input_location, "add a deduction guide to suppress this "
30406 "warning");
30409 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30410 cp_type_quals (ptype));
30413 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30414 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30415 The CONTEXT determines the context in which auto deduction is performed
30416 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30418 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30419 to properly substitute the result. It's also used in the adc_unify and
30420 adc_requirement contexts to communicate the necessary template arguments
30421 to satisfaction. OUTER_TARGS is ignored in other contexts.
30423 For partial-concept-ids, extra args may be appended to the list of deduced
30424 template arguments prior to determining constraint satisfaction. */
30426 tree
30427 do_auto_deduction (tree type, tree init, tree auto_node,
30428 tsubst_flags_t complain, auto_deduction_context context,
30429 tree outer_targs, int flags)
30431 if (init == error_mark_node)
30432 return error_mark_node;
30434 if (init && type_dependent_expression_p (init)
30435 && context != adc_unify)
30436 /* Defining a subset of type-dependent expressions that we can deduce
30437 from ahead of time isn't worth the trouble. */
30438 return type;
30440 /* Similarly, we can't deduce from another undeduced decl. */
30441 if (init && undeduced_auto_decl (init))
30442 return type;
30444 /* We may be doing a partial substitution, but we still want to replace
30445 auto_node. */
30446 complain &= ~tf_partial;
30448 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30449 /* C++17 class template argument deduction. */
30450 return do_class_deduction (type, tmpl, init, flags, complain);
30452 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30453 /* Nothing we can do with this, even in deduction context. */
30454 return type;
30456 location_t loc = cp_expr_loc_or_input_loc (init);
30458 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30459 with either a new invented type template parameter U or, if the
30460 initializer is a braced-init-list (8.5.4), with
30461 std::initializer_list<U>. */
30462 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30464 if (!DIRECT_LIST_INIT_P (init))
30465 type = listify_autos (type, auto_node);
30466 else if (CONSTRUCTOR_NELTS (init) == 1)
30467 init = CONSTRUCTOR_ELT (init, 0)->value;
30468 else
30470 if (complain & tf_warning_or_error)
30472 if (permerror (loc, "direct-list-initialization of "
30473 "%<auto%> requires exactly one element"))
30474 inform (loc,
30475 "for deduction to %<std::initializer_list%>, use copy-"
30476 "list-initialization (i.e. add %<=%> before the %<{%>)");
30478 type = listify_autos (type, auto_node);
30482 if (type == error_mark_node)
30483 return error_mark_node;
30485 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30487 /* We don't recurse here because we can't deduce from a nested
30488 initializer_list. */
30489 if (CONSTRUCTOR_ELTS (init))
30490 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30491 elt.value = resolve_nondeduced_context (elt.value, complain);
30493 else
30494 init = resolve_nondeduced_context (init, complain);
30496 tree targs;
30497 if (context == adc_decomp_type
30498 && auto_node == type
30499 && init != error_mark_node
30500 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30502 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30503 and initializer has array type, deduce cv-qualified array type. */
30504 targs = make_tree_vec (1);
30505 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30507 else if (AUTO_IS_DECLTYPE (auto_node))
30509 /* Figure out if INIT is an unparenthesized id-expression or an
30510 unparenthesized class member access. */
30511 tree stripped_init = tree_strip_any_location_wrapper (init);
30512 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30513 reference type). Only the latter is an id-expression. */
30514 if (REFERENCE_REF_P (stripped_init)
30515 && !REF_PARENTHESIZED_P (stripped_init))
30516 stripped_init = TREE_OPERAND (stripped_init, 0);
30517 const bool id = (DECL_P (stripped_init)
30518 || ((TREE_CODE (stripped_init) == COMPONENT_REF
30519 || TREE_CODE (stripped_init) == SCOPE_REF)
30520 && !REF_PARENTHESIZED_P (stripped_init)));
30521 tree deduced = finish_decltype_type (init, id, complain);
30522 deduced = canonicalize_type_argument (deduced, complain);
30523 if (deduced == error_mark_node)
30524 return error_mark_node;
30525 targs = make_tree_vec (1);
30526 TREE_VEC_ELT (targs, 0) = deduced;
30528 else
30530 if (error_operand_p (init))
30531 return error_mark_node;
30533 tree parms = build_tree_list (NULL_TREE, type);
30534 tree tparms;
30536 if (flag_concepts_ts)
30537 tparms = extract_autos (type);
30538 else
30540 tparms = make_tree_vec (1);
30541 TREE_VEC_ELT (tparms, 0)
30542 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30545 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30546 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30547 DEDUCE_CALL,
30548 NULL, /*explain_p=*/false);
30549 if (val > 0)
30551 if (processing_template_decl)
30552 /* Try again at instantiation time. */
30553 return type;
30554 if (type && type != error_mark_node
30555 && (complain & tf_error))
30556 /* If type is error_mark_node a diagnostic must have been
30557 emitted by now. Also, having a mention to '<type error>'
30558 in the diagnostic is not really useful to the user. */
30560 if (cfun
30561 && FNDECL_USED_AUTO (current_function_decl)
30562 && (auto_node
30563 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30564 && LAMBDA_FUNCTION_P (current_function_decl))
30565 error_at (loc, "unable to deduce lambda return type from %qE",
30566 init);
30567 else
30568 error_at (loc, "unable to deduce %qT from %qE", type, init);
30569 type_unification_real (tparms, targs, parms, &init, 1, 0,
30570 DEDUCE_CALL,
30571 NULL, /*explain_p=*/true);
30573 return error_mark_node;
30577 /* Check any placeholder constraints against the deduced type. */
30578 if (processing_template_decl && context == adc_unify)
30579 /* Constraints will be checked after deduction. */;
30580 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30582 if (processing_template_decl)
30584 gcc_checking_assert (context == adc_variable_type
30585 || context == adc_return_type
30586 || context == adc_decomp_type);
30587 gcc_checking_assert (!type_dependent_expression_p (init));
30588 /* If the constraint is dependent, we need to wait until
30589 instantiation time to resolve the placeholder. */
30590 if (placeholder_type_constraint_dependent_p (constr))
30591 return type;
30594 if (context == adc_return_type
30595 || context == adc_variable_type
30596 || context == adc_decomp_type)
30597 if (tree fn = current_function_decl)
30598 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30600 outer_targs = DECL_TEMPLATE_INFO (fn)
30601 ? DECL_TI_ARGS (fn) : NULL_TREE;
30602 if (LAMBDA_FUNCTION_P (fn))
30604 /* As in satisfy_declaration_constraints. */
30605 tree regen_args = lambda_regenerating_args (fn);
30606 if (outer_targs)
30607 outer_targs = add_to_template_args (regen_args, outer_targs);
30608 else
30609 outer_targs = regen_args;
30613 tree full_targs = add_to_template_args (outer_targs, targs);
30615 /* HACK: Compensate for callers not always communicating all levels of
30616 outer template arguments by filling in the outermost missing levels
30617 with dummy levels before checking satisfaction. We'll still crash
30618 if the constraint depends on a template argument belonging to one of
30619 these missing levels, but this hack otherwise allows us to handle a
30620 large subset of possible constraints (including all non-dependent
30621 constraints). */
30622 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30623 - TMPL_ARGS_DEPTH (full_targs)))
30625 tree dummy_levels = make_tree_vec (missing_levels);
30626 for (int i = 0; i < missing_levels; ++i)
30627 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30628 full_targs = add_to_template_args (dummy_levels, full_targs);
30631 if (!constraints_satisfied_p (auto_node, full_targs))
30633 if (complain & tf_warning_or_error)
30635 auto_diagnostic_group d;
30636 switch (context)
30638 case adc_unspecified:
30639 case adc_unify:
30640 error_at (loc, "placeholder constraints not satisfied");
30641 break;
30642 case adc_variable_type:
30643 case adc_decomp_type:
30644 error_at (loc, "deduced initializer does not satisfy "
30645 "placeholder constraints");
30646 break;
30647 case adc_return_type:
30648 error_at (loc, "deduced return type does not satisfy "
30649 "placeholder constraints");
30650 break;
30651 case adc_requirement:
30652 error_at (loc, "deduced expression type does not satisfy "
30653 "placeholder constraints");
30654 break;
30656 diagnose_constraints (loc, auto_node, full_targs);
30658 return error_mark_node;
30662 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
30663 /* The outer template arguments are already substituted into type
30664 (but we still may have used them for constraint checking above). */;
30665 else if (context == adc_unify)
30666 targs = add_to_template_args (outer_targs, targs);
30667 else if (processing_template_decl)
30668 targs = add_to_template_args (current_template_args (), targs);
30669 return tsubst (type, targs, complain, NULL_TREE);
30672 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
30673 result. */
30675 tree
30676 splice_late_return_type (tree type, tree late_return_type)
30678 if (late_return_type)
30680 gcc_assert (is_auto (type) || seen_error ());
30681 return late_return_type;
30684 if (tree auto_node = find_type_usage (type, is_auto))
30685 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
30687 /* In an abbreviated function template we didn't know we were dealing
30688 with a function template when we saw the auto return type, so rebuild
30689 the return type using an auto with the correct level. */
30690 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
30691 tree auto_vec = make_tree_vec (1);
30692 TREE_VEC_ELT (auto_vec, 0) = new_auto;
30693 tree targs = add_outermost_template_args (current_template_args (),
30694 auto_vec);
30695 /* Also rebuild the constraint info in terms of the new auto. */
30696 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
30697 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
30698 = build_tree_list (current_template_parms,
30699 tsubst_constraint (TREE_VALUE (ci), targs,
30700 tf_none, NULL_TREE));
30701 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
30702 return tsubst (type, targs, tf_none, NULL_TREE);
30704 return type;
30707 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
30708 'decltype(auto)' or a deduced class template. */
30710 bool
30711 is_auto (const_tree type)
30713 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
30714 && (TYPE_IDENTIFIER (type) == auto_identifier
30715 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
30716 return true;
30717 else
30718 return false;
30721 /* for_each_template_parm callback for type_uses_auto. */
30724 is_auto_r (tree tp, void */*data*/)
30726 return is_auto (tp);
30729 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
30730 a use of `auto'. Returns NULL_TREE otherwise. */
30732 tree
30733 type_uses_auto (tree type)
30735 if (type == NULL_TREE)
30736 return NULL_TREE;
30737 else if (flag_concepts_ts)
30739 /* The Concepts TS allows multiple autos in one type-specifier; just
30740 return the first one we find, do_auto_deduction will collect all of
30741 them. */
30742 if (uses_template_parms (type))
30743 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
30744 /*visited*/NULL, /*nondeduced*/false);
30745 else
30746 return NULL_TREE;
30748 else
30749 return find_type_usage (type, is_auto);
30752 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
30753 concepts are enabled, auto is acceptable in template arguments, but
30754 only when TEMPL identifies a template class. Return TRUE if any
30755 such errors were reported. */
30757 bool
30758 check_auto_in_tmpl_args (tree tmpl, tree args)
30760 if (!flag_concepts_ts)
30761 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
30762 have already been rejected by the parser more generally. */
30763 return false;
30765 /* If there were previous errors, nevermind. */
30766 if (!args || TREE_CODE (args) != TREE_VEC)
30767 return false;
30769 /* If TMPL is an identifier, we're parsing and we can't tell yet
30770 whether TMPL is supposed to be a type, a function or a variable.
30771 We'll only be able to tell during template substitution, so we
30772 expect to be called again then. If concepts are enabled and we
30773 know we have a type, we're ok. */
30774 if (identifier_p (tmpl)
30775 || (DECL_P (tmpl)
30776 && (DECL_TYPE_TEMPLATE_P (tmpl)
30777 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
30778 return false;
30780 /* Quickly search for any occurrences of auto; usually there won't
30781 be any, and then we'll avoid allocating the vector. */
30782 if (!type_uses_auto (args))
30783 return false;
30785 bool errors = false;
30787 tree vec = extract_autos (args);
30788 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
30790 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
30791 error_at (DECL_SOURCE_LOCATION (xauto),
30792 "invalid use of %qT in template argument", xauto);
30793 errors = true;
30796 return errors;
30799 /* Recursively walk over && expressions searching for EXPR. Return a reference
30800 to that expression. */
30802 static tree *find_template_requirement (tree *t, tree key)
30804 if (*t == key)
30805 return t;
30806 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
30808 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
30809 return p;
30810 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
30811 return p;
30813 return 0;
30816 /* Convert the generic type parameters in PARM that match the types given in the
30817 range [START_IDX, END_IDX) from the current_template_parms into generic type
30818 packs. */
30820 tree
30821 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
30823 tree current = current_template_parms;
30824 int depth = TMPL_PARMS_DEPTH (current);
30825 current = INNERMOST_TEMPLATE_PARMS (current);
30826 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
30828 for (int i = 0; i < start_idx; ++i)
30829 TREE_VEC_ELT (replacement, i)
30830 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30832 for (int i = start_idx; i < end_idx; ++i)
30834 /* Create a distinct parameter pack type from the current parm and add it
30835 to the replacement args to tsubst below into the generic function
30836 parameter. */
30837 tree node = TREE_VEC_ELT (current, i);
30838 tree o = TREE_TYPE (TREE_VALUE (node));
30839 tree t = copy_type (o);
30840 TEMPLATE_TYPE_PARM_INDEX (t)
30841 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
30842 t, 0, 0, tf_none);
30843 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
30844 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
30845 TYPE_MAIN_VARIANT (t) = t;
30846 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
30847 TYPE_CANONICAL (t) = canonical_type_parameter (t);
30848 TREE_VEC_ELT (replacement, i) = t;
30850 /* Replace the current template parameter with new pack. */
30851 TREE_VALUE (node) = TREE_CHAIN (t);
30853 /* Surgically adjust the associated constraint of adjusted parameter
30854 and it's corresponding contribution to the current template
30855 requirements. */
30856 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
30858 tree id = unpack_concept_check (constr);
30859 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
30860 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
30861 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
30863 /* If there was a constraint, we also need to replace that in
30864 the template requirements, which we've already built. */
30865 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
30866 reqs = find_template_requirement (reqs, constr);
30867 *reqs = fold;
30871 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
30872 TREE_VEC_ELT (replacement, i)
30873 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30875 /* If there are more levels then build up the replacement with the outer
30876 template parms. */
30877 if (depth > 1)
30878 replacement = add_to_template_args (template_parms_to_args
30879 (TREE_CHAIN (current_template_parms)),
30880 replacement);
30882 return tsubst (parm, replacement, tf_none, NULL_TREE);
30885 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
30886 0..N-1. */
30888 void
30889 declare_integer_pack (void)
30891 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
30892 build_function_type_list (integer_type_node,
30893 integer_type_node,
30894 NULL_TREE),
30895 NULL_TREE, ECF_CONST);
30896 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
30897 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
30898 CP_BUILT_IN_INTEGER_PACK);
30901 /* Walk the decl or type specialization table calling FN on each
30902 entry. */
30904 void
30905 walk_specializations (bool decls_p,
30906 void (*fn) (bool decls_p, spec_entry *entry, void *data),
30907 void *data)
30909 spec_hash_table *table = decls_p ? decl_specializations
30910 : type_specializations;
30911 spec_hash_table::iterator end (table->end ());
30912 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
30913 fn (decls_p, *iter, data);
30916 /* Lookup the specialization of *ELT, in the decl or type
30917 specialization table. Return the SPEC that's already there, or
30918 NULL if nothing. */
30920 tree
30921 match_mergeable_specialization (bool decl_p, spec_entry *elt)
30923 hash_table<spec_hasher> *specializations
30924 = decl_p ? decl_specializations : type_specializations;
30925 hashval_t hash = spec_hasher::hash (elt);
30926 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30928 if (slot)
30929 return (*slot)->spec;
30931 return NULL_TREE;
30934 /* Return flags encoding whether SPEC is on the instantiation and/or
30935 specialization lists of TMPL. */
30937 unsigned
30938 get_mergeable_specialization_flags (tree tmpl, tree decl)
30940 unsigned flags = 0;
30942 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30943 inst; inst = TREE_CHAIN (inst))
30944 if (TREE_VALUE (inst) == decl)
30946 flags |= 1;
30947 break;
30950 if (CLASS_TYPE_P (TREE_TYPE (decl))
30951 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30952 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30953 /* Only need to search if DECL is a partial specialization. */
30954 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30955 part; part = TREE_CHAIN (part))
30956 if (TREE_VALUE (part) == decl)
30958 flags |= 2;
30959 break;
30962 return flags;
30965 /* Add a new specialization described by SPEC. DECL is the
30966 maybe-template decl and FLAGS is as returned from
30967 get_mergeable_specialization_flags. */
30969 void
30970 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30971 tree decl, unsigned flags)
30973 hashval_t hash = spec_hasher::hash (elt);
30974 if (decl_p)
30976 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30978 gcc_checking_assert (!*slot);
30979 auto entry = ggc_alloc<spec_entry> ();
30980 *entry = *elt;
30981 *slot = entry;
30983 if (alias_p)
30985 elt->spec = TREE_TYPE (elt->spec);
30986 gcc_checking_assert (elt->spec);
30990 if (!decl_p || alias_p)
30992 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30994 /* We don't distinguish different constrained partial type
30995 specializations, so there could be duplicates. Everything else
30996 must be new. */
30997 if (!(flags & 2 && *slot))
30999 gcc_checking_assert (!*slot);
31001 auto entry = ggc_alloc<spec_entry> ();
31002 *entry = *elt;
31003 *slot = entry;
31007 if (flags & 1)
31008 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31009 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31011 if (flags & 2)
31013 /* A partial specialization. */
31014 tree cons = tree_cons (elt->args, decl,
31015 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31016 TREE_TYPE (cons) = elt->spec;
31017 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31021 /* Set up the hash tables for template instantiations. */
31023 void
31024 init_template_processing (void)
31026 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31027 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31029 if (cxx_dialect >= cxx11)
31030 declare_integer_pack ();
31033 /* Print stats about the template hash tables for -fstats. */
31035 void
31036 print_template_statistics (void)
31038 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31039 "%f collisions\n", (long) decl_specializations->size (),
31040 (long) decl_specializations->elements (),
31041 decl_specializations->collisions ());
31042 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31043 "%f collisions\n", (long) type_specializations->size (),
31044 (long) type_specializations->elements (),
31045 type_specializations->collisions ());
31048 #if CHECKING_P
31050 namespace selftest {
31052 /* Verify that build_non_dependent_expr () works, for various expressions,
31053 and that location wrappers don't affect the results. */
31055 static void
31056 test_build_non_dependent_expr ()
31058 location_t loc = BUILTINS_LOCATION;
31060 /* Verify constants, without and with location wrappers. */
31061 tree int_cst = build_int_cst (integer_type_node, 42);
31062 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31064 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31065 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31066 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31068 tree string_lit = build_string (4, "foo");
31069 TREE_TYPE (string_lit) = char_array_type_node;
31070 string_lit = fix_string_type (string_lit);
31071 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31073 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31074 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31075 ASSERT_EQ (wrapped_string_lit,
31076 build_non_dependent_expr (wrapped_string_lit));
31079 /* Verify that type_dependent_expression_p () works correctly, even
31080 in the presence of location wrapper nodes. */
31082 static void
31083 test_type_dependent_expression_p ()
31085 location_t loc = BUILTINS_LOCATION;
31087 tree name = get_identifier ("foo");
31089 /* If no templates are involved, nothing is type-dependent. */
31090 gcc_assert (!processing_template_decl);
31091 ASSERT_FALSE (type_dependent_expression_p (name));
31093 ++processing_template_decl;
31095 /* Within a template, an unresolved name is always type-dependent. */
31096 ASSERT_TRUE (type_dependent_expression_p (name));
31098 /* Ensure it copes with NULL_TREE and errors. */
31099 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31100 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31102 /* A USING_DECL in a template should be type-dependent, even if wrapped
31103 with a location wrapper (PR c++/83799). */
31104 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31105 TREE_TYPE (using_decl) = integer_type_node;
31106 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31107 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31108 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31109 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31111 --processing_template_decl;
31114 /* Run all of the selftests within this file. */
31116 void
31117 cp_pt_cc_tests ()
31119 test_build_non_dependent_expr ();
31120 test_type_dependent_expression_p ();
31123 } // namespace selftest
31125 #endif /* #if CHECKING_P */
31127 #include "gt-cp-pt.h"