PR c++/85710 - ICE with -Wmemset-elt-size.
[official-gcc.git] / gcc / cp / pt.c
blob448cd69b722b1ad23d298d52645bd3a2d2171a2f
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2018 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 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43 #include "gcc-rich-location.h"
44 #include "selftest.h"
46 /* The type of functions taking a tree, and some additional data, and
47 returning an int. */
48 typedef int (*tree_fn_t) (tree, void*);
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51 instantiations have been deferred, either because their definitions
52 were not yet available, or because we were putting off doing the work. */
53 struct GTY ((chain_next ("%h.next"))) pending_template
55 struct pending_template *next;
56 struct tinst_level *tinst;
59 static GTY(()) struct pending_template *pending_templates;
60 static GTY(()) struct pending_template *last_pending_template;
62 int processing_template_parmlist;
63 static int template_header_count;
65 static GTY(()) tree saved_trees;
66 static vec<int> inline_parm_levels;
68 static GTY(()) struct tinst_level *current_tinst_level;
70 static GTY(()) tree saved_access_scope;
72 /* Live only within one (recursive) call to tsubst_expr. We use
73 this to pass the statement expression node from the STMT_EXPR
74 to the EXPR_STMT that is its result. */
75 static tree cur_stmt_expr;
77 // -------------------------------------------------------------------------- //
78 // Local Specialization Stack
80 // Implementation of the RAII helper for creating new local
81 // specializations.
82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83 : saved (local_specializations)
85 if (policy == lss_blank || !saved)
86 local_specializations = new hash_map<tree, tree>;
87 else
88 local_specializations = new hash_map<tree, tree>(*saved);
91 local_specialization_stack::~local_specialization_stack ()
93 delete local_specializations;
94 local_specializations = saved;
97 /* True if we've recursed into fn_type_unification too many times. */
98 static bool excessive_deduction_depth;
100 struct GTY((for_user)) spec_entry
102 tree tmpl;
103 tree args;
104 tree spec;
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
109 static hashval_t hash (spec_entry *);
110 static bool equal (spec_entry *, spec_entry *);
113 static GTY (()) hash_table<spec_hasher> *decl_specializations;
115 static GTY (()) hash_table<spec_hasher> *type_specializations;
117 /* Contains canonical template parameter types. The vector is indexed by
118 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
119 TREE_LIST, whose TREE_VALUEs contain the canonical template
120 parameters of various types and levels. */
121 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
123 #define UNIFY_ALLOW_NONE 0
124 #define UNIFY_ALLOW_MORE_CV_QUAL 1
125 #define UNIFY_ALLOW_LESS_CV_QUAL 2
126 #define UNIFY_ALLOW_DERIVED 4
127 #define UNIFY_ALLOW_INTEGER 8
128 #define UNIFY_ALLOW_OUTER_LEVEL 16
129 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
130 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
132 enum template_base_result {
133 tbr_incomplete_type,
134 tbr_ambiguous_baseclass,
135 tbr_success
138 static void push_access_scope (tree);
139 static void pop_access_scope (tree);
140 static bool resolve_overloaded_unification (tree, tree, tree, tree,
141 unification_kind_t, int,
142 bool);
143 static int try_one_overload (tree, tree, tree, tree, tree,
144 unification_kind_t, int, bool, bool);
145 static int unify (tree, tree, tree, tree, int, bool);
146 static void add_pending_template (tree);
147 static tree reopen_tinst_level (struct tinst_level *);
148 static tree tsubst_initializer_list (tree, tree);
149 static tree get_partial_spec_bindings (tree, tree, tree);
150 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
151 bool, bool);
152 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
153 bool, bool);
154 static void tsubst_enum (tree, tree, tree);
155 static tree add_to_template_args (tree, tree);
156 static tree add_outermost_template_args (tree, tree);
157 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
158 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
159 tree);
160 static int type_unification_real (tree, tree, tree, const tree *,
161 unsigned int, int, unification_kind_t, int,
162 vec<deferred_access_check, va_gc> **,
163 bool);
164 static void note_template_header (int);
165 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
166 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
167 static tree convert_template_argument (tree, tree, tree,
168 tsubst_flags_t, int, tree);
169 static tree for_each_template_parm (tree, tree_fn_t, void*,
170 hash_set<tree> *, bool, tree_fn_t = NULL);
171 static tree expand_template_argument_pack (tree);
172 static tree build_template_parm_index (int, int, int, tree, tree);
173 static bool inline_needs_template_parms (tree, bool);
174 static void push_inline_template_parms_recursive (tree, int);
175 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
176 static int mark_template_parm (tree, void *);
177 static int template_parm_this_level_p (tree, void *);
178 static tree tsubst_friend_function (tree, tree);
179 static tree tsubst_friend_class (tree, tree);
180 static int can_complete_type_without_circularity (tree);
181 static tree get_bindings (tree, tree, tree, bool);
182 static int template_decl_level (tree);
183 static int check_cv_quals_for_unify (int, tree, tree);
184 static void template_parm_level_and_index (tree, int*, int*);
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_arg (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
191 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
192 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
193 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
194 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
195 static bool check_specialization_scope (void);
196 static tree process_partial_specialization (tree);
197 static void set_current_access_from_decl (tree);
198 static enum template_base_result get_template_base (tree, tree, tree, tree,
199 bool , tree *);
200 static tree try_class_unification (tree, tree, tree, tree, bool);
201 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
202 tree, tree);
203 static bool template_template_parm_bindings_ok_p (tree, tree);
204 static void tsubst_default_arguments (tree, tsubst_flags_t);
205 static tree for_each_template_parm_r (tree *, int *, void *);
206 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
207 static void copy_default_args_to_explicit_spec (tree);
208 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
209 static bool dependent_template_arg_p (tree);
210 static bool any_template_arguments_need_structural_equality_p (tree);
211 static bool dependent_type_p_r (tree);
212 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
213 static tree tsubst_decl (tree, tree, tsubst_flags_t);
214 static void perform_typedefs_access_check (tree tmpl, tree targs);
215 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
216 location_t);
217 static tree listify (tree);
218 static tree listify_autos (tree, tree);
219 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
220 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
221 static bool complex_alias_template_p (const_tree tmpl);
222 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
223 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
224 static tree make_argument_pack (tree);
225 static void register_parameter_specializations (tree, tree);
226 static tree enclosing_instantiation_of (tree tctx);
228 /* Make the current scope suitable for access checking when we are
229 processing T. T can be FUNCTION_DECL for instantiated function
230 template, VAR_DECL for static member variable, or TYPE_DECL for
231 alias template (needed by instantiate_decl). */
233 static void
234 push_access_scope (tree t)
236 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
237 || TREE_CODE (t) == TYPE_DECL);
239 if (DECL_FRIEND_CONTEXT (t))
240 push_nested_class (DECL_FRIEND_CONTEXT (t));
241 else if (DECL_CLASS_SCOPE_P (t))
242 push_nested_class (DECL_CONTEXT (t));
243 else
244 push_to_top_level ();
246 if (TREE_CODE (t) == FUNCTION_DECL)
248 saved_access_scope = tree_cons
249 (NULL_TREE, current_function_decl, saved_access_scope);
250 current_function_decl = t;
254 /* Restore the scope set up by push_access_scope. T is the node we
255 are processing. */
257 static void
258 pop_access_scope (tree t)
260 if (TREE_CODE (t) == FUNCTION_DECL)
262 current_function_decl = TREE_VALUE (saved_access_scope);
263 saved_access_scope = TREE_CHAIN (saved_access_scope);
266 if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
267 pop_nested_class ();
268 else
269 pop_from_top_level ();
272 /* Do any processing required when DECL (a member template
273 declaration) is finished. Returns the TEMPLATE_DECL corresponding
274 to DECL, unless it is a specialization, in which case the DECL
275 itself is returned. */
277 tree
278 finish_member_template_decl (tree decl)
280 if (decl == error_mark_node)
281 return error_mark_node;
283 gcc_assert (DECL_P (decl));
285 if (TREE_CODE (decl) == TYPE_DECL)
287 tree type;
289 type = TREE_TYPE (decl);
290 if (type == error_mark_node)
291 return error_mark_node;
292 if (MAYBE_CLASS_TYPE_P (type)
293 && CLASSTYPE_TEMPLATE_INFO (type)
294 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
296 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
297 check_member_template (tmpl);
298 return tmpl;
300 return NULL_TREE;
302 else if (TREE_CODE (decl) == FIELD_DECL)
303 error ("data member %qD cannot be a member template", decl);
304 else if (DECL_TEMPLATE_INFO (decl))
306 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
308 check_member_template (DECL_TI_TEMPLATE (decl));
309 return DECL_TI_TEMPLATE (decl);
311 else
312 return decl;
314 else
315 error ("invalid member template declaration %qD", decl);
317 return error_mark_node;
320 /* Create a template info node. */
322 tree
323 build_template_info (tree template_decl, tree template_args)
325 tree result = make_node (TEMPLATE_INFO);
326 TI_TEMPLATE (result) = template_decl;
327 TI_ARGS (result) = template_args;
328 return result;
331 /* Return the template info node corresponding to T, whatever T is. */
333 tree
334 get_template_info (const_tree t)
336 tree tinfo = NULL_TREE;
338 if (!t || t == error_mark_node)
339 return NULL;
341 if (TREE_CODE (t) == NAMESPACE_DECL
342 || TREE_CODE (t) == PARM_DECL)
343 return NULL;
345 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
346 tinfo = DECL_TEMPLATE_INFO (t);
348 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
349 t = TREE_TYPE (t);
351 if (OVERLOAD_TYPE_P (t))
352 tinfo = TYPE_TEMPLATE_INFO (t);
353 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
354 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
356 return tinfo;
359 /* Returns the template nesting level of the indicated class TYPE.
361 For example, in:
362 template <class T>
363 struct A
365 template <class U>
366 struct B {};
369 A<T>::B<U> has depth two, while A<T> has depth one.
370 Both A<T>::B<int> and A<int>::B<U> have depth one, if
371 they are instantiations, not specializations.
373 This function is guaranteed to return 0 if passed NULL_TREE so
374 that, for example, `template_class_depth (current_class_type)' is
375 always safe. */
378 template_class_depth (tree type)
380 int depth;
382 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
384 tree tinfo = get_template_info (type);
386 if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
387 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
388 ++depth;
390 if (DECL_P (type))
391 type = CP_DECL_CONTEXT (type);
392 else if (LAMBDA_TYPE_P (type))
393 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
394 else
395 type = CP_TYPE_CONTEXT (type);
398 return depth;
401 /* Subroutine of maybe_begin_member_template_processing.
402 Returns true if processing DECL needs us to push template parms. */
404 static bool
405 inline_needs_template_parms (tree decl, bool nsdmi)
407 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
408 return false;
410 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
411 > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
414 /* Subroutine of maybe_begin_member_template_processing.
415 Push the template parms in PARMS, starting from LEVELS steps into the
416 chain, and ending at the beginning, since template parms are listed
417 innermost first. */
419 static void
420 push_inline_template_parms_recursive (tree parmlist, int levels)
422 tree parms = TREE_VALUE (parmlist);
423 int i;
425 if (levels > 1)
426 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
428 ++processing_template_decl;
429 current_template_parms
430 = tree_cons (size_int (processing_template_decl),
431 parms, current_template_parms);
432 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
434 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
435 NULL);
436 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
438 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
440 if (error_operand_p (parm))
441 continue;
443 gcc_assert (DECL_P (parm));
445 switch (TREE_CODE (parm))
447 case TYPE_DECL:
448 case TEMPLATE_DECL:
449 pushdecl (parm);
450 break;
452 case PARM_DECL:
453 /* Push the CONST_DECL. */
454 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
455 break;
457 default:
458 gcc_unreachable ();
463 /* Restore the template parameter context for a member template, a
464 friend template defined in a class definition, or a non-template
465 member of template class. */
467 void
468 maybe_begin_member_template_processing (tree decl)
470 tree parms;
471 int levels = 0;
472 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
474 if (nsdmi)
476 tree ctx = DECL_CONTEXT (decl);
477 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
478 /* Disregard full specializations (c++/60999). */
479 && uses_template_parms (ctx)
480 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
483 if (inline_needs_template_parms (decl, nsdmi))
485 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
486 levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
488 if (DECL_TEMPLATE_SPECIALIZATION (decl))
490 --levels;
491 parms = TREE_CHAIN (parms);
494 push_inline_template_parms_recursive (parms, levels);
497 /* Remember how many levels of template parameters we pushed so that
498 we can pop them later. */
499 inline_parm_levels.safe_push (levels);
502 /* Undo the effects of maybe_begin_member_template_processing. */
504 void
505 maybe_end_member_template_processing (void)
507 int i;
508 int last;
510 if (inline_parm_levels.length () == 0)
511 return;
513 last = inline_parm_levels.pop ();
514 for (i = 0; i < last; ++i)
516 --processing_template_decl;
517 current_template_parms = TREE_CHAIN (current_template_parms);
518 poplevel (0, 0, 0);
522 /* Return a new template argument vector which contains all of ARGS,
523 but has as its innermost set of arguments the EXTRA_ARGS. */
525 static tree
526 add_to_template_args (tree args, tree extra_args)
528 tree new_args;
529 int extra_depth;
530 int i;
531 int j;
533 if (args == NULL_TREE || extra_args == error_mark_node)
534 return extra_args;
536 extra_depth = TMPL_ARGS_DEPTH (extra_args);
537 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
539 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
540 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
542 for (j = 1; j <= extra_depth; ++j, ++i)
543 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
545 return new_args;
548 /* Like add_to_template_args, but only the outermost ARGS are added to
549 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
550 (EXTRA_ARGS) levels are added. This function is used to combine
551 the template arguments from a partial instantiation with the
552 template arguments used to attain the full instantiation from the
553 partial instantiation. */
555 static tree
556 add_outermost_template_args (tree args, tree extra_args)
558 tree new_args;
560 /* If there are more levels of EXTRA_ARGS than there are ARGS,
561 something very fishy is going on. */
562 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
564 /* If *all* the new arguments will be the EXTRA_ARGS, just return
565 them. */
566 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
567 return extra_args;
569 /* For the moment, we make ARGS look like it contains fewer levels. */
570 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
572 new_args = add_to_template_args (args, extra_args);
574 /* Now, we restore ARGS to its full dimensions. */
575 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
577 return new_args;
580 /* Return the N levels of innermost template arguments from the ARGS. */
582 tree
583 get_innermost_template_args (tree args, int n)
585 tree new_args;
586 int extra_levels;
587 int i;
589 gcc_assert (n >= 0);
591 /* If N is 1, just return the innermost set of template arguments. */
592 if (n == 1)
593 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
595 /* If we're not removing anything, just return the arguments we were
596 given. */
597 extra_levels = TMPL_ARGS_DEPTH (args) - n;
598 gcc_assert (extra_levels >= 0);
599 if (extra_levels == 0)
600 return args;
602 /* Make a new set of arguments, not containing the outer arguments. */
603 new_args = make_tree_vec (n);
604 for (i = 1; i <= n; ++i)
605 SET_TMPL_ARGS_LEVEL (new_args, i,
606 TMPL_ARGS_LEVEL (args, i + extra_levels));
608 return new_args;
611 /* The inverse of get_innermost_template_args: Return all but the innermost
612 EXTRA_LEVELS levels of template arguments from the ARGS. */
614 static tree
615 strip_innermost_template_args (tree args, int extra_levels)
617 tree new_args;
618 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
619 int i;
621 gcc_assert (n >= 0);
623 /* If N is 1, just return the outermost set of template arguments. */
624 if (n == 1)
625 return TMPL_ARGS_LEVEL (args, 1);
627 /* If we're not removing anything, just return the arguments we were
628 given. */
629 gcc_assert (extra_levels >= 0);
630 if (extra_levels == 0)
631 return args;
633 /* Make a new set of arguments, not containing the inner arguments. */
634 new_args = make_tree_vec (n);
635 for (i = 1; i <= n; ++i)
636 SET_TMPL_ARGS_LEVEL (new_args, i,
637 TMPL_ARGS_LEVEL (args, i));
639 return new_args;
642 /* We've got a template header coming up; push to a new level for storing
643 the parms. */
645 void
646 begin_template_parm_list (void)
648 /* We use a non-tag-transparent scope here, which causes pushtag to
649 put tags in this scope, rather than in the enclosing class or
650 namespace scope. This is the right thing, since we want
651 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
652 global template class, push_template_decl handles putting the
653 TEMPLATE_DECL into top-level scope. For a nested template class,
654 e.g.:
656 template <class T> struct S1 {
657 template <class T> struct S2 {};
660 pushtag contains special code to insert the TEMPLATE_DECL for S2
661 at the right scope. */
662 begin_scope (sk_template_parms, NULL);
663 ++processing_template_decl;
664 ++processing_template_parmlist;
665 note_template_header (0);
667 /* Add a dummy parameter level while we process the parameter list. */
668 current_template_parms
669 = tree_cons (size_int (processing_template_decl),
670 make_tree_vec (0),
671 current_template_parms);
674 /* This routine is called when a specialization is declared. If it is
675 invalid to declare a specialization here, an error is reported and
676 false is returned, otherwise this routine will return true. */
678 static bool
679 check_specialization_scope (void)
681 tree scope = current_scope ();
683 /* [temp.expl.spec]
685 An explicit specialization shall be declared in the namespace of
686 which the template is a member, or, for member templates, in the
687 namespace of which the enclosing class or enclosing class
688 template is a member. An explicit specialization of a member
689 function, member class or static data member of a class template
690 shall be declared in the namespace of which the class template
691 is a member. */
692 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
694 error ("explicit specialization in non-namespace scope %qD", scope);
695 return false;
698 /* [temp.expl.spec]
700 In an explicit specialization declaration for a member of a class
701 template or a member template that appears in namespace scope,
702 the member template and some of its enclosing class templates may
703 remain unspecialized, except that the declaration shall not
704 explicitly specialize a class member template if its enclosing
705 class templates are not explicitly specialized as well. */
706 if (current_template_parms)
708 error ("enclosing class templates are not explicitly specialized");
709 return false;
712 return true;
715 /* We've just seen template <>. */
717 bool
718 begin_specialization (void)
720 begin_scope (sk_template_spec, NULL);
721 note_template_header (1);
722 return check_specialization_scope ();
725 /* Called at then end of processing a declaration preceded by
726 template<>. */
728 void
729 end_specialization (void)
731 finish_scope ();
732 reset_specialization ();
735 /* Any template <>'s that we have seen thus far are not referring to a
736 function specialization. */
738 void
739 reset_specialization (void)
741 processing_specialization = 0;
742 template_header_count = 0;
745 /* We've just seen a template header. If SPECIALIZATION is nonzero,
746 it was of the form template <>. */
748 static void
749 note_template_header (int specialization)
751 processing_specialization = specialization;
752 template_header_count++;
755 /* We're beginning an explicit instantiation. */
757 void
758 begin_explicit_instantiation (void)
760 gcc_assert (!processing_explicit_instantiation);
761 processing_explicit_instantiation = true;
765 void
766 end_explicit_instantiation (void)
768 gcc_assert (processing_explicit_instantiation);
769 processing_explicit_instantiation = false;
772 /* An explicit specialization or partial specialization of TMPL is being
773 declared. Check that the namespace in which the specialization is
774 occurring is permissible. Returns false iff it is invalid to
775 specialize TMPL in the current namespace. */
777 static bool
778 check_specialization_namespace (tree tmpl)
780 tree tpl_ns = decl_namespace_context (tmpl);
782 /* [tmpl.expl.spec]
784 An explicit specialization shall be declared in a namespace enclosing the
785 specialized template. An explicit specialization whose declarator-id is
786 not qualified shall be declared in the nearest enclosing namespace of the
787 template, or, if the namespace is inline (7.3.1), any namespace from its
788 enclosing namespace set. */
789 if (current_scope() != DECL_CONTEXT (tmpl)
790 && !at_namespace_scope_p ())
792 error ("specialization of %qD must appear at namespace scope", tmpl);
793 return false;
796 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
797 /* Same or enclosing namespace. */
798 return true;
799 else
801 permerror (input_location,
802 "specialization of %qD in different namespace", tmpl);
803 inform (DECL_SOURCE_LOCATION (tmpl),
804 " from definition of %q#D", tmpl);
805 return false;
809 /* SPEC is an explicit instantiation. Check that it is valid to
810 perform this explicit instantiation in the current namespace. */
812 static void
813 check_explicit_instantiation_namespace (tree spec)
815 tree ns;
817 /* DR 275: An explicit instantiation shall appear in an enclosing
818 namespace of its template. */
819 ns = decl_namespace_context (spec);
820 if (!is_nested_namespace (current_namespace, ns))
821 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
822 "(which does not enclose namespace %qD)",
823 spec, current_namespace, ns);
826 // Returns the type of a template specialization only if that
827 // specialization needs to be defined. Otherwise (e.g., if the type has
828 // already been defined), the function returns NULL_TREE.
829 static tree
830 maybe_new_partial_specialization (tree type)
832 // An implicit instantiation of an incomplete type implies
833 // the definition of a new class template.
835 // template<typename T>
836 // struct S;
838 // template<typename T>
839 // struct S<T*>;
841 // Here, S<T*> is an implicit instantiation of S whose type
842 // is incomplete.
843 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
844 return type;
846 // It can also be the case that TYPE is a completed specialization.
847 // Continuing the previous example, suppose we also declare:
849 // template<typename T>
850 // requires Integral<T>
851 // struct S<T*>;
853 // Here, S<T*> refers to the specialization S<T*> defined
854 // above. However, we need to differentiate definitions because
855 // we intend to define a new partial specialization. In this case,
856 // we rely on the fact that the constraints are different for
857 // this declaration than that above.
859 // Note that we also get here for injected class names and
860 // late-parsed template definitions. We must ensure that we
861 // do not create new type declarations for those cases.
862 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
864 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
865 tree args = CLASSTYPE_TI_ARGS (type);
867 // If there are no template parameters, this cannot be a new
868 // partial template specializtion?
869 if (!current_template_parms)
870 return NULL_TREE;
872 // The injected-class-name is not a new partial specialization.
873 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
874 return NULL_TREE;
876 // If the constraints are not the same as those of the primary
877 // then, we can probably create a new specialization.
878 tree type_constr = current_template_constraints ();
880 if (type == TREE_TYPE (tmpl))
882 tree main_constr = get_constraints (tmpl);
883 if (equivalent_constraints (type_constr, main_constr))
884 return NULL_TREE;
887 // Also, if there's a pre-existing specialization with matching
888 // constraints, then this also isn't new.
889 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
890 while (specs)
892 tree spec_tmpl = TREE_VALUE (specs);
893 tree spec_args = TREE_PURPOSE (specs);
894 tree spec_constr = get_constraints (spec_tmpl);
895 if (comp_template_args (args, spec_args)
896 && equivalent_constraints (type_constr, spec_constr))
897 return NULL_TREE;
898 specs = TREE_CHAIN (specs);
901 // Create a new type node (and corresponding type decl)
902 // for the newly declared specialization.
903 tree t = make_class_type (TREE_CODE (type));
904 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
905 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
907 /* We only need a separate type node for storing the definition of this
908 partial specialization; uses of S<T*> are unconstrained, so all are
909 equivalent. So keep TYPE_CANONICAL the same. */
910 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
912 // Build the corresponding type decl.
913 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
914 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
915 DECL_SOURCE_LOCATION (d) = input_location;
917 return t;
920 return NULL_TREE;
923 /* The TYPE is being declared. If it is a template type, that means it
924 is a partial specialization. Do appropriate error-checking. */
926 tree
927 maybe_process_partial_specialization (tree type)
929 tree context;
931 if (type == error_mark_node)
932 return error_mark_node;
934 /* A lambda that appears in specialization context is not itself a
935 specialization. */
936 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
937 return type;
939 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
941 error ("name of class shadows template template parameter %qD",
942 TYPE_NAME (type));
943 return error_mark_node;
946 context = TYPE_CONTEXT (type);
948 if (TYPE_ALIAS_P (type))
950 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
952 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
953 error ("specialization of alias template %qD",
954 TI_TEMPLATE (tinfo));
955 else
956 error ("explicit specialization of non-template %qT", type);
957 return error_mark_node;
959 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
961 /* This is for ordinary explicit specialization and partial
962 specialization of a template class such as:
964 template <> class C<int>;
968 template <class T> class C<T*>;
970 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
972 if (tree t = maybe_new_partial_specialization (type))
974 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
975 && !at_namespace_scope_p ())
976 return error_mark_node;
977 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
978 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
979 if (processing_template_decl)
981 tree decl = push_template_decl (TYPE_MAIN_DECL (t));
982 if (decl == error_mark_node)
983 return error_mark_node;
984 return TREE_TYPE (decl);
987 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
988 error ("specialization of %qT after instantiation", type);
989 else if (errorcount && !processing_specialization
990 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
991 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
992 /* Trying to define a specialization either without a template<> header
993 or in an inappropriate place. We've already given an error, so just
994 bail now so we don't actually define the specialization. */
995 return error_mark_node;
997 else if (CLASS_TYPE_P (type)
998 && !CLASSTYPE_USE_TEMPLATE (type)
999 && CLASSTYPE_TEMPLATE_INFO (type)
1000 && context && CLASS_TYPE_P (context)
1001 && CLASSTYPE_TEMPLATE_INFO (context))
1003 /* This is for an explicit specialization of member class
1004 template according to [temp.expl.spec/18]:
1006 template <> template <class U> class C<int>::D;
1008 The context `C<int>' must be an implicit instantiation.
1009 Otherwise this is just a member class template declared
1010 earlier like:
1012 template <> class C<int> { template <class U> class D; };
1013 template <> template <class U> class C<int>::D;
1015 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1016 while in the second case, `C<int>::D' is a primary template
1017 and `C<T>::D' may not exist. */
1019 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1020 && !COMPLETE_TYPE_P (type))
1022 tree t;
1023 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1025 if (current_namespace
1026 != decl_namespace_context (tmpl))
1028 permerror (input_location,
1029 "specializing %q#T in different namespace", type);
1030 permerror (DECL_SOURCE_LOCATION (tmpl),
1031 " from definition of %q#D", tmpl);
1034 /* Check for invalid specialization after instantiation:
1036 template <> template <> class C<int>::D<int>;
1037 template <> template <class U> class C<int>::D; */
1039 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1040 t; t = TREE_CHAIN (t))
1042 tree inst = TREE_VALUE (t);
1043 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1044 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1046 /* We already have a full specialization of this partial
1047 instantiation, or a full specialization has been
1048 looked up but not instantiated. Reassign it to the
1049 new member specialization template. */
1050 spec_entry elt;
1051 spec_entry *entry;
1053 elt.tmpl = most_general_template (tmpl);
1054 elt.args = CLASSTYPE_TI_ARGS (inst);
1055 elt.spec = inst;
1057 type_specializations->remove_elt (&elt);
1059 elt.tmpl = tmpl;
1060 elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1062 spec_entry **slot
1063 = type_specializations->find_slot (&elt, INSERT);
1064 entry = ggc_alloc<spec_entry> ();
1065 *entry = elt;
1066 *slot = entry;
1068 else
1069 /* But if we've had an implicit instantiation, that's a
1070 problem ([temp.expl.spec]/6). */
1071 error ("specialization %qT after instantiation %qT",
1072 type, inst);
1075 /* Mark TYPE as a specialization. And as a result, we only
1076 have one level of template argument for the innermost
1077 class template. */
1078 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1079 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1080 CLASSTYPE_TI_ARGS (type)
1081 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1084 else if (processing_specialization)
1086 /* Someday C++0x may allow for enum template specialization. */
1087 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1088 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1089 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1090 "of %qD not allowed by ISO C++", type);
1091 else
1093 error ("explicit specialization of non-template %qT", type);
1094 return error_mark_node;
1098 return type;
1101 /* Returns nonzero if we can optimize the retrieval of specializations
1102 for TMPL, a TEMPLATE_DECL. In particular, for such a template, we
1103 do not use DECL_TEMPLATE_SPECIALIZATIONS at all. */
1105 static inline bool
1106 optimize_specialization_lookup_p (tree tmpl)
1108 return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1109 && DECL_CLASS_SCOPE_P (tmpl)
1110 /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1111 parameter. */
1112 && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1113 /* The optimized lookup depends on the fact that the
1114 template arguments for the member function template apply
1115 purely to the containing class, which is not true if the
1116 containing class is an explicit or partial
1117 specialization. */
1118 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1119 && !DECL_MEMBER_TEMPLATE_P (tmpl)
1120 && !DECL_CONV_FN_P (tmpl)
1121 /* It is possible to have a template that is not a member
1122 template and is not a member of a template class:
1124 template <typename T>
1125 struct S { friend A::f(); };
1127 Here, the friend function is a template, but the context does
1128 not have template information. The optimized lookup relies
1129 on having ARGS be the template arguments for both the class
1130 and the function template. */
1131 && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1134 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1135 gone through coerce_template_parms by now. */
1137 static void
1138 verify_unstripped_args_1 (tree inner)
1140 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1142 tree arg = TREE_VEC_ELT (inner, i);
1143 if (TREE_CODE (arg) == TEMPLATE_DECL)
1144 /* OK */;
1145 else if (TYPE_P (arg))
1146 gcc_assert (strip_typedefs (arg, NULL) == arg);
1147 else if (ARGUMENT_PACK_P (arg))
1148 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1149 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1150 /* Allow typedefs on the type of a non-type argument, since a
1151 parameter can have them. */;
1152 else
1153 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1157 static void
1158 verify_unstripped_args (tree args)
1160 ++processing_template_decl;
1161 if (!any_dependent_template_arguments_p (args))
1162 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1163 --processing_template_decl;
1166 /* Retrieve the specialization (in the sense of [temp.spec] - a
1167 specialization is either an instantiation or an explicit
1168 specialization) of TMPL for the given template ARGS. If there is
1169 no such specialization, return NULL_TREE. The ARGS are a vector of
1170 arguments, or a vector of vectors of arguments, in the case of
1171 templates with more than one level of parameters.
1173 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1174 then we search for a partial specialization matching ARGS. This
1175 parameter is ignored if TMPL is not a class template.
1177 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1178 result is a NONTYPE_ARGUMENT_PACK. */
1180 static tree
1181 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1183 if (tmpl == NULL_TREE)
1184 return NULL_TREE;
1186 if (args == error_mark_node)
1187 return NULL_TREE;
1189 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1190 || TREE_CODE (tmpl) == FIELD_DECL);
1192 /* There should be as many levels of arguments as there are
1193 levels of parameters. */
1194 gcc_assert (TMPL_ARGS_DEPTH (args)
1195 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1196 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1197 : template_class_depth (DECL_CONTEXT (tmpl))));
1199 if (flag_checking)
1200 verify_unstripped_args (args);
1202 /* Lambda functions in templates aren't instantiated normally, but through
1203 tsubst_lambda_expr. */
1204 if (lambda_fn_in_template_p (tmpl))
1205 return NULL_TREE;
1207 if (optimize_specialization_lookup_p (tmpl))
1209 /* The template arguments actually apply to the containing
1210 class. Find the class specialization with those
1211 arguments. */
1212 tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1213 tree class_specialization
1214 = retrieve_specialization (class_template, args, 0);
1215 if (!class_specialization)
1216 return NULL_TREE;
1218 /* Find the instance of TMPL. */
1219 tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1220 for (ovl_iterator iter (fns); iter; ++iter)
1222 tree fn = *iter;
1223 if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1224 /* using-declarations can add base methods to the method vec,
1225 and we don't want those here. */
1226 && DECL_CONTEXT (fn) == class_specialization)
1227 return fn;
1229 return NULL_TREE;
1231 else
1233 spec_entry *found;
1234 spec_entry elt;
1235 hash_table<spec_hasher> *specializations;
1237 elt.tmpl = tmpl;
1238 elt.args = args;
1239 elt.spec = NULL_TREE;
1241 if (DECL_CLASS_TEMPLATE_P (tmpl))
1242 specializations = type_specializations;
1243 else
1244 specializations = decl_specializations;
1246 if (hash == 0)
1247 hash = spec_hasher::hash (&elt);
1248 found = specializations->find_with_hash (&elt, hash);
1249 if (found)
1250 return found->spec;
1253 return NULL_TREE;
1256 /* Like retrieve_specialization, but for local declarations. */
1258 tree
1259 retrieve_local_specialization (tree tmpl)
1261 if (local_specializations == NULL)
1262 return NULL_TREE;
1264 tree *slot = local_specializations->get (tmpl);
1265 return slot ? *slot : NULL_TREE;
1268 /* Returns nonzero iff DECL is a specialization of TMPL. */
1271 is_specialization_of (tree decl, tree tmpl)
1273 tree t;
1275 if (TREE_CODE (decl) == FUNCTION_DECL)
1277 for (t = decl;
1278 t != NULL_TREE;
1279 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1280 if (t == tmpl)
1281 return 1;
1283 else
1285 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1287 for (t = TREE_TYPE (decl);
1288 t != NULL_TREE;
1289 t = CLASSTYPE_USE_TEMPLATE (t)
1290 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1291 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1292 return 1;
1295 return 0;
1298 /* Returns nonzero iff DECL is a specialization of friend declaration
1299 FRIEND_DECL according to [temp.friend]. */
1301 bool
1302 is_specialization_of_friend (tree decl, tree friend_decl)
1304 bool need_template = true;
1305 int template_depth;
1307 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1308 || TREE_CODE (decl) == TYPE_DECL);
1310 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1311 of a template class, we want to check if DECL is a specialization
1312 if this. */
1313 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1314 && DECL_TEMPLATE_INFO (friend_decl)
1315 && !DECL_USE_TEMPLATE (friend_decl))
1317 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1318 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1319 need_template = false;
1321 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1322 && !PRIMARY_TEMPLATE_P (friend_decl))
1323 need_template = false;
1325 /* There is nothing to do if this is not a template friend. */
1326 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1327 return false;
1329 if (is_specialization_of (decl, friend_decl))
1330 return true;
1332 /* [temp.friend/6]
1333 A member of a class template may be declared to be a friend of a
1334 non-template class. In this case, the corresponding member of
1335 every specialization of the class template is a friend of the
1336 class granting friendship.
1338 For example, given a template friend declaration
1340 template <class T> friend void A<T>::f();
1342 the member function below is considered a friend
1344 template <> struct A<int> {
1345 void f();
1348 For this type of template friend, TEMPLATE_DEPTH below will be
1349 nonzero. To determine if DECL is a friend of FRIEND, we first
1350 check if the enclosing class is a specialization of another. */
1352 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1353 if (template_depth
1354 && DECL_CLASS_SCOPE_P (decl)
1355 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1356 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1358 /* Next, we check the members themselves. In order to handle
1359 a few tricky cases, such as when FRIEND_DECL's are
1361 template <class T> friend void A<T>::g(T t);
1362 template <class T> template <T t> friend void A<T>::h();
1364 and DECL's are
1366 void A<int>::g(int);
1367 template <int> void A<int>::h();
1369 we need to figure out ARGS, the template arguments from
1370 the context of DECL. This is required for template substitution
1371 of `T' in the function parameter of `g' and template parameter
1372 of `h' in the above examples. Here ARGS corresponds to `int'. */
1374 tree context = DECL_CONTEXT (decl);
1375 tree args = NULL_TREE;
1376 int current_depth = 0;
1378 while (current_depth < template_depth)
1380 if (CLASSTYPE_TEMPLATE_INFO (context))
1382 if (current_depth == 0)
1383 args = TYPE_TI_ARGS (context);
1384 else
1385 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1386 current_depth++;
1388 context = TYPE_CONTEXT (context);
1391 if (TREE_CODE (decl) == FUNCTION_DECL)
1393 bool is_template;
1394 tree friend_type;
1395 tree decl_type;
1396 tree friend_args_type;
1397 tree decl_args_type;
1399 /* Make sure that both DECL and FRIEND_DECL are templates or
1400 non-templates. */
1401 is_template = DECL_TEMPLATE_INFO (decl)
1402 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1403 if (need_template ^ is_template)
1404 return false;
1405 else if (is_template)
1407 /* If both are templates, check template parameter list. */
1408 tree friend_parms
1409 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1410 args, tf_none);
1411 if (!comp_template_parms
1412 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1413 friend_parms))
1414 return false;
1416 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1418 else
1419 decl_type = TREE_TYPE (decl);
1421 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1422 tf_none, NULL_TREE);
1423 if (friend_type == error_mark_node)
1424 return false;
1426 /* Check if return types match. */
1427 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1428 return false;
1430 /* Check if function parameter types match, ignoring the
1431 `this' parameter. */
1432 friend_args_type = TYPE_ARG_TYPES (friend_type);
1433 decl_args_type = TYPE_ARG_TYPES (decl_type);
1434 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1435 friend_args_type = TREE_CHAIN (friend_args_type);
1436 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1437 decl_args_type = TREE_CHAIN (decl_args_type);
1439 return compparms (decl_args_type, friend_args_type);
1441 else
1443 /* DECL is a TYPE_DECL */
1444 bool is_template;
1445 tree decl_type = TREE_TYPE (decl);
1447 /* Make sure that both DECL and FRIEND_DECL are templates or
1448 non-templates. */
1449 is_template
1450 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1451 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1453 if (need_template ^ is_template)
1454 return false;
1455 else if (is_template)
1457 tree friend_parms;
1458 /* If both are templates, check the name of the two
1459 TEMPLATE_DECL's first because is_friend didn't. */
1460 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1461 != DECL_NAME (friend_decl))
1462 return false;
1464 /* Now check template parameter list. */
1465 friend_parms
1466 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1467 args, tf_none);
1468 return comp_template_parms
1469 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1470 friend_parms);
1472 else
1473 return (DECL_NAME (decl)
1474 == DECL_NAME (friend_decl));
1477 return false;
1480 /* Register the specialization SPEC as a specialization of TMPL with
1481 the indicated ARGS. IS_FRIEND indicates whether the specialization
1482 is actually just a friend declaration. ATTRLIST is the list of
1483 attributes that the specialization is declared with or NULL when
1484 it isn't. Returns SPEC, or an equivalent prior declaration, if
1485 available.
1487 We also store instantiations of field packs in the hash table, even
1488 though they are not themselves templates, to make lookup easier. */
1490 static tree
1491 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1492 hashval_t hash)
1494 tree fn;
1495 spec_entry **slot = NULL;
1496 spec_entry elt;
1498 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1499 || (TREE_CODE (tmpl) == FIELD_DECL
1500 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1502 if (TREE_CODE (spec) == FUNCTION_DECL
1503 && uses_template_parms (DECL_TI_ARGS (spec)))
1504 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1505 register it; we want the corresponding TEMPLATE_DECL instead.
1506 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1507 the more obvious `uses_template_parms (spec)' to avoid problems
1508 with default function arguments. In particular, given
1509 something like this:
1511 template <class T> void f(T t1, T t = T())
1513 the default argument expression is not substituted for in an
1514 instantiation unless and until it is actually needed. */
1515 return spec;
1517 if (optimize_specialization_lookup_p (tmpl))
1518 /* We don't put these specializations in the hash table, but we might
1519 want to give an error about a mismatch. */
1520 fn = retrieve_specialization (tmpl, args, 0);
1521 else
1523 elt.tmpl = tmpl;
1524 elt.args = args;
1525 elt.spec = spec;
1527 if (hash == 0)
1528 hash = spec_hasher::hash (&elt);
1530 slot =
1531 decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1532 if (*slot)
1533 fn = ((spec_entry *) *slot)->spec;
1534 else
1535 fn = NULL_TREE;
1538 /* We can sometimes try to re-register a specialization that we've
1539 already got. In particular, regenerate_decl_from_template calls
1540 duplicate_decls which will update the specialization list. But,
1541 we'll still get called again here anyhow. It's more convenient
1542 to simply allow this than to try to prevent it. */
1543 if (fn == spec)
1544 return spec;
1545 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1547 if (DECL_TEMPLATE_INSTANTIATION (fn))
1549 if (DECL_ODR_USED (fn)
1550 || DECL_EXPLICIT_INSTANTIATION (fn))
1552 error ("specialization of %qD after instantiation",
1553 fn);
1554 return error_mark_node;
1556 else
1558 tree clone;
1559 /* This situation should occur only if the first
1560 specialization is an implicit instantiation, the
1561 second is an explicit specialization, and the
1562 implicit instantiation has not yet been used. That
1563 situation can occur if we have implicitly
1564 instantiated a member function and then specialized
1565 it later.
1567 We can also wind up here if a friend declaration that
1568 looked like an instantiation turns out to be a
1569 specialization:
1571 template <class T> void foo(T);
1572 class S { friend void foo<>(int) };
1573 template <> void foo(int);
1575 We transform the existing DECL in place so that any
1576 pointers to it become pointers to the updated
1577 declaration.
1579 If there was a definition for the template, but not
1580 for the specialization, we want this to look as if
1581 there were no definition, and vice versa. */
1582 DECL_INITIAL (fn) = NULL_TREE;
1583 duplicate_decls (spec, fn, is_friend);
1584 /* The call to duplicate_decls will have applied
1585 [temp.expl.spec]:
1587 An explicit specialization of a function template
1588 is inline only if it is explicitly declared to be,
1589 and independently of whether its function template
1592 to the primary function; now copy the inline bits to
1593 the various clones. */
1594 FOR_EACH_CLONE (clone, fn)
1596 DECL_DECLARED_INLINE_P (clone)
1597 = DECL_DECLARED_INLINE_P (fn);
1598 DECL_SOURCE_LOCATION (clone)
1599 = DECL_SOURCE_LOCATION (fn);
1600 DECL_DELETED_FN (clone)
1601 = DECL_DELETED_FN (fn);
1603 check_specialization_namespace (tmpl);
1605 return fn;
1608 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1610 tree dd = duplicate_decls (spec, fn, is_friend);
1611 if (dd == error_mark_node)
1612 /* We've already complained in duplicate_decls. */
1613 return error_mark_node;
1615 if (dd == NULL_TREE && DECL_INITIAL (spec))
1616 /* Dup decl failed, but this is a new definition. Set the
1617 line number so any errors match this new
1618 definition. */
1619 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1621 return fn;
1624 else if (fn)
1625 return duplicate_decls (spec, fn, is_friend);
1627 /* A specialization must be declared in the same namespace as the
1628 template it is specializing. */
1629 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1630 && !check_specialization_namespace (tmpl))
1631 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1633 if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1635 spec_entry *entry = ggc_alloc<spec_entry> ();
1636 gcc_assert (tmpl && args && spec);
1637 *entry = elt;
1638 *slot = entry;
1639 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1640 && PRIMARY_TEMPLATE_P (tmpl)
1641 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1642 || variable_template_p (tmpl))
1643 /* If TMPL is a forward declaration of a template function, keep a list
1644 of all specializations in case we need to reassign them to a friend
1645 template later in tsubst_friend_function.
1647 Also keep a list of all variable template instantiations so that
1648 process_partial_specialization can check whether a later partial
1649 specialization would have used it. */
1650 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1651 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1654 return spec;
1657 /* Returns true iff two spec_entry nodes are equivalent. */
1659 int comparing_specializations;
1661 bool
1662 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1664 int equal;
1666 ++comparing_specializations;
1667 equal = (e1->tmpl == e2->tmpl
1668 && comp_template_args (e1->args, e2->args));
1669 if (equal && flag_concepts
1670 /* tmpl could be a FIELD_DECL for a capture pack. */
1671 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1672 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1673 && uses_template_parms (e1->args))
1675 /* Partial specializations of a variable template can be distinguished by
1676 constraints. */
1677 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1678 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1679 equal = equivalent_constraints (c1, c2);
1681 --comparing_specializations;
1683 return equal;
1686 /* Returns a hash for a template TMPL and template arguments ARGS. */
1688 static hashval_t
1689 hash_tmpl_and_args (tree tmpl, tree args)
1691 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1692 return iterative_hash_template_arg (args, val);
1695 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1696 ignoring SPEC. */
1698 hashval_t
1699 spec_hasher::hash (spec_entry *e)
1701 return hash_tmpl_and_args (e->tmpl, e->args);
1704 /* Recursively calculate a hash value for a template argument ARG, for use
1705 in the hash tables of template specializations. */
1707 hashval_t
1708 iterative_hash_template_arg (tree arg, hashval_t val)
1710 unsigned HOST_WIDE_INT i;
1711 enum tree_code code;
1712 char tclass;
1714 if (arg == NULL_TREE)
1715 return iterative_hash_object (arg, val);
1717 if (!TYPE_P (arg))
1718 STRIP_NOPS (arg);
1720 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1721 gcc_unreachable ();
1723 code = TREE_CODE (arg);
1724 tclass = TREE_CODE_CLASS (code);
1726 val = iterative_hash_object (code, val);
1728 switch (code)
1730 case ERROR_MARK:
1731 return val;
1733 case IDENTIFIER_NODE:
1734 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1736 case TREE_VEC:
1738 int i, len = TREE_VEC_LENGTH (arg);
1739 for (i = 0; i < len; ++i)
1740 val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1741 return val;
1744 case TYPE_PACK_EXPANSION:
1745 case EXPR_PACK_EXPANSION:
1746 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1747 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1749 case TYPE_ARGUMENT_PACK:
1750 case NONTYPE_ARGUMENT_PACK:
1751 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1753 case TREE_LIST:
1754 for (; arg; arg = TREE_CHAIN (arg))
1755 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1756 return val;
1758 case OVERLOAD:
1759 for (lkp_iterator iter (arg); iter; ++iter)
1760 val = iterative_hash_template_arg (*iter, val);
1761 return val;
1763 case CONSTRUCTOR:
1765 tree field, value;
1766 iterative_hash_template_arg (TREE_TYPE (arg), val);
1767 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1769 val = iterative_hash_template_arg (field, val);
1770 val = iterative_hash_template_arg (value, val);
1772 return val;
1775 case PARM_DECL:
1776 if (!DECL_ARTIFICIAL (arg))
1778 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1779 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1781 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1783 case TARGET_EXPR:
1784 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1786 case PTRMEM_CST:
1787 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1788 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1790 case TEMPLATE_PARM_INDEX:
1791 val = iterative_hash_template_arg
1792 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1793 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1794 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1796 case TRAIT_EXPR:
1797 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1798 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1799 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1801 case BASELINK:
1802 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1803 val);
1804 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1805 val);
1807 case MODOP_EXPR:
1808 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1809 code = TREE_CODE (TREE_OPERAND (arg, 1));
1810 val = iterative_hash_object (code, val);
1811 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1813 case LAMBDA_EXPR:
1814 /* A lambda can't appear in a template arg, but don't crash on
1815 erroneous input. */
1816 gcc_assert (seen_error ());
1817 return val;
1819 case CAST_EXPR:
1820 case IMPLICIT_CONV_EXPR:
1821 case STATIC_CAST_EXPR:
1822 case REINTERPRET_CAST_EXPR:
1823 case CONST_CAST_EXPR:
1824 case DYNAMIC_CAST_EXPR:
1825 case NEW_EXPR:
1826 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1827 /* Now hash operands as usual. */
1828 break;
1830 default:
1831 break;
1834 switch (tclass)
1836 case tcc_type:
1837 if (alias_template_specialization_p (arg))
1839 // We want an alias specialization that survived strip_typedefs
1840 // to hash differently from its TYPE_CANONICAL, to avoid hash
1841 // collisions that compare as different in template_args_equal.
1842 // These could be dependent specializations that strip_typedefs
1843 // left alone, or untouched specializations because
1844 // coerce_template_parms returns the unconverted template
1845 // arguments if it sees incomplete argument packs.
1846 tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1847 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1849 if (TYPE_CANONICAL (arg))
1850 return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1851 val);
1852 else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1853 return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1854 /* Otherwise just compare the types during lookup. */
1855 return val;
1857 case tcc_declaration:
1858 case tcc_constant:
1859 return iterative_hash_expr (arg, val);
1861 default:
1862 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1864 unsigned n = cp_tree_operand_length (arg);
1865 for (i = 0; i < n; ++i)
1866 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1867 return val;
1870 gcc_unreachable ();
1871 return 0;
1874 /* Unregister the specialization SPEC as a specialization of TMPL.
1875 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1876 if the SPEC was listed as a specialization of TMPL.
1878 Note that SPEC has been ggc_freed, so we can't look inside it. */
1880 bool
1881 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1883 spec_entry *entry;
1884 spec_entry elt;
1886 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1887 elt.args = TI_ARGS (tinfo);
1888 elt.spec = NULL_TREE;
1890 entry = decl_specializations->find (&elt);
1891 if (entry != NULL)
1893 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1894 gcc_assert (new_spec != NULL_TREE);
1895 entry->spec = new_spec;
1896 return 1;
1899 return 0;
1902 /* Like register_specialization, but for local declarations. We are
1903 registering SPEC, an instantiation of TMPL. */
1905 void
1906 register_local_specialization (tree spec, tree tmpl)
1908 gcc_assert (tmpl != spec);
1909 local_specializations->put (tmpl, spec);
1912 /* TYPE is a class type. Returns true if TYPE is an explicitly
1913 specialized class. */
1915 bool
1916 explicit_class_specialization_p (tree type)
1918 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1919 return false;
1920 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1923 /* Print the list of functions at FNS, going through all the overloads
1924 for each element of the list. Alternatively, FNS can not be a
1925 TREE_LIST, in which case it will be printed together with all the
1926 overloads.
1928 MORE and *STR should respectively be FALSE and NULL when the function
1929 is called from the outside. They are used internally on recursive
1930 calls. print_candidates manages the two parameters and leaves NULL
1931 in *STR when it ends. */
1933 static void
1934 print_candidates_1 (tree fns, char **str, bool more = false)
1936 if (TREE_CODE (fns) == TREE_LIST)
1937 for (; fns; fns = TREE_CHAIN (fns))
1938 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1939 else
1940 for (lkp_iterator iter (fns); iter;)
1942 tree cand = *iter;
1943 ++iter;
1945 const char *pfx = *str;
1946 if (!pfx)
1948 if (more || iter)
1949 pfx = _("candidates are:");
1950 else
1951 pfx = _("candidate is:");
1952 *str = get_spaces (pfx);
1954 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
1958 /* Print the list of candidate FNS in an error message. FNS can also
1959 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
1961 void
1962 print_candidates (tree fns)
1964 char *str = NULL;
1965 print_candidates_1 (fns, &str);
1966 free (str);
1969 /* Get a (possibly) constrained template declaration for the
1970 purpose of ordering candidates. */
1971 static tree
1972 get_template_for_ordering (tree list)
1974 gcc_assert (TREE_CODE (list) == TREE_LIST);
1975 tree f = TREE_VALUE (list);
1976 if (tree ti = DECL_TEMPLATE_INFO (f))
1977 return TI_TEMPLATE (ti);
1978 return f;
1981 /* Among candidates having the same signature, return the
1982 most constrained or NULL_TREE if there is no best candidate.
1983 If the signatures of candidates vary (e.g., template
1984 specialization vs. member function), then there can be no
1985 most constrained.
1987 Note that we don't compare constraints on the functions
1988 themselves, but rather those of their templates. */
1989 static tree
1990 most_constrained_function (tree candidates)
1992 // Try to find the best candidate in a first pass.
1993 tree champ = candidates;
1994 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
1996 int winner = more_constrained (get_template_for_ordering (champ),
1997 get_template_for_ordering (c));
1998 if (winner == -1)
1999 champ = c; // The candidate is more constrained
2000 else if (winner == 0)
2001 return NULL_TREE; // Neither is more constrained
2004 // Verify that the champ is better than previous candidates.
2005 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2006 if (!more_constrained (get_template_for_ordering (champ),
2007 get_template_for_ordering (c)))
2008 return NULL_TREE;
2011 return champ;
2015 /* Returns the template (one of the functions given by TEMPLATE_ID)
2016 which can be specialized to match the indicated DECL with the
2017 explicit template args given in TEMPLATE_ID. The DECL may be
2018 NULL_TREE if none is available. In that case, the functions in
2019 TEMPLATE_ID are non-members.
2021 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2022 specialization of a member template.
2024 The TEMPLATE_COUNT is the number of references to qualifying
2025 template classes that appeared in the name of the function. See
2026 check_explicit_specialization for a more accurate description.
2028 TSK indicates what kind of template declaration (if any) is being
2029 declared. TSK_TEMPLATE indicates that the declaration given by
2030 DECL, though a FUNCTION_DECL, has template parameters, and is
2031 therefore a template function.
2033 The template args (those explicitly specified and those deduced)
2034 are output in a newly created vector *TARGS_OUT.
2036 If it is impossible to determine the result, an error message is
2037 issued. The error_mark_node is returned to indicate failure. */
2039 static tree
2040 determine_specialization (tree template_id,
2041 tree decl,
2042 tree* targs_out,
2043 int need_member_template,
2044 int template_count,
2045 tmpl_spec_kind tsk)
2047 tree fns;
2048 tree targs;
2049 tree explicit_targs;
2050 tree candidates = NULL_TREE;
2052 /* A TREE_LIST of templates of which DECL may be a specialization.
2053 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2054 corresponding TREE_PURPOSE is the set of template arguments that,
2055 when used to instantiate the template, would produce a function
2056 with the signature of DECL. */
2057 tree templates = NULL_TREE;
2058 int header_count;
2059 cp_binding_level *b;
2061 *targs_out = NULL_TREE;
2063 if (template_id == error_mark_node || decl == error_mark_node)
2064 return error_mark_node;
2066 /* We shouldn't be specializing a member template of an
2067 unspecialized class template; we already gave an error in
2068 check_specialization_scope, now avoid crashing. */
2069 if (!VAR_P (decl)
2070 && template_count && DECL_CLASS_SCOPE_P (decl)
2071 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2073 gcc_assert (errorcount);
2074 return error_mark_node;
2077 fns = TREE_OPERAND (template_id, 0);
2078 explicit_targs = TREE_OPERAND (template_id, 1);
2080 if (fns == error_mark_node)
2081 return error_mark_node;
2083 /* Check for baselinks. */
2084 if (BASELINK_P (fns))
2085 fns = BASELINK_FUNCTIONS (fns);
2087 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2089 error ("%qD is not a function template", fns);
2090 return error_mark_node;
2092 else if (VAR_P (decl) && !variable_template_p (fns))
2094 error ("%qD is not a variable template", fns);
2095 return error_mark_node;
2098 /* Count the number of template headers specified for this
2099 specialization. */
2100 header_count = 0;
2101 for (b = current_binding_level;
2102 b->kind == sk_template_parms;
2103 b = b->level_chain)
2104 ++header_count;
2106 tree orig_fns = fns;
2108 if (variable_template_p (fns))
2110 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2111 targs = coerce_template_parms (parms, explicit_targs, fns,
2112 tf_warning_or_error,
2113 /*req_all*/true, /*use_defarg*/true);
2114 if (targs != error_mark_node)
2115 templates = tree_cons (targs, fns, templates);
2117 else for (lkp_iterator iter (fns); iter; ++iter)
2119 tree fn = *iter;
2121 if (TREE_CODE (fn) == TEMPLATE_DECL)
2123 tree decl_arg_types;
2124 tree fn_arg_types;
2125 tree insttype;
2127 /* In case of explicit specialization, we need to check if
2128 the number of template headers appearing in the specialization
2129 is correct. This is usually done in check_explicit_specialization,
2130 but the check done there cannot be exhaustive when specializing
2131 member functions. Consider the following code:
2133 template <> void A<int>::f(int);
2134 template <> template <> void A<int>::f(int);
2136 Assuming that A<int> is not itself an explicit specialization
2137 already, the first line specializes "f" which is a non-template
2138 member function, whilst the second line specializes "f" which
2139 is a template member function. So both lines are syntactically
2140 correct, and check_explicit_specialization does not reject
2141 them.
2143 Here, we can do better, as we are matching the specialization
2144 against the declarations. We count the number of template
2145 headers, and we check if they match TEMPLATE_COUNT + 1
2146 (TEMPLATE_COUNT is the number of qualifying template classes,
2147 plus there must be another header for the member template
2148 itself).
2150 Notice that if header_count is zero, this is not a
2151 specialization but rather a template instantiation, so there
2152 is no check we can perform here. */
2153 if (header_count && header_count != template_count + 1)
2154 continue;
2156 /* Check that the number of template arguments at the
2157 innermost level for DECL is the same as for FN. */
2158 if (current_binding_level->kind == sk_template_parms
2159 && !current_binding_level->explicit_spec_p
2160 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2161 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2162 (current_template_parms))))
2163 continue;
2165 /* DECL might be a specialization of FN. */
2166 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2167 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2169 /* For a non-static member function, we need to make sure
2170 that the const qualification is the same. Since
2171 get_bindings does not try to merge the "this" parameter,
2172 we must do the comparison explicitly. */
2173 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2175 if (!same_type_p (TREE_VALUE (fn_arg_types),
2176 TREE_VALUE (decl_arg_types)))
2177 continue;
2179 /* And the ref-qualification. */
2180 if (type_memfn_rqual (TREE_TYPE (decl))
2181 != type_memfn_rqual (TREE_TYPE (fn)))
2182 continue;
2185 /* Skip the "this" parameter and, for constructors of
2186 classes with virtual bases, the VTT parameter. A
2187 full specialization of a constructor will have a VTT
2188 parameter, but a template never will. */
2189 decl_arg_types
2190 = skip_artificial_parms_for (decl, decl_arg_types);
2191 fn_arg_types
2192 = skip_artificial_parms_for (fn, fn_arg_types);
2194 /* Function templates cannot be specializations; there are
2195 no partial specializations of functions. Therefore, if
2196 the type of DECL does not match FN, there is no
2197 match.
2199 Note that it should never be the case that we have both
2200 candidates added here, and for regular member functions
2201 below. */
2202 if (tsk == tsk_template)
2204 if (compparms (fn_arg_types, decl_arg_types))
2205 candidates = tree_cons (NULL_TREE, fn, candidates);
2206 continue;
2209 /* See whether this function might be a specialization of this
2210 template. Suppress access control because we might be trying
2211 to make this specialization a friend, and we have already done
2212 access control for the declaration of the specialization. */
2213 push_deferring_access_checks (dk_no_check);
2214 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2215 pop_deferring_access_checks ();
2217 if (!targs)
2218 /* We cannot deduce template arguments that when used to
2219 specialize TMPL will produce DECL. */
2220 continue;
2222 if (uses_template_parms (targs))
2223 /* We deduced something involving 'auto', which isn't a valid
2224 template argument. */
2225 continue;
2227 /* Remove, from the set of candidates, all those functions
2228 whose constraints are not satisfied. */
2229 if (flag_concepts && !constraints_satisfied_p (fn, targs))
2230 continue;
2232 // Then, try to form the new function type.
2233 insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2234 if (insttype == error_mark_node)
2235 continue;
2236 fn_arg_types
2237 = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2238 if (!compparms (fn_arg_types, decl_arg_types))
2239 continue;
2241 /* Save this template, and the arguments deduced. */
2242 templates = tree_cons (targs, fn, templates);
2244 else if (need_member_template)
2245 /* FN is an ordinary member function, and we need a
2246 specialization of a member template. */
2248 else if (TREE_CODE (fn) != FUNCTION_DECL)
2249 /* We can get IDENTIFIER_NODEs here in certain erroneous
2250 cases. */
2252 else if (!DECL_FUNCTION_MEMBER_P (fn))
2253 /* This is just an ordinary non-member function. Nothing can
2254 be a specialization of that. */
2256 else if (DECL_ARTIFICIAL (fn))
2257 /* Cannot specialize functions that are created implicitly. */
2259 else
2261 tree decl_arg_types;
2263 /* This is an ordinary member function. However, since
2264 we're here, we can assume its enclosing class is a
2265 template class. For example,
2267 template <typename T> struct S { void f(); };
2268 template <> void S<int>::f() {}
2270 Here, S<int>::f is a non-template, but S<int> is a
2271 template class. If FN has the same type as DECL, we
2272 might be in business. */
2274 if (!DECL_TEMPLATE_INFO (fn))
2275 /* Its enclosing class is an explicit specialization
2276 of a template class. This is not a candidate. */
2277 continue;
2279 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2280 TREE_TYPE (TREE_TYPE (fn))))
2281 /* The return types differ. */
2282 continue;
2284 /* Adjust the type of DECL in case FN is a static member. */
2285 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2286 if (DECL_STATIC_FUNCTION_P (fn)
2287 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2288 decl_arg_types = TREE_CHAIN (decl_arg_types);
2290 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2291 decl_arg_types))
2292 continue;
2294 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2295 && (type_memfn_rqual (TREE_TYPE (decl))
2296 != type_memfn_rqual (TREE_TYPE (fn))))
2297 continue;
2299 // If the deduced arguments do not satisfy the constraints,
2300 // this is not a candidate.
2301 if (flag_concepts && !constraints_satisfied_p (fn))
2302 continue;
2304 // Add the candidate.
2305 candidates = tree_cons (NULL_TREE, fn, candidates);
2309 if (templates && TREE_CHAIN (templates))
2311 /* We have:
2313 [temp.expl.spec]
2315 It is possible for a specialization with a given function
2316 signature to be instantiated from more than one function
2317 template. In such cases, explicit specification of the
2318 template arguments must be used to uniquely identify the
2319 function template specialization being specialized.
2321 Note that here, there's no suggestion that we're supposed to
2322 determine which of the candidate templates is most
2323 specialized. However, we, also have:
2325 [temp.func.order]
2327 Partial ordering of overloaded function template
2328 declarations is used in the following contexts to select
2329 the function template to which a function template
2330 specialization refers:
2332 -- when an explicit specialization refers to a function
2333 template.
2335 So, we do use the partial ordering rules, at least for now.
2336 This extension can only serve to make invalid programs valid,
2337 so it's safe. And, there is strong anecdotal evidence that
2338 the committee intended the partial ordering rules to apply;
2339 the EDG front end has that behavior, and John Spicer claims
2340 that the committee simply forgot to delete the wording in
2341 [temp.expl.spec]. */
2342 tree tmpl = most_specialized_instantiation (templates);
2343 if (tmpl != error_mark_node)
2345 templates = tmpl;
2346 TREE_CHAIN (templates) = NULL_TREE;
2350 // Concepts allows multiple declarations of member functions
2351 // with the same signature. Like above, we need to rely on
2352 // on the partial ordering of those candidates to determine which
2353 // is the best.
2354 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2356 if (tree cand = most_constrained_function (candidates))
2358 candidates = cand;
2359 TREE_CHAIN (cand) = NULL_TREE;
2363 if (templates == NULL_TREE && candidates == NULL_TREE)
2365 error ("template-id %qD for %q+D does not match any template "
2366 "declaration", template_id, decl);
2367 if (header_count && header_count != template_count + 1)
2368 inform (input_location, "saw %d %<template<>%>, need %d for "
2369 "specializing a member function template",
2370 header_count, template_count + 1);
2371 else
2372 print_candidates (orig_fns);
2373 return error_mark_node;
2375 else if ((templates && TREE_CHAIN (templates))
2376 || (candidates && TREE_CHAIN (candidates))
2377 || (templates && candidates))
2379 error ("ambiguous template specialization %qD for %q+D",
2380 template_id, decl);
2381 candidates = chainon (candidates, templates);
2382 print_candidates (candidates);
2383 return error_mark_node;
2386 /* We have one, and exactly one, match. */
2387 if (candidates)
2389 tree fn = TREE_VALUE (candidates);
2390 *targs_out = copy_node (DECL_TI_ARGS (fn));
2392 // Propagate the candidate's constraints to the declaration.
2393 set_constraints (decl, get_constraints (fn));
2395 /* DECL is a re-declaration or partial instantiation of a template
2396 function. */
2397 if (TREE_CODE (fn) == TEMPLATE_DECL)
2398 return fn;
2399 /* It was a specialization of an ordinary member function in a
2400 template class. */
2401 return DECL_TI_TEMPLATE (fn);
2404 /* It was a specialization of a template. */
2405 targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2406 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2408 *targs_out = copy_node (targs);
2409 SET_TMPL_ARGS_LEVEL (*targs_out,
2410 TMPL_ARGS_DEPTH (*targs_out),
2411 TREE_PURPOSE (templates));
2413 else
2414 *targs_out = TREE_PURPOSE (templates);
2415 return TREE_VALUE (templates);
2418 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2419 but with the default argument values filled in from those in the
2420 TMPL_TYPES. */
2422 static tree
2423 copy_default_args_to_explicit_spec_1 (tree spec_types,
2424 tree tmpl_types)
2426 tree new_spec_types;
2428 if (!spec_types)
2429 return NULL_TREE;
2431 if (spec_types == void_list_node)
2432 return void_list_node;
2434 /* Substitute into the rest of the list. */
2435 new_spec_types =
2436 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2437 TREE_CHAIN (tmpl_types));
2439 /* Add the default argument for this parameter. */
2440 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2441 TREE_VALUE (spec_types),
2442 new_spec_types);
2445 /* DECL is an explicit specialization. Replicate default arguments
2446 from the template it specializes. (That way, code like:
2448 template <class T> void f(T = 3);
2449 template <> void f(double);
2450 void g () { f (); }
2452 works, as required.) An alternative approach would be to look up
2453 the correct default arguments at the call-site, but this approach
2454 is consistent with how implicit instantiations are handled. */
2456 static void
2457 copy_default_args_to_explicit_spec (tree decl)
2459 tree tmpl;
2460 tree spec_types;
2461 tree tmpl_types;
2462 tree new_spec_types;
2463 tree old_type;
2464 tree new_type;
2465 tree t;
2466 tree object_type = NULL_TREE;
2467 tree in_charge = NULL_TREE;
2468 tree vtt = NULL_TREE;
2470 /* See if there's anything we need to do. */
2471 tmpl = DECL_TI_TEMPLATE (decl);
2472 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2473 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2474 if (TREE_PURPOSE (t))
2475 break;
2476 if (!t)
2477 return;
2479 old_type = TREE_TYPE (decl);
2480 spec_types = TYPE_ARG_TYPES (old_type);
2482 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2484 /* Remove the this pointer, but remember the object's type for
2485 CV quals. */
2486 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2487 spec_types = TREE_CHAIN (spec_types);
2488 tmpl_types = TREE_CHAIN (tmpl_types);
2490 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2492 /* DECL may contain more parameters than TMPL due to the extra
2493 in-charge parameter in constructors and destructors. */
2494 in_charge = spec_types;
2495 spec_types = TREE_CHAIN (spec_types);
2497 if (DECL_HAS_VTT_PARM_P (decl))
2499 vtt = spec_types;
2500 spec_types = TREE_CHAIN (spec_types);
2504 /* Compute the merged default arguments. */
2505 new_spec_types =
2506 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2508 /* Compute the new FUNCTION_TYPE. */
2509 if (object_type)
2511 if (vtt)
2512 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2513 TREE_VALUE (vtt),
2514 new_spec_types);
2516 if (in_charge)
2517 /* Put the in-charge parameter back. */
2518 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2519 TREE_VALUE (in_charge),
2520 new_spec_types);
2522 new_type = build_method_type_directly (object_type,
2523 TREE_TYPE (old_type),
2524 new_spec_types);
2526 else
2527 new_type = build_function_type (TREE_TYPE (old_type),
2528 new_spec_types);
2529 new_type = cp_build_type_attribute_variant (new_type,
2530 TYPE_ATTRIBUTES (old_type));
2531 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2533 TREE_TYPE (decl) = new_type;
2536 /* Return the number of template headers we expect to see for a definition
2537 or specialization of CTYPE or one of its non-template members. */
2540 num_template_headers_for_class (tree ctype)
2542 int num_templates = 0;
2544 while (ctype && CLASS_TYPE_P (ctype))
2546 /* You're supposed to have one `template <...>' for every
2547 template class, but you don't need one for a full
2548 specialization. For example:
2550 template <class T> struct S{};
2551 template <> struct S<int> { void f(); };
2552 void S<int>::f () {}
2554 is correct; there shouldn't be a `template <>' for the
2555 definition of `S<int>::f'. */
2556 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2557 /* If CTYPE does not have template information of any
2558 kind, then it is not a template, nor is it nested
2559 within a template. */
2560 break;
2561 if (explicit_class_specialization_p (ctype))
2562 break;
2563 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2564 ++num_templates;
2566 ctype = TYPE_CONTEXT (ctype);
2569 return num_templates;
2572 /* Do a simple sanity check on the template headers that precede the
2573 variable declaration DECL. */
2575 void
2576 check_template_variable (tree decl)
2578 tree ctx = CP_DECL_CONTEXT (decl);
2579 int wanted = num_template_headers_for_class (ctx);
2580 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2581 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2583 if (cxx_dialect < cxx14)
2584 pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2585 "variable templates only available with "
2586 "-std=c++14 or -std=gnu++14");
2588 // Namespace-scope variable templates should have a template header.
2589 ++wanted;
2591 if (template_header_count > wanted)
2593 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2594 "too many template headers for %qD "
2595 "(should be %d)",
2596 decl, wanted);
2597 if (warned && CLASS_TYPE_P (ctx)
2598 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2599 inform (DECL_SOURCE_LOCATION (decl),
2600 "members of an explicitly specialized class are defined "
2601 "without a template header");
2605 /* An explicit specialization whose declarator-id or class-head-name is not
2606 qualified shall be declared in the nearest enclosing namespace of the
2607 template, or, if the namespace is inline (7.3.1), any namespace from its
2608 enclosing namespace set.
2610 If the name declared in the explicit instantiation is an unqualified name,
2611 the explicit instantiation shall appear in the namespace where its template
2612 is declared or, if that namespace is inline (7.3.1), any namespace from its
2613 enclosing namespace set. */
2615 void
2616 check_unqualified_spec_or_inst (tree t, location_t loc)
2618 tree tmpl = most_general_template (t);
2619 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2620 && !is_nested_namespace (current_namespace,
2621 CP_DECL_CONTEXT (tmpl), true))
2623 if (processing_specialization)
2624 permerror (loc, "explicit specialization of %qD outside its "
2625 "namespace must use a nested-name-specifier", tmpl);
2626 else if (processing_explicit_instantiation
2627 && cxx_dialect >= cxx11)
2628 /* This was allowed in C++98, so only pedwarn. */
2629 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2630 "outside its namespace must use a nested-name-"
2631 "specifier", tmpl);
2635 /* Warn for a template specialization SPEC that is missing some of a set
2636 of function or type attributes that the template TEMPL is declared with.
2637 ATTRLIST is a list of additional attributes that SPEC should be taken
2638 to ultimately be declared with. */
2640 static void
2641 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2643 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2644 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2646 if (TREE_CODE (tmpl) != FUNCTION_DECL)
2647 return;
2649 /* Avoid warning if either declaration or its type is deprecated. */
2650 if (TREE_DEPRECATED (tmpl)
2651 || TREE_DEPRECATED (spec))
2652 return;
2654 tree tmpl_type = TREE_TYPE (tmpl);
2655 tree spec_type = TREE_TYPE (spec);
2657 if (TREE_DEPRECATED (tmpl_type)
2658 || TREE_DEPRECATED (spec_type)
2659 || TREE_DEPRECATED (TREE_TYPE (tmpl_type))
2660 || TREE_DEPRECATED (TREE_TYPE (spec_type)))
2661 return;
2663 tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpl_type) };
2664 tree spec_attrs[] = { DECL_ATTRIBUTES (spec), TYPE_ATTRIBUTES (spec_type) };
2666 if (!spec_attrs[0])
2667 spec_attrs[0] = attrlist;
2668 else if (!spec_attrs[1])
2669 spec_attrs[1] = attrlist;
2671 /* Avoid warning if the primary has no attributes. */
2672 if (!tmpl_attrs[0] && !tmpl_attrs[1])
2673 return;
2675 /* Avoid warning if either declaration contains an attribute on
2676 the white list below. */
2677 const char* const whitelist[] = {
2678 "error", "warning"
2681 for (unsigned i = 0; i != 2; ++i)
2682 for (unsigned j = 0; j != sizeof whitelist / sizeof *whitelist; ++j)
2683 if (lookup_attribute (whitelist[j], tmpl_attrs[i])
2684 || lookup_attribute (whitelist[j], spec_attrs[i]))
2685 return;
2687 /* Avoid warning if the difference between the primary and
2688 the specialization is not in one of the attributes below. */
2689 const char* const blacklist[] = {
2690 "alloc_align", "alloc_size", "assume_aligned", "format",
2691 "format_arg", "malloc", "nonnull"
2694 /* Put together a list of the black listed attributes that the primary
2695 template is declared with that the specialization is not, in case
2696 it's not apparent from the most recent declaration of the primary. */
2697 unsigned nattrs = 0;
2698 pretty_printer str;
2700 for (unsigned i = 0; i != sizeof blacklist / sizeof *blacklist; ++i)
2702 for (unsigned j = 0; j != 2; ++j)
2704 if (!lookup_attribute (blacklist[i], tmpl_attrs[j]))
2705 continue;
2707 for (unsigned k = 0; k != 1 + !!spec_attrs[1]; ++k)
2709 if (lookup_attribute (blacklist[i], spec_attrs[k]))
2710 break;
2712 if (nattrs)
2713 pp_string (&str, ", ");
2714 pp_begin_quote (&str, pp_show_color (global_dc->printer));
2715 pp_string (&str, blacklist[i]);
2716 pp_end_quote (&str, pp_show_color (global_dc->printer));
2717 ++nattrs;
2722 if (!nattrs)
2723 return;
2725 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2726 "explicit specialization %q#D may be missing attributes",
2727 spec))
2728 inform (DECL_SOURCE_LOCATION (tmpl),
2729 nattrs > 1
2730 ? G_("missing primary template attributes %s")
2731 : G_("missing primary template attribute %s"),
2732 pp_formatted_text (&str));
2735 /* Check to see if the function just declared, as indicated in
2736 DECLARATOR, and in DECL, is a specialization of a function
2737 template. We may also discover that the declaration is an explicit
2738 instantiation at this point.
2740 Returns DECL, or an equivalent declaration that should be used
2741 instead if all goes well. Issues an error message if something is
2742 amiss. Returns error_mark_node if the error is not easily
2743 recoverable.
2745 FLAGS is a bitmask consisting of the following flags:
2747 2: The function has a definition.
2748 4: The function is a friend.
2750 The TEMPLATE_COUNT is the number of references to qualifying
2751 template classes that appeared in the name of the function. For
2752 example, in
2754 template <class T> struct S { void f(); };
2755 void S<int>::f();
2757 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2758 classes are not counted in the TEMPLATE_COUNT, so that in
2760 template <class T> struct S {};
2761 template <> struct S<int> { void f(); }
2762 template <> void S<int>::f();
2764 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2765 invalid; there should be no template <>.)
2767 If the function is a specialization, it is marked as such via
2768 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2769 is set up correctly, and it is added to the list of specializations
2770 for that template. */
2772 tree
2773 check_explicit_specialization (tree declarator,
2774 tree decl,
2775 int template_count,
2776 int flags,
2777 tree attrlist)
2779 int have_def = flags & 2;
2780 int is_friend = flags & 4;
2781 bool is_concept = flags & 8;
2782 int specialization = 0;
2783 int explicit_instantiation = 0;
2784 int member_specialization = 0;
2785 tree ctype = DECL_CLASS_CONTEXT (decl);
2786 tree dname = DECL_NAME (decl);
2787 tmpl_spec_kind tsk;
2789 if (is_friend)
2791 if (!processing_specialization)
2792 tsk = tsk_none;
2793 else
2794 tsk = tsk_excessive_parms;
2796 else
2797 tsk = current_tmpl_spec_kind (template_count);
2799 switch (tsk)
2801 case tsk_none:
2802 if (processing_specialization && !VAR_P (decl))
2804 specialization = 1;
2805 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2807 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2809 if (is_friend)
2810 /* This could be something like:
2812 template <class T> void f(T);
2813 class S { friend void f<>(int); } */
2814 specialization = 1;
2815 else
2817 /* This case handles bogus declarations like template <>
2818 template <class T> void f<int>(); */
2820 error ("template-id %qD in declaration of primary template",
2821 declarator);
2822 return decl;
2825 break;
2827 case tsk_invalid_member_spec:
2828 /* The error has already been reported in
2829 check_specialization_scope. */
2830 return error_mark_node;
2832 case tsk_invalid_expl_inst:
2833 error ("template parameter list used in explicit instantiation");
2835 /* Fall through. */
2837 case tsk_expl_inst:
2838 if (have_def)
2839 error ("definition provided for explicit instantiation");
2841 explicit_instantiation = 1;
2842 break;
2844 case tsk_excessive_parms:
2845 case tsk_insufficient_parms:
2846 if (tsk == tsk_excessive_parms)
2847 error ("too many template parameter lists in declaration of %qD",
2848 decl);
2849 else if (template_header_count)
2850 error("too few template parameter lists in declaration of %qD", decl);
2851 else
2852 error("explicit specialization of %qD must be introduced by "
2853 "%<template <>%>", decl);
2855 /* Fall through. */
2856 case tsk_expl_spec:
2857 if (is_concept)
2858 error ("explicit specialization declared %<concept%>");
2860 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2861 /* In cases like template<> constexpr bool v = true;
2862 We'll give an error in check_template_variable. */
2863 break;
2865 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2866 if (ctype)
2867 member_specialization = 1;
2868 else
2869 specialization = 1;
2870 break;
2872 case tsk_template:
2873 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2875 /* This case handles bogus declarations like template <>
2876 template <class T> void f<int>(); */
2878 if (!uses_template_parms (declarator))
2879 error ("template-id %qD in declaration of primary template",
2880 declarator);
2881 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2883 /* Partial specialization of variable template. */
2884 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2885 specialization = 1;
2886 goto ok;
2888 else if (cxx_dialect < cxx14)
2889 error ("non-type partial specialization %qD "
2890 "is not allowed", declarator);
2891 else
2892 error ("non-class, non-variable partial specialization %qD "
2893 "is not allowed", declarator);
2894 return decl;
2895 ok:;
2898 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2899 /* This is a specialization of a member template, without
2900 specialization the containing class. Something like:
2902 template <class T> struct S {
2903 template <class U> void f (U);
2905 template <> template <class U> void S<int>::f(U) {}
2907 That's a specialization -- but of the entire template. */
2908 specialization = 1;
2909 break;
2911 default:
2912 gcc_unreachable ();
2915 if ((specialization || member_specialization)
2916 /* This doesn't apply to variable templates. */
2917 && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2918 || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2920 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2921 for (; t; t = TREE_CHAIN (t))
2922 if (TREE_PURPOSE (t))
2924 permerror (input_location,
2925 "default argument specified in explicit specialization");
2926 break;
2930 if (specialization || member_specialization || explicit_instantiation)
2932 tree tmpl = NULL_TREE;
2933 tree targs = NULL_TREE;
2934 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2936 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2937 if (!was_template_id)
2939 tree fns;
2941 gcc_assert (identifier_p (declarator));
2942 if (ctype)
2943 fns = dname;
2944 else
2946 /* If there is no class context, the explicit instantiation
2947 must be at namespace scope. */
2948 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2950 /* Find the namespace binding, using the declaration
2951 context. */
2952 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2953 false, true);
2954 if (fns == error_mark_node)
2955 /* If lookup fails, look for a friend declaration so we can
2956 give a better diagnostic. */
2957 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2958 /*type*/false, /*complain*/true,
2959 /*hidden*/true);
2961 if (fns == error_mark_node || !is_overloaded_fn (fns))
2963 error ("%qD is not a template function", dname);
2964 fns = error_mark_node;
2968 declarator = lookup_template_function (fns, NULL_TREE);
2971 if (declarator == error_mark_node)
2972 return error_mark_node;
2974 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2976 if (!explicit_instantiation)
2977 /* A specialization in class scope. This is invalid,
2978 but the error will already have been flagged by
2979 check_specialization_scope. */
2980 return error_mark_node;
2981 else
2983 /* It's not valid to write an explicit instantiation in
2984 class scope, e.g.:
2986 class C { template void f(); }
2988 This case is caught by the parser. However, on
2989 something like:
2991 template class C { void f(); };
2993 (which is invalid) we can get here. The error will be
2994 issued later. */
2998 return decl;
3000 else if (ctype != NULL_TREE
3001 && (identifier_p (TREE_OPERAND (declarator, 0))))
3003 // We'll match variable templates in start_decl.
3004 if (VAR_P (decl))
3005 return decl;
3007 /* Find the list of functions in ctype that have the same
3008 name as the declared function. */
3009 tree name = TREE_OPERAND (declarator, 0);
3011 if (constructor_name_p (name, ctype))
3013 if (DECL_CONSTRUCTOR_P (decl)
3014 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3015 : !CLASSTYPE_DESTRUCTOR (ctype))
3017 /* From [temp.expl.spec]:
3019 If such an explicit specialization for the member
3020 of a class template names an implicitly-declared
3021 special member function (clause _special_), the
3022 program is ill-formed.
3024 Similar language is found in [temp.explicit]. */
3025 error ("specialization of implicitly-declared special member function");
3026 return error_mark_node;
3029 name = DECL_NAME (decl);
3032 /* For a type-conversion operator, We might be looking for
3033 `operator int' which will be a specialization of
3034 `operator T'. Grab all the conversion operators, and
3035 then select from them. */
3036 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3037 ? conv_op_identifier : name);
3039 if (fns == NULL_TREE)
3041 error ("no member function %qD declared in %qT", name, ctype);
3042 return error_mark_node;
3044 else
3045 TREE_OPERAND (declarator, 0) = fns;
3048 /* Figure out what exactly is being specialized at this point.
3049 Note that for an explicit instantiation, even one for a
3050 member function, we cannot tell a priori whether the
3051 instantiation is for a member template, or just a member
3052 function of a template class. Even if a member template is
3053 being instantiated, the member template arguments may be
3054 elided if they can be deduced from the rest of the
3055 declaration. */
3056 tmpl = determine_specialization (declarator, decl,
3057 &targs,
3058 member_specialization,
3059 template_count,
3060 tsk);
3062 if (!tmpl || tmpl == error_mark_node)
3063 /* We couldn't figure out what this declaration was
3064 specializing. */
3065 return error_mark_node;
3066 else
3068 if (TREE_CODE (decl) == FUNCTION_DECL
3069 && DECL_HIDDEN_FRIEND_P (tmpl))
3071 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3072 "friend declaration %qD is not visible to "
3073 "explicit specialization", tmpl))
3074 inform (DECL_SOURCE_LOCATION (tmpl),
3075 "friend declaration here");
3077 else if (!ctype && !is_friend
3078 && CP_DECL_CONTEXT (decl) == current_namespace)
3079 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3081 tree gen_tmpl = most_general_template (tmpl);
3083 if (explicit_instantiation)
3085 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3086 is done by do_decl_instantiation later. */
3088 int arg_depth = TMPL_ARGS_DEPTH (targs);
3089 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3091 if (arg_depth > parm_depth)
3093 /* If TMPL is not the most general template (for
3094 example, if TMPL is a friend template that is
3095 injected into namespace scope), then there will
3096 be too many levels of TARGS. Remove some of them
3097 here. */
3098 int i;
3099 tree new_targs;
3101 new_targs = make_tree_vec (parm_depth);
3102 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3103 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3104 = TREE_VEC_ELT (targs, i);
3105 targs = new_targs;
3108 return instantiate_template (tmpl, targs, tf_error);
3111 /* If we thought that the DECL was a member function, but it
3112 turns out to be specializing a static member function,
3113 make DECL a static member function as well. */
3114 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3115 && DECL_STATIC_FUNCTION_P (tmpl)
3116 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3117 revert_static_member_fn (decl);
3119 /* If this is a specialization of a member template of a
3120 template class, we want to return the TEMPLATE_DECL, not
3121 the specialization of it. */
3122 if (tsk == tsk_template && !was_template_id)
3124 tree result = DECL_TEMPLATE_RESULT (tmpl);
3125 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3126 DECL_INITIAL (result) = NULL_TREE;
3127 if (have_def)
3129 tree parm;
3130 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3131 DECL_SOURCE_LOCATION (result)
3132 = DECL_SOURCE_LOCATION (decl);
3133 /* We want to use the argument list specified in the
3134 definition, not in the original declaration. */
3135 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3136 for (parm = DECL_ARGUMENTS (result); parm;
3137 parm = DECL_CHAIN (parm))
3138 DECL_CONTEXT (parm) = result;
3140 return register_specialization (tmpl, gen_tmpl, targs,
3141 is_friend, 0);
3144 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3145 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3147 if (was_template_id)
3148 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3150 /* Inherit default function arguments from the template
3151 DECL is specializing. */
3152 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3153 copy_default_args_to_explicit_spec (decl);
3155 /* This specialization has the same protection as the
3156 template it specializes. */
3157 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3158 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3160 /* 7.1.1-1 [dcl.stc]
3162 A storage-class-specifier shall not be specified in an
3163 explicit specialization...
3165 The parser rejects these, so unless action is taken here,
3166 explicit function specializations will always appear with
3167 global linkage.
3169 The action recommended by the C++ CWG in response to C++
3170 defect report 605 is to make the storage class and linkage
3171 of the explicit specialization match the templated function:
3173 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3175 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3177 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3178 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3180 /* A concept cannot be specialized. */
3181 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3183 error ("explicit specialization of function concept %qD",
3184 gen_tmpl);
3185 return error_mark_node;
3188 /* This specialization has the same linkage and visibility as
3189 the function template it specializes. */
3190 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3191 if (! TREE_PUBLIC (decl))
3193 DECL_INTERFACE_KNOWN (decl) = 1;
3194 DECL_NOT_REALLY_EXTERN (decl) = 1;
3196 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3197 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3199 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3200 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3204 /* If DECL is a friend declaration, declared using an
3205 unqualified name, the namespace associated with DECL may
3206 have been set incorrectly. For example, in:
3208 template <typename T> void f(T);
3209 namespace N {
3210 struct S { friend void f<int>(int); }
3213 we will have set the DECL_CONTEXT for the friend
3214 declaration to N, rather than to the global namespace. */
3215 if (DECL_NAMESPACE_SCOPE_P (decl))
3216 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3218 if (is_friend && !have_def)
3219 /* This is not really a declaration of a specialization.
3220 It's just the name of an instantiation. But, it's not
3221 a request for an instantiation, either. */
3222 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3223 else if (TREE_CODE (decl) == FUNCTION_DECL)
3224 /* A specialization is not necessarily COMDAT. */
3225 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3226 && DECL_DECLARED_INLINE_P (decl));
3227 else if (VAR_P (decl))
3228 DECL_COMDAT (decl) = false;
3230 /* If this is a full specialization, register it so that we can find
3231 it again. Partial specializations will be registered in
3232 process_partial_specialization. */
3233 if (!processing_template_decl)
3235 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3237 decl = register_specialization (decl, gen_tmpl, targs,
3238 is_friend, 0);
3242 /* A 'structor should already have clones. */
3243 gcc_assert (decl == error_mark_node
3244 || variable_template_p (tmpl)
3245 || !(DECL_CONSTRUCTOR_P (decl)
3246 || DECL_DESTRUCTOR_P (decl))
3247 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3251 return decl;
3254 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3255 parameters. These are represented in the same format used for
3256 DECL_TEMPLATE_PARMS. */
3259 comp_template_parms (const_tree parms1, const_tree parms2)
3261 const_tree p1;
3262 const_tree p2;
3264 if (parms1 == parms2)
3265 return 1;
3267 for (p1 = parms1, p2 = parms2;
3268 p1 != NULL_TREE && p2 != NULL_TREE;
3269 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3271 tree t1 = TREE_VALUE (p1);
3272 tree t2 = TREE_VALUE (p2);
3273 int i;
3275 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3276 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3278 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3279 return 0;
3281 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3283 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3284 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3286 /* If either of the template parameters are invalid, assume
3287 they match for the sake of error recovery. */
3288 if (error_operand_p (parm1) || error_operand_p (parm2))
3289 return 1;
3291 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3292 return 0;
3294 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3295 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3296 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3297 continue;
3298 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3299 return 0;
3303 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3304 /* One set of parameters has more parameters lists than the
3305 other. */
3306 return 0;
3308 return 1;
3311 /* Determine whether PARM is a parameter pack. */
3313 bool
3314 template_parameter_pack_p (const_tree parm)
3316 /* Determine if we have a non-type template parameter pack. */
3317 if (TREE_CODE (parm) == PARM_DECL)
3318 return (DECL_TEMPLATE_PARM_P (parm)
3319 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3320 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3321 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3323 /* If this is a list of template parameters, we could get a
3324 TYPE_DECL or a TEMPLATE_DECL. */
3325 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3326 parm = TREE_TYPE (parm);
3328 /* Otherwise it must be a type template parameter. */
3329 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3330 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3331 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3334 /* Determine if T is a function parameter pack. */
3336 bool
3337 function_parameter_pack_p (const_tree t)
3339 if (t && TREE_CODE (t) == PARM_DECL)
3340 return DECL_PACK_P (t);
3341 return false;
3344 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3345 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3347 tree
3348 get_function_template_decl (const_tree primary_func_tmpl_inst)
3350 if (! primary_func_tmpl_inst
3351 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3352 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3353 return NULL;
3355 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3358 /* Return true iff the function parameter PARAM_DECL was expanded
3359 from the function parameter pack PACK. */
3361 bool
3362 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3364 if (DECL_ARTIFICIAL (param_decl)
3365 || !function_parameter_pack_p (pack))
3366 return false;
3368 /* The parameter pack and its pack arguments have the same
3369 DECL_PARM_INDEX. */
3370 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3373 /* Determine whether ARGS describes a variadic template args list,
3374 i.e., one that is terminated by a template argument pack. */
3376 static bool
3377 template_args_variadic_p (tree args)
3379 int nargs;
3380 tree last_parm;
3382 if (args == NULL_TREE)
3383 return false;
3385 args = INNERMOST_TEMPLATE_ARGS (args);
3386 nargs = TREE_VEC_LENGTH (args);
3388 if (nargs == 0)
3389 return false;
3391 last_parm = TREE_VEC_ELT (args, nargs - 1);
3393 return ARGUMENT_PACK_P (last_parm);
3396 /* Generate a new name for the parameter pack name NAME (an
3397 IDENTIFIER_NODE) that incorporates its */
3399 static tree
3400 make_ith_pack_parameter_name (tree name, int i)
3402 /* Munge the name to include the parameter index. */
3403 #define NUMBUF_LEN 128
3404 char numbuf[NUMBUF_LEN];
3405 char* newname;
3406 int newname_len;
3408 if (name == NULL_TREE)
3409 return name;
3410 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3411 newname_len = IDENTIFIER_LENGTH (name)
3412 + strlen (numbuf) + 2;
3413 newname = (char*)alloca (newname_len);
3414 snprintf (newname, newname_len,
3415 "%s#%i", IDENTIFIER_POINTER (name), i);
3416 return get_identifier (newname);
3419 /* Return true if T is a primary function, class or alias template
3420 specialization, not including the template pattern. */
3422 bool
3423 primary_template_specialization_p (const_tree t)
3425 if (!t)
3426 return false;
3428 if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3429 return (DECL_LANG_SPECIFIC (t)
3430 && DECL_USE_TEMPLATE (t)
3431 && DECL_TEMPLATE_INFO (t)
3432 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3433 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3434 return (CLASSTYPE_TEMPLATE_INFO (t)
3435 && CLASSTYPE_USE_TEMPLATE (t)
3436 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3437 else if (alias_template_specialization_p (t))
3438 return true;
3439 return false;
3442 /* Return true if PARM is a template template parameter. */
3444 bool
3445 template_template_parameter_p (const_tree parm)
3447 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3450 /* Return true iff PARM is a DECL representing a type template
3451 parameter. */
3453 bool
3454 template_type_parameter_p (const_tree parm)
3456 return (parm
3457 && (TREE_CODE (parm) == TYPE_DECL
3458 || TREE_CODE (parm) == TEMPLATE_DECL)
3459 && DECL_TEMPLATE_PARM_P (parm));
3462 /* Return the template parameters of T if T is a
3463 primary template instantiation, NULL otherwise. */
3465 tree
3466 get_primary_template_innermost_parameters (const_tree t)
3468 tree parms = NULL, template_info = NULL;
3470 if ((template_info = get_template_info (t))
3471 && primary_template_specialization_p (t))
3472 parms = INNERMOST_TEMPLATE_PARMS
3473 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3475 return parms;
3478 /* Return the template parameters of the LEVELth level from the full list
3479 of template parameters PARMS. */
3481 tree
3482 get_template_parms_at_level (tree parms, int level)
3484 tree p;
3485 if (!parms
3486 || TREE_CODE (parms) != TREE_LIST
3487 || level > TMPL_PARMS_DEPTH (parms))
3488 return NULL_TREE;
3490 for (p = parms; p; p = TREE_CHAIN (p))
3491 if (TMPL_PARMS_DEPTH (p) == level)
3492 return p;
3494 return NULL_TREE;
3497 /* Returns the template arguments of T if T is a template instantiation,
3498 NULL otherwise. */
3500 tree
3501 get_template_innermost_arguments (const_tree t)
3503 tree args = NULL, template_info = NULL;
3505 if ((template_info = get_template_info (t))
3506 && TI_ARGS (template_info))
3507 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3509 return args;
3512 /* Return the argument pack elements of T if T is a template argument pack,
3513 NULL otherwise. */
3515 tree
3516 get_template_argument_pack_elems (const_tree t)
3518 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3519 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3520 return NULL;
3522 return ARGUMENT_PACK_ARGS (t);
3525 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3526 ARGUMENT_PACK_SELECT represents. */
3528 static tree
3529 argument_pack_select_arg (tree t)
3531 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3532 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3534 /* If the selected argument is an expansion E, that most likely means we were
3535 called from gen_elem_of_pack_expansion_instantiation during the
3536 substituting of an argument pack (of which the Ith element is a pack
3537 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3538 In this case, the Ith element resulting from this substituting is going to
3539 be a pack expansion, which pattern is the pattern of E. Let's return the
3540 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3541 resulting pack expansion from it. */
3542 if (PACK_EXPANSION_P (arg))
3544 /* Make sure we aren't throwing away arg info. */
3545 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3546 arg = PACK_EXPANSION_PATTERN (arg);
3549 return arg;
3553 /* True iff FN is a function representing a built-in variadic parameter
3554 pack. */
3556 bool
3557 builtin_pack_fn_p (tree fn)
3559 if (!fn
3560 || TREE_CODE (fn) != FUNCTION_DECL
3561 || !DECL_IS_BUILTIN (fn))
3562 return false;
3564 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3565 return true;
3567 return false;
3570 /* True iff CALL is a call to a function representing a built-in variadic
3571 parameter pack. */
3573 static bool
3574 builtin_pack_call_p (tree call)
3576 if (TREE_CODE (call) != CALL_EXPR)
3577 return false;
3578 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3581 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3583 static tree
3584 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3585 tree in_decl)
3587 tree ohi = CALL_EXPR_ARG (call, 0);
3588 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3589 false/*fn*/, true/*int_cst*/);
3591 if (value_dependent_expression_p (hi))
3593 if (hi != ohi)
3595 call = copy_node (call);
3596 CALL_EXPR_ARG (call, 0) = hi;
3598 tree ex = make_pack_expansion (call, complain);
3599 tree vec = make_tree_vec (1);
3600 TREE_VEC_ELT (vec, 0) = ex;
3601 return vec;
3603 else
3605 hi = cxx_constant_value (hi);
3606 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3608 /* Calculate the largest value of len that won't make the size of the vec
3609 overflow an int. The compiler will exceed resource limits long before
3610 this, but it seems a decent place to diagnose. */
3611 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3613 if (len < 0 || len > max)
3615 if ((complain & tf_error)
3616 && hi != error_mark_node)
3617 error ("argument to __integer_pack must be between 0 and %d", max);
3618 return error_mark_node;
3621 tree vec = make_tree_vec (len);
3623 for (int i = 0; i < len; ++i)
3624 TREE_VEC_ELT (vec, i) = size_int (i);
3626 return vec;
3630 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3631 CALL. */
3633 static tree
3634 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3635 tree in_decl)
3637 if (!builtin_pack_call_p (call))
3638 return NULL_TREE;
3640 tree fn = CALL_EXPR_FN (call);
3642 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3643 return expand_integer_pack (call, args, complain, in_decl);
3645 return NULL_TREE;
3648 /* Structure used to track the progress of find_parameter_packs_r. */
3649 struct find_parameter_pack_data
3651 /* TREE_LIST that will contain all of the parameter packs found by
3652 the traversal. */
3653 tree* parameter_packs;
3655 /* Set of AST nodes that have been visited by the traversal. */
3656 hash_set<tree> *visited;
3658 /* True iff we're making a type pack expansion. */
3659 bool type_pack_expansion_p;
3662 /* Identifies all of the argument packs that occur in a template
3663 argument and appends them to the TREE_LIST inside DATA, which is a
3664 find_parameter_pack_data structure. This is a subroutine of
3665 make_pack_expansion and uses_parameter_packs. */
3666 static tree
3667 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3669 tree t = *tp;
3670 struct find_parameter_pack_data* ppd =
3671 (struct find_parameter_pack_data*)data;
3672 bool parameter_pack_p = false;
3674 /* Handle type aliases/typedefs. */
3675 if (TYPE_ALIAS_P (t))
3677 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3678 cp_walk_tree (&TI_ARGS (tinfo),
3679 &find_parameter_packs_r,
3680 ppd, ppd->visited);
3681 *walk_subtrees = 0;
3682 return NULL_TREE;
3685 /* Identify whether this is a parameter pack or not. */
3686 switch (TREE_CODE (t))
3688 case TEMPLATE_PARM_INDEX:
3689 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3690 parameter_pack_p = true;
3691 break;
3693 case TEMPLATE_TYPE_PARM:
3694 t = TYPE_MAIN_VARIANT (t);
3695 /* FALLTHRU */
3696 case TEMPLATE_TEMPLATE_PARM:
3697 /* If the placeholder appears in the decl-specifier-seq of a function
3698 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3699 is a pack expansion, the invented template parameter is a template
3700 parameter pack. */
3701 if (ppd->type_pack_expansion_p && is_auto (t))
3702 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3703 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3704 parameter_pack_p = true;
3705 break;
3707 case FIELD_DECL:
3708 case PARM_DECL:
3709 if (DECL_PACK_P (t))
3711 /* We don't want to walk into the type of a PARM_DECL,
3712 because we don't want to see the type parameter pack. */
3713 *walk_subtrees = 0;
3714 parameter_pack_p = true;
3716 break;
3718 case VAR_DECL:
3719 if (DECL_PACK_P (t))
3721 /* We don't want to walk into the type of a variadic capture proxy,
3722 because we don't want to see the type parameter pack. */
3723 *walk_subtrees = 0;
3724 parameter_pack_p = true;
3726 else if (variable_template_specialization_p (t))
3728 cp_walk_tree (&DECL_TI_ARGS (t),
3729 find_parameter_packs_r,
3730 ppd, ppd->visited);
3731 *walk_subtrees = 0;
3733 break;
3735 case CALL_EXPR:
3736 if (builtin_pack_call_p (t))
3737 parameter_pack_p = true;
3738 break;
3740 case BASES:
3741 parameter_pack_p = true;
3742 break;
3743 default:
3744 /* Not a parameter pack. */
3745 break;
3748 if (parameter_pack_p)
3750 /* Add this parameter pack to the list. */
3751 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3754 if (TYPE_P (t))
3755 cp_walk_tree (&TYPE_CONTEXT (t),
3756 &find_parameter_packs_r, ppd, ppd->visited);
3758 /* This switch statement will return immediately if we don't find a
3759 parameter pack. */
3760 switch (TREE_CODE (t))
3762 case TEMPLATE_PARM_INDEX:
3763 return NULL_TREE;
3765 case BOUND_TEMPLATE_TEMPLATE_PARM:
3766 /* Check the template itself. */
3767 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3768 &find_parameter_packs_r, ppd, ppd->visited);
3769 /* Check the template arguments. */
3770 cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3771 ppd->visited);
3772 *walk_subtrees = 0;
3773 return NULL_TREE;
3775 case TEMPLATE_TYPE_PARM:
3776 case TEMPLATE_TEMPLATE_PARM:
3777 return NULL_TREE;
3779 case PARM_DECL:
3780 return NULL_TREE;
3782 case DECL_EXPR:
3783 /* Ignore the declaration of a capture proxy for a parameter pack. */
3784 if (is_capture_proxy (DECL_EXPR_DECL (t)))
3785 *walk_subtrees = 0;
3786 return NULL_TREE;
3788 case RECORD_TYPE:
3789 if (TYPE_PTRMEMFUNC_P (t))
3790 return NULL_TREE;
3791 /* Fall through. */
3793 case UNION_TYPE:
3794 case ENUMERAL_TYPE:
3795 if (TYPE_TEMPLATE_INFO (t))
3796 cp_walk_tree (&TYPE_TI_ARGS (t),
3797 &find_parameter_packs_r, ppd, ppd->visited);
3799 *walk_subtrees = 0;
3800 return NULL_TREE;
3802 case TEMPLATE_DECL:
3803 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3804 return NULL_TREE;
3805 gcc_fallthrough();
3807 case CONSTRUCTOR:
3808 cp_walk_tree (&TREE_TYPE (t),
3809 &find_parameter_packs_r, ppd, ppd->visited);
3810 return NULL_TREE;
3812 case TYPENAME_TYPE:
3813 cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3814 ppd, ppd->visited);
3815 *walk_subtrees = 0;
3816 return NULL_TREE;
3818 case TYPE_PACK_EXPANSION:
3819 case EXPR_PACK_EXPANSION:
3820 *walk_subtrees = 0;
3821 return NULL_TREE;
3823 case INTEGER_TYPE:
3824 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3825 ppd, ppd->visited);
3826 *walk_subtrees = 0;
3827 return NULL_TREE;
3829 case IDENTIFIER_NODE:
3830 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3831 ppd->visited);
3832 *walk_subtrees = 0;
3833 return NULL_TREE;
3835 case LAMBDA_EXPR:
3837 /* Look at explicit captures. */
3838 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3839 cap; cap = TREE_CHAIN (cap))
3840 cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3841 ppd->visited);
3842 /* Since we defer implicit capture, look in the body as well. */
3843 tree fn = lambda_function (t);
3844 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3845 ppd->visited);
3846 *walk_subtrees = 0;
3847 return NULL_TREE;
3850 case DECLTYPE_TYPE:
3852 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3853 type_pack_expansion_p to false so that any placeholders
3854 within the expression don't get marked as parameter packs. */
3855 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3856 ppd->type_pack_expansion_p = false;
3857 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3858 ppd, ppd->visited);
3859 ppd->type_pack_expansion_p = type_pack_expansion_p;
3860 *walk_subtrees = 0;
3861 return NULL_TREE;
3864 default:
3865 return NULL_TREE;
3868 return NULL_TREE;
3871 /* Determines if the expression or type T uses any parameter packs. */
3872 bool
3873 uses_parameter_packs (tree t)
3875 tree parameter_packs = NULL_TREE;
3876 struct find_parameter_pack_data ppd;
3877 ppd.parameter_packs = &parameter_packs;
3878 ppd.visited = new hash_set<tree>;
3879 ppd.type_pack_expansion_p = false;
3880 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3881 delete ppd.visited;
3882 return parameter_packs != NULL_TREE;
3885 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3886 representation a base-class initializer into a parameter pack
3887 expansion. If all goes well, the resulting node will be an
3888 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3889 respectively. */
3890 tree
3891 make_pack_expansion (tree arg, tsubst_flags_t complain)
3893 tree result;
3894 tree parameter_packs = NULL_TREE;
3895 bool for_types = false;
3896 struct find_parameter_pack_data ppd;
3898 if (!arg || arg == error_mark_node)
3899 return arg;
3901 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3903 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3904 class initializer. In this case, the TREE_PURPOSE will be a
3905 _TYPE node (representing the base class expansion we're
3906 initializing) and the TREE_VALUE will be a TREE_LIST
3907 containing the initialization arguments.
3909 The resulting expansion looks somewhat different from most
3910 expansions. Rather than returning just one _EXPANSION, we
3911 return a TREE_LIST whose TREE_PURPOSE is a
3912 TYPE_PACK_EXPANSION containing the bases that will be
3913 initialized. The TREE_VALUE will be identical to the
3914 original TREE_VALUE, which is a list of arguments that will
3915 be passed to each base. We do not introduce any new pack
3916 expansion nodes into the TREE_VALUE (although it is possible
3917 that some already exist), because the TREE_PURPOSE and
3918 TREE_VALUE all need to be expanded together with the same
3919 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
3920 resulting TREE_PURPOSE will mention the parameter packs in
3921 both the bases and the arguments to the bases. */
3922 tree purpose;
3923 tree value;
3924 tree parameter_packs = NULL_TREE;
3926 /* Determine which parameter packs will be used by the base
3927 class expansion. */
3928 ppd.visited = new hash_set<tree>;
3929 ppd.parameter_packs = &parameter_packs;
3930 ppd.type_pack_expansion_p = true;
3931 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3932 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3933 &ppd, ppd.visited);
3935 if (parameter_packs == NULL_TREE)
3937 if (complain & tf_error)
3938 error ("base initializer expansion %qT contains no parameter packs",
3939 arg);
3940 delete ppd.visited;
3941 return error_mark_node;
3944 if (TREE_VALUE (arg) != void_type_node)
3946 /* Collect the sets of parameter packs used in each of the
3947 initialization arguments. */
3948 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3950 /* Determine which parameter packs will be expanded in this
3951 argument. */
3952 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3953 &ppd, ppd.visited);
3957 delete ppd.visited;
3959 /* Create the pack expansion type for the base type. */
3960 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3961 SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3962 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3963 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
3965 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3966 they will rarely be compared to anything. */
3967 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3969 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3972 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3973 for_types = true;
3975 /* Build the PACK_EXPANSION_* node. */
3976 result = for_types
3977 ? cxx_make_type (TYPE_PACK_EXPANSION)
3978 : make_node (EXPR_PACK_EXPANSION);
3979 SET_PACK_EXPANSION_PATTERN (result, arg);
3980 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3982 /* Propagate type and const-expression information. */
3983 TREE_TYPE (result) = TREE_TYPE (arg);
3984 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3985 /* Mark this read now, since the expansion might be length 0. */
3986 mark_exp_read (arg);
3988 else
3989 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3990 they will rarely be compared to anything. */
3991 SET_TYPE_STRUCTURAL_EQUALITY (result);
3993 /* Determine which parameter packs will be expanded. */
3994 ppd.parameter_packs = &parameter_packs;
3995 ppd.visited = new hash_set<tree>;
3996 ppd.type_pack_expansion_p = TYPE_P (arg);
3997 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3998 delete ppd.visited;
4000 /* Make sure we found some parameter packs. */
4001 if (parameter_packs == NULL_TREE)
4003 if (complain & tf_error)
4005 if (TYPE_P (arg))
4006 error ("expansion pattern %qT contains no parameter packs", arg);
4007 else
4008 error ("expansion pattern %qE contains no parameter packs", arg);
4010 return error_mark_node;
4012 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4014 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4016 return result;
4019 /* Checks T for any "bare" parameter packs, which have not yet been
4020 expanded, and issues an error if any are found. This operation can
4021 only be done on full expressions or types (e.g., an expression
4022 statement, "if" condition, etc.), because we could have expressions like:
4024 foo(f(g(h(args)))...)
4026 where "args" is a parameter pack. check_for_bare_parameter_packs
4027 should not be called for the subexpressions args, h(args),
4028 g(h(args)), or f(g(h(args))), because we would produce erroneous
4029 error messages.
4031 Returns TRUE and emits an error if there were bare parameter packs,
4032 returns FALSE otherwise. */
4033 bool
4034 check_for_bare_parameter_packs (tree t)
4036 tree parameter_packs = NULL_TREE;
4037 struct find_parameter_pack_data ppd;
4039 if (!processing_template_decl || !t || t == error_mark_node)
4040 return false;
4042 /* A lambda might use a parameter pack from the containing context. */
4043 if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4044 && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4045 return false;
4047 if (TREE_CODE (t) == TYPE_DECL)
4048 t = TREE_TYPE (t);
4050 ppd.parameter_packs = &parameter_packs;
4051 ppd.visited = new hash_set<tree>;
4052 ppd.type_pack_expansion_p = false;
4053 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4054 delete ppd.visited;
4056 if (parameter_packs)
4058 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
4059 error_at (loc, "parameter packs not expanded with %<...%>:");
4060 while (parameter_packs)
4062 tree pack = TREE_VALUE (parameter_packs);
4063 tree name = NULL_TREE;
4065 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4066 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4067 name = TYPE_NAME (pack);
4068 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4069 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4070 else if (TREE_CODE (pack) == CALL_EXPR)
4071 name = DECL_NAME (CALL_EXPR_FN (pack));
4072 else
4073 name = DECL_NAME (pack);
4075 if (name)
4076 inform (loc, " %qD", name);
4077 else
4078 inform (loc, " <anonymous>");
4080 parameter_packs = TREE_CHAIN (parameter_packs);
4083 return true;
4086 return false;
4089 /* Expand any parameter packs that occur in the template arguments in
4090 ARGS. */
4091 tree
4092 expand_template_argument_pack (tree args)
4094 if (args == error_mark_node)
4095 return error_mark_node;
4097 tree result_args = NULL_TREE;
4098 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4099 int num_result_args = -1;
4100 int non_default_args_count = -1;
4102 /* First, determine if we need to expand anything, and the number of
4103 slots we'll need. */
4104 for (in_arg = 0; in_arg < nargs; ++in_arg)
4106 tree arg = TREE_VEC_ELT (args, in_arg);
4107 if (arg == NULL_TREE)
4108 return args;
4109 if (ARGUMENT_PACK_P (arg))
4111 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4112 if (num_result_args < 0)
4113 num_result_args = in_arg + num_packed;
4114 else
4115 num_result_args += num_packed;
4117 else
4119 if (num_result_args >= 0)
4120 num_result_args++;
4124 /* If no expansion is necessary, we're done. */
4125 if (num_result_args < 0)
4126 return args;
4128 /* Expand arguments. */
4129 result_args = make_tree_vec (num_result_args);
4130 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4131 non_default_args_count =
4132 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4133 for (in_arg = 0; in_arg < nargs; ++in_arg)
4135 tree arg = TREE_VEC_ELT (args, in_arg);
4136 if (ARGUMENT_PACK_P (arg))
4138 tree packed = ARGUMENT_PACK_ARGS (arg);
4139 int i, num_packed = TREE_VEC_LENGTH (packed);
4140 for (i = 0; i < num_packed; ++i, ++out_arg)
4141 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4142 if (non_default_args_count > 0)
4143 non_default_args_count += num_packed - 1;
4145 else
4147 TREE_VEC_ELT (result_args, out_arg) = arg;
4148 ++out_arg;
4151 if (non_default_args_count >= 0)
4152 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4153 return result_args;
4156 /* Checks if DECL shadows a template parameter.
4158 [temp.local]: A template-parameter shall not be redeclared within its
4159 scope (including nested scopes).
4161 Emits an error and returns TRUE if the DECL shadows a parameter,
4162 returns FALSE otherwise. */
4164 bool
4165 check_template_shadow (tree decl)
4167 tree olddecl;
4169 /* If we're not in a template, we can't possibly shadow a template
4170 parameter. */
4171 if (!current_template_parms)
4172 return true;
4174 /* Figure out what we're shadowing. */
4175 decl = OVL_FIRST (decl);
4176 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4178 /* If there's no previous binding for this name, we're not shadowing
4179 anything, let alone a template parameter. */
4180 if (!olddecl)
4181 return true;
4183 /* If we're not shadowing a template parameter, we're done. Note
4184 that OLDDECL might be an OVERLOAD (or perhaps even an
4185 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4186 node. */
4187 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4188 return true;
4190 /* We check for decl != olddecl to avoid bogus errors for using a
4191 name inside a class. We check TPFI to avoid duplicate errors for
4192 inline member templates. */
4193 if (decl == olddecl
4194 || (DECL_TEMPLATE_PARM_P (decl)
4195 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4196 return true;
4198 /* Don't complain about the injected class name, as we've already
4199 complained about the class itself. */
4200 if (DECL_SELF_REFERENCE_P (decl))
4201 return false;
4203 if (DECL_TEMPLATE_PARM_P (decl))
4204 error ("declaration of template parameter %q+D shadows "
4205 "template parameter", decl);
4206 else
4207 error ("declaration of %q+#D shadows template parameter", decl);
4208 inform (DECL_SOURCE_LOCATION (olddecl),
4209 "template parameter %qD declared here", olddecl);
4210 return false;
4213 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4214 ORIG_LEVEL, DECL, and TYPE. */
4216 static tree
4217 build_template_parm_index (int index,
4218 int level,
4219 int orig_level,
4220 tree decl,
4221 tree type)
4223 tree t = make_node (TEMPLATE_PARM_INDEX);
4224 TEMPLATE_PARM_IDX (t) = index;
4225 TEMPLATE_PARM_LEVEL (t) = level;
4226 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4227 TEMPLATE_PARM_DECL (t) = decl;
4228 TREE_TYPE (t) = type;
4229 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4230 TREE_READONLY (t) = TREE_READONLY (decl);
4232 return t;
4235 /* Find the canonical type parameter for the given template type
4236 parameter. Returns the canonical type parameter, which may be TYPE
4237 if no such parameter existed. */
4239 static tree
4240 canonical_type_parameter (tree type)
4242 tree list;
4243 int idx = TEMPLATE_TYPE_IDX (type);
4244 if (!canonical_template_parms)
4245 vec_alloc (canonical_template_parms, idx + 1);
4247 if (canonical_template_parms->length () <= (unsigned) idx)
4248 vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4250 list = (*canonical_template_parms)[idx];
4251 while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4252 list = TREE_CHAIN (list);
4254 if (list)
4255 return TREE_VALUE (list);
4256 else
4258 (*canonical_template_parms)[idx]
4259 = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4260 return type;
4264 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4265 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4266 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4267 new one is created. */
4269 static tree
4270 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4271 tsubst_flags_t complain)
4273 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4274 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4275 != TEMPLATE_PARM_LEVEL (index) - levels)
4276 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4278 tree orig_decl = TEMPLATE_PARM_DECL (index);
4279 tree decl, t;
4281 decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4282 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4283 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4284 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4285 DECL_ARTIFICIAL (decl) = 1;
4286 SET_DECL_TEMPLATE_PARM_P (decl);
4288 t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4289 TEMPLATE_PARM_LEVEL (index) - levels,
4290 TEMPLATE_PARM_ORIG_LEVEL (index),
4291 decl, type);
4292 TEMPLATE_PARM_DESCENDANTS (index) = t;
4293 TEMPLATE_PARM_PARAMETER_PACK (t)
4294 = TEMPLATE_PARM_PARAMETER_PACK (index);
4296 /* Template template parameters need this. */
4297 if (TREE_CODE (decl) == TEMPLATE_DECL)
4299 DECL_TEMPLATE_RESULT (decl)
4300 = build_decl (DECL_SOURCE_LOCATION (decl),
4301 TYPE_DECL, DECL_NAME (decl), type);
4302 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4303 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4304 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4308 return TEMPLATE_PARM_DESCENDANTS (index);
4311 /* Process information from new template parameter PARM and append it
4312 to the LIST being built. This new parameter is a non-type
4313 parameter iff IS_NON_TYPE is true. This new parameter is a
4314 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4315 is in PARM_LOC. */
4317 tree
4318 process_template_parm (tree list, location_t parm_loc, tree parm,
4319 bool is_non_type, bool is_parameter_pack)
4321 tree decl = 0;
4322 int idx = 0;
4324 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4325 tree defval = TREE_PURPOSE (parm);
4326 tree constr = TREE_TYPE (parm);
4328 if (list)
4330 tree p = tree_last (list);
4332 if (p && TREE_VALUE (p) != error_mark_node)
4334 p = TREE_VALUE (p);
4335 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4336 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4337 else
4338 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4341 ++idx;
4344 if (is_non_type)
4346 parm = TREE_VALUE (parm);
4348 SET_DECL_TEMPLATE_PARM_P (parm);
4350 if (TREE_TYPE (parm) != error_mark_node)
4352 /* [temp.param]
4354 The top-level cv-qualifiers on the template-parameter are
4355 ignored when determining its type. */
4356 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4357 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4358 TREE_TYPE (parm) = error_mark_node;
4359 else if (uses_parameter_packs (TREE_TYPE (parm))
4360 && !is_parameter_pack
4361 /* If we're in a nested template parameter list, the template
4362 template parameter could be a parameter pack. */
4363 && processing_template_parmlist == 1)
4365 /* This template parameter is not a parameter pack, but it
4366 should be. Complain about "bare" parameter packs. */
4367 check_for_bare_parameter_packs (TREE_TYPE (parm));
4369 /* Recover by calling this a parameter pack. */
4370 is_parameter_pack = true;
4374 /* A template parameter is not modifiable. */
4375 TREE_CONSTANT (parm) = 1;
4376 TREE_READONLY (parm) = 1;
4377 decl = build_decl (parm_loc,
4378 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4379 TREE_CONSTANT (decl) = 1;
4380 TREE_READONLY (decl) = 1;
4381 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4382 = build_template_parm_index (idx, processing_template_decl,
4383 processing_template_decl,
4384 decl, TREE_TYPE (parm));
4386 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4387 = is_parameter_pack;
4389 else
4391 tree t;
4392 parm = TREE_VALUE (TREE_VALUE (parm));
4394 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4396 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4397 /* This is for distinguishing between real templates and template
4398 template parameters */
4399 TREE_TYPE (parm) = t;
4400 TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4401 decl = parm;
4403 else
4405 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4406 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4407 decl = build_decl (parm_loc,
4408 TYPE_DECL, parm, t);
4411 TYPE_NAME (t) = decl;
4412 TYPE_STUB_DECL (t) = decl;
4413 parm = decl;
4414 TEMPLATE_TYPE_PARM_INDEX (t)
4415 = build_template_parm_index (idx, processing_template_decl,
4416 processing_template_decl,
4417 decl, TREE_TYPE (parm));
4418 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4419 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4421 DECL_ARTIFICIAL (decl) = 1;
4422 SET_DECL_TEMPLATE_PARM_P (decl);
4424 /* Build requirements for the type/template parameter.
4425 This must be done after SET_DECL_TEMPLATE_PARM_P or
4426 process_template_parm could fail. */
4427 tree reqs = finish_shorthand_constraint (parm, constr);
4429 pushdecl (decl);
4431 if (defval && TREE_CODE (defval) == OVERLOAD)
4432 lookup_keep (defval, true);
4434 /* Build the parameter node linking the parameter declaration,
4435 its default argument (if any), and its constraints (if any). */
4436 parm = build_tree_list (defval, parm);
4437 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4439 return chainon (list, parm);
4442 /* The end of a template parameter list has been reached. Process the
4443 tree list into a parameter vector, converting each parameter into a more
4444 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4445 as PARM_DECLs. */
4447 tree
4448 end_template_parm_list (tree parms)
4450 int nparms;
4451 tree parm, next;
4452 tree saved_parmlist = make_tree_vec (list_length (parms));
4454 /* Pop the dummy parameter level and add the real one. */
4455 current_template_parms = TREE_CHAIN (current_template_parms);
4457 current_template_parms
4458 = tree_cons (size_int (processing_template_decl),
4459 saved_parmlist, current_template_parms);
4461 for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4463 next = TREE_CHAIN (parm);
4464 TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4465 TREE_CHAIN (parm) = NULL_TREE;
4468 --processing_template_parmlist;
4470 return saved_parmlist;
4473 // Explicitly indicate the end of the template parameter list. We assume
4474 // that the current template parameters have been constructed and/or
4475 // managed explicitly, as when creating new template template parameters
4476 // from a shorthand constraint.
4477 void
4478 end_template_parm_list ()
4480 --processing_template_parmlist;
4483 /* end_template_decl is called after a template declaration is seen. */
4485 void
4486 end_template_decl (void)
4488 reset_specialization ();
4490 if (! processing_template_decl)
4491 return;
4493 /* This matches the pushlevel in begin_template_parm_list. */
4494 finish_scope ();
4496 --processing_template_decl;
4497 current_template_parms = TREE_CHAIN (current_template_parms);
4500 /* Takes a TREE_LIST representing a template parameter and convert it
4501 into an argument suitable to be passed to the type substitution
4502 functions. Note that If the TREE_LIST contains an error_mark
4503 node, the returned argument is error_mark_node. */
4505 tree
4506 template_parm_to_arg (tree t)
4509 if (t == NULL_TREE
4510 || TREE_CODE (t) != TREE_LIST)
4511 return t;
4513 if (error_operand_p (TREE_VALUE (t)))
4514 return error_mark_node;
4516 t = TREE_VALUE (t);
4518 if (TREE_CODE (t) == TYPE_DECL
4519 || TREE_CODE (t) == TEMPLATE_DECL)
4521 t = TREE_TYPE (t);
4523 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4525 /* Turn this argument into a TYPE_ARGUMENT_PACK
4526 with a single element, which expands T. */
4527 tree vec = make_tree_vec (1);
4528 if (CHECKING_P)
4529 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4531 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4533 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4534 SET_ARGUMENT_PACK_ARGS (t, vec);
4537 else
4539 t = DECL_INITIAL (t);
4541 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4543 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4544 with a single element, which expands T. */
4545 tree vec = make_tree_vec (1);
4546 if (CHECKING_P)
4547 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4549 t = convert_from_reference (t);
4550 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4552 t = make_node (NONTYPE_ARGUMENT_PACK);
4553 SET_ARGUMENT_PACK_ARGS (t, vec);
4555 else
4556 t = convert_from_reference (t);
4558 return t;
4561 /* Given a single level of template parameters (a TREE_VEC), return it
4562 as a set of template arguments. */
4564 static tree
4565 template_parms_level_to_args (tree parms)
4567 tree a = copy_node (parms);
4568 TREE_TYPE (a) = NULL_TREE;
4569 for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4570 TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4572 if (CHECKING_P)
4573 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4575 return a;
4578 /* Given a set of template parameters, return them as a set of template
4579 arguments. The template parameters are represented as a TREE_VEC, in
4580 the form documented in cp-tree.h for template arguments. */
4582 static tree
4583 template_parms_to_args (tree parms)
4585 tree header;
4586 tree args = NULL_TREE;
4587 int length = TMPL_PARMS_DEPTH (parms);
4588 int l = length;
4590 /* If there is only one level of template parameters, we do not
4591 create a TREE_VEC of TREE_VECs. Instead, we return a single
4592 TREE_VEC containing the arguments. */
4593 if (length > 1)
4594 args = make_tree_vec (length);
4596 for (header = parms; header; header = TREE_CHAIN (header))
4598 tree a = template_parms_level_to_args (TREE_VALUE (header));
4600 if (length > 1)
4601 TREE_VEC_ELT (args, --l) = a;
4602 else
4603 args = a;
4606 return args;
4609 /* Within the declaration of a template, return the currently active
4610 template parameters as an argument TREE_VEC. */
4612 static tree
4613 current_template_args (void)
4615 return template_parms_to_args (current_template_parms);
4618 /* Update the declared TYPE by doing any lookups which were thought to be
4619 dependent, but are not now that we know the SCOPE of the declarator. */
4621 tree
4622 maybe_update_decl_type (tree orig_type, tree scope)
4624 tree type = orig_type;
4626 if (type == NULL_TREE)
4627 return type;
4629 if (TREE_CODE (orig_type) == TYPE_DECL)
4630 type = TREE_TYPE (type);
4632 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4633 && dependent_type_p (type)
4634 /* Don't bother building up the args in this case. */
4635 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4637 /* tsubst in the args corresponding to the template parameters,
4638 including auto if present. Most things will be unchanged, but
4639 make_typename_type and tsubst_qualified_id will resolve
4640 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
4641 tree args = current_template_args ();
4642 tree auto_node = type_uses_auto (type);
4643 tree pushed;
4644 if (auto_node)
4646 tree auto_vec = make_tree_vec (1);
4647 TREE_VEC_ELT (auto_vec, 0) = auto_node;
4648 args = add_to_template_args (args, auto_vec);
4650 pushed = push_scope (scope);
4651 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4652 if (pushed)
4653 pop_scope (scope);
4656 if (type == error_mark_node)
4657 return orig_type;
4659 if (TREE_CODE (orig_type) == TYPE_DECL)
4661 if (same_type_p (type, TREE_TYPE (orig_type)))
4662 type = orig_type;
4663 else
4664 type = TYPE_NAME (type);
4666 return type;
4669 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4670 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
4671 the new template is a member template. */
4673 static tree
4674 build_template_decl (tree decl, tree parms, bool member_template_p)
4676 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4677 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4678 DECL_TEMPLATE_PARMS (tmpl) = parms;
4679 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4680 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4681 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4683 return tmpl;
4686 struct template_parm_data
4688 /* The level of the template parameters we are currently
4689 processing. */
4690 int level;
4692 /* The index of the specialization argument we are currently
4693 processing. */
4694 int current_arg;
4696 /* An array whose size is the number of template parameters. The
4697 elements are nonzero if the parameter has been used in any one
4698 of the arguments processed so far. */
4699 int* parms;
4701 /* An array whose size is the number of template arguments. The
4702 elements are nonzero if the argument makes use of template
4703 parameters of this level. */
4704 int* arg_uses_template_parms;
4707 /* Subroutine of push_template_decl used to see if each template
4708 parameter in a partial specialization is used in the explicit
4709 argument list. If T is of the LEVEL given in DATA (which is
4710 treated as a template_parm_data*), then DATA->PARMS is marked
4711 appropriately. */
4713 static int
4714 mark_template_parm (tree t, void* data)
4716 int level;
4717 int idx;
4718 struct template_parm_data* tpd = (struct template_parm_data*) data;
4720 template_parm_level_and_index (t, &level, &idx);
4722 if (level == tpd->level)
4724 tpd->parms[idx] = 1;
4725 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4728 /* In C++17 the type of a non-type argument is a deduced context. */
4729 if (cxx_dialect >= cxx17
4730 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4731 for_each_template_parm (TREE_TYPE (t),
4732 &mark_template_parm,
4733 data,
4734 NULL,
4735 /*include_nondeduced_p=*/false);
4737 /* Return zero so that for_each_template_parm will continue the
4738 traversal of the tree; we want to mark *every* template parm. */
4739 return 0;
4742 /* Process the partial specialization DECL. */
4744 static tree
4745 process_partial_specialization (tree decl)
4747 tree type = TREE_TYPE (decl);
4748 tree tinfo = get_template_info (decl);
4749 tree maintmpl = TI_TEMPLATE (tinfo);
4750 tree specargs = TI_ARGS (tinfo);
4751 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4752 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4753 tree inner_parms;
4754 tree inst;
4755 int nargs = TREE_VEC_LENGTH (inner_args);
4756 int ntparms;
4757 int i;
4758 bool did_error_intro = false;
4759 struct template_parm_data tpd;
4760 struct template_parm_data tpd2;
4762 gcc_assert (current_template_parms);
4764 /* A concept cannot be specialized. */
4765 if (flag_concepts && variable_concept_p (maintmpl))
4767 error ("specialization of variable concept %q#D", maintmpl);
4768 return error_mark_node;
4771 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4772 ntparms = TREE_VEC_LENGTH (inner_parms);
4774 /* We check that each of the template parameters given in the
4775 partial specialization is used in the argument list to the
4776 specialization. For example:
4778 template <class T> struct S;
4779 template <class T> struct S<T*>;
4781 The second declaration is OK because `T*' uses the template
4782 parameter T, whereas
4784 template <class T> struct S<int>;
4786 is no good. Even trickier is:
4788 template <class T>
4789 struct S1
4791 template <class U>
4792 struct S2;
4793 template <class U>
4794 struct S2<T>;
4797 The S2<T> declaration is actually invalid; it is a
4798 full-specialization. Of course,
4800 template <class U>
4801 struct S2<T (*)(U)>;
4803 or some such would have been OK. */
4804 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4805 tpd.parms = XALLOCAVEC (int, ntparms);
4806 memset (tpd.parms, 0, sizeof (int) * ntparms);
4808 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4809 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4810 for (i = 0; i < nargs; ++i)
4812 tpd.current_arg = i;
4813 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4814 &mark_template_parm,
4815 &tpd,
4816 NULL,
4817 /*include_nondeduced_p=*/false);
4819 for (i = 0; i < ntparms; ++i)
4820 if (tpd.parms[i] == 0)
4822 /* One of the template parms was not used in a deduced context in the
4823 specialization. */
4824 if (!did_error_intro)
4826 error ("template parameters not deducible in "
4827 "partial specialization:");
4828 did_error_intro = true;
4831 inform (input_location, " %qD",
4832 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4835 if (did_error_intro)
4836 return error_mark_node;
4838 /* [temp.class.spec]
4840 The argument list of the specialization shall not be identical to
4841 the implicit argument list of the primary template. */
4842 tree main_args
4843 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4844 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4845 && (!flag_concepts
4846 || !strictly_subsumes (current_template_constraints (),
4847 get_constraints (maintmpl))))
4849 if (!flag_concepts)
4850 error ("partial specialization %q+D does not specialize "
4851 "any template arguments; to define the primary template, "
4852 "remove the template argument list", decl);
4853 else
4854 error ("partial specialization %q+D does not specialize any "
4855 "template arguments and is not more constrained than "
4856 "the primary template; to define the primary template, "
4857 "remove the template argument list", decl);
4858 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4861 /* A partial specialization that replaces multiple parameters of the
4862 primary template with a pack expansion is less specialized for those
4863 parameters. */
4864 if (nargs < DECL_NTPARMS (maintmpl))
4866 error ("partial specialization is not more specialized than the "
4867 "primary template because it replaces multiple parameters "
4868 "with a pack expansion");
4869 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4870 /* Avoid crash in process_partial_specialization. */
4871 return decl;
4874 /* If we aren't in a dependent class, we can actually try deduction. */
4875 else if (tpd.level == 1
4876 /* FIXME we should be able to handle a partial specialization of a
4877 partial instantiation, but currently we can't (c++/41727). */
4878 && TMPL_ARGS_DEPTH (specargs) == 1
4879 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4881 if (permerror (input_location, "partial specialization %qD is not "
4882 "more specialized than", decl))
4883 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4884 maintmpl);
4887 /* [temp.class.spec]
4889 A partially specialized non-type argument expression shall not
4890 involve template parameters of the partial specialization except
4891 when the argument expression is a simple identifier.
4893 The type of a template parameter corresponding to a specialized
4894 non-type argument shall not be dependent on a parameter of the
4895 specialization.
4897 Also, we verify that pack expansions only occur at the
4898 end of the argument list. */
4899 gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4900 tpd2.parms = 0;
4901 for (i = 0; i < nargs; ++i)
4903 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4904 tree arg = TREE_VEC_ELT (inner_args, i);
4905 tree packed_args = NULL_TREE;
4906 int j, len = 1;
4908 if (ARGUMENT_PACK_P (arg))
4910 /* Extract the arguments from the argument pack. We'll be
4911 iterating over these in the following loop. */
4912 packed_args = ARGUMENT_PACK_ARGS (arg);
4913 len = TREE_VEC_LENGTH (packed_args);
4916 for (j = 0; j < len; j++)
4918 if (packed_args)
4919 /* Get the Jth argument in the parameter pack. */
4920 arg = TREE_VEC_ELT (packed_args, j);
4922 if (PACK_EXPANSION_P (arg))
4924 /* Pack expansions must come at the end of the
4925 argument list. */
4926 if ((packed_args && j < len - 1)
4927 || (!packed_args && i < nargs - 1))
4929 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4930 error ("parameter pack argument %qE must be at the "
4931 "end of the template argument list", arg);
4932 else
4933 error ("parameter pack argument %qT must be at the "
4934 "end of the template argument list", arg);
4938 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4939 /* We only care about the pattern. */
4940 arg = PACK_EXPANSION_PATTERN (arg);
4942 if (/* These first two lines are the `non-type' bit. */
4943 !TYPE_P (arg)
4944 && TREE_CODE (arg) != TEMPLATE_DECL
4945 /* This next two lines are the `argument expression is not just a
4946 simple identifier' condition and also the `specialized
4947 non-type argument' bit. */
4948 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4949 && !(REFERENCE_REF_P (arg)
4950 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4952 if ((!packed_args && tpd.arg_uses_template_parms[i])
4953 || (packed_args && uses_template_parms (arg)))
4954 error ("template argument %qE involves template parameter(s)",
4955 arg);
4956 else
4958 /* Look at the corresponding template parameter,
4959 marking which template parameters its type depends
4960 upon. */
4961 tree type = TREE_TYPE (parm);
4963 if (!tpd2.parms)
4965 /* We haven't yet initialized TPD2. Do so now. */
4966 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4967 /* The number of parameters here is the number in the
4968 main template, which, as checked in the assertion
4969 above, is NARGS. */
4970 tpd2.parms = XALLOCAVEC (int, nargs);
4971 tpd2.level =
4972 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4975 /* Mark the template parameters. But this time, we're
4976 looking for the template parameters of the main
4977 template, not in the specialization. */
4978 tpd2.current_arg = i;
4979 tpd2.arg_uses_template_parms[i] = 0;
4980 memset (tpd2.parms, 0, sizeof (int) * nargs);
4981 for_each_template_parm (type,
4982 &mark_template_parm,
4983 &tpd2,
4984 NULL,
4985 /*include_nondeduced_p=*/false);
4987 if (tpd2.arg_uses_template_parms [i])
4989 /* The type depended on some template parameters.
4990 If they are fully specialized in the
4991 specialization, that's OK. */
4992 int j;
4993 int count = 0;
4994 for (j = 0; j < nargs; ++j)
4995 if (tpd2.parms[j] != 0
4996 && tpd.arg_uses_template_parms [j])
4997 ++count;
4998 if (count != 0)
4999 error_n (input_location, count,
5000 "type %qT of template argument %qE depends "
5001 "on a template parameter",
5002 "type %qT of template argument %qE depends "
5003 "on template parameters",
5004 type,
5005 arg);
5012 /* We should only get here once. */
5013 if (TREE_CODE (decl) == TYPE_DECL)
5014 gcc_assert (!COMPLETE_TYPE_P (type));
5016 // Build the template decl.
5017 tree tmpl = build_template_decl (decl, current_template_parms,
5018 DECL_MEMBER_TEMPLATE_P (maintmpl));
5019 TREE_TYPE (tmpl) = type;
5020 DECL_TEMPLATE_RESULT (tmpl) = decl;
5021 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5022 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5023 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5025 /* Give template template parms a DECL_CONTEXT of the template
5026 for which they are a parameter. */
5027 for (i = 0; i < ntparms; ++i)
5029 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5030 if (TREE_CODE (parm) == TEMPLATE_DECL)
5031 DECL_CONTEXT (parm) = tmpl;
5034 if (VAR_P (decl))
5035 /* We didn't register this in check_explicit_specialization so we could
5036 wait until the constraints were set. */
5037 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5038 else
5039 associate_classtype_constraints (type);
5041 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5042 = tree_cons (specargs, tmpl,
5043 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5044 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5046 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5047 inst = TREE_CHAIN (inst))
5049 tree instance = TREE_VALUE (inst);
5050 if (TYPE_P (instance)
5051 ? (COMPLETE_TYPE_P (instance)
5052 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5053 : DECL_TEMPLATE_INSTANTIATION (instance))
5055 tree spec = most_specialized_partial_spec (instance, tf_none);
5056 tree inst_decl = (DECL_P (instance)
5057 ? instance : TYPE_NAME (instance));
5058 if (!spec)
5059 /* OK */;
5060 else if (spec == error_mark_node)
5061 permerror (input_location,
5062 "declaration of %qD ambiguates earlier template "
5063 "instantiation for %qD", decl, inst_decl);
5064 else if (TREE_VALUE (spec) == tmpl)
5065 permerror (input_location,
5066 "partial specialization of %qD after instantiation "
5067 "of %qD", decl, inst_decl);
5071 return decl;
5074 /* PARM is a template parameter of some form; return the corresponding
5075 TEMPLATE_PARM_INDEX. */
5077 static tree
5078 get_template_parm_index (tree parm)
5080 if (TREE_CODE (parm) == PARM_DECL
5081 || TREE_CODE (parm) == CONST_DECL)
5082 parm = DECL_INITIAL (parm);
5083 else if (TREE_CODE (parm) == TYPE_DECL
5084 || TREE_CODE (parm) == TEMPLATE_DECL)
5085 parm = TREE_TYPE (parm);
5086 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5087 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5088 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5089 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5090 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5091 return parm;
5094 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5095 parameter packs used by the template parameter PARM. */
5097 static void
5098 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5100 /* A type parm can't refer to another parm. */
5101 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5102 return;
5103 else if (TREE_CODE (parm) == PARM_DECL)
5105 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5106 ppd, ppd->visited);
5107 return;
5110 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5112 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5113 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5114 fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
5117 /* PARM is a template parameter pack. Return any parameter packs used in
5118 its type or the type of any of its template parameters. If there are
5119 any such packs, it will be instantiated into a fixed template parameter
5120 list by partial instantiation rather than be fully deduced. */
5122 tree
5123 fixed_parameter_pack_p (tree parm)
5125 /* This can only be true in a member template. */
5126 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5127 return NULL_TREE;
5128 /* This can only be true for a parameter pack. */
5129 if (!template_parameter_pack_p (parm))
5130 return NULL_TREE;
5131 /* A type parm can't refer to another parm. */
5132 if (TREE_CODE (parm) == TYPE_DECL)
5133 return NULL_TREE;
5135 tree parameter_packs = NULL_TREE;
5136 struct find_parameter_pack_data ppd;
5137 ppd.parameter_packs = &parameter_packs;
5138 ppd.visited = new hash_set<tree>;
5139 ppd.type_pack_expansion_p = false;
5141 fixed_parameter_pack_p_1 (parm, &ppd);
5143 delete ppd.visited;
5144 return parameter_packs;
5147 /* Check that a template declaration's use of default arguments and
5148 parameter packs is not invalid. Here, PARMS are the template
5149 parameters. IS_PRIMARY is true if DECL is the thing declared by
5150 a primary template. IS_PARTIAL is true if DECL is a partial
5151 specialization.
5153 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5154 function template declaration or a friend class template
5155 declaration. In the function case, 1 indicates a declaration, 2
5156 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5157 emitted for extraneous default arguments.
5159 Returns TRUE if there were no errors found, FALSE otherwise. */
5161 bool
5162 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5163 bool is_partial, int is_friend_decl)
5165 const char *msg;
5166 int last_level_to_check;
5167 tree parm_level;
5168 bool no_errors = true;
5170 /* [temp.param]
5172 A default template-argument shall not be specified in a
5173 function template declaration or a function template definition, nor
5174 in the template-parameter-list of the definition of a member of a
5175 class template. */
5177 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5178 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5179 /* You can't have a function template declaration in a local
5180 scope, nor you can you define a member of a class template in a
5181 local scope. */
5182 return true;
5184 if ((TREE_CODE (decl) == TYPE_DECL
5185 && TREE_TYPE (decl)
5186 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5187 || (TREE_CODE (decl) == FUNCTION_DECL
5188 && LAMBDA_FUNCTION_P (decl)))
5189 /* A lambda doesn't have an explicit declaration; don't complain
5190 about the parms of the enclosing class. */
5191 return true;
5193 if (current_class_type
5194 && !TYPE_BEING_DEFINED (current_class_type)
5195 && DECL_LANG_SPECIFIC (decl)
5196 && DECL_DECLARES_FUNCTION_P (decl)
5197 /* If this is either a friend defined in the scope of the class
5198 or a member function. */
5199 && (DECL_FUNCTION_MEMBER_P (decl)
5200 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5201 : DECL_FRIEND_CONTEXT (decl)
5202 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5203 : false)
5204 /* And, if it was a member function, it really was defined in
5205 the scope of the class. */
5206 && (!DECL_FUNCTION_MEMBER_P (decl)
5207 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5208 /* We already checked these parameters when the template was
5209 declared, so there's no need to do it again now. This function
5210 was defined in class scope, but we're processing its body now
5211 that the class is complete. */
5212 return true;
5214 /* Core issue 226 (C++0x only): the following only applies to class
5215 templates. */
5216 if (is_primary
5217 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5219 /* [temp.param]
5221 If a template-parameter has a default template-argument, all
5222 subsequent template-parameters shall have a default
5223 template-argument supplied. */
5224 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5226 tree inner_parms = TREE_VALUE (parm_level);
5227 int ntparms = TREE_VEC_LENGTH (inner_parms);
5228 int seen_def_arg_p = 0;
5229 int i;
5231 for (i = 0; i < ntparms; ++i)
5233 tree parm = TREE_VEC_ELT (inner_parms, i);
5235 if (parm == error_mark_node)
5236 continue;
5238 if (TREE_PURPOSE (parm))
5239 seen_def_arg_p = 1;
5240 else if (seen_def_arg_p
5241 && !template_parameter_pack_p (TREE_VALUE (parm)))
5243 error ("no default argument for %qD", TREE_VALUE (parm));
5244 /* For better subsequent error-recovery, we indicate that
5245 there should have been a default argument. */
5246 TREE_PURPOSE (parm) = error_mark_node;
5247 no_errors = false;
5249 else if (!is_partial
5250 && !is_friend_decl
5251 /* Don't complain about an enclosing partial
5252 specialization. */
5253 && parm_level == parms
5254 && TREE_CODE (decl) == TYPE_DECL
5255 && i < ntparms - 1
5256 && template_parameter_pack_p (TREE_VALUE (parm))
5257 /* A fixed parameter pack will be partially
5258 instantiated into a fixed length list. */
5259 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5261 /* A primary class template can only have one
5262 parameter pack, at the end of the template
5263 parameter list. */
5265 error ("parameter pack %q+D must be at the end of the"
5266 " template parameter list", TREE_VALUE (parm));
5268 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5269 = error_mark_node;
5270 no_errors = false;
5276 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5277 || is_partial
5278 || !is_primary
5279 || is_friend_decl)
5280 /* For an ordinary class template, default template arguments are
5281 allowed at the innermost level, e.g.:
5282 template <class T = int>
5283 struct S {};
5284 but, in a partial specialization, they're not allowed even
5285 there, as we have in [temp.class.spec]:
5287 The template parameter list of a specialization shall not
5288 contain default template argument values.
5290 So, for a partial specialization, or for a function template
5291 (in C++98/C++03), we look at all of them. */
5293 else
5294 /* But, for a primary class template that is not a partial
5295 specialization we look at all template parameters except the
5296 innermost ones. */
5297 parms = TREE_CHAIN (parms);
5299 /* Figure out what error message to issue. */
5300 if (is_friend_decl == 2)
5301 msg = G_("default template arguments may not be used in function template "
5302 "friend re-declaration");
5303 else if (is_friend_decl)
5304 msg = G_("default template arguments may not be used in template "
5305 "friend declarations");
5306 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5307 msg = G_("default template arguments may not be used in function templates "
5308 "without -std=c++11 or -std=gnu++11");
5309 else if (is_partial)
5310 msg = G_("default template arguments may not be used in "
5311 "partial specializations");
5312 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5313 msg = G_("default argument for template parameter for class enclosing %qD");
5314 else
5315 /* Per [temp.param]/9, "A default template-argument shall not be
5316 specified in the template-parameter-lists of the definition of
5317 a member of a class template that appears outside of the member's
5318 class.", thus if we aren't handling a member of a class template
5319 there is no need to examine the parameters. */
5320 return true;
5322 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5323 /* If we're inside a class definition, there's no need to
5324 examine the parameters to the class itself. On the one
5325 hand, they will be checked when the class is defined, and,
5326 on the other, default arguments are valid in things like:
5327 template <class T = double>
5328 struct S { template <class U> void f(U); };
5329 Here the default argument for `S' has no bearing on the
5330 declaration of `f'. */
5331 last_level_to_check = template_class_depth (current_class_type) + 1;
5332 else
5333 /* Check everything. */
5334 last_level_to_check = 0;
5336 for (parm_level = parms;
5337 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5338 parm_level = TREE_CHAIN (parm_level))
5340 tree inner_parms = TREE_VALUE (parm_level);
5341 int i;
5342 int ntparms;
5344 ntparms = TREE_VEC_LENGTH (inner_parms);
5345 for (i = 0; i < ntparms; ++i)
5347 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5348 continue;
5350 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5352 if (msg)
5354 no_errors = false;
5355 if (is_friend_decl == 2)
5356 return no_errors;
5358 error (msg, decl);
5359 msg = 0;
5362 /* Clear out the default argument so that we are not
5363 confused later. */
5364 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5368 /* At this point, if we're still interested in issuing messages,
5369 they must apply to classes surrounding the object declared. */
5370 if (msg)
5371 msg = G_("default argument for template parameter for class "
5372 "enclosing %qD");
5375 return no_errors;
5378 /* Worker for push_template_decl_real, called via
5379 for_each_template_parm. DATA is really an int, indicating the
5380 level of the parameters we are interested in. If T is a template
5381 parameter of that level, return nonzero. */
5383 static int
5384 template_parm_this_level_p (tree t, void* data)
5386 int this_level = *(int *)data;
5387 int level;
5389 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5390 level = TEMPLATE_PARM_LEVEL (t);
5391 else
5392 level = TEMPLATE_TYPE_LEVEL (t);
5393 return level == this_level;
5396 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5397 DATA is really an int, indicating the innermost outer level of parameters.
5398 If T is a template parameter of that level or further out, return
5399 nonzero. */
5401 static int
5402 template_parm_outer_level (tree t, void *data)
5404 int this_level = *(int *)data;
5405 int level;
5407 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5408 level = TEMPLATE_PARM_LEVEL (t);
5409 else
5410 level = TEMPLATE_TYPE_LEVEL (t);
5411 return level <= this_level;
5414 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5415 parameters given by current_template_args, or reuses a
5416 previously existing one, if appropriate. Returns the DECL, or an
5417 equivalent one, if it is replaced via a call to duplicate_decls.
5419 If IS_FRIEND is true, DECL is a friend declaration. */
5421 tree
5422 push_template_decl_real (tree decl, bool is_friend)
5424 tree tmpl;
5425 tree args;
5426 tree info;
5427 tree ctx;
5428 bool is_primary;
5429 bool is_partial;
5430 int new_template_p = 0;
5431 /* True if the template is a member template, in the sense of
5432 [temp.mem]. */
5433 bool member_template_p = false;
5435 if (decl == error_mark_node || !current_template_parms)
5436 return error_mark_node;
5438 /* See if this is a partial specialization. */
5439 is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5440 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5441 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5442 || (VAR_P (decl)
5443 && DECL_LANG_SPECIFIC (decl)
5444 && DECL_TEMPLATE_SPECIALIZATION (decl)
5445 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5447 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5448 is_friend = true;
5450 if (is_friend)
5451 /* For a friend, we want the context of the friend, not
5452 the type of which it is a friend. */
5453 ctx = CP_DECL_CONTEXT (decl);
5454 else if (CP_DECL_CONTEXT (decl)
5455 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5456 /* In the case of a virtual function, we want the class in which
5457 it is defined. */
5458 ctx = CP_DECL_CONTEXT (decl);
5459 else
5460 /* Otherwise, if we're currently defining some class, the DECL
5461 is assumed to be a member of the class. */
5462 ctx = current_scope ();
5464 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5465 ctx = NULL_TREE;
5467 if (!DECL_CONTEXT (decl))
5468 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5470 /* See if this is a primary template. */
5471 if (is_friend && ctx
5472 && uses_template_parms_level (ctx, processing_template_decl))
5473 /* A friend template that specifies a class context, i.e.
5474 template <typename T> friend void A<T>::f();
5475 is not primary. */
5476 is_primary = false;
5477 else if (TREE_CODE (decl) == TYPE_DECL
5478 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5479 is_primary = false;
5480 else
5481 is_primary = template_parm_scope_p ();
5483 if (is_primary)
5485 warning (OPT_Wtemplates, "template %qD declared", decl);
5487 if (DECL_CLASS_SCOPE_P (decl))
5488 member_template_p = true;
5489 if (TREE_CODE (decl) == TYPE_DECL
5490 && anon_aggrname_p (DECL_NAME (decl)))
5492 error ("template class without a name");
5493 return error_mark_node;
5495 else if (TREE_CODE (decl) == FUNCTION_DECL)
5497 if (member_template_p)
5499 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5500 error ("member template %qD may not have virt-specifiers", decl);
5502 if (DECL_DESTRUCTOR_P (decl))
5504 /* [temp.mem]
5506 A destructor shall not be a member template. */
5507 error ("destructor %qD declared as member template", decl);
5508 return error_mark_node;
5510 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5511 && (!prototype_p (TREE_TYPE (decl))
5512 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5513 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5514 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5515 == void_list_node)))
5517 /* [basic.stc.dynamic.allocation]
5519 An allocation function can be a function
5520 template. ... Template allocation functions shall
5521 have two or more parameters. */
5522 error ("invalid template declaration of %qD", decl);
5523 return error_mark_node;
5526 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5527 && CLASS_TYPE_P (TREE_TYPE (decl)))
5529 /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS. */
5530 tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5531 for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5533 tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5534 if (TREE_CODE (t) == TYPE_DECL)
5535 t = TREE_TYPE (t);
5536 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5537 TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5540 else if (TREE_CODE (decl) == TYPE_DECL
5541 && TYPE_DECL_ALIAS_P (decl))
5542 /* alias-declaration */
5543 gcc_assert (!DECL_ARTIFICIAL (decl));
5544 else if (VAR_P (decl))
5545 /* C++14 variable template. */;
5546 else
5548 error ("template declaration of %q#D", decl);
5549 return error_mark_node;
5553 /* Check to see that the rules regarding the use of default
5554 arguments are not being violated. We check args for a friend
5555 functions when we know whether it's a definition, introducing
5556 declaration or re-declaration. */
5557 if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5558 check_default_tmpl_args (decl, current_template_parms,
5559 is_primary, is_partial, is_friend);
5561 /* Ensure that there are no parameter packs in the type of this
5562 declaration that have not been expanded. */
5563 if (TREE_CODE (decl) == FUNCTION_DECL)
5565 /* Check each of the arguments individually to see if there are
5566 any bare parameter packs. */
5567 tree type = TREE_TYPE (decl);
5568 tree arg = DECL_ARGUMENTS (decl);
5569 tree argtype = TYPE_ARG_TYPES (type);
5571 while (arg && argtype)
5573 if (!DECL_PACK_P (arg)
5574 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5576 /* This is a PARM_DECL that contains unexpanded parameter
5577 packs. We have already complained about this in the
5578 check_for_bare_parameter_packs call, so just replace
5579 these types with ERROR_MARK_NODE. */
5580 TREE_TYPE (arg) = error_mark_node;
5581 TREE_VALUE (argtype) = error_mark_node;
5584 arg = DECL_CHAIN (arg);
5585 argtype = TREE_CHAIN (argtype);
5588 /* Check for bare parameter packs in the return type and the
5589 exception specifiers. */
5590 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5591 /* Errors were already issued, set return type to int
5592 as the frontend doesn't expect error_mark_node as
5593 the return type. */
5594 TREE_TYPE (type) = integer_type_node;
5595 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5596 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5598 else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5599 && TYPE_DECL_ALIAS_P (decl))
5600 ? DECL_ORIGINAL_TYPE (decl)
5601 : TREE_TYPE (decl)))
5603 TREE_TYPE (decl) = error_mark_node;
5604 return error_mark_node;
5607 if (is_partial)
5608 return process_partial_specialization (decl);
5610 args = current_template_args ();
5612 if (!ctx
5613 || TREE_CODE (ctx) == FUNCTION_DECL
5614 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5615 || (TREE_CODE (decl) == TYPE_DECL
5616 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5617 || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5619 if (DECL_LANG_SPECIFIC (decl)
5620 && DECL_TEMPLATE_INFO (decl)
5621 && DECL_TI_TEMPLATE (decl))
5622 tmpl = DECL_TI_TEMPLATE (decl);
5623 /* If DECL is a TYPE_DECL for a class-template, then there won't
5624 be DECL_LANG_SPECIFIC. The information equivalent to
5625 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
5626 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5627 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5628 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5630 /* Since a template declaration already existed for this
5631 class-type, we must be redeclaring it here. Make sure
5632 that the redeclaration is valid. */
5633 redeclare_class_template (TREE_TYPE (decl),
5634 current_template_parms,
5635 current_template_constraints ());
5636 /* We don't need to create a new TEMPLATE_DECL; just use the
5637 one we already had. */
5638 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5640 else
5642 tmpl = build_template_decl (decl, current_template_parms,
5643 member_template_p);
5644 new_template_p = 1;
5646 if (DECL_LANG_SPECIFIC (decl)
5647 && DECL_TEMPLATE_SPECIALIZATION (decl))
5649 /* A specialization of a member template of a template
5650 class. */
5651 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5652 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5653 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5657 else
5659 tree a, t, current, parms;
5660 int i;
5661 tree tinfo = get_template_info (decl);
5663 if (!tinfo)
5665 error ("template definition of non-template %q#D", decl);
5666 return error_mark_node;
5669 tmpl = TI_TEMPLATE (tinfo);
5671 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5672 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5673 && DECL_TEMPLATE_SPECIALIZATION (decl)
5674 && DECL_MEMBER_TEMPLATE_P (tmpl))
5676 tree new_tmpl;
5678 /* The declaration is a specialization of a member
5679 template, declared outside the class. Therefore, the
5680 innermost template arguments will be NULL, so we
5681 replace them with the arguments determined by the
5682 earlier call to check_explicit_specialization. */
5683 args = DECL_TI_ARGS (decl);
5685 new_tmpl
5686 = build_template_decl (decl, current_template_parms,
5687 member_template_p);
5688 DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5689 TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5690 DECL_TI_TEMPLATE (decl) = new_tmpl;
5691 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5692 DECL_TEMPLATE_INFO (new_tmpl)
5693 = build_template_info (tmpl, args);
5695 register_specialization (new_tmpl,
5696 most_general_template (tmpl),
5697 args,
5698 is_friend, 0);
5699 return decl;
5702 /* Make sure the template headers we got make sense. */
5704 parms = DECL_TEMPLATE_PARMS (tmpl);
5705 i = TMPL_PARMS_DEPTH (parms);
5706 if (TMPL_ARGS_DEPTH (args) != i)
5708 error ("expected %d levels of template parms for %q#D, got %d",
5709 i, decl, TMPL_ARGS_DEPTH (args));
5710 DECL_INTERFACE_KNOWN (decl) = 1;
5711 return error_mark_node;
5713 else
5714 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5716 a = TMPL_ARGS_LEVEL (args, i);
5717 t = INNERMOST_TEMPLATE_PARMS (parms);
5719 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5721 if (current == decl)
5722 error ("got %d template parameters for %q#D",
5723 TREE_VEC_LENGTH (a), decl);
5724 else
5725 error ("got %d template parameters for %q#T",
5726 TREE_VEC_LENGTH (a), current);
5727 error (" but %d required", TREE_VEC_LENGTH (t));
5728 /* Avoid crash in import_export_decl. */
5729 DECL_INTERFACE_KNOWN (decl) = 1;
5730 return error_mark_node;
5733 if (current == decl)
5734 current = ctx;
5735 else if (current == NULL_TREE)
5736 /* Can happen in erroneous input. */
5737 break;
5738 else
5739 current = get_containing_scope (current);
5742 /* Check that the parms are used in the appropriate qualifying scopes
5743 in the declarator. */
5744 if (!comp_template_args
5745 (TI_ARGS (tinfo),
5746 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5748 error ("template arguments to %qD do not match original "
5749 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5750 if (!uses_template_parms (TI_ARGS (tinfo)))
5751 inform (input_location, "use %<template<>%> for"
5752 " an explicit specialization");
5753 /* Avoid crash in import_export_decl. */
5754 DECL_INTERFACE_KNOWN (decl) = 1;
5755 return error_mark_node;
5759 DECL_TEMPLATE_RESULT (tmpl) = decl;
5760 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5762 /* Push template declarations for global functions and types. Note
5763 that we do not try to push a global template friend declared in a
5764 template class; such a thing may well depend on the template
5765 parameters of the class. */
5766 if (new_template_p && !ctx
5767 && !(is_friend && template_class_depth (current_class_type) > 0))
5769 tmpl = pushdecl_namespace_level (tmpl, is_friend);
5770 if (tmpl == error_mark_node)
5771 return error_mark_node;
5773 /* Hide template friend classes that haven't been declared yet. */
5774 if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5776 DECL_ANTICIPATED (tmpl) = 1;
5777 DECL_FRIEND_P (tmpl) = 1;
5781 if (is_primary)
5783 tree parms = DECL_TEMPLATE_PARMS (tmpl);
5785 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5787 /* Give template template parms a DECL_CONTEXT of the template
5788 for which they are a parameter. */
5789 parms = INNERMOST_TEMPLATE_PARMS (parms);
5790 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5792 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5793 if (TREE_CODE (parm) == TEMPLATE_DECL)
5794 DECL_CONTEXT (parm) = tmpl;
5797 if (TREE_CODE (decl) == TYPE_DECL
5798 && TYPE_DECL_ALIAS_P (decl)
5799 && complex_alias_template_p (tmpl))
5800 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5803 /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5804 back to its most general template. If TMPL is a specialization,
5805 ARGS may only have the innermost set of arguments. Add the missing
5806 argument levels if necessary. */
5807 if (DECL_TEMPLATE_INFO (tmpl))
5808 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5810 info = build_template_info (tmpl, args);
5812 if (DECL_IMPLICIT_TYPEDEF_P (decl))
5813 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5814 else
5816 if (is_primary)
5817 retrofit_lang_decl (decl);
5818 if (DECL_LANG_SPECIFIC (decl))
5819 DECL_TEMPLATE_INFO (decl) = info;
5822 if (flag_implicit_templates
5823 && !is_friend
5824 && TREE_PUBLIC (decl)
5825 && VAR_OR_FUNCTION_DECL_P (decl))
5826 /* Set DECL_COMDAT on template instantiations; if we force
5827 them to be emitted by explicit instantiation or -frepo,
5828 mark_needed will tell cgraph to do the right thing. */
5829 DECL_COMDAT (decl) = true;
5831 return DECL_TEMPLATE_RESULT (tmpl);
5834 tree
5835 push_template_decl (tree decl)
5837 return push_template_decl_real (decl, false);
5840 /* FN is an inheriting constructor that inherits from the constructor
5841 template INHERITED; turn FN into a constructor template with a matching
5842 template header. */
5844 tree
5845 add_inherited_template_parms (tree fn, tree inherited)
5847 tree inner_parms
5848 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5849 inner_parms = copy_node (inner_parms);
5850 tree parms
5851 = tree_cons (size_int (processing_template_decl + 1),
5852 inner_parms, current_template_parms);
5853 tree tmpl = build_template_decl (fn, parms, /*member*/true);
5854 tree args = template_parms_to_args (parms);
5855 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5856 TREE_TYPE (tmpl) = TREE_TYPE (fn);
5857 DECL_TEMPLATE_RESULT (tmpl) = fn;
5858 DECL_ARTIFICIAL (tmpl) = true;
5859 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5860 return tmpl;
5863 /* Called when a class template TYPE is redeclared with the indicated
5864 template PARMS, e.g.:
5866 template <class T> struct S;
5867 template <class T> struct S {}; */
5869 bool
5870 redeclare_class_template (tree type, tree parms, tree cons)
5872 tree tmpl;
5873 tree tmpl_parms;
5874 int i;
5876 if (!TYPE_TEMPLATE_INFO (type))
5878 error ("%qT is not a template type", type);
5879 return false;
5882 tmpl = TYPE_TI_TEMPLATE (type);
5883 if (!PRIMARY_TEMPLATE_P (tmpl))
5884 /* The type is nested in some template class. Nothing to worry
5885 about here; there are no new template parameters for the nested
5886 type. */
5887 return true;
5889 if (!parms)
5891 error ("template specifiers not specified in declaration of %qD",
5892 tmpl);
5893 return false;
5896 parms = INNERMOST_TEMPLATE_PARMS (parms);
5897 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5899 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5901 error_n (input_location, TREE_VEC_LENGTH (parms),
5902 "redeclared with %d template parameter",
5903 "redeclared with %d template parameters",
5904 TREE_VEC_LENGTH (parms));
5905 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5906 "previous declaration %qD used %d template parameter",
5907 "previous declaration %qD used %d template parameters",
5908 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5909 return false;
5912 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5914 tree tmpl_parm;
5915 tree parm;
5916 tree tmpl_default;
5917 tree parm_default;
5919 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5920 || TREE_VEC_ELT (parms, i) == error_mark_node)
5921 continue;
5923 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5924 if (error_operand_p (tmpl_parm))
5925 return false;
5927 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5928 tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5929 parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5931 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5932 TEMPLATE_DECL. */
5933 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5934 || (TREE_CODE (tmpl_parm) != TYPE_DECL
5935 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5936 || (TREE_CODE (tmpl_parm) != PARM_DECL
5937 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5938 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5939 || (TREE_CODE (tmpl_parm) == PARM_DECL
5940 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5941 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5943 error ("template parameter %q+#D", tmpl_parm);
5944 error ("redeclared here as %q#D", parm);
5945 return false;
5948 if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5950 /* We have in [temp.param]:
5952 A template-parameter may not be given default arguments
5953 by two different declarations in the same scope. */
5954 error_at (input_location, "redefinition of default argument for %q#D", parm);
5955 inform (DECL_SOURCE_LOCATION (tmpl_parm),
5956 "original definition appeared here");
5957 return false;
5960 if (parm_default != NULL_TREE)
5961 /* Update the previous template parameters (which are the ones
5962 that will really count) with the new default value. */
5963 TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5964 else if (tmpl_default != NULL_TREE)
5965 /* Update the new parameters, too; they'll be used as the
5966 parameters for any members. */
5967 TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5969 /* Give each template template parm in this redeclaration a
5970 DECL_CONTEXT of the template for which they are a parameter. */
5971 if (TREE_CODE (parm) == TEMPLATE_DECL)
5973 gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5974 DECL_CONTEXT (parm) = tmpl;
5977 if (TREE_CODE (parm) == TYPE_DECL)
5978 TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
5981 // Cannot redeclare a class template with a different set of constraints.
5982 if (!equivalent_constraints (get_constraints (tmpl), cons))
5984 error_at (input_location, "redeclaration %q#D with different "
5985 "constraints", tmpl);
5986 inform (DECL_SOURCE_LOCATION (tmpl),
5987 "original declaration appeared here");
5990 return true;
5993 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5994 to be used when the caller has already checked
5995 (processing_template_decl
5996 && !instantiation_dependent_expression_p (expr)
5997 && potential_constant_expression (expr))
5998 and cleared processing_template_decl. */
6000 tree
6001 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6003 return tsubst_copy_and_build (expr,
6004 /*args=*/NULL_TREE,
6005 complain,
6006 /*in_decl=*/NULL_TREE,
6007 /*function_p=*/false,
6008 /*integral_constant_expression_p=*/true);
6011 /* Simplify EXPR if it is a non-dependent expression. Returns the
6012 (possibly simplified) expression. */
6014 tree
6015 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6017 if (expr == NULL_TREE)
6018 return NULL_TREE;
6020 /* If we're in a template, but EXPR isn't value dependent, simplify
6021 it. We're supposed to treat:
6023 template <typename T> void f(T[1 + 1]);
6024 template <typename T> void f(T[2]);
6026 as two declarations of the same function, for example. */
6027 if (processing_template_decl
6028 && is_nondependent_constant_expression (expr))
6030 processing_template_decl_sentinel s;
6031 expr = instantiate_non_dependent_expr_internal (expr, complain);
6033 return expr;
6036 tree
6037 instantiate_non_dependent_expr (tree expr)
6039 return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6042 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6043 an uninstantiated expression. */
6045 tree
6046 instantiate_non_dependent_or_null (tree expr)
6048 if (expr == NULL_TREE)
6049 return NULL_TREE;
6050 if (processing_template_decl)
6052 if (!is_nondependent_constant_expression (expr))
6053 expr = NULL_TREE;
6054 else
6056 processing_template_decl_sentinel s;
6057 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6060 return expr;
6063 /* True iff T is a specialization of a variable template. */
6065 bool
6066 variable_template_specialization_p (tree t)
6068 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6069 return false;
6070 tree tmpl = DECL_TI_TEMPLATE (t);
6071 return variable_template_p (tmpl);
6074 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6075 template declaration, or a TYPE_DECL for an alias declaration. */
6077 bool
6078 alias_type_or_template_p (tree t)
6080 if (t == NULL_TREE)
6081 return false;
6082 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6083 || (TYPE_P (t)
6084 && TYPE_NAME (t)
6085 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6086 || DECL_ALIAS_TEMPLATE_P (t));
6089 /* Return TRUE iff T is a specialization of an alias template. */
6091 bool
6092 alias_template_specialization_p (const_tree t)
6094 /* It's an alias template specialization if it's an alias and its
6095 TYPE_NAME is a specialization of a primary template. */
6096 if (TYPE_ALIAS_P (t))
6097 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6098 return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6100 return false;
6103 /* An alias template is complex from a SFINAE perspective if a template-id
6104 using that alias can be ill-formed when the expansion is not, as with
6105 the void_t template. We determine this by checking whether the
6106 expansion for the alias template uses all its template parameters. */
6108 struct uses_all_template_parms_data
6110 int level;
6111 bool *seen;
6114 static int
6115 uses_all_template_parms_r (tree t, void *data_)
6117 struct uses_all_template_parms_data &data
6118 = *(struct uses_all_template_parms_data*)data_;
6119 tree idx = get_template_parm_index (t);
6121 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6122 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6123 return 0;
6126 static bool
6127 complex_alias_template_p (const_tree tmpl)
6129 struct uses_all_template_parms_data data;
6130 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6131 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6132 data.level = TMPL_PARMS_DEPTH (parms);
6133 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6134 data.seen = XALLOCAVEC (bool, len);
6135 for (int i = 0; i < len; ++i)
6136 data.seen[i] = false;
6138 for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6139 for (int i = 0; i < len; ++i)
6140 if (!data.seen[i])
6141 return true;
6142 return false;
6145 /* Return TRUE iff T is a specialization of a complex alias template with
6146 dependent template-arguments. */
6148 bool
6149 dependent_alias_template_spec_p (const_tree t)
6151 if (!alias_template_specialization_p (t))
6152 return false;
6154 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6155 if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6156 return false;
6158 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6159 if (!any_dependent_template_arguments_p (args))
6160 return false;
6162 return true;
6165 /* Return the number of innermost template parameters in TMPL. */
6167 static int
6168 num_innermost_template_parms (tree tmpl)
6170 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6171 return TREE_VEC_LENGTH (parms);
6174 /* Return either TMPL or another template that it is equivalent to under DR
6175 1286: An alias that just changes the name of a template is equivalent to
6176 the other template. */
6178 static tree
6179 get_underlying_template (tree tmpl)
6181 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6182 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6184 /* Determine if the alias is equivalent to an underlying template. */
6185 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6186 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6187 if (!tinfo)
6188 break;
6190 tree underlying = TI_TEMPLATE (tinfo);
6191 if (!PRIMARY_TEMPLATE_P (underlying)
6192 || (num_innermost_template_parms (tmpl)
6193 != num_innermost_template_parms (underlying)))
6194 break;
6196 tree alias_args = INNERMOST_TEMPLATE_ARGS
6197 (template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6198 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6199 break;
6201 /* Alias is equivalent. Strip it and repeat. */
6202 tmpl = underlying;
6205 return tmpl;
6208 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6209 must be a reference-to-function or a pointer-to-function type, as specified
6210 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6211 and check that the resulting function has external linkage. */
6213 static tree
6214 convert_nontype_argument_function (tree type, tree expr,
6215 tsubst_flags_t complain)
6217 tree fns = expr;
6218 tree fn, fn_no_ptr;
6219 linkage_kind linkage;
6221 fn = instantiate_type (type, fns, tf_none);
6222 if (fn == error_mark_node)
6223 return error_mark_node;
6225 if (value_dependent_expression_p (fn))
6226 goto accept;
6228 fn_no_ptr = strip_fnptr_conv (fn);
6229 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6230 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6231 if (BASELINK_P (fn_no_ptr))
6232 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6234 /* [temp.arg.nontype]/1
6236 A template-argument for a non-type, non-template template-parameter
6237 shall be one of:
6238 [...]
6239 -- the address of an object or function with external [C++11: or
6240 internal] linkage. */
6242 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6244 if (complain & tf_error)
6246 error ("%qE is not a valid template argument for type %qT",
6247 expr, type);
6248 if (TYPE_PTR_P (type))
6249 inform (input_location, "it must be the address of a function "
6250 "with external linkage");
6251 else
6252 inform (input_location, "it must be the name of a function with "
6253 "external linkage");
6255 return NULL_TREE;
6258 linkage = decl_linkage (fn_no_ptr);
6259 if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6261 if (complain & tf_error)
6263 if (cxx_dialect >= cxx11)
6264 error ("%qE is not a valid template argument for type %qT "
6265 "because %qD has no linkage",
6266 expr, type, fn_no_ptr);
6267 else
6268 error ("%qE is not a valid template argument for type %qT "
6269 "because %qD does not have external linkage",
6270 expr, type, fn_no_ptr);
6272 return NULL_TREE;
6275 accept:
6276 if (TYPE_REF_P (type))
6278 if (REFERENCE_REF_P (fn))
6279 fn = TREE_OPERAND (fn, 0);
6280 else
6281 fn = build_address (fn);
6283 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6284 fn = build_nop (type, fn);
6286 return fn;
6289 /* Subroutine of convert_nontype_argument.
6290 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6291 Emit an error otherwise. */
6293 static bool
6294 check_valid_ptrmem_cst_expr (tree type, tree expr,
6295 tsubst_flags_t complain)
6297 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6298 tree orig_expr = expr;
6299 STRIP_NOPS (expr);
6300 if (null_ptr_cst_p (expr))
6301 return true;
6302 if (TREE_CODE (expr) == PTRMEM_CST
6303 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6304 PTRMEM_CST_CLASS (expr)))
6305 return true;
6306 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6307 return true;
6308 if (processing_template_decl
6309 && TREE_CODE (expr) == ADDR_EXPR
6310 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6311 return true;
6312 if (complain & tf_error)
6314 error_at (loc, "%qE is not a valid template argument for type %qT",
6315 orig_expr, type);
6316 if (TREE_CODE (expr) != PTRMEM_CST)
6317 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6318 else
6319 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6321 return false;
6324 /* Returns TRUE iff the address of OP is value-dependent.
6326 14.6.2.4 [temp.dep.temp]:
6327 A non-integral non-type template-argument is dependent if its type is
6328 dependent or it has either of the following forms
6329 qualified-id
6330 & qualified-id
6331 and contains a nested-name-specifier which specifies a class-name that
6332 names a dependent type.
6334 We generalize this to just say that the address of a member of a
6335 dependent class is value-dependent; the above doesn't cover the
6336 address of a static data member named with an unqualified-id. */
6338 static bool
6339 has_value_dependent_address (tree op)
6341 /* We could use get_inner_reference here, but there's no need;
6342 this is only relevant for template non-type arguments, which
6343 can only be expressed as &id-expression. */
6344 if (DECL_P (op))
6346 tree ctx = CP_DECL_CONTEXT (op);
6347 if (TYPE_P (ctx) && dependent_type_p (ctx))
6348 return true;
6351 return false;
6354 /* The next set of functions are used for providing helpful explanatory
6355 diagnostics for failed overload resolution. Their messages should be
6356 indented by two spaces for consistency with the messages in
6357 call.c */
6359 static int
6360 unify_success (bool /*explain_p*/)
6362 return 0;
6365 /* Other failure functions should call this one, to provide a single function
6366 for setting a breakpoint on. */
6368 static int
6369 unify_invalid (bool /*explain_p*/)
6371 return 1;
6374 static int
6375 unify_parameter_deduction_failure (bool explain_p, tree parm)
6377 if (explain_p)
6378 inform (input_location,
6379 " couldn't deduce template parameter %qD", parm);
6380 return unify_invalid (explain_p);
6383 static int
6384 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6386 if (explain_p)
6387 inform (input_location,
6388 " types %qT and %qT have incompatible cv-qualifiers",
6389 parm, arg);
6390 return unify_invalid (explain_p);
6393 static int
6394 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6396 if (explain_p)
6397 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6398 return unify_invalid (explain_p);
6401 static int
6402 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6404 if (explain_p)
6405 inform (input_location,
6406 " template parameter %qD is not a parameter pack, but "
6407 "argument %qD is",
6408 parm, arg);
6409 return unify_invalid (explain_p);
6412 static int
6413 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6415 if (explain_p)
6416 inform (input_location,
6417 " template argument %qE does not match "
6418 "pointer-to-member constant %qE",
6419 arg, parm);
6420 return unify_invalid (explain_p);
6423 static int
6424 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6426 if (explain_p)
6427 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6428 return unify_invalid (explain_p);
6431 static int
6432 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6434 if (explain_p)
6435 inform (input_location,
6436 " inconsistent parameter pack deduction with %qT and %qT",
6437 old_arg, new_arg);
6438 return unify_invalid (explain_p);
6441 static int
6442 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6444 if (explain_p)
6446 if (TYPE_P (parm))
6447 inform (input_location,
6448 " deduced conflicting types for parameter %qT (%qT and %qT)",
6449 parm, first, second);
6450 else
6451 inform (input_location,
6452 " deduced conflicting values for non-type parameter "
6453 "%qE (%qE and %qE)", parm, first, second);
6455 return unify_invalid (explain_p);
6458 static int
6459 unify_vla_arg (bool explain_p, tree arg)
6461 if (explain_p)
6462 inform (input_location,
6463 " variable-sized array type %qT is not "
6464 "a valid template argument",
6465 arg);
6466 return unify_invalid (explain_p);
6469 static int
6470 unify_method_type_error (bool explain_p, tree arg)
6472 if (explain_p)
6473 inform (input_location,
6474 " member function type %qT is not a valid template argument",
6475 arg);
6476 return unify_invalid (explain_p);
6479 static int
6480 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6482 if (explain_p)
6484 if (least_p)
6485 inform_n (input_location, wanted,
6486 " candidate expects at least %d argument, %d provided",
6487 " candidate expects at least %d arguments, %d provided",
6488 wanted, have);
6489 else
6490 inform_n (input_location, wanted,
6491 " candidate expects %d argument, %d provided",
6492 " candidate expects %d arguments, %d provided",
6493 wanted, have);
6495 return unify_invalid (explain_p);
6498 static int
6499 unify_too_many_arguments (bool explain_p, int have, int wanted)
6501 return unify_arity (explain_p, have, wanted);
6504 static int
6505 unify_too_few_arguments (bool explain_p, int have, int wanted,
6506 bool least_p = false)
6508 return unify_arity (explain_p, have, wanted, least_p);
6511 static int
6512 unify_arg_conversion (bool explain_p, tree to_type,
6513 tree from_type, tree arg)
6515 if (explain_p)
6516 inform (EXPR_LOC_OR_LOC (arg, input_location),
6517 " cannot convert %qE (type %qT) to type %qT",
6518 arg, from_type, to_type);
6519 return unify_invalid (explain_p);
6522 static int
6523 unify_no_common_base (bool explain_p, enum template_base_result r,
6524 tree parm, tree arg)
6526 if (explain_p)
6527 switch (r)
6529 case tbr_ambiguous_baseclass:
6530 inform (input_location, " %qT is an ambiguous base class of %qT",
6531 parm, arg);
6532 break;
6533 default:
6534 inform (input_location, " %qT is not derived from %qT", arg, parm);
6535 break;
6537 return unify_invalid (explain_p);
6540 static int
6541 unify_inconsistent_template_template_parameters (bool explain_p)
6543 if (explain_p)
6544 inform (input_location,
6545 " template parameters of a template template argument are "
6546 "inconsistent with other deduced template arguments");
6547 return unify_invalid (explain_p);
6550 static int
6551 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6553 if (explain_p)
6554 inform (input_location,
6555 " can't deduce a template for %qT from non-template type %qT",
6556 parm, arg);
6557 return unify_invalid (explain_p);
6560 static int
6561 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6563 if (explain_p)
6564 inform (input_location,
6565 " template argument %qE does not match %qE", arg, parm);
6566 return unify_invalid (explain_p);
6569 /* Attempt to convert the non-type template parameter EXPR to the
6570 indicated TYPE. If the conversion is successful, return the
6571 converted value. If the conversion is unsuccessful, return
6572 NULL_TREE if we issued an error message, or error_mark_node if we
6573 did not. We issue error messages for out-and-out bad template
6574 parameters, but not simply because the conversion failed, since we
6575 might be just trying to do argument deduction. Both TYPE and EXPR
6576 must be non-dependent.
6578 The conversion follows the special rules described in
6579 [temp.arg.nontype], and it is much more strict than an implicit
6580 conversion.
6582 This function is called twice for each template argument (see
6583 lookup_template_class for a more accurate description of this
6584 problem). This means that we need to handle expressions which
6585 are not valid in a C++ source, but can be created from the
6586 first call (for instance, casts to perform conversions). These
6587 hacks can go away after we fix the double coercion problem. */
6589 static tree
6590 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6592 tree expr_type;
6593 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6594 tree orig_expr = expr;
6596 /* Detect immediately string literals as invalid non-type argument.
6597 This special-case is not needed for correctness (we would easily
6598 catch this later), but only to provide better diagnostic for this
6599 common user mistake. As suggested by DR 100, we do not mention
6600 linkage issues in the diagnostic as this is not the point. */
6601 /* FIXME we're making this OK. */
6602 if (TREE_CODE (expr) == STRING_CST)
6604 if (complain & tf_error)
6605 error ("%qE is not a valid template argument for type %qT "
6606 "because string literals can never be used in this context",
6607 expr, type);
6608 return NULL_TREE;
6611 /* Add the ADDR_EXPR now for the benefit of
6612 value_dependent_expression_p. */
6613 if (TYPE_PTROBV_P (type)
6614 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6616 expr = decay_conversion (expr, complain);
6617 if (expr == error_mark_node)
6618 return error_mark_node;
6621 /* If we are in a template, EXPR may be non-dependent, but still
6622 have a syntactic, rather than semantic, form. For example, EXPR
6623 might be a SCOPE_REF, rather than the VAR_DECL to which the
6624 SCOPE_REF refers. Preserving the qualifying scope is necessary
6625 so that access checking can be performed when the template is
6626 instantiated -- but here we need the resolved form so that we can
6627 convert the argument. */
6628 bool non_dep = false;
6629 if (TYPE_REF_OBJ_P (type)
6630 && has_value_dependent_address (expr))
6631 /* If we want the address and it's value-dependent, don't fold. */;
6632 else if (processing_template_decl
6633 && is_nondependent_constant_expression (expr))
6634 non_dep = true;
6635 if (error_operand_p (expr))
6636 return error_mark_node;
6637 expr_type = TREE_TYPE (expr);
6639 /* If the argument is non-dependent, perform any conversions in
6640 non-dependent context as well. */
6641 processing_template_decl_sentinel s (non_dep);
6642 if (non_dep)
6643 expr = instantiate_non_dependent_expr_internal (expr, complain);
6645 if (value_dependent_expression_p (expr))
6646 expr = canonicalize_expr_argument (expr, complain);
6648 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6649 to a non-type argument of "nullptr". */
6650 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6651 expr = fold_simple (convert (type, expr));
6653 /* In C++11, integral or enumeration non-type template arguments can be
6654 arbitrary constant expressions. Pointer and pointer to
6655 member arguments can be general constant expressions that evaluate
6656 to a null value, but otherwise still need to be of a specific form. */
6657 if (cxx_dialect >= cxx11)
6659 if (TREE_CODE (expr) == PTRMEM_CST)
6660 /* A PTRMEM_CST is already constant, and a valid template
6661 argument for a parameter of pointer to member type, we just want
6662 to leave it in that form rather than lower it to a
6663 CONSTRUCTOR. */;
6664 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6665 || cxx_dialect >= cxx17)
6667 /* C++17: A template-argument for a non-type template-parameter shall
6668 be a converted constant expression (8.20) of the type of the
6669 template-parameter. */
6670 expr = build_converted_constant_expr (type, expr, complain);
6671 if (expr == error_mark_node)
6672 return error_mark_node;
6673 expr = maybe_constant_value (expr);
6674 expr = convert_from_reference (expr);
6676 else if (TYPE_PTR_OR_PTRMEM_P (type))
6678 tree folded = maybe_constant_value (expr);
6679 if (TYPE_PTR_P (type) ? integer_zerop (folded)
6680 : null_member_pointer_value_p (folded))
6681 expr = folded;
6685 if (TYPE_REF_P (type))
6686 expr = mark_lvalue_use (expr);
6687 else
6688 expr = mark_rvalue_use (expr);
6690 /* HACK: Due to double coercion, we can get a
6691 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6692 which is the tree that we built on the first call (see
6693 below when coercing to reference to object or to reference to
6694 function). We just strip everything and get to the arg.
6695 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6696 for examples. */
6697 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6699 tree probe_type, probe = expr;
6700 if (REFERENCE_REF_P (probe))
6701 probe = TREE_OPERAND (probe, 0);
6702 probe_type = TREE_TYPE (probe);
6703 if (TREE_CODE (probe) == NOP_EXPR)
6705 /* ??? Maybe we could use convert_from_reference here, but we
6706 would need to relax its constraints because the NOP_EXPR
6707 could actually change the type to something more cv-qualified,
6708 and this is not folded by convert_from_reference. */
6709 tree addr = TREE_OPERAND (probe, 0);
6710 if (TYPE_REF_P (probe_type)
6711 && TREE_CODE (addr) == ADDR_EXPR
6712 && TYPE_PTR_P (TREE_TYPE (addr))
6713 && (same_type_ignoring_top_level_qualifiers_p
6714 (TREE_TYPE (probe_type),
6715 TREE_TYPE (TREE_TYPE (addr)))))
6717 expr = TREE_OPERAND (addr, 0);
6718 expr_type = TREE_TYPE (probe_type);
6723 /* [temp.arg.nontype]/5, bullet 1
6725 For a non-type template-parameter of integral or enumeration type,
6726 integral promotions (_conv.prom_) and integral conversions
6727 (_conv.integral_) are applied. */
6728 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6730 if (cxx_dialect < cxx11)
6732 tree t = build_converted_constant_expr (type, expr, complain);
6733 t = maybe_constant_value (t);
6734 if (t != error_mark_node)
6735 expr = t;
6738 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6739 return error_mark_node;
6741 /* Notice that there are constant expressions like '4 % 0' which
6742 do not fold into integer constants. */
6743 if (TREE_CODE (expr) != INTEGER_CST
6744 && !value_dependent_expression_p (expr))
6746 if (complain & tf_error)
6748 int errs = errorcount, warns = warningcount + werrorcount;
6749 if (!require_potential_constant_expression (expr))
6750 expr = error_mark_node;
6751 else
6752 expr = cxx_constant_value (expr);
6753 if (errorcount > errs || warningcount + werrorcount > warns)
6754 inform (loc, "in template argument for type %qT", type);
6755 if (expr == error_mark_node)
6756 return NULL_TREE;
6757 /* else cxx_constant_value complained but gave us
6758 a real constant, so go ahead. */
6759 if (TREE_CODE (expr) != INTEGER_CST)
6761 /* Some assemble time constant expressions like
6762 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6763 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6764 as we can emit them into .rodata initializers of
6765 variables, yet they can't fold into an INTEGER_CST at
6766 compile time. Refuse them here. */
6767 gcc_checking_assert (reduced_constant_expression_p (expr));
6768 error_at (loc, "template argument %qE for type %qT not "
6769 "a constant integer", expr, type);
6770 return NULL_TREE;
6773 else
6774 return NULL_TREE;
6777 /* Avoid typedef problems. */
6778 if (TREE_TYPE (expr) != type)
6779 expr = fold_convert (type, expr);
6781 /* [temp.arg.nontype]/5, bullet 2
6783 For a non-type template-parameter of type pointer to object,
6784 qualification conversions (_conv.qual_) and the array-to-pointer
6785 conversion (_conv.array_) are applied. */
6786 else if (TYPE_PTROBV_P (type))
6788 tree decayed = expr;
6790 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6791 decay_conversion or an explicit cast. If it's a problematic cast,
6792 we'll complain about it below. */
6793 if (TREE_CODE (expr) == NOP_EXPR)
6795 tree probe = expr;
6796 STRIP_NOPS (probe);
6797 if (TREE_CODE (probe) == ADDR_EXPR
6798 && TYPE_PTR_P (TREE_TYPE (probe)))
6800 expr = probe;
6801 expr_type = TREE_TYPE (expr);
6805 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
6807 A template-argument for a non-type, non-template template-parameter
6808 shall be one of: [...]
6810 -- the name of a non-type template-parameter;
6811 -- the address of an object or function with external linkage, [...]
6812 expressed as "& id-expression" where the & is optional if the name
6813 refers to a function or array, or if the corresponding
6814 template-parameter is a reference.
6816 Here, we do not care about functions, as they are invalid anyway
6817 for a parameter of type pointer-to-object. */
6819 if (value_dependent_expression_p (expr))
6820 /* Non-type template parameters are OK. */
6822 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6823 /* Null pointer values are OK in C++11. */;
6824 else if (TREE_CODE (expr) != ADDR_EXPR)
6826 if (VAR_P (expr))
6828 if (complain & tf_error)
6829 error ("%qD is not a valid template argument "
6830 "because %qD is a variable, not the address of "
6831 "a variable", orig_expr, expr);
6832 return NULL_TREE;
6834 if (INDIRECT_TYPE_P (expr_type))
6836 if (complain & tf_error)
6837 error ("%qE is not a valid template argument for %qT "
6838 "because it is not the address of a variable",
6839 orig_expr, type);
6840 return NULL_TREE;
6842 /* Other values, like integer constants, might be valid
6843 non-type arguments of some other type. */
6844 return error_mark_node;
6846 else
6848 tree decl = TREE_OPERAND (expr, 0);
6850 if (!VAR_P (decl))
6852 if (complain & tf_error)
6853 error ("%qE is not a valid template argument of type %qT "
6854 "because %qE is not a variable", orig_expr, type, decl);
6855 return NULL_TREE;
6857 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6859 if (complain & tf_error)
6860 error ("%qE is not a valid template argument of type %qT "
6861 "because %qD does not have external linkage",
6862 orig_expr, type, decl);
6863 return NULL_TREE;
6865 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6866 && decl_linkage (decl) == lk_none)
6868 if (complain & tf_error)
6869 error ("%qE is not a valid template argument of type %qT "
6870 "because %qD has no linkage", orig_expr, type, decl);
6871 return NULL_TREE;
6873 /* C++17: For a non-type template-parameter of reference or pointer
6874 type, the value of the constant expression shall not refer to (or
6875 for a pointer type, shall not be the address of):
6876 * a subobject (4.5),
6877 * a temporary object (15.2),
6878 * a string literal (5.13.5),
6879 * the result of a typeid expression (8.2.8), or
6880 * a predefined __func__ variable (11.4.1). */
6881 else if (DECL_ARTIFICIAL (decl))
6883 if (complain & tf_error)
6884 error ("the address of %qD is not a valid template argument",
6885 decl);
6886 return NULL_TREE;
6888 else if (!same_type_ignoring_top_level_qualifiers_p
6889 (strip_array_types (TREE_TYPE (type)),
6890 strip_array_types (TREE_TYPE (decl))))
6892 if (complain & tf_error)
6893 error ("the address of the %qT subobject of %qD is not a "
6894 "valid template argument", TREE_TYPE (type), decl);
6895 return NULL_TREE;
6897 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6899 if (complain & tf_error)
6900 error ("the address of %qD is not a valid template argument "
6901 "because it does not have static storage duration",
6902 decl);
6903 return NULL_TREE;
6907 expr = decayed;
6909 expr = perform_qualification_conversions (type, expr);
6910 if (expr == error_mark_node)
6911 return error_mark_node;
6913 /* [temp.arg.nontype]/5, bullet 3
6915 For a non-type template-parameter of type reference to object, no
6916 conversions apply. The type referred to by the reference may be more
6917 cv-qualified than the (otherwise identical) type of the
6918 template-argument. The template-parameter is bound directly to the
6919 template-argument, which must be an lvalue. */
6920 else if (TYPE_REF_OBJ_P (type))
6922 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6923 expr_type))
6924 return error_mark_node;
6926 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6928 if (complain & tf_error)
6929 error ("%qE is not a valid template argument for type %qT "
6930 "because of conflicts in cv-qualification", expr, type);
6931 return NULL_TREE;
6934 if (!lvalue_p (expr))
6936 if (complain & tf_error)
6937 error ("%qE is not a valid template argument for type %qT "
6938 "because it is not an lvalue", expr, type);
6939 return NULL_TREE;
6942 /* [temp.arg.nontype]/1
6944 A template-argument for a non-type, non-template template-parameter
6945 shall be one of: [...]
6947 -- the address of an object or function with external linkage. */
6948 if (INDIRECT_REF_P (expr)
6949 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6951 expr = TREE_OPERAND (expr, 0);
6952 if (DECL_P (expr))
6954 if (complain & tf_error)
6955 error ("%q#D is not a valid template argument for type %qT "
6956 "because a reference variable does not have a constant "
6957 "address", expr, type);
6958 return NULL_TREE;
6962 if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
6963 && value_dependent_expression_p (expr))
6964 /* OK, dependent reference. We don't want to ask whether a DECL is
6965 itself value-dependent, since what we want here is its address. */;
6966 else
6968 if (!DECL_P (expr))
6970 if (complain & tf_error)
6971 error ("%qE is not a valid template argument for type %qT "
6972 "because it is not an object with linkage",
6973 expr, type);
6974 return NULL_TREE;
6977 /* DR 1155 allows internal linkage in C++11 and up. */
6978 linkage_kind linkage = decl_linkage (expr);
6979 if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
6981 if (complain & tf_error)
6982 error ("%qE is not a valid template argument for type %qT "
6983 "because object %qD does not have linkage",
6984 expr, type, expr);
6985 return NULL_TREE;
6988 expr = build_address (expr);
6991 if (!same_type_p (type, TREE_TYPE (expr)))
6992 expr = build_nop (type, expr);
6994 /* [temp.arg.nontype]/5, bullet 4
6996 For a non-type template-parameter of type pointer to function, only
6997 the function-to-pointer conversion (_conv.func_) is applied. If the
6998 template-argument represents a set of overloaded functions (or a
6999 pointer to such), the matching function is selected from the set
7000 (_over.over_). */
7001 else if (TYPE_PTRFN_P (type))
7003 /* If the argument is a template-id, we might not have enough
7004 context information to decay the pointer. */
7005 if (!type_unknown_p (expr_type))
7007 expr = decay_conversion (expr, complain);
7008 if (expr == error_mark_node)
7009 return error_mark_node;
7012 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7013 /* Null pointer values are OK in C++11. */
7014 return perform_qualification_conversions (type, expr);
7016 expr = convert_nontype_argument_function (type, expr, complain);
7017 if (!expr || expr == error_mark_node)
7018 return expr;
7020 /* [temp.arg.nontype]/5, bullet 5
7022 For a non-type template-parameter of type reference to function, no
7023 conversions apply. If the template-argument represents a set of
7024 overloaded functions, the matching function is selected from the set
7025 (_over.over_). */
7026 else if (TYPE_REFFN_P (type))
7028 if (TREE_CODE (expr) == ADDR_EXPR)
7030 if (complain & tf_error)
7032 error ("%qE is not a valid template argument for type %qT "
7033 "because it is a pointer", expr, type);
7034 inform (input_location, "try using %qE instead",
7035 TREE_OPERAND (expr, 0));
7037 return NULL_TREE;
7040 expr = convert_nontype_argument_function (type, expr, complain);
7041 if (!expr || expr == error_mark_node)
7042 return expr;
7044 /* [temp.arg.nontype]/5, bullet 6
7046 For a non-type template-parameter of type pointer to member function,
7047 no conversions apply. If the template-argument represents a set of
7048 overloaded member functions, the matching member function is selected
7049 from the set (_over.over_). */
7050 else if (TYPE_PTRMEMFUNC_P (type))
7052 expr = instantiate_type (type, expr, tf_none);
7053 if (expr == error_mark_node)
7054 return error_mark_node;
7056 /* [temp.arg.nontype] bullet 1 says the pointer to member
7057 expression must be a pointer-to-member constant. */
7058 if (!value_dependent_expression_p (expr)
7059 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7060 return NULL_TREE;
7062 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7063 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7064 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7065 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7067 /* [temp.arg.nontype]/5, bullet 7
7069 For a non-type template-parameter of type pointer to data member,
7070 qualification conversions (_conv.qual_) are applied. */
7071 else if (TYPE_PTRDATAMEM_P (type))
7073 /* [temp.arg.nontype] bullet 1 says the pointer to member
7074 expression must be a pointer-to-member constant. */
7075 if (!value_dependent_expression_p (expr)
7076 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7077 return NULL_TREE;
7079 expr = perform_qualification_conversions (type, expr);
7080 if (expr == error_mark_node)
7081 return expr;
7083 else if (NULLPTR_TYPE_P (type))
7085 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7087 if (complain & tf_error)
7088 error ("%qE is not a valid template argument for type %qT "
7089 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7090 return NULL_TREE;
7092 return expr;
7094 /* A template non-type parameter must be one of the above. */
7095 else
7096 gcc_unreachable ();
7098 /* Sanity check: did we actually convert the argument to the
7099 right type? */
7100 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7101 (type, TREE_TYPE (expr)));
7102 return convert_from_reference (expr);
7105 /* Subroutine of coerce_template_template_parms, which returns 1 if
7106 PARM_PARM and ARG_PARM match using the rule for the template
7107 parameters of template template parameters. Both PARM and ARG are
7108 template parameters; the rest of the arguments are the same as for
7109 coerce_template_template_parms.
7111 static int
7112 coerce_template_template_parm (tree parm,
7113 tree arg,
7114 tsubst_flags_t complain,
7115 tree in_decl,
7116 tree outer_args)
7118 if (arg == NULL_TREE || error_operand_p (arg)
7119 || parm == NULL_TREE || error_operand_p (parm))
7120 return 0;
7122 if (TREE_CODE (arg) != TREE_CODE (parm))
7123 return 0;
7125 switch (TREE_CODE (parm))
7127 case TEMPLATE_DECL:
7128 /* We encounter instantiations of templates like
7129 template <template <template <class> class> class TT>
7130 class C; */
7132 tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7133 tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7135 if (!coerce_template_template_parms
7136 (parmparm, argparm, complain, in_decl, outer_args))
7137 return 0;
7139 /* Fall through. */
7141 case TYPE_DECL:
7142 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7143 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7144 /* Argument is a parameter pack but parameter is not. */
7145 return 0;
7146 break;
7148 case PARM_DECL:
7149 /* The tsubst call is used to handle cases such as
7151 template <int> class C {};
7152 template <class T, template <T> class TT> class D {};
7153 D<int, C> d;
7155 i.e. the parameter list of TT depends on earlier parameters. */
7156 if (!uses_template_parms (TREE_TYPE (arg)))
7158 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7159 if (!uses_template_parms (t)
7160 && !same_type_p (t, TREE_TYPE (arg)))
7161 return 0;
7164 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7165 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7166 /* Argument is a parameter pack but parameter is not. */
7167 return 0;
7169 break;
7171 default:
7172 gcc_unreachable ();
7175 return 1;
7178 /* Coerce template argument list ARGLIST for use with template
7179 template-parameter TEMPL. */
7181 static tree
7182 coerce_template_args_for_ttp (tree templ, tree arglist,
7183 tsubst_flags_t complain)
7185 /* Consider an example where a template template parameter declared as
7187 template <class T, class U = std::allocator<T> > class TT
7189 The template parameter level of T and U are one level larger than
7190 of TT. To proper process the default argument of U, say when an
7191 instantiation `TT<int>' is seen, we need to build the full
7192 arguments containing {int} as the innermost level. Outer levels,
7193 available when not appearing as default template argument, can be
7194 obtained from the arguments of the enclosing template.
7196 Suppose that TT is later substituted with std::vector. The above
7197 instantiation is `TT<int, std::allocator<T> >' with TT at
7198 level 1, and T at level 2, while the template arguments at level 1
7199 becomes {std::vector} and the inner level 2 is {int}. */
7201 tree outer = DECL_CONTEXT (templ);
7202 if (outer)
7204 if (DECL_TEMPLATE_SPECIALIZATION (outer))
7205 /* We want arguments for the partial specialization, not arguments for
7206 the primary template. */
7207 outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7208 else
7209 outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7211 else if (current_template_parms)
7213 /* This is an argument of the current template, so we haven't set
7214 DECL_CONTEXT yet. */
7215 tree relevant_template_parms;
7217 /* Parameter levels that are greater than the level of the given
7218 template template parm are irrelevant. */
7219 relevant_template_parms = current_template_parms;
7220 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7221 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7222 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7224 outer = template_parms_to_args (relevant_template_parms);
7227 if (outer)
7228 arglist = add_to_template_args (outer, arglist);
7230 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7231 return coerce_template_parms (parmlist, arglist, templ,
7232 complain,
7233 /*require_all_args=*/true,
7234 /*use_default_args=*/true);
7237 /* A cache of template template parameters with match-all default
7238 arguments. */
7239 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7240 static void
7241 store_defaulted_ttp (tree v, tree t)
7243 if (!defaulted_ttp_cache)
7244 defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7245 defaulted_ttp_cache->put (v, t);
7247 static tree
7248 lookup_defaulted_ttp (tree v)
7250 if (defaulted_ttp_cache)
7251 if (tree *p = defaulted_ttp_cache->get (v))
7252 return *p;
7253 return NULL_TREE;
7256 /* T is a bound template template-parameter. Copy its arguments into default
7257 arguments of the template template-parameter's template parameters. */
7259 static tree
7260 add_defaults_to_ttp (tree otmpl)
7262 if (tree c = lookup_defaulted_ttp (otmpl))
7263 return c;
7265 tree ntmpl = copy_node (otmpl);
7267 tree ntype = copy_node (TREE_TYPE (otmpl));
7268 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7269 TYPE_MAIN_VARIANT (ntype) = ntype;
7270 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7271 TYPE_NAME (ntype) = ntmpl;
7272 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7274 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7275 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7276 TEMPLATE_PARM_DECL (idx) = ntmpl;
7277 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7279 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7280 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7281 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7282 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7283 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7285 tree o = TREE_VEC_ELT (vec, i);
7286 if (!template_parameter_pack_p (TREE_VALUE (o)))
7288 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7289 TREE_PURPOSE (n) = any_targ_node;
7293 store_defaulted_ttp (otmpl, ntmpl);
7294 return ntmpl;
7297 /* ARG is a bound potential template template-argument, and PARGS is a list
7298 of arguments for the corresponding template template-parameter. Adjust
7299 PARGS as appropriate for application to ARG's template, and if ARG is a
7300 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7301 arguments to the template template parameter. */
7303 static tree
7304 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7306 ++processing_template_decl;
7307 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7308 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7310 /* When comparing two template template-parameters in partial ordering,
7311 rewrite the one currently being used as an argument to have default
7312 arguments for all parameters. */
7313 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7314 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7315 if (pargs != error_mark_node)
7316 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7317 TYPE_TI_ARGS (arg));
7319 else
7321 tree aparms
7322 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7323 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7324 /*require_all*/true,
7325 /*use_default*/true);
7327 --processing_template_decl;
7328 return pargs;
7331 /* Subroutine of unify for the case when PARM is a
7332 BOUND_TEMPLATE_TEMPLATE_PARM. */
7334 static int
7335 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7336 bool explain_p)
7338 tree parmvec = TYPE_TI_ARGS (parm);
7339 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7341 /* The template template parm might be variadic and the argument
7342 not, so flatten both argument lists. */
7343 parmvec = expand_template_argument_pack (parmvec);
7344 argvec = expand_template_argument_pack (argvec);
7346 if (flag_new_ttp)
7348 /* In keeping with P0522R0, adjust P's template arguments
7349 to apply to A's template; then flatten it again. */
7350 tree nparmvec = parmvec;
7351 nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7352 nparmvec = expand_template_argument_pack (nparmvec);
7354 if (unify (tparms, targs, nparmvec, argvec,
7355 UNIFY_ALLOW_NONE, explain_p))
7356 return 1;
7358 /* If the P0522 adjustment eliminated a pack expansion, deduce
7359 empty packs. */
7360 if (flag_new_ttp
7361 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7362 && unify_pack_expansion (tparms, targs, parmvec, argvec,
7363 DEDUCE_EXACT, /*sub*/true, explain_p))
7364 return 1;
7366 else
7368 /* Deduce arguments T, i from TT<T> or TT<i>.
7369 We check each element of PARMVEC and ARGVEC individually
7370 rather than the whole TREE_VEC since they can have
7371 different number of elements, which is allowed under N2555. */
7373 int len = TREE_VEC_LENGTH (parmvec);
7375 /* Check if the parameters end in a pack, making them
7376 variadic. */
7377 int parm_variadic_p = 0;
7378 if (len > 0
7379 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7380 parm_variadic_p = 1;
7382 for (int i = 0; i < len - parm_variadic_p; ++i)
7383 /* If the template argument list of P contains a pack
7384 expansion that is not the last template argument, the
7385 entire template argument list is a non-deduced
7386 context. */
7387 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7388 return unify_success (explain_p);
7390 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7391 return unify_too_few_arguments (explain_p,
7392 TREE_VEC_LENGTH (argvec), len);
7394 for (int i = 0; i < len - parm_variadic_p; ++i)
7395 if (unify (tparms, targs,
7396 TREE_VEC_ELT (parmvec, i),
7397 TREE_VEC_ELT (argvec, i),
7398 UNIFY_ALLOW_NONE, explain_p))
7399 return 1;
7401 if (parm_variadic_p
7402 && unify_pack_expansion (tparms, targs,
7403 parmvec, argvec,
7404 DEDUCE_EXACT,
7405 /*subr=*/true, explain_p))
7406 return 1;
7409 return 0;
7412 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7413 template template parameters. Both PARM_PARMS and ARG_PARMS are
7414 vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7415 or PARM_DECL.
7417 Consider the example:
7418 template <class T> class A;
7419 template<template <class U> class TT> class B;
7421 For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7422 the parameters to A, and OUTER_ARGS contains A. */
7424 static int
7425 coerce_template_template_parms (tree parm_parms,
7426 tree arg_parms,
7427 tsubst_flags_t complain,
7428 tree in_decl,
7429 tree outer_args)
7431 int nparms, nargs, i;
7432 tree parm, arg;
7433 int variadic_p = 0;
7435 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7436 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7438 nparms = TREE_VEC_LENGTH (parm_parms);
7439 nargs = TREE_VEC_LENGTH (arg_parms);
7441 if (flag_new_ttp)
7443 /* P0522R0: A template template-parameter P is at least as specialized as
7444 a template template-argument A if, given the following rewrite to two
7445 function templates, the function template corresponding to P is at
7446 least as specialized as the function template corresponding to A
7447 according to the partial ordering rules for function templates
7448 ([temp.func.order]). Given an invented class template X with the
7449 template parameter list of A (including default arguments):
7451 * Each of the two function templates has the same template parameters,
7452 respectively, as P or A.
7454 * Each function template has a single function parameter whose type is
7455 a specialization of X with template arguments corresponding to the
7456 template parameters from the respective function template where, for
7457 each template parameter PP in the template parameter list of the
7458 function template, a corresponding template argument AA is formed. If
7459 PP declares a parameter pack, then AA is the pack expansion
7460 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7462 If the rewrite produces an invalid type, then P is not at least as
7463 specialized as A. */
7465 /* So coerce P's args to apply to A's parms, and then deduce between A's
7466 args and the converted args. If that succeeds, A is at least as
7467 specialized as P, so they match.*/
7468 tree pargs = template_parms_level_to_args (parm_parms);
7469 ++processing_template_decl;
7470 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7471 /*require_all*/true, /*use_default*/true);
7472 --processing_template_decl;
7473 if (pargs != error_mark_node)
7475 tree targs = make_tree_vec (nargs);
7476 tree aargs = template_parms_level_to_args (arg_parms);
7477 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7478 /*explain*/false))
7479 return 1;
7483 /* Determine whether we have a parameter pack at the end of the
7484 template template parameter's template parameter list. */
7485 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7487 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7489 if (error_operand_p (parm))
7490 return 0;
7492 switch (TREE_CODE (parm))
7494 case TEMPLATE_DECL:
7495 case TYPE_DECL:
7496 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7497 variadic_p = 1;
7498 break;
7500 case PARM_DECL:
7501 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7502 variadic_p = 1;
7503 break;
7505 default:
7506 gcc_unreachable ();
7510 if (nargs != nparms
7511 && !(variadic_p && nargs >= nparms - 1))
7512 return 0;
7514 /* Check all of the template parameters except the parameter pack at
7515 the end (if any). */
7516 for (i = 0; i < nparms - variadic_p; ++i)
7518 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7519 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7520 continue;
7522 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7523 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7525 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7526 outer_args))
7527 return 0;
7531 if (variadic_p)
7533 /* Check each of the template parameters in the template
7534 argument against the template parameter pack at the end of
7535 the template template parameter. */
7536 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7537 return 0;
7539 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7541 for (; i < nargs; ++i)
7543 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7544 continue;
7546 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7548 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7549 outer_args))
7550 return 0;
7554 return 1;
7557 /* Verifies that the deduced template arguments (in TARGS) for the
7558 template template parameters (in TPARMS) represent valid bindings,
7559 by comparing the template parameter list of each template argument
7560 to the template parameter list of its corresponding template
7561 template parameter, in accordance with DR150. This
7562 routine can only be called after all template arguments have been
7563 deduced. It will return TRUE if all of the template template
7564 parameter bindings are okay, FALSE otherwise. */
7565 bool
7566 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7568 int i, ntparms = TREE_VEC_LENGTH (tparms);
7569 bool ret = true;
7571 /* We're dealing with template parms in this process. */
7572 ++processing_template_decl;
7574 targs = INNERMOST_TEMPLATE_ARGS (targs);
7576 for (i = 0; i < ntparms; ++i)
7578 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7579 tree targ = TREE_VEC_ELT (targs, i);
7581 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7583 tree packed_args = NULL_TREE;
7584 int idx, len = 1;
7586 if (ARGUMENT_PACK_P (targ))
7588 /* Look inside the argument pack. */
7589 packed_args = ARGUMENT_PACK_ARGS (targ);
7590 len = TREE_VEC_LENGTH (packed_args);
7593 for (idx = 0; idx < len; ++idx)
7595 tree targ_parms = NULL_TREE;
7597 if (packed_args)
7598 /* Extract the next argument from the argument
7599 pack. */
7600 targ = TREE_VEC_ELT (packed_args, idx);
7602 if (PACK_EXPANSION_P (targ))
7603 /* Look at the pattern of the pack expansion. */
7604 targ = PACK_EXPANSION_PATTERN (targ);
7606 /* Extract the template parameters from the template
7607 argument. */
7608 if (TREE_CODE (targ) == TEMPLATE_DECL)
7609 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7610 else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7611 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7613 /* Verify that we can coerce the template template
7614 parameters from the template argument to the template
7615 parameter. This requires an exact match. */
7616 if (targ_parms
7617 && !coerce_template_template_parms
7618 (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7619 targ_parms,
7620 tf_none,
7621 tparm,
7622 targs))
7624 ret = false;
7625 goto out;
7631 out:
7633 --processing_template_decl;
7634 return ret;
7637 /* Since type attributes aren't mangled, we need to strip them from
7638 template type arguments. */
7640 static tree
7641 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7643 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7644 return arg;
7645 bool removed_attributes = false;
7646 tree canon = strip_typedefs (arg, &removed_attributes);
7647 if (removed_attributes
7648 && (complain & tf_warning))
7649 warning (OPT_Wignored_attributes,
7650 "ignoring attributes on template argument %qT", arg);
7651 return canon;
7654 /* And from inside dependent non-type arguments like sizeof(Type). */
7656 static tree
7657 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7659 if (!arg || arg == error_mark_node)
7660 return arg;
7661 bool removed_attributes = false;
7662 tree canon = strip_typedefs_expr (arg, &removed_attributes);
7663 if (removed_attributes
7664 && (complain & tf_warning))
7665 warning (OPT_Wignored_attributes,
7666 "ignoring attributes in template argument %qE", arg);
7667 return canon;
7670 // A template declaration can be substituted for a constrained
7671 // template template parameter only when the argument is more
7672 // constrained than the parameter.
7673 static bool
7674 is_compatible_template_arg (tree parm, tree arg)
7676 tree parm_cons = get_constraints (parm);
7678 /* For now, allow constrained template template arguments
7679 and unconstrained template template parameters. */
7680 if (parm_cons == NULL_TREE)
7681 return true;
7683 tree arg_cons = get_constraints (arg);
7685 // If the template parameter is constrained, we need to rewrite its
7686 // constraints in terms of the ARG's template parameters. This ensures
7687 // that all of the template parameter types will have the same depth.
7689 // Note that this is only valid when coerce_template_template_parm is
7690 // true for the innermost template parameters of PARM and ARG. In other
7691 // words, because coercion is successful, this conversion will be valid.
7692 if (parm_cons)
7694 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7695 parm_cons = tsubst_constraint_info (parm_cons,
7696 INNERMOST_TEMPLATE_ARGS (args),
7697 tf_none, NULL_TREE);
7698 if (parm_cons == error_mark_node)
7699 return false;
7702 return subsumes (parm_cons, arg_cons);
7705 // Convert a placeholder argument into a binding to the original
7706 // parameter. The original parameter is saved as the TREE_TYPE of
7707 // ARG.
7708 static inline tree
7709 convert_wildcard_argument (tree parm, tree arg)
7711 TREE_TYPE (arg) = parm;
7712 return arg;
7715 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7716 because one of them is dependent. But we need to represent the
7717 conversion for the benefit of cp_tree_equal. */
7719 static tree
7720 maybe_convert_nontype_argument (tree type, tree arg)
7722 /* Auto parms get no conversion. */
7723 if (type_uses_auto (type))
7724 return arg;
7725 /* We don't need or want to add this conversion now if we're going to use the
7726 argument for deduction. */
7727 if (value_dependent_expression_p (arg))
7728 return arg;
7730 type = cv_unqualified (type);
7731 tree argtype = TREE_TYPE (arg);
7732 if (same_type_p (type, argtype))
7733 return arg;
7735 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7736 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7737 return arg;
7740 /* Convert the indicated template ARG as necessary to match the
7741 indicated template PARM. Returns the converted ARG, or
7742 error_mark_node if the conversion was unsuccessful. Error and
7743 warning messages are issued under control of COMPLAIN. This
7744 conversion is for the Ith parameter in the parameter list. ARGS is
7745 the full set of template arguments deduced so far. */
7747 static tree
7748 convert_template_argument (tree parm,
7749 tree arg,
7750 tree args,
7751 tsubst_flags_t complain,
7752 int i,
7753 tree in_decl)
7755 tree orig_arg;
7756 tree val;
7757 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7759 if (parm == error_mark_node)
7760 return error_mark_node;
7762 /* Trivially convert placeholders. */
7763 if (TREE_CODE (arg) == WILDCARD_DECL)
7764 return convert_wildcard_argument (parm, arg);
7766 if (arg == any_targ_node)
7767 return arg;
7769 if (TREE_CODE (arg) == TREE_LIST
7770 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7772 /* The template argument was the name of some
7773 member function. That's usually
7774 invalid, but static members are OK. In any
7775 case, grab the underlying fields/functions
7776 and issue an error later if required. */
7777 orig_arg = TREE_VALUE (arg);
7778 TREE_TYPE (arg) = unknown_type_node;
7781 orig_arg = arg;
7783 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7784 requires_type = (TREE_CODE (parm) == TYPE_DECL
7785 || requires_tmpl_type);
7787 /* When determining whether an argument pack expansion is a template,
7788 look at the pattern. */
7789 if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7790 arg = PACK_EXPANSION_PATTERN (arg);
7792 /* Deal with an injected-class-name used as a template template arg. */
7793 if (requires_tmpl_type && CLASS_TYPE_P (arg))
7795 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7796 if (TREE_CODE (t) == TEMPLATE_DECL)
7798 if (cxx_dialect >= cxx11)
7799 /* OK under DR 1004. */;
7800 else if (complain & tf_warning_or_error)
7801 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7802 " used as template template argument", TYPE_NAME (arg));
7803 else if (flag_pedantic_errors)
7804 t = arg;
7806 arg = t;
7810 is_tmpl_type =
7811 ((TREE_CODE (arg) == TEMPLATE_DECL
7812 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7813 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7814 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7815 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7817 if (is_tmpl_type
7818 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7819 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7820 arg = TYPE_STUB_DECL (arg);
7822 is_type = TYPE_P (arg) || is_tmpl_type;
7824 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7825 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7827 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7829 if (complain & tf_error)
7830 error ("invalid use of destructor %qE as a type", orig_arg);
7831 return error_mark_node;
7834 permerror (input_location,
7835 "to refer to a type member of a template parameter, "
7836 "use %<typename %E%>", orig_arg);
7838 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7839 TREE_OPERAND (arg, 1),
7840 typename_type,
7841 complain);
7842 arg = orig_arg;
7843 is_type = 1;
7845 if (is_type != requires_type)
7847 if (in_decl)
7849 if (complain & tf_error)
7851 error ("type/value mismatch at argument %d in template "
7852 "parameter list for %qD",
7853 i + 1, in_decl);
7854 if (is_type)
7855 inform (input_location,
7856 " expected a constant of type %qT, got %qT",
7857 TREE_TYPE (parm),
7858 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7859 else if (requires_tmpl_type)
7860 inform (input_location,
7861 " expected a class template, got %qE", orig_arg);
7862 else
7863 inform (input_location,
7864 " expected a type, got %qE", orig_arg);
7867 return error_mark_node;
7869 if (is_tmpl_type ^ requires_tmpl_type)
7871 if (in_decl && (complain & tf_error))
7873 error ("type/value mismatch at argument %d in template "
7874 "parameter list for %qD",
7875 i + 1, in_decl);
7876 if (is_tmpl_type)
7877 inform (input_location,
7878 " expected a type, got %qT", DECL_NAME (arg));
7879 else
7880 inform (input_location,
7881 " expected a class template, got %qT", orig_arg);
7883 return error_mark_node;
7886 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7887 /* We already did the appropriate conversion when packing args. */
7888 val = orig_arg;
7889 else if (is_type)
7891 if (requires_tmpl_type)
7893 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7894 /* The number of argument required is not known yet.
7895 Just accept it for now. */
7896 val = orig_arg;
7897 else
7899 tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7900 tree argparm;
7902 /* Strip alias templates that are equivalent to another
7903 template. */
7904 arg = get_underlying_template (arg);
7905 argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7907 if (coerce_template_template_parms (parmparm, argparm,
7908 complain, in_decl,
7909 args))
7911 val = arg;
7913 /* TEMPLATE_TEMPLATE_PARM node is preferred over
7914 TEMPLATE_DECL. */
7915 if (val != error_mark_node)
7917 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7918 val = TREE_TYPE (val);
7919 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7920 val = make_pack_expansion (val, complain);
7923 else
7925 if (in_decl && (complain & tf_error))
7927 error ("type/value mismatch at argument %d in "
7928 "template parameter list for %qD",
7929 i + 1, in_decl);
7930 inform (input_location,
7931 " expected a template of type %qD, got %qT",
7932 parm, orig_arg);
7935 val = error_mark_node;
7938 // Check that the constraints are compatible before allowing the
7939 // substitution.
7940 if (val != error_mark_node)
7941 if (!is_compatible_template_arg (parm, arg))
7943 if (in_decl && (complain & tf_error))
7945 error ("constraint mismatch at argument %d in "
7946 "template parameter list for %qD",
7947 i + 1, in_decl);
7948 inform (input_location, " expected %qD but got %qD",
7949 parm, arg);
7951 val = error_mark_node;
7955 else
7956 val = orig_arg;
7957 /* We only form one instance of each template specialization.
7958 Therefore, if we use a non-canonical variant (i.e., a
7959 typedef), any future messages referring to the type will use
7960 the typedef, which is confusing if those future uses do not
7961 themselves also use the typedef. */
7962 if (TYPE_P (val))
7963 val = canonicalize_type_argument (val, complain);
7965 else
7967 tree t = TREE_TYPE (parm);
7969 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
7970 > TMPL_ARGS_DEPTH (args))
7971 /* We don't have enough levels of args to do any substitution. This
7972 can happen in the context of -fnew-ttp-matching. */;
7973 else if (tree a = type_uses_auto (t))
7975 t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
7976 if (t == error_mark_node)
7977 return error_mark_node;
7979 else
7980 t = tsubst (t, args, complain, in_decl);
7982 if (invalid_nontype_parm_type_p (t, complain))
7983 return error_mark_node;
7985 if (!type_dependent_expression_p (orig_arg)
7986 && !uses_template_parms (t))
7987 /* We used to call digest_init here. However, digest_init
7988 will report errors, which we don't want when complain
7989 is zero. More importantly, digest_init will try too
7990 hard to convert things: for example, `0' should not be
7991 converted to pointer type at this point according to
7992 the standard. Accepting this is not merely an
7993 extension, since deciding whether or not these
7994 conversions can occur is part of determining which
7995 function template to call, or whether a given explicit
7996 argument specification is valid. */
7997 val = convert_nontype_argument (t, orig_arg, complain);
7998 else
8000 val = canonicalize_expr_argument (orig_arg, complain);
8001 val = maybe_convert_nontype_argument (t, val);
8005 if (val == NULL_TREE)
8006 val = error_mark_node;
8007 else if (val == error_mark_node && (complain & tf_error))
8008 error ("could not convert template argument %qE from %qT to %qT",
8009 orig_arg, TREE_TYPE (orig_arg), t);
8011 if (INDIRECT_REF_P (val))
8013 /* Reject template arguments that are references to built-in
8014 functions with no library fallbacks. */
8015 const_tree inner = TREE_OPERAND (val, 0);
8016 const_tree innertype = TREE_TYPE (inner);
8017 if (innertype
8018 && TYPE_REF_P (innertype)
8019 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8020 && TREE_OPERAND_LENGTH (inner) > 0
8021 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8022 return error_mark_node;
8025 if (TREE_CODE (val) == SCOPE_REF)
8027 /* Strip typedefs from the SCOPE_REF. */
8028 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8029 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8030 complain);
8031 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8032 QUALIFIED_NAME_IS_TEMPLATE (val));
8036 return val;
8039 /* Coerces the remaining template arguments in INNER_ARGS (from
8040 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8041 Returns the coerced argument pack. PARM_IDX is the position of this
8042 parameter in the template parameter list. ARGS is the original
8043 template argument list. */
8044 static tree
8045 coerce_template_parameter_pack (tree parms,
8046 int parm_idx,
8047 tree args,
8048 tree inner_args,
8049 int arg_idx,
8050 tree new_args,
8051 int* lost,
8052 tree in_decl,
8053 tsubst_flags_t complain)
8055 tree parm = TREE_VEC_ELT (parms, parm_idx);
8056 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8057 tree packed_args;
8058 tree argument_pack;
8059 tree packed_parms = NULL_TREE;
8061 if (arg_idx > nargs)
8062 arg_idx = nargs;
8064 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8066 /* When the template parameter is a non-type template parameter pack
8067 or template template parameter pack whose type or template
8068 parameters use parameter packs, we know exactly how many arguments
8069 we are looking for. Build a vector of the instantiated decls for
8070 these template parameters in PACKED_PARMS. */
8071 /* We can't use make_pack_expansion here because it would interpret a
8072 _DECL as a use rather than a declaration. */
8073 tree decl = TREE_VALUE (parm);
8074 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8075 SET_PACK_EXPANSION_PATTERN (exp, decl);
8076 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8077 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8079 TREE_VEC_LENGTH (args)--;
8080 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8081 TREE_VEC_LENGTH (args)++;
8083 if (packed_parms == error_mark_node)
8084 return error_mark_node;
8086 /* If we're doing a partial instantiation of a member template,
8087 verify that all of the types used for the non-type
8088 template parameter pack are, in fact, valid for non-type
8089 template parameters. */
8090 if (arg_idx < nargs
8091 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8093 int j, len = TREE_VEC_LENGTH (packed_parms);
8094 for (j = 0; j < len; ++j)
8096 tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
8097 if (invalid_nontype_parm_type_p (t, complain))
8098 return error_mark_node;
8100 /* We don't know how many args we have yet, just
8101 use the unconverted ones for now. */
8102 return NULL_TREE;
8105 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8107 /* Check if we have a placeholder pack, which indicates we're
8108 in the context of a introduction list. In that case we want
8109 to match this pack to the single placeholder. */
8110 else if (arg_idx < nargs
8111 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8112 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8114 nargs = arg_idx + 1;
8115 packed_args = make_tree_vec (1);
8117 else
8118 packed_args = make_tree_vec (nargs - arg_idx);
8120 /* Convert the remaining arguments, which will be a part of the
8121 parameter pack "parm". */
8122 int first_pack_arg = arg_idx;
8123 for (; arg_idx < nargs; ++arg_idx)
8125 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8126 tree actual_parm = TREE_VALUE (parm);
8127 int pack_idx = arg_idx - first_pack_arg;
8129 if (packed_parms)
8131 /* Once we've packed as many args as we have types, stop. */
8132 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8133 break;
8134 else if (PACK_EXPANSION_P (arg))
8135 /* We don't know how many args we have yet, just
8136 use the unconverted ones for now. */
8137 return NULL_TREE;
8138 else
8139 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8142 if (arg == error_mark_node)
8144 if (complain & tf_error)
8145 error ("template argument %d is invalid", arg_idx + 1);
8147 else
8148 arg = convert_template_argument (actual_parm,
8149 arg, new_args, complain, parm_idx,
8150 in_decl);
8151 if (arg == error_mark_node)
8152 (*lost)++;
8153 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8156 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8157 && TREE_VEC_LENGTH (packed_args) > 0)
8159 if (complain & tf_error)
8160 error ("wrong number of template arguments (%d, should be %d)",
8161 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8162 return error_mark_node;
8165 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8166 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8167 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8168 else
8170 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8171 TREE_CONSTANT (argument_pack) = 1;
8174 SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8175 if (CHECKING_P)
8176 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8177 TREE_VEC_LENGTH (packed_args));
8178 return argument_pack;
8181 /* Returns the number of pack expansions in the template argument vector
8182 ARGS. */
8184 static int
8185 pack_expansion_args_count (tree args)
8187 int i;
8188 int count = 0;
8189 if (args)
8190 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8192 tree elt = TREE_VEC_ELT (args, i);
8193 if (elt && PACK_EXPANSION_P (elt))
8194 ++count;
8196 return count;
8199 /* Convert all template arguments to their appropriate types, and
8200 return a vector containing the innermost resulting template
8201 arguments. If any error occurs, return error_mark_node. Error and
8202 warning messages are issued under control of COMPLAIN.
8204 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8205 for arguments not specified in ARGS. Otherwise, if
8206 USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8207 unspecified arguments. If REQUIRE_ALL_ARGS is true, but
8208 USE_DEFAULT_ARGS is false, then all arguments must be specified in
8209 ARGS. */
8211 static tree
8212 coerce_template_parms (tree parms,
8213 tree args,
8214 tree in_decl,
8215 tsubst_flags_t complain,
8216 bool require_all_args,
8217 bool use_default_args)
8219 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8220 tree orig_inner_args;
8221 tree inner_args;
8222 tree new_args;
8223 tree new_inner_args;
8224 int saved_unevaluated_operand;
8225 int saved_inhibit_evaluation_warnings;
8227 /* When used as a boolean value, indicates whether this is a
8228 variadic template parameter list. Since it's an int, we can also
8229 subtract it from nparms to get the number of non-variadic
8230 parameters. */
8231 int variadic_p = 0;
8232 int variadic_args_p = 0;
8233 int post_variadic_parms = 0;
8235 /* Adjustment to nparms for fixed parameter packs. */
8236 int fixed_pack_adjust = 0;
8237 int fixed_packs = 0;
8238 int missing = 0;
8240 /* Likewise for parameters with default arguments. */
8241 int default_p = 0;
8243 if (args == error_mark_node)
8244 return error_mark_node;
8246 nparms = TREE_VEC_LENGTH (parms);
8248 /* Determine if there are any parameter packs or default arguments. */
8249 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8251 tree parm = TREE_VEC_ELT (parms, parm_idx);
8252 if (variadic_p)
8253 ++post_variadic_parms;
8254 if (template_parameter_pack_p (TREE_VALUE (parm)))
8255 ++variadic_p;
8256 if (TREE_PURPOSE (parm))
8257 ++default_p;
8260 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8261 /* If there are no parameters that follow a parameter pack, we need to
8262 expand any argument packs so that we can deduce a parameter pack from
8263 some non-packed args followed by an argument pack, as in variadic85.C.
8264 If there are such parameters, we need to leave argument packs intact
8265 so the arguments are assigned properly. This can happen when dealing
8266 with a nested class inside a partial specialization of a class
8267 template, as in variadic92.C, or when deducing a template parameter pack
8268 from a sub-declarator, as in variadic114.C. */
8269 if (!post_variadic_parms)
8270 inner_args = expand_template_argument_pack (inner_args);
8272 /* Count any pack expansion args. */
8273 variadic_args_p = pack_expansion_args_count (inner_args);
8275 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8276 if ((nargs - variadic_args_p > nparms && !variadic_p)
8277 || (nargs < nparms - variadic_p
8278 && require_all_args
8279 && !variadic_args_p
8280 && (!use_default_args
8281 || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8282 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8284 bad_nargs:
8285 if (complain & tf_error)
8287 if (variadic_p || default_p)
8289 nparms -= variadic_p + default_p;
8290 error ("wrong number of template arguments "
8291 "(%d, should be at least %d)", nargs, nparms);
8293 else
8294 error ("wrong number of template arguments "
8295 "(%d, should be %d)", nargs, nparms);
8297 if (in_decl)
8298 inform (DECL_SOURCE_LOCATION (in_decl),
8299 "provided for %qD", in_decl);
8302 return error_mark_node;
8304 /* We can't pass a pack expansion to a non-pack parameter of an alias
8305 template (DR 1430). */
8306 else if (in_decl
8307 && (DECL_ALIAS_TEMPLATE_P (in_decl)
8308 || concept_template_p (in_decl))
8309 && variadic_args_p
8310 && nargs - variadic_args_p < nparms - variadic_p)
8312 if (complain & tf_error)
8314 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8316 tree arg = TREE_VEC_ELT (inner_args, i);
8317 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8319 if (PACK_EXPANSION_P (arg)
8320 && !template_parameter_pack_p (parm))
8322 if (DECL_ALIAS_TEMPLATE_P (in_decl))
8323 error_at (location_of (arg),
8324 "pack expansion argument for non-pack parameter "
8325 "%qD of alias template %qD", parm, in_decl);
8326 else
8327 error_at (location_of (arg),
8328 "pack expansion argument for non-pack parameter "
8329 "%qD of concept %qD", parm, in_decl);
8330 inform (DECL_SOURCE_LOCATION (parm), "declared here");
8331 goto found;
8334 gcc_unreachable ();
8335 found:;
8337 return error_mark_node;
8340 /* We need to evaluate the template arguments, even though this
8341 template-id may be nested within a "sizeof". */
8342 saved_unevaluated_operand = cp_unevaluated_operand;
8343 cp_unevaluated_operand = 0;
8344 saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8345 c_inhibit_evaluation_warnings = 0;
8346 new_inner_args = make_tree_vec (nparms);
8347 new_args = add_outermost_template_args (args, new_inner_args);
8348 int pack_adjust = 0;
8349 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8351 tree arg;
8352 tree parm;
8354 /* Get the Ith template parameter. */
8355 parm = TREE_VEC_ELT (parms, parm_idx);
8357 if (parm == error_mark_node)
8359 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8360 continue;
8363 /* Calculate the next argument. */
8364 if (arg_idx < nargs)
8365 arg = TREE_VEC_ELT (inner_args, arg_idx);
8366 else
8367 arg = NULL_TREE;
8369 if (template_parameter_pack_p (TREE_VALUE (parm))
8370 && !(arg && ARGUMENT_PACK_P (arg)))
8372 /* Some arguments will be placed in the
8373 template parameter pack PARM. */
8374 arg = coerce_template_parameter_pack (parms, parm_idx, args,
8375 inner_args, arg_idx,
8376 new_args, &lost,
8377 in_decl, complain);
8379 if (arg == NULL_TREE)
8381 /* We don't know how many args we have yet, just use the
8382 unconverted (and still packed) ones for now. */
8383 new_inner_args = orig_inner_args;
8384 arg_idx = nargs;
8385 break;
8388 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8390 /* Store this argument. */
8391 if (arg == error_mark_node)
8393 lost++;
8394 /* We are done with all of the arguments. */
8395 arg_idx = nargs;
8396 break;
8398 else
8400 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8401 arg_idx += pack_adjust;
8402 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8404 ++fixed_packs;
8405 fixed_pack_adjust += pack_adjust;
8409 continue;
8411 else if (arg)
8413 if (PACK_EXPANSION_P (arg))
8415 /* "If every valid specialization of a variadic template
8416 requires an empty template parameter pack, the template is
8417 ill-formed, no diagnostic required." So check that the
8418 pattern works with this parameter. */
8419 tree pattern = PACK_EXPANSION_PATTERN (arg);
8420 tree conv = convert_template_argument (TREE_VALUE (parm),
8421 pattern, new_args,
8422 complain, parm_idx,
8423 in_decl);
8424 if (conv == error_mark_node)
8426 if (complain & tf_error)
8427 inform (input_location, "so any instantiation with a "
8428 "non-empty parameter pack would be ill-formed");
8429 ++lost;
8431 else if (TYPE_P (conv) && !TYPE_P (pattern))
8432 /* Recover from missing typename. */
8433 TREE_VEC_ELT (inner_args, arg_idx)
8434 = make_pack_expansion (conv, complain);
8436 /* We don't know how many args we have yet, just
8437 use the unconverted ones for now. */
8438 new_inner_args = inner_args;
8439 arg_idx = nargs;
8440 break;
8443 else if (require_all_args)
8445 /* There must be a default arg in this case. */
8446 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8447 complain, in_decl);
8448 /* The position of the first default template argument,
8449 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8450 Record that. */
8451 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8452 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8453 arg_idx - pack_adjust);
8455 else
8456 break;
8458 if (arg == error_mark_node)
8460 if (complain & tf_error)
8461 error ("template argument %d is invalid", arg_idx + 1);
8463 else if (!arg)
8465 /* This can occur if there was an error in the template
8466 parameter list itself (which we would already have
8467 reported) that we are trying to recover from, e.g., a class
8468 template with a parameter list such as
8469 template<typename..., typename> (cpp0x/variadic150.C). */
8470 ++lost;
8472 /* This can also happen with a fixed parameter pack (71834). */
8473 if (arg_idx >= nargs)
8474 ++missing;
8476 else
8477 arg = convert_template_argument (TREE_VALUE (parm),
8478 arg, new_args, complain,
8479 parm_idx, in_decl);
8481 if (arg == error_mark_node)
8482 lost++;
8483 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8485 cp_unevaluated_operand = saved_unevaluated_operand;
8486 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8488 if (missing || arg_idx < nargs - variadic_args_p)
8490 /* If we had fixed parameter packs, we didn't know how many arguments we
8491 actually needed earlier; now we do. */
8492 nparms += fixed_pack_adjust;
8493 variadic_p -= fixed_packs;
8494 goto bad_nargs;
8497 if (arg_idx < nargs)
8499 /* We had some pack expansion arguments that will only work if the packs
8500 are empty, but wait until instantiation time to complain.
8501 See variadic-ttp3.C. */
8502 int len = nparms + (nargs - arg_idx);
8503 tree args = make_tree_vec (len);
8504 int i = 0;
8505 for (; i < nparms; ++i)
8506 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8507 for (; i < len; ++i, ++arg_idx)
8508 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8509 arg_idx - pack_adjust);
8510 new_inner_args = args;
8513 if (lost)
8515 gcc_assert (!(complain & tf_error) || seen_error ());
8516 return error_mark_node;
8519 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8520 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8521 TREE_VEC_LENGTH (new_inner_args));
8523 return new_inner_args;
8526 /* Convert all template arguments to their appropriate types, and
8527 return a vector containing the innermost resulting template
8528 arguments. If any error occurs, return error_mark_node. Error and
8529 warning messages are not issued.
8531 Note that no function argument deduction is performed, and default
8532 arguments are used to fill in unspecified arguments. */
8533 tree
8534 coerce_template_parms (tree parms, tree args, tree in_decl)
8536 return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8539 /* Convert all template arguments to their appropriate type, and
8540 instantiate default arguments as needed. This returns a vector
8541 containing the innermost resulting template arguments, or
8542 error_mark_node if unsuccessful. */
8543 tree
8544 coerce_template_parms (tree parms, tree args, tree in_decl,
8545 tsubst_flags_t complain)
8547 return coerce_template_parms (parms, args, in_decl, complain, true, true);
8550 /* Like coerce_template_parms. If PARMS represents all template
8551 parameters levels, this function returns a vector of vectors
8552 representing all the resulting argument levels. Note that in this
8553 case, only the innermost arguments are coerced because the
8554 outermost ones are supposed to have been coerced already.
8556 Otherwise, if PARMS represents only (the innermost) vector of
8557 parameters, this function returns a vector containing just the
8558 innermost resulting arguments. */
8560 static tree
8561 coerce_innermost_template_parms (tree parms,
8562 tree args,
8563 tree in_decl,
8564 tsubst_flags_t complain,
8565 bool require_all_args,
8566 bool use_default_args)
8568 int parms_depth = TMPL_PARMS_DEPTH (parms);
8569 int args_depth = TMPL_ARGS_DEPTH (args);
8570 tree coerced_args;
8572 if (parms_depth > 1)
8574 coerced_args = make_tree_vec (parms_depth);
8575 tree level;
8576 int cur_depth;
8578 for (level = parms, cur_depth = parms_depth;
8579 parms_depth > 0 && level != NULL_TREE;
8580 level = TREE_CHAIN (level), --cur_depth)
8582 tree l;
8583 if (cur_depth == args_depth)
8584 l = coerce_template_parms (TREE_VALUE (level),
8585 args, in_decl, complain,
8586 require_all_args,
8587 use_default_args);
8588 else
8589 l = TMPL_ARGS_LEVEL (args, cur_depth);
8591 if (l == error_mark_node)
8592 return error_mark_node;
8594 SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8597 else
8598 coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8599 args, in_decl, complain,
8600 require_all_args,
8601 use_default_args);
8602 return coerced_args;
8605 /* Returns 1 if template args OT and NT are equivalent. */
8608 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8610 if (nt == ot)
8611 return 1;
8612 if (nt == NULL_TREE || ot == NULL_TREE)
8613 return false;
8614 if (nt == any_targ_node || ot == any_targ_node)
8615 return true;
8617 if (TREE_CODE (nt) == TREE_VEC)
8618 /* For member templates */
8619 return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8620 else if (PACK_EXPANSION_P (ot))
8621 return (PACK_EXPANSION_P (nt)
8622 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8623 PACK_EXPANSION_PATTERN (nt))
8624 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8625 PACK_EXPANSION_EXTRA_ARGS (nt)));
8626 else if (ARGUMENT_PACK_P (ot))
8628 int i, len;
8629 tree opack, npack;
8631 if (!ARGUMENT_PACK_P (nt))
8632 return 0;
8634 opack = ARGUMENT_PACK_ARGS (ot);
8635 npack = ARGUMENT_PACK_ARGS (nt);
8636 len = TREE_VEC_LENGTH (opack);
8637 if (TREE_VEC_LENGTH (npack) != len)
8638 return 0;
8639 for (i = 0; i < len; ++i)
8640 if (!template_args_equal (TREE_VEC_ELT (opack, i),
8641 TREE_VEC_ELT (npack, i)))
8642 return 0;
8643 return 1;
8645 else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8646 gcc_unreachable ();
8647 else if (TYPE_P (nt))
8649 if (!TYPE_P (ot))
8650 return false;
8651 /* Don't treat an alias template specialization with dependent
8652 arguments as equivalent to its underlying type when used as a
8653 template argument; we need them to be distinct so that we
8654 substitute into the specialization arguments at instantiation
8655 time. And aliases can't be equivalent without being ==, so
8656 we don't need to look any deeper.
8658 During partial ordering, however, we need to treat them normally so
8659 that we can order uses of the same alias with different
8660 cv-qualification (79960). */
8661 if (!partial_order
8662 && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8663 return false;
8664 else
8665 return same_type_p (ot, nt);
8667 else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8668 return 0;
8669 else
8671 /* Try to treat a template non-type argument that has been converted
8672 to the parameter type as equivalent to one that hasn't yet. */
8673 for (enum tree_code code1 = TREE_CODE (ot);
8674 CONVERT_EXPR_CODE_P (code1)
8675 || code1 == NON_LVALUE_EXPR;
8676 code1 = TREE_CODE (ot))
8677 ot = TREE_OPERAND (ot, 0);
8678 for (enum tree_code code2 = TREE_CODE (nt);
8679 CONVERT_EXPR_CODE_P (code2)
8680 || code2 == NON_LVALUE_EXPR;
8681 code2 = TREE_CODE (nt))
8682 nt = TREE_OPERAND (nt, 0);
8684 return cp_tree_equal (ot, nt);
8688 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8689 template arguments. Returns 0 otherwise, and updates OLDARG_PTR and
8690 NEWARG_PTR with the offending arguments if they are non-NULL. */
8693 comp_template_args (tree oldargs, tree newargs,
8694 tree *oldarg_ptr, tree *newarg_ptr,
8695 bool partial_order)
8697 int i;
8699 if (oldargs == newargs)
8700 return 1;
8702 if (!oldargs || !newargs)
8703 return 0;
8705 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8706 return 0;
8708 for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8710 tree nt = TREE_VEC_ELT (newargs, i);
8711 tree ot = TREE_VEC_ELT (oldargs, i);
8713 if (! template_args_equal (ot, nt, partial_order))
8715 if (oldarg_ptr != NULL)
8716 *oldarg_ptr = ot;
8717 if (newarg_ptr != NULL)
8718 *newarg_ptr = nt;
8719 return 0;
8722 return 1;
8725 inline bool
8726 comp_template_args_porder (tree oargs, tree nargs)
8728 return comp_template_args (oargs, nargs, NULL, NULL, true);
8731 /* Implement a freelist interface for objects of type T.
8733 Head is a separate object, rather than a regular member, so that we
8734 can define it as a GTY deletable pointer, which is highly
8735 desirable. A data member could be declared that way, but then the
8736 containing object would implicitly get GTY((user)), which would
8737 prevent us from instantiating freelists as global objects.
8738 Although this way we can create freelist global objects, they're
8739 such thin wrappers that instantiating temporaries at every use
8740 loses nothing and saves permanent storage for the freelist object.
8742 Member functions next, anew, poison and reinit have default
8743 implementations that work for most of the types we're interested
8744 in, but if they don't work for some type, they should be explicitly
8745 specialized. See the comments before them for requirements, and
8746 the example specializations for the tree_list_freelist. */
8747 template <typename T>
8748 class freelist
8750 /* Return the next object in a chain. We could just do type
8751 punning, but if we access the object with its underlying type, we
8752 avoid strict-aliasing trouble. This needs only work between
8753 poison and reinit. */
8754 static T *&next (T *obj) { return obj->next; }
8756 /* Return a newly allocated, uninitialized or minimally-initialized
8757 object of type T. Any initialization performed by anew should
8758 either remain across the life of the object and the execution of
8759 poison, or be redone by reinit. */
8760 static T *anew () { return ggc_alloc<T> (); }
8762 /* Optionally scribble all over the bits holding the object, so that
8763 they become (mostly?) uninitialized memory. This is called while
8764 preparing to make the object part of the free list. */
8765 static void poison (T *obj) {
8766 T *p ATTRIBUTE_UNUSED = obj;
8767 T **q ATTRIBUTE_UNUSED = &next (obj);
8769 #ifdef ENABLE_GC_CHECKING
8770 /* Poison the data, to indicate the data is garbage. */
8771 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
8772 memset (p, 0xa5, sizeof (*p));
8773 #endif
8774 /* Let valgrind know the object is free. */
8775 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
8777 /* Let valgrind know the next portion of the object is available,
8778 but uninitialized. */
8779 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8782 /* Bring an object that underwent at least one lifecycle after anew
8783 and before the most recent free and poison, back to a usable
8784 state, reinitializing whatever is needed for it to be
8785 functionally equivalent to an object just allocated and returned
8786 by anew. This may poison or clear the next field, used by
8787 freelist housekeeping after poison was called. */
8788 static void reinit (T *obj) {
8789 T **q ATTRIBUTE_UNUSED = &next (obj);
8791 #ifdef ENABLE_GC_CHECKING
8792 memset (q, 0xa5, sizeof (*q));
8793 #endif
8794 /* Let valgrind know the entire object is available, but
8795 uninitialized. */
8796 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
8799 /* Reference a GTY-deletable pointer that points to the first object
8800 in the free list proper. */
8801 T *&head;
8802 public:
8803 /* Construct a freelist object chaining objects off of HEAD. */
8804 freelist (T *&head) : head(head) {}
8806 /* Add OBJ to the free object list. The former head becomes OBJ's
8807 successor. */
8808 void free (T *obj)
8810 poison (obj);
8811 next (obj) = head;
8812 head = obj;
8815 /* Take an object from the free list, if one is available, or
8816 allocate a new one. Objects taken from the free list should be
8817 regarded as filled with garbage, except for bits that are
8818 configured to be preserved across free and alloc. */
8819 T *alloc ()
8821 if (head)
8823 T *obj = head;
8824 head = next (head);
8825 reinit (obj);
8826 return obj;
8828 else
8829 return anew ();
8833 /* Explicitly specialize the interfaces for freelist<tree_node>: we
8834 want to allocate a TREE_LIST using the usual interface, and ensure
8835 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
8836 build_tree_list logic in reinit, so this could go out of sync. */
8837 template <>
8838 inline tree &
8839 freelist<tree_node>::next (tree obj)
8841 return TREE_CHAIN (obj);
8843 template <>
8844 inline tree
8845 freelist<tree_node>::anew ()
8847 return build_tree_list (NULL, NULL);
8849 template <>
8850 inline void
8851 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
8853 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
8854 tree p ATTRIBUTE_UNUSED = obj;
8855 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8856 tree *q ATTRIBUTE_UNUSED = &next (obj);
8858 #ifdef ENABLE_GC_CHECKING
8859 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8861 /* Poison the data, to indicate the data is garbage. */
8862 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
8863 memset (p, 0xa5, size);
8864 #endif
8865 /* Let valgrind know the object is free. */
8866 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
8867 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
8868 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8869 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8871 #ifdef ENABLE_GC_CHECKING
8872 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
8873 /* Keep TREE_CHAIN functional. */
8874 TREE_SET_CODE (obj, TREE_LIST);
8875 #else
8876 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8877 #endif
8879 template <>
8880 inline void
8881 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
8883 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8885 #ifdef ENABLE_GC_CHECKING
8886 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8887 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8888 memset (obj, 0, sizeof (tree_list));
8889 #endif
8891 /* Let valgrind know the entire object is available, but
8892 uninitialized. */
8893 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8895 #ifdef ENABLE_GC_CHECKING
8896 TREE_SET_CODE (obj, TREE_LIST);
8897 #else
8898 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8899 #endif
8902 /* Point to the first object in the TREE_LIST freelist. */
8903 static GTY((deletable)) tree tree_list_freelist_head;
8904 /* Return the/an actual TREE_LIST freelist. */
8905 static inline freelist<tree_node>
8906 tree_list_freelist ()
8908 return tree_list_freelist_head;
8911 /* Point to the first object in the tinst_level freelist. */
8912 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
8913 /* Return the/an actual tinst_level freelist. */
8914 static inline freelist<tinst_level>
8915 tinst_level_freelist ()
8917 return tinst_level_freelist_head;
8920 /* Point to the first object in the pending_template freelist. */
8921 static GTY((deletable)) pending_template *pending_template_freelist_head;
8922 /* Return the/an actual pending_template freelist. */
8923 static inline freelist<pending_template>
8924 pending_template_freelist ()
8926 return pending_template_freelist_head;
8929 /* Build the TREE_LIST object out of a split list, store it
8930 permanently, and return it. */
8931 tree
8932 tinst_level::to_list ()
8934 gcc_assert (split_list_p ());
8935 tree ret = tree_list_freelist ().alloc ();
8936 TREE_PURPOSE (ret) = tldcl;
8937 TREE_VALUE (ret) = targs;
8938 tldcl = ret;
8939 targs = NULL;
8940 gcc_assert (tree_list_p ());
8941 return ret;
8944 const unsigned short tinst_level::refcount_infinity;
8946 /* Increment OBJ's refcount unless it is already infinite. */
8947 static tinst_level *
8948 inc_refcount_use (tinst_level *obj)
8950 if (obj && obj->refcount != tinst_level::refcount_infinity)
8951 ++obj->refcount;
8952 return obj;
8955 /* Release storage for OBJ and node, if it's a TREE_LIST. */
8956 void
8957 tinst_level::free (tinst_level *obj)
8959 if (obj->tree_list_p ())
8960 tree_list_freelist ().free (obj->get_node ());
8961 tinst_level_freelist ().free (obj);
8964 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
8965 OBJ's DECL and OBJ, and start over with the tinst_level object that
8966 used to be referenced by OBJ's NEXT. */
8967 static void
8968 dec_refcount_use (tinst_level *obj)
8970 while (obj
8971 && obj->refcount != tinst_level::refcount_infinity
8972 && !--obj->refcount)
8974 tinst_level *next = obj->next;
8975 tinst_level::free (obj);
8976 obj = next;
8980 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
8981 and of the former PTR. Omitting the second argument is equivalent
8982 to passing (T*)NULL; this is allowed because passing the
8983 zero-valued integral constant NULL confuses type deduction and/or
8984 overload resolution. */
8985 template <typename T>
8986 static void
8987 set_refcount_ptr (T *& ptr, T *obj = NULL)
8989 T *save = ptr;
8990 ptr = inc_refcount_use (obj);
8991 dec_refcount_use (save);
8994 static void
8995 add_pending_template (tree d)
8997 tree ti = (TYPE_P (d)
8998 ? CLASSTYPE_TEMPLATE_INFO (d)
8999 : DECL_TEMPLATE_INFO (d));
9000 struct pending_template *pt;
9001 int level;
9003 if (TI_PENDING_TEMPLATE_FLAG (ti))
9004 return;
9006 /* We are called both from instantiate_decl, where we've already had a
9007 tinst_level pushed, and instantiate_template, where we haven't.
9008 Compensate. */
9009 gcc_assert (TREE_CODE (d) != TREE_LIST);
9010 level = !current_tinst_level
9011 || current_tinst_level->maybe_get_node () != d;
9013 if (level)
9014 push_tinst_level (d);
9016 pt = pending_template_freelist ().alloc ();
9017 pt->next = NULL;
9018 pt->tinst = NULL;
9019 set_refcount_ptr (pt->tinst, current_tinst_level);
9020 if (last_pending_template)
9021 last_pending_template->next = pt;
9022 else
9023 pending_templates = pt;
9025 last_pending_template = pt;
9027 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9029 if (level)
9030 pop_tinst_level ();
9034 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9035 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9036 documentation for TEMPLATE_ID_EXPR. */
9038 tree
9039 lookup_template_function (tree fns, tree arglist)
9041 tree type;
9043 if (fns == error_mark_node || arglist == error_mark_node)
9044 return error_mark_node;
9046 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9048 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9050 error ("%q#D is not a function template", fns);
9051 return error_mark_node;
9054 if (BASELINK_P (fns))
9056 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9057 unknown_type_node,
9058 BASELINK_FUNCTIONS (fns),
9059 arglist);
9060 return fns;
9063 type = TREE_TYPE (fns);
9064 if (TREE_CODE (fns) == OVERLOAD || !type)
9065 type = unknown_type_node;
9067 return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
9070 /* Within the scope of a template class S<T>, the name S gets bound
9071 (in build_self_reference) to a TYPE_DECL for the class, not a
9072 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9073 or one of its enclosing classes, and that type is a template,
9074 return the associated TEMPLATE_DECL. Otherwise, the original
9075 DECL is returned.
9077 Also handle the case when DECL is a TREE_LIST of ambiguous
9078 injected-class-names from different bases. */
9080 tree
9081 maybe_get_template_decl_from_type_decl (tree decl)
9083 if (decl == NULL_TREE)
9084 return decl;
9086 /* DR 176: A lookup that finds an injected-class-name (10.2
9087 [class.member.lookup]) can result in an ambiguity in certain cases
9088 (for example, if it is found in more than one base class). If all of
9089 the injected-class-names that are found refer to specializations of
9090 the same class template, and if the name is followed by a
9091 template-argument-list, the reference refers to the class template
9092 itself and not a specialization thereof, and is not ambiguous. */
9093 if (TREE_CODE (decl) == TREE_LIST)
9095 tree t, tmpl = NULL_TREE;
9096 for (t = decl; t; t = TREE_CHAIN (t))
9098 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9099 if (!tmpl)
9100 tmpl = elt;
9101 else if (tmpl != elt)
9102 break;
9104 if (tmpl && t == NULL_TREE)
9105 return tmpl;
9106 else
9107 return decl;
9110 return (decl != NULL_TREE
9111 && DECL_SELF_REFERENCE_P (decl)
9112 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9113 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9116 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9117 parameters, find the desired type.
9119 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9121 IN_DECL, if non-NULL, is the template declaration we are trying to
9122 instantiate.
9124 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9125 the class we are looking up.
9127 Issue error and warning messages under control of COMPLAIN.
9129 If the template class is really a local class in a template
9130 function, then the FUNCTION_CONTEXT is the function in which it is
9131 being instantiated.
9133 ??? Note that this function is currently called *twice* for each
9134 template-id: the first time from the parser, while creating the
9135 incomplete type (finish_template_type), and the second type during the
9136 real instantiation (instantiate_template_class). This is surely something
9137 that we want to avoid. It also causes some problems with argument
9138 coercion (see convert_nontype_argument for more information on this). */
9140 static tree
9141 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9142 int entering_scope, tsubst_flags_t complain)
9144 tree templ = NULL_TREE, parmlist;
9145 tree t;
9146 spec_entry **slot;
9147 spec_entry *entry;
9148 spec_entry elt;
9149 hashval_t hash;
9151 if (identifier_p (d1))
9153 tree value = innermost_non_namespace_value (d1);
9154 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9155 templ = value;
9156 else
9158 if (context)
9159 push_decl_namespace (context);
9160 templ = lookup_name (d1);
9161 templ = maybe_get_template_decl_from_type_decl (templ);
9162 if (context)
9163 pop_decl_namespace ();
9165 if (templ)
9166 context = DECL_CONTEXT (templ);
9168 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9170 tree type = TREE_TYPE (d1);
9172 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9173 an implicit typename for the second A. Deal with it. */
9174 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9175 type = TREE_TYPE (type);
9177 if (CLASSTYPE_TEMPLATE_INFO (type))
9179 templ = CLASSTYPE_TI_TEMPLATE (type);
9180 d1 = DECL_NAME (templ);
9183 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9184 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9186 templ = TYPE_TI_TEMPLATE (d1);
9187 d1 = DECL_NAME (templ);
9189 else if (DECL_TYPE_TEMPLATE_P (d1))
9191 templ = d1;
9192 d1 = DECL_NAME (templ);
9193 context = DECL_CONTEXT (templ);
9195 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9197 templ = d1;
9198 d1 = DECL_NAME (templ);
9201 /* Issue an error message if we didn't find a template. */
9202 if (! templ)
9204 if (complain & tf_error)
9205 error ("%qT is not a template", d1);
9206 return error_mark_node;
9209 if (TREE_CODE (templ) != TEMPLATE_DECL
9210 /* Make sure it's a user visible template, if it was named by
9211 the user. */
9212 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9213 && !PRIMARY_TEMPLATE_P (templ)))
9215 if (complain & tf_error)
9217 error ("non-template type %qT used as a template", d1);
9218 if (in_decl)
9219 error ("for template declaration %q+D", in_decl);
9221 return error_mark_node;
9224 complain &= ~tf_user;
9226 /* An alias that just changes the name of a template is equivalent to the
9227 other template, so if any of the arguments are pack expansions, strip
9228 the alias to avoid problems with a pack expansion passed to a non-pack
9229 alias template parameter (DR 1430). */
9230 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9231 templ = get_underlying_template (templ);
9233 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9235 tree parm;
9236 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9237 if (arglist2 == error_mark_node
9238 || (!uses_template_parms (arglist2)
9239 && check_instantiated_args (templ, arglist2, complain)))
9240 return error_mark_node;
9242 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9243 return parm;
9245 else
9247 tree template_type = TREE_TYPE (templ);
9248 tree gen_tmpl;
9249 tree type_decl;
9250 tree found = NULL_TREE;
9251 int arg_depth;
9252 int parm_depth;
9253 int is_dependent_type;
9254 int use_partial_inst_tmpl = false;
9256 if (template_type == error_mark_node)
9257 /* An error occurred while building the template TEMPL, and a
9258 diagnostic has most certainly been emitted for that
9259 already. Let's propagate that error. */
9260 return error_mark_node;
9262 gen_tmpl = most_general_template (templ);
9263 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9264 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9265 arg_depth = TMPL_ARGS_DEPTH (arglist);
9267 if (arg_depth == 1 && parm_depth > 1)
9269 /* We've been given an incomplete set of template arguments.
9270 For example, given:
9272 template <class T> struct S1 {
9273 template <class U> struct S2 {};
9274 template <class U> struct S2<U*> {};
9277 we will be called with an ARGLIST of `U*', but the
9278 TEMPLATE will be `template <class T> template
9279 <class U> struct S1<T>::S2'. We must fill in the missing
9280 arguments. */
9281 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9282 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9283 arg_depth = TMPL_ARGS_DEPTH (arglist);
9286 /* Now we should have enough arguments. */
9287 gcc_assert (parm_depth == arg_depth);
9289 /* From here on, we're only interested in the most general
9290 template. */
9292 /* Calculate the BOUND_ARGS. These will be the args that are
9293 actually tsubst'd into the definition to create the
9294 instantiation. */
9295 arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9296 complain,
9297 /*require_all_args=*/true,
9298 /*use_default_args=*/true);
9300 if (arglist == error_mark_node)
9301 /* We were unable to bind the arguments. */
9302 return error_mark_node;
9304 /* In the scope of a template class, explicit references to the
9305 template class refer to the type of the template, not any
9306 instantiation of it. For example, in:
9308 template <class T> class C { void f(C<T>); }
9310 the `C<T>' is just the same as `C'. Outside of the
9311 class, however, such a reference is an instantiation. */
9312 if (entering_scope
9313 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9314 || currently_open_class (template_type))
9316 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9318 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9319 return template_type;
9322 /* If we already have this specialization, return it. */
9323 elt.tmpl = gen_tmpl;
9324 elt.args = arglist;
9325 elt.spec = NULL_TREE;
9326 hash = spec_hasher::hash (&elt);
9327 entry = type_specializations->find_with_hash (&elt, hash);
9329 if (entry)
9330 return entry->spec;
9332 /* If the the template's constraints are not satisfied,
9333 then we cannot form a valid type.
9335 Note that the check is deferred until after the hash
9336 lookup. This prevents redundant checks on previously
9337 instantiated specializations. */
9338 if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9340 if (complain & tf_error)
9342 error ("template constraint failure");
9343 diagnose_constraints (input_location, gen_tmpl, arglist);
9345 return error_mark_node;
9348 is_dependent_type = uses_template_parms (arglist);
9350 /* If the deduced arguments are invalid, then the binding
9351 failed. */
9352 if (!is_dependent_type
9353 && check_instantiated_args (gen_tmpl,
9354 INNERMOST_TEMPLATE_ARGS (arglist),
9355 complain))
9356 return error_mark_node;
9358 if (!is_dependent_type
9359 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9360 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9361 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9363 found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9364 DECL_NAME (gen_tmpl),
9365 /*tag_scope=*/ts_global);
9366 return found;
9369 context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
9370 complain, in_decl);
9371 if (context == error_mark_node)
9372 return error_mark_node;
9374 if (!context)
9375 context = global_namespace;
9377 /* Create the type. */
9378 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9380 /* The user referred to a specialization of an alias
9381 template represented by GEN_TMPL.
9383 [temp.alias]/2 says:
9385 When a template-id refers to the specialization of an
9386 alias template, it is equivalent to the associated
9387 type obtained by substitution of its
9388 template-arguments for the template-parameters in the
9389 type-id of the alias template. */
9391 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9392 /* Note that the call above (by indirectly calling
9393 register_specialization in tsubst_decl) registers the
9394 TYPE_DECL representing the specialization of the alias
9395 template. So next time someone substitutes ARGLIST for
9396 the template parms into the alias template (GEN_TMPL),
9397 she'll get that TYPE_DECL back. */
9399 if (t == error_mark_node)
9400 return t;
9402 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9404 if (!is_dependent_type)
9406 set_current_access_from_decl (TYPE_NAME (template_type));
9407 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9408 tsubst (ENUM_UNDERLYING_TYPE (template_type),
9409 arglist, complain, in_decl),
9410 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9411 arglist, complain, in_decl),
9412 SCOPED_ENUM_P (template_type), NULL);
9414 if (t == error_mark_node)
9415 return t;
9417 else
9419 /* We don't want to call start_enum for this type, since
9420 the values for the enumeration constants may involve
9421 template parameters. And, no one should be interested
9422 in the enumeration constants for such a type. */
9423 t = cxx_make_type (ENUMERAL_TYPE);
9424 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9426 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9427 ENUM_FIXED_UNDERLYING_TYPE_P (t)
9428 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9430 else if (CLASS_TYPE_P (template_type))
9432 /* Lambda closures are regenerated in tsubst_lambda_expr, not
9433 instantiated here. */
9434 gcc_assert (!LAMBDA_TYPE_P (template_type));
9436 t = make_class_type (TREE_CODE (template_type));
9437 CLASSTYPE_DECLARED_CLASS (t)
9438 = CLASSTYPE_DECLARED_CLASS (template_type);
9439 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9441 /* A local class. Make sure the decl gets registered properly. */
9442 if (context == current_function_decl)
9443 if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9444 == error_mark_node)
9445 return error_mark_node;
9447 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9448 /* This instantiation is another name for the primary
9449 template type. Set the TYPE_CANONICAL field
9450 appropriately. */
9451 TYPE_CANONICAL (t) = template_type;
9452 else if (any_template_arguments_need_structural_equality_p (arglist))
9453 /* Some of the template arguments require structural
9454 equality testing, so this template class requires
9455 structural equality testing. */
9456 SET_TYPE_STRUCTURAL_EQUALITY (t);
9458 else
9459 gcc_unreachable ();
9461 /* If we called start_enum or pushtag above, this information
9462 will already be set up. */
9463 if (!TYPE_NAME (t))
9465 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9467 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9468 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9469 DECL_SOURCE_LOCATION (type_decl)
9470 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9472 else
9473 type_decl = TYPE_NAME (t);
9475 if (CLASS_TYPE_P (template_type))
9477 TREE_PRIVATE (type_decl)
9478 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9479 TREE_PROTECTED (type_decl)
9480 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9481 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9483 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9484 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9488 if (OVERLOAD_TYPE_P (t)
9489 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9491 static const char *tags[] = {"abi_tag", "may_alias"};
9493 for (unsigned ix = 0; ix != 2; ix++)
9495 tree attributes
9496 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9498 if (attributes)
9499 TYPE_ATTRIBUTES (t)
9500 = tree_cons (TREE_PURPOSE (attributes),
9501 TREE_VALUE (attributes),
9502 TYPE_ATTRIBUTES (t));
9506 /* Let's consider the explicit specialization of a member
9507 of a class template specialization that is implicitly instantiated,
9508 e.g.:
9509 template<class T>
9510 struct S
9512 template<class U> struct M {}; //#0
9515 template<>
9516 template<>
9517 struct S<int>::M<char> //#1
9519 int i;
9521 [temp.expl.spec]/4 says this is valid.
9523 In this case, when we write:
9524 S<int>::M<char> m;
9526 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9527 the one of #0.
9529 When we encounter #1, we want to store the partial instantiation
9530 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9532 For all cases other than this "explicit specialization of member of a
9533 class template", we just want to store the most general template into
9534 the CLASSTYPE_TI_TEMPLATE of M.
9536 This case of "explicit specialization of member of a class template"
9537 only happens when:
9538 1/ the enclosing class is an instantiation of, and therefore not
9539 the same as, the context of the most general template, and
9540 2/ we aren't looking at the partial instantiation itself, i.e.
9541 the innermost arguments are not the same as the innermost parms of
9542 the most general template.
9544 So it's only when 1/ and 2/ happens that we want to use the partial
9545 instantiation of the member template in lieu of its most general
9546 template. */
9548 if (PRIMARY_TEMPLATE_P (gen_tmpl)
9549 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9550 /* the enclosing class must be an instantiation... */
9551 && CLASS_TYPE_P (context)
9552 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9554 TREE_VEC_LENGTH (arglist)--;
9555 ++processing_template_decl;
9556 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9557 tree partial_inst_args =
9558 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9559 arglist, complain, NULL_TREE);
9560 --processing_template_decl;
9561 TREE_VEC_LENGTH (arglist)++;
9562 if (partial_inst_args == error_mark_node)
9563 return error_mark_node;
9564 use_partial_inst_tmpl =
9565 /*...and we must not be looking at the partial instantiation
9566 itself. */
9567 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9568 partial_inst_args);
9571 if (!use_partial_inst_tmpl)
9572 /* This case is easy; there are no member templates involved. */
9573 found = gen_tmpl;
9574 else
9576 /* This is a full instantiation of a member template. Find
9577 the partial instantiation of which this is an instance. */
9579 /* Temporarily reduce by one the number of levels in the ARGLIST
9580 so as to avoid comparing the last set of arguments. */
9581 TREE_VEC_LENGTH (arglist)--;
9582 found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9583 TREE_VEC_LENGTH (arglist)++;
9584 /* FOUND is either a proper class type, or an alias
9585 template specialization. In the later case, it's a
9586 TYPE_DECL, resulting from the substituting of arguments
9587 for parameters in the TYPE_DECL of the alias template
9588 done earlier. So be careful while getting the template
9589 of FOUND. */
9590 found = (TREE_CODE (found) == TEMPLATE_DECL
9591 ? found
9592 : (TREE_CODE (found) == TYPE_DECL
9593 ? DECL_TI_TEMPLATE (found)
9594 : CLASSTYPE_TI_TEMPLATE (found)));
9597 // Build template info for the new specialization.
9598 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9600 elt.spec = t;
9601 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9602 entry = ggc_alloc<spec_entry> ();
9603 *entry = elt;
9604 *slot = entry;
9606 /* Note this use of the partial instantiation so we can check it
9607 later in maybe_process_partial_specialization. */
9608 DECL_TEMPLATE_INSTANTIATIONS (found)
9609 = tree_cons (arglist, t,
9610 DECL_TEMPLATE_INSTANTIATIONS (found));
9612 if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9613 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9614 /* Now that the type has been registered on the instantiations
9615 list, we set up the enumerators. Because the enumeration
9616 constants may involve the enumeration type itself, we make
9617 sure to register the type first, and then create the
9618 constants. That way, doing tsubst_expr for the enumeration
9619 constants won't result in recursive calls here; we'll find
9620 the instantiation and exit above. */
9621 tsubst_enum (template_type, t, arglist);
9623 if (CLASS_TYPE_P (template_type) && is_dependent_type)
9624 /* If the type makes use of template parameters, the
9625 code that generates debugging information will crash. */
9626 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9628 /* Possibly limit visibility based on template args. */
9629 TREE_PUBLIC (type_decl) = 1;
9630 determine_visibility (type_decl);
9632 inherit_targ_abi_tags (t);
9634 return t;
9638 /* Wrapper for lookup_template_class_1. */
9640 tree
9641 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9642 int entering_scope, tsubst_flags_t complain)
9644 tree ret;
9645 timevar_push (TV_TEMPLATE_INST);
9646 ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9647 entering_scope, complain);
9648 timevar_pop (TV_TEMPLATE_INST);
9649 return ret;
9652 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
9654 tree
9655 lookup_template_variable (tree templ, tree arglist)
9657 /* The type of the expression is NULL_TREE since the template-id could refer
9658 to an explicit or partial specialization. */
9659 tree type = NULL_TREE;
9660 if (flag_concepts && variable_concept_p (templ))
9661 /* Except that concepts are always bool. */
9662 type = boolean_type_node;
9663 return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9666 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9668 tree
9669 finish_template_variable (tree var, tsubst_flags_t complain)
9671 tree templ = TREE_OPERAND (var, 0);
9672 tree arglist = TREE_OPERAND (var, 1);
9674 /* We never want to return a VAR_DECL for a variable concept, since they
9675 aren't instantiated. In a template, leave the TEMPLATE_ID_EXPR alone. */
9676 bool concept_p = flag_concepts && variable_concept_p (templ);
9677 if (concept_p && processing_template_decl)
9678 return var;
9680 tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9681 arglist = add_outermost_template_args (tmpl_args, arglist);
9683 templ = most_general_template (templ);
9684 tree parms = DECL_TEMPLATE_PARMS (templ);
9685 arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9686 /*req_all*/true,
9687 /*use_default*/true);
9689 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9691 if (complain & tf_error)
9693 error ("use of invalid variable template %qE", var);
9694 diagnose_constraints (location_of (var), templ, arglist);
9696 return error_mark_node;
9699 /* If a template-id refers to a specialization of a variable
9700 concept, then the expression is true if and only if the
9701 concept's constraints are satisfied by the given template
9702 arguments.
9704 NOTE: This is an extension of Concepts Lite TS that
9705 allows constraints to be used in expressions. */
9706 if (concept_p)
9708 tree decl = DECL_TEMPLATE_RESULT (templ);
9709 return evaluate_variable_concept (decl, arglist);
9712 return instantiate_template (templ, arglist, complain);
9715 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9716 TARGS template args, and instantiate it if it's not dependent. */
9718 tree
9719 lookup_and_finish_template_variable (tree templ, tree targs,
9720 tsubst_flags_t complain)
9722 templ = lookup_template_variable (templ, targs);
9723 if (!any_dependent_template_arguments_p (targs))
9725 templ = finish_template_variable (templ, complain);
9726 mark_used (templ);
9729 return convert_from_reference (templ);
9733 struct pair_fn_data
9735 tree_fn_t fn;
9736 tree_fn_t any_fn;
9737 void *data;
9738 /* True when we should also visit template parameters that occur in
9739 non-deduced contexts. */
9740 bool include_nondeduced_p;
9741 hash_set<tree> *visited;
9744 /* Called from for_each_template_parm via walk_tree. */
9746 static tree
9747 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9749 tree t = *tp;
9750 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9751 tree_fn_t fn = pfd->fn;
9752 void *data = pfd->data;
9753 tree result = NULL_TREE;
9755 #define WALK_SUBTREE(NODE) \
9756 do \
9758 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
9759 pfd->include_nondeduced_p, \
9760 pfd->any_fn); \
9761 if (result) goto out; \
9763 while (0)
9765 if (pfd->any_fn && (*pfd->any_fn)(t, data))
9766 return t;
9768 if (TYPE_P (t)
9769 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9770 WALK_SUBTREE (TYPE_CONTEXT (t));
9772 switch (TREE_CODE (t))
9774 case RECORD_TYPE:
9775 if (TYPE_PTRMEMFUNC_P (t))
9776 break;
9777 /* Fall through. */
9779 case UNION_TYPE:
9780 case ENUMERAL_TYPE:
9781 if (!TYPE_TEMPLATE_INFO (t))
9782 *walk_subtrees = 0;
9783 else
9784 WALK_SUBTREE (TYPE_TI_ARGS (t));
9785 break;
9787 case INTEGER_TYPE:
9788 WALK_SUBTREE (TYPE_MIN_VALUE (t));
9789 WALK_SUBTREE (TYPE_MAX_VALUE (t));
9790 break;
9792 case METHOD_TYPE:
9793 /* Since we're not going to walk subtrees, we have to do this
9794 explicitly here. */
9795 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9796 /* Fall through. */
9798 case FUNCTION_TYPE:
9799 /* Check the return type. */
9800 WALK_SUBTREE (TREE_TYPE (t));
9802 /* Check the parameter types. Since default arguments are not
9803 instantiated until they are needed, the TYPE_ARG_TYPES may
9804 contain expressions that involve template parameters. But,
9805 no-one should be looking at them yet. And, once they're
9806 instantiated, they don't contain template parameters, so
9807 there's no point in looking at them then, either. */
9809 tree parm;
9811 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9812 WALK_SUBTREE (TREE_VALUE (parm));
9814 /* Since we've already handled the TYPE_ARG_TYPES, we don't
9815 want walk_tree walking into them itself. */
9816 *walk_subtrees = 0;
9819 if (flag_noexcept_type)
9821 tree spec = TYPE_RAISES_EXCEPTIONS (t);
9822 if (spec)
9823 WALK_SUBTREE (TREE_PURPOSE (spec));
9825 break;
9827 case TYPEOF_TYPE:
9828 case DECLTYPE_TYPE:
9829 case UNDERLYING_TYPE:
9830 if (pfd->include_nondeduced_p
9831 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9832 pfd->visited,
9833 pfd->include_nondeduced_p,
9834 pfd->any_fn))
9835 return error_mark_node;
9836 *walk_subtrees = false;
9837 break;
9839 case FUNCTION_DECL:
9840 case VAR_DECL:
9841 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9842 WALK_SUBTREE (DECL_TI_ARGS (t));
9843 /* Fall through. */
9845 case PARM_DECL:
9846 case CONST_DECL:
9847 if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9848 WALK_SUBTREE (DECL_INITIAL (t));
9849 if (DECL_CONTEXT (t)
9850 && pfd->include_nondeduced_p)
9851 WALK_SUBTREE (DECL_CONTEXT (t));
9852 break;
9854 case BOUND_TEMPLATE_TEMPLATE_PARM:
9855 /* Record template parameters such as `T' inside `TT<T>'. */
9856 WALK_SUBTREE (TYPE_TI_ARGS (t));
9857 /* Fall through. */
9859 case TEMPLATE_TEMPLATE_PARM:
9860 case TEMPLATE_TYPE_PARM:
9861 case TEMPLATE_PARM_INDEX:
9862 if (fn && (*fn)(t, data))
9863 return t;
9864 else if (!fn)
9865 return t;
9866 break;
9868 case TEMPLATE_DECL:
9869 /* A template template parameter is encountered. */
9870 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9871 WALK_SUBTREE (TREE_TYPE (t));
9873 /* Already substituted template template parameter */
9874 *walk_subtrees = 0;
9875 break;
9877 case TYPENAME_TYPE:
9878 /* A template-id in a TYPENAME_TYPE might be a deduced context after
9879 partial instantiation. */
9880 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
9881 break;
9883 case CONSTRUCTOR:
9884 if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
9885 && pfd->include_nondeduced_p)
9886 WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
9887 break;
9889 case INDIRECT_REF:
9890 case COMPONENT_REF:
9891 /* If there's no type, then this thing must be some expression
9892 involving template parameters. */
9893 if (!fn && !TREE_TYPE (t))
9894 return error_mark_node;
9895 break;
9897 case MODOP_EXPR:
9898 case CAST_EXPR:
9899 case IMPLICIT_CONV_EXPR:
9900 case REINTERPRET_CAST_EXPR:
9901 case CONST_CAST_EXPR:
9902 case STATIC_CAST_EXPR:
9903 case DYNAMIC_CAST_EXPR:
9904 case ARROW_EXPR:
9905 case DOTSTAR_EXPR:
9906 case TYPEID_EXPR:
9907 case PSEUDO_DTOR_EXPR:
9908 if (!fn)
9909 return error_mark_node;
9910 break;
9912 default:
9913 break;
9916 #undef WALK_SUBTREE
9918 /* We didn't find any template parameters we liked. */
9919 out:
9920 return result;
9923 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
9924 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
9925 call FN with the parameter and the DATA.
9926 If FN returns nonzero, the iteration is terminated, and
9927 for_each_template_parm returns 1. Otherwise, the iteration
9928 continues. If FN never returns a nonzero value, the value
9929 returned by for_each_template_parm is 0. If FN is NULL, it is
9930 considered to be the function which always returns 1.
9932 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
9933 parameters that occur in non-deduced contexts. When false, only
9934 visits those template parameters that can be deduced. */
9936 static tree
9937 for_each_template_parm (tree t, tree_fn_t fn, void* data,
9938 hash_set<tree> *visited,
9939 bool include_nondeduced_p,
9940 tree_fn_t any_fn)
9942 struct pair_fn_data pfd;
9943 tree result;
9945 /* Set up. */
9946 pfd.fn = fn;
9947 pfd.any_fn = any_fn;
9948 pfd.data = data;
9949 pfd.include_nondeduced_p = include_nondeduced_p;
9951 /* Walk the tree. (Conceptually, we would like to walk without
9952 duplicates, but for_each_template_parm_r recursively calls
9953 for_each_template_parm, so we would need to reorganize a fair
9954 bit to use walk_tree_without_duplicates, so we keep our own
9955 visited list.) */
9956 if (visited)
9957 pfd.visited = visited;
9958 else
9959 pfd.visited = new hash_set<tree>;
9960 result = cp_walk_tree (&t,
9961 for_each_template_parm_r,
9962 &pfd,
9963 pfd.visited);
9965 /* Clean up. */
9966 if (!visited)
9968 delete pfd.visited;
9969 pfd.visited = 0;
9972 return result;
9975 /* Returns true if T depends on any template parameter. */
9978 uses_template_parms (tree t)
9980 if (t == NULL_TREE)
9981 return false;
9983 bool dependent_p;
9984 int saved_processing_template_decl;
9986 saved_processing_template_decl = processing_template_decl;
9987 if (!saved_processing_template_decl)
9988 processing_template_decl = 1;
9989 if (TYPE_P (t))
9990 dependent_p = dependent_type_p (t);
9991 else if (TREE_CODE (t) == TREE_VEC)
9992 dependent_p = any_dependent_template_arguments_p (t);
9993 else if (TREE_CODE (t) == TREE_LIST)
9994 dependent_p = (uses_template_parms (TREE_VALUE (t))
9995 || uses_template_parms (TREE_CHAIN (t)));
9996 else if (TREE_CODE (t) == TYPE_DECL)
9997 dependent_p = dependent_type_p (TREE_TYPE (t));
9998 else if (DECL_P (t)
9999 || EXPR_P (t)
10000 || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10001 || TREE_CODE (t) == OVERLOAD
10002 || BASELINK_P (t)
10003 || identifier_p (t)
10004 || TREE_CODE (t) == TRAIT_EXPR
10005 || TREE_CODE (t) == CONSTRUCTOR
10006 || CONSTANT_CLASS_P (t))
10007 dependent_p = (type_dependent_expression_p (t)
10008 || value_dependent_expression_p (t));
10009 else
10011 gcc_assert (t == error_mark_node);
10012 dependent_p = false;
10015 processing_template_decl = saved_processing_template_decl;
10017 return dependent_p;
10020 /* Returns true iff current_function_decl is an incompletely instantiated
10021 template. Useful instead of processing_template_decl because the latter
10022 is set to 0 during instantiate_non_dependent_expr. */
10024 bool
10025 in_template_function (void)
10027 tree fn = current_function_decl;
10028 bool ret;
10029 ++processing_template_decl;
10030 ret = (fn && DECL_LANG_SPECIFIC (fn)
10031 && DECL_TEMPLATE_INFO (fn)
10032 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10033 --processing_template_decl;
10034 return ret;
10037 /* Returns true if T depends on any template parameter with level LEVEL. */
10039 bool
10040 uses_template_parms_level (tree t, int level)
10042 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10043 /*include_nondeduced_p=*/true);
10046 /* Returns true if the signature of DECL depends on any template parameter from
10047 its enclosing class. */
10049 bool
10050 uses_outer_template_parms (tree decl)
10052 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10053 if (depth == 0)
10054 return false;
10055 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10056 &depth, NULL, /*include_nondeduced_p=*/true))
10057 return true;
10058 if (PRIMARY_TEMPLATE_P (decl)
10059 && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10060 (DECL_TEMPLATE_PARMS (decl)),
10061 template_parm_outer_level,
10062 &depth, NULL, /*include_nondeduced_p=*/true))
10063 return true;
10064 tree ci = get_constraints (decl);
10065 if (ci)
10066 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10067 if (ci && for_each_template_parm (ci, template_parm_outer_level,
10068 &depth, NULL, /*nondeduced*/true))
10069 return true;
10070 return false;
10073 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10074 ill-formed translation unit, i.e. a variable or function that isn't
10075 usable in a constant expression. */
10077 static inline bool
10078 neglectable_inst_p (tree d)
10080 return (d && DECL_P (d)
10081 && !undeduced_auto_decl (d)
10082 && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10083 : decl_maybe_constant_var_p (d)));
10086 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10087 neglectable and instantiated from within an erroneous instantiation. */
10089 static bool
10090 limit_bad_template_recursion (tree decl)
10092 struct tinst_level *lev = current_tinst_level;
10093 int errs = errorcount + sorrycount;
10094 if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10095 return false;
10097 for (; lev; lev = lev->next)
10098 if (neglectable_inst_p (lev->maybe_get_node ()))
10099 break;
10101 return (lev && errs > lev->errors);
10104 static int tinst_depth;
10105 extern int max_tinst_depth;
10106 int depth_reached;
10108 static GTY(()) struct tinst_level *last_error_tinst_level;
10110 /* We're starting to instantiate D; record the template instantiation context
10111 at LOC for diagnostics and to restore it later. */
10113 static bool
10114 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10116 struct tinst_level *new_level;
10118 if (tinst_depth >= max_tinst_depth)
10120 /* Tell error.c not to try to instantiate any templates. */
10121 at_eof = 2;
10122 fatal_error (input_location,
10123 "template instantiation depth exceeds maximum of %d"
10124 " (use -ftemplate-depth= to increase the maximum)",
10125 max_tinst_depth);
10126 return false;
10129 /* If the current instantiation caused problems, don't let it instantiate
10130 anything else. Do allow deduction substitution and decls usable in
10131 constant expressions. */
10132 if (!targs && limit_bad_template_recursion (tldcl))
10133 return false;
10135 /* When not -quiet, dump template instantiations other than functions, since
10136 announce_function will take care of those. */
10137 if (!quiet_flag && !targs
10138 && TREE_CODE (tldcl) != TREE_LIST
10139 && TREE_CODE (tldcl) != FUNCTION_DECL)
10140 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10142 new_level = tinst_level_freelist ().alloc ();
10143 new_level->tldcl = tldcl;
10144 new_level->targs = targs;
10145 new_level->locus = loc;
10146 new_level->errors = errorcount + sorrycount;
10147 new_level->next = NULL;
10148 new_level->refcount = 0;
10149 set_refcount_ptr (new_level->next, current_tinst_level);
10150 set_refcount_ptr (current_tinst_level, new_level);
10152 ++tinst_depth;
10153 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10154 depth_reached = tinst_depth;
10156 return true;
10159 /* We're starting substitution of TMPL<ARGS>; record the template
10160 substitution context for diagnostics and to restore it later. */
10162 static bool
10163 push_tinst_level (tree tmpl, tree args)
10165 return push_tinst_level_loc (tmpl, args, input_location);
10168 /* We're starting to instantiate D; record INPUT_LOCATION and the
10169 template instantiation context for diagnostics and to restore it
10170 later. */
10172 bool
10173 push_tinst_level (tree d)
10175 return push_tinst_level_loc (d, input_location);
10178 /* Likewise, but record LOC as the program location. */
10180 bool
10181 push_tinst_level_loc (tree d, location_t loc)
10183 gcc_assert (TREE_CODE (d) != TREE_LIST);
10184 return push_tinst_level_loc (d, NULL, loc);
10187 /* We're done instantiating this template; return to the instantiation
10188 context. */
10190 void
10191 pop_tinst_level (void)
10193 /* Restore the filename and line number stashed away when we started
10194 this instantiation. */
10195 input_location = current_tinst_level->locus;
10196 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10197 --tinst_depth;
10200 /* We're instantiating a deferred template; restore the template
10201 instantiation context in which the instantiation was requested, which
10202 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
10204 static tree
10205 reopen_tinst_level (struct tinst_level *level)
10207 struct tinst_level *t;
10209 tinst_depth = 0;
10210 for (t = level; t; t = t->next)
10211 ++tinst_depth;
10213 set_refcount_ptr (current_tinst_level, level);
10214 pop_tinst_level ();
10215 if (current_tinst_level)
10216 current_tinst_level->errors = errorcount+sorrycount;
10217 return level->maybe_get_node ();
10220 /* Returns the TINST_LEVEL which gives the original instantiation
10221 context. */
10223 struct tinst_level *
10224 outermost_tinst_level (void)
10226 struct tinst_level *level = current_tinst_level;
10227 if (level)
10228 while (level->next)
10229 level = level->next;
10230 return level;
10233 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
10234 vector of template arguments, as for tsubst.
10236 Returns an appropriate tsubst'd friend declaration. */
10238 static tree
10239 tsubst_friend_function (tree decl, tree args)
10241 tree new_friend;
10243 if (TREE_CODE (decl) == FUNCTION_DECL
10244 && DECL_TEMPLATE_INSTANTIATION (decl)
10245 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10246 /* This was a friend declared with an explicit template
10247 argument list, e.g.:
10249 friend void f<>(T);
10251 to indicate that f was a template instantiation, not a new
10252 function declaration. Now, we have to figure out what
10253 instantiation of what template. */
10255 tree template_id, arglist, fns;
10256 tree new_args;
10257 tree tmpl;
10258 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10260 /* Friend functions are looked up in the containing namespace scope.
10261 We must enter that scope, to avoid finding member functions of the
10262 current class with same name. */
10263 push_nested_namespace (ns);
10264 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10265 tf_warning_or_error, NULL_TREE,
10266 /*integral_constant_expression_p=*/false);
10267 pop_nested_namespace (ns);
10268 arglist = tsubst (DECL_TI_ARGS (decl), args,
10269 tf_warning_or_error, NULL_TREE);
10270 template_id = lookup_template_function (fns, arglist);
10272 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10273 tmpl = determine_specialization (template_id, new_friend,
10274 &new_args,
10275 /*need_member_template=*/0,
10276 TREE_VEC_LENGTH (args),
10277 tsk_none);
10278 return instantiate_template (tmpl, new_args, tf_error);
10281 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10283 /* The NEW_FRIEND will look like an instantiation, to the
10284 compiler, but is not an instantiation from the point of view of
10285 the language. For example, we might have had:
10287 template <class T> struct S {
10288 template <class U> friend void f(T, U);
10291 Then, in S<int>, template <class U> void f(int, U) is not an
10292 instantiation of anything. */
10293 if (new_friend == error_mark_node)
10294 return error_mark_node;
10296 DECL_USE_TEMPLATE (new_friend) = 0;
10297 if (TREE_CODE (decl) == TEMPLATE_DECL)
10299 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10300 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10301 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10304 /* The mangled name for the NEW_FRIEND is incorrect. The function
10305 is not a template instantiation and should not be mangled like
10306 one. Therefore, we forget the mangling here; we'll recompute it
10307 later if we need it. */
10308 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10310 SET_DECL_RTL (new_friend, NULL);
10311 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10314 if (DECL_NAMESPACE_SCOPE_P (new_friend))
10316 tree old_decl;
10317 tree new_friend_template_info;
10318 tree new_friend_result_template_info;
10319 tree ns;
10320 int new_friend_is_defn;
10322 /* We must save some information from NEW_FRIEND before calling
10323 duplicate decls since that function will free NEW_FRIEND if
10324 possible. */
10325 new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10326 new_friend_is_defn =
10327 (DECL_INITIAL (DECL_TEMPLATE_RESULT
10328 (template_for_substitution (new_friend)))
10329 != NULL_TREE);
10330 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10332 /* This declaration is a `primary' template. */
10333 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10335 new_friend_result_template_info
10336 = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10338 else
10339 new_friend_result_template_info = NULL_TREE;
10341 /* Inside pushdecl_namespace_level, we will push into the
10342 current namespace. However, the friend function should go
10343 into the namespace of the template. */
10344 ns = decl_namespace_context (new_friend);
10345 push_nested_namespace (ns);
10346 old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10347 pop_nested_namespace (ns);
10349 if (old_decl == error_mark_node)
10350 return error_mark_node;
10352 if (old_decl != new_friend)
10354 /* This new friend declaration matched an existing
10355 declaration. For example, given:
10357 template <class T> void f(T);
10358 template <class U> class C {
10359 template <class T> friend void f(T) {}
10362 the friend declaration actually provides the definition
10363 of `f', once C has been instantiated for some type. So,
10364 old_decl will be the out-of-class template declaration,
10365 while new_friend is the in-class definition.
10367 But, if `f' was called before this point, the
10368 instantiation of `f' will have DECL_TI_ARGS corresponding
10369 to `T' but not to `U', references to which might appear
10370 in the definition of `f'. Previously, the most general
10371 template for an instantiation of `f' was the out-of-class
10372 version; now it is the in-class version. Therefore, we
10373 run through all specialization of `f', adding to their
10374 DECL_TI_ARGS appropriately. In particular, they need a
10375 new set of outer arguments, corresponding to the
10376 arguments for this class instantiation.
10378 The same situation can arise with something like this:
10380 friend void f(int);
10381 template <class T> class C {
10382 friend void f(T) {}
10385 when `C<int>' is instantiated. Now, `f(int)' is defined
10386 in the class. */
10388 if (!new_friend_is_defn)
10389 /* On the other hand, if the in-class declaration does
10390 *not* provide a definition, then we don't want to alter
10391 existing definitions. We can just leave everything
10392 alone. */
10394 else
10396 tree new_template = TI_TEMPLATE (new_friend_template_info);
10397 tree new_args = TI_ARGS (new_friend_template_info);
10399 /* Overwrite whatever template info was there before, if
10400 any, with the new template information pertaining to
10401 the declaration. */
10402 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10404 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10406 /* We should have called reregister_specialization in
10407 duplicate_decls. */
10408 gcc_assert (retrieve_specialization (new_template,
10409 new_args, 0)
10410 == old_decl);
10412 /* Instantiate it if the global has already been used. */
10413 if (DECL_ODR_USED (old_decl))
10414 instantiate_decl (old_decl, /*defer_ok=*/true,
10415 /*expl_inst_class_mem_p=*/false);
10417 else
10419 tree t;
10421 /* Indicate that the old function template is a partial
10422 instantiation. */
10423 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10424 = new_friend_result_template_info;
10426 gcc_assert (new_template
10427 == most_general_template (new_template));
10428 gcc_assert (new_template != old_decl);
10430 /* Reassign any specializations already in the hash table
10431 to the new more general template, and add the
10432 additional template args. */
10433 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10434 t != NULL_TREE;
10435 t = TREE_CHAIN (t))
10437 tree spec = TREE_VALUE (t);
10438 spec_entry elt;
10440 elt.tmpl = old_decl;
10441 elt.args = DECL_TI_ARGS (spec);
10442 elt.spec = NULL_TREE;
10444 decl_specializations->remove_elt (&elt);
10446 DECL_TI_ARGS (spec)
10447 = add_outermost_template_args (new_args,
10448 DECL_TI_ARGS (spec));
10450 register_specialization
10451 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
10454 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10458 /* The information from NEW_FRIEND has been merged into OLD_DECL
10459 by duplicate_decls. */
10460 new_friend = old_decl;
10463 else
10465 tree context = DECL_CONTEXT (new_friend);
10466 bool dependent_p;
10468 /* In the code
10469 template <class T> class C {
10470 template <class U> friend void C1<U>::f (); // case 1
10471 friend void C2<T>::f (); // case 2
10473 we only need to make sure CONTEXT is a complete type for
10474 case 2. To distinguish between the two cases, we note that
10475 CONTEXT of case 1 remains dependent type after tsubst while
10476 this isn't true for case 2. */
10477 ++processing_template_decl;
10478 dependent_p = dependent_type_p (context);
10479 --processing_template_decl;
10481 if (!dependent_p
10482 && !complete_type_or_else (context, NULL_TREE))
10483 return error_mark_node;
10485 if (COMPLETE_TYPE_P (context))
10487 tree fn = new_friend;
10488 /* do_friend adds the TEMPLATE_DECL for any member friend
10489 template even if it isn't a member template, i.e.
10490 template <class T> friend A<T>::f();
10491 Look through it in that case. */
10492 if (TREE_CODE (fn) == TEMPLATE_DECL
10493 && !PRIMARY_TEMPLATE_P (fn))
10494 fn = DECL_TEMPLATE_RESULT (fn);
10495 /* Check to see that the declaration is really present, and,
10496 possibly obtain an improved declaration. */
10497 fn = check_classfn (context, fn, NULL_TREE);
10499 if (fn)
10500 new_friend = fn;
10504 return new_friend;
10507 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
10508 template arguments, as for tsubst.
10510 Returns an appropriate tsubst'd friend type or error_mark_node on
10511 failure. */
10513 static tree
10514 tsubst_friend_class (tree friend_tmpl, tree args)
10516 tree tmpl;
10518 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10520 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10521 return TREE_TYPE (tmpl);
10524 tree context = CP_DECL_CONTEXT (friend_tmpl);
10525 if (TREE_CODE (context) == NAMESPACE_DECL)
10526 push_nested_namespace (context);
10527 else
10528 push_nested_class (context);
10530 tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10531 /*non_class=*/false, /*block_p=*/false,
10532 /*namespaces_only=*/false, LOOKUP_HIDDEN);
10534 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10536 /* The friend template has already been declared. Just
10537 check to see that the declarations match, and install any new
10538 default parameters. We must tsubst the default parameters,
10539 of course. We only need the innermost template parameters
10540 because that is all that redeclare_class_template will look
10541 at. */
10542 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10543 > TMPL_ARGS_DEPTH (args))
10545 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10546 args, tf_warning_or_error);
10547 location_t saved_input_location = input_location;
10548 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10549 tree cons = get_constraints (tmpl);
10550 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10551 input_location = saved_input_location;
10554 else
10556 /* The friend template has not already been declared. In this
10557 case, the instantiation of the template class will cause the
10558 injection of this template into the namespace scope. */
10559 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10561 if (tmpl != error_mark_node)
10563 /* The new TMPL is not an instantiation of anything, so we
10564 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
10565 for the new type because that is supposed to be the
10566 corresponding template decl, i.e., TMPL. */
10567 DECL_USE_TEMPLATE (tmpl) = 0;
10568 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10569 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10570 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10571 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10573 /* It is hidden. */
10574 retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10575 DECL_ANTICIPATED (tmpl)
10576 = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10578 /* Inject this template into the enclosing namspace scope. */
10579 tmpl = pushdecl_namespace_level (tmpl, true);
10583 if (TREE_CODE (context) == NAMESPACE_DECL)
10584 pop_nested_namespace (context);
10585 else
10586 pop_nested_class ();
10588 return TREE_TYPE (tmpl);
10591 /* Returns zero if TYPE cannot be completed later due to circularity.
10592 Otherwise returns one. */
10594 static int
10595 can_complete_type_without_circularity (tree type)
10597 if (type == NULL_TREE || type == error_mark_node)
10598 return 0;
10599 else if (COMPLETE_TYPE_P (type))
10600 return 1;
10601 else if (TREE_CODE (type) == ARRAY_TYPE)
10602 return can_complete_type_without_circularity (TREE_TYPE (type));
10603 else if (CLASS_TYPE_P (type)
10604 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10605 return 0;
10606 else
10607 return 1;
10610 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10611 tsubst_flags_t, tree);
10613 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10614 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
10616 static tree
10617 tsubst_attribute (tree t, tree *decl_p, tree args,
10618 tsubst_flags_t complain, tree in_decl)
10620 gcc_assert (ATTR_IS_DEPENDENT (t));
10622 tree val = TREE_VALUE (t);
10623 if (val == NULL_TREE)
10624 /* Nothing to do. */;
10625 else if ((flag_openmp || flag_openmp_simd)
10626 && is_attribute_p ("omp declare simd",
10627 get_attribute_name (t)))
10629 tree clauses = TREE_VALUE (val);
10630 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10631 complain, in_decl);
10632 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10633 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10634 tree parms = DECL_ARGUMENTS (*decl_p);
10635 clauses
10636 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10637 if (clauses)
10638 val = build_tree_list (NULL_TREE, clauses);
10639 else
10640 val = NULL_TREE;
10642 /* If the first attribute argument is an identifier, don't
10643 pass it through tsubst. Attributes like mode, format,
10644 cleanup and several target specific attributes expect it
10645 unmodified. */
10646 else if (attribute_takes_identifier_p (get_attribute_name (t)))
10648 tree chain
10649 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10650 /*integral_constant_expression_p=*/false);
10651 if (chain != TREE_CHAIN (val))
10652 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10654 else if (PACK_EXPANSION_P (val))
10656 /* An attribute pack expansion. */
10657 tree purp = TREE_PURPOSE (t);
10658 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10659 if (pack == error_mark_node)
10660 return error_mark_node;
10661 int len = TREE_VEC_LENGTH (pack);
10662 tree list = NULL_TREE;
10663 tree *q = &list;
10664 for (int i = 0; i < len; ++i)
10666 tree elt = TREE_VEC_ELT (pack, i);
10667 *q = build_tree_list (purp, elt);
10668 q = &TREE_CHAIN (*q);
10670 return list;
10672 else
10673 val = tsubst_expr (val, args, complain, in_decl,
10674 /*integral_constant_expression_p=*/false);
10676 if (val != TREE_VALUE (t))
10677 return build_tree_list (TREE_PURPOSE (t), val);
10678 return t;
10681 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10682 unchanged or a new TREE_LIST chain. */
10684 static tree
10685 tsubst_attributes (tree attributes, tree args,
10686 tsubst_flags_t complain, tree in_decl)
10688 tree last_dep = NULL_TREE;
10690 for (tree t = attributes; t; t = TREE_CHAIN (t))
10691 if (ATTR_IS_DEPENDENT (t))
10693 last_dep = t;
10694 attributes = copy_list (attributes);
10695 break;
10698 if (last_dep)
10699 for (tree *p = &attributes; *p; )
10701 tree t = *p;
10702 if (ATTR_IS_DEPENDENT (t))
10704 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10705 if (subst != t)
10707 *p = subst;
10708 while (*p)
10709 p = &TREE_CHAIN (*p);
10710 *p = TREE_CHAIN (t);
10711 continue;
10714 p = &TREE_CHAIN (*p);
10717 return attributes;
10720 /* Apply any attributes which had to be deferred until instantiation
10721 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10722 ARGS, COMPLAIN, IN_DECL are as tsubst. */
10724 static void
10725 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10726 tree args, tsubst_flags_t complain, tree in_decl)
10728 tree last_dep = NULL_TREE;
10729 tree t;
10730 tree *p;
10732 if (attributes == NULL_TREE)
10733 return;
10735 if (DECL_P (*decl_p))
10737 if (TREE_TYPE (*decl_p) == error_mark_node)
10738 return;
10739 p = &DECL_ATTRIBUTES (*decl_p);
10740 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10741 to our attributes parameter. */
10742 gcc_assert (*p == attributes);
10744 else
10746 p = &TYPE_ATTRIBUTES (*decl_p);
10747 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10748 lookup_template_class_1, and should be preserved. */
10749 gcc_assert (*p != attributes);
10750 while (*p)
10751 p = &TREE_CHAIN (*p);
10754 for (t = attributes; t; t = TREE_CHAIN (t))
10755 if (ATTR_IS_DEPENDENT (t))
10757 last_dep = t;
10758 attributes = copy_list (attributes);
10759 break;
10762 *p = attributes;
10763 if (last_dep)
10765 tree late_attrs = NULL_TREE;
10766 tree *q = &late_attrs;
10768 for (; *p; )
10770 t = *p;
10771 if (ATTR_IS_DEPENDENT (t))
10773 *p = TREE_CHAIN (t);
10774 TREE_CHAIN (t) = NULL_TREE;
10775 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10776 while (*q)
10777 q = &TREE_CHAIN (*q);
10779 else
10780 p = &TREE_CHAIN (t);
10783 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10787 /* Perform (or defer) access check for typedefs that were referenced
10788 from within the template TMPL code.
10789 This is a subroutine of instantiate_decl and instantiate_class_template.
10790 TMPL is the template to consider and TARGS is the list of arguments of
10791 that template. */
10793 static void
10794 perform_typedefs_access_check (tree tmpl, tree targs)
10796 location_t saved_location;
10797 unsigned i;
10798 qualified_typedef_usage_t *iter;
10800 if (!tmpl
10801 || (!CLASS_TYPE_P (tmpl)
10802 && TREE_CODE (tmpl) != FUNCTION_DECL))
10803 return;
10805 saved_location = input_location;
10806 FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10808 tree type_decl = iter->typedef_decl;
10809 tree type_scope = iter->context;
10811 if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10812 continue;
10814 if (uses_template_parms (type_decl))
10815 type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10816 if (uses_template_parms (type_scope))
10817 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10819 /* Make access check error messages point to the location
10820 of the use of the typedef. */
10821 input_location = iter->locus;
10822 perform_or_defer_access_check (TYPE_BINFO (type_scope),
10823 type_decl, type_decl,
10824 tf_warning_or_error);
10826 input_location = saved_location;
10829 static tree
10830 instantiate_class_template_1 (tree type)
10832 tree templ, args, pattern, t, member;
10833 tree typedecl;
10834 tree pbinfo;
10835 tree base_list;
10836 unsigned int saved_maximum_field_alignment;
10837 tree fn_context;
10839 if (type == error_mark_node)
10840 return error_mark_node;
10842 if (COMPLETE_OR_OPEN_TYPE_P (type)
10843 || uses_template_parms (type))
10844 return type;
10846 /* Figure out which template is being instantiated. */
10847 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10848 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10850 /* Mark the type as in the process of being defined. */
10851 TYPE_BEING_DEFINED (type) = 1;
10853 /* We may be in the middle of deferred access check. Disable
10854 it now. */
10855 deferring_access_check_sentinel acs (dk_no_deferred);
10857 /* Determine what specialization of the original template to
10858 instantiate. */
10859 t = most_specialized_partial_spec (type, tf_warning_or_error);
10860 if (t == error_mark_node)
10861 return error_mark_node;
10862 else if (t)
10864 /* This TYPE is actually an instantiation of a partial
10865 specialization. We replace the innermost set of ARGS with
10866 the arguments appropriate for substitution. For example,
10867 given:
10869 template <class T> struct S {};
10870 template <class T> struct S<T*> {};
10872 and supposing that we are instantiating S<int*>, ARGS will
10873 presently be {int*} -- but we need {int}. */
10874 pattern = TREE_TYPE (t);
10875 args = TREE_PURPOSE (t);
10877 else
10879 pattern = TREE_TYPE (templ);
10880 args = CLASSTYPE_TI_ARGS (type);
10883 /* If the template we're instantiating is incomplete, then clearly
10884 there's nothing we can do. */
10885 if (!COMPLETE_TYPE_P (pattern))
10887 /* We can try again later. */
10888 TYPE_BEING_DEFINED (type) = 0;
10889 return type;
10892 /* If we've recursively instantiated too many templates, stop. */
10893 if (! push_tinst_level (type))
10894 return type;
10896 int saved_unevaluated_operand = cp_unevaluated_operand;
10897 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10899 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
10900 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
10901 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
10902 fn_context = error_mark_node;
10903 if (!fn_context)
10904 push_to_top_level ();
10905 else
10907 cp_unevaluated_operand = 0;
10908 c_inhibit_evaluation_warnings = 0;
10910 /* Use #pragma pack from the template context. */
10911 saved_maximum_field_alignment = maximum_field_alignment;
10912 maximum_field_alignment = TYPE_PRECISION (pattern);
10914 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
10916 /* Set the input location to the most specialized template definition.
10917 This is needed if tsubsting causes an error. */
10918 typedecl = TYPE_MAIN_DECL (pattern);
10919 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
10920 DECL_SOURCE_LOCATION (typedecl);
10922 TYPE_PACKED (type) = TYPE_PACKED (pattern);
10923 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
10924 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
10925 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
10926 if (ANON_AGGR_TYPE_P (pattern))
10927 SET_ANON_AGGR_TYPE_P (type);
10928 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
10930 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
10931 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
10932 /* Adjust visibility for template arguments. */
10933 determine_visibility (TYPE_MAIN_DECL (type));
10935 if (CLASS_TYPE_P (type))
10936 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
10938 pbinfo = TYPE_BINFO (pattern);
10940 /* We should never instantiate a nested class before its enclosing
10941 class; we need to look up the nested class by name before we can
10942 instantiate it, and that lookup should instantiate the enclosing
10943 class. */
10944 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
10945 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
10947 base_list = NULL_TREE;
10948 if (BINFO_N_BASE_BINFOS (pbinfo))
10950 tree pbase_binfo;
10951 tree pushed_scope;
10952 int i;
10954 /* We must enter the scope containing the type, as that is where
10955 the accessibility of types named in dependent bases are
10956 looked up from. */
10957 pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
10959 /* Substitute into each of the bases to determine the actual
10960 basetypes. */
10961 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
10963 tree base;
10964 tree access = BINFO_BASE_ACCESS (pbinfo, i);
10965 tree expanded_bases = NULL_TREE;
10966 int idx, len = 1;
10968 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
10970 expanded_bases =
10971 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
10972 args, tf_error, NULL_TREE);
10973 if (expanded_bases == error_mark_node)
10974 continue;
10976 len = TREE_VEC_LENGTH (expanded_bases);
10979 for (idx = 0; idx < len; idx++)
10981 if (expanded_bases)
10982 /* Extract the already-expanded base class. */
10983 base = TREE_VEC_ELT (expanded_bases, idx);
10984 else
10985 /* Substitute to figure out the base class. */
10986 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
10987 NULL_TREE);
10989 if (base == error_mark_node)
10990 continue;
10992 base_list = tree_cons (access, base, base_list);
10993 if (BINFO_VIRTUAL_P (pbase_binfo))
10994 TREE_TYPE (base_list) = integer_type_node;
10998 /* The list is now in reverse order; correct that. */
10999 base_list = nreverse (base_list);
11001 if (pushed_scope)
11002 pop_scope (pushed_scope);
11004 /* Now call xref_basetypes to set up all the base-class
11005 information. */
11006 xref_basetypes (type, base_list);
11008 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11009 (int) ATTR_FLAG_TYPE_IN_PLACE,
11010 args, tf_error, NULL_TREE);
11011 fixup_attribute_variants (type);
11013 /* Now that our base classes are set up, enter the scope of the
11014 class, so that name lookups into base classes, etc. will work
11015 correctly. This is precisely analogous to what we do in
11016 begin_class_definition when defining an ordinary non-template
11017 class, except we also need to push the enclosing classes. */
11018 push_nested_class (type);
11020 /* Now members are processed in the order of declaration. */
11021 for (member = CLASSTYPE_DECL_LIST (pattern);
11022 member; member = TREE_CHAIN (member))
11024 tree t = TREE_VALUE (member);
11026 if (TREE_PURPOSE (member))
11028 if (TYPE_P (t))
11030 if (LAMBDA_TYPE_P (t))
11031 /* A closure type for a lambda in an NSDMI or default argument.
11032 Ignore it; it will be regenerated when needed. */
11033 continue;
11035 /* Build new CLASSTYPE_NESTED_UTDS. */
11037 tree newtag;
11038 bool class_template_p;
11040 class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11041 && TYPE_LANG_SPECIFIC (t)
11042 && CLASSTYPE_IS_TEMPLATE (t));
11043 /* If the member is a class template, then -- even after
11044 substitution -- there may be dependent types in the
11045 template argument list for the class. We increment
11046 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11047 that function will assume that no types are dependent
11048 when outside of a template. */
11049 if (class_template_p)
11050 ++processing_template_decl;
11051 newtag = tsubst (t, args, tf_error, NULL_TREE);
11052 if (class_template_p)
11053 --processing_template_decl;
11054 if (newtag == error_mark_node)
11055 continue;
11057 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11059 tree name = TYPE_IDENTIFIER (t);
11061 if (class_template_p)
11062 /* Unfortunately, lookup_template_class sets
11063 CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11064 instantiation (i.e., for the type of a member
11065 template class nested within a template class.)
11066 This behavior is required for
11067 maybe_process_partial_specialization to work
11068 correctly, but is not accurate in this case;
11069 the TAG is not an instantiation of anything.
11070 (The corresponding TEMPLATE_DECL is an
11071 instantiation, but the TYPE is not.) */
11072 CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11074 /* Now, we call pushtag to put this NEWTAG into the scope of
11075 TYPE. We first set up the IDENTIFIER_TYPE_VALUE to avoid
11076 pushtag calling push_template_decl. We don't have to do
11077 this for enums because it will already have been done in
11078 tsubst_enum. */
11079 if (name)
11080 SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11081 pushtag (name, newtag, /*tag_scope=*/ts_current);
11084 else if (DECL_DECLARES_FUNCTION_P (t))
11086 tree r;
11088 if (TREE_CODE (t) == TEMPLATE_DECL)
11089 ++processing_template_decl;
11090 r = tsubst (t, args, tf_error, NULL_TREE);
11091 if (TREE_CODE (t) == TEMPLATE_DECL)
11092 --processing_template_decl;
11093 set_current_access_from_decl (r);
11094 finish_member_declaration (r);
11095 /* Instantiate members marked with attribute used. */
11096 if (r != error_mark_node && DECL_PRESERVE_P (r))
11097 mark_used (r);
11098 if (TREE_CODE (r) == FUNCTION_DECL
11099 && DECL_OMP_DECLARE_REDUCTION_P (r))
11100 cp_check_omp_declare_reduction (r);
11102 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11103 && LAMBDA_TYPE_P (TREE_TYPE (t)))
11104 /* A closure type for a lambda in an NSDMI or default argument.
11105 Ignore it; it will be regenerated when needed. */;
11106 else
11108 /* Build new TYPE_FIELDS. */
11109 if (TREE_CODE (t) == STATIC_ASSERT)
11111 tree condition;
11113 ++c_inhibit_evaluation_warnings;
11114 condition =
11115 tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11116 tf_warning_or_error, NULL_TREE,
11117 /*integral_constant_expression_p=*/true);
11118 --c_inhibit_evaluation_warnings;
11120 finish_static_assert (condition,
11121 STATIC_ASSERT_MESSAGE (t),
11122 STATIC_ASSERT_SOURCE_LOCATION (t),
11123 /*member_p=*/true);
11125 else if (TREE_CODE (t) != CONST_DECL)
11127 tree r;
11128 tree vec = NULL_TREE;
11129 int len = 1;
11131 /* The file and line for this declaration, to
11132 assist in error message reporting. Since we
11133 called push_tinst_level above, we don't need to
11134 restore these. */
11135 input_location = DECL_SOURCE_LOCATION (t);
11137 if (TREE_CODE (t) == TEMPLATE_DECL)
11138 ++processing_template_decl;
11139 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11140 if (TREE_CODE (t) == TEMPLATE_DECL)
11141 --processing_template_decl;
11143 if (TREE_CODE (r) == TREE_VEC)
11145 /* A capture pack became multiple fields. */
11146 vec = r;
11147 len = TREE_VEC_LENGTH (vec);
11150 for (int i = 0; i < len; ++i)
11152 if (vec)
11153 r = TREE_VEC_ELT (vec, i);
11154 if (VAR_P (r))
11156 /* In [temp.inst]:
11158 [t]he initialization (and any associated
11159 side-effects) of a static data member does
11160 not occur unless the static data member is
11161 itself used in a way that requires the
11162 definition of the static data member to
11163 exist.
11165 Therefore, we do not substitute into the
11166 initialized for the static data member here. */
11167 finish_static_data_member_decl
11169 /*init=*/NULL_TREE,
11170 /*init_const_expr_p=*/false,
11171 /*asmspec_tree=*/NULL_TREE,
11172 /*flags=*/0);
11173 /* Instantiate members marked with attribute used. */
11174 if (r != error_mark_node && DECL_PRESERVE_P (r))
11175 mark_used (r);
11177 else if (TREE_CODE (r) == FIELD_DECL)
11179 /* Determine whether R has a valid type and can be
11180 completed later. If R is invalid, then its type
11181 is replaced by error_mark_node. */
11182 tree rtype = TREE_TYPE (r);
11183 if (can_complete_type_without_circularity (rtype))
11184 complete_type (rtype);
11186 if (!complete_or_array_type_p (rtype))
11188 /* If R's type couldn't be completed and
11189 it isn't a flexible array member (whose
11190 type is incomplete by definition) give
11191 an error. */
11192 cxx_incomplete_type_error (r, rtype);
11193 TREE_TYPE (r) = error_mark_node;
11195 else if (TREE_CODE (rtype) == ARRAY_TYPE
11196 && TYPE_DOMAIN (rtype) == NULL_TREE
11197 && (TREE_CODE (type) == UNION_TYPE
11198 || TREE_CODE (type) == QUAL_UNION_TYPE))
11200 error ("flexible array member %qD in union", r);
11201 TREE_TYPE (r) = error_mark_node;
11205 /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11206 such a thing will already have been added to the field
11207 list by tsubst_enum in finish_member_declaration in the
11208 CLASSTYPE_NESTED_UTDS case above. */
11209 if (!(TREE_CODE (r) == TYPE_DECL
11210 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11211 && DECL_ARTIFICIAL (r)))
11213 set_current_access_from_decl (r);
11214 finish_member_declaration (r);
11220 else
11222 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11223 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11225 /* Build new CLASSTYPE_FRIEND_CLASSES. */
11227 tree friend_type = t;
11228 bool adjust_processing_template_decl = false;
11230 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11232 /* template <class T> friend class C; */
11233 friend_type = tsubst_friend_class (friend_type, args);
11234 adjust_processing_template_decl = true;
11236 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11238 /* template <class T> friend class C::D; */
11239 friend_type = tsubst (friend_type, args,
11240 tf_warning_or_error, NULL_TREE);
11241 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11242 friend_type = TREE_TYPE (friend_type);
11243 adjust_processing_template_decl = true;
11245 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11246 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11248 /* This could be either
11250 friend class T::C;
11252 when dependent_type_p is false or
11254 template <class U> friend class T::C;
11256 otherwise. */
11257 /* Bump processing_template_decl in case this is something like
11258 template <class T> friend struct A<T>::B. */
11259 ++processing_template_decl;
11260 friend_type = tsubst (friend_type, args,
11261 tf_warning_or_error, NULL_TREE);
11262 if (dependent_type_p (friend_type))
11263 adjust_processing_template_decl = true;
11264 --processing_template_decl;
11266 else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11267 && !CLASSTYPE_USE_TEMPLATE (friend_type)
11268 && TYPE_HIDDEN_P (friend_type))
11270 /* friend class C;
11272 where C hasn't been declared yet. Let's lookup name
11273 from namespace scope directly, bypassing any name that
11274 come from dependent base class. */
11275 tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11277 /* The call to xref_tag_from_type does injection for friend
11278 classes. */
11279 push_nested_namespace (ns);
11280 friend_type =
11281 xref_tag_from_type (friend_type, NULL_TREE,
11282 /*tag_scope=*/ts_current);
11283 pop_nested_namespace (ns);
11285 else if (uses_template_parms (friend_type))
11286 /* friend class C<T>; */
11287 friend_type = tsubst (friend_type, args,
11288 tf_warning_or_error, NULL_TREE);
11289 /* Otherwise it's
11291 friend class C;
11293 where C is already declared or
11295 friend class C<int>;
11297 We don't have to do anything in these cases. */
11299 if (adjust_processing_template_decl)
11300 /* Trick make_friend_class into realizing that the friend
11301 we're adding is a template, not an ordinary class. It's
11302 important that we use make_friend_class since it will
11303 perform some error-checking and output cross-reference
11304 information. */
11305 ++processing_template_decl;
11307 if (friend_type != error_mark_node)
11308 make_friend_class (type, friend_type, /*complain=*/false);
11310 if (adjust_processing_template_decl)
11311 --processing_template_decl;
11313 else
11315 /* Build new DECL_FRIENDLIST. */
11316 tree r;
11318 /* The file and line for this declaration, to
11319 assist in error message reporting. Since we
11320 called push_tinst_level above, we don't need to
11321 restore these. */
11322 input_location = DECL_SOURCE_LOCATION (t);
11324 if (TREE_CODE (t) == TEMPLATE_DECL)
11326 ++processing_template_decl;
11327 push_deferring_access_checks (dk_no_check);
11330 r = tsubst_friend_function (t, args);
11331 add_friend (type, r, /*complain=*/false);
11332 if (TREE_CODE (t) == TEMPLATE_DECL)
11334 pop_deferring_access_checks ();
11335 --processing_template_decl;
11341 if (fn_context)
11343 /* Restore these before substituting into the lambda capture
11344 initializers. */
11345 cp_unevaluated_operand = saved_unevaluated_operand;
11346 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11349 /* Set the file and line number information to whatever is given for
11350 the class itself. This puts error messages involving generated
11351 implicit functions at a predictable point, and the same point
11352 that would be used for non-template classes. */
11353 input_location = DECL_SOURCE_LOCATION (typedecl);
11355 unreverse_member_declarations (type);
11356 finish_struct_1 (type);
11357 TYPE_BEING_DEFINED (type) = 0;
11359 /* We don't instantiate default arguments for member functions. 14.7.1:
11361 The implicit instantiation of a class template specialization causes
11362 the implicit instantiation of the declarations, but not of the
11363 definitions or default arguments, of the class member functions,
11364 member classes, static data members and member templates.... */
11366 /* Some typedefs referenced from within the template code need to be access
11367 checked at template instantiation time, i.e now. These types were
11368 added to the template at parsing time. Let's get those and perform
11369 the access checks then. */
11370 perform_typedefs_access_check (pattern, args);
11371 perform_deferred_access_checks (tf_warning_or_error);
11372 pop_nested_class ();
11373 maximum_field_alignment = saved_maximum_field_alignment;
11374 if (!fn_context)
11375 pop_from_top_level ();
11376 pop_tinst_level ();
11378 /* The vtable for a template class can be emitted in any translation
11379 unit in which the class is instantiated. When there is no key
11380 method, however, finish_struct_1 will already have added TYPE to
11381 the keyed_classes. */
11382 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11383 vec_safe_push (keyed_classes, type);
11385 return type;
11388 /* Wrapper for instantiate_class_template_1. */
11390 tree
11391 instantiate_class_template (tree type)
11393 tree ret;
11394 timevar_push (TV_TEMPLATE_INST);
11395 ret = instantiate_class_template_1 (type);
11396 timevar_pop (TV_TEMPLATE_INST);
11397 return ret;
11400 static tree
11401 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11403 tree r;
11405 if (!t)
11406 r = t;
11407 else if (TYPE_P (t))
11408 r = tsubst (t, args, complain, in_decl);
11409 else
11411 if (!(complain & tf_warning))
11412 ++c_inhibit_evaluation_warnings;
11413 r = tsubst_expr (t, args, complain, in_decl,
11414 /*integral_constant_expression_p=*/true);
11415 if (!(complain & tf_warning))
11416 --c_inhibit_evaluation_warnings;
11418 return r;
11421 /* Given a function parameter pack TMPL_PARM and some function parameters
11422 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11423 and set *SPEC_P to point at the next point in the list. */
11425 tree
11426 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11428 /* Collect all of the extra "packed" parameters into an
11429 argument pack. */
11430 tree parmvec;
11431 tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11432 tree spec_parm = *spec_p;
11433 int i, len;
11435 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11436 if (tmpl_parm
11437 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11438 break;
11440 /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters. */
11441 parmvec = make_tree_vec (len);
11442 spec_parm = *spec_p;
11443 for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11445 tree elt = spec_parm;
11446 if (DECL_PACK_P (elt))
11447 elt = make_pack_expansion (elt);
11448 TREE_VEC_ELT (parmvec, i) = elt;
11451 /* Build the argument packs. */
11452 SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11453 *spec_p = spec_parm;
11455 return argpack;
11458 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11459 NONTYPE_ARGUMENT_PACK. */
11461 static tree
11462 make_fnparm_pack (tree spec_parm)
11464 return extract_fnparm_pack (NULL_TREE, &spec_parm);
11467 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11468 pack expansion with no extra args, 2 if it has extra args, or 0
11469 if it is not a pack expansion. */
11471 static int
11472 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11474 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11475 if (i >= TREE_VEC_LENGTH (vec))
11476 return 0;
11477 tree elt = TREE_VEC_ELT (vec, i);
11478 if (DECL_P (elt))
11479 /* A decl pack is itself an expansion. */
11480 elt = TREE_TYPE (elt);
11481 if (!PACK_EXPANSION_P (elt))
11482 return 0;
11483 if (PACK_EXPANSION_EXTRA_ARGS (elt))
11484 return 2;
11485 return 1;
11489 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
11491 static tree
11492 make_argument_pack_select (tree arg_pack, unsigned index)
11494 tree aps = make_node (ARGUMENT_PACK_SELECT);
11496 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11497 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11499 return aps;
11502 /* This is a subroutine of tsubst_pack_expansion.
11504 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11505 mechanism to store the (non complete list of) arguments of the
11506 substitution and return a non substituted pack expansion, in order
11507 to wait for when we have enough arguments to really perform the
11508 substitution. */
11510 static bool
11511 use_pack_expansion_extra_args_p (tree parm_packs,
11512 int arg_pack_len,
11513 bool has_empty_arg)
11515 /* If one pack has an expansion and another pack has a normal
11516 argument or if one pack has an empty argument and an another
11517 one hasn't then tsubst_pack_expansion cannot perform the
11518 substitution and need to fall back on the
11519 PACK_EXPANSION_EXTRA mechanism. */
11520 if (parm_packs == NULL_TREE)
11521 return false;
11522 else if (has_empty_arg)
11523 return true;
11525 bool has_expansion_arg = false;
11526 for (int i = 0 ; i < arg_pack_len; ++i)
11528 bool has_non_expansion_arg = false;
11529 for (tree parm_pack = parm_packs;
11530 parm_pack;
11531 parm_pack = TREE_CHAIN (parm_pack))
11533 tree arg = TREE_VALUE (parm_pack);
11535 int exp = argument_pack_element_is_expansion_p (arg, i);
11536 if (exp == 2)
11537 /* We can't substitute a pack expansion with extra args into
11538 our pattern. */
11539 return true;
11540 else if (exp)
11541 has_expansion_arg = true;
11542 else
11543 has_non_expansion_arg = true;
11546 if (has_expansion_arg && has_non_expansion_arg)
11547 return true;
11549 return false;
11552 /* [temp.variadic]/6 says that:
11554 The instantiation of a pack expansion [...]
11555 produces a list E1,E2, ..., En, where N is the number of elements
11556 in the pack expansion parameters.
11558 This subroutine of tsubst_pack_expansion produces one of these Ei.
11560 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
11561 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11562 PATTERN, and each TREE_VALUE is its corresponding argument pack.
11563 INDEX is the index 'i' of the element Ei to produce. ARGS,
11564 COMPLAIN, and IN_DECL are the same parameters as for the
11565 tsubst_pack_expansion function.
11567 The function returns the resulting Ei upon successful completion,
11568 or error_mark_node.
11570 Note that this function possibly modifies the ARGS parameter, so
11571 it's the responsibility of the caller to restore it. */
11573 static tree
11574 gen_elem_of_pack_expansion_instantiation (tree pattern,
11575 tree parm_packs,
11576 unsigned index,
11577 tree args /* This parm gets
11578 modified. */,
11579 tsubst_flags_t complain,
11580 tree in_decl)
11582 tree t;
11583 bool ith_elem_is_expansion = false;
11585 /* For each parameter pack, change the substitution of the parameter
11586 pack to the ith argument in its argument pack, then expand the
11587 pattern. */
11588 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11590 tree parm = TREE_PURPOSE (pack);
11591 tree arg_pack = TREE_VALUE (pack);
11592 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
11594 ith_elem_is_expansion |=
11595 argument_pack_element_is_expansion_p (arg_pack, index);
11597 /* Select the Ith argument from the pack. */
11598 if (TREE_CODE (parm) == PARM_DECL
11599 || VAR_P (parm)
11600 || TREE_CODE (parm) == FIELD_DECL)
11602 if (index == 0)
11604 aps = make_argument_pack_select (arg_pack, index);
11605 if (!mark_used (parm, complain) && !(complain & tf_error))
11606 return error_mark_node;
11607 register_local_specialization (aps, parm);
11609 else
11610 aps = retrieve_local_specialization (parm);
11612 else
11614 int idx, level;
11615 template_parm_level_and_index (parm, &level, &idx);
11617 if (index == 0)
11619 aps = make_argument_pack_select (arg_pack, index);
11620 /* Update the corresponding argument. */
11621 TMPL_ARG (args, level, idx) = aps;
11623 else
11624 /* Re-use the ARGUMENT_PACK_SELECT. */
11625 aps = TMPL_ARG (args, level, idx);
11627 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11630 /* Substitute into the PATTERN with the (possibly altered)
11631 arguments. */
11632 if (pattern == in_decl)
11633 /* Expanding a fixed parameter pack from
11634 coerce_template_parameter_pack. */
11635 t = tsubst_decl (pattern, args, complain);
11636 else if (pattern == error_mark_node)
11637 t = error_mark_node;
11638 else if (constraint_p (pattern))
11640 if (processing_template_decl)
11641 t = tsubst_constraint (pattern, args, complain, in_decl);
11642 else
11643 t = (constraints_satisfied_p (pattern, args)
11644 ? boolean_true_node : boolean_false_node);
11646 else if (!TYPE_P (pattern))
11647 t = tsubst_expr (pattern, args, complain, in_decl,
11648 /*integral_constant_expression_p=*/false);
11649 else
11650 t = tsubst (pattern, args, complain, in_decl);
11652 /* If the Ith argument pack element is a pack expansion, then
11653 the Ith element resulting from the substituting is going to
11654 be a pack expansion as well. */
11655 if (ith_elem_is_expansion)
11656 t = make_pack_expansion (t, complain);
11658 return t;
11661 /* When the unexpanded parameter pack in a fold expression expands to an empty
11662 sequence, the value of the expression is as follows; the program is
11663 ill-formed if the operator is not listed in this table.
11665 && true
11666 || false
11667 , void() */
11669 tree
11670 expand_empty_fold (tree t, tsubst_flags_t complain)
11672 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11673 if (!FOLD_EXPR_MODIFY_P (t))
11674 switch (code)
11676 case TRUTH_ANDIF_EXPR:
11677 return boolean_true_node;
11678 case TRUTH_ORIF_EXPR:
11679 return boolean_false_node;
11680 case COMPOUND_EXPR:
11681 return void_node;
11682 default:
11683 break;
11686 if (complain & tf_error)
11687 error_at (location_of (t),
11688 "fold of empty expansion over %O", code);
11689 return error_mark_node;
11692 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11693 form an expression that combines the two terms using the
11694 operator of T. */
11696 static tree
11697 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11699 tree op = FOLD_EXPR_OP (t);
11700 tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11702 // Handle compound assignment operators.
11703 if (FOLD_EXPR_MODIFY_P (t))
11704 return build_x_modify_expr (input_location, left, code, right, complain);
11706 switch (code)
11708 case COMPOUND_EXPR:
11709 return build_x_compound_expr (input_location, left, right, complain);
11710 case DOTSTAR_EXPR:
11711 return build_m_component_ref (left, right, complain);
11712 default:
11713 return build_x_binary_op (input_location, code,
11714 left, TREE_CODE (left),
11715 right, TREE_CODE (right),
11716 /*overload=*/NULL,
11717 complain);
11721 /* Substitute ARGS into the pack of a fold expression T. */
11723 static inline tree
11724 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11726 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11729 /* Substitute ARGS into the pack of a fold expression T. */
11731 static inline tree
11732 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11734 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11737 /* Expand a PACK of arguments into a grouped as left fold.
11738 Given a pack containing elements A0, A1, ..., An and an
11739 operator @, this builds the expression:
11741 ((A0 @ A1) @ A2) ... @ An
11743 Note that PACK must not be empty.
11745 The operator is defined by the original fold expression T. */
11747 static tree
11748 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11750 tree left = TREE_VEC_ELT (pack, 0);
11751 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11753 tree right = TREE_VEC_ELT (pack, i);
11754 left = fold_expression (t, left, right, complain);
11756 return left;
11759 /* Substitute into a unary left fold expression. */
11761 static tree
11762 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11763 tree in_decl)
11765 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11766 if (pack == error_mark_node)
11767 return error_mark_node;
11768 if (PACK_EXPANSION_P (pack))
11770 tree r = copy_node (t);
11771 FOLD_EXPR_PACK (r) = pack;
11772 return r;
11774 if (TREE_VEC_LENGTH (pack) == 0)
11775 return expand_empty_fold (t, complain);
11776 else
11777 return expand_left_fold (t, pack, complain);
11780 /* Substitute into a binary left fold expression.
11782 Do ths by building a single (non-empty) vector of argumnts and
11783 building the expression from those elements. */
11785 static tree
11786 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11787 tree in_decl)
11789 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11790 if (pack == error_mark_node)
11791 return error_mark_node;
11792 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11793 if (init == error_mark_node)
11794 return error_mark_node;
11796 if (PACK_EXPANSION_P (pack))
11798 tree r = copy_node (t);
11799 FOLD_EXPR_PACK (r) = pack;
11800 FOLD_EXPR_INIT (r) = init;
11801 return r;
11804 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11805 TREE_VEC_ELT (vec, 0) = init;
11806 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11807 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11809 return expand_left_fold (t, vec, complain);
11812 /* Expand a PACK of arguments into a grouped as right fold.
11813 Given a pack containing elementns A0, A1, ..., and an
11814 operator @, this builds the expression:
11816 A0@ ... (An-2 @ (An-1 @ An))
11818 Note that PACK must not be empty.
11820 The operator is defined by the original fold expression T. */
11822 tree
11823 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11825 // Build the expression.
11826 int n = TREE_VEC_LENGTH (pack);
11827 tree right = TREE_VEC_ELT (pack, n - 1);
11828 for (--n; n != 0; --n)
11830 tree left = TREE_VEC_ELT (pack, n - 1);
11831 right = fold_expression (t, left, right, complain);
11833 return right;
11836 /* Substitute into a unary right fold expression. */
11838 static tree
11839 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11840 tree in_decl)
11842 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11843 if (pack == error_mark_node)
11844 return error_mark_node;
11845 if (PACK_EXPANSION_P (pack))
11847 tree r = copy_node (t);
11848 FOLD_EXPR_PACK (r) = pack;
11849 return r;
11851 if (TREE_VEC_LENGTH (pack) == 0)
11852 return expand_empty_fold (t, complain);
11853 else
11854 return expand_right_fold (t, pack, complain);
11857 /* Substitute into a binary right fold expression.
11859 Do ths by building a single (non-empty) vector of arguments and
11860 building the expression from those elements. */
11862 static tree
11863 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11864 tree in_decl)
11866 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11867 if (pack == error_mark_node)
11868 return error_mark_node;
11869 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11870 if (init == error_mark_node)
11871 return error_mark_node;
11873 if (PACK_EXPANSION_P (pack))
11875 tree r = copy_node (t);
11876 FOLD_EXPR_PACK (r) = pack;
11877 FOLD_EXPR_INIT (r) = init;
11878 return r;
11881 int n = TREE_VEC_LENGTH (pack);
11882 tree vec = make_tree_vec (n + 1);
11883 for (int i = 0; i < n; ++i)
11884 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11885 TREE_VEC_ELT (vec, n) = init;
11887 return expand_right_fold (t, vec, complain);
11890 /* Walk through the pattern of a pack expansion, adding everything in
11891 local_specializations to a list. */
11893 struct el_data
11895 hash_set<tree> internal;
11896 tree extra;
11897 tsubst_flags_t complain;
11899 el_data (tsubst_flags_t c)
11900 : extra (NULL_TREE), complain (c) {}
11902 static tree
11903 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
11905 el_data &data = *reinterpret_cast<el_data*>(data_);
11906 tree *extra = &data.extra;
11907 tsubst_flags_t complain = data.complain;
11909 if (TYPE_P (*tp) && typedef_variant_p (*tp))
11910 /* Remember local typedefs (85214). */
11911 tp = &TYPE_NAME (*tp);
11913 if (TREE_CODE (*tp) == DECL_EXPR)
11914 data.internal.add (DECL_EXPR_DECL (*tp));
11915 else if (tree spec = retrieve_local_specialization (*tp))
11917 if (data.internal.contains (*tp))
11918 /* Don't mess with variables declared within the pattern. */
11919 return NULL_TREE;
11920 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11922 /* Maybe pull out the PARM_DECL for a partial instantiation. */
11923 tree args = ARGUMENT_PACK_ARGS (spec);
11924 if (TREE_VEC_LENGTH (args) == 1)
11926 tree elt = TREE_VEC_ELT (args, 0);
11927 if (PACK_EXPANSION_P (elt))
11928 elt = PACK_EXPANSION_PATTERN (elt);
11929 if (DECL_PACK_P (elt))
11930 spec = elt;
11932 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11934 /* Handle lambda capture here, since we aren't doing any
11935 substitution now, and so tsubst_copy won't call
11936 process_outer_var_ref. */
11937 tree args = ARGUMENT_PACK_ARGS (spec);
11938 int len = TREE_VEC_LENGTH (args);
11939 for (int i = 0; i < len; ++i)
11941 tree arg = TREE_VEC_ELT (args, i);
11942 tree carg = arg;
11943 if (outer_automatic_var_p (arg))
11944 carg = process_outer_var_ref (arg, complain);
11945 if (carg != arg)
11947 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
11948 proxies. */
11949 if (i == 0)
11951 spec = copy_node (spec);
11952 args = copy_node (args);
11953 SET_ARGUMENT_PACK_ARGS (spec, args);
11954 register_local_specialization (spec, *tp);
11956 TREE_VEC_ELT (args, i) = carg;
11961 if (outer_automatic_var_p (spec))
11962 spec = process_outer_var_ref (spec, complain);
11963 *extra = tree_cons (*tp, spec, *extra);
11965 return NULL_TREE;
11967 static tree
11968 extract_local_specs (tree pattern, tsubst_flags_t complain)
11970 el_data data (complain);
11971 cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
11972 return data.extra;
11975 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
11976 for use in PACK_EXPANSION_EXTRA_ARGS. */
11978 tree
11979 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
11981 tree extra = args;
11982 if (local_specializations)
11983 if (tree locals = extract_local_specs (pattern, complain))
11984 extra = tree_cons (NULL_TREE, extra, locals);
11985 return extra;
11988 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
11989 normal template args to ARGS. */
11991 tree
11992 add_extra_args (tree extra, tree args)
11994 if (extra && TREE_CODE (extra) == TREE_LIST)
11996 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
11998 /* The partial instantiation involved local declarations collected in
11999 extract_local_specs; map from the general template to our local
12000 context. */
12001 tree gen = TREE_PURPOSE (elt);
12002 tree inst = TREE_VALUE (elt);
12003 if (DECL_P (inst))
12004 if (tree local = retrieve_local_specialization (inst))
12005 inst = local;
12006 /* else inst is already a full instantiation of the pack. */
12007 register_local_specialization (inst, gen);
12009 gcc_assert (!TREE_PURPOSE (extra));
12010 extra = TREE_VALUE (extra);
12012 return add_to_template_args (extra, args);
12015 /* Substitute ARGS into T, which is an pack expansion
12016 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12017 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12018 (if only a partial substitution could be performed) or
12019 ERROR_MARK_NODE if there was an error. */
12020 tree
12021 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12022 tree in_decl)
12024 tree pattern;
12025 tree pack, packs = NULL_TREE;
12026 bool unsubstituted_packs = false;
12027 bool unsubstituted_fn_pack = false;
12028 int i, len = -1;
12029 tree result;
12030 hash_map<tree, tree> *saved_local_specializations = NULL;
12031 bool need_local_specializations = false;
12032 int levels;
12034 gcc_assert (PACK_EXPANSION_P (t));
12035 pattern = PACK_EXPANSION_PATTERN (t);
12037 /* Add in any args remembered from an earlier partial instantiation. */
12038 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12040 levels = TMPL_ARGS_DEPTH (args);
12042 /* Determine the argument packs that will instantiate the parameter
12043 packs used in the expansion expression. While we're at it,
12044 compute the number of arguments to be expanded and make sure it
12045 is consistent. */
12046 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12047 pack = TREE_CHAIN (pack))
12049 tree parm_pack = TREE_VALUE (pack);
12050 tree arg_pack = NULL_TREE;
12051 tree orig_arg = NULL_TREE;
12052 int level = 0;
12054 if (TREE_CODE (parm_pack) == BASES)
12056 gcc_assert (parm_pack == pattern);
12057 if (BASES_DIRECT (parm_pack))
12058 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12059 args, complain,
12060 in_decl, false),
12061 complain);
12062 else
12063 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12064 args, complain, in_decl,
12065 false), complain);
12067 else if (builtin_pack_call_p (parm_pack))
12069 if (parm_pack != pattern)
12071 if (complain & tf_error)
12072 sorry ("%qE is not the entire pattern of the pack expansion",
12073 parm_pack);
12074 return error_mark_node;
12076 return expand_builtin_pack_call (parm_pack, args,
12077 complain, in_decl);
12079 else if (TREE_CODE (parm_pack) == PARM_DECL)
12081 /* We know we have correct local_specializations if this
12082 expansion is at function scope, or if we're dealing with a
12083 local parameter in a requires expression; for the latter,
12084 tsubst_requires_expr set it up appropriately. */
12085 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12086 arg_pack = retrieve_local_specialization (parm_pack);
12087 else
12088 /* We can't rely on local_specializations for a parameter
12089 name used later in a function declaration (such as in a
12090 late-specified return type). Even if it exists, it might
12091 have the wrong value for a recursive call. */
12092 need_local_specializations = true;
12094 if (!arg_pack)
12096 /* This parameter pack was used in an unevaluated context. Just
12097 make a dummy decl, since it's only used for its type. */
12098 ++cp_unevaluated_operand;
12099 arg_pack = tsubst_decl (parm_pack, args, complain);
12100 --cp_unevaluated_operand;
12101 if (arg_pack && DECL_PACK_P (arg_pack))
12102 /* Partial instantiation of the parm_pack, we can't build
12103 up an argument pack yet. */
12104 arg_pack = NULL_TREE;
12105 else
12106 arg_pack = make_fnparm_pack (arg_pack);
12108 else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12109 /* This argument pack isn't fully instantiated yet. We set this
12110 flag rather than clear arg_pack because we do want to do the
12111 optimization below, and we don't want to substitute directly
12112 into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12113 where it isn't expected). */
12114 unsubstituted_fn_pack = true;
12116 else if (is_normal_capture_proxy (parm_pack))
12118 arg_pack = retrieve_local_specialization (parm_pack);
12119 if (argument_pack_element_is_expansion_p (arg_pack, 0))
12120 unsubstituted_fn_pack = true;
12122 else
12124 int idx;
12125 template_parm_level_and_index (parm_pack, &level, &idx);
12127 if (level <= levels)
12128 arg_pack = TMPL_ARG (args, level, idx);
12131 orig_arg = arg_pack;
12132 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12133 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12135 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12136 /* This can only happen if we forget to expand an argument
12137 pack somewhere else. Just return an error, silently. */
12139 result = make_tree_vec (1);
12140 TREE_VEC_ELT (result, 0) = error_mark_node;
12141 return result;
12144 if (arg_pack)
12146 int my_len =
12147 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12149 /* Don't bother trying to do a partial substitution with
12150 incomplete packs; we'll try again after deduction. */
12151 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12152 return t;
12154 if (len < 0)
12155 len = my_len;
12156 else if (len != my_len
12157 && !unsubstituted_fn_pack)
12159 if (!(complain & tf_error))
12160 /* Fail quietly. */;
12161 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12162 error ("mismatched argument pack lengths while expanding %qT",
12163 pattern);
12164 else
12165 error ("mismatched argument pack lengths while expanding %qE",
12166 pattern);
12167 return error_mark_node;
12170 /* Keep track of the parameter packs and their corresponding
12171 argument packs. */
12172 packs = tree_cons (parm_pack, arg_pack, packs);
12173 TREE_TYPE (packs) = orig_arg;
12175 else
12177 /* We can't substitute for this parameter pack. We use a flag as
12178 well as the missing_level counter because function parameter
12179 packs don't have a level. */
12180 gcc_assert (processing_template_decl || is_auto (parm_pack));
12181 unsubstituted_packs = true;
12185 /* If the expansion is just T..., return the matching argument pack, unless
12186 we need to call convert_from_reference on all the elements. This is an
12187 important optimization; see c++/68422. */
12188 if (!unsubstituted_packs
12189 && TREE_PURPOSE (packs) == pattern)
12191 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12193 /* If the argument pack is a single pack expansion, pull it out. */
12194 if (TREE_VEC_LENGTH (args) == 1
12195 && pack_expansion_args_count (args))
12196 return TREE_VEC_ELT (args, 0);
12198 /* Types need no adjustment, nor does sizeof..., and if we still have
12199 some pack expansion args we won't do anything yet. */
12200 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12201 || PACK_EXPANSION_SIZEOF_P (t)
12202 || pack_expansion_args_count (args))
12203 return args;
12204 /* Also optimize expression pack expansions if we can tell that the
12205 elements won't have reference type. */
12206 tree type = TREE_TYPE (pattern);
12207 if (type && !TYPE_REF_P (type)
12208 && !PACK_EXPANSION_P (type)
12209 && !WILDCARD_TYPE_P (type))
12210 return args;
12211 /* Otherwise use the normal path so we get convert_from_reference. */
12214 /* We cannot expand this expansion expression, because we don't have
12215 all of the argument packs we need. */
12216 if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12218 /* We got some full packs, but we can't substitute them in until we
12219 have values for all the packs. So remember these until then. */
12221 t = make_pack_expansion (pattern, complain);
12222 PACK_EXPANSION_EXTRA_ARGS (t)
12223 = build_extra_args (pattern, args, complain);
12224 return t;
12226 else if (unsubstituted_packs)
12228 /* There were no real arguments, we're just replacing a parameter
12229 pack with another version of itself. Substitute into the
12230 pattern and return a PACK_EXPANSION_*. The caller will need to
12231 deal with that. */
12232 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12233 t = tsubst_expr (pattern, args, complain, in_decl,
12234 /*integral_constant_expression_p=*/false);
12235 else
12236 t = tsubst (pattern, args, complain, in_decl);
12237 t = make_pack_expansion (t, complain);
12238 return t;
12241 gcc_assert (len >= 0);
12243 if (need_local_specializations)
12245 /* We're in a late-specified return type, so create our own local
12246 specializations map; the current map is either NULL or (in the
12247 case of recursive unification) might have bindings that we don't
12248 want to use or alter. */
12249 saved_local_specializations = local_specializations;
12250 local_specializations = new hash_map<tree, tree>;
12253 /* For each argument in each argument pack, substitute into the
12254 pattern. */
12255 result = make_tree_vec (len);
12256 tree elem_args = copy_template_args (args);
12257 for (i = 0; i < len; ++i)
12259 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12261 elem_args, complain,
12262 in_decl);
12263 TREE_VEC_ELT (result, i) = t;
12264 if (t == error_mark_node)
12266 result = error_mark_node;
12267 break;
12271 /* Update ARGS to restore the substitution from parameter packs to
12272 their argument packs. */
12273 for (pack = packs; pack; pack = TREE_CHAIN (pack))
12275 tree parm = TREE_PURPOSE (pack);
12277 if (TREE_CODE (parm) == PARM_DECL
12278 || VAR_P (parm)
12279 || TREE_CODE (parm) == FIELD_DECL)
12280 register_local_specialization (TREE_TYPE (pack), parm);
12281 else
12283 int idx, level;
12285 if (TREE_VALUE (pack) == NULL_TREE)
12286 continue;
12288 template_parm_level_and_index (parm, &level, &idx);
12290 /* Update the corresponding argument. */
12291 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12292 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12293 TREE_TYPE (pack);
12294 else
12295 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12299 if (need_local_specializations)
12301 delete local_specializations;
12302 local_specializations = saved_local_specializations;
12305 /* If the dependent pack arguments were such that we end up with only a
12306 single pack expansion again, there's no need to keep it in a TREE_VEC. */
12307 if (len == 1 && TREE_CODE (result) == TREE_VEC
12308 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12309 return TREE_VEC_ELT (result, 0);
12311 return result;
12314 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12315 TMPL. We do this using DECL_PARM_INDEX, which should work even with
12316 parameter packs; all parms generated from a function parameter pack will
12317 have the same DECL_PARM_INDEX. */
12319 tree
12320 get_pattern_parm (tree parm, tree tmpl)
12322 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12323 tree patparm;
12325 if (DECL_ARTIFICIAL (parm))
12327 for (patparm = DECL_ARGUMENTS (pattern);
12328 patparm; patparm = DECL_CHAIN (patparm))
12329 if (DECL_ARTIFICIAL (patparm)
12330 && DECL_NAME (parm) == DECL_NAME (patparm))
12331 break;
12333 else
12335 patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12336 patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12337 gcc_assert (DECL_PARM_INDEX (patparm)
12338 == DECL_PARM_INDEX (parm));
12341 return patparm;
12344 /* Make an argument pack out of the TREE_VEC VEC. */
12346 static tree
12347 make_argument_pack (tree vec)
12349 tree pack;
12350 tree elt = TREE_VEC_ELT (vec, 0);
12351 if (TYPE_P (elt))
12352 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12353 else
12355 pack = make_node (NONTYPE_ARGUMENT_PACK);
12356 TREE_CONSTANT (pack) = 1;
12358 SET_ARGUMENT_PACK_ARGS (pack, vec);
12359 return pack;
12362 /* Return an exact copy of template args T that can be modified
12363 independently. */
12365 static tree
12366 copy_template_args (tree t)
12368 if (t == error_mark_node)
12369 return t;
12371 int len = TREE_VEC_LENGTH (t);
12372 tree new_vec = make_tree_vec (len);
12374 for (int i = 0; i < len; ++i)
12376 tree elt = TREE_VEC_ELT (t, i);
12377 if (elt && TREE_CODE (elt) == TREE_VEC)
12378 elt = copy_template_args (elt);
12379 TREE_VEC_ELT (new_vec, i) = elt;
12382 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12383 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12385 return new_vec;
12388 /* Substitute ARGS into the vector or list of template arguments T. */
12390 static tree
12391 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12393 tree orig_t = t;
12394 int len, need_new = 0, i, expanded_len_adjust = 0, out;
12395 tree *elts;
12397 if (t == error_mark_node)
12398 return error_mark_node;
12400 len = TREE_VEC_LENGTH (t);
12401 elts = XALLOCAVEC (tree, len);
12403 for (i = 0; i < len; i++)
12405 tree orig_arg = TREE_VEC_ELT (t, i);
12406 tree new_arg;
12408 if (TREE_CODE (orig_arg) == TREE_VEC)
12409 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12410 else if (PACK_EXPANSION_P (orig_arg))
12412 /* Substitute into an expansion expression. */
12413 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12415 if (TREE_CODE (new_arg) == TREE_VEC)
12416 /* Add to the expanded length adjustment the number of
12417 expanded arguments. We subtract one from this
12418 measurement, because the argument pack expression
12419 itself is already counted as 1 in
12420 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12421 the argument pack is empty. */
12422 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12424 else if (ARGUMENT_PACK_P (orig_arg))
12426 /* Substitute into each of the arguments. */
12427 new_arg = TYPE_P (orig_arg)
12428 ? cxx_make_type (TREE_CODE (orig_arg))
12429 : make_node (TREE_CODE (orig_arg));
12431 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12432 args, complain, in_decl);
12433 if (pack_args == error_mark_node)
12434 new_arg = error_mark_node;
12435 else
12436 SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12438 if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12439 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12441 else
12442 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12444 if (new_arg == error_mark_node)
12445 return error_mark_node;
12447 elts[i] = new_arg;
12448 if (new_arg != orig_arg)
12449 need_new = 1;
12452 if (!need_new)
12453 return t;
12455 /* Make space for the expanded arguments coming from template
12456 argument packs. */
12457 t = make_tree_vec (len + expanded_len_adjust);
12458 /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12459 arguments for a member template.
12460 In that case each TREE_VEC in ORIG_T represents a level of template
12461 arguments, and ORIG_T won't carry any non defaulted argument count.
12462 It will rather be the nested TREE_VECs that will carry one.
12463 In other words, ORIG_T carries a non defaulted argument count only
12464 if it doesn't contain any nested TREE_VEC. */
12465 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12467 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12468 count += expanded_len_adjust;
12469 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12471 for (i = 0, out = 0; i < len; i++)
12473 if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12474 || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12475 && TREE_CODE (elts[i]) == TREE_VEC)
12477 int idx;
12479 /* Now expand the template argument pack "in place". */
12480 for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12481 TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12483 else
12485 TREE_VEC_ELT (t, out) = elts[i];
12486 out++;
12490 return t;
12493 /* Substitute ARGS into one level PARMS of template parameters. */
12495 static tree
12496 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12498 if (parms == error_mark_node)
12499 return error_mark_node;
12501 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12503 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12505 tree tuple = TREE_VEC_ELT (parms, i);
12507 if (tuple == error_mark_node)
12508 continue;
12510 TREE_VEC_ELT (new_vec, i) =
12511 tsubst_template_parm (tuple, args, complain);
12514 return new_vec;
12517 /* Return the result of substituting ARGS into the template parameters
12518 given by PARMS. If there are m levels of ARGS and m + n levels of
12519 PARMS, then the result will contain n levels of PARMS. For
12520 example, if PARMS is `template <class T> template <class U>
12521 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12522 result will be `template <int*, double, class V>'. */
12524 static tree
12525 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12527 tree r = NULL_TREE;
12528 tree* new_parms;
12530 /* When substituting into a template, we must set
12531 PROCESSING_TEMPLATE_DECL as the template parameters may be
12532 dependent if they are based on one-another, and the dependency
12533 predicates are short-circuit outside of templates. */
12534 ++processing_template_decl;
12536 for (new_parms = &r;
12537 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12538 new_parms = &(TREE_CHAIN (*new_parms)),
12539 parms = TREE_CHAIN (parms))
12541 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12542 args, complain);
12543 *new_parms =
12544 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12545 - TMPL_ARGS_DEPTH (args)),
12546 new_vec, NULL_TREE);
12549 --processing_template_decl;
12551 return r;
12554 /* Return the result of substituting ARGS into one template parameter
12555 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12556 parameter and which TREE_PURPOSE is the default argument of the
12557 template parameter. */
12559 static tree
12560 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12562 tree default_value, parm_decl;
12564 if (args == NULL_TREE
12565 || t == NULL_TREE
12566 || t == error_mark_node)
12567 return t;
12569 gcc_assert (TREE_CODE (t) == TREE_LIST);
12571 default_value = TREE_PURPOSE (t);
12572 parm_decl = TREE_VALUE (t);
12574 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12575 if (TREE_CODE (parm_decl) == PARM_DECL
12576 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12577 parm_decl = error_mark_node;
12578 default_value = tsubst_template_arg (default_value, args,
12579 complain, NULL_TREE);
12581 return build_tree_list (default_value, parm_decl);
12584 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12585 type T. If T is not an aggregate or enumeration type, it is
12586 handled as if by tsubst. IN_DECL is as for tsubst. If
12587 ENTERING_SCOPE is nonzero, T is the context for a template which
12588 we are presently tsubst'ing. Return the substituted value. */
12590 static tree
12591 tsubst_aggr_type (tree t,
12592 tree args,
12593 tsubst_flags_t complain,
12594 tree in_decl,
12595 int entering_scope)
12597 if (t == NULL_TREE)
12598 return NULL_TREE;
12600 switch (TREE_CODE (t))
12602 case RECORD_TYPE:
12603 if (TYPE_PTRMEMFUNC_P (t))
12604 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12606 /* Fall through. */
12607 case ENUMERAL_TYPE:
12608 case UNION_TYPE:
12609 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12611 tree argvec;
12612 tree context;
12613 tree r;
12614 int saved_unevaluated_operand;
12615 int saved_inhibit_evaluation_warnings;
12617 /* In "sizeof(X<I>)" we need to evaluate "I". */
12618 saved_unevaluated_operand = cp_unevaluated_operand;
12619 cp_unevaluated_operand = 0;
12620 saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12621 c_inhibit_evaluation_warnings = 0;
12623 /* First, determine the context for the type we are looking
12624 up. */
12625 context = TYPE_CONTEXT (t);
12626 if (context && TYPE_P (context))
12628 context = tsubst_aggr_type (context, args, complain,
12629 in_decl, /*entering_scope=*/1);
12630 /* If context is a nested class inside a class template,
12631 it may still need to be instantiated (c++/33959). */
12632 context = complete_type (context);
12635 /* Then, figure out what arguments are appropriate for the
12636 type we are trying to find. For example, given:
12638 template <class T> struct S;
12639 template <class T, class U> void f(T, U) { S<U> su; }
12641 and supposing that we are instantiating f<int, double>,
12642 then our ARGS will be {int, double}, but, when looking up
12643 S we only want {double}. */
12644 argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12645 complain, in_decl);
12646 if (argvec == error_mark_node)
12647 r = error_mark_node;
12648 else
12650 r = lookup_template_class (t, argvec, in_decl, context,
12651 entering_scope, complain);
12652 r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12655 cp_unevaluated_operand = saved_unevaluated_operand;
12656 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12658 return r;
12660 else
12661 /* This is not a template type, so there's nothing to do. */
12662 return t;
12664 default:
12665 return tsubst (t, args, complain, in_decl);
12669 static GTY((cache)) tree_cache_map *defarg_inst;
12671 /* Substitute into the default argument ARG (a default argument for
12672 FN), which has the indicated TYPE. */
12674 tree
12675 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12676 tsubst_flags_t complain)
12678 tree saved_class_ptr = NULL_TREE;
12679 tree saved_class_ref = NULL_TREE;
12680 int errs = errorcount + sorrycount;
12682 /* This can happen in invalid code. */
12683 if (TREE_CODE (arg) == DEFAULT_ARG)
12684 return arg;
12686 tree parm = FUNCTION_FIRST_USER_PARM (fn);
12687 parm = chain_index (parmnum, parm);
12688 tree parmtype = TREE_TYPE (parm);
12689 if (DECL_BY_REFERENCE (parm))
12690 parmtype = TREE_TYPE (parmtype);
12691 if (parmtype == error_mark_node)
12692 return error_mark_node;
12694 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12696 tree *slot;
12697 if (defarg_inst && (slot = defarg_inst->get (parm)))
12698 return *slot;
12700 /* This default argument came from a template. Instantiate the
12701 default argument here, not in tsubst. In the case of
12702 something like:
12704 template <class T>
12705 struct S {
12706 static T t();
12707 void f(T = t());
12710 we must be careful to do name lookup in the scope of S<T>,
12711 rather than in the current class. */
12712 push_access_scope (fn);
12713 /* The "this" pointer is not valid in a default argument. */
12714 if (cfun)
12716 saved_class_ptr = current_class_ptr;
12717 cp_function_chain->x_current_class_ptr = NULL_TREE;
12718 saved_class_ref = current_class_ref;
12719 cp_function_chain->x_current_class_ref = NULL_TREE;
12722 start_lambda_scope (parm);
12724 push_deferring_access_checks(dk_no_deferred);
12725 /* The default argument expression may cause implicitly defined
12726 member functions to be synthesized, which will result in garbage
12727 collection. We must treat this situation as if we were within
12728 the body of function so as to avoid collecting live data on the
12729 stack. */
12730 ++function_depth;
12731 arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12732 complain, NULL_TREE,
12733 /*integral_constant_expression_p=*/false);
12734 --function_depth;
12735 pop_deferring_access_checks();
12737 finish_lambda_scope ();
12739 /* Restore the "this" pointer. */
12740 if (cfun)
12742 cp_function_chain->x_current_class_ptr = saved_class_ptr;
12743 cp_function_chain->x_current_class_ref = saved_class_ref;
12746 if (errorcount+sorrycount > errs
12747 && (complain & tf_warning_or_error))
12748 inform (input_location,
12749 " when instantiating default argument for call to %qD", fn);
12751 /* Make sure the default argument is reasonable. */
12752 arg = check_default_argument (type, arg, complain);
12754 pop_access_scope (fn);
12756 if (arg != error_mark_node && !cp_unevaluated_operand)
12758 if (!defarg_inst)
12759 defarg_inst = tree_cache_map::create_ggc (37);
12760 defarg_inst->put (parm, arg);
12763 return arg;
12766 /* Substitute into all the default arguments for FN. */
12768 static void
12769 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12771 tree arg;
12772 tree tmpl_args;
12774 tmpl_args = DECL_TI_ARGS (fn);
12776 /* If this function is not yet instantiated, we certainly don't need
12777 its default arguments. */
12778 if (uses_template_parms (tmpl_args))
12779 return;
12780 /* Don't do this again for clones. */
12781 if (DECL_CLONED_FUNCTION_P (fn))
12782 return;
12784 int i = 0;
12785 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12786 arg;
12787 arg = TREE_CHAIN (arg), ++i)
12788 if (TREE_PURPOSE (arg))
12789 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12790 TREE_VALUE (arg),
12791 TREE_PURPOSE (arg),
12792 complain);
12795 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
12797 static tree
12798 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12799 tree lambda_fntype)
12801 tree gen_tmpl, argvec;
12802 hashval_t hash = 0;
12803 tree in_decl = t;
12805 /* Nobody should be tsubst'ing into non-template functions. */
12806 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12808 if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12810 /* If T is not dependent, just return it. */
12811 if (!uses_template_parms (DECL_TI_ARGS (t)))
12812 return t;
12814 /* Calculate the most general template of which R is a
12815 specialization. */
12816 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12818 /* We're substituting a lambda function under tsubst_lambda_expr but not
12819 directly from it; find the matching function we're already inside.
12820 But don't do this if T is a generic lambda with a single level of
12821 template parms, as in that case we're doing a normal instantiation. */
12822 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12823 && (!generic_lambda_fn_p (t)
12824 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12825 return enclosing_instantiation_of (t);
12827 /* Calculate the complete set of arguments used to
12828 specialize R. */
12829 argvec = tsubst_template_args (DECL_TI_ARGS
12830 (DECL_TEMPLATE_RESULT
12831 (DECL_TI_TEMPLATE (t))),
12832 args, complain, in_decl);
12833 if (argvec == error_mark_node)
12834 return error_mark_node;
12836 /* Check to see if we already have this specialization. */
12837 if (!lambda_fntype)
12839 hash = hash_tmpl_and_args (gen_tmpl, argvec);
12840 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12841 return spec;
12844 /* We can see more levels of arguments than parameters if
12845 there was a specialization of a member template, like
12846 this:
12848 template <class T> struct S { template <class U> void f(); }
12849 template <> template <class U> void S<int>::f(U);
12851 Here, we'll be substituting into the specialization,
12852 because that's where we can find the code we actually
12853 want to generate, but we'll have enough arguments for
12854 the most general template.
12856 We also deal with the peculiar case:
12858 template <class T> struct S {
12859 template <class U> friend void f();
12861 template <class U> void f() {}
12862 template S<int>;
12863 template void f<double>();
12865 Here, the ARGS for the instantiation of will be {int,
12866 double}. But, we only need as many ARGS as there are
12867 levels of template parameters in CODE_PATTERN. We are
12868 careful not to get fooled into reducing the ARGS in
12869 situations like:
12871 template <class T> struct S { template <class U> void f(U); }
12872 template <class T> template <> void S<T>::f(int) {}
12874 which we can spot because the pattern will be a
12875 specialization in this case. */
12876 int args_depth = TMPL_ARGS_DEPTH (args);
12877 int parms_depth =
12878 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12880 if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12881 args = get_innermost_template_args (args, parms_depth);
12883 else
12885 /* This special case arises when we have something like this:
12887 template <class T> struct S {
12888 friend void f<int>(int, double);
12891 Here, the DECL_TI_TEMPLATE for the friend declaration
12892 will be an IDENTIFIER_NODE. We are being called from
12893 tsubst_friend_function, and we want only to create a
12894 new decl (R) with appropriate types so that we can call
12895 determine_specialization. */
12896 gen_tmpl = NULL_TREE;
12897 argvec = NULL_TREE;
12900 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
12901 : NULL_TREE);
12902 tree ctx = closure ? closure : DECL_CONTEXT (t);
12903 bool member = ctx && TYPE_P (ctx);
12905 if (member && !closure)
12906 ctx = tsubst_aggr_type (ctx, args,
12907 complain, t, /*entering_scope=*/1);
12909 tree type = (lambda_fntype ? lambda_fntype
12910 : tsubst (TREE_TYPE (t), args,
12911 complain | tf_fndecl_type, in_decl));
12912 if (type == error_mark_node)
12913 return error_mark_node;
12915 /* If we hit excessive deduction depth, the type is bogus even if
12916 it isn't error_mark_node, so don't build a decl. */
12917 if (excessive_deduction_depth)
12918 return error_mark_node;
12920 /* We do NOT check for matching decls pushed separately at this
12921 point, as they may not represent instantiations of this
12922 template, and in any case are considered separate under the
12923 discrete model. */
12924 tree r = copy_decl (t);
12925 DECL_USE_TEMPLATE (r) = 0;
12926 TREE_TYPE (r) = type;
12927 /* Clear out the mangled name and RTL for the instantiation. */
12928 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12929 SET_DECL_RTL (r, NULL);
12930 /* Leave DECL_INITIAL set on deleted instantiations. */
12931 if (!DECL_DELETED_FN (r))
12932 DECL_INITIAL (r) = NULL_TREE;
12933 DECL_CONTEXT (r) = ctx;
12935 /* OpenMP UDRs have the only argument a reference to the declared
12936 type. We want to diagnose if the declared type is a reference,
12937 which is invalid, but as references to references are usually
12938 quietly merged, diagnose it here. */
12939 if (DECL_OMP_DECLARE_REDUCTION_P (t))
12941 tree argtype
12942 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
12943 argtype = tsubst (argtype, args, complain, in_decl);
12944 if (TYPE_REF_P (argtype))
12945 error_at (DECL_SOURCE_LOCATION (t),
12946 "reference type %qT in "
12947 "%<#pragma omp declare reduction%>", argtype);
12948 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
12949 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
12950 argtype);
12953 if (member && DECL_CONV_FN_P (r))
12954 /* Type-conversion operator. Reconstruct the name, in
12955 case it's the name of one of the template's parameters. */
12956 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
12958 tree parms = DECL_ARGUMENTS (t);
12959 if (closure)
12960 parms = DECL_CHAIN (parms);
12961 parms = tsubst (parms, args, complain, t);
12962 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
12963 DECL_CONTEXT (parm) = r;
12964 if (closure)
12966 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
12967 DECL_CHAIN (tparm) = parms;
12968 parms = tparm;
12970 DECL_ARGUMENTS (r) = parms;
12971 DECL_RESULT (r) = NULL_TREE;
12973 TREE_STATIC (r) = 0;
12974 TREE_PUBLIC (r) = TREE_PUBLIC (t);
12975 DECL_EXTERNAL (r) = 1;
12976 /* If this is an instantiation of a function with internal
12977 linkage, we already know what object file linkage will be
12978 assigned to the instantiation. */
12979 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
12980 DECL_DEFER_OUTPUT (r) = 0;
12981 DECL_CHAIN (r) = NULL_TREE;
12982 DECL_PENDING_INLINE_INFO (r) = 0;
12983 DECL_PENDING_INLINE_P (r) = 0;
12984 DECL_SAVED_TREE (r) = NULL_TREE;
12985 DECL_STRUCT_FUNCTION (r) = NULL;
12986 TREE_USED (r) = 0;
12987 /* We'll re-clone as appropriate in instantiate_template. */
12988 DECL_CLONED_FUNCTION (r) = NULL_TREE;
12990 /* If we aren't complaining now, return on error before we register
12991 the specialization so that we'll complain eventually. */
12992 if ((complain & tf_error) == 0
12993 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
12994 && !grok_op_properties (r, /*complain=*/false))
12995 return error_mark_node;
12997 /* When instantiating a constrained member, substitute
12998 into the constraints to create a new constraint. */
12999 if (tree ci = get_constraints (t))
13000 if (member)
13002 ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13003 set_constraints (r, ci);
13006 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
13007 this in the special friend case mentioned above where
13008 GEN_TMPL is NULL. */
13009 if (gen_tmpl && !closure)
13011 DECL_TEMPLATE_INFO (r)
13012 = build_template_info (gen_tmpl, argvec);
13013 SET_DECL_IMPLICIT_INSTANTIATION (r);
13015 tree new_r
13016 = register_specialization (r, gen_tmpl, argvec, false, hash);
13017 if (new_r != r)
13018 /* We instantiated this while substituting into
13019 the type earlier (template/friend54.C). */
13020 return new_r;
13022 /* We're not supposed to instantiate default arguments
13023 until they are called, for a template. But, for a
13024 declaration like:
13026 template <class T> void f ()
13027 { extern void g(int i = T()); }
13029 we should do the substitution when the template is
13030 instantiated. We handle the member function case in
13031 instantiate_class_template since the default arguments
13032 might refer to other members of the class. */
13033 if (!member
13034 && !PRIMARY_TEMPLATE_P (gen_tmpl)
13035 && !uses_template_parms (argvec))
13036 tsubst_default_arguments (r, complain);
13038 else
13039 DECL_TEMPLATE_INFO (r) = NULL_TREE;
13041 /* Copy the list of befriending classes. */
13042 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13043 *friends;
13044 friends = &TREE_CHAIN (*friends))
13046 *friends = copy_node (*friends);
13047 TREE_VALUE (*friends)
13048 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13051 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13053 maybe_retrofit_in_chrg (r);
13054 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13055 return error_mark_node;
13056 /* If this is an instantiation of a member template, clone it.
13057 If it isn't, that'll be handled by
13058 clone_constructors_and_destructors. */
13059 if (PRIMARY_TEMPLATE_P (gen_tmpl))
13060 clone_function_decl (r, /*update_methods=*/false);
13062 else if ((complain & tf_error) != 0
13063 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13064 && !grok_op_properties (r, /*complain=*/true))
13065 return error_mark_node;
13067 if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13068 SET_DECL_FRIEND_CONTEXT (r,
13069 tsubst (DECL_FRIEND_CONTEXT (t),
13070 args, complain, in_decl));
13072 /* Possibly limit visibility based on template args. */
13073 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13074 if (DECL_VISIBILITY_SPECIFIED (t))
13076 DECL_VISIBILITY_SPECIFIED (r) = 0;
13077 DECL_ATTRIBUTES (r)
13078 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13080 determine_visibility (r);
13081 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13082 && !processing_template_decl)
13083 defaulted_late_check (r);
13085 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13086 args, complain, in_decl);
13087 return r;
13090 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
13092 static tree
13093 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13094 tree lambda_fntype)
13096 /* We can get here when processing a member function template,
13097 member class template, or template template parameter. */
13098 tree decl = DECL_TEMPLATE_RESULT (t);
13099 tree in_decl = t;
13100 tree spec;
13101 tree tmpl_args;
13102 tree full_args;
13103 tree r;
13104 hashval_t hash = 0;
13106 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13108 /* Template template parameter is treated here. */
13109 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13110 if (new_type == error_mark_node)
13111 r = error_mark_node;
13112 /* If we get a real template back, return it. This can happen in
13113 the context of most_specialized_partial_spec. */
13114 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13115 r = new_type;
13116 else
13117 /* The new TEMPLATE_DECL was built in
13118 reduce_template_parm_level. */
13119 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13120 return r;
13123 if (!lambda_fntype)
13125 /* We might already have an instance of this template.
13126 The ARGS are for the surrounding class type, so the
13127 full args contain the tsubst'd args for the context,
13128 plus the innermost args from the template decl. */
13129 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13130 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13131 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13132 /* Because this is a template, the arguments will still be
13133 dependent, even after substitution. If
13134 PROCESSING_TEMPLATE_DECL is not set, the dependency
13135 predicates will short-circuit. */
13136 ++processing_template_decl;
13137 full_args = tsubst_template_args (tmpl_args, args,
13138 complain, in_decl);
13139 --processing_template_decl;
13140 if (full_args == error_mark_node)
13141 return error_mark_node;
13143 /* If this is a default template template argument,
13144 tsubst might not have changed anything. */
13145 if (full_args == tmpl_args)
13146 return t;
13148 hash = hash_tmpl_and_args (t, full_args);
13149 spec = retrieve_specialization (t, full_args, hash);
13150 if (spec != NULL_TREE)
13151 return spec;
13154 /* Make a new template decl. It will be similar to the
13155 original, but will record the current template arguments.
13156 We also create a new function declaration, which is just
13157 like the old one, but points to this new template, rather
13158 than the old one. */
13159 r = copy_decl (t);
13160 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13161 DECL_CHAIN (r) = NULL_TREE;
13163 // Build new template info linking to the original template decl.
13164 if (!lambda_fntype)
13166 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13167 SET_DECL_IMPLICIT_INSTANTIATION (r);
13169 else
13170 DECL_TEMPLATE_INFO (r) = NULL_TREE;
13172 /* The template parameters for this new template are all the
13173 template parameters for the old template, except the
13174 outermost level of parameters. */
13175 DECL_TEMPLATE_PARMS (r)
13176 = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13177 complain);
13179 if (TREE_CODE (decl) == TYPE_DECL
13180 && !TYPE_DECL_ALIAS_P (decl))
13182 tree new_type;
13183 ++processing_template_decl;
13184 new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13185 --processing_template_decl;
13186 if (new_type == error_mark_node)
13187 return error_mark_node;
13189 TREE_TYPE (r) = new_type;
13190 /* For a partial specialization, we need to keep pointing to
13191 the primary template. */
13192 if (!DECL_TEMPLATE_SPECIALIZATION (t))
13193 CLASSTYPE_TI_TEMPLATE (new_type) = r;
13194 DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13195 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13196 DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13198 else
13200 tree new_decl;
13201 ++processing_template_decl;
13202 if (TREE_CODE (decl) == FUNCTION_DECL)
13203 new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13204 else
13205 new_decl = tsubst (decl, args, complain, in_decl);
13206 --processing_template_decl;
13207 if (new_decl == error_mark_node)
13208 return error_mark_node;
13210 DECL_TEMPLATE_RESULT (r) = new_decl;
13211 TREE_TYPE (r) = TREE_TYPE (new_decl);
13212 DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13213 if (lambda_fntype)
13215 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13216 DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13218 else
13220 DECL_TI_TEMPLATE (new_decl) = r;
13221 DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13225 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13226 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13228 if (PRIMARY_TEMPLATE_P (t))
13229 DECL_PRIMARY_TEMPLATE (r) = r;
13231 if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13232 && !lambda_fntype)
13233 /* Record this non-type partial instantiation. */
13234 register_specialization (r, t,
13235 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13236 false, hash);
13238 return r;
13241 /* True if FN is the op() for a lambda in an uninstantiated template. */
13243 bool
13244 lambda_fn_in_template_p (tree fn)
13246 if (!fn || !LAMBDA_FUNCTION_P (fn))
13247 return false;
13248 tree closure = DECL_CONTEXT (fn);
13249 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13252 /* We're instantiating a variable from template function TCTX. Return the
13253 corresponding current enclosing scope. This gets complicated because lambda
13254 functions in templates are regenerated rather than instantiated, but generic
13255 lambda functions are subsequently instantiated. */
13257 static tree
13258 enclosing_instantiation_of (tree otctx)
13260 tree tctx = otctx;
13261 tree fn = current_function_decl;
13262 int lambda_count = 0;
13264 for (; tctx && lambda_fn_in_template_p (tctx);
13265 tctx = decl_function_context (tctx))
13266 ++lambda_count;
13267 for (; fn; fn = decl_function_context (fn))
13269 tree ofn = fn;
13270 int flambda_count = 0;
13271 for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
13272 fn = decl_function_context (fn))
13273 ++flambda_count;
13274 if ((fn && DECL_TEMPLATE_INFO (fn))
13275 ? most_general_template (fn) != most_general_template (tctx)
13276 : fn != tctx)
13277 continue;
13278 gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13279 || DECL_CONV_FN_P (ofn));
13280 return ofn;
13282 gcc_unreachable ();
13285 /* Substitute the ARGS into the T, which is a _DECL. Return the
13286 result of the substitution. Issue error and warning messages under
13287 control of COMPLAIN. */
13289 static tree
13290 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13292 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13293 location_t saved_loc;
13294 tree r = NULL_TREE;
13295 tree in_decl = t;
13296 hashval_t hash = 0;
13298 /* Set the filename and linenumber to improve error-reporting. */
13299 saved_loc = input_location;
13300 input_location = DECL_SOURCE_LOCATION (t);
13302 switch (TREE_CODE (t))
13304 case TEMPLATE_DECL:
13305 r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13306 break;
13308 case FUNCTION_DECL:
13309 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13310 break;
13312 case PARM_DECL:
13314 tree type = NULL_TREE;
13315 int i, len = 1;
13316 tree expanded_types = NULL_TREE;
13317 tree prev_r = NULL_TREE;
13318 tree first_r = NULL_TREE;
13320 if (DECL_PACK_P (t))
13322 /* If there is a local specialization that isn't a
13323 parameter pack, it means that we're doing a "simple"
13324 substitution from inside tsubst_pack_expansion. Just
13325 return the local specialization (which will be a single
13326 parm). */
13327 tree spec = retrieve_local_specialization (t);
13328 if (spec
13329 && TREE_CODE (spec) == PARM_DECL
13330 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13331 RETURN (spec);
13333 /* Expand the TYPE_PACK_EXPANSION that provides the types for
13334 the parameters in this function parameter pack. */
13335 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13336 complain, in_decl);
13337 if (TREE_CODE (expanded_types) == TREE_VEC)
13339 len = TREE_VEC_LENGTH (expanded_types);
13341 /* Zero-length parameter packs are boring. Just substitute
13342 into the chain. */
13343 if (len == 0)
13344 RETURN (tsubst (TREE_CHAIN (t), args, complain,
13345 TREE_CHAIN (t)));
13347 else
13349 /* All we did was update the type. Make a note of that. */
13350 type = expanded_types;
13351 expanded_types = NULL_TREE;
13355 /* Loop through all of the parameters we'll build. When T is
13356 a function parameter pack, LEN is the number of expanded
13357 types in EXPANDED_TYPES; otherwise, LEN is 1. */
13358 r = NULL_TREE;
13359 for (i = 0; i < len; ++i)
13361 prev_r = r;
13362 r = copy_node (t);
13363 if (DECL_TEMPLATE_PARM_P (t))
13364 SET_DECL_TEMPLATE_PARM_P (r);
13366 if (expanded_types)
13367 /* We're on the Ith parameter of the function parameter
13368 pack. */
13370 /* Get the Ith type. */
13371 type = TREE_VEC_ELT (expanded_types, i);
13373 /* Rename the parameter to include the index. */
13374 DECL_NAME (r)
13375 = make_ith_pack_parameter_name (DECL_NAME (r), i);
13377 else if (!type)
13378 /* We're dealing with a normal parameter. */
13379 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13381 type = type_decays_to (type);
13382 TREE_TYPE (r) = type;
13383 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13385 if (DECL_INITIAL (r))
13387 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13388 DECL_INITIAL (r) = TREE_TYPE (r);
13389 else
13390 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13391 complain, in_decl);
13394 DECL_CONTEXT (r) = NULL_TREE;
13396 if (!DECL_TEMPLATE_PARM_P (r))
13397 DECL_ARG_TYPE (r) = type_passed_as (type);
13399 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13400 args, complain, in_decl);
13402 /* Keep track of the first new parameter we
13403 generate. That's what will be returned to the
13404 caller. */
13405 if (!first_r)
13406 first_r = r;
13408 /* Build a proper chain of parameters when substituting
13409 into a function parameter pack. */
13410 if (prev_r)
13411 DECL_CHAIN (prev_r) = r;
13414 /* If cp_unevaluated_operand is set, we're just looking for a
13415 single dummy parameter, so don't keep going. */
13416 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13417 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13418 complain, DECL_CHAIN (t));
13420 /* FIRST_R contains the start of the chain we've built. */
13421 r = first_r;
13423 break;
13425 case FIELD_DECL:
13427 tree type = NULL_TREE;
13428 tree vec = NULL_TREE;
13429 tree expanded_types = NULL_TREE;
13430 int len = 1;
13432 if (PACK_EXPANSION_P (TREE_TYPE (t)))
13434 /* This field is a lambda capture pack. Return a TREE_VEC of
13435 the expanded fields to instantiate_class_template_1. */
13436 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13437 complain, in_decl);
13438 if (TREE_CODE (expanded_types) == TREE_VEC)
13440 len = TREE_VEC_LENGTH (expanded_types);
13441 vec = make_tree_vec (len);
13443 else
13445 /* All we did was update the type. Make a note of that. */
13446 type = expanded_types;
13447 expanded_types = NULL_TREE;
13451 for (int i = 0; i < len; ++i)
13453 r = copy_decl (t);
13454 if (expanded_types)
13456 type = TREE_VEC_ELT (expanded_types, i);
13457 DECL_NAME (r)
13458 = make_ith_pack_parameter_name (DECL_NAME (r), i);
13460 else if (!type)
13461 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13463 if (type == error_mark_node)
13464 RETURN (error_mark_node);
13465 TREE_TYPE (r) = type;
13466 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13468 if (DECL_C_BIT_FIELD (r))
13469 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13470 number of bits. */
13471 DECL_BIT_FIELD_REPRESENTATIVE (r)
13472 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13473 complain, in_decl,
13474 /*integral_constant_expression_p=*/true);
13475 if (DECL_INITIAL (t))
13477 /* Set up DECL_TEMPLATE_INFO so that we can get at the
13478 NSDMI in perform_member_init. Still set DECL_INITIAL
13479 so that we know there is one. */
13480 DECL_INITIAL (r) = void_node;
13481 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13482 retrofit_lang_decl (r);
13483 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13485 /* We don't have to set DECL_CONTEXT here; it is set by
13486 finish_member_declaration. */
13487 DECL_CHAIN (r) = NULL_TREE;
13489 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13490 args, complain, in_decl);
13492 if (vec)
13493 TREE_VEC_ELT (vec, i) = r;
13496 if (vec)
13497 r = vec;
13499 break;
13501 case USING_DECL:
13502 /* We reach here only for member using decls. We also need to check
13503 uses_template_parms because DECL_DEPENDENT_P is not set for a
13504 using-declaration that designates a member of the current
13505 instantiation (c++/53549). */
13506 if (DECL_DEPENDENT_P (t)
13507 || uses_template_parms (USING_DECL_SCOPE (t)))
13509 tree scope = USING_DECL_SCOPE (t);
13510 tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13511 if (PACK_EXPANSION_P (scope))
13513 tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13514 int len = TREE_VEC_LENGTH (vec);
13515 r = make_tree_vec (len);
13516 for (int i = 0; i < len; ++i)
13518 tree escope = TREE_VEC_ELT (vec, i);
13519 tree elt = do_class_using_decl (escope, name);
13520 if (!elt)
13522 r = error_mark_node;
13523 break;
13525 else
13527 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13528 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13530 TREE_VEC_ELT (r, i) = elt;
13533 else
13535 tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13536 complain, in_decl);
13537 r = do_class_using_decl (inst_scope, name);
13538 if (!r)
13539 r = error_mark_node;
13540 else
13542 TREE_PROTECTED (r) = TREE_PROTECTED (t);
13543 TREE_PRIVATE (r) = TREE_PRIVATE (t);
13547 else
13549 r = copy_node (t);
13550 DECL_CHAIN (r) = NULL_TREE;
13552 break;
13554 case TYPE_DECL:
13555 case VAR_DECL:
13557 tree argvec = NULL_TREE;
13558 tree gen_tmpl = NULL_TREE;
13559 tree spec;
13560 tree tmpl = NULL_TREE;
13561 tree ctx;
13562 tree type = NULL_TREE;
13563 bool local_p;
13565 if (TREE_TYPE (t) == error_mark_node)
13566 RETURN (error_mark_node);
13568 if (TREE_CODE (t) == TYPE_DECL
13569 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13571 /* If this is the canonical decl, we don't have to
13572 mess with instantiations, and often we can't (for
13573 typename, template type parms and such). Note that
13574 TYPE_NAME is not correct for the above test if
13575 we've copied the type for a typedef. */
13576 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13577 if (type == error_mark_node)
13578 RETURN (error_mark_node);
13579 r = TYPE_NAME (type);
13580 break;
13583 /* Check to see if we already have the specialization we
13584 need. */
13585 spec = NULL_TREE;
13586 if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13588 /* T is a static data member or namespace-scope entity.
13589 We have to substitute into namespace-scope variables
13590 (not just variable templates) because of cases like:
13592 template <class T> void f() { extern T t; }
13594 where the entity referenced is not known until
13595 instantiation time. */
13596 local_p = false;
13597 ctx = DECL_CONTEXT (t);
13598 if (DECL_CLASS_SCOPE_P (t))
13600 ctx = tsubst_aggr_type (ctx, args,
13601 complain,
13602 in_decl, /*entering_scope=*/1);
13603 /* If CTX is unchanged, then T is in fact the
13604 specialization we want. That situation occurs when
13605 referencing a static data member within in its own
13606 class. We can use pointer equality, rather than
13607 same_type_p, because DECL_CONTEXT is always
13608 canonical... */
13609 if (ctx == DECL_CONTEXT (t)
13610 /* ... unless T is a member template; in which
13611 case our caller can be willing to create a
13612 specialization of that template represented
13613 by T. */
13614 && !(DECL_TI_TEMPLATE (t)
13615 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13616 spec = t;
13619 if (!spec)
13621 tmpl = DECL_TI_TEMPLATE (t);
13622 gen_tmpl = most_general_template (tmpl);
13623 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13624 if (argvec != error_mark_node)
13625 argvec = (coerce_innermost_template_parms
13626 (DECL_TEMPLATE_PARMS (gen_tmpl),
13627 argvec, t, complain,
13628 /*all*/true, /*defarg*/true));
13629 if (argvec == error_mark_node)
13630 RETURN (error_mark_node);
13631 hash = hash_tmpl_and_args (gen_tmpl, argvec);
13632 spec = retrieve_specialization (gen_tmpl, argvec, hash);
13635 else
13637 /* A local variable. */
13638 local_p = true;
13639 /* Subsequent calls to pushdecl will fill this in. */
13640 ctx = NULL_TREE;
13641 /* Unless this is a reference to a static variable from an
13642 enclosing function, in which case we need to fill it in now. */
13643 if (TREE_STATIC (t))
13645 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13646 if (fn != current_function_decl)
13647 ctx = fn;
13649 spec = retrieve_local_specialization (t);
13651 /* If we already have the specialization we need, there is
13652 nothing more to do. */
13653 if (spec)
13655 r = spec;
13656 break;
13659 /* Create a new node for the specialization we need. */
13660 r = copy_decl (t);
13661 if (type == NULL_TREE)
13663 if (is_typedef_decl (t))
13664 type = DECL_ORIGINAL_TYPE (t);
13665 else
13666 type = TREE_TYPE (t);
13667 if (VAR_P (t)
13668 && VAR_HAD_UNKNOWN_BOUND (t)
13669 && type != error_mark_node)
13670 type = strip_array_domain (type);
13671 tree sub_args = args;
13672 if (tree auto_node = type_uses_auto (type))
13674 /* Mask off any template args past the variable's context so we
13675 don't replace the auto with an unrelated argument. */
13676 int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13677 int extra = TMPL_ARGS_DEPTH (args) - nouter;
13678 if (extra > 0)
13679 /* This should never happen with the new lambda instantiation
13680 model, but keep the handling just in case. */
13681 gcc_assert (!CHECKING_P),
13682 sub_args = strip_innermost_template_args (args, extra);
13684 type = tsubst (type, sub_args, complain, in_decl);
13686 if (VAR_P (r))
13688 DECL_INITIALIZED_P (r) = 0;
13689 DECL_TEMPLATE_INSTANTIATED (r) = 0;
13690 if (type == error_mark_node)
13691 RETURN (error_mark_node);
13692 if (TREE_CODE (type) == FUNCTION_TYPE)
13694 /* It may seem that this case cannot occur, since:
13696 typedef void f();
13697 void g() { f x; }
13699 declares a function, not a variable. However:
13701 typedef void f();
13702 template <typename T> void g() { T t; }
13703 template void g<f>();
13705 is an attempt to declare a variable with function
13706 type. */
13707 error ("variable %qD has function type",
13708 /* R is not yet sufficiently initialized, so we
13709 just use its name. */
13710 DECL_NAME (r));
13711 RETURN (error_mark_node);
13713 type = complete_type (type);
13714 /* Wait until cp_finish_decl to set this again, to handle
13715 circular dependency (template/instantiate6.C). */
13716 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13717 type = check_var_type (DECL_NAME (r), type);
13719 if (DECL_HAS_VALUE_EXPR_P (t))
13721 tree ve = DECL_VALUE_EXPR (t);
13722 ve = tsubst_expr (ve, args, complain, in_decl,
13723 /*constant_expression_p=*/false);
13724 if (REFERENCE_REF_P (ve))
13726 gcc_assert (TYPE_REF_P (type));
13727 ve = TREE_OPERAND (ve, 0);
13729 SET_DECL_VALUE_EXPR (r, ve);
13731 if (CP_DECL_THREAD_LOCAL_P (r)
13732 && !processing_template_decl)
13733 set_decl_tls_model (r, decl_default_tls_model (r));
13735 else if (DECL_SELF_REFERENCE_P (t))
13736 SET_DECL_SELF_REFERENCE_P (r);
13737 TREE_TYPE (r) = type;
13738 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13739 DECL_CONTEXT (r) = ctx;
13740 /* Clear out the mangled name and RTL for the instantiation. */
13741 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13742 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13743 SET_DECL_RTL (r, NULL);
13744 /* The initializer must not be expanded until it is required;
13745 see [temp.inst]. */
13746 DECL_INITIAL (r) = NULL_TREE;
13747 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13748 if (VAR_P (r))
13750 if (DECL_LANG_SPECIFIC (r))
13751 SET_DECL_DEPENDENT_INIT_P (r, false);
13753 SET_DECL_MODE (r, VOIDmode);
13755 /* Possibly limit visibility based on template args. */
13756 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13757 if (DECL_VISIBILITY_SPECIFIED (t))
13759 DECL_VISIBILITY_SPECIFIED (r) = 0;
13760 DECL_ATTRIBUTES (r)
13761 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13763 determine_visibility (r);
13766 if (!local_p)
13768 /* A static data member declaration is always marked
13769 external when it is declared in-class, even if an
13770 initializer is present. We mimic the non-template
13771 processing here. */
13772 DECL_EXTERNAL (r) = 1;
13773 if (DECL_NAMESPACE_SCOPE_P (t))
13774 DECL_NOT_REALLY_EXTERN (r) = 1;
13776 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13777 SET_DECL_IMPLICIT_INSTANTIATION (r);
13778 register_specialization (r, gen_tmpl, argvec, false, hash);
13780 else
13782 if (DECL_LANG_SPECIFIC (r))
13783 DECL_TEMPLATE_INFO (r) = NULL_TREE;
13784 if (!cp_unevaluated_operand)
13785 register_local_specialization (r, t);
13788 DECL_CHAIN (r) = NULL_TREE;
13790 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13791 /*flags=*/0,
13792 args, complain, in_decl);
13794 /* Preserve a typedef that names a type. */
13795 if (is_typedef_decl (r) && type != error_mark_node)
13797 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13798 set_underlying_type (r);
13799 if (TYPE_DECL_ALIAS_P (r))
13800 /* An alias template specialization can be dependent
13801 even if its underlying type is not. */
13802 TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13805 layout_decl (r, 0);
13807 break;
13809 default:
13810 gcc_unreachable ();
13812 #undef RETURN
13814 out:
13815 /* Restore the file and line information. */
13816 input_location = saved_loc;
13818 return r;
13821 /* Substitute into the ARG_TYPES of a function type.
13822 If END is a TREE_CHAIN, leave it and any following types
13823 un-substituted. */
13825 static tree
13826 tsubst_arg_types (tree arg_types,
13827 tree args,
13828 tree end,
13829 tsubst_flags_t complain,
13830 tree in_decl)
13832 tree remaining_arg_types;
13833 tree type = NULL_TREE;
13834 int i = 1;
13835 tree expanded_args = NULL_TREE;
13836 tree default_arg;
13838 if (!arg_types || arg_types == void_list_node || arg_types == end)
13839 return arg_types;
13841 remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13842 args, end, complain, in_decl);
13843 if (remaining_arg_types == error_mark_node)
13844 return error_mark_node;
13846 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13848 /* For a pack expansion, perform substitution on the
13849 entire expression. Later on, we'll handle the arguments
13850 one-by-one. */
13851 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13852 args, complain, in_decl);
13854 if (TREE_CODE (expanded_args) == TREE_VEC)
13855 /* So that we'll spin through the parameters, one by one. */
13856 i = TREE_VEC_LENGTH (expanded_args);
13857 else
13859 /* We only partially substituted into the parameter
13860 pack. Our type is TYPE_PACK_EXPANSION. */
13861 type = expanded_args;
13862 expanded_args = NULL_TREE;
13866 while (i > 0) {
13867 --i;
13869 if (expanded_args)
13870 type = TREE_VEC_ELT (expanded_args, i);
13871 else if (!type)
13872 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
13874 if (type == error_mark_node)
13875 return error_mark_node;
13876 if (VOID_TYPE_P (type))
13878 if (complain & tf_error)
13880 error ("invalid parameter type %qT", type);
13881 if (in_decl)
13882 error ("in declaration %q+D", in_decl);
13884 return error_mark_node;
13886 /* DR 657. */
13887 if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
13888 return error_mark_node;
13890 /* Do array-to-pointer, function-to-pointer conversion, and ignore
13891 top-level qualifiers as required. */
13892 type = cv_unqualified (type_decays_to (type));
13894 /* We do not substitute into default arguments here. The standard
13895 mandates that they be instantiated only when needed, which is
13896 done in build_over_call. */
13897 default_arg = TREE_PURPOSE (arg_types);
13899 /* Except that we do substitute default arguments under tsubst_lambda_expr,
13900 since the new op() won't have any associated template arguments for us
13901 to refer to later. */
13902 if (lambda_fn_in_template_p (in_decl))
13903 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
13904 false/*fn*/, false/*constexpr*/);
13906 if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
13908 /* We've instantiated a template before its default arguments
13909 have been parsed. This can happen for a nested template
13910 class, and is not an error unless we require the default
13911 argument in a call of this function. */
13912 remaining_arg_types =
13913 tree_cons (default_arg, type, remaining_arg_types);
13914 vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
13916 else
13917 remaining_arg_types =
13918 hash_tree_cons (default_arg, type, remaining_arg_types);
13921 return remaining_arg_types;
13924 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
13925 *not* handle the exception-specification for FNTYPE, because the
13926 initial substitution of explicitly provided template parameters
13927 during argument deduction forbids substitution into the
13928 exception-specification:
13930 [temp.deduct]
13932 All references in the function type of the function template to the
13933 corresponding template parameters are replaced by the specified tem-
13934 plate argument values. If a substitution in a template parameter or
13935 in the function type of the function template results in an invalid
13936 type, type deduction fails. [Note: The equivalent substitution in
13937 exception specifications is done only when the function is instanti-
13938 ated, at which point a program is ill-formed if the substitution
13939 results in an invalid type.] */
13941 static tree
13942 tsubst_function_type (tree t,
13943 tree args,
13944 tsubst_flags_t complain,
13945 tree in_decl)
13947 tree return_type;
13948 tree arg_types = NULL_TREE;
13949 tree fntype;
13951 /* The TYPE_CONTEXT is not used for function/method types. */
13952 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
13954 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
13955 failure. */
13956 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13958 if (late_return_type_p)
13960 /* Substitute the argument types. */
13961 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
13962 complain, in_decl);
13963 if (arg_types == error_mark_node)
13964 return error_mark_node;
13966 tree save_ccp = current_class_ptr;
13967 tree save_ccr = current_class_ref;
13968 tree this_type = (TREE_CODE (t) == METHOD_TYPE
13969 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
13970 bool do_inject = this_type && CLASS_TYPE_P (this_type);
13971 if (do_inject)
13973 /* DR 1207: 'this' is in scope in the trailing return type. */
13974 inject_this_parameter (this_type, cp_type_quals (this_type));
13977 /* Substitute the return type. */
13978 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13980 if (do_inject)
13982 current_class_ptr = save_ccp;
13983 current_class_ref = save_ccr;
13986 else
13987 /* Substitute the return type. */
13988 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13990 if (return_type == error_mark_node)
13991 return error_mark_node;
13992 /* DR 486 clarifies that creation of a function type with an
13993 invalid return type is a deduction failure. */
13994 if (TREE_CODE (return_type) == ARRAY_TYPE
13995 || TREE_CODE (return_type) == FUNCTION_TYPE)
13997 if (complain & tf_error)
13999 if (TREE_CODE (return_type) == ARRAY_TYPE)
14000 error ("function returning an array");
14001 else
14002 error ("function returning a function");
14004 return error_mark_node;
14006 /* And DR 657. */
14007 if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14008 return error_mark_node;
14010 if (!late_return_type_p)
14012 /* Substitute the argument types. */
14013 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14014 complain, in_decl);
14015 if (arg_types == error_mark_node)
14016 return error_mark_node;
14019 /* Construct a new type node and return it. */
14020 if (TREE_CODE (t) == FUNCTION_TYPE)
14022 fntype = build_function_type (return_type, arg_types);
14023 fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
14025 else
14027 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14028 /* Don't pick up extra function qualifiers from the basetype. */
14029 r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14030 if (! MAYBE_CLASS_TYPE_P (r))
14032 /* [temp.deduct]
14034 Type deduction may fail for any of the following
14035 reasons:
14037 -- Attempting to create "pointer to member of T" when T
14038 is not a class type. */
14039 if (complain & tf_error)
14040 error ("creating pointer to member function of non-class type %qT",
14042 return error_mark_node;
14045 fntype = build_method_type_directly (r, return_type,
14046 TREE_CHAIN (arg_types));
14048 fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14050 /* See comment above. */
14051 tree raises = NULL_TREE;
14052 cp_ref_qualifier rqual = type_memfn_rqual (t);
14053 fntype = build_cp_fntype_variant (fntype, rqual, raises, late_return_type_p);
14055 return fntype;
14058 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
14059 ARGS into that specification, and return the substituted
14060 specification. If there is no specification, return NULL_TREE. */
14062 static tree
14063 tsubst_exception_specification (tree fntype,
14064 tree args,
14065 tsubst_flags_t complain,
14066 tree in_decl,
14067 bool defer_ok)
14069 tree specs;
14070 tree new_specs;
14072 specs = TYPE_RAISES_EXCEPTIONS (fntype);
14073 new_specs = NULL_TREE;
14074 if (specs && TREE_PURPOSE (specs))
14076 /* A noexcept-specifier. */
14077 tree expr = TREE_PURPOSE (specs);
14078 if (TREE_CODE (expr) == INTEGER_CST)
14079 new_specs = expr;
14080 else if (defer_ok)
14082 /* Defer instantiation of noexcept-specifiers to avoid
14083 excessive instantiations (c++/49107). */
14084 new_specs = make_node (DEFERRED_NOEXCEPT);
14085 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14087 /* We already partially instantiated this member template,
14088 so combine the new args with the old. */
14089 DEFERRED_NOEXCEPT_PATTERN (new_specs)
14090 = DEFERRED_NOEXCEPT_PATTERN (expr);
14091 DEFERRED_NOEXCEPT_ARGS (new_specs)
14092 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14094 else
14096 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14097 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14100 else
14101 new_specs = tsubst_copy_and_build
14102 (expr, args, complain, in_decl, /*function_p=*/false,
14103 /*integral_constant_expression_p=*/true);
14104 new_specs = build_noexcept_spec (new_specs, complain);
14106 else if (specs)
14108 if (! TREE_VALUE (specs))
14109 new_specs = specs;
14110 else
14111 while (specs)
14113 tree spec;
14114 int i, len = 1;
14115 tree expanded_specs = NULL_TREE;
14117 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14119 /* Expand the pack expansion type. */
14120 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14121 args, complain,
14122 in_decl);
14124 if (expanded_specs == error_mark_node)
14125 return error_mark_node;
14126 else if (TREE_CODE (expanded_specs) == TREE_VEC)
14127 len = TREE_VEC_LENGTH (expanded_specs);
14128 else
14130 /* We're substituting into a member template, so
14131 we got a TYPE_PACK_EXPANSION back. Add that
14132 expansion and move on. */
14133 gcc_assert (TREE_CODE (expanded_specs)
14134 == TYPE_PACK_EXPANSION);
14135 new_specs = add_exception_specifier (new_specs,
14136 expanded_specs,
14137 complain);
14138 specs = TREE_CHAIN (specs);
14139 continue;
14143 for (i = 0; i < len; ++i)
14145 if (expanded_specs)
14146 spec = TREE_VEC_ELT (expanded_specs, i);
14147 else
14148 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14149 if (spec == error_mark_node)
14150 return spec;
14151 new_specs = add_exception_specifier (new_specs, spec,
14152 complain);
14155 specs = TREE_CHAIN (specs);
14158 return new_specs;
14161 /* Take the tree structure T and replace template parameters used
14162 therein with the argument vector ARGS. IN_DECL is an associated
14163 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
14164 Issue error and warning messages under control of COMPLAIN. Note
14165 that we must be relatively non-tolerant of extensions here, in
14166 order to preserve conformance; if we allow substitutions that
14167 should not be allowed, we may allow argument deductions that should
14168 not succeed, and therefore report ambiguous overload situations
14169 where there are none. In theory, we could allow the substitution,
14170 but indicate that it should have failed, and allow our caller to
14171 make sure that the right thing happens, but we don't try to do this
14172 yet.
14174 This function is used for dealing with types, decls and the like;
14175 for expressions, use tsubst_expr or tsubst_copy. */
14177 tree
14178 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14180 enum tree_code code;
14181 tree type, r = NULL_TREE;
14183 if (t == NULL_TREE || t == error_mark_node
14184 || t == integer_type_node
14185 || t == void_type_node
14186 || t == char_type_node
14187 || t == unknown_type_node
14188 || TREE_CODE (t) == NAMESPACE_DECL
14189 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14190 return t;
14192 if (DECL_P (t))
14193 return tsubst_decl (t, args, complain);
14195 if (args == NULL_TREE)
14196 return t;
14198 code = TREE_CODE (t);
14200 if (code == IDENTIFIER_NODE)
14201 type = IDENTIFIER_TYPE_VALUE (t);
14202 else
14203 type = TREE_TYPE (t);
14205 gcc_assert (type != unknown_type_node);
14207 /* Reuse typedefs. We need to do this to handle dependent attributes,
14208 such as attribute aligned. */
14209 if (TYPE_P (t)
14210 && typedef_variant_p (t))
14212 tree decl = TYPE_NAME (t);
14214 if (alias_template_specialization_p (t))
14216 /* DECL represents an alias template and we want to
14217 instantiate it. */
14218 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14219 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14220 r = instantiate_alias_template (tmpl, gen_args, complain);
14222 else if (DECL_CLASS_SCOPE_P (decl)
14223 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14224 && uses_template_parms (DECL_CONTEXT (decl)))
14226 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14227 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14228 r = retrieve_specialization (tmpl, gen_args, 0);
14230 else if (DECL_FUNCTION_SCOPE_P (decl)
14231 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14232 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14233 r = retrieve_local_specialization (decl);
14234 else
14235 /* The typedef is from a non-template context. */
14236 return t;
14238 if (r)
14240 r = TREE_TYPE (r);
14241 r = cp_build_qualified_type_real
14242 (r, cp_type_quals (t) | cp_type_quals (r),
14243 complain | tf_ignore_bad_quals);
14244 return r;
14246 else
14248 /* We don't have an instantiation yet, so drop the typedef. */
14249 int quals = cp_type_quals (t);
14250 t = DECL_ORIGINAL_TYPE (decl);
14251 t = cp_build_qualified_type_real (t, quals,
14252 complain | tf_ignore_bad_quals);
14256 bool fndecl_type = (complain & tf_fndecl_type);
14257 complain &= ~tf_fndecl_type;
14259 if (type
14260 && code != TYPENAME_TYPE
14261 && code != TEMPLATE_TYPE_PARM
14262 && code != TEMPLATE_PARM_INDEX
14263 && code != IDENTIFIER_NODE
14264 && code != FUNCTION_TYPE
14265 && code != METHOD_TYPE)
14266 type = tsubst (type, args, complain, in_decl);
14267 if (type == error_mark_node)
14268 return error_mark_node;
14270 switch (code)
14272 case RECORD_TYPE:
14273 case UNION_TYPE:
14274 case ENUMERAL_TYPE:
14275 return tsubst_aggr_type (t, args, complain, in_decl,
14276 /*entering_scope=*/0);
14278 case ERROR_MARK:
14279 case IDENTIFIER_NODE:
14280 case VOID_TYPE:
14281 case REAL_TYPE:
14282 case COMPLEX_TYPE:
14283 case VECTOR_TYPE:
14284 case BOOLEAN_TYPE:
14285 case NULLPTR_TYPE:
14286 case LANG_TYPE:
14287 return t;
14289 case INTEGER_TYPE:
14290 if (t == integer_type_node)
14291 return t;
14293 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14294 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14295 return t;
14298 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14300 max = tsubst_expr (omax, args, complain, in_decl,
14301 /*integral_constant_expression_p=*/false);
14303 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14304 needed. */
14305 if (TREE_CODE (max) == NOP_EXPR
14306 && TREE_SIDE_EFFECTS (omax)
14307 && !TREE_TYPE (max))
14308 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14310 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
14311 with TREE_SIDE_EFFECTS that indicates this is not an integral
14312 constant expression. */
14313 if (processing_template_decl
14314 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14316 gcc_assert (TREE_CODE (max) == NOP_EXPR);
14317 TREE_SIDE_EFFECTS (max) = 1;
14320 return compute_array_index_type (NULL_TREE, max, complain);
14323 case TEMPLATE_TYPE_PARM:
14324 case TEMPLATE_TEMPLATE_PARM:
14325 case BOUND_TEMPLATE_TEMPLATE_PARM:
14326 case TEMPLATE_PARM_INDEX:
14328 int idx;
14329 int level;
14330 int levels;
14331 tree arg = NULL_TREE;
14333 /* Early in template argument deduction substitution, we don't
14334 want to reduce the level of 'auto', or it will be confused
14335 with a normal template parm in subsequent deduction. */
14336 if (is_auto (t) && (complain & tf_partial))
14337 return t;
14339 r = NULL_TREE;
14341 gcc_assert (TREE_VEC_LENGTH (args) > 0);
14342 template_parm_level_and_index (t, &level, &idx);
14344 levels = TMPL_ARGS_DEPTH (args);
14345 if (level <= levels
14346 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14348 arg = TMPL_ARG (args, level, idx);
14350 /* See through ARGUMENT_PACK_SELECT arguments. */
14351 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14352 arg = argument_pack_select_arg (arg);
14355 if (arg == error_mark_node)
14356 return error_mark_node;
14357 else if (arg != NULL_TREE)
14359 if (ARGUMENT_PACK_P (arg))
14360 /* If ARG is an argument pack, we don't actually want to
14361 perform a substitution here, because substitutions
14362 for argument packs are only done
14363 element-by-element. We can get to this point when
14364 substituting the type of a non-type template
14365 parameter pack, when that type actually contains
14366 template parameter packs from an outer template, e.g.,
14368 template<typename... Types> struct A {
14369 template<Types... Values> struct B { };
14370 }; */
14371 return t;
14373 if (code == TEMPLATE_TYPE_PARM)
14375 int quals;
14376 gcc_assert (TYPE_P (arg));
14378 quals = cp_type_quals (arg) | cp_type_quals (t);
14380 return cp_build_qualified_type_real
14381 (arg, quals, complain | tf_ignore_bad_quals);
14383 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14385 /* We are processing a type constructed from a
14386 template template parameter. */
14387 tree argvec = tsubst (TYPE_TI_ARGS (t),
14388 args, complain, in_decl);
14389 if (argvec == error_mark_node)
14390 return error_mark_node;
14392 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14393 || TREE_CODE (arg) == TEMPLATE_DECL
14394 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14396 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14397 /* Consider this code:
14399 template <template <class> class Template>
14400 struct Internal {
14401 template <class Arg> using Bind = Template<Arg>;
14404 template <template <class> class Template, class Arg>
14405 using Instantiate = Template<Arg>; //#0
14407 template <template <class> class Template,
14408 class Argument>
14409 using Bind =
14410 Instantiate<Internal<Template>::template Bind,
14411 Argument>; //#1
14413 When #1 is parsed, the
14414 BOUND_TEMPLATE_TEMPLATE_PARM representing the
14415 parameter `Template' in #0 matches the
14416 UNBOUND_CLASS_TEMPLATE representing the argument
14417 `Internal<Template>::template Bind'; We then want
14418 to assemble the type `Bind<Argument>' that can't
14419 be fully created right now, because
14420 `Internal<Template>' not being complete, the Bind
14421 template cannot be looked up in that context. So
14422 we need to "store" `Bind<Argument>' for later
14423 when the context of Bind becomes complete. Let's
14424 store that in a TYPENAME_TYPE. */
14425 return make_typename_type (TYPE_CONTEXT (arg),
14426 build_nt (TEMPLATE_ID_EXPR,
14427 TYPE_IDENTIFIER (arg),
14428 argvec),
14429 typename_type,
14430 complain);
14432 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
14433 are resolving nested-types in the signature of a
14434 member function templates. Otherwise ARG is a
14435 TEMPLATE_DECL and is the real template to be
14436 instantiated. */
14437 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14438 arg = TYPE_NAME (arg);
14440 r = lookup_template_class (arg,
14441 argvec, in_decl,
14442 DECL_CONTEXT (arg),
14443 /*entering_scope=*/0,
14444 complain);
14445 return cp_build_qualified_type_real
14446 (r, cp_type_quals (t) | cp_type_quals (r), complain);
14448 else if (code == TEMPLATE_TEMPLATE_PARM)
14449 return arg;
14450 else
14451 /* TEMPLATE_PARM_INDEX. */
14452 return convert_from_reference (unshare_expr (arg));
14455 if (level == 1)
14456 /* This can happen during the attempted tsubst'ing in
14457 unify. This means that we don't yet have any information
14458 about the template parameter in question. */
14459 return t;
14461 /* If we get here, we must have been looking at a parm for a
14462 more deeply nested template. Make a new version of this
14463 template parameter, but with a lower level. */
14464 switch (code)
14466 case TEMPLATE_TYPE_PARM:
14467 case TEMPLATE_TEMPLATE_PARM:
14468 case BOUND_TEMPLATE_TEMPLATE_PARM:
14469 if (cp_type_quals (t))
14471 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14472 r = cp_build_qualified_type_real
14473 (r, cp_type_quals (t),
14474 complain | (code == TEMPLATE_TYPE_PARM
14475 ? tf_ignore_bad_quals : 0));
14477 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14478 && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14479 && (r = (TEMPLATE_PARM_DESCENDANTS
14480 (TEMPLATE_TYPE_PARM_INDEX (t))))
14481 && (r = TREE_TYPE (r))
14482 && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14483 /* Break infinite recursion when substituting the constraints
14484 of a constrained placeholder. */;
14485 else
14487 r = copy_type (t);
14488 TEMPLATE_TYPE_PARM_INDEX (r)
14489 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14490 r, levels, args, complain);
14491 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14492 TYPE_MAIN_VARIANT (r) = r;
14493 TYPE_POINTER_TO (r) = NULL_TREE;
14494 TYPE_REFERENCE_TO (r) = NULL_TREE;
14496 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14498 /* Propagate constraints on placeholders. */
14499 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14500 PLACEHOLDER_TYPE_CONSTRAINTS (r)
14501 = tsubst_constraint (constr, args, complain, in_decl);
14502 else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14504 pl = tsubst_copy (pl, args, complain, in_decl);
14505 CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14509 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14510 /* We have reduced the level of the template
14511 template parameter, but not the levels of its
14512 template parameters, so canonical_type_parameter
14513 will not be able to find the canonical template
14514 template parameter for this level. Thus, we
14515 require structural equality checking to compare
14516 TEMPLATE_TEMPLATE_PARMs. */
14517 SET_TYPE_STRUCTURAL_EQUALITY (r);
14518 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14519 SET_TYPE_STRUCTURAL_EQUALITY (r);
14520 else
14521 TYPE_CANONICAL (r) = canonical_type_parameter (r);
14523 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14525 tree tinfo = TYPE_TEMPLATE_INFO (t);
14526 /* We might need to substitute into the types of non-type
14527 template parameters. */
14528 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14529 complain, in_decl);
14530 if (tmpl == error_mark_node)
14531 return error_mark_node;
14532 tree argvec = tsubst (TI_ARGS (tinfo), args,
14533 complain, in_decl);
14534 if (argvec == error_mark_node)
14535 return error_mark_node;
14537 TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14538 = build_template_info (tmpl, argvec);
14541 break;
14543 case TEMPLATE_PARM_INDEX:
14544 /* OK, now substitute the type of the non-type parameter. We
14545 couldn't do it earlier because it might be an auto parameter,
14546 and we wouldn't need to if we had an argument. */
14547 type = tsubst (type, args, complain, in_decl);
14548 if (type == error_mark_node)
14549 return error_mark_node;
14550 r = reduce_template_parm_level (t, type, levels, args, complain);
14551 break;
14553 default:
14554 gcc_unreachable ();
14557 return r;
14560 case TREE_LIST:
14562 tree purpose, value, chain;
14564 if (t == void_list_node)
14565 return t;
14567 purpose = TREE_PURPOSE (t);
14568 if (purpose)
14570 purpose = tsubst (purpose, args, complain, in_decl);
14571 if (purpose == error_mark_node)
14572 return error_mark_node;
14574 value = TREE_VALUE (t);
14575 if (value)
14577 value = tsubst (value, args, complain, in_decl);
14578 if (value == error_mark_node)
14579 return error_mark_node;
14581 chain = TREE_CHAIN (t);
14582 if (chain && chain != void_type_node)
14584 chain = tsubst (chain, args, complain, in_decl);
14585 if (chain == error_mark_node)
14586 return error_mark_node;
14588 if (purpose == TREE_PURPOSE (t)
14589 && value == TREE_VALUE (t)
14590 && chain == TREE_CHAIN (t))
14591 return t;
14592 return hash_tree_cons (purpose, value, chain);
14595 case TREE_BINFO:
14596 /* We should never be tsubsting a binfo. */
14597 gcc_unreachable ();
14599 case TREE_VEC:
14600 /* A vector of template arguments. */
14601 gcc_assert (!type);
14602 return tsubst_template_args (t, args, complain, in_decl);
14604 case POINTER_TYPE:
14605 case REFERENCE_TYPE:
14607 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14608 return t;
14610 /* [temp.deduct]
14612 Type deduction may fail for any of the following
14613 reasons:
14615 -- Attempting to create a pointer to reference type.
14616 -- Attempting to create a reference to a reference type or
14617 a reference to void.
14619 Core issue 106 says that creating a reference to a reference
14620 during instantiation is no longer a cause for failure. We
14621 only enforce this check in strict C++98 mode. */
14622 if ((TYPE_REF_P (type)
14623 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14624 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14626 static location_t last_loc;
14628 /* We keep track of the last time we issued this error
14629 message to avoid spewing a ton of messages during a
14630 single bad template instantiation. */
14631 if (complain & tf_error
14632 && last_loc != input_location)
14634 if (VOID_TYPE_P (type))
14635 error ("forming reference to void");
14636 else if (code == POINTER_TYPE)
14637 error ("forming pointer to reference type %qT", type);
14638 else
14639 error ("forming reference to reference type %qT", type);
14640 last_loc = input_location;
14643 return error_mark_node;
14645 else if (TREE_CODE (type) == FUNCTION_TYPE
14646 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14647 || type_memfn_rqual (type) != REF_QUAL_NONE))
14649 if (complain & tf_error)
14651 if (code == POINTER_TYPE)
14652 error ("forming pointer to qualified function type %qT",
14653 type);
14654 else
14655 error ("forming reference to qualified function type %qT",
14656 type);
14658 return error_mark_node;
14660 else if (code == POINTER_TYPE)
14662 r = build_pointer_type (type);
14663 if (TREE_CODE (type) == METHOD_TYPE)
14664 r = build_ptrmemfunc_type (r);
14666 else if (TYPE_REF_P (type))
14667 /* In C++0x, during template argument substitution, when there is an
14668 attempt to create a reference to a reference type, reference
14669 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14671 "If a template-argument for a template-parameter T names a type
14672 that is a reference to a type A, an attempt to create the type
14673 'lvalue reference to cv T' creates the type 'lvalue reference to
14674 A,' while an attempt to create the type type rvalue reference to
14675 cv T' creates the type T"
14677 r = cp_build_reference_type
14678 (TREE_TYPE (type),
14679 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14680 else
14681 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14682 r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14684 if (r != error_mark_node)
14685 /* Will this ever be needed for TYPE_..._TO values? */
14686 layout_type (r);
14688 return r;
14690 case OFFSET_TYPE:
14692 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14693 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14695 /* [temp.deduct]
14697 Type deduction may fail for any of the following
14698 reasons:
14700 -- Attempting to create "pointer to member of T" when T
14701 is not a class type. */
14702 if (complain & tf_error)
14703 error ("creating pointer to member of non-class type %qT", r);
14704 return error_mark_node;
14706 if (TYPE_REF_P (type))
14708 if (complain & tf_error)
14709 error ("creating pointer to member reference type %qT", type);
14710 return error_mark_node;
14712 if (VOID_TYPE_P (type))
14714 if (complain & tf_error)
14715 error ("creating pointer to member of type void");
14716 return error_mark_node;
14718 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14719 if (TREE_CODE (type) == FUNCTION_TYPE)
14721 /* The type of the implicit object parameter gets its
14722 cv-qualifiers from the FUNCTION_TYPE. */
14723 tree memptr;
14724 tree method_type
14725 = build_memfn_type (type, r, type_memfn_quals (type),
14726 type_memfn_rqual (type));
14727 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14728 return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14729 complain);
14731 else
14732 return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14733 cp_type_quals (t),
14734 complain);
14736 case FUNCTION_TYPE:
14737 case METHOD_TYPE:
14739 tree fntype;
14740 tree specs;
14741 fntype = tsubst_function_type (t, args, complain, in_decl);
14742 if (fntype == error_mark_node)
14743 return error_mark_node;
14745 /* Substitute the exception specification. */
14746 specs = tsubst_exception_specification (t, args, complain, in_decl,
14747 /*defer_ok*/fndecl_type);
14748 if (specs == error_mark_node)
14749 return error_mark_node;
14750 if (specs)
14751 fntype = build_exception_variant (fntype, specs);
14752 return fntype;
14754 case ARRAY_TYPE:
14756 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14757 if (domain == error_mark_node)
14758 return error_mark_node;
14760 /* As an optimization, we avoid regenerating the array type if
14761 it will obviously be the same as T. */
14762 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14763 return t;
14765 /* These checks should match the ones in create_array_type_for_decl.
14767 [temp.deduct]
14769 The deduction may fail for any of the following reasons:
14771 -- Attempting to create an array with an element type that
14772 is void, a function type, or a reference type, or [DR337]
14773 an abstract class type. */
14774 if (VOID_TYPE_P (type)
14775 || TREE_CODE (type) == FUNCTION_TYPE
14776 || (TREE_CODE (type) == ARRAY_TYPE
14777 && TYPE_DOMAIN (type) == NULL_TREE)
14778 || TYPE_REF_P (type))
14780 if (complain & tf_error)
14781 error ("creating array of %qT", type);
14782 return error_mark_node;
14785 if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14786 return error_mark_node;
14788 r = build_cplus_array_type (type, domain);
14790 if (!valid_array_size_p (input_location, r, in_decl,
14791 (complain & tf_error)))
14792 return error_mark_node;
14794 if (TYPE_USER_ALIGN (t))
14796 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14797 TYPE_USER_ALIGN (r) = 1;
14800 return r;
14803 case TYPENAME_TYPE:
14805 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14806 in_decl, /*entering_scope=*/1);
14807 if (ctx == error_mark_node)
14808 return error_mark_node;
14810 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14811 complain, in_decl);
14812 if (f == error_mark_node)
14813 return error_mark_node;
14815 if (!MAYBE_CLASS_TYPE_P (ctx))
14817 if (complain & tf_error)
14818 error ("%qT is not a class, struct, or union type", ctx);
14819 return error_mark_node;
14821 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14823 /* Normally, make_typename_type does not require that the CTX
14824 have complete type in order to allow things like:
14826 template <class T> struct S { typename S<T>::X Y; };
14828 But, such constructs have already been resolved by this
14829 point, so here CTX really should have complete type, unless
14830 it's a partial instantiation. */
14831 ctx = complete_type (ctx);
14832 if (!COMPLETE_TYPE_P (ctx))
14834 if (complain & tf_error)
14835 cxx_incomplete_type_error (NULL_TREE, ctx);
14836 return error_mark_node;
14840 f = make_typename_type (ctx, f, typename_type,
14841 complain | tf_keep_type_decl);
14842 if (f == error_mark_node)
14843 return f;
14844 if (TREE_CODE (f) == TYPE_DECL)
14846 complain |= tf_ignore_bad_quals;
14847 f = TREE_TYPE (f);
14850 if (TREE_CODE (f) != TYPENAME_TYPE)
14852 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14854 if (complain & tf_error)
14855 error ("%qT resolves to %qT, which is not an enumeration type",
14856 t, f);
14857 else
14858 return error_mark_node;
14860 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14862 if (complain & tf_error)
14863 error ("%qT resolves to %qT, which is is not a class type",
14864 t, f);
14865 else
14866 return error_mark_node;
14870 return cp_build_qualified_type_real
14871 (f, cp_type_quals (f) | cp_type_quals (t), complain);
14874 case UNBOUND_CLASS_TEMPLATE:
14876 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14877 in_decl, /*entering_scope=*/1);
14878 tree name = TYPE_IDENTIFIER (t);
14879 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
14881 if (ctx == error_mark_node || name == error_mark_node)
14882 return error_mark_node;
14884 if (parm_list)
14885 parm_list = tsubst_template_parms (parm_list, args, complain);
14886 return make_unbound_class_template (ctx, name, parm_list, complain);
14889 case TYPEOF_TYPE:
14891 tree type;
14893 ++cp_unevaluated_operand;
14894 ++c_inhibit_evaluation_warnings;
14896 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
14897 complain, in_decl,
14898 /*integral_constant_expression_p=*/false);
14900 --cp_unevaluated_operand;
14901 --c_inhibit_evaluation_warnings;
14903 type = finish_typeof (type);
14904 return cp_build_qualified_type_real (type,
14905 cp_type_quals (t)
14906 | cp_type_quals (type),
14907 complain);
14910 case DECLTYPE_TYPE:
14912 tree type;
14914 ++cp_unevaluated_operand;
14915 ++c_inhibit_evaluation_warnings;
14917 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
14918 complain|tf_decltype, in_decl,
14919 /*function_p*/false,
14920 /*integral_constant_expression*/false);
14922 if (DECLTYPE_FOR_INIT_CAPTURE (t))
14924 if (type == NULL_TREE)
14926 if (complain & tf_error)
14927 error ("empty initializer in lambda init-capture");
14928 type = error_mark_node;
14930 else if (TREE_CODE (type) == TREE_LIST)
14931 type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
14934 --cp_unevaluated_operand;
14935 --c_inhibit_evaluation_warnings;
14937 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
14938 type = lambda_capture_field_type (type,
14939 DECLTYPE_FOR_INIT_CAPTURE (t),
14940 DECLTYPE_FOR_REF_CAPTURE (t));
14941 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
14942 type = lambda_proxy_type (type);
14943 else
14945 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
14946 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
14947 && EXPR_P (type))
14948 /* In a template ~id could be either a complement expression
14949 or an unqualified-id naming a destructor; if instantiating
14950 it produces an expression, it's not an id-expression or
14951 member access. */
14952 id = false;
14953 type = finish_decltype_type (type, id, complain);
14955 return cp_build_qualified_type_real (type,
14956 cp_type_quals (t)
14957 | cp_type_quals (type),
14958 complain | tf_ignore_bad_quals);
14961 case UNDERLYING_TYPE:
14963 tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
14964 complain, in_decl);
14965 return finish_underlying_type (type);
14968 case TYPE_ARGUMENT_PACK:
14969 case NONTYPE_ARGUMENT_PACK:
14971 tree r;
14973 if (code == NONTYPE_ARGUMENT_PACK)
14974 r = make_node (code);
14975 else
14976 r = cxx_make_type (code);
14978 tree pack_args = ARGUMENT_PACK_ARGS (t);
14979 pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
14980 SET_ARGUMENT_PACK_ARGS (r, pack_args);
14982 return r;
14985 case VOID_CST:
14986 case INTEGER_CST:
14987 case REAL_CST:
14988 case STRING_CST:
14989 case PLUS_EXPR:
14990 case MINUS_EXPR:
14991 case NEGATE_EXPR:
14992 case NOP_EXPR:
14993 case INDIRECT_REF:
14994 case ADDR_EXPR:
14995 case CALL_EXPR:
14996 case ARRAY_REF:
14997 case SCOPE_REF:
14998 /* We should use one of the expression tsubsts for these codes. */
14999 gcc_unreachable ();
15001 default:
15002 sorry ("use of %qs in template", get_tree_code_name (code));
15003 return error_mark_node;
15007 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
15008 expression on the left-hand side of the "." or "->" operator. We
15009 only do the lookup if we had a dependent BASELINK. Otherwise we
15010 adjust it onto the instantiated heirarchy. */
15012 static tree
15013 tsubst_baselink (tree baselink, tree object_type,
15014 tree args, tsubst_flags_t complain, tree in_decl)
15016 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15017 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15018 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15020 tree optype = BASELINK_OPTYPE (baselink);
15021 optype = tsubst (optype, args, complain, in_decl);
15023 tree template_args = NULL_TREE;
15024 bool template_id_p = false;
15025 tree fns = BASELINK_FUNCTIONS (baselink);
15026 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15028 template_id_p = true;
15029 template_args = TREE_OPERAND (fns, 1);
15030 fns = TREE_OPERAND (fns, 0);
15031 if (template_args)
15032 template_args = tsubst_template_args (template_args, args,
15033 complain, in_decl);
15036 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15037 binfo_type = tsubst (binfo_type, args, complain, in_decl);
15038 bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15040 if (dependent_p)
15042 tree name = OVL_NAME (fns);
15043 if (IDENTIFIER_CONV_OP_P (name))
15044 name = make_conv_op_name (optype);
15046 if (name == complete_dtor_identifier)
15047 /* Treat as-if non-dependent below. */
15048 dependent_p = false;
15050 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15051 if (!baselink)
15053 if ((complain & tf_error)
15054 && constructor_name_p (name, qualifying_scope))
15055 error ("cannot call constructor %<%T::%D%> directly",
15056 qualifying_scope, name);
15057 return error_mark_node;
15060 if (BASELINK_P (baselink))
15061 fns = BASELINK_FUNCTIONS (baselink);
15063 else
15064 /* We're going to overwrite pieces below, make a duplicate. */
15065 baselink = copy_node (baselink);
15067 /* If lookup found a single function, mark it as used at this point.
15068 (If lookup found multiple functions the one selected later by
15069 overload resolution will be marked as used at that point.) */
15070 if (!template_id_p && !really_overloaded_fn (fns))
15072 tree fn = OVL_FIRST (fns);
15073 bool ok = mark_used (fn, complain);
15074 if (!ok && !(complain & tf_error))
15075 return error_mark_node;
15076 if (ok && BASELINK_P (baselink))
15077 /* We might have instantiated an auto function. */
15078 TREE_TYPE (baselink) = TREE_TYPE (fn);
15081 if (BASELINK_P (baselink))
15083 /* Add back the template arguments, if present. */
15084 if (template_id_p)
15085 BASELINK_FUNCTIONS (baselink)
15086 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15088 /* Update the conversion operator type. */
15089 BASELINK_OPTYPE (baselink) = optype;
15092 if (!object_type)
15093 object_type = current_class_type;
15095 if (qualified_p || !dependent_p)
15097 baselink = adjust_result_of_qualified_name_lookup (baselink,
15098 qualifying_scope,
15099 object_type);
15100 if (!qualified_p)
15101 /* We need to call adjust_result_of_qualified_name_lookup in case the
15102 destructor names a base class, but we unset BASELINK_QUALIFIED_P
15103 so that we still get virtual function binding. */
15104 BASELINK_QUALIFIED_P (baselink) = false;
15107 return baselink;
15110 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
15111 true if the qualified-id will be a postfix-expression in-and-of
15112 itself; false if more of the postfix-expression follows the
15113 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
15114 of "&". */
15116 static tree
15117 tsubst_qualified_id (tree qualified_id, tree args,
15118 tsubst_flags_t complain, tree in_decl,
15119 bool done, bool address_p)
15121 tree expr;
15122 tree scope;
15123 tree name;
15124 bool is_template;
15125 tree template_args;
15126 location_t loc = UNKNOWN_LOCATION;
15128 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15130 /* Figure out what name to look up. */
15131 name = TREE_OPERAND (qualified_id, 1);
15132 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15134 is_template = true;
15135 loc = EXPR_LOCATION (name);
15136 template_args = TREE_OPERAND (name, 1);
15137 if (template_args)
15138 template_args = tsubst_template_args (template_args, args,
15139 complain, in_decl);
15140 if (template_args == error_mark_node)
15141 return error_mark_node;
15142 name = TREE_OPERAND (name, 0);
15144 else
15146 is_template = false;
15147 template_args = NULL_TREE;
15150 /* Substitute into the qualifying scope. When there are no ARGS, we
15151 are just trying to simplify a non-dependent expression. In that
15152 case the qualifying scope may be dependent, and, in any case,
15153 substituting will not help. */
15154 scope = TREE_OPERAND (qualified_id, 0);
15155 if (args)
15157 scope = tsubst (scope, args, complain, in_decl);
15158 expr = tsubst_copy (name, args, complain, in_decl);
15160 else
15161 expr = name;
15163 if (dependent_scope_p (scope))
15165 if (is_template)
15166 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15167 tree r = build_qualified_name (NULL_TREE, scope, expr,
15168 QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15169 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15170 return r;
15173 if (!BASELINK_P (name) && !DECL_P (expr))
15175 if (TREE_CODE (expr) == BIT_NOT_EXPR)
15177 /* A BIT_NOT_EXPR is used to represent a destructor. */
15178 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15180 error ("qualifying type %qT does not match destructor name ~%qT",
15181 scope, TREE_OPERAND (expr, 0));
15182 expr = error_mark_node;
15184 else
15185 expr = lookup_qualified_name (scope, complete_dtor_identifier,
15186 /*is_type_p=*/0, false);
15188 else
15189 expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15190 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15191 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15193 if (complain & tf_error)
15195 error ("dependent-name %qE is parsed as a non-type, but "
15196 "instantiation yields a type", qualified_id);
15197 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15199 return error_mark_node;
15203 if (DECL_P (expr))
15205 check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15206 scope);
15207 /* Remember that there was a reference to this entity. */
15208 if (!mark_used (expr, complain) && !(complain & tf_error))
15209 return error_mark_node;
15212 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15214 if (complain & tf_error)
15215 qualified_name_lookup_error (scope,
15216 TREE_OPERAND (qualified_id, 1),
15217 expr, input_location);
15218 return error_mark_node;
15221 if (is_template)
15223 /* We may be repeating a check already done during parsing, but
15224 if it was well-formed and passed then, it will pass again
15225 now, and if it didn't, we wouldn't have got here. The case
15226 we want to catch is when we couldn't tell then, and can now,
15227 namely when templ prior to substitution was an
15228 identifier. */
15229 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15230 return error_mark_node;
15232 if (variable_template_p (expr))
15233 expr = lookup_and_finish_template_variable (expr, template_args,
15234 complain);
15235 else
15236 expr = lookup_template_function (expr, template_args);
15239 if (expr == error_mark_node && complain & tf_error)
15240 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15241 expr, input_location);
15242 else if (TYPE_P (scope))
15244 expr = (adjust_result_of_qualified_name_lookup
15245 (expr, scope, current_nonlambda_class_type ()));
15246 expr = (finish_qualified_id_expr
15247 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15248 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15249 /*template_arg_p=*/false, complain));
15252 /* Expressions do not generally have reference type. */
15253 if (TREE_CODE (expr) != SCOPE_REF
15254 /* However, if we're about to form a pointer-to-member, we just
15255 want the referenced member referenced. */
15256 && TREE_CODE (expr) != OFFSET_REF)
15257 expr = convert_from_reference (expr);
15259 if (REF_PARENTHESIZED_P (qualified_id))
15260 expr = force_paren_expr (expr);
15262 return expr;
15265 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
15266 initializer, DECL is the substituted VAR_DECL. Other arguments are as
15267 for tsubst. */
15269 static tree
15270 tsubst_init (tree init, tree decl, tree args,
15271 tsubst_flags_t complain, tree in_decl)
15273 if (!init)
15274 return NULL_TREE;
15276 init = tsubst_expr (init, args, complain, in_decl, false);
15278 if (!init && TREE_TYPE (decl) != error_mark_node)
15280 /* If we had an initializer but it
15281 instantiated to nothing,
15282 value-initialize the object. This will
15283 only occur when the initializer was a
15284 pack expansion where the parameter packs
15285 used in that expansion were of length
15286 zero. */
15287 init = build_value_init (TREE_TYPE (decl),
15288 complain);
15289 if (TREE_CODE (init) == AGGR_INIT_EXPR)
15290 init = get_target_expr_sfinae (init, complain);
15291 if (TREE_CODE (init) == TARGET_EXPR)
15292 TARGET_EXPR_DIRECT_INIT_P (init) = true;
15295 return init;
15298 /* Like tsubst, but deals with expressions. This function just replaces
15299 template parms; to finish processing the resultant expression, use
15300 tsubst_copy_and_build or tsubst_expr. */
15302 static tree
15303 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15305 enum tree_code code;
15306 tree r;
15308 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15309 return t;
15311 code = TREE_CODE (t);
15313 switch (code)
15315 case PARM_DECL:
15316 r = retrieve_local_specialization (t);
15318 if (r == NULL_TREE)
15320 /* We get here for a use of 'this' in an NSDMI. */
15321 if (DECL_NAME (t) == this_identifier && current_class_ptr)
15322 return current_class_ptr;
15324 /* This can happen for a parameter name used later in a function
15325 declaration (such as in a late-specified return type). Just
15326 make a dummy decl, since it's only used for its type. */
15327 gcc_assert (cp_unevaluated_operand != 0);
15328 r = tsubst_decl (t, args, complain);
15329 /* Give it the template pattern as its context; its true context
15330 hasn't been instantiated yet and this is good enough for
15331 mangling. */
15332 DECL_CONTEXT (r) = DECL_CONTEXT (t);
15335 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15336 r = argument_pack_select_arg (r);
15337 if (!mark_used (r, complain) && !(complain & tf_error))
15338 return error_mark_node;
15339 return r;
15341 case CONST_DECL:
15343 tree enum_type;
15344 tree v;
15346 if (DECL_TEMPLATE_PARM_P (t))
15347 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15348 /* There is no need to substitute into namespace-scope
15349 enumerators. */
15350 if (DECL_NAMESPACE_SCOPE_P (t))
15351 return t;
15352 /* If ARGS is NULL, then T is known to be non-dependent. */
15353 if (args == NULL_TREE)
15354 return scalar_constant_value (t);
15356 /* Unfortunately, we cannot just call lookup_name here.
15357 Consider:
15359 template <int I> int f() {
15360 enum E { a = I };
15361 struct S { void g() { E e = a; } };
15364 When we instantiate f<7>::S::g(), say, lookup_name is not
15365 clever enough to find f<7>::a. */
15366 enum_type
15367 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15368 /*entering_scope=*/0);
15370 for (v = TYPE_VALUES (enum_type);
15371 v != NULL_TREE;
15372 v = TREE_CHAIN (v))
15373 if (TREE_PURPOSE (v) == DECL_NAME (t))
15374 return TREE_VALUE (v);
15376 /* We didn't find the name. That should never happen; if
15377 name-lookup found it during preliminary parsing, we
15378 should find it again here during instantiation. */
15379 gcc_unreachable ();
15381 return t;
15383 case FIELD_DECL:
15384 if (DECL_CONTEXT (t))
15386 tree ctx;
15388 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15389 /*entering_scope=*/1);
15390 if (ctx != DECL_CONTEXT (t))
15392 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15393 if (!r)
15395 if (complain & tf_error)
15396 error ("using invalid field %qD", t);
15397 return error_mark_node;
15399 return r;
15403 return t;
15405 case VAR_DECL:
15406 case FUNCTION_DECL:
15407 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15408 r = tsubst (t, args, complain, in_decl);
15409 else if (local_variable_p (t)
15410 && uses_template_parms (DECL_CONTEXT (t)))
15412 r = retrieve_local_specialization (t);
15413 if (r == NULL_TREE)
15415 /* First try name lookup to find the instantiation. */
15416 r = lookup_name (DECL_NAME (t));
15417 if (r && !is_capture_proxy (r))
15419 /* Make sure that the one we found is the one we want. */
15420 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15421 if (ctx != DECL_CONTEXT (r))
15422 r = NULL_TREE;
15425 if (r)
15426 /* OK */;
15427 else
15429 /* This can happen for a variable used in a
15430 late-specified return type of a local lambda, or for a
15431 local static or constant. Building a new VAR_DECL
15432 should be OK in all those cases. */
15433 r = tsubst_decl (t, args, complain);
15434 if (local_specializations)
15435 /* Avoid infinite recursion (79640). */
15436 register_local_specialization (r, t);
15437 if (decl_maybe_constant_var_p (r))
15439 /* We can't call cp_finish_decl, so handle the
15440 initializer by hand. */
15441 tree init = tsubst_init (DECL_INITIAL (t), r, args,
15442 complain, in_decl);
15443 if (!processing_template_decl)
15444 init = maybe_constant_init (init);
15445 if (processing_template_decl
15446 ? potential_constant_expression (init)
15447 : reduced_constant_expression_p (init))
15448 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15449 = TREE_CONSTANT (r) = true;
15450 DECL_INITIAL (r) = init;
15451 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15452 TREE_TYPE (r)
15453 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15454 complain, adc_variable_type);
15456 gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15457 || decl_constant_var_p (r)
15458 || errorcount || sorrycount);
15459 if (!processing_template_decl
15460 && !TREE_STATIC (r))
15461 r = process_outer_var_ref (r, complain);
15463 /* Remember this for subsequent uses. */
15464 if (local_specializations)
15465 register_local_specialization (r, t);
15467 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15468 r = argument_pack_select_arg (r);
15470 else
15471 r = t;
15472 if (!mark_used (r, complain))
15473 return error_mark_node;
15474 return r;
15476 case NAMESPACE_DECL:
15477 return t;
15479 case OVERLOAD:
15480 /* An OVERLOAD will always be a non-dependent overload set; an
15481 overload set from function scope will just be represented with an
15482 IDENTIFIER_NODE, and from class scope with a BASELINK. */
15483 gcc_assert (!uses_template_parms (t));
15484 /* We must have marked any lookups as persistent. */
15485 gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15486 return t;
15488 case BASELINK:
15489 return tsubst_baselink (t, current_nonlambda_class_type (),
15490 args, complain, in_decl);
15492 case TEMPLATE_DECL:
15493 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15494 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15495 args, complain, in_decl);
15496 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15497 return tsubst (t, args, complain, in_decl);
15498 else if (DECL_CLASS_SCOPE_P (t)
15499 && uses_template_parms (DECL_CONTEXT (t)))
15501 /* Template template argument like the following example need
15502 special treatment:
15504 template <template <class> class TT> struct C {};
15505 template <class T> struct D {
15506 template <class U> struct E {};
15507 C<E> c; // #1
15509 D<int> d; // #2
15511 We are processing the template argument `E' in #1 for
15512 the template instantiation #2. Originally, `E' is a
15513 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
15514 have to substitute this with one having context `D<int>'. */
15516 tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15517 if (dependent_scope_p (context))
15519 /* When rewriting a constructor into a deduction guide, a
15520 non-dependent name can become dependent, so memtmpl<args>
15521 becomes context::template memtmpl<args>. */
15522 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15523 return build_qualified_name (type, context, DECL_NAME (t),
15524 /*template*/true);
15526 return lookup_field (context, DECL_NAME(t), 0, false);
15528 else
15529 /* Ordinary template template argument. */
15530 return t;
15532 case NON_LVALUE_EXPR:
15533 case VIEW_CONVERT_EXPR:
15535 /* Handle location wrappers by substituting the wrapped node
15536 first, *then* reusing the resulting type. Doing the type
15537 first ensures that we handle template parameters and
15538 parameter pack expansions. */
15539 gcc_assert (location_wrapper_p (t));
15540 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15541 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15544 case CAST_EXPR:
15545 case REINTERPRET_CAST_EXPR:
15546 case CONST_CAST_EXPR:
15547 case STATIC_CAST_EXPR:
15548 case DYNAMIC_CAST_EXPR:
15549 case IMPLICIT_CONV_EXPR:
15550 case CONVERT_EXPR:
15551 case NOP_EXPR:
15553 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15554 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15555 return build1 (code, type, op0);
15558 case SIZEOF_EXPR:
15559 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15560 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15562 tree expanded, op = TREE_OPERAND (t, 0);
15563 int len = 0;
15565 if (SIZEOF_EXPR_TYPE_P (t))
15566 op = TREE_TYPE (op);
15568 ++cp_unevaluated_operand;
15569 ++c_inhibit_evaluation_warnings;
15570 /* We only want to compute the number of arguments. */
15571 if (PACK_EXPANSION_P (op))
15572 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15573 else
15574 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15575 args, complain, in_decl);
15576 --cp_unevaluated_operand;
15577 --c_inhibit_evaluation_warnings;
15579 if (TREE_CODE (expanded) == TREE_VEC)
15581 len = TREE_VEC_LENGTH (expanded);
15582 /* Set TREE_USED for the benefit of -Wunused. */
15583 for (int i = 0; i < len; i++)
15584 if (DECL_P (TREE_VEC_ELT (expanded, i)))
15585 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15588 if (expanded == error_mark_node)
15589 return error_mark_node;
15590 else if (PACK_EXPANSION_P (expanded)
15591 || (TREE_CODE (expanded) == TREE_VEC
15592 && pack_expansion_args_count (expanded)))
15595 if (PACK_EXPANSION_P (expanded))
15596 /* OK. */;
15597 else if (TREE_VEC_LENGTH (expanded) == 1)
15598 expanded = TREE_VEC_ELT (expanded, 0);
15599 else
15600 expanded = make_argument_pack (expanded);
15602 if (TYPE_P (expanded))
15603 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15604 false,
15605 complain & tf_error);
15606 else
15607 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15608 complain & tf_error);
15610 else
15611 return build_int_cst (size_type_node, len);
15613 if (SIZEOF_EXPR_TYPE_P (t))
15615 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15616 args, complain, in_decl);
15617 r = build1 (NOP_EXPR, r, error_mark_node);
15618 r = build1 (SIZEOF_EXPR,
15619 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15620 SIZEOF_EXPR_TYPE_P (r) = 1;
15621 return r;
15623 /* Fall through */
15625 case INDIRECT_REF:
15626 case NEGATE_EXPR:
15627 case TRUTH_NOT_EXPR:
15628 case BIT_NOT_EXPR:
15629 case ADDR_EXPR:
15630 case UNARY_PLUS_EXPR: /* Unary + */
15631 case ALIGNOF_EXPR:
15632 case AT_ENCODE_EXPR:
15633 case ARROW_EXPR:
15634 case THROW_EXPR:
15635 case TYPEID_EXPR:
15636 case REALPART_EXPR:
15637 case IMAGPART_EXPR:
15638 case PAREN_EXPR:
15640 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15641 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15642 r = build1 (code, type, op0);
15643 if (code == ALIGNOF_EXPR)
15644 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15645 return r;
15648 case COMPONENT_REF:
15650 tree object;
15651 tree name;
15653 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15654 name = TREE_OPERAND (t, 1);
15655 if (TREE_CODE (name) == BIT_NOT_EXPR)
15657 name = tsubst_copy (TREE_OPERAND (name, 0), args,
15658 complain, in_decl);
15659 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15661 else if (TREE_CODE (name) == SCOPE_REF
15662 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15664 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15665 complain, in_decl);
15666 name = TREE_OPERAND (name, 1);
15667 name = tsubst_copy (TREE_OPERAND (name, 0), args,
15668 complain, in_decl);
15669 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15670 name = build_qualified_name (/*type=*/NULL_TREE,
15671 base, name,
15672 /*template_p=*/false);
15674 else if (BASELINK_P (name))
15675 name = tsubst_baselink (name,
15676 non_reference (TREE_TYPE (object)),
15677 args, complain,
15678 in_decl);
15679 else
15680 name = tsubst_copy (name, args, complain, in_decl);
15681 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15684 case PLUS_EXPR:
15685 case MINUS_EXPR:
15686 case MULT_EXPR:
15687 case TRUNC_DIV_EXPR:
15688 case CEIL_DIV_EXPR:
15689 case FLOOR_DIV_EXPR:
15690 case ROUND_DIV_EXPR:
15691 case EXACT_DIV_EXPR:
15692 case BIT_AND_EXPR:
15693 case BIT_IOR_EXPR:
15694 case BIT_XOR_EXPR:
15695 case TRUNC_MOD_EXPR:
15696 case FLOOR_MOD_EXPR:
15697 case TRUTH_ANDIF_EXPR:
15698 case TRUTH_ORIF_EXPR:
15699 case TRUTH_AND_EXPR:
15700 case TRUTH_OR_EXPR:
15701 case RSHIFT_EXPR:
15702 case LSHIFT_EXPR:
15703 case RROTATE_EXPR:
15704 case LROTATE_EXPR:
15705 case EQ_EXPR:
15706 case NE_EXPR:
15707 case MAX_EXPR:
15708 case MIN_EXPR:
15709 case LE_EXPR:
15710 case GE_EXPR:
15711 case LT_EXPR:
15712 case GT_EXPR:
15713 case COMPOUND_EXPR:
15714 case DOTSTAR_EXPR:
15715 case MEMBER_REF:
15716 case PREDECREMENT_EXPR:
15717 case PREINCREMENT_EXPR:
15718 case POSTDECREMENT_EXPR:
15719 case POSTINCREMENT_EXPR:
15721 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15722 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15723 return build_nt (code, op0, op1);
15726 case SCOPE_REF:
15728 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15729 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15730 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15731 QUALIFIED_NAME_IS_TEMPLATE (t));
15734 case ARRAY_REF:
15736 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15737 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15738 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15741 case CALL_EXPR:
15743 int n = VL_EXP_OPERAND_LENGTH (t);
15744 tree result = build_vl_exp (CALL_EXPR, n);
15745 int i;
15746 for (i = 0; i < n; i++)
15747 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15748 complain, in_decl);
15749 return result;
15752 case COND_EXPR:
15753 case MODOP_EXPR:
15754 case PSEUDO_DTOR_EXPR:
15755 case VEC_PERM_EXPR:
15757 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15758 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15759 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15760 r = build_nt (code, op0, op1, op2);
15761 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15762 return r;
15765 case NEW_EXPR:
15767 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15768 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15769 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15770 r = build_nt (code, op0, op1, op2);
15771 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15772 return r;
15775 case DELETE_EXPR:
15777 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15778 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15779 r = build_nt (code, op0, op1);
15780 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15781 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15782 return r;
15785 case TEMPLATE_ID_EXPR:
15787 /* Substituted template arguments */
15788 tree fn = TREE_OPERAND (t, 0);
15789 tree targs = TREE_OPERAND (t, 1);
15791 fn = tsubst_copy (fn, args, complain, in_decl);
15792 if (targs)
15793 targs = tsubst_template_args (targs, args, complain, in_decl);
15795 return lookup_template_function (fn, targs);
15798 case TREE_LIST:
15800 tree purpose, value, chain;
15802 if (t == void_list_node)
15803 return t;
15805 purpose = TREE_PURPOSE (t);
15806 if (purpose)
15807 purpose = tsubst_copy (purpose, args, complain, in_decl);
15808 value = TREE_VALUE (t);
15809 if (value)
15810 value = tsubst_copy (value, args, complain, in_decl);
15811 chain = TREE_CHAIN (t);
15812 if (chain && chain != void_type_node)
15813 chain = tsubst_copy (chain, args, complain, in_decl);
15814 if (purpose == TREE_PURPOSE (t)
15815 && value == TREE_VALUE (t)
15816 && chain == TREE_CHAIN (t))
15817 return t;
15818 return tree_cons (purpose, value, chain);
15821 case RECORD_TYPE:
15822 case UNION_TYPE:
15823 case ENUMERAL_TYPE:
15824 case INTEGER_TYPE:
15825 case TEMPLATE_TYPE_PARM:
15826 case TEMPLATE_TEMPLATE_PARM:
15827 case BOUND_TEMPLATE_TEMPLATE_PARM:
15828 case TEMPLATE_PARM_INDEX:
15829 case POINTER_TYPE:
15830 case REFERENCE_TYPE:
15831 case OFFSET_TYPE:
15832 case FUNCTION_TYPE:
15833 case METHOD_TYPE:
15834 case ARRAY_TYPE:
15835 case TYPENAME_TYPE:
15836 case UNBOUND_CLASS_TEMPLATE:
15837 case TYPEOF_TYPE:
15838 case DECLTYPE_TYPE:
15839 case TYPE_DECL:
15840 return tsubst (t, args, complain, in_decl);
15842 case USING_DECL:
15843 t = DECL_NAME (t);
15844 /* Fall through. */
15845 case IDENTIFIER_NODE:
15846 if (IDENTIFIER_CONV_OP_P (t))
15848 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15849 return make_conv_op_name (new_type);
15851 else
15852 return t;
15854 case CONSTRUCTOR:
15855 /* This is handled by tsubst_copy_and_build. */
15856 gcc_unreachable ();
15858 case VA_ARG_EXPR:
15860 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15861 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15862 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15865 case CLEANUP_POINT_EXPR:
15866 /* We shouldn't have built any of these during initial template
15867 generation. Instead, they should be built during instantiation
15868 in response to the saved STMT_IS_FULL_EXPR_P setting. */
15869 gcc_unreachable ();
15871 case OFFSET_REF:
15873 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15874 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15875 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15876 r = build2 (code, type, op0, op1);
15877 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
15878 if (!mark_used (TREE_OPERAND (r, 1), complain)
15879 && !(complain & tf_error))
15880 return error_mark_node;
15881 return r;
15884 case EXPR_PACK_EXPANSION:
15885 error ("invalid use of pack expansion expression");
15886 return error_mark_node;
15888 case NONTYPE_ARGUMENT_PACK:
15889 error ("use %<...%> to expand argument pack");
15890 return error_mark_node;
15892 case VOID_CST:
15893 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
15894 return t;
15896 case INTEGER_CST:
15897 case REAL_CST:
15898 case STRING_CST:
15899 case COMPLEX_CST:
15901 /* Instantiate any typedefs in the type. */
15902 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15903 r = fold_convert (type, t);
15904 gcc_assert (TREE_CODE (r) == code);
15905 return r;
15908 case PTRMEM_CST:
15909 /* These can sometimes show up in a partial instantiation, but never
15910 involve template parms. */
15911 gcc_assert (!uses_template_parms (t));
15912 return t;
15914 case UNARY_LEFT_FOLD_EXPR:
15915 return tsubst_unary_left_fold (t, args, complain, in_decl);
15916 case UNARY_RIGHT_FOLD_EXPR:
15917 return tsubst_unary_right_fold (t, args, complain, in_decl);
15918 case BINARY_LEFT_FOLD_EXPR:
15919 return tsubst_binary_left_fold (t, args, complain, in_decl);
15920 case BINARY_RIGHT_FOLD_EXPR:
15921 return tsubst_binary_right_fold (t, args, complain, in_decl);
15922 case PREDICT_EXPR:
15923 return t;
15925 case DEBUG_BEGIN_STMT:
15926 /* ??? There's no point in copying it for now, but maybe some
15927 day it will contain more information, such as a pointer back
15928 to the containing function, inlined copy or so. */
15929 return t;
15931 default:
15932 /* We shouldn't get here, but keep going if !flag_checking. */
15933 if (flag_checking)
15934 gcc_unreachable ();
15935 return t;
15939 /* Helper function for tsubst_omp_clauses, used for instantiation of
15940 OMP_CLAUSE_DECL of clauses. */
15942 static tree
15943 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
15944 tree in_decl)
15946 if (decl == NULL_TREE)
15947 return NULL_TREE;
15949 /* Handle an OpenMP array section represented as a TREE_LIST (or
15950 OMP_CLAUSE_DEPEND_KIND). An OMP_CLAUSE_DEPEND (with a depend
15951 kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
15952 TREE_LIST. We can handle it exactly the same as an array section
15953 (purpose, value, and a chain), even though the nomenclature
15954 (low_bound, length, etc) is different. */
15955 if (TREE_CODE (decl) == TREE_LIST)
15957 tree low_bound
15958 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
15959 /*integral_constant_expression_p=*/false);
15960 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
15961 /*integral_constant_expression_p=*/false);
15962 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
15963 in_decl);
15964 if (TREE_PURPOSE (decl) == low_bound
15965 && TREE_VALUE (decl) == length
15966 && TREE_CHAIN (decl) == chain)
15967 return decl;
15968 tree ret = tree_cons (low_bound, length, chain);
15969 OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
15970 = OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
15971 return ret;
15973 tree ret = tsubst_expr (decl, args, complain, in_decl,
15974 /*integral_constant_expression_p=*/false);
15975 /* Undo convert_from_reference tsubst_expr could have called. */
15976 if (decl
15977 && REFERENCE_REF_P (ret)
15978 && !REFERENCE_REF_P (decl))
15979 ret = TREE_OPERAND (ret, 0);
15980 return ret;
15983 /* Like tsubst_copy, but specifically for OpenMP clauses. */
15985 static tree
15986 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
15987 tree args, tsubst_flags_t complain, tree in_decl)
15989 tree new_clauses = NULL_TREE, nc, oc;
15990 tree linear_no_step = NULL_TREE;
15992 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
15994 nc = copy_node (oc);
15995 OMP_CLAUSE_CHAIN (nc) = new_clauses;
15996 new_clauses = nc;
15998 switch (OMP_CLAUSE_CODE (nc))
16000 case OMP_CLAUSE_LASTPRIVATE:
16001 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16003 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16004 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16005 in_decl, /*integral_constant_expression_p=*/false);
16006 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16007 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16009 /* FALLTHRU */
16010 case OMP_CLAUSE_PRIVATE:
16011 case OMP_CLAUSE_SHARED:
16012 case OMP_CLAUSE_FIRSTPRIVATE:
16013 case OMP_CLAUSE_COPYIN:
16014 case OMP_CLAUSE_COPYPRIVATE:
16015 case OMP_CLAUSE_UNIFORM:
16016 case OMP_CLAUSE_DEPEND:
16017 case OMP_CLAUSE_FROM:
16018 case OMP_CLAUSE_TO:
16019 case OMP_CLAUSE_MAP:
16020 case OMP_CLAUSE_USE_DEVICE_PTR:
16021 case OMP_CLAUSE_IS_DEVICE_PTR:
16022 OMP_CLAUSE_DECL (nc)
16023 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16024 in_decl);
16025 break;
16026 case OMP_CLAUSE_TILE:
16027 case OMP_CLAUSE_IF:
16028 case OMP_CLAUSE_NUM_THREADS:
16029 case OMP_CLAUSE_SCHEDULE:
16030 case OMP_CLAUSE_COLLAPSE:
16031 case OMP_CLAUSE_FINAL:
16032 case OMP_CLAUSE_DEVICE:
16033 case OMP_CLAUSE_DIST_SCHEDULE:
16034 case OMP_CLAUSE_NUM_TEAMS:
16035 case OMP_CLAUSE_THREAD_LIMIT:
16036 case OMP_CLAUSE_SAFELEN:
16037 case OMP_CLAUSE_SIMDLEN:
16038 case OMP_CLAUSE_NUM_TASKS:
16039 case OMP_CLAUSE_GRAINSIZE:
16040 case OMP_CLAUSE_PRIORITY:
16041 case OMP_CLAUSE_ORDERED:
16042 case OMP_CLAUSE_HINT:
16043 case OMP_CLAUSE_NUM_GANGS:
16044 case OMP_CLAUSE_NUM_WORKERS:
16045 case OMP_CLAUSE_VECTOR_LENGTH:
16046 case OMP_CLAUSE_WORKER:
16047 case OMP_CLAUSE_VECTOR:
16048 case OMP_CLAUSE_ASYNC:
16049 case OMP_CLAUSE_WAIT:
16050 OMP_CLAUSE_OPERAND (nc, 0)
16051 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16052 in_decl, /*integral_constant_expression_p=*/false);
16053 break;
16054 case OMP_CLAUSE_REDUCTION:
16055 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16057 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16058 if (TREE_CODE (placeholder) == SCOPE_REF)
16060 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16061 complain, in_decl);
16062 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16063 = build_qualified_name (NULL_TREE, scope,
16064 TREE_OPERAND (placeholder, 1),
16065 false);
16067 else
16068 gcc_assert (identifier_p (placeholder));
16070 OMP_CLAUSE_DECL (nc)
16071 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16072 in_decl);
16073 break;
16074 case OMP_CLAUSE_GANG:
16075 case OMP_CLAUSE_ALIGNED:
16076 OMP_CLAUSE_DECL (nc)
16077 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16078 in_decl);
16079 OMP_CLAUSE_OPERAND (nc, 1)
16080 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16081 in_decl, /*integral_constant_expression_p=*/false);
16082 break;
16083 case OMP_CLAUSE_LINEAR:
16084 OMP_CLAUSE_DECL (nc)
16085 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16086 in_decl);
16087 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16089 gcc_assert (!linear_no_step);
16090 linear_no_step = nc;
16092 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16093 OMP_CLAUSE_LINEAR_STEP (nc)
16094 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16095 complain, in_decl);
16096 else
16097 OMP_CLAUSE_LINEAR_STEP (nc)
16098 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16099 in_decl,
16100 /*integral_constant_expression_p=*/false);
16101 break;
16102 case OMP_CLAUSE_NOWAIT:
16103 case OMP_CLAUSE_DEFAULT:
16104 case OMP_CLAUSE_UNTIED:
16105 case OMP_CLAUSE_MERGEABLE:
16106 case OMP_CLAUSE_INBRANCH:
16107 case OMP_CLAUSE_NOTINBRANCH:
16108 case OMP_CLAUSE_PROC_BIND:
16109 case OMP_CLAUSE_FOR:
16110 case OMP_CLAUSE_PARALLEL:
16111 case OMP_CLAUSE_SECTIONS:
16112 case OMP_CLAUSE_TASKGROUP:
16113 case OMP_CLAUSE_NOGROUP:
16114 case OMP_CLAUSE_THREADS:
16115 case OMP_CLAUSE_SIMD:
16116 case OMP_CLAUSE_DEFAULTMAP:
16117 case OMP_CLAUSE_INDEPENDENT:
16118 case OMP_CLAUSE_AUTO:
16119 case OMP_CLAUSE_SEQ:
16120 break;
16121 default:
16122 gcc_unreachable ();
16124 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16125 switch (OMP_CLAUSE_CODE (nc))
16127 case OMP_CLAUSE_SHARED:
16128 case OMP_CLAUSE_PRIVATE:
16129 case OMP_CLAUSE_FIRSTPRIVATE:
16130 case OMP_CLAUSE_LASTPRIVATE:
16131 case OMP_CLAUSE_COPYPRIVATE:
16132 case OMP_CLAUSE_LINEAR:
16133 case OMP_CLAUSE_REDUCTION:
16134 case OMP_CLAUSE_USE_DEVICE_PTR:
16135 case OMP_CLAUSE_IS_DEVICE_PTR:
16136 /* tsubst_expr on SCOPE_REF results in returning
16137 finish_non_static_data_member result. Undo that here. */
16138 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16139 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16140 == IDENTIFIER_NODE))
16142 tree t = OMP_CLAUSE_DECL (nc);
16143 tree v = t;
16144 while (v)
16145 switch (TREE_CODE (v))
16147 case COMPONENT_REF:
16148 case MEM_REF:
16149 case INDIRECT_REF:
16150 CASE_CONVERT:
16151 case POINTER_PLUS_EXPR:
16152 v = TREE_OPERAND (v, 0);
16153 continue;
16154 case PARM_DECL:
16155 if (DECL_CONTEXT (v) == current_function_decl
16156 && DECL_ARTIFICIAL (v)
16157 && DECL_NAME (v) == this_identifier)
16158 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16159 /* FALLTHRU */
16160 default:
16161 v = NULL_TREE;
16162 break;
16165 else if (VAR_P (OMP_CLAUSE_DECL (oc))
16166 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16167 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16168 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16169 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16171 tree decl = OMP_CLAUSE_DECL (nc);
16172 if (VAR_P (decl))
16174 retrofit_lang_decl (decl);
16175 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16178 break;
16179 default:
16180 break;
16184 new_clauses = nreverse (new_clauses);
16185 if (ort != C_ORT_OMP_DECLARE_SIMD)
16187 new_clauses = finish_omp_clauses (new_clauses, ort);
16188 if (linear_no_step)
16189 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16190 if (nc == linear_no_step)
16192 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16193 break;
16196 return new_clauses;
16199 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
16201 static tree
16202 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16203 tree in_decl)
16205 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16207 tree purpose, value, chain;
16209 if (t == NULL)
16210 return t;
16212 if (TREE_CODE (t) != TREE_LIST)
16213 return tsubst_copy_and_build (t, args, complain, in_decl,
16214 /*function_p=*/false,
16215 /*integral_constant_expression_p=*/false);
16217 if (t == void_list_node)
16218 return t;
16220 purpose = TREE_PURPOSE (t);
16221 if (purpose)
16222 purpose = RECUR (purpose);
16223 value = TREE_VALUE (t);
16224 if (value)
16226 if (TREE_CODE (value) != LABEL_DECL)
16227 value = RECUR (value);
16228 else
16230 value = lookup_label (DECL_NAME (value));
16231 gcc_assert (TREE_CODE (value) == LABEL_DECL);
16232 TREE_USED (value) = 1;
16235 chain = TREE_CHAIN (t);
16236 if (chain && chain != void_type_node)
16237 chain = RECUR (chain);
16238 return tree_cons (purpose, value, chain);
16239 #undef RECUR
16242 /* Used to temporarily communicate the list of #pragma omp parallel
16243 clauses to #pragma omp for instantiation if they are combined
16244 together. */
16246 static tree *omp_parallel_combined_clauses;
16248 /* Substitute one OMP_FOR iterator. */
16250 static void
16251 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
16252 tree initv, tree condv, tree incrv, tree *clauses,
16253 tree args, tsubst_flags_t complain, tree in_decl,
16254 bool integral_constant_expression_p)
16256 #define RECUR(NODE) \
16257 tsubst_expr ((NODE), args, complain, in_decl, \
16258 integral_constant_expression_p)
16259 tree decl, init, cond, incr;
16261 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16262 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16264 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16266 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16267 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16270 decl = TREE_OPERAND (init, 0);
16271 init = TREE_OPERAND (init, 1);
16272 tree decl_expr = NULL_TREE;
16273 if (init && TREE_CODE (init) == DECL_EXPR)
16275 /* We need to jump through some hoops to handle declarations in the
16276 init-statement, since we might need to handle auto deduction,
16277 but we need to keep control of initialization. */
16278 decl_expr = init;
16279 init = DECL_INITIAL (DECL_EXPR_DECL (init));
16280 decl = tsubst_decl (decl, args, complain);
16282 else
16284 if (TREE_CODE (decl) == SCOPE_REF)
16286 decl = RECUR (decl);
16287 if (TREE_CODE (decl) == COMPONENT_REF)
16289 tree v = decl;
16290 while (v)
16291 switch (TREE_CODE (v))
16293 case COMPONENT_REF:
16294 case MEM_REF:
16295 case INDIRECT_REF:
16296 CASE_CONVERT:
16297 case POINTER_PLUS_EXPR:
16298 v = TREE_OPERAND (v, 0);
16299 continue;
16300 case PARM_DECL:
16301 if (DECL_CONTEXT (v) == current_function_decl
16302 && DECL_ARTIFICIAL (v)
16303 && DECL_NAME (v) == this_identifier)
16305 decl = TREE_OPERAND (decl, 1);
16306 decl = omp_privatize_field (decl, false);
16308 /* FALLTHRU */
16309 default:
16310 v = NULL_TREE;
16311 break;
16315 else
16316 decl = RECUR (decl);
16318 init = RECUR (init);
16320 tree auto_node = type_uses_auto (TREE_TYPE (decl));
16321 if (auto_node && init)
16322 TREE_TYPE (decl)
16323 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16325 gcc_assert (!type_dependent_expression_p (decl));
16327 if (!CLASS_TYPE_P (TREE_TYPE (decl)))
16329 if (decl_expr)
16331 /* Declare the variable, but don't let that initialize it. */
16332 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16333 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16334 RECUR (decl_expr);
16335 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16338 cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16339 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16340 if (TREE_CODE (incr) == MODIFY_EXPR)
16342 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16343 tree rhs = RECUR (TREE_OPERAND (incr, 1));
16344 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16345 NOP_EXPR, rhs, complain);
16347 else
16348 incr = RECUR (incr);
16349 TREE_VEC_ELT (declv, i) = decl;
16350 TREE_VEC_ELT (initv, i) = init;
16351 TREE_VEC_ELT (condv, i) = cond;
16352 TREE_VEC_ELT (incrv, i) = incr;
16353 return;
16356 if (decl_expr)
16358 /* Declare and initialize the variable. */
16359 RECUR (decl_expr);
16360 init = NULL_TREE;
16362 else if (init)
16364 tree *pc;
16365 int j;
16366 for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
16368 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16370 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16371 && OMP_CLAUSE_DECL (*pc) == decl)
16372 break;
16373 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16374 && OMP_CLAUSE_DECL (*pc) == decl)
16376 if (j)
16377 break;
16378 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
16379 tree c = *pc;
16380 *pc = OMP_CLAUSE_CHAIN (c);
16381 OMP_CLAUSE_CHAIN (c) = *clauses;
16382 *clauses = c;
16384 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16385 && OMP_CLAUSE_DECL (*pc) == decl)
16387 error ("iteration variable %qD should not be firstprivate",
16388 decl);
16389 *pc = OMP_CLAUSE_CHAIN (*pc);
16391 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16392 && OMP_CLAUSE_DECL (*pc) == decl)
16394 error ("iteration variable %qD should not be reduction",
16395 decl);
16396 *pc = OMP_CLAUSE_CHAIN (*pc);
16398 else
16399 pc = &OMP_CLAUSE_CHAIN (*pc);
16401 if (*pc)
16402 break;
16404 if (*pc == NULL_TREE)
16406 tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16407 OMP_CLAUSE_DECL (c) = decl;
16408 c = finish_omp_clauses (c, C_ORT_OMP);
16409 if (c)
16411 OMP_CLAUSE_CHAIN (c) = *clauses;
16412 *clauses = c;
16416 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16417 if (COMPARISON_CLASS_P (cond))
16419 tree op0 = RECUR (TREE_OPERAND (cond, 0));
16420 tree op1 = RECUR (TREE_OPERAND (cond, 1));
16421 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16423 else
16424 cond = RECUR (cond);
16425 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16426 switch (TREE_CODE (incr))
16428 case PREINCREMENT_EXPR:
16429 case PREDECREMENT_EXPR:
16430 case POSTINCREMENT_EXPR:
16431 case POSTDECREMENT_EXPR:
16432 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16433 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16434 break;
16435 case MODIFY_EXPR:
16436 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16437 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16439 tree rhs = TREE_OPERAND (incr, 1);
16440 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16441 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16442 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16443 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16444 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16445 rhs0, rhs1));
16447 else
16448 incr = RECUR (incr);
16449 break;
16450 case MODOP_EXPR:
16451 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16452 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16454 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16455 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16456 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16457 TREE_TYPE (decl), lhs,
16458 RECUR (TREE_OPERAND (incr, 2))));
16460 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16461 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16462 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16464 tree rhs = TREE_OPERAND (incr, 2);
16465 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16466 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16467 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16468 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16469 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16470 rhs0, rhs1));
16472 else
16473 incr = RECUR (incr);
16474 break;
16475 default:
16476 incr = RECUR (incr);
16477 break;
16480 TREE_VEC_ELT (declv, i) = decl;
16481 TREE_VEC_ELT (initv, i) = init;
16482 TREE_VEC_ELT (condv, i) = cond;
16483 TREE_VEC_ELT (incrv, i) = incr;
16484 #undef RECUR
16487 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16488 of OMP_TARGET's body. */
16490 static tree
16491 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16493 *walk_subtrees = 0;
16494 switch (TREE_CODE (*tp))
16496 case OMP_TEAMS:
16497 return *tp;
16498 case BIND_EXPR:
16499 case STATEMENT_LIST:
16500 *walk_subtrees = 1;
16501 break;
16502 default:
16503 break;
16505 return NULL_TREE;
16508 /* Helper function for tsubst_expr. For decomposition declaration
16509 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16510 also the corresponding decls representing the identifiers
16511 of the decomposition declaration. Return DECL if successful
16512 or error_mark_node otherwise, set *FIRST to the first decl
16513 in the list chained through DECL_CHAIN and *CNT to the number
16514 of such decls. */
16516 static tree
16517 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16518 tsubst_flags_t complain, tree in_decl, tree *first,
16519 unsigned int *cnt)
16521 tree decl2, decl3, prev = decl;
16522 *cnt = 0;
16523 gcc_assert (DECL_NAME (decl) == NULL_TREE);
16524 for (decl2 = DECL_CHAIN (pattern_decl);
16525 decl2
16526 && VAR_P (decl2)
16527 && DECL_DECOMPOSITION_P (decl2)
16528 && DECL_NAME (decl2);
16529 decl2 = DECL_CHAIN (decl2))
16531 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16533 gcc_assert (errorcount);
16534 return error_mark_node;
16536 (*cnt)++;
16537 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16538 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16539 tree v = DECL_VALUE_EXPR (decl2);
16540 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16541 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16542 decl3 = tsubst (decl2, args, complain, in_decl);
16543 SET_DECL_VALUE_EXPR (decl2, v);
16544 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16545 if (VAR_P (decl3))
16546 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16547 else
16549 gcc_assert (errorcount);
16550 decl = error_mark_node;
16551 continue;
16553 maybe_push_decl (decl3);
16554 if (error_operand_p (decl3))
16555 decl = error_mark_node;
16556 else if (decl != error_mark_node
16557 && DECL_CHAIN (decl3) != prev
16558 && decl != prev)
16560 gcc_assert (errorcount);
16561 decl = error_mark_node;
16563 else
16564 prev = decl3;
16566 *first = prev;
16567 return decl;
16570 /* Like tsubst_copy for expressions, etc. but also does semantic
16571 processing. */
16573 tree
16574 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16575 bool integral_constant_expression_p)
16577 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16578 #define RECUR(NODE) \
16579 tsubst_expr ((NODE), args, complain, in_decl, \
16580 integral_constant_expression_p)
16582 tree stmt, tmp;
16583 tree r;
16584 location_t loc;
16586 if (t == NULL_TREE || t == error_mark_node)
16587 return t;
16589 loc = input_location;
16590 if (EXPR_HAS_LOCATION (t))
16591 input_location = EXPR_LOCATION (t);
16592 if (STATEMENT_CODE_P (TREE_CODE (t)))
16593 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16595 switch (TREE_CODE (t))
16597 case STATEMENT_LIST:
16599 tree_stmt_iterator i;
16600 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16601 RECUR (tsi_stmt (i));
16602 break;
16605 case CTOR_INITIALIZER:
16606 finish_mem_initializers (tsubst_initializer_list
16607 (TREE_OPERAND (t, 0), args));
16608 break;
16610 case RETURN_EXPR:
16611 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16612 break;
16614 case EXPR_STMT:
16615 tmp = RECUR (EXPR_STMT_EXPR (t));
16616 if (EXPR_STMT_STMT_EXPR_RESULT (t))
16617 finish_stmt_expr_expr (tmp, cur_stmt_expr);
16618 else
16619 finish_expr_stmt (tmp);
16620 break;
16622 case USING_STMT:
16623 finish_local_using_directive (USING_STMT_NAMESPACE (t),
16624 /*attribs=*/NULL_TREE);
16625 break;
16627 case DECL_EXPR:
16629 tree decl, pattern_decl;
16630 tree init;
16632 pattern_decl = decl = DECL_EXPR_DECL (t);
16633 if (TREE_CODE (decl) == LABEL_DECL)
16634 finish_label_decl (DECL_NAME (decl));
16635 else if (TREE_CODE (decl) == USING_DECL)
16637 tree scope = USING_DECL_SCOPE (decl);
16638 tree name = DECL_NAME (decl);
16640 scope = tsubst (scope, args, complain, in_decl);
16641 decl = lookup_qualified_name (scope, name,
16642 /*is_type_p=*/false,
16643 /*complain=*/false);
16644 if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16645 qualified_name_lookup_error (scope, name, decl, input_location);
16646 else
16647 finish_local_using_decl (decl, scope, name);
16649 else if (is_capture_proxy (decl)
16650 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16652 /* We're in tsubst_lambda_expr, we've already inserted a new
16653 capture proxy, so look it up and register it. */
16654 tree inst;
16655 if (DECL_PACK_P (decl))
16657 inst = (retrieve_local_specialization
16658 (DECL_CAPTURED_VARIABLE (decl)));
16659 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16661 else
16663 inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16664 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16665 gcc_assert (inst != decl && is_capture_proxy (inst));
16667 register_local_specialization (inst, decl);
16668 break;
16670 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16671 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16672 /* Don't copy the old closure; we'll create a new one in
16673 tsubst_lambda_expr. */
16674 break;
16675 else
16677 init = DECL_INITIAL (decl);
16678 decl = tsubst (decl, args, complain, in_decl);
16679 if (decl != error_mark_node)
16681 /* By marking the declaration as instantiated, we avoid
16682 trying to instantiate it. Since instantiate_decl can't
16683 handle local variables, and since we've already done
16684 all that needs to be done, that's the right thing to
16685 do. */
16686 if (VAR_P (decl))
16687 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16688 if (VAR_P (decl)
16689 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16690 /* Anonymous aggregates are a special case. */
16691 finish_anon_union (decl);
16692 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16694 DECL_CONTEXT (decl) = current_function_decl;
16695 if (DECL_NAME (decl) == this_identifier)
16697 tree lam = DECL_CONTEXT (current_function_decl);
16698 lam = CLASSTYPE_LAMBDA_EXPR (lam);
16699 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16701 insert_capture_proxy (decl);
16703 else if (DECL_IMPLICIT_TYPEDEF_P (t))
16704 /* We already did a pushtag. */;
16705 else if (TREE_CODE (decl) == FUNCTION_DECL
16706 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16707 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16709 DECL_CONTEXT (decl) = NULL_TREE;
16710 pushdecl (decl);
16711 DECL_CONTEXT (decl) = current_function_decl;
16712 cp_check_omp_declare_reduction (decl);
16714 else
16716 int const_init = false;
16717 maybe_push_decl (decl);
16718 if (VAR_P (decl)
16719 && DECL_PRETTY_FUNCTION_P (decl))
16721 /* For __PRETTY_FUNCTION__ we have to adjust the
16722 initializer. */
16723 const char *const name
16724 = cxx_printable_name (current_function_decl, 2);
16725 init = cp_fname_init (name, &TREE_TYPE (decl));
16727 else
16728 init = tsubst_init (init, decl, args, complain, in_decl);
16730 if (VAR_P (decl))
16731 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16732 (pattern_decl));
16733 if (VAR_P (decl)
16734 && DECL_DECOMPOSITION_P (decl)
16735 && TREE_TYPE (pattern_decl) != error_mark_node)
16737 unsigned int cnt;
16738 tree first;
16739 tree ndecl
16740 = tsubst_decomp_names (decl, pattern_decl, args,
16741 complain, in_decl, &first, &cnt);
16742 if (ndecl != error_mark_node)
16743 cp_maybe_mangle_decomp (ndecl, first, cnt);
16744 cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16745 if (ndecl != error_mark_node)
16746 cp_finish_decomp (ndecl, first, cnt);
16748 else
16749 cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16754 break;
16757 case FOR_STMT:
16758 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16759 RECUR (FOR_INIT_STMT (t));
16760 finish_init_stmt (stmt);
16761 tmp = RECUR (FOR_COND (t));
16762 finish_for_cond (tmp, stmt, false, 0);
16763 tmp = RECUR (FOR_EXPR (t));
16764 finish_for_expr (tmp, stmt);
16766 bool prev = note_iteration_stmt_body_start ();
16767 RECUR (FOR_BODY (t));
16768 note_iteration_stmt_body_end (prev);
16770 finish_for_stmt (stmt);
16771 break;
16773 case RANGE_FOR_STMT:
16775 /* Construct another range_for, if this is not a final
16776 substitution (for inside inside a generic lambda of a
16777 template). Otherwise convert to a regular for. */
16778 tree decl, expr;
16779 stmt = (processing_template_decl
16780 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16781 : begin_for_stmt (NULL_TREE, NULL_TREE));
16782 decl = RANGE_FOR_DECL (t);
16783 decl = tsubst (decl, args, complain, in_decl);
16784 maybe_push_decl (decl);
16785 expr = RECUR (RANGE_FOR_EXPR (t));
16787 tree decomp_first = NULL_TREE;
16788 unsigned decomp_cnt = 0;
16789 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16790 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16791 complain, in_decl,
16792 &decomp_first, &decomp_cnt);
16794 if (processing_template_decl)
16796 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16797 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16798 finish_range_for_decl (stmt, decl, expr);
16800 else
16802 unsigned short unroll = (RANGE_FOR_UNROLL (t)
16803 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16804 stmt = cp_convert_range_for (stmt, decl, expr,
16805 decomp_first, decomp_cnt,
16806 RANGE_FOR_IVDEP (t), unroll);
16809 bool prev = note_iteration_stmt_body_start ();
16810 RECUR (RANGE_FOR_BODY (t));
16811 note_iteration_stmt_body_end (prev);
16812 finish_for_stmt (stmt);
16814 break;
16816 case WHILE_STMT:
16817 stmt = begin_while_stmt ();
16818 tmp = RECUR (WHILE_COND (t));
16819 finish_while_stmt_cond (tmp, stmt, false, 0);
16821 bool prev = note_iteration_stmt_body_start ();
16822 RECUR (WHILE_BODY (t));
16823 note_iteration_stmt_body_end (prev);
16825 finish_while_stmt (stmt);
16826 break;
16828 case DO_STMT:
16829 stmt = begin_do_stmt ();
16831 bool prev = note_iteration_stmt_body_start ();
16832 RECUR (DO_BODY (t));
16833 note_iteration_stmt_body_end (prev);
16835 finish_do_body (stmt);
16836 tmp = RECUR (DO_COND (t));
16837 finish_do_stmt (tmp, stmt, false, 0);
16838 break;
16840 case IF_STMT:
16841 stmt = begin_if_stmt ();
16842 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16843 if (IF_STMT_CONSTEXPR_P (t))
16844 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
16845 tmp = RECUR (IF_COND (t));
16846 tmp = finish_if_stmt_cond (tmp, stmt);
16847 if (IF_STMT_CONSTEXPR_P (t)
16848 && instantiation_dependent_expression_p (tmp))
16850 /* We're partially instantiating a generic lambda, but the condition
16851 of the constexpr if is still dependent. Don't substitute into the
16852 branches now, just remember the template arguments. */
16853 do_poplevel (IF_SCOPE (stmt));
16854 IF_COND (stmt) = IF_COND (t);
16855 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
16856 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
16857 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
16858 add_stmt (stmt);
16859 break;
16861 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
16862 /* Don't instantiate the THEN_CLAUSE. */;
16863 else
16865 bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
16866 if (inhibit)
16867 ++c_inhibit_evaluation_warnings;
16868 RECUR (THEN_CLAUSE (t));
16869 if (inhibit)
16870 --c_inhibit_evaluation_warnings;
16872 finish_then_clause (stmt);
16874 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
16875 /* Don't instantiate the ELSE_CLAUSE. */;
16876 else if (ELSE_CLAUSE (t))
16878 bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
16879 begin_else_clause (stmt);
16880 if (inhibit)
16881 ++c_inhibit_evaluation_warnings;
16882 RECUR (ELSE_CLAUSE (t));
16883 if (inhibit)
16884 --c_inhibit_evaluation_warnings;
16885 finish_else_clause (stmt);
16888 finish_if_stmt (stmt);
16889 break;
16891 case BIND_EXPR:
16892 if (BIND_EXPR_BODY_BLOCK (t))
16893 stmt = begin_function_body ();
16894 else
16895 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
16896 ? BCS_TRY_BLOCK : 0);
16898 RECUR (BIND_EXPR_BODY (t));
16900 if (BIND_EXPR_BODY_BLOCK (t))
16901 finish_function_body (stmt);
16902 else
16903 finish_compound_stmt (stmt);
16904 break;
16906 case BREAK_STMT:
16907 finish_break_stmt ();
16908 break;
16910 case CONTINUE_STMT:
16911 finish_continue_stmt ();
16912 break;
16914 case SWITCH_STMT:
16915 stmt = begin_switch_stmt ();
16916 tmp = RECUR (SWITCH_STMT_COND (t));
16917 finish_switch_cond (tmp, stmt);
16918 RECUR (SWITCH_STMT_BODY (t));
16919 finish_switch_stmt (stmt);
16920 break;
16922 case CASE_LABEL_EXPR:
16924 tree low = RECUR (CASE_LOW (t));
16925 tree high = RECUR (CASE_HIGH (t));
16926 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
16927 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
16928 FALLTHROUGH_LABEL_P (CASE_LABEL (l))
16929 = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
16931 break;
16933 case LABEL_EXPR:
16935 tree decl = LABEL_EXPR_LABEL (t);
16936 tree label;
16938 label = finish_label_stmt (DECL_NAME (decl));
16939 if (TREE_CODE (label) == LABEL_DECL)
16940 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
16941 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
16942 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
16944 break;
16946 case GOTO_EXPR:
16947 tmp = GOTO_DESTINATION (t);
16948 if (TREE_CODE (tmp) != LABEL_DECL)
16949 /* Computed goto's must be tsubst'd into. On the other hand,
16950 non-computed gotos must not be; the identifier in question
16951 will have no binding. */
16952 tmp = RECUR (tmp);
16953 else
16954 tmp = DECL_NAME (tmp);
16955 finish_goto_stmt (tmp);
16956 break;
16958 case ASM_EXPR:
16960 tree string = RECUR (ASM_STRING (t));
16961 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
16962 complain, in_decl);
16963 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
16964 complain, in_decl);
16965 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
16966 complain, in_decl);
16967 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
16968 complain, in_decl);
16969 tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
16970 clobbers, labels);
16971 tree asm_expr = tmp;
16972 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
16973 asm_expr = TREE_OPERAND (asm_expr, 0);
16974 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
16976 break;
16978 case TRY_BLOCK:
16979 if (CLEANUP_P (t))
16981 stmt = begin_try_block ();
16982 RECUR (TRY_STMTS (t));
16983 finish_cleanup_try_block (stmt);
16984 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
16986 else
16988 tree compound_stmt = NULL_TREE;
16990 if (FN_TRY_BLOCK_P (t))
16991 stmt = begin_function_try_block (&compound_stmt);
16992 else
16993 stmt = begin_try_block ();
16995 RECUR (TRY_STMTS (t));
16997 if (FN_TRY_BLOCK_P (t))
16998 finish_function_try_block (stmt);
16999 else
17000 finish_try_block (stmt);
17002 RECUR (TRY_HANDLERS (t));
17003 if (FN_TRY_BLOCK_P (t))
17004 finish_function_handler_sequence (stmt, compound_stmt);
17005 else
17006 finish_handler_sequence (stmt);
17008 break;
17010 case HANDLER:
17012 tree decl = HANDLER_PARMS (t);
17014 if (decl)
17016 decl = tsubst (decl, args, complain, in_decl);
17017 /* Prevent instantiate_decl from trying to instantiate
17018 this variable. We've already done all that needs to be
17019 done. */
17020 if (decl != error_mark_node)
17021 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17023 stmt = begin_handler ();
17024 finish_handler_parms (decl, stmt);
17025 RECUR (HANDLER_BODY (t));
17026 finish_handler (stmt);
17028 break;
17030 case TAG_DEFN:
17031 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17032 if (CLASS_TYPE_P (tmp))
17034 /* Local classes are not independent templates; they are
17035 instantiated along with their containing function. And this
17036 way we don't have to deal with pushing out of one local class
17037 to instantiate a member of another local class. */
17038 /* Closures are handled by the LAMBDA_EXPR. */
17039 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17040 complete_type (tmp);
17041 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17042 if ((VAR_P (fld)
17043 || (TREE_CODE (fld) == FUNCTION_DECL
17044 && !DECL_ARTIFICIAL (fld)))
17045 && DECL_TEMPLATE_INSTANTIATION (fld))
17046 instantiate_decl (fld, /*defer_ok=*/false,
17047 /*expl_inst_class=*/false);
17049 break;
17051 case STATIC_ASSERT:
17053 tree condition;
17055 ++c_inhibit_evaluation_warnings;
17056 condition =
17057 tsubst_expr (STATIC_ASSERT_CONDITION (t),
17058 args,
17059 complain, in_decl,
17060 /*integral_constant_expression_p=*/true);
17061 --c_inhibit_evaluation_warnings;
17063 finish_static_assert (condition,
17064 STATIC_ASSERT_MESSAGE (t),
17065 STATIC_ASSERT_SOURCE_LOCATION (t),
17066 /*member_p=*/false);
17068 break;
17070 case OACC_KERNELS:
17071 case OACC_PARALLEL:
17072 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17073 in_decl);
17074 stmt = begin_omp_parallel ();
17075 RECUR (OMP_BODY (t));
17076 finish_omp_construct (TREE_CODE (t), stmt, tmp);
17077 break;
17079 case OMP_PARALLEL:
17080 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17081 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17082 complain, in_decl);
17083 if (OMP_PARALLEL_COMBINED (t))
17084 omp_parallel_combined_clauses = &tmp;
17085 stmt = begin_omp_parallel ();
17086 RECUR (OMP_PARALLEL_BODY (t));
17087 gcc_assert (omp_parallel_combined_clauses == NULL);
17088 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17089 = OMP_PARALLEL_COMBINED (t);
17090 pop_omp_privatization_clauses (r);
17091 break;
17093 case OMP_TASK:
17094 r = push_omp_privatization_clauses (false);
17095 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17096 complain, in_decl);
17097 stmt = begin_omp_task ();
17098 RECUR (OMP_TASK_BODY (t));
17099 finish_omp_task (tmp, stmt);
17100 pop_omp_privatization_clauses (r);
17101 break;
17103 case OMP_FOR:
17104 case OMP_SIMD:
17105 case OMP_DISTRIBUTE:
17106 case OMP_TASKLOOP:
17107 case OACC_LOOP:
17109 tree clauses, body, pre_body;
17110 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17111 tree orig_declv = NULL_TREE;
17112 tree incrv = NULL_TREE;
17113 enum c_omp_region_type ort = C_ORT_OMP;
17114 int i;
17116 if (TREE_CODE (t) == OACC_LOOP)
17117 ort = C_ORT_ACC;
17119 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17120 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17121 in_decl);
17122 if (OMP_FOR_INIT (t) != NULL_TREE)
17124 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17125 if (OMP_FOR_ORIG_DECLS (t))
17126 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17127 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17128 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17129 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17132 stmt = begin_omp_structured_block ();
17134 pre_body = push_stmt_list ();
17135 RECUR (OMP_FOR_PRE_BODY (t));
17136 pre_body = pop_stmt_list (pre_body);
17138 if (OMP_FOR_INIT (t) != NULL_TREE)
17139 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17140 tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
17141 incrv, &clauses, args, complain, in_decl,
17142 integral_constant_expression_p);
17143 omp_parallel_combined_clauses = NULL;
17145 body = push_stmt_list ();
17146 RECUR (OMP_FOR_BODY (t));
17147 body = pop_stmt_list (body);
17149 if (OMP_FOR_INIT (t) != NULL_TREE)
17150 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17151 orig_declv, initv, condv, incrv, body, pre_body,
17152 NULL, clauses);
17153 else
17155 t = make_node (TREE_CODE (t));
17156 TREE_TYPE (t) = void_type_node;
17157 OMP_FOR_BODY (t) = body;
17158 OMP_FOR_PRE_BODY (t) = pre_body;
17159 OMP_FOR_CLAUSES (t) = clauses;
17160 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17161 add_stmt (t);
17164 add_stmt (finish_omp_structured_block (stmt));
17165 pop_omp_privatization_clauses (r);
17167 break;
17169 case OMP_SECTIONS:
17170 omp_parallel_combined_clauses = NULL;
17171 /* FALLTHRU */
17172 case OMP_SINGLE:
17173 case OMP_TEAMS:
17174 case OMP_CRITICAL:
17175 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17176 && OMP_TEAMS_COMBINED (t));
17177 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17178 in_decl);
17179 stmt = push_stmt_list ();
17180 RECUR (OMP_BODY (t));
17181 stmt = pop_stmt_list (stmt);
17183 t = copy_node (t);
17184 OMP_BODY (t) = stmt;
17185 OMP_CLAUSES (t) = tmp;
17186 add_stmt (t);
17187 pop_omp_privatization_clauses (r);
17188 break;
17190 case OACC_DATA:
17191 case OMP_TARGET_DATA:
17192 case OMP_TARGET:
17193 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17194 ? C_ORT_ACC : C_ORT_OMP, args, complain,
17195 in_decl);
17196 keep_next_level (true);
17197 stmt = begin_omp_structured_block ();
17199 RECUR (OMP_BODY (t));
17200 stmt = finish_omp_structured_block (stmt);
17202 t = copy_node (t);
17203 OMP_BODY (t) = stmt;
17204 OMP_CLAUSES (t) = tmp;
17205 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17207 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17208 if (teams)
17210 /* For combined target teams, ensure the num_teams and
17211 thread_limit clause expressions are evaluated on the host,
17212 before entering the target construct. */
17213 tree c;
17214 for (c = OMP_TEAMS_CLAUSES (teams);
17215 c; c = OMP_CLAUSE_CHAIN (c))
17216 if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17217 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17218 && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17220 tree expr = OMP_CLAUSE_OPERAND (c, 0);
17221 expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17222 if (expr == error_mark_node)
17223 continue;
17224 tmp = TARGET_EXPR_SLOT (expr);
17225 add_stmt (expr);
17226 OMP_CLAUSE_OPERAND (c, 0) = expr;
17227 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17228 OMP_CLAUSE_FIRSTPRIVATE);
17229 OMP_CLAUSE_DECL (tc) = tmp;
17230 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17231 OMP_TARGET_CLAUSES (t) = tc;
17235 add_stmt (t);
17236 break;
17238 case OACC_DECLARE:
17239 t = copy_node (t);
17240 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17241 complain, in_decl);
17242 OACC_DECLARE_CLAUSES (t) = tmp;
17243 add_stmt (t);
17244 break;
17246 case OMP_TARGET_UPDATE:
17247 case OMP_TARGET_ENTER_DATA:
17248 case OMP_TARGET_EXIT_DATA:
17249 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17250 complain, in_decl);
17251 t = copy_node (t);
17252 OMP_STANDALONE_CLAUSES (t) = tmp;
17253 add_stmt (t);
17254 break;
17256 case OACC_ENTER_DATA:
17257 case OACC_EXIT_DATA:
17258 case OACC_UPDATE:
17259 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17260 complain, in_decl);
17261 t = copy_node (t);
17262 OMP_STANDALONE_CLAUSES (t) = tmp;
17263 add_stmt (t);
17264 break;
17266 case OMP_ORDERED:
17267 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17268 complain, in_decl);
17269 stmt = push_stmt_list ();
17270 RECUR (OMP_BODY (t));
17271 stmt = pop_stmt_list (stmt);
17273 t = copy_node (t);
17274 OMP_BODY (t) = stmt;
17275 OMP_ORDERED_CLAUSES (t) = tmp;
17276 add_stmt (t);
17277 break;
17279 case OMP_SECTION:
17280 case OMP_MASTER:
17281 case OMP_TASKGROUP:
17282 stmt = push_stmt_list ();
17283 RECUR (OMP_BODY (t));
17284 stmt = pop_stmt_list (stmt);
17286 t = copy_node (t);
17287 OMP_BODY (t) = stmt;
17288 add_stmt (t);
17289 break;
17291 case OMP_ATOMIC:
17292 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17293 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17295 tree op1 = TREE_OPERAND (t, 1);
17296 tree rhs1 = NULL_TREE;
17297 tree lhs, rhs;
17298 if (TREE_CODE (op1) == COMPOUND_EXPR)
17300 rhs1 = RECUR (TREE_OPERAND (op1, 0));
17301 op1 = TREE_OPERAND (op1, 1);
17303 lhs = RECUR (TREE_OPERAND (op1, 0));
17304 rhs = RECUR (TREE_OPERAND (op1, 1));
17305 finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
17306 NULL_TREE, NULL_TREE, rhs1,
17307 OMP_ATOMIC_SEQ_CST (t));
17309 else
17311 tree op1 = TREE_OPERAND (t, 1);
17312 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17313 tree rhs1 = NULL_TREE;
17314 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17315 enum tree_code opcode = NOP_EXPR;
17316 if (code == OMP_ATOMIC_READ)
17318 v = RECUR (TREE_OPERAND (op1, 0));
17319 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17321 else if (code == OMP_ATOMIC_CAPTURE_OLD
17322 || code == OMP_ATOMIC_CAPTURE_NEW)
17324 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17325 v = RECUR (TREE_OPERAND (op1, 0));
17326 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17327 if (TREE_CODE (op11) == COMPOUND_EXPR)
17329 rhs1 = RECUR (TREE_OPERAND (op11, 0));
17330 op11 = TREE_OPERAND (op11, 1);
17332 lhs = RECUR (TREE_OPERAND (op11, 0));
17333 rhs = RECUR (TREE_OPERAND (op11, 1));
17334 opcode = TREE_CODE (op11);
17335 if (opcode == MODIFY_EXPR)
17336 opcode = NOP_EXPR;
17338 else
17340 code = OMP_ATOMIC;
17341 lhs = RECUR (TREE_OPERAND (op1, 0));
17342 rhs = RECUR (TREE_OPERAND (op1, 1));
17344 finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
17345 OMP_ATOMIC_SEQ_CST (t));
17347 break;
17349 case TRANSACTION_EXPR:
17351 int flags = 0;
17352 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17353 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17355 if (TRANSACTION_EXPR_IS_STMT (t))
17357 tree body = TRANSACTION_EXPR_BODY (t);
17358 tree noex = NULL_TREE;
17359 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17361 noex = MUST_NOT_THROW_COND (body);
17362 if (noex == NULL_TREE)
17363 noex = boolean_true_node;
17364 body = TREE_OPERAND (body, 0);
17366 stmt = begin_transaction_stmt (input_location, NULL, flags);
17367 RECUR (body);
17368 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17370 else
17372 stmt = build_transaction_expr (EXPR_LOCATION (t),
17373 RECUR (TRANSACTION_EXPR_BODY (t)),
17374 flags, NULL_TREE);
17375 RETURN (stmt);
17378 break;
17380 case MUST_NOT_THROW_EXPR:
17382 tree op0 = RECUR (TREE_OPERAND (t, 0));
17383 tree cond = RECUR (MUST_NOT_THROW_COND (t));
17384 RETURN (build_must_not_throw_expr (op0, cond));
17387 case EXPR_PACK_EXPANSION:
17388 error ("invalid use of pack expansion expression");
17389 RETURN (error_mark_node);
17391 case NONTYPE_ARGUMENT_PACK:
17392 error ("use %<...%> to expand argument pack");
17393 RETURN (error_mark_node);
17395 case COMPOUND_EXPR:
17396 tmp = RECUR (TREE_OPERAND (t, 0));
17397 if (tmp == NULL_TREE)
17398 /* If the first operand was a statement, we're done with it. */
17399 RETURN (RECUR (TREE_OPERAND (t, 1)));
17400 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17401 RECUR (TREE_OPERAND (t, 1)),
17402 complain));
17404 case ANNOTATE_EXPR:
17405 tmp = RECUR (TREE_OPERAND (t, 0));
17406 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17407 TREE_TYPE (tmp), tmp,
17408 RECUR (TREE_OPERAND (t, 1)),
17409 RECUR (TREE_OPERAND (t, 2))));
17411 default:
17412 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17414 RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17415 /*function_p=*/false,
17416 integral_constant_expression_p));
17419 RETURN (NULL_TREE);
17420 out:
17421 input_location = loc;
17422 return r;
17423 #undef RECUR
17424 #undef RETURN
17427 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17428 function. For description of the body see comment above
17429 cp_parser_omp_declare_reduction_exprs. */
17431 static void
17432 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17434 if (t == NULL_TREE || t == error_mark_node)
17435 return;
17437 gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17439 tree_stmt_iterator tsi;
17440 int i;
17441 tree stmts[7];
17442 memset (stmts, 0, sizeof stmts);
17443 for (i = 0, tsi = tsi_start (t);
17444 i < 7 && !tsi_end_p (tsi);
17445 i++, tsi_next (&tsi))
17446 stmts[i] = tsi_stmt (tsi);
17447 gcc_assert (tsi_end_p (tsi));
17449 if (i >= 3)
17451 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17452 && TREE_CODE (stmts[1]) == DECL_EXPR);
17453 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17454 args, complain, in_decl);
17455 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17456 args, complain, in_decl);
17457 DECL_CONTEXT (omp_out) = current_function_decl;
17458 DECL_CONTEXT (omp_in) = current_function_decl;
17459 keep_next_level (true);
17460 tree block = begin_omp_structured_block ();
17461 tsubst_expr (stmts[2], args, complain, in_decl, false);
17462 block = finish_omp_structured_block (block);
17463 block = maybe_cleanup_point_expr_void (block);
17464 add_decl_expr (omp_out);
17465 if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17466 TREE_NO_WARNING (omp_out) = 1;
17467 add_decl_expr (omp_in);
17468 finish_expr_stmt (block);
17470 if (i >= 6)
17472 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17473 && TREE_CODE (stmts[4]) == DECL_EXPR);
17474 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17475 args, complain, in_decl);
17476 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17477 args, complain, in_decl);
17478 DECL_CONTEXT (omp_priv) = current_function_decl;
17479 DECL_CONTEXT (omp_orig) = current_function_decl;
17480 keep_next_level (true);
17481 tree block = begin_omp_structured_block ();
17482 tsubst_expr (stmts[5], args, complain, in_decl, false);
17483 block = finish_omp_structured_block (block);
17484 block = maybe_cleanup_point_expr_void (block);
17485 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17486 add_decl_expr (omp_priv);
17487 add_decl_expr (omp_orig);
17488 finish_expr_stmt (block);
17489 if (i == 7)
17490 add_decl_expr (omp_orig);
17494 /* T is a postfix-expression that is not being used in a function
17495 call. Return the substituted version of T. */
17497 static tree
17498 tsubst_non_call_postfix_expression (tree t, tree args,
17499 tsubst_flags_t complain,
17500 tree in_decl)
17502 if (TREE_CODE (t) == SCOPE_REF)
17503 t = tsubst_qualified_id (t, args, complain, in_decl,
17504 /*done=*/false, /*address_p=*/false);
17505 else
17506 t = tsubst_copy_and_build (t, args, complain, in_decl,
17507 /*function_p=*/false,
17508 /*integral_constant_expression_p=*/false);
17510 return t;
17513 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
17514 instantiation context. Instantiating a pack expansion containing a lambda
17515 might result in multiple lambdas all based on the same lambda in the
17516 template. */
17518 tree
17519 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17521 tree oldfn = lambda_function (t);
17522 in_decl = oldfn;
17524 tree r = build_lambda_expr ();
17526 LAMBDA_EXPR_LOCATION (r)
17527 = LAMBDA_EXPR_LOCATION (t);
17528 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17529 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17530 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17532 if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17533 LAMBDA_EXPR_EXTRA_SCOPE (r) = NULL_TREE;
17534 else
17535 record_lambda_scope (r);
17537 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17538 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17540 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17541 cap = TREE_CHAIN (cap))
17543 tree field = TREE_PURPOSE (cap);
17544 if (PACK_EXPANSION_P (field))
17545 field = PACK_EXPANSION_PATTERN (field);
17546 field = tsubst_decl (field, args, complain);
17548 if (field == error_mark_node)
17549 return error_mark_node;
17551 tree init = TREE_VALUE (cap);
17552 if (PACK_EXPANSION_P (init))
17553 init = tsubst_pack_expansion (init, args, complain, in_decl);
17554 else
17555 init = tsubst_copy_and_build (init, args, complain, in_decl,
17556 /*fn*/false, /*constexpr*/false);
17558 if (TREE_CODE (field) == TREE_VEC)
17560 int len = TREE_VEC_LENGTH (field);
17561 gcc_assert (TREE_CODE (init) == TREE_VEC
17562 && TREE_VEC_LENGTH (init) == len);
17563 for (int i = 0; i < len; ++i)
17564 LAMBDA_EXPR_CAPTURE_LIST (r)
17565 = tree_cons (TREE_VEC_ELT (field, i),
17566 TREE_VEC_ELT (init, i),
17567 LAMBDA_EXPR_CAPTURE_LIST (r));
17569 else
17571 LAMBDA_EXPR_CAPTURE_LIST (r)
17572 = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17574 if (id_equal (DECL_NAME (field), "__this"))
17575 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17579 tree type = begin_lambda_type (r);
17580 if (type == error_mark_node)
17581 return error_mark_node;
17583 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
17584 determine_visibility (TYPE_NAME (type));
17586 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17588 tree oldtmpl = (generic_lambda_fn_p (oldfn)
17589 ? DECL_TI_TEMPLATE (oldfn)
17590 : NULL_TREE);
17592 tree fntype = static_fn_type (oldfn);
17593 if (oldtmpl)
17594 ++processing_template_decl;
17595 fntype = tsubst (fntype, args, complain, in_decl);
17596 if (oldtmpl)
17597 --processing_template_decl;
17599 if (fntype == error_mark_node)
17600 r = error_mark_node;
17601 else
17603 /* Fix the type of 'this'. */
17604 fntype = build_memfn_type (fntype, type,
17605 type_memfn_quals (fntype),
17606 type_memfn_rqual (fntype));
17607 tree fn, tmpl;
17608 if (oldtmpl)
17610 tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17611 fn = DECL_TEMPLATE_RESULT (tmpl);
17612 finish_member_declaration (tmpl);
17614 else
17616 tmpl = NULL_TREE;
17617 fn = tsubst_function_decl (oldfn, args, complain, fntype);
17618 finish_member_declaration (fn);
17621 /* Let finish_function set this. */
17622 DECL_DECLARED_CONSTEXPR_P (fn) = false;
17624 bool nested = cfun;
17625 if (nested)
17626 push_function_context ();
17627 else
17628 /* Still increment function_depth so that we don't GC in the
17629 middle of an expression. */
17630 ++function_depth;
17632 local_specialization_stack s (lss_copy);
17634 tree body = start_lambda_function (fn, r);
17636 register_parameter_specializations (oldfn, fn);
17638 if (oldtmpl)
17640 /* We might not partially instantiate some parts of the function, so
17641 copy these flags from the original template. */
17642 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
17643 current_function_returns_value = ol->returns_value;
17644 current_function_returns_null = ol->returns_null;
17645 current_function_returns_abnormally = ol->returns_abnormally;
17646 current_function_infinite_loop = ol->infinite_loop;
17649 tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17650 /*constexpr*/false);
17652 finish_lambda_function (body);
17654 if (nested)
17655 pop_function_context ();
17656 else
17657 --function_depth;
17659 /* The capture list was built up in reverse order; fix that now. */
17660 LAMBDA_EXPR_CAPTURE_LIST (r)
17661 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17663 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17665 maybe_add_lambda_conv_op (type);
17668 finish_struct (type, /*attr*/NULL_TREE);
17670 insert_pending_capture_proxies ();
17672 return r;
17675 /* Like tsubst but deals with expressions and performs semantic
17676 analysis. FUNCTION_P is true if T is the "F" in "F (ARGS)". */
17678 tree
17679 tsubst_copy_and_build (tree t,
17680 tree args,
17681 tsubst_flags_t complain,
17682 tree in_decl,
17683 bool function_p,
17684 bool integral_constant_expression_p)
17686 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17687 #define RECUR(NODE) \
17688 tsubst_copy_and_build (NODE, args, complain, in_decl, \
17689 /*function_p=*/false, \
17690 integral_constant_expression_p)
17692 tree retval, op1;
17693 location_t loc;
17695 if (t == NULL_TREE || t == error_mark_node)
17696 return t;
17698 loc = input_location;
17699 if (EXPR_HAS_LOCATION (t))
17700 input_location = EXPR_LOCATION (t);
17702 /* N3276 decltype magic only applies to calls at the top level or on the
17703 right side of a comma. */
17704 tsubst_flags_t decltype_flag = (complain & tf_decltype);
17705 complain &= ~tf_decltype;
17707 switch (TREE_CODE (t))
17709 case USING_DECL:
17710 t = DECL_NAME (t);
17711 /* Fall through. */
17712 case IDENTIFIER_NODE:
17714 tree decl;
17715 cp_id_kind idk;
17716 bool non_integral_constant_expression_p;
17717 const char *error_msg;
17719 if (IDENTIFIER_CONV_OP_P (t))
17721 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17722 t = make_conv_op_name (new_type);
17725 /* Look up the name. */
17726 decl = lookup_name (t);
17728 /* By convention, expressions use ERROR_MARK_NODE to indicate
17729 failure, not NULL_TREE. */
17730 if (decl == NULL_TREE)
17731 decl = error_mark_node;
17733 decl = finish_id_expression (t, decl, NULL_TREE,
17734 &idk,
17735 integral_constant_expression_p,
17736 /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17737 &non_integral_constant_expression_p,
17738 /*template_p=*/false,
17739 /*done=*/true,
17740 /*address_p=*/false,
17741 /*template_arg_p=*/false,
17742 &error_msg,
17743 input_location);
17744 if (error_msg)
17745 error (error_msg);
17746 if (!function_p && identifier_p (decl))
17748 if (complain & tf_error)
17749 unqualified_name_lookup_error (decl);
17750 decl = error_mark_node;
17752 RETURN (decl);
17755 case TEMPLATE_ID_EXPR:
17757 tree object;
17758 tree templ = RECUR (TREE_OPERAND (t, 0));
17759 tree targs = TREE_OPERAND (t, 1);
17761 if (targs)
17762 targs = tsubst_template_args (targs, args, complain, in_decl);
17763 if (targs == error_mark_node)
17764 RETURN (error_mark_node);
17766 if (TREE_CODE (templ) == SCOPE_REF)
17768 tree name = TREE_OPERAND (templ, 1);
17769 tree tid = lookup_template_function (name, targs);
17770 TREE_OPERAND (templ, 1) = tid;
17771 RETURN (templ);
17774 if (variable_template_p (templ))
17775 RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17777 if (TREE_CODE (templ) == COMPONENT_REF)
17779 object = TREE_OPERAND (templ, 0);
17780 templ = TREE_OPERAND (templ, 1);
17782 else
17783 object = NULL_TREE;
17784 templ = lookup_template_function (templ, targs);
17786 if (object)
17787 RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17788 object, templ, NULL_TREE));
17789 else
17790 RETURN (baselink_for_fns (templ));
17793 case INDIRECT_REF:
17795 tree r = RECUR (TREE_OPERAND (t, 0));
17797 if (REFERENCE_REF_P (t))
17799 /* A type conversion to reference type will be enclosed in
17800 such an indirect ref, but the substitution of the cast
17801 will have also added such an indirect ref. */
17802 r = convert_from_reference (r);
17804 else
17805 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17806 complain|decltype_flag);
17808 if (REF_PARENTHESIZED_P (t))
17809 r = force_paren_expr (r);
17811 RETURN (r);
17814 case NOP_EXPR:
17816 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17817 tree op0 = RECUR (TREE_OPERAND (t, 0));
17818 RETURN (build_nop (type, op0));
17821 case IMPLICIT_CONV_EXPR:
17823 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17824 tree expr = RECUR (TREE_OPERAND (t, 0));
17825 if (dependent_type_p (type) || type_dependent_expression_p (expr))
17827 retval = copy_node (t);
17828 TREE_TYPE (retval) = type;
17829 TREE_OPERAND (retval, 0) = expr;
17830 RETURN (retval);
17832 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17833 /* We'll pass this to convert_nontype_argument again, we don't need
17834 to actually perform any conversion here. */
17835 RETURN (expr);
17836 int flags = LOOKUP_IMPLICIT;
17837 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17838 flags = LOOKUP_NORMAL;
17839 RETURN (perform_implicit_conversion_flags (type, expr, complain,
17840 flags));
17843 case CONVERT_EXPR:
17845 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17846 tree op0 = RECUR (TREE_OPERAND (t, 0));
17847 if (op0 == error_mark_node)
17848 RETURN (error_mark_node);
17849 RETURN (build1 (CONVERT_EXPR, type, op0));
17852 case CAST_EXPR:
17853 case REINTERPRET_CAST_EXPR:
17854 case CONST_CAST_EXPR:
17855 case DYNAMIC_CAST_EXPR:
17856 case STATIC_CAST_EXPR:
17858 tree type;
17859 tree op, r = NULL_TREE;
17861 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17862 if (integral_constant_expression_p
17863 && !cast_valid_in_integral_constant_expression_p (type))
17865 if (complain & tf_error)
17866 error ("a cast to a type other than an integral or "
17867 "enumeration type cannot appear in a constant-expression");
17868 RETURN (error_mark_node);
17871 op = RECUR (TREE_OPERAND (t, 0));
17873 warning_sentinel s(warn_useless_cast);
17874 warning_sentinel s2(warn_ignored_qualifiers);
17875 switch (TREE_CODE (t))
17877 case CAST_EXPR:
17878 r = build_functional_cast (type, op, complain);
17879 break;
17880 case REINTERPRET_CAST_EXPR:
17881 r = build_reinterpret_cast (type, op, complain);
17882 break;
17883 case CONST_CAST_EXPR:
17884 r = build_const_cast (type, op, complain);
17885 break;
17886 case DYNAMIC_CAST_EXPR:
17887 r = build_dynamic_cast (type, op, complain);
17888 break;
17889 case STATIC_CAST_EXPR:
17890 r = build_static_cast (type, op, complain);
17891 break;
17892 default:
17893 gcc_unreachable ();
17896 RETURN (r);
17899 case POSTDECREMENT_EXPR:
17900 case POSTINCREMENT_EXPR:
17901 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17902 args, complain, in_decl);
17903 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
17904 complain|decltype_flag));
17906 case PREDECREMENT_EXPR:
17907 case PREINCREMENT_EXPR:
17908 case NEGATE_EXPR:
17909 case BIT_NOT_EXPR:
17910 case ABS_EXPR:
17911 case TRUTH_NOT_EXPR:
17912 case UNARY_PLUS_EXPR: /* Unary + */
17913 case REALPART_EXPR:
17914 case IMAGPART_EXPR:
17915 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
17916 RECUR (TREE_OPERAND (t, 0)),
17917 complain|decltype_flag));
17919 case FIX_TRUNC_EXPR:
17920 gcc_unreachable ();
17922 case ADDR_EXPR:
17923 op1 = TREE_OPERAND (t, 0);
17924 if (TREE_CODE (op1) == LABEL_DECL)
17925 RETURN (finish_label_address_expr (DECL_NAME (op1),
17926 EXPR_LOCATION (op1)));
17927 if (TREE_CODE (op1) == SCOPE_REF)
17928 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
17929 /*done=*/true, /*address_p=*/true);
17930 else
17931 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
17932 in_decl);
17933 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
17934 complain|decltype_flag));
17936 case PLUS_EXPR:
17937 case MINUS_EXPR:
17938 case MULT_EXPR:
17939 case TRUNC_DIV_EXPR:
17940 case CEIL_DIV_EXPR:
17941 case FLOOR_DIV_EXPR:
17942 case ROUND_DIV_EXPR:
17943 case EXACT_DIV_EXPR:
17944 case BIT_AND_EXPR:
17945 case BIT_IOR_EXPR:
17946 case BIT_XOR_EXPR:
17947 case TRUNC_MOD_EXPR:
17948 case FLOOR_MOD_EXPR:
17949 case TRUTH_ANDIF_EXPR:
17950 case TRUTH_ORIF_EXPR:
17951 case TRUTH_AND_EXPR:
17952 case TRUTH_OR_EXPR:
17953 case RSHIFT_EXPR:
17954 case LSHIFT_EXPR:
17955 case RROTATE_EXPR:
17956 case LROTATE_EXPR:
17957 case EQ_EXPR:
17958 case NE_EXPR:
17959 case MAX_EXPR:
17960 case MIN_EXPR:
17961 case LE_EXPR:
17962 case GE_EXPR:
17963 case LT_EXPR:
17964 case GT_EXPR:
17965 case MEMBER_REF:
17966 case DOTSTAR_EXPR:
17968 warning_sentinel s1(warn_type_limits);
17969 warning_sentinel s2(warn_div_by_zero);
17970 warning_sentinel s3(warn_logical_op);
17971 warning_sentinel s4(warn_tautological_compare);
17972 tree op0 = RECUR (TREE_OPERAND (t, 0));
17973 tree op1 = RECUR (TREE_OPERAND (t, 1));
17974 tree r = build_x_binary_op
17975 (input_location, TREE_CODE (t),
17976 op0,
17977 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
17978 ? ERROR_MARK
17979 : TREE_CODE (TREE_OPERAND (t, 0))),
17980 op1,
17981 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
17982 ? ERROR_MARK
17983 : TREE_CODE (TREE_OPERAND (t, 1))),
17984 /*overload=*/NULL,
17985 complain|decltype_flag);
17986 if (EXPR_P (r) && TREE_NO_WARNING (t))
17987 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17989 RETURN (r);
17992 case POINTER_PLUS_EXPR:
17994 tree op0 = RECUR (TREE_OPERAND (t, 0));
17995 tree op1 = RECUR (TREE_OPERAND (t, 1));
17996 RETURN (fold_build_pointer_plus (op0, op1));
17999 case SCOPE_REF:
18000 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18001 /*address_p=*/false));
18002 case ARRAY_REF:
18003 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18004 args, complain, in_decl);
18005 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18006 RECUR (TREE_OPERAND (t, 1)),
18007 complain|decltype_flag));
18009 case SIZEOF_EXPR:
18010 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18011 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18012 RETURN (tsubst_copy (t, args, complain, in_decl));
18013 /* Fall through */
18015 case ALIGNOF_EXPR:
18017 tree r;
18019 op1 = TREE_OPERAND (t, 0);
18020 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18021 op1 = TREE_TYPE (op1);
18022 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18023 && ALIGNOF_EXPR_STD_P (t));
18024 if (!args)
18026 /* When there are no ARGS, we are trying to evaluate a
18027 non-dependent expression from the parser. Trying to do
18028 the substitutions may not work. */
18029 if (!TYPE_P (op1))
18030 op1 = TREE_TYPE (op1);
18032 else
18034 ++cp_unevaluated_operand;
18035 ++c_inhibit_evaluation_warnings;
18036 if (TYPE_P (op1))
18037 op1 = tsubst (op1, args, complain, in_decl);
18038 else
18039 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18040 /*function_p=*/false,
18041 /*integral_constant_expression_p=*/
18042 false);
18043 --cp_unevaluated_operand;
18044 --c_inhibit_evaluation_warnings;
18046 if (TYPE_P (op1))
18047 r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18048 complain & tf_error);
18049 else
18050 r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18051 complain & tf_error);
18052 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18054 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18056 if (!processing_template_decl && TYPE_P (op1))
18058 r = build_min (SIZEOF_EXPR, size_type_node,
18059 build1 (NOP_EXPR, op1, error_mark_node));
18060 SIZEOF_EXPR_TYPE_P (r) = 1;
18062 else
18063 r = build_min (SIZEOF_EXPR, size_type_node, op1);
18064 TREE_SIDE_EFFECTS (r) = 0;
18065 TREE_READONLY (r) = 1;
18067 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18069 RETURN (r);
18072 case AT_ENCODE_EXPR:
18074 op1 = TREE_OPERAND (t, 0);
18075 ++cp_unevaluated_operand;
18076 ++c_inhibit_evaluation_warnings;
18077 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18078 /*function_p=*/false,
18079 /*integral_constant_expression_p=*/false);
18080 --cp_unevaluated_operand;
18081 --c_inhibit_evaluation_warnings;
18082 RETURN (objc_build_encode_expr (op1));
18085 case NOEXCEPT_EXPR:
18086 op1 = TREE_OPERAND (t, 0);
18087 ++cp_unevaluated_operand;
18088 ++c_inhibit_evaluation_warnings;
18089 ++cp_noexcept_operand;
18090 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18091 /*function_p=*/false,
18092 /*integral_constant_expression_p=*/false);
18093 --cp_unevaluated_operand;
18094 --c_inhibit_evaluation_warnings;
18095 --cp_noexcept_operand;
18096 RETURN (finish_noexcept_expr (op1, complain));
18098 case MODOP_EXPR:
18100 warning_sentinel s(warn_div_by_zero);
18101 tree lhs = RECUR (TREE_OPERAND (t, 0));
18102 tree rhs = RECUR (TREE_OPERAND (t, 2));
18103 tree r = build_x_modify_expr
18104 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18105 complain|decltype_flag);
18106 /* TREE_NO_WARNING must be set if either the expression was
18107 parenthesized or it uses an operator such as >>= rather
18108 than plain assignment. In the former case, it was already
18109 set and must be copied. In the latter case,
18110 build_x_modify_expr sets it and it must not be reset
18111 here. */
18112 if (TREE_NO_WARNING (t))
18113 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18115 RETURN (r);
18118 case ARROW_EXPR:
18119 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18120 args, complain, in_decl);
18121 /* Remember that there was a reference to this entity. */
18122 if (DECL_P (op1)
18123 && !mark_used (op1, complain) && !(complain & tf_error))
18124 RETURN (error_mark_node);
18125 RETURN (build_x_arrow (input_location, op1, complain));
18127 case NEW_EXPR:
18129 tree placement = RECUR (TREE_OPERAND (t, 0));
18130 tree init = RECUR (TREE_OPERAND (t, 3));
18131 vec<tree, va_gc> *placement_vec;
18132 vec<tree, va_gc> *init_vec;
18133 tree ret;
18135 if (placement == NULL_TREE)
18136 placement_vec = NULL;
18137 else
18139 placement_vec = make_tree_vector ();
18140 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18141 vec_safe_push (placement_vec, TREE_VALUE (placement));
18144 /* If there was an initializer in the original tree, but it
18145 instantiated to an empty list, then we should pass a
18146 non-NULL empty vector to tell build_new that it was an
18147 empty initializer() rather than no initializer. This can
18148 only happen when the initializer is a pack expansion whose
18149 parameter packs are of length zero. */
18150 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18151 init_vec = NULL;
18152 else
18154 init_vec = make_tree_vector ();
18155 if (init == void_node)
18156 gcc_assert (init_vec != NULL);
18157 else
18159 for (; init != NULL_TREE; init = TREE_CHAIN (init))
18160 vec_safe_push (init_vec, TREE_VALUE (init));
18164 /* Avoid passing an enclosing decl to valid_array_size_p. */
18165 in_decl = NULL_TREE;
18167 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18168 tree op2 = RECUR (TREE_OPERAND (t, 2));
18169 ret = build_new (&placement_vec, op1, op2, &init_vec,
18170 NEW_EXPR_USE_GLOBAL (t),
18171 complain);
18173 if (placement_vec != NULL)
18174 release_tree_vector (placement_vec);
18175 if (init_vec != NULL)
18176 release_tree_vector (init_vec);
18178 RETURN (ret);
18181 case DELETE_EXPR:
18183 tree op0 = RECUR (TREE_OPERAND (t, 0));
18184 tree op1 = RECUR (TREE_OPERAND (t, 1));
18185 RETURN (delete_sanity (op0, op1,
18186 DELETE_EXPR_USE_VEC (t),
18187 DELETE_EXPR_USE_GLOBAL (t),
18188 complain));
18191 case COMPOUND_EXPR:
18193 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18194 complain & ~tf_decltype, in_decl,
18195 /*function_p=*/false,
18196 integral_constant_expression_p);
18197 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18198 op0,
18199 RECUR (TREE_OPERAND (t, 1)),
18200 complain|decltype_flag));
18203 case CALL_EXPR:
18205 tree function;
18206 vec<tree, va_gc> *call_args;
18207 unsigned int nargs, i;
18208 bool qualified_p;
18209 bool koenig_p;
18210 tree ret;
18212 function = CALL_EXPR_FN (t);
18213 /* Internal function with no arguments. */
18214 if (function == NULL_TREE && call_expr_nargs (t) == 0)
18215 RETURN (t);
18217 /* When we parsed the expression, we determined whether or
18218 not Koenig lookup should be performed. */
18219 koenig_p = KOENIG_LOOKUP_P (t);
18220 if (function == NULL_TREE)
18222 koenig_p = false;
18223 qualified_p = false;
18225 else if (TREE_CODE (function) == SCOPE_REF)
18227 qualified_p = true;
18228 function = tsubst_qualified_id (function, args, complain, in_decl,
18229 /*done=*/false,
18230 /*address_p=*/false);
18232 else if (koenig_p && identifier_p (function))
18234 /* Do nothing; calling tsubst_copy_and_build on an identifier
18235 would incorrectly perform unqualified lookup again.
18237 Note that we can also have an IDENTIFIER_NODE if the earlier
18238 unqualified lookup found a member function; in that case
18239 koenig_p will be false and we do want to do the lookup
18240 again to find the instantiated member function.
18242 FIXME but doing that causes c++/15272, so we need to stop
18243 using IDENTIFIER_NODE in that situation. */
18244 qualified_p = false;
18246 else
18248 if (TREE_CODE (function) == COMPONENT_REF)
18250 tree op = TREE_OPERAND (function, 1);
18252 qualified_p = (TREE_CODE (op) == SCOPE_REF
18253 || (BASELINK_P (op)
18254 && BASELINK_QUALIFIED_P (op)));
18256 else
18257 qualified_p = false;
18259 if (TREE_CODE (function) == ADDR_EXPR
18260 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18261 /* Avoid error about taking the address of a constructor. */
18262 function = TREE_OPERAND (function, 0);
18264 function = tsubst_copy_and_build (function, args, complain,
18265 in_decl,
18266 !qualified_p,
18267 integral_constant_expression_p);
18269 if (BASELINK_P (function))
18270 qualified_p = true;
18273 nargs = call_expr_nargs (t);
18274 call_args = make_tree_vector ();
18275 for (i = 0; i < nargs; ++i)
18277 tree arg = CALL_EXPR_ARG (t, i);
18279 if (!PACK_EXPANSION_P (arg))
18280 vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18281 else
18283 /* Expand the pack expansion and push each entry onto
18284 CALL_ARGS. */
18285 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18286 if (TREE_CODE (arg) == TREE_VEC)
18288 unsigned int len, j;
18290 len = TREE_VEC_LENGTH (arg);
18291 for (j = 0; j < len; ++j)
18293 tree value = TREE_VEC_ELT (arg, j);
18294 if (value != NULL_TREE)
18295 value = convert_from_reference (value);
18296 vec_safe_push (call_args, value);
18299 else
18301 /* A partial substitution. Add one entry. */
18302 vec_safe_push (call_args, arg);
18307 /* We do not perform argument-dependent lookup if normal
18308 lookup finds a non-function, in accordance with the
18309 expected resolution of DR 218. */
18310 if (koenig_p
18311 && ((is_overloaded_fn (function)
18312 /* If lookup found a member function, the Koenig lookup is
18313 not appropriate, even if an unqualified-name was used
18314 to denote the function. */
18315 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18316 || identifier_p (function))
18317 /* Only do this when substitution turns a dependent call
18318 into a non-dependent call. */
18319 && type_dependent_expression_p_push (t)
18320 && !any_type_dependent_arguments_p (call_args))
18321 function = perform_koenig_lookup (function, call_args, tf_none);
18323 if (function != NULL_TREE
18324 && identifier_p (function)
18325 && !any_type_dependent_arguments_p (call_args))
18327 if (koenig_p && (complain & tf_warning_or_error))
18329 /* For backwards compatibility and good diagnostics, try
18330 the unqualified lookup again if we aren't in SFINAE
18331 context. */
18332 tree unq = (tsubst_copy_and_build
18333 (function, args, complain, in_decl, true,
18334 integral_constant_expression_p));
18335 if (unq == error_mark_node)
18337 release_tree_vector (call_args);
18338 RETURN (error_mark_node);
18341 if (unq != function)
18343 /* In a lambda fn, we have to be careful to not
18344 introduce new this captures. Legacy code can't
18345 be using lambdas anyway, so it's ok to be
18346 stricter. */
18347 bool in_lambda = (current_class_type
18348 && LAMBDA_TYPE_P (current_class_type));
18349 char const *const msg
18350 = G_("%qD was not declared in this scope, "
18351 "and no declarations were found by "
18352 "argument-dependent lookup at the point "
18353 "of instantiation");
18355 bool diag = true;
18356 if (in_lambda)
18357 error_at (EXPR_LOC_OR_LOC (t, input_location),
18358 msg, function);
18359 else
18360 diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
18361 msg, function);
18362 if (diag)
18364 tree fn = unq;
18366 if (INDIRECT_REF_P (fn))
18367 fn = TREE_OPERAND (fn, 0);
18368 if (is_overloaded_fn (fn))
18369 fn = get_first_fn (fn);
18371 if (!DECL_P (fn))
18372 /* Can't say anything more. */;
18373 else if (DECL_CLASS_SCOPE_P (fn))
18375 location_t loc = EXPR_LOC_OR_LOC (t,
18376 input_location);
18377 inform (loc,
18378 "declarations in dependent base %qT are "
18379 "not found by unqualified lookup",
18380 DECL_CLASS_CONTEXT (fn));
18381 if (current_class_ptr)
18382 inform (loc,
18383 "use %<this->%D%> instead", function);
18384 else
18385 inform (loc,
18386 "use %<%T::%D%> instead",
18387 current_class_name, function);
18389 else
18390 inform (DECL_SOURCE_LOCATION (fn),
18391 "%qD declared here, later in the "
18392 "translation unit", fn);
18393 if (in_lambda)
18395 release_tree_vector (call_args);
18396 RETURN (error_mark_node);
18400 function = unq;
18403 if (identifier_p (function))
18405 if (complain & tf_error)
18406 unqualified_name_lookup_error (function);
18407 release_tree_vector (call_args);
18408 RETURN (error_mark_node);
18412 /* Remember that there was a reference to this entity. */
18413 if (function != NULL_TREE
18414 && DECL_P (function)
18415 && !mark_used (function, complain) && !(complain & tf_error))
18417 release_tree_vector (call_args);
18418 RETURN (error_mark_node);
18421 /* Put back tf_decltype for the actual call. */
18422 complain |= decltype_flag;
18424 if (function == NULL_TREE)
18425 switch (CALL_EXPR_IFN (t))
18427 case IFN_LAUNDER:
18428 gcc_assert (nargs == 1);
18429 if (vec_safe_length (call_args) != 1)
18431 error_at (EXPR_LOC_OR_LOC (t, input_location),
18432 "wrong number of arguments to "
18433 "%<__builtin_launder%>");
18434 ret = error_mark_node;
18436 else
18437 ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
18438 input_location),
18439 (*call_args)[0], complain);
18440 break;
18442 default:
18443 /* Unsupported internal function with arguments. */
18444 gcc_unreachable ();
18446 else if (TREE_CODE (function) == OFFSET_REF
18447 || TREE_CODE (function) == DOTSTAR_EXPR
18448 || TREE_CODE (function) == MEMBER_REF)
18449 ret = build_offset_ref_call_from_tree (function, &call_args,
18450 complain);
18451 else if (TREE_CODE (function) == COMPONENT_REF)
18453 tree instance = TREE_OPERAND (function, 0);
18454 tree fn = TREE_OPERAND (function, 1);
18456 if (processing_template_decl
18457 && (type_dependent_expression_p (instance)
18458 || (!BASELINK_P (fn)
18459 && TREE_CODE (fn) != FIELD_DECL)
18460 || type_dependent_expression_p (fn)
18461 || any_type_dependent_arguments_p (call_args)))
18462 ret = build_min_nt_call_vec (function, call_args);
18463 else if (!BASELINK_P (fn))
18464 ret = finish_call_expr (function, &call_args,
18465 /*disallow_virtual=*/false,
18466 /*koenig_p=*/false,
18467 complain);
18468 else
18469 ret = (build_new_method_call
18470 (instance, fn,
18471 &call_args, NULL_TREE,
18472 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18473 /*fn_p=*/NULL,
18474 complain));
18476 else
18477 ret = finish_call_expr (function, &call_args,
18478 /*disallow_virtual=*/qualified_p,
18479 koenig_p,
18480 complain);
18482 release_tree_vector (call_args);
18484 if (ret != error_mark_node)
18486 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18487 bool ord = CALL_EXPR_ORDERED_ARGS (t);
18488 bool rev = CALL_EXPR_REVERSE_ARGS (t);
18489 bool thk = CALL_FROM_THUNK_P (t);
18490 if (op || ord || rev || thk)
18492 function = extract_call_expr (ret);
18493 CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18494 CALL_EXPR_ORDERED_ARGS (function) = ord;
18495 CALL_EXPR_REVERSE_ARGS (function) = rev;
18496 if (thk)
18498 if (TREE_CODE (function) == CALL_EXPR)
18499 CALL_FROM_THUNK_P (function) = true;
18500 else
18501 AGGR_INIT_FROM_THUNK_P (function) = true;
18502 /* The thunk location is not interesting. */
18503 SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18508 RETURN (ret);
18511 case COND_EXPR:
18513 tree cond = RECUR (TREE_OPERAND (t, 0));
18514 tree folded_cond = fold_non_dependent_expr (cond);
18515 tree exp1, exp2;
18517 if (TREE_CODE (folded_cond) == INTEGER_CST)
18519 if (integer_zerop (folded_cond))
18521 ++c_inhibit_evaluation_warnings;
18522 exp1 = RECUR (TREE_OPERAND (t, 1));
18523 --c_inhibit_evaluation_warnings;
18524 exp2 = RECUR (TREE_OPERAND (t, 2));
18526 else
18528 exp1 = RECUR (TREE_OPERAND (t, 1));
18529 ++c_inhibit_evaluation_warnings;
18530 exp2 = RECUR (TREE_OPERAND (t, 2));
18531 --c_inhibit_evaluation_warnings;
18533 cond = folded_cond;
18535 else
18537 exp1 = RECUR (TREE_OPERAND (t, 1));
18538 exp2 = RECUR (TREE_OPERAND (t, 2));
18541 warning_sentinel s(warn_duplicated_branches);
18542 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18543 cond, exp1, exp2, complain));
18546 case PSEUDO_DTOR_EXPR:
18548 tree op0 = RECUR (TREE_OPERAND (t, 0));
18549 tree op1 = RECUR (TREE_OPERAND (t, 1));
18550 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18551 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18552 input_location));
18555 case TREE_LIST:
18557 tree purpose, value, chain;
18559 if (t == void_list_node)
18560 RETURN (t);
18562 if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18563 || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18565 /* We have pack expansions, so expand those and
18566 create a new list out of it. */
18567 tree purposevec = NULL_TREE;
18568 tree valuevec = NULL_TREE;
18569 tree chain;
18570 int i, len = -1;
18572 /* Expand the argument expressions. */
18573 if (TREE_PURPOSE (t))
18574 purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18575 complain, in_decl);
18576 if (TREE_VALUE (t))
18577 valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18578 complain, in_decl);
18580 /* Build the rest of the list. */
18581 chain = TREE_CHAIN (t);
18582 if (chain && chain != void_type_node)
18583 chain = RECUR (chain);
18585 /* Determine the number of arguments. */
18586 if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18588 len = TREE_VEC_LENGTH (purposevec);
18589 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18591 else if (TREE_CODE (valuevec) == TREE_VEC)
18592 len = TREE_VEC_LENGTH (valuevec);
18593 else
18595 /* Since we only performed a partial substitution into
18596 the argument pack, we only RETURN (a single list
18597 node. */
18598 if (purposevec == TREE_PURPOSE (t)
18599 && valuevec == TREE_VALUE (t)
18600 && chain == TREE_CHAIN (t))
18601 RETURN (t);
18603 RETURN (tree_cons (purposevec, valuevec, chain));
18606 /* Convert the argument vectors into a TREE_LIST */
18607 i = len;
18608 while (i > 0)
18610 /* Grab the Ith values. */
18611 i--;
18612 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18613 : NULL_TREE;
18614 value
18615 = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18616 : NULL_TREE;
18618 /* Build the list (backwards). */
18619 chain = tree_cons (purpose, value, chain);
18622 RETURN (chain);
18625 purpose = TREE_PURPOSE (t);
18626 if (purpose)
18627 purpose = RECUR (purpose);
18628 value = TREE_VALUE (t);
18629 if (value)
18630 value = RECUR (value);
18631 chain = TREE_CHAIN (t);
18632 if (chain && chain != void_type_node)
18633 chain = RECUR (chain);
18634 if (purpose == TREE_PURPOSE (t)
18635 && value == TREE_VALUE (t)
18636 && chain == TREE_CHAIN (t))
18637 RETURN (t);
18638 RETURN (tree_cons (purpose, value, chain));
18641 case COMPONENT_REF:
18643 tree object;
18644 tree object_type;
18645 tree member;
18646 tree r;
18648 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18649 args, complain, in_decl);
18650 /* Remember that there was a reference to this entity. */
18651 if (DECL_P (object)
18652 && !mark_used (object, complain) && !(complain & tf_error))
18653 RETURN (error_mark_node);
18654 object_type = TREE_TYPE (object);
18656 member = TREE_OPERAND (t, 1);
18657 if (BASELINK_P (member))
18658 member = tsubst_baselink (member,
18659 non_reference (TREE_TYPE (object)),
18660 args, complain, in_decl);
18661 else
18662 member = tsubst_copy (member, args, complain, in_decl);
18663 if (member == error_mark_node)
18664 RETURN (error_mark_node);
18666 if (TREE_CODE (member) == FIELD_DECL)
18668 r = finish_non_static_data_member (member, object, NULL_TREE);
18669 if (TREE_CODE (r) == COMPONENT_REF)
18670 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18671 RETURN (r);
18673 else if (type_dependent_expression_p (object))
18674 /* We can't do much here. */;
18675 else if (!CLASS_TYPE_P (object_type))
18677 if (scalarish_type_p (object_type))
18679 tree s = NULL_TREE;
18680 tree dtor = member;
18682 if (TREE_CODE (dtor) == SCOPE_REF)
18684 s = TREE_OPERAND (dtor, 0);
18685 dtor = TREE_OPERAND (dtor, 1);
18687 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18689 dtor = TREE_OPERAND (dtor, 0);
18690 if (TYPE_P (dtor))
18691 RETURN (finish_pseudo_destructor_expr
18692 (object, s, dtor, input_location));
18696 else if (TREE_CODE (member) == SCOPE_REF
18697 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18699 /* Lookup the template functions now that we know what the
18700 scope is. */
18701 tree scope = TREE_OPERAND (member, 0);
18702 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18703 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18704 member = lookup_qualified_name (scope, tmpl,
18705 /*is_type_p=*/false,
18706 /*complain=*/false);
18707 if (BASELINK_P (member))
18709 BASELINK_FUNCTIONS (member)
18710 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18711 args);
18712 member = (adjust_result_of_qualified_name_lookup
18713 (member, BINFO_TYPE (BASELINK_BINFO (member)),
18714 object_type));
18716 else
18718 qualified_name_lookup_error (scope, tmpl, member,
18719 input_location);
18720 RETURN (error_mark_node);
18723 else if (TREE_CODE (member) == SCOPE_REF
18724 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18725 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18727 if (complain & tf_error)
18729 if (TYPE_P (TREE_OPERAND (member, 0)))
18730 error ("%qT is not a class or namespace",
18731 TREE_OPERAND (member, 0));
18732 else
18733 error ("%qD is not a class or namespace",
18734 TREE_OPERAND (member, 0));
18736 RETURN (error_mark_node);
18739 r = finish_class_member_access_expr (object, member,
18740 /*template_p=*/false,
18741 complain);
18742 if (TREE_CODE (r) == COMPONENT_REF)
18743 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18744 RETURN (r);
18747 case THROW_EXPR:
18748 RETURN (build_throw
18749 (RECUR (TREE_OPERAND (t, 0))));
18751 case CONSTRUCTOR:
18753 vec<constructor_elt, va_gc> *n;
18754 constructor_elt *ce;
18755 unsigned HOST_WIDE_INT idx;
18756 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18757 bool process_index_p;
18758 int newlen;
18759 bool need_copy_p = false;
18760 tree r;
18762 if (type == error_mark_node)
18763 RETURN (error_mark_node);
18765 /* We do not want to process the index of aggregate
18766 initializers as they are identifier nodes which will be
18767 looked up by digest_init. */
18768 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18770 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18771 newlen = vec_safe_length (n);
18772 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18774 if (ce->index && process_index_p
18775 /* An identifier index is looked up in the type
18776 being initialized, not the current scope. */
18777 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
18778 ce->index = RECUR (ce->index);
18780 if (PACK_EXPANSION_P (ce->value))
18782 /* Substitute into the pack expansion. */
18783 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18784 in_decl);
18786 if (ce->value == error_mark_node
18787 || PACK_EXPANSION_P (ce->value))
18789 else if (TREE_VEC_LENGTH (ce->value) == 1)
18790 /* Just move the argument into place. */
18791 ce->value = TREE_VEC_ELT (ce->value, 0);
18792 else
18794 /* Update the length of the final CONSTRUCTOR
18795 arguments vector, and note that we will need to
18796 copy.*/
18797 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18798 need_copy_p = true;
18801 else
18802 ce->value = RECUR (ce->value);
18805 if (need_copy_p)
18807 vec<constructor_elt, va_gc> *old_n = n;
18809 vec_alloc (n, newlen);
18810 FOR_EACH_VEC_ELT (*old_n, idx, ce)
18812 if (TREE_CODE (ce->value) == TREE_VEC)
18814 int i, len = TREE_VEC_LENGTH (ce->value);
18815 for (i = 0; i < len; ++i)
18816 CONSTRUCTOR_APPEND_ELT (n, 0,
18817 TREE_VEC_ELT (ce->value, i));
18819 else
18820 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18824 r = build_constructor (init_list_type_node, n);
18825 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18827 if (TREE_HAS_CONSTRUCTOR (t))
18829 fcl_t cl = fcl_functional;
18830 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18831 cl = fcl_c99;
18832 RETURN (finish_compound_literal (type, r, complain, cl));
18835 TREE_TYPE (r) = type;
18836 RETURN (r);
18839 case TYPEID_EXPR:
18841 tree operand_0 = TREE_OPERAND (t, 0);
18842 if (TYPE_P (operand_0))
18844 operand_0 = tsubst (operand_0, args, complain, in_decl);
18845 RETURN (get_typeid (operand_0, complain));
18847 else
18849 operand_0 = RECUR (operand_0);
18850 RETURN (build_typeid (operand_0, complain));
18854 case VAR_DECL:
18855 if (!args)
18856 RETURN (t);
18857 /* Fall through */
18859 case PARM_DECL:
18861 tree r = tsubst_copy (t, args, complain, in_decl);
18862 /* ??? We're doing a subset of finish_id_expression here. */
18863 if (VAR_P (r)
18864 && !processing_template_decl
18865 && !cp_unevaluated_operand
18866 && (TREE_STATIC (r) || DECL_EXTERNAL (r))
18867 && CP_DECL_THREAD_LOCAL_P (r))
18869 if (tree wrap = get_tls_wrapper_fn (r))
18870 /* Replace an evaluated use of the thread_local variable with
18871 a call to its wrapper. */
18872 r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
18874 else if (outer_automatic_var_p (r))
18875 r = process_outer_var_ref (r, complain);
18877 if (!TYPE_REF_P (TREE_TYPE (t)))
18878 /* If the original type was a reference, we'll be wrapped in
18879 the appropriate INDIRECT_REF. */
18880 r = convert_from_reference (r);
18881 RETURN (r);
18884 case VA_ARG_EXPR:
18886 tree op0 = RECUR (TREE_OPERAND (t, 0));
18887 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18888 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
18891 case OFFSETOF_EXPR:
18893 tree object_ptr
18894 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
18895 in_decl, /*function_p=*/false,
18896 /*integral_constant_expression_p=*/false);
18897 RETURN (finish_offsetof (object_ptr,
18898 RECUR (TREE_OPERAND (t, 0)),
18899 EXPR_LOCATION (t)));
18902 case ADDRESSOF_EXPR:
18903 RETURN (cp_build_addressof (EXPR_LOCATION (t),
18904 RECUR (TREE_OPERAND (t, 0)), complain));
18906 case TRAIT_EXPR:
18908 tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
18909 complain, in_decl);
18911 tree type2 = TRAIT_EXPR_TYPE2 (t);
18912 if (type2 && TREE_CODE (type2) == TREE_LIST)
18913 type2 = RECUR (type2);
18914 else if (type2)
18915 type2 = tsubst (type2, args, complain, in_decl);
18917 RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
18920 case STMT_EXPR:
18922 tree old_stmt_expr = cur_stmt_expr;
18923 tree stmt_expr = begin_stmt_expr ();
18925 cur_stmt_expr = stmt_expr;
18926 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
18927 integral_constant_expression_p);
18928 stmt_expr = finish_stmt_expr (stmt_expr, false);
18929 cur_stmt_expr = old_stmt_expr;
18931 /* If the resulting list of expression statement is empty,
18932 fold it further into void_node. */
18933 if (empty_expr_stmt_p (stmt_expr))
18934 stmt_expr = void_node;
18936 RETURN (stmt_expr);
18939 case LAMBDA_EXPR:
18941 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
18943 RETURN (build_lambda_object (r));
18946 case TARGET_EXPR:
18947 /* We can get here for a constant initializer of non-dependent type.
18948 FIXME stop folding in cp_parser_initializer_clause. */
18950 tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
18951 complain);
18952 RETURN (r);
18955 case TRANSACTION_EXPR:
18956 RETURN (tsubst_expr(t, args, complain, in_decl,
18957 integral_constant_expression_p));
18959 case PAREN_EXPR:
18960 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
18962 case VEC_PERM_EXPR:
18964 tree op0 = RECUR (TREE_OPERAND (t, 0));
18965 tree op1 = RECUR (TREE_OPERAND (t, 1));
18966 tree op2 = RECUR (TREE_OPERAND (t, 2));
18967 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
18968 complain));
18971 case REQUIRES_EXPR:
18972 RETURN (tsubst_requires_expr (t, args, complain, in_decl));
18974 case NON_LVALUE_EXPR:
18975 case VIEW_CONVERT_EXPR:
18976 /* We should only see these for location wrapper nodes, or within
18977 instantiate_non_dependent_expr (when args is NULL_TREE). */
18978 gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
18979 if (location_wrapper_p (t))
18980 RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
18981 EXPR_LOCATION (t)));
18982 /* fallthrough. */
18984 default:
18985 /* Handle Objective-C++ constructs, if appropriate. */
18987 tree subst
18988 = objcp_tsubst_copy_and_build (t, args, complain,
18989 in_decl, /*function_p=*/false);
18990 if (subst)
18991 RETURN (subst);
18993 RETURN (tsubst_copy (t, args, complain, in_decl));
18996 #undef RECUR
18997 #undef RETURN
18998 out:
18999 input_location = loc;
19000 return retval;
19003 /* Verify that the instantiated ARGS are valid. For type arguments,
19004 make sure that the type's linkage is ok. For non-type arguments,
19005 make sure they are constants if they are integral or enumerations.
19006 Emit an error under control of COMPLAIN, and return TRUE on error. */
19008 static bool
19009 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
19011 if (dependent_template_arg_p (t))
19012 return false;
19013 if (ARGUMENT_PACK_P (t))
19015 tree vec = ARGUMENT_PACK_ARGS (t);
19016 int len = TREE_VEC_LENGTH (vec);
19017 bool result = false;
19018 int i;
19020 for (i = 0; i < len; ++i)
19021 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19022 result = true;
19023 return result;
19025 else if (TYPE_P (t))
19027 /* [basic.link]: A name with no linkage (notably, the name
19028 of a class or enumeration declared in a local scope)
19029 shall not be used to declare an entity with linkage.
19030 This implies that names with no linkage cannot be used as
19031 template arguments
19033 DR 757 relaxes this restriction for C++0x. */
19034 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19035 : no_linkage_check (t, /*relaxed_p=*/false));
19037 if (nt)
19039 /* DR 488 makes use of a type with no linkage cause
19040 type deduction to fail. */
19041 if (complain & tf_error)
19043 if (TYPE_UNNAMED_P (nt))
19044 error ("%qT is/uses unnamed type", t);
19045 else
19046 error ("template argument for %qD uses local type %qT",
19047 tmpl, t);
19049 return true;
19051 /* In order to avoid all sorts of complications, we do not
19052 allow variably-modified types as template arguments. */
19053 else if (variably_modified_type_p (t, NULL_TREE))
19055 if (complain & tf_error)
19056 error ("%qT is a variably modified type", t);
19057 return true;
19060 /* Class template and alias template arguments should be OK. */
19061 else if (DECL_TYPE_TEMPLATE_P (t))
19063 /* A non-type argument of integral or enumerated type must be a
19064 constant. */
19065 else if (TREE_TYPE (t)
19066 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19067 && !REFERENCE_REF_P (t)
19068 && !TREE_CONSTANT (t))
19070 if (complain & tf_error)
19071 error ("integral expression %qE is not constant", t);
19072 return true;
19074 return false;
19077 static bool
19078 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19080 int ix, len = DECL_NTPARMS (tmpl);
19081 bool result = false;
19083 for (ix = 0; ix != len; ix++)
19085 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19086 result = true;
19088 if (result && (complain & tf_error))
19089 error (" trying to instantiate %qD", tmpl);
19090 return result;
19093 /* We're out of SFINAE context now, so generate diagnostics for the access
19094 errors we saw earlier when instantiating D from TMPL and ARGS. */
19096 static void
19097 recheck_decl_substitution (tree d, tree tmpl, tree args)
19099 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19100 tree type = TREE_TYPE (pattern);
19101 location_t loc = input_location;
19103 push_access_scope (d);
19104 push_deferring_access_checks (dk_no_deferred);
19105 input_location = DECL_SOURCE_LOCATION (pattern);
19106 tsubst (type, args, tf_warning_or_error, d);
19107 input_location = loc;
19108 pop_deferring_access_checks ();
19109 pop_access_scope (d);
19112 /* Instantiate the indicated variable, function, or alias template TMPL with
19113 the template arguments in TARG_PTR. */
19115 static tree
19116 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19118 tree targ_ptr = orig_args;
19119 tree fndecl;
19120 tree gen_tmpl;
19121 tree spec;
19122 bool access_ok = true;
19124 if (tmpl == error_mark_node)
19125 return error_mark_node;
19127 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19129 /* If this function is a clone, handle it specially. */
19130 if (DECL_CLONED_FUNCTION_P (tmpl))
19132 tree spec;
19133 tree clone;
19135 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19136 DECL_CLONED_FUNCTION. */
19137 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19138 targ_ptr, complain);
19139 if (spec == error_mark_node)
19140 return error_mark_node;
19142 /* Look for the clone. */
19143 FOR_EACH_CLONE (clone, spec)
19144 if (DECL_NAME (clone) == DECL_NAME (tmpl))
19145 return clone;
19146 /* We should always have found the clone by now. */
19147 gcc_unreachable ();
19148 return NULL_TREE;
19151 if (targ_ptr == error_mark_node)
19152 return error_mark_node;
19154 /* Check to see if we already have this specialization. */
19155 gen_tmpl = most_general_template (tmpl);
19156 if (TMPL_ARGS_DEPTH (targ_ptr)
19157 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19158 /* targ_ptr only has the innermost template args, so add the outer ones
19159 from tmpl, which could be either a partial instantiation or gen_tmpl (in
19160 the case of a non-dependent call within a template definition). */
19161 targ_ptr = (add_outermost_template_args
19162 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19163 targ_ptr));
19165 /* It would be nice to avoid hashing here and then again in tsubst_decl,
19166 but it doesn't seem to be on the hot path. */
19167 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19169 gcc_assert (tmpl == gen_tmpl
19170 || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19171 == spec)
19172 || fndecl == NULL_TREE);
19174 if (spec != NULL_TREE)
19176 if (FNDECL_HAS_ACCESS_ERRORS (spec))
19178 if (complain & tf_error)
19179 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19180 return error_mark_node;
19182 return spec;
19185 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19186 complain))
19187 return error_mark_node;
19189 /* We are building a FUNCTION_DECL, during which the access of its
19190 parameters and return types have to be checked. However this
19191 FUNCTION_DECL which is the desired context for access checking
19192 is not built yet. We solve this chicken-and-egg problem by
19193 deferring all checks until we have the FUNCTION_DECL. */
19194 push_deferring_access_checks (dk_deferred);
19196 /* Instantiation of the function happens in the context of the function
19197 template, not the context of the overload resolution we're doing. */
19198 push_to_top_level ();
19199 /* If there are dependent arguments, e.g. because we're doing partial
19200 ordering, make sure processing_template_decl stays set. */
19201 if (uses_template_parms (targ_ptr))
19202 ++processing_template_decl;
19203 if (DECL_CLASS_SCOPE_P (gen_tmpl))
19205 tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19206 complain, gen_tmpl, true);
19207 push_nested_class (ctx);
19210 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19212 fndecl = NULL_TREE;
19213 if (VAR_P (pattern))
19215 /* We need to determine if we're using a partial or explicit
19216 specialization now, because the type of the variable could be
19217 different. */
19218 tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19219 tree elt = most_specialized_partial_spec (tid, complain);
19220 if (elt == error_mark_node)
19221 pattern = error_mark_node;
19222 else if (elt)
19224 tree partial_tmpl = TREE_VALUE (elt);
19225 tree partial_args = TREE_PURPOSE (elt);
19226 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19227 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19231 /* Substitute template parameters to obtain the specialization. */
19232 if (fndecl == NULL_TREE)
19233 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19234 if (DECL_CLASS_SCOPE_P (gen_tmpl))
19235 pop_nested_class ();
19236 pop_from_top_level ();
19238 if (fndecl == error_mark_node)
19240 pop_deferring_access_checks ();
19241 return error_mark_node;
19244 /* The DECL_TI_TEMPLATE should always be the immediate parent
19245 template, not the most general template. */
19246 DECL_TI_TEMPLATE (fndecl) = tmpl;
19247 DECL_TI_ARGS (fndecl) = targ_ptr;
19249 /* Now we know the specialization, compute access previously
19250 deferred. Do no access control for inheriting constructors,
19251 as we already checked access for the inherited constructor. */
19252 if (!(flag_new_inheriting_ctors
19253 && DECL_INHERITED_CTOR (fndecl)))
19255 push_access_scope (fndecl);
19256 if (!perform_deferred_access_checks (complain))
19257 access_ok = false;
19258 pop_access_scope (fndecl);
19260 pop_deferring_access_checks ();
19262 /* If we've just instantiated the main entry point for a function,
19263 instantiate all the alternate entry points as well. We do this
19264 by cloning the instantiation of the main entry point, not by
19265 instantiating the template clones. */
19266 if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19267 clone_function_decl (fndecl, /*update_methods=*/false);
19269 if (!access_ok)
19271 if (!(complain & tf_error))
19273 /* Remember to reinstantiate when we're out of SFINAE so the user
19274 can see the errors. */
19275 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19277 return error_mark_node;
19279 return fndecl;
19282 /* Wrapper for instantiate_template_1. */
19284 tree
19285 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19287 tree ret;
19288 timevar_push (TV_TEMPLATE_INST);
19289 ret = instantiate_template_1 (tmpl, orig_args, complain);
19290 timevar_pop (TV_TEMPLATE_INST);
19291 return ret;
19294 /* Instantiate the alias template TMPL with ARGS. Also push a template
19295 instantiation level, which instantiate_template doesn't do because
19296 functions and variables have sufficient context established by the
19297 callers. */
19299 static tree
19300 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19302 if (tmpl == error_mark_node || args == error_mark_node)
19303 return error_mark_node;
19304 if (!push_tinst_level (tmpl, args))
19305 return error_mark_node;
19307 args =
19308 coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19309 args, tmpl, complain,
19310 /*require_all_args=*/true,
19311 /*use_default_args=*/true);
19313 tree r = instantiate_template (tmpl, args, complain);
19314 pop_tinst_level ();
19316 return r;
19319 /* PARM is a template parameter pack for FN. Returns true iff
19320 PARM is used in a deducible way in the argument list of FN. */
19322 static bool
19323 pack_deducible_p (tree parm, tree fn)
19325 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19326 for (; t; t = TREE_CHAIN (t))
19328 tree type = TREE_VALUE (t);
19329 tree packs;
19330 if (!PACK_EXPANSION_P (type))
19331 continue;
19332 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19333 packs; packs = TREE_CHAIN (packs))
19334 if (template_args_equal (TREE_VALUE (packs), parm))
19336 /* The template parameter pack is used in a function parameter
19337 pack. If this is the end of the parameter list, the
19338 template parameter pack is deducible. */
19339 if (TREE_CHAIN (t) == void_list_node)
19340 return true;
19341 else
19342 /* Otherwise, not. Well, it could be deduced from
19343 a non-pack parameter, but doing so would end up with
19344 a deduction mismatch, so don't bother. */
19345 return false;
19348 /* The template parameter pack isn't used in any function parameter
19349 packs, but it might be used deeper, e.g. tuple<Args...>. */
19350 return true;
19353 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
19354 NARGS elements of the arguments that are being used when calling
19355 it. TARGS is a vector into which the deduced template arguments
19356 are placed.
19358 Returns either a FUNCTION_DECL for the matching specialization of FN or
19359 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
19360 true, diagnostics will be printed to explain why it failed.
19362 If FN is a conversion operator, or we are trying to produce a specific
19363 specialization, RETURN_TYPE is the return type desired.
19365 The EXPLICIT_TARGS are explicit template arguments provided via a
19366 template-id.
19368 The parameter STRICT is one of:
19370 DEDUCE_CALL:
19371 We are deducing arguments for a function call, as in
19372 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
19373 deducing arguments for a call to the result of a conversion
19374 function template, as in [over.call.object].
19376 DEDUCE_CONV:
19377 We are deducing arguments for a conversion function, as in
19378 [temp.deduct.conv].
19380 DEDUCE_EXACT:
19381 We are deducing arguments when doing an explicit instantiation
19382 as in [temp.explicit], when determining an explicit specialization
19383 as in [temp.expl.spec], or when taking the address of a function
19384 template, as in [temp.deduct.funcaddr]. */
19386 tree
19387 fn_type_unification (tree fn,
19388 tree explicit_targs,
19389 tree targs,
19390 const tree *args,
19391 unsigned int nargs,
19392 tree return_type,
19393 unification_kind_t strict,
19394 int flags,
19395 bool explain_p,
19396 bool decltype_p)
19398 tree parms;
19399 tree fntype;
19400 tree decl = NULL_TREE;
19401 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
19402 bool ok;
19403 static int deduction_depth;
19405 tree orig_fn = fn;
19406 if (flag_new_inheriting_ctors)
19407 fn = strip_inheriting_ctors (fn);
19409 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
19410 tree r = error_mark_node;
19412 tree full_targs = targs;
19413 if (TMPL_ARGS_DEPTH (targs)
19414 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
19415 full_targs = (add_outermost_template_args
19416 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
19417 targs));
19419 if (decltype_p)
19420 complain |= tf_decltype;
19422 /* In C++0x, it's possible to have a function template whose type depends
19423 on itself recursively. This is most obvious with decltype, but can also
19424 occur with enumeration scope (c++/48969). So we need to catch infinite
19425 recursion and reject the substitution at deduction time; this function
19426 will return error_mark_node for any repeated substitution.
19428 This also catches excessive recursion such as when f<N> depends on
19429 f<N-1> across all integers, and returns error_mark_node for all the
19430 substitutions back up to the initial one.
19432 This is, of course, not reentrant. */
19433 if (excessive_deduction_depth)
19434 return error_mark_node;
19435 ++deduction_depth;
19437 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19439 fntype = TREE_TYPE (fn);
19440 if (explicit_targs)
19442 /* [temp.deduct]
19444 The specified template arguments must match the template
19445 parameters in kind (i.e., type, nontype, template), and there
19446 must not be more arguments than there are parameters;
19447 otherwise type deduction fails.
19449 Nontype arguments must match the types of the corresponding
19450 nontype template parameters, or must be convertible to the
19451 types of the corresponding nontype parameters as specified in
19452 _temp.arg.nontype_, otherwise type deduction fails.
19454 All references in the function type of the function template
19455 to the corresponding template parameters are replaced by the
19456 specified template argument values. If a substitution in a
19457 template parameter or in the function type of the function
19458 template results in an invalid type, type deduction fails. */
19459 int i, len = TREE_VEC_LENGTH (tparms);
19460 location_t loc = input_location;
19461 bool incomplete = false;
19463 if (explicit_targs == error_mark_node)
19464 goto fail;
19466 if (TMPL_ARGS_DEPTH (explicit_targs)
19467 < TMPL_ARGS_DEPTH (full_targs))
19468 explicit_targs = add_outermost_template_args (full_targs,
19469 explicit_targs);
19471 /* Adjust any explicit template arguments before entering the
19472 substitution context. */
19473 explicit_targs
19474 = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19475 complain,
19476 /*require_all_args=*/false,
19477 /*use_default_args=*/false));
19478 if (explicit_targs == error_mark_node)
19479 goto fail;
19481 /* Substitute the explicit args into the function type. This is
19482 necessary so that, for instance, explicitly declared function
19483 arguments can match null pointed constants. If we were given
19484 an incomplete set of explicit args, we must not do semantic
19485 processing during substitution as we could create partial
19486 instantiations. */
19487 for (i = 0; i < len; i++)
19489 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19490 bool parameter_pack = false;
19491 tree targ = TREE_VEC_ELT (explicit_targs, i);
19493 /* Dig out the actual parm. */
19494 if (TREE_CODE (parm) == TYPE_DECL
19495 || TREE_CODE (parm) == TEMPLATE_DECL)
19497 parm = TREE_TYPE (parm);
19498 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19500 else if (TREE_CODE (parm) == PARM_DECL)
19502 parm = DECL_INITIAL (parm);
19503 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19506 if (!parameter_pack && targ == NULL_TREE)
19507 /* No explicit argument for this template parameter. */
19508 incomplete = true;
19510 if (parameter_pack && pack_deducible_p (parm, fn))
19512 /* Mark the argument pack as "incomplete". We could
19513 still deduce more arguments during unification.
19514 We remove this mark in type_unification_real. */
19515 if (targ)
19517 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19518 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19519 = ARGUMENT_PACK_ARGS (targ);
19522 /* We have some incomplete argument packs. */
19523 incomplete = true;
19527 if (!push_tinst_level (fn, explicit_targs))
19529 excessive_deduction_depth = true;
19530 goto fail;
19532 processing_template_decl += incomplete;
19533 input_location = DECL_SOURCE_LOCATION (fn);
19534 /* Ignore any access checks; we'll see them again in
19535 instantiate_template and they might have the wrong
19536 access path at this point. */
19537 push_deferring_access_checks (dk_deferred);
19538 fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19539 complain | tf_partial | tf_fndecl_type, NULL_TREE);
19540 pop_deferring_access_checks ();
19541 input_location = loc;
19542 processing_template_decl -= incomplete;
19543 pop_tinst_level ();
19545 if (fntype == error_mark_node)
19546 goto fail;
19548 /* Place the explicitly specified arguments in TARGS. */
19549 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19550 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19551 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19554 /* Never do unification on the 'this' parameter. */
19555 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19557 if (return_type && strict == DEDUCE_CALL)
19559 /* We're deducing for a call to the result of a template conversion
19560 function. The parms we really want are in return_type. */
19561 if (INDIRECT_TYPE_P (return_type))
19562 return_type = TREE_TYPE (return_type);
19563 parms = TYPE_ARG_TYPES (return_type);
19565 else if (return_type)
19567 tree *new_args;
19569 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19570 new_args = XALLOCAVEC (tree, nargs + 1);
19571 new_args[0] = return_type;
19572 memcpy (new_args + 1, args, nargs * sizeof (tree));
19573 args = new_args;
19574 ++nargs;
19577 /* We allow incomplete unification without an error message here
19578 because the standard doesn't seem to explicitly prohibit it. Our
19579 callers must be ready to deal with unification failures in any
19580 event. */
19582 /* If we aren't explaining yet, push tinst context so we can see where
19583 any errors (e.g. from class instantiations triggered by instantiation
19584 of default template arguments) come from. If we are explaining, this
19585 context is redundant. */
19586 if (!explain_p && !push_tinst_level (fn, targs))
19588 excessive_deduction_depth = true;
19589 goto fail;
19592 /* type_unification_real will pass back any access checks from default
19593 template argument substitution. */
19594 vec<deferred_access_check, va_gc> *checks;
19595 checks = NULL;
19597 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19598 full_targs, parms, args, nargs, /*subr=*/0,
19599 strict, flags, &checks, explain_p);
19600 if (!explain_p)
19601 pop_tinst_level ();
19602 if (!ok)
19603 goto fail;
19605 /* Now that we have bindings for all of the template arguments,
19606 ensure that the arguments deduced for the template template
19607 parameters have compatible template parameter lists. We cannot
19608 check this property before we have deduced all template
19609 arguments, because the template parameter types of a template
19610 template parameter might depend on prior template parameters
19611 deduced after the template template parameter. The following
19612 ill-formed example illustrates this issue:
19614 template<typename T, template<T> class C> void f(C<5>, T);
19616 template<int N> struct X {};
19618 void g() {
19619 f(X<5>(), 5l); // error: template argument deduction fails
19622 The template parameter list of 'C' depends on the template type
19623 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19624 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
19625 time that we deduce 'C'. */
19626 if (!template_template_parm_bindings_ok_p
19627 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19629 unify_inconsistent_template_template_parameters (explain_p);
19630 goto fail;
19633 /* All is well so far. Now, check:
19635 [temp.deduct]
19637 When all template arguments have been deduced, all uses of
19638 template parameters in nondeduced contexts are replaced with
19639 the corresponding deduced argument values. If the
19640 substitution results in an invalid type, as described above,
19641 type deduction fails. */
19642 if (!push_tinst_level (fn, targs))
19644 excessive_deduction_depth = true;
19645 goto fail;
19648 /* Also collect access checks from the instantiation. */
19649 reopen_deferring_access_checks (checks);
19651 decl = instantiate_template (fn, targs, complain);
19653 checks = get_deferred_access_checks ();
19654 pop_deferring_access_checks ();
19656 pop_tinst_level ();
19658 if (decl == error_mark_node)
19659 goto fail;
19661 /* Now perform any access checks encountered during substitution. */
19662 push_access_scope (decl);
19663 ok = perform_access_checks (checks, complain);
19664 pop_access_scope (decl);
19665 if (!ok)
19666 goto fail;
19668 /* If we're looking for an exact match, check that what we got
19669 is indeed an exact match. It might not be if some template
19670 parameters are used in non-deduced contexts. But don't check
19671 for an exact match if we have dependent template arguments;
19672 in that case we're doing partial ordering, and we already know
19673 that we have two candidates that will provide the actual type. */
19674 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19676 tree substed = TREE_TYPE (decl);
19677 unsigned int i;
19679 tree sarg
19680 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19681 if (return_type)
19682 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19683 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19684 if (!same_type_p (args[i], TREE_VALUE (sarg)))
19686 unify_type_mismatch (explain_p, args[i],
19687 TREE_VALUE (sarg));
19688 goto fail;
19692 /* After doing deduction with the inherited constructor, actually return an
19693 instantiation of the inheriting constructor. */
19694 if (orig_fn != fn)
19695 decl = instantiate_template (orig_fn, targs, complain);
19697 r = decl;
19699 fail:
19700 --deduction_depth;
19701 if (excessive_deduction_depth)
19703 if (deduction_depth == 0)
19704 /* Reset once we're all the way out. */
19705 excessive_deduction_depth = false;
19708 return r;
19711 /* Adjust types before performing type deduction, as described in
19712 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
19713 sections are symmetric. PARM is the type of a function parameter
19714 or the return type of the conversion function. ARG is the type of
19715 the argument passed to the call, or the type of the value
19716 initialized with the result of the conversion function.
19717 ARG_EXPR is the original argument expression, which may be null. */
19719 static int
19720 maybe_adjust_types_for_deduction (unification_kind_t strict,
19721 tree* parm,
19722 tree* arg,
19723 tree arg_expr)
19725 int result = 0;
19727 switch (strict)
19729 case DEDUCE_CALL:
19730 break;
19732 case DEDUCE_CONV:
19733 /* Swap PARM and ARG throughout the remainder of this
19734 function; the handling is precisely symmetric since PARM
19735 will initialize ARG rather than vice versa. */
19736 std::swap (parm, arg);
19737 break;
19739 case DEDUCE_EXACT:
19740 /* Core issue #873: Do the DR606 thing (see below) for these cases,
19741 too, but here handle it by stripping the reference from PARM
19742 rather than by adding it to ARG. */
19743 if (TYPE_REF_P (*parm)
19744 && TYPE_REF_IS_RVALUE (*parm)
19745 && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19746 && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19747 && TYPE_REF_P (*arg)
19748 && !TYPE_REF_IS_RVALUE (*arg))
19749 *parm = TREE_TYPE (*parm);
19750 /* Nothing else to do in this case. */
19751 return 0;
19753 default:
19754 gcc_unreachable ();
19757 if (!TYPE_REF_P (*parm))
19759 /* [temp.deduct.call]
19761 If P is not a reference type:
19763 --If A is an array type, the pointer type produced by the
19764 array-to-pointer standard conversion (_conv.array_) is
19765 used in place of A for type deduction; otherwise,
19767 --If A is a function type, the pointer type produced by
19768 the function-to-pointer standard conversion
19769 (_conv.func_) is used in place of A for type deduction;
19770 otherwise,
19772 --If A is a cv-qualified type, the top level
19773 cv-qualifiers of A's type are ignored for type
19774 deduction. */
19775 if (TREE_CODE (*arg) == ARRAY_TYPE)
19776 *arg = build_pointer_type (TREE_TYPE (*arg));
19777 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19778 *arg = build_pointer_type (*arg);
19779 else
19780 *arg = TYPE_MAIN_VARIANT (*arg);
19783 /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19784 reference to a cv-unqualified template parameter that does not represent a
19785 template parameter of a class template (during class template argument
19786 deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19787 an lvalue, the type "lvalue reference to A" is used in place of A for type
19788 deduction. */
19789 if (TYPE_REF_P (*parm)
19790 && TYPE_REF_IS_RVALUE (*parm)
19791 && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19792 && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19793 && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19794 && (arg_expr ? lvalue_p (arg_expr)
19795 /* try_one_overload doesn't provide an arg_expr, but
19796 functions are always lvalues. */
19797 : TREE_CODE (*arg) == FUNCTION_TYPE))
19798 *arg = build_reference_type (*arg);
19800 /* [temp.deduct.call]
19802 If P is a cv-qualified type, the top level cv-qualifiers
19803 of P's type are ignored for type deduction. If P is a
19804 reference type, the type referred to by P is used for
19805 type deduction. */
19806 *parm = TYPE_MAIN_VARIANT (*parm);
19807 if (TYPE_REF_P (*parm))
19809 *parm = TREE_TYPE (*parm);
19810 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19813 /* DR 322. For conversion deduction, remove a reference type on parm
19814 too (which has been swapped into ARG). */
19815 if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
19816 *arg = TREE_TYPE (*arg);
19818 return result;
19821 /* Subroutine of unify_one_argument. PARM is a function parameter of a
19822 template which does contain any deducible template parameters; check if
19823 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
19824 unify_one_argument. */
19826 static int
19827 check_non_deducible_conversion (tree parm, tree arg, int strict,
19828 int flags, bool explain_p)
19830 tree type;
19832 if (!TYPE_P (arg))
19833 type = TREE_TYPE (arg);
19834 else
19835 type = arg;
19837 if (same_type_p (parm, type))
19838 return unify_success (explain_p);
19840 if (strict == DEDUCE_CONV)
19842 if (can_convert_arg (type, parm, NULL_TREE, flags,
19843 explain_p ? tf_warning_or_error : tf_none))
19844 return unify_success (explain_p);
19846 else if (strict != DEDUCE_EXACT)
19848 if (can_convert_arg (parm, type,
19849 TYPE_P (arg) ? NULL_TREE : arg,
19850 flags, explain_p ? tf_warning_or_error : tf_none))
19851 return unify_success (explain_p);
19854 if (strict == DEDUCE_EXACT)
19855 return unify_type_mismatch (explain_p, parm, arg);
19856 else
19857 return unify_arg_conversion (explain_p, parm, type, arg);
19860 static bool uses_deducible_template_parms (tree type);
19862 /* Returns true iff the expression EXPR is one from which a template
19863 argument can be deduced. In other words, if it's an undecorated
19864 use of a template non-type parameter. */
19866 static bool
19867 deducible_expression (tree expr)
19869 /* Strip implicit conversions. */
19870 while (CONVERT_EXPR_P (expr))
19871 expr = TREE_OPERAND (expr, 0);
19872 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
19875 /* Returns true iff the array domain DOMAIN uses a template parameter in a
19876 deducible way; that is, if it has a max value of <PARM> - 1. */
19878 static bool
19879 deducible_array_bound (tree domain)
19881 if (domain == NULL_TREE)
19882 return false;
19884 tree max = TYPE_MAX_VALUE (domain);
19885 if (TREE_CODE (max) != MINUS_EXPR)
19886 return false;
19888 return deducible_expression (TREE_OPERAND (max, 0));
19891 /* Returns true iff the template arguments ARGS use a template parameter
19892 in a deducible way. */
19894 static bool
19895 deducible_template_args (tree args)
19897 for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
19899 bool deducible;
19900 tree elt = TREE_VEC_ELT (args, i);
19901 if (ARGUMENT_PACK_P (elt))
19902 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
19903 else
19905 if (PACK_EXPANSION_P (elt))
19906 elt = PACK_EXPANSION_PATTERN (elt);
19907 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
19908 deducible = true;
19909 else if (TYPE_P (elt))
19910 deducible = uses_deducible_template_parms (elt);
19911 else
19912 deducible = deducible_expression (elt);
19914 if (deducible)
19915 return true;
19917 return false;
19920 /* Returns true iff TYPE contains any deducible references to template
19921 parameters, as per 14.8.2.5. */
19923 static bool
19924 uses_deducible_template_parms (tree type)
19926 if (PACK_EXPANSION_P (type))
19927 type = PACK_EXPANSION_PATTERN (type);
19929 /* T
19930 cv-list T
19931 TT<T>
19932 TT<i>
19933 TT<> */
19934 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19935 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19936 return true;
19938 /* T*
19940 T&& */
19941 if (INDIRECT_TYPE_P (type))
19942 return uses_deducible_template_parms (TREE_TYPE (type));
19944 /* T[integer-constant ]
19945 type [i] */
19946 if (TREE_CODE (type) == ARRAY_TYPE)
19947 return (uses_deducible_template_parms (TREE_TYPE (type))
19948 || deducible_array_bound (TYPE_DOMAIN (type)));
19950 /* T type ::*
19951 type T::*
19952 T T::*
19953 T (type ::*)()
19954 type (T::*)()
19955 type (type ::*)(T)
19956 type (T::*)(T)
19957 T (type ::*)(T)
19958 T (T::*)()
19959 T (T::*)(T) */
19960 if (TYPE_PTRMEM_P (type))
19961 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
19962 || (uses_deducible_template_parms
19963 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
19965 /* template-name <T> (where template-name refers to a class template)
19966 template-name <i> (where template-name refers to a class template) */
19967 if (CLASS_TYPE_P (type)
19968 && CLASSTYPE_TEMPLATE_INFO (type)
19969 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
19970 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
19971 (CLASSTYPE_TI_ARGS (type)));
19973 /* type (T)
19975 T(T) */
19976 if (TREE_CODE (type) == FUNCTION_TYPE
19977 || TREE_CODE (type) == METHOD_TYPE)
19979 if (uses_deducible_template_parms (TREE_TYPE (type)))
19980 return true;
19981 tree parm = TYPE_ARG_TYPES (type);
19982 if (TREE_CODE (type) == METHOD_TYPE)
19983 parm = TREE_CHAIN (parm);
19984 for (; parm; parm = TREE_CHAIN (parm))
19985 if (uses_deducible_template_parms (TREE_VALUE (parm)))
19986 return true;
19989 return false;
19992 /* Subroutine of type_unification_real and unify_pack_expansion to
19993 handle unification of a single P/A pair. Parameters are as
19994 for those functions. */
19996 static int
19997 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
19998 int subr, unification_kind_t strict,
19999 bool explain_p)
20001 tree arg_expr = NULL_TREE;
20002 int arg_strict;
20004 if (arg == error_mark_node || parm == error_mark_node)
20005 return unify_invalid (explain_p);
20006 if (arg == unknown_type_node)
20007 /* We can't deduce anything from this, but we might get all the
20008 template args from other function args. */
20009 return unify_success (explain_p);
20011 /* Implicit conversions (Clause 4) will be performed on a function
20012 argument to convert it to the type of the corresponding function
20013 parameter if the parameter type contains no template-parameters that
20014 participate in template argument deduction. */
20015 if (strict != DEDUCE_EXACT
20016 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
20017 /* For function parameters with no deducible template parameters,
20018 just return. We'll check non-dependent conversions later. */
20019 return unify_success (explain_p);
20021 switch (strict)
20023 case DEDUCE_CALL:
20024 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20025 | UNIFY_ALLOW_MORE_CV_QUAL
20026 | UNIFY_ALLOW_DERIVED);
20027 break;
20029 case DEDUCE_CONV:
20030 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20031 break;
20033 case DEDUCE_EXACT:
20034 arg_strict = UNIFY_ALLOW_NONE;
20035 break;
20037 default:
20038 gcc_unreachable ();
20041 /* We only do these transformations if this is the top-level
20042 parameter_type_list in a call or declaration matching; in other
20043 situations (nested function declarators, template argument lists) we
20044 won't be comparing a type to an expression, and we don't do any type
20045 adjustments. */
20046 if (!subr)
20048 if (!TYPE_P (arg))
20050 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20051 if (type_unknown_p (arg))
20053 /* [temp.deduct.type] A template-argument can be
20054 deduced from a pointer to function or pointer
20055 to member function argument if the set of
20056 overloaded functions does not contain function
20057 templates and at most one of a set of
20058 overloaded functions provides a unique
20059 match. */
20060 resolve_overloaded_unification (tparms, targs, parm,
20061 arg, strict,
20062 arg_strict, explain_p);
20063 /* If a unique match was not found, this is a
20064 non-deduced context, so we still succeed. */
20065 return unify_success (explain_p);
20068 arg_expr = arg;
20069 arg = unlowered_expr_type (arg);
20070 if (arg == error_mark_node)
20071 return unify_invalid (explain_p);
20074 arg_strict |=
20075 maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20077 else
20078 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20079 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20080 return unify_template_argument_mismatch (explain_p, parm, arg);
20082 /* For deduction from an init-list we need the actual list. */
20083 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20084 arg = arg_expr;
20085 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20088 /* for_each_template_parm callback that always returns 0. */
20090 static int
20091 zero_r (tree, void *)
20093 return 0;
20096 /* for_each_template_parm any_fn callback to handle deduction of a template
20097 type argument from the type of an array bound. */
20099 static int
20100 array_deduction_r (tree t, void *data)
20102 tree_pair_p d = (tree_pair_p)data;
20103 tree &tparms = d->purpose;
20104 tree &targs = d->value;
20106 if (TREE_CODE (t) == ARRAY_TYPE)
20107 if (tree dom = TYPE_DOMAIN (t))
20108 if (tree max = TYPE_MAX_VALUE (dom))
20110 if (TREE_CODE (max) == MINUS_EXPR)
20111 max = TREE_OPERAND (max, 0);
20112 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20113 unify (tparms, targs, TREE_TYPE (max), size_type_node,
20114 UNIFY_ALLOW_NONE, /*explain*/false);
20117 /* Keep walking. */
20118 return 0;
20121 /* Try to deduce any not-yet-deduced template type arguments from the type of
20122 an array bound. This is handled separately from unify because 14.8.2.5 says
20123 "The type of a type parameter is only deduced from an array bound if it is
20124 not otherwise deduced." */
20126 static void
20127 try_array_deduction (tree tparms, tree targs, tree parm)
20129 tree_pair_s data = { tparms, targs };
20130 hash_set<tree> visited;
20131 for_each_template_parm (parm, zero_r, &data, &visited,
20132 /*nondeduced*/false, array_deduction_r);
20135 /* Most parms like fn_type_unification.
20137 If SUBR is 1, we're being called recursively (to unify the
20138 arguments of a function or method parameter of a function
20139 template).
20141 CHECKS is a pointer to a vector of access checks encountered while
20142 substituting default template arguments. */
20144 static int
20145 type_unification_real (tree tparms,
20146 tree full_targs,
20147 tree xparms,
20148 const tree *xargs,
20149 unsigned int xnargs,
20150 int subr,
20151 unification_kind_t strict,
20152 int flags,
20153 vec<deferred_access_check, va_gc> **checks,
20154 bool explain_p)
20156 tree parm, arg;
20157 int i;
20158 int ntparms = TREE_VEC_LENGTH (tparms);
20159 int saw_undeduced = 0;
20160 tree parms;
20161 const tree *args;
20162 unsigned int nargs;
20163 unsigned int ia;
20165 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20166 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20167 gcc_assert (ntparms > 0);
20169 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20171 /* Reset the number of non-defaulted template arguments contained
20172 in TARGS. */
20173 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20175 again:
20176 parms = xparms;
20177 args = xargs;
20178 nargs = xnargs;
20180 ia = 0;
20181 while (parms && parms != void_list_node
20182 && ia < nargs)
20184 parm = TREE_VALUE (parms);
20186 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20187 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20188 /* For a function parameter pack that occurs at the end of the
20189 parameter-declaration-list, the type A of each remaining
20190 argument of the call is compared with the type P of the
20191 declarator-id of the function parameter pack. */
20192 break;
20194 parms = TREE_CHAIN (parms);
20196 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20197 /* For a function parameter pack that does not occur at the
20198 end of the parameter-declaration-list, the type of the
20199 parameter pack is a non-deduced context. */
20200 continue;
20202 arg = args[ia];
20203 ++ia;
20205 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20206 explain_p))
20207 return 1;
20210 if (parms
20211 && parms != void_list_node
20212 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20214 /* Unify the remaining arguments with the pack expansion type. */
20215 tree argvec;
20216 tree parmvec = make_tree_vec (1);
20218 /* Allocate a TREE_VEC and copy in all of the arguments */
20219 argvec = make_tree_vec (nargs - ia);
20220 for (i = 0; ia < nargs; ++ia, ++i)
20221 TREE_VEC_ELT (argvec, i) = args[ia];
20223 /* Copy the parameter into parmvec. */
20224 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20225 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20226 /*subr=*/subr, explain_p))
20227 return 1;
20229 /* Advance to the end of the list of parameters. */
20230 parms = TREE_CHAIN (parms);
20233 /* Fail if we've reached the end of the parm list, and more args
20234 are present, and the parm list isn't variadic. */
20235 if (ia < nargs && parms == void_list_node)
20236 return unify_too_many_arguments (explain_p, nargs, ia);
20237 /* Fail if parms are left and they don't have default values and
20238 they aren't all deduced as empty packs (c++/57397). This is
20239 consistent with sufficient_parms_p. */
20240 if (parms && parms != void_list_node
20241 && TREE_PURPOSE (parms) == NULL_TREE)
20243 unsigned int count = nargs;
20244 tree p = parms;
20245 bool type_pack_p;
20248 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20249 if (!type_pack_p)
20250 count++;
20251 p = TREE_CHAIN (p);
20253 while (p && p != void_list_node);
20254 if (count != nargs)
20255 return unify_too_few_arguments (explain_p, ia, count,
20256 type_pack_p);
20259 if (!subr)
20261 tsubst_flags_t complain = (explain_p
20262 ? tf_warning_or_error
20263 : tf_none);
20264 bool tried_array_deduction = (cxx_dialect < cxx17);
20266 for (i = 0; i < ntparms; i++)
20268 tree targ = TREE_VEC_ELT (targs, i);
20269 tree tparm = TREE_VEC_ELT (tparms, i);
20271 /* Clear the "incomplete" flags on all argument packs now so that
20272 substituting them into later default arguments works. */
20273 if (targ && ARGUMENT_PACK_P (targ))
20275 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20276 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20279 if (targ || tparm == error_mark_node)
20280 continue;
20281 tparm = TREE_VALUE (tparm);
20283 if (TREE_CODE (tparm) == TYPE_DECL
20284 && !tried_array_deduction)
20286 try_array_deduction (tparms, targs, xparms);
20287 tried_array_deduction = true;
20288 if (TREE_VEC_ELT (targs, i))
20289 continue;
20292 /* If this is an undeduced nontype parameter that depends on
20293 a type parameter, try another pass; its type may have been
20294 deduced from a later argument than the one from which
20295 this parameter can be deduced. */
20296 if (TREE_CODE (tparm) == PARM_DECL
20297 && uses_template_parms (TREE_TYPE (tparm))
20298 && saw_undeduced < 2)
20300 saw_undeduced = 1;
20301 continue;
20304 /* Core issue #226 (C++0x) [temp.deduct]:
20306 If a template argument has not been deduced, its
20307 default template argument, if any, is used.
20309 When we are in C++98 mode, TREE_PURPOSE will either
20310 be NULL_TREE or ERROR_MARK_NODE, so we do not need
20311 to explicitly check cxx_dialect here. */
20312 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
20313 /* OK, there is a default argument. Wait until after the
20314 conversion check to do substitution. */
20315 continue;
20317 /* If the type parameter is a parameter pack, then it will
20318 be deduced to an empty parameter pack. */
20319 if (template_parameter_pack_p (tparm))
20321 tree arg;
20323 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
20325 arg = make_node (NONTYPE_ARGUMENT_PACK);
20326 TREE_CONSTANT (arg) = 1;
20328 else
20329 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
20331 SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
20333 TREE_VEC_ELT (targs, i) = arg;
20334 continue;
20337 return unify_parameter_deduction_failure (explain_p, tparm);
20340 /* DR 1391: All parameters have args, now check non-dependent parms for
20341 convertibility. */
20342 if (saw_undeduced < 2)
20343 for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
20344 parms && parms != void_list_node && ia < nargs; )
20346 parm = TREE_VALUE (parms);
20348 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20349 && (!TREE_CHAIN (parms)
20350 || TREE_CHAIN (parms) == void_list_node))
20351 /* For a function parameter pack that occurs at the end of the
20352 parameter-declaration-list, the type A of each remaining
20353 argument of the call is compared with the type P of the
20354 declarator-id of the function parameter pack. */
20355 break;
20357 parms = TREE_CHAIN (parms);
20359 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20360 /* For a function parameter pack that does not occur at the
20361 end of the parameter-declaration-list, the type of the
20362 parameter pack is a non-deduced context. */
20363 continue;
20365 arg = args[ia];
20366 ++ia;
20368 if (uses_template_parms (parm))
20369 continue;
20370 if (check_non_deducible_conversion (parm, arg, strict, flags,
20371 explain_p))
20372 return 1;
20375 /* Now substitute into the default template arguments. */
20376 for (i = 0; i < ntparms; i++)
20378 tree targ = TREE_VEC_ELT (targs, i);
20379 tree tparm = TREE_VEC_ELT (tparms, i);
20381 if (targ || tparm == error_mark_node)
20382 continue;
20383 tree parm = TREE_VALUE (tparm);
20384 tree arg = TREE_PURPOSE (tparm);
20385 reopen_deferring_access_checks (*checks);
20386 location_t save_loc = input_location;
20387 if (DECL_P (parm))
20388 input_location = DECL_SOURCE_LOCATION (parm);
20390 if (saw_undeduced == 1
20391 && TREE_CODE (parm) == PARM_DECL
20392 && uses_template_parms (TREE_TYPE (parm)))
20394 /* The type of this non-type parameter depends on undeduced
20395 parameters. Don't try to use its default argument yet,
20396 since we might deduce an argument for it on the next pass,
20397 but do check whether the arguments we already have cause
20398 substitution failure, so that that happens before we try
20399 later default arguments (78489). */
20400 ++processing_template_decl;
20401 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
20402 NULL_TREE);
20403 --processing_template_decl;
20404 if (type == error_mark_node)
20405 arg = error_mark_node;
20406 else
20407 arg = NULL_TREE;
20409 else
20411 tree substed = NULL_TREE;
20412 if (saw_undeduced == 1 && processing_template_decl == 0)
20414 /* First instatiate in template context, in case we still
20415 depend on undeduced template parameters. */
20416 ++processing_template_decl;
20417 substed = tsubst_template_arg (arg, full_targs, complain,
20418 NULL_TREE);
20419 --processing_template_decl;
20420 if (substed != error_mark_node
20421 && !uses_template_parms (substed))
20422 /* We replaced all the tparms, substitute again out of
20423 template context. */
20424 substed = NULL_TREE;
20426 if (!substed)
20427 substed = tsubst_template_arg (arg, full_targs, complain,
20428 NULL_TREE);
20430 if (!uses_template_parms (substed))
20431 arg = convert_template_argument (parm, substed, full_targs,
20432 complain, i, NULL_TREE);
20433 else if (saw_undeduced == 1)
20434 arg = NULL_TREE;
20435 else
20436 arg = error_mark_node;
20439 input_location = save_loc;
20440 *checks = get_deferred_access_checks ();
20441 pop_deferring_access_checks ();
20443 if (arg == error_mark_node)
20444 return 1;
20445 else if (arg)
20447 TREE_VEC_ELT (targs, i) = arg;
20448 /* The position of the first default template argument,
20449 is also the number of non-defaulted arguments in TARGS.
20450 Record that. */
20451 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20452 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20456 if (saw_undeduced++ == 1)
20457 goto again;
20460 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20461 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20463 return unify_success (explain_p);
20466 /* Subroutine of type_unification_real. Args are like the variables
20467 at the call site. ARG is an overloaded function (or template-id);
20468 we try deducing template args from each of the overloads, and if
20469 only one succeeds, we go with that. Modifies TARGS and returns
20470 true on success. */
20472 static bool
20473 resolve_overloaded_unification (tree tparms,
20474 tree targs,
20475 tree parm,
20476 tree arg,
20477 unification_kind_t strict,
20478 int sub_strict,
20479 bool explain_p)
20481 tree tempargs = copy_node (targs);
20482 int good = 0;
20483 tree goodfn = NULL_TREE;
20484 bool addr_p;
20486 if (TREE_CODE (arg) == ADDR_EXPR)
20488 arg = TREE_OPERAND (arg, 0);
20489 addr_p = true;
20491 else
20492 addr_p = false;
20494 if (TREE_CODE (arg) == COMPONENT_REF)
20495 /* Handle `&x' where `x' is some static or non-static member
20496 function name. */
20497 arg = TREE_OPERAND (arg, 1);
20499 if (TREE_CODE (arg) == OFFSET_REF)
20500 arg = TREE_OPERAND (arg, 1);
20502 /* Strip baselink information. */
20503 if (BASELINK_P (arg))
20504 arg = BASELINK_FUNCTIONS (arg);
20506 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20508 /* If we got some explicit template args, we need to plug them into
20509 the affected templates before we try to unify, in case the
20510 explicit args will completely resolve the templates in question. */
20512 int ok = 0;
20513 tree expl_subargs = TREE_OPERAND (arg, 1);
20514 arg = TREE_OPERAND (arg, 0);
20516 for (lkp_iterator iter (arg); iter; ++iter)
20518 tree fn = *iter;
20519 tree subargs, elem;
20521 if (TREE_CODE (fn) != TEMPLATE_DECL)
20522 continue;
20524 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20525 expl_subargs, NULL_TREE, tf_none,
20526 /*require_all_args=*/true,
20527 /*use_default_args=*/true);
20528 if (subargs != error_mark_node
20529 && !any_dependent_template_arguments_p (subargs))
20531 elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20532 if (try_one_overload (tparms, targs, tempargs, parm,
20533 elem, strict, sub_strict, addr_p, explain_p)
20534 && (!goodfn || !same_type_p (goodfn, elem)))
20536 goodfn = elem;
20537 ++good;
20540 else if (subargs)
20541 ++ok;
20543 /* If no templates (or more than one) are fully resolved by the
20544 explicit arguments, this template-id is a non-deduced context; it
20545 could still be OK if we deduce all template arguments for the
20546 enclosing call through other arguments. */
20547 if (good != 1)
20548 good = ok;
20550 else if (TREE_CODE (arg) != OVERLOAD
20551 && TREE_CODE (arg) != FUNCTION_DECL)
20552 /* If ARG is, for example, "(0, &f)" then its type will be unknown
20553 -- but the deduction does not succeed because the expression is
20554 not just the function on its own. */
20555 return false;
20556 else
20557 for (lkp_iterator iter (arg); iter; ++iter)
20559 tree fn = *iter;
20560 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20561 strict, sub_strict, addr_p, explain_p)
20562 && (!goodfn || !decls_match (goodfn, fn)))
20564 goodfn = fn;
20565 ++good;
20569 /* [temp.deduct.type] A template-argument can be deduced from a pointer
20570 to function or pointer to member function argument if the set of
20571 overloaded functions does not contain function templates and at most
20572 one of a set of overloaded functions provides a unique match.
20574 So if we found multiple possibilities, we return success but don't
20575 deduce anything. */
20577 if (good == 1)
20579 int i = TREE_VEC_LENGTH (targs);
20580 for (; i--; )
20581 if (TREE_VEC_ELT (tempargs, i))
20583 tree old = TREE_VEC_ELT (targs, i);
20584 tree new_ = TREE_VEC_ELT (tempargs, i);
20585 if (new_ && old && ARGUMENT_PACK_P (old)
20586 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
20587 /* Don't forget explicit template arguments in a pack. */
20588 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20589 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
20590 TREE_VEC_ELT (targs, i) = new_;
20593 if (good)
20594 return true;
20596 return false;
20599 /* Core DR 115: In contexts where deduction is done and fails, or in
20600 contexts where deduction is not done, if a template argument list is
20601 specified and it, along with any default template arguments, identifies
20602 a single function template specialization, then the template-id is an
20603 lvalue for the function template specialization. */
20605 tree
20606 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20608 tree expr, offset, baselink;
20609 bool addr;
20611 if (!type_unknown_p (orig_expr))
20612 return orig_expr;
20614 expr = orig_expr;
20615 addr = false;
20616 offset = NULL_TREE;
20617 baselink = NULL_TREE;
20619 if (TREE_CODE (expr) == ADDR_EXPR)
20621 expr = TREE_OPERAND (expr, 0);
20622 addr = true;
20624 if (TREE_CODE (expr) == OFFSET_REF)
20626 offset = expr;
20627 expr = TREE_OPERAND (expr, 1);
20629 if (BASELINK_P (expr))
20631 baselink = expr;
20632 expr = BASELINK_FUNCTIONS (expr);
20635 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20637 int good = 0;
20638 tree goodfn = NULL_TREE;
20640 /* If we got some explicit template args, we need to plug them into
20641 the affected templates before we try to unify, in case the
20642 explicit args will completely resolve the templates in question. */
20644 tree expl_subargs = TREE_OPERAND (expr, 1);
20645 tree arg = TREE_OPERAND (expr, 0);
20646 tree badfn = NULL_TREE;
20647 tree badargs = NULL_TREE;
20649 for (lkp_iterator iter (arg); iter; ++iter)
20651 tree fn = *iter;
20652 tree subargs, elem;
20654 if (TREE_CODE (fn) != TEMPLATE_DECL)
20655 continue;
20657 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20658 expl_subargs, NULL_TREE, tf_none,
20659 /*require_all_args=*/true,
20660 /*use_default_args=*/true);
20661 if (subargs != error_mark_node
20662 && !any_dependent_template_arguments_p (subargs))
20664 elem = instantiate_template (fn, subargs, tf_none);
20665 if (elem == error_mark_node)
20667 badfn = fn;
20668 badargs = subargs;
20670 else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20672 goodfn = elem;
20673 ++good;
20677 if (good == 1)
20679 mark_used (goodfn);
20680 expr = goodfn;
20681 if (baselink)
20682 expr = build_baselink (BASELINK_BINFO (baselink),
20683 BASELINK_ACCESS_BINFO (baselink),
20684 expr, BASELINK_OPTYPE (baselink));
20685 if (offset)
20687 tree base
20688 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20689 expr = build_offset_ref (base, expr, addr, complain);
20691 if (addr)
20692 expr = cp_build_addr_expr (expr, complain);
20693 return expr;
20695 else if (good == 0 && badargs && (complain & tf_error))
20696 /* There were no good options and at least one bad one, so let the
20697 user know what the problem is. */
20698 instantiate_template (badfn, badargs, complain);
20700 return orig_expr;
20703 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20704 overload. Fills TARGS with any deduced arguments, or error_mark_node if
20705 different overloads deduce different arguments for a given parm.
20706 ADDR_P is true if the expression for which deduction is being
20707 performed was of the form "& fn" rather than simply "fn".
20709 Returns 1 on success. */
20711 static int
20712 try_one_overload (tree tparms,
20713 tree orig_targs,
20714 tree targs,
20715 tree parm,
20716 tree arg,
20717 unification_kind_t strict,
20718 int sub_strict,
20719 bool addr_p,
20720 bool explain_p)
20722 int nargs;
20723 tree tempargs;
20724 int i;
20726 if (arg == error_mark_node)
20727 return 0;
20729 /* [temp.deduct.type] A template-argument can be deduced from a pointer
20730 to function or pointer to member function argument if the set of
20731 overloaded functions does not contain function templates and at most
20732 one of a set of overloaded functions provides a unique match.
20734 So if this is a template, just return success. */
20736 if (uses_template_parms (arg))
20737 return 1;
20739 if (TREE_CODE (arg) == METHOD_TYPE)
20740 arg = build_ptrmemfunc_type (build_pointer_type (arg));
20741 else if (addr_p)
20742 arg = build_pointer_type (arg);
20744 sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20746 /* We don't copy orig_targs for this because if we have already deduced
20747 some template args from previous args, unify would complain when we
20748 try to deduce a template parameter for the same argument, even though
20749 there isn't really a conflict. */
20750 nargs = TREE_VEC_LENGTH (targs);
20751 tempargs = make_tree_vec (nargs);
20753 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20754 return 0;
20756 /* First make sure we didn't deduce anything that conflicts with
20757 explicitly specified args. */
20758 for (i = nargs; i--; )
20760 tree elt = TREE_VEC_ELT (tempargs, i);
20761 tree oldelt = TREE_VEC_ELT (orig_targs, i);
20763 if (!elt)
20764 /*NOP*/;
20765 else if (uses_template_parms (elt))
20766 /* Since we're unifying against ourselves, we will fill in
20767 template args used in the function parm list with our own
20768 template parms. Discard them. */
20769 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20770 else if (oldelt && ARGUMENT_PACK_P (oldelt))
20772 /* Check that the argument at each index of the deduced argument pack
20773 is equivalent to the corresponding explicitly specified argument.
20774 We may have deduced more arguments than were explicitly specified,
20775 and that's OK. */
20777 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20778 that's wrong if we deduce the same argument pack from multiple
20779 function arguments: it's only incomplete the first time. */
20781 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20782 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20784 if (TREE_VEC_LENGTH (deduced_pack)
20785 < TREE_VEC_LENGTH (explicit_pack))
20786 return 0;
20788 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20789 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20790 TREE_VEC_ELT (deduced_pack, j)))
20791 return 0;
20793 else if (oldelt && !template_args_equal (oldelt, elt))
20794 return 0;
20797 for (i = nargs; i--; )
20799 tree elt = TREE_VEC_ELT (tempargs, i);
20801 if (elt)
20802 TREE_VEC_ELT (targs, i) = elt;
20805 return 1;
20808 /* PARM is a template class (perhaps with unbound template
20809 parameters). ARG is a fully instantiated type. If ARG can be
20810 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
20811 TARGS are as for unify. */
20813 static tree
20814 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20815 bool explain_p)
20817 tree copy_of_targs;
20819 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
20820 return NULL_TREE;
20821 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20822 /* Matches anything. */;
20823 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
20824 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
20825 return NULL_TREE;
20827 /* We need to make a new template argument vector for the call to
20828 unify. If we used TARGS, we'd clutter it up with the result of
20829 the attempted unification, even if this class didn't work out.
20830 We also don't want to commit ourselves to all the unifications
20831 we've already done, since unification is supposed to be done on
20832 an argument-by-argument basis. In other words, consider the
20833 following pathological case:
20835 template <int I, int J, int K>
20836 struct S {};
20838 template <int I, int J>
20839 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
20841 template <int I, int J, int K>
20842 void f(S<I, J, K>, S<I, I, I>);
20844 void g() {
20845 S<0, 0, 0> s0;
20846 S<0, 1, 2> s2;
20848 f(s0, s2);
20851 Now, by the time we consider the unification involving `s2', we
20852 already know that we must have `f<0, 0, 0>'. But, even though
20853 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
20854 because there are two ways to unify base classes of S<0, 1, 2>
20855 with S<I, I, I>. If we kept the already deduced knowledge, we
20856 would reject the possibility I=1. */
20857 copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
20859 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20861 if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
20862 return NULL_TREE;
20863 return arg;
20866 /* If unification failed, we're done. */
20867 if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
20868 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
20869 return NULL_TREE;
20871 return arg;
20874 /* Given a template type PARM and a class type ARG, find the unique
20875 base type in ARG that is an instance of PARM. We do not examine
20876 ARG itself; only its base-classes. If there is not exactly one
20877 appropriate base class, return NULL_TREE. PARM may be the type of
20878 a partial specialization, as well as a plain template type. Used
20879 by unify. */
20881 static enum template_base_result
20882 get_template_base (tree tparms, tree targs, tree parm, tree arg,
20883 bool explain_p, tree *result)
20885 tree rval = NULL_TREE;
20886 tree binfo;
20888 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
20890 binfo = TYPE_BINFO (complete_type (arg));
20891 if (!binfo)
20893 /* The type could not be completed. */
20894 *result = NULL_TREE;
20895 return tbr_incomplete_type;
20898 /* Walk in inheritance graph order. The search order is not
20899 important, and this avoids multiple walks of virtual bases. */
20900 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
20902 tree r = try_class_unification (tparms, targs, parm,
20903 BINFO_TYPE (binfo), explain_p);
20905 if (r)
20907 /* If there is more than one satisfactory baseclass, then:
20909 [temp.deduct.call]
20911 If they yield more than one possible deduced A, the type
20912 deduction fails.
20914 applies. */
20915 if (rval && !same_type_p (r, rval))
20917 *result = NULL_TREE;
20918 return tbr_ambiguous_baseclass;
20921 rval = r;
20925 *result = rval;
20926 return tbr_success;
20929 /* Returns the level of DECL, which declares a template parameter. */
20931 static int
20932 template_decl_level (tree decl)
20934 switch (TREE_CODE (decl))
20936 case TYPE_DECL:
20937 case TEMPLATE_DECL:
20938 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
20940 case PARM_DECL:
20941 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
20943 default:
20944 gcc_unreachable ();
20946 return 0;
20949 /* Decide whether ARG can be unified with PARM, considering only the
20950 cv-qualifiers of each type, given STRICT as documented for unify.
20951 Returns nonzero iff the unification is OK on that basis. */
20953 static int
20954 check_cv_quals_for_unify (int strict, tree arg, tree parm)
20956 int arg_quals = cp_type_quals (arg);
20957 int parm_quals = cp_type_quals (parm);
20959 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20960 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
20962 /* Although a CVR qualifier is ignored when being applied to a
20963 substituted template parameter ([8.3.2]/1 for example), that
20964 does not allow us to unify "const T" with "int&" because both
20965 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
20966 It is ok when we're allowing additional CV qualifiers
20967 at the outer level [14.8.2.1]/3,1st bullet. */
20968 if ((TYPE_REF_P (arg)
20969 || TREE_CODE (arg) == FUNCTION_TYPE
20970 || TREE_CODE (arg) == METHOD_TYPE)
20971 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
20972 return 0;
20974 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
20975 && (parm_quals & TYPE_QUAL_RESTRICT))
20976 return 0;
20979 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
20980 && (arg_quals & parm_quals) != parm_quals)
20981 return 0;
20983 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
20984 && (parm_quals & arg_quals) != arg_quals)
20985 return 0;
20987 return 1;
20990 /* Determines the LEVEL and INDEX for the template parameter PARM. */
20991 void
20992 template_parm_level_and_index (tree parm, int* level, int* index)
20994 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20995 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
20996 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20998 *index = TEMPLATE_TYPE_IDX (parm);
20999 *level = TEMPLATE_TYPE_LEVEL (parm);
21001 else
21003 *index = TEMPLATE_PARM_IDX (parm);
21004 *level = TEMPLATE_PARM_LEVEL (parm);
21008 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
21009 do { \
21010 if (unify (TP, TA, P, A, S, EP)) \
21011 return 1; \
21012 } while (0)
21014 /* Unifies the remaining arguments in PACKED_ARGS with the pack
21015 expansion at the end of PACKED_PARMS. Returns 0 if the type
21016 deduction succeeds, 1 otherwise. STRICT is the same as in
21017 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
21018 function call argument list. We'll need to adjust the arguments to make them
21019 types. SUBR tells us if this is from a recursive call to
21020 type_unification_real, or for comparing two template argument
21021 lists. */
21023 static int
21024 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
21025 tree packed_args, unification_kind_t strict,
21026 bool subr, bool explain_p)
21028 tree parm
21029 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
21030 tree pattern = PACK_EXPANSION_PATTERN (parm);
21031 tree pack, packs = NULL_TREE;
21032 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
21034 /* Add in any args remembered from an earlier partial instantiation. */
21035 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21036 int levels = TMPL_ARGS_DEPTH (targs);
21038 packed_args = expand_template_argument_pack (packed_args);
21040 int len = TREE_VEC_LENGTH (packed_args);
21042 /* Determine the parameter packs we will be deducing from the
21043 pattern, and record their current deductions. */
21044 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21045 pack; pack = TREE_CHAIN (pack))
21047 tree parm_pack = TREE_VALUE (pack);
21048 int idx, level;
21050 /* Only template parameter packs can be deduced, not e.g. function
21051 parameter packs or __bases or __integer_pack. */
21052 if (!TEMPLATE_PARM_P (parm_pack))
21053 continue;
21055 /* Determine the index and level of this parameter pack. */
21056 template_parm_level_and_index (parm_pack, &level, &idx);
21057 if (level < levels)
21058 continue;
21060 /* Keep track of the parameter packs and their corresponding
21061 argument packs. */
21062 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21063 TREE_TYPE (packs) = make_tree_vec (len - start);
21066 /* Loop through all of the arguments that have not yet been
21067 unified and unify each with the pattern. */
21068 for (i = start; i < len; i++)
21070 tree parm;
21071 bool any_explicit = false;
21072 tree arg = TREE_VEC_ELT (packed_args, i);
21074 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21075 or the element of its argument pack at the current index if
21076 this argument was explicitly specified. */
21077 for (pack = packs; pack; pack = TREE_CHAIN (pack))
21079 int idx, level;
21080 tree arg, pargs;
21081 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21083 arg = NULL_TREE;
21084 if (TREE_VALUE (pack)
21085 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21086 && (i - start < TREE_VEC_LENGTH (pargs)))
21088 any_explicit = true;
21089 arg = TREE_VEC_ELT (pargs, i - start);
21091 TMPL_ARG (targs, level, idx) = arg;
21094 /* If we had explicit template arguments, substitute them into the
21095 pattern before deduction. */
21096 if (any_explicit)
21098 /* Some arguments might still be unspecified or dependent. */
21099 bool dependent;
21100 ++processing_template_decl;
21101 dependent = any_dependent_template_arguments_p (targs);
21102 if (!dependent)
21103 --processing_template_decl;
21104 parm = tsubst (pattern, targs,
21105 explain_p ? tf_warning_or_error : tf_none,
21106 NULL_TREE);
21107 if (dependent)
21108 --processing_template_decl;
21109 if (parm == error_mark_node)
21110 return 1;
21112 else
21113 parm = pattern;
21115 /* Unify the pattern with the current argument. */
21116 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21117 explain_p))
21118 return 1;
21120 /* For each parameter pack, collect the deduced value. */
21121 for (pack = packs; pack; pack = TREE_CHAIN (pack))
21123 int idx, level;
21124 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21126 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
21127 TMPL_ARG (targs, level, idx);
21131 /* Verify that the results of unification with the parameter packs
21132 produce results consistent with what we've seen before, and make
21133 the deduced argument packs available. */
21134 for (pack = packs; pack; pack = TREE_CHAIN (pack))
21136 tree old_pack = TREE_VALUE (pack);
21137 tree new_args = TREE_TYPE (pack);
21138 int i, len = TREE_VEC_LENGTH (new_args);
21139 int idx, level;
21140 bool nondeduced_p = false;
21142 /* By default keep the original deduced argument pack.
21143 If necessary, more specific code is going to update the
21144 resulting deduced argument later down in this function. */
21145 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21146 TMPL_ARG (targs, level, idx) = old_pack;
21148 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21149 actually deduce anything. */
21150 for (i = 0; i < len && !nondeduced_p; ++i)
21151 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21152 nondeduced_p = true;
21153 if (nondeduced_p)
21154 continue;
21156 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21158 /* If we had fewer function args than explicit template args,
21159 just use the explicits. */
21160 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21161 int explicit_len = TREE_VEC_LENGTH (explicit_args);
21162 if (len < explicit_len)
21163 new_args = explicit_args;
21166 if (!old_pack)
21168 tree result;
21169 /* Build the deduced *_ARGUMENT_PACK. */
21170 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21172 result = make_node (NONTYPE_ARGUMENT_PACK);
21173 TREE_CONSTANT (result) = 1;
21175 else
21176 result = cxx_make_type (TYPE_ARGUMENT_PACK);
21178 SET_ARGUMENT_PACK_ARGS (result, new_args);
21180 /* Note the deduced argument packs for this parameter
21181 pack. */
21182 TMPL_ARG (targs, level, idx) = result;
21184 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21185 && (ARGUMENT_PACK_ARGS (old_pack)
21186 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21188 /* We only had the explicitly-provided arguments before, but
21189 now we have a complete set of arguments. */
21190 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21192 SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21193 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21194 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21196 else
21198 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21199 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21201 if (!comp_template_args (old_args, new_args,
21202 &bad_old_arg, &bad_new_arg))
21203 /* Inconsistent unification of this parameter pack. */
21204 return unify_parameter_pack_inconsistent (explain_p,
21205 bad_old_arg,
21206 bad_new_arg);
21210 return unify_success (explain_p);
21213 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
21214 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
21215 parameters and return value are as for unify. */
21217 static int
21218 unify_array_domain (tree tparms, tree targs,
21219 tree parm_dom, tree arg_dom,
21220 bool explain_p)
21222 tree parm_max;
21223 tree arg_max;
21224 bool parm_cst;
21225 bool arg_cst;
21227 /* Our representation of array types uses "N - 1" as the
21228 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21229 not an integer constant. We cannot unify arbitrarily
21230 complex expressions, so we eliminate the MINUS_EXPRs
21231 here. */
21232 parm_max = TYPE_MAX_VALUE (parm_dom);
21233 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21234 if (!parm_cst)
21236 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21237 parm_max = TREE_OPERAND (parm_max, 0);
21239 arg_max = TYPE_MAX_VALUE (arg_dom);
21240 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21241 if (!arg_cst)
21243 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21244 trying to unify the type of a variable with the type
21245 of a template parameter. For example:
21247 template <unsigned int N>
21248 void f (char (&) [N]);
21249 int g();
21250 void h(int i) {
21251 char a[g(i)];
21252 f(a);
21255 Here, the type of the ARG will be "int [g(i)]", and
21256 may be a SAVE_EXPR, etc. */
21257 if (TREE_CODE (arg_max) != MINUS_EXPR)
21258 return unify_vla_arg (explain_p, arg_dom);
21259 arg_max = TREE_OPERAND (arg_max, 0);
21262 /* If only one of the bounds used a MINUS_EXPR, compensate
21263 by adding one to the other bound. */
21264 if (parm_cst && !arg_cst)
21265 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21266 integer_type_node,
21267 parm_max,
21268 integer_one_node);
21269 else if (arg_cst && !parm_cst)
21270 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21271 integer_type_node,
21272 arg_max,
21273 integer_one_node);
21275 return unify (tparms, targs, parm_max, arg_max,
21276 UNIFY_ALLOW_INTEGER, explain_p);
21279 /* Returns whether T, a P or A in unify, is a type, template or expression. */
21281 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21283 static pa_kind_t
21284 pa_kind (tree t)
21286 if (PACK_EXPANSION_P (t))
21287 t = PACK_EXPANSION_PATTERN (t);
21288 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21289 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21290 || DECL_TYPE_TEMPLATE_P (t))
21291 return pa_tmpl;
21292 else if (TYPE_P (t))
21293 return pa_type;
21294 else
21295 return pa_expr;
21298 /* Deduce the value of template parameters. TPARMS is the (innermost)
21299 set of template parameters to a template. TARGS is the bindings
21300 for those template parameters, as determined thus far; TARGS may
21301 include template arguments for outer levels of template parameters
21302 as well. PARM is a parameter to a template function, or a
21303 subcomponent of that parameter; ARG is the corresponding argument.
21304 This function attempts to match PARM with ARG in a manner
21305 consistent with the existing assignments in TARGS. If more values
21306 are deduced, then TARGS is updated.
21308 Returns 0 if the type deduction succeeds, 1 otherwise. The
21309 parameter STRICT is a bitwise or of the following flags:
21311 UNIFY_ALLOW_NONE:
21312 Require an exact match between PARM and ARG.
21313 UNIFY_ALLOW_MORE_CV_QUAL:
21314 Allow the deduced ARG to be more cv-qualified (by qualification
21315 conversion) than ARG.
21316 UNIFY_ALLOW_LESS_CV_QUAL:
21317 Allow the deduced ARG to be less cv-qualified than ARG.
21318 UNIFY_ALLOW_DERIVED:
21319 Allow the deduced ARG to be a template base class of ARG,
21320 or a pointer to a template base class of the type pointed to by
21321 ARG.
21322 UNIFY_ALLOW_INTEGER:
21323 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
21324 case for more information.
21325 UNIFY_ALLOW_OUTER_LEVEL:
21326 This is the outermost level of a deduction. Used to determine validity
21327 of qualification conversions. A valid qualification conversion must
21328 have const qualified pointers leading up to the inner type which
21329 requires additional CV quals, except at the outer level, where const
21330 is not required [conv.qual]. It would be normal to set this flag in
21331 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
21332 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
21333 This is the outermost level of a deduction, and PARM can be more CV
21334 qualified at this point.
21335 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
21336 This is the outermost level of a deduction, and PARM can be less CV
21337 qualified at this point. */
21339 static int
21340 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
21341 bool explain_p)
21343 int idx;
21344 tree targ;
21345 tree tparm;
21346 int strict_in = strict;
21347 tsubst_flags_t complain = (explain_p
21348 ? tf_warning_or_error
21349 : tf_none);
21351 /* I don't think this will do the right thing with respect to types.
21352 But the only case I've seen it in so far has been array bounds, where
21353 signedness is the only information lost, and I think that will be
21354 okay. */
21355 while (CONVERT_EXPR_P (parm))
21356 parm = TREE_OPERAND (parm, 0);
21358 if (arg == error_mark_node)
21359 return unify_invalid (explain_p);
21360 if (arg == unknown_type_node
21361 || arg == init_list_type_node)
21362 /* We can't deduce anything from this, but we might get all the
21363 template args from other function args. */
21364 return unify_success (explain_p);
21366 if (parm == any_targ_node || arg == any_targ_node)
21367 return unify_success (explain_p);
21369 /* If PARM uses template parameters, then we can't bail out here,
21370 even if ARG == PARM, since we won't record unifications for the
21371 template parameters. We might need them if we're trying to
21372 figure out which of two things is more specialized. */
21373 if (arg == parm && !uses_template_parms (parm))
21374 return unify_success (explain_p);
21376 /* Handle init lists early, so the rest of the function can assume
21377 we're dealing with a type. */
21378 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
21380 tree elt, elttype;
21381 unsigned i;
21382 tree orig_parm = parm;
21384 /* Replace T with std::initializer_list<T> for deduction. */
21385 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21386 && flag_deduce_init_list)
21387 parm = listify (parm);
21389 if (!is_std_init_list (parm)
21390 && TREE_CODE (parm) != ARRAY_TYPE)
21391 /* We can only deduce from an initializer list argument if the
21392 parameter is std::initializer_list or an array; otherwise this
21393 is a non-deduced context. */
21394 return unify_success (explain_p);
21396 if (TREE_CODE (parm) == ARRAY_TYPE)
21397 elttype = TREE_TYPE (parm);
21398 else
21400 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
21401 /* Deduction is defined in terms of a single type, so just punt
21402 on the (bizarre) std::initializer_list<T...>. */
21403 if (PACK_EXPANSION_P (elttype))
21404 return unify_success (explain_p);
21407 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
21409 int elt_strict = strict;
21411 if (elt == error_mark_node)
21412 return unify_invalid (explain_p);
21414 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
21416 tree type = TREE_TYPE (elt);
21417 if (type == error_mark_node)
21418 return unify_invalid (explain_p);
21419 /* It should only be possible to get here for a call. */
21420 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
21421 elt_strict |= maybe_adjust_types_for_deduction
21422 (DEDUCE_CALL, &elttype, &type, elt);
21423 elt = type;
21426 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
21427 explain_p);
21430 if (TREE_CODE (parm) == ARRAY_TYPE
21431 && deducible_array_bound (TYPE_DOMAIN (parm)))
21433 /* Also deduce from the length of the initializer list. */
21434 tree max = size_int (CONSTRUCTOR_NELTS (arg));
21435 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
21436 if (idx == error_mark_node)
21437 return unify_invalid (explain_p);
21438 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21439 idx, explain_p);
21442 /* If the std::initializer_list<T> deduction worked, replace the
21443 deduced A with std::initializer_list<A>. */
21444 if (orig_parm != parm)
21446 idx = TEMPLATE_TYPE_IDX (orig_parm);
21447 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21448 targ = listify (targ);
21449 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
21451 return unify_success (explain_p);
21454 /* If parm and arg aren't the same kind of thing (template, type, or
21455 expression), fail early. */
21456 if (pa_kind (parm) != pa_kind (arg))
21457 return unify_invalid (explain_p);
21459 /* Immediately reject some pairs that won't unify because of
21460 cv-qualification mismatches. */
21461 if (TREE_CODE (arg) == TREE_CODE (parm)
21462 && TYPE_P (arg)
21463 /* It is the elements of the array which hold the cv quals of an array
21464 type, and the elements might be template type parms. We'll check
21465 when we recurse. */
21466 && TREE_CODE (arg) != ARRAY_TYPE
21467 /* We check the cv-qualifiers when unifying with template type
21468 parameters below. We want to allow ARG `const T' to unify with
21469 PARM `T' for example, when computing which of two templates
21470 is more specialized, for example. */
21471 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21472 && !check_cv_quals_for_unify (strict_in, arg, parm))
21473 return unify_cv_qual_mismatch (explain_p, parm, arg);
21475 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21476 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21477 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21478 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21479 strict &= ~UNIFY_ALLOW_DERIVED;
21480 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21481 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21483 switch (TREE_CODE (parm))
21485 case TYPENAME_TYPE:
21486 case SCOPE_REF:
21487 case UNBOUND_CLASS_TEMPLATE:
21488 /* In a type which contains a nested-name-specifier, template
21489 argument values cannot be deduced for template parameters used
21490 within the nested-name-specifier. */
21491 return unify_success (explain_p);
21493 case TEMPLATE_TYPE_PARM:
21494 case TEMPLATE_TEMPLATE_PARM:
21495 case BOUND_TEMPLATE_TEMPLATE_PARM:
21496 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21497 if (error_operand_p (tparm))
21498 return unify_invalid (explain_p);
21500 if (TEMPLATE_TYPE_LEVEL (parm)
21501 != template_decl_level (tparm))
21502 /* The PARM is not one we're trying to unify. Just check
21503 to see if it matches ARG. */
21505 if (TREE_CODE (arg) == TREE_CODE (parm)
21506 && (is_auto (parm) ? is_auto (arg)
21507 : same_type_p (parm, arg)))
21508 return unify_success (explain_p);
21509 else
21510 return unify_type_mismatch (explain_p, parm, arg);
21512 idx = TEMPLATE_TYPE_IDX (parm);
21513 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21514 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21515 if (error_operand_p (tparm))
21516 return unify_invalid (explain_p);
21518 /* Check for mixed types and values. */
21519 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21520 && TREE_CODE (tparm) != TYPE_DECL)
21521 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21522 && TREE_CODE (tparm) != TEMPLATE_DECL))
21523 gcc_unreachable ();
21525 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21527 if ((strict_in & UNIFY_ALLOW_DERIVED)
21528 && CLASS_TYPE_P (arg))
21530 /* First try to match ARG directly. */
21531 tree t = try_class_unification (tparms, targs, parm, arg,
21532 explain_p);
21533 if (!t)
21535 /* Otherwise, look for a suitable base of ARG, as below. */
21536 enum template_base_result r;
21537 r = get_template_base (tparms, targs, parm, arg,
21538 explain_p, &t);
21539 if (!t)
21540 return unify_no_common_base (explain_p, r, parm, arg);
21541 arg = t;
21544 /* ARG must be constructed from a template class or a template
21545 template parameter. */
21546 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21547 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21548 return unify_template_deduction_failure (explain_p, parm, arg);
21550 /* Deduce arguments T, i from TT<T> or TT<i>. */
21551 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21552 return 1;
21554 arg = TYPE_TI_TEMPLATE (arg);
21556 /* Fall through to deduce template name. */
21559 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21560 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21562 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
21564 /* Simple cases: Value already set, does match or doesn't. */
21565 if (targ != NULL_TREE && template_args_equal (targ, arg))
21566 return unify_success (explain_p);
21567 else if (targ)
21568 return unify_inconsistency (explain_p, parm, targ, arg);
21570 else
21572 /* If PARM is `const T' and ARG is only `int', we don't have
21573 a match unless we are allowing additional qualification.
21574 If ARG is `const int' and PARM is just `T' that's OK;
21575 that binds `const int' to `T'. */
21576 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21577 arg, parm))
21578 return unify_cv_qual_mismatch (explain_p, parm, arg);
21580 /* Consider the case where ARG is `const volatile int' and
21581 PARM is `const T'. Then, T should be `volatile int'. */
21582 arg = cp_build_qualified_type_real
21583 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21584 if (arg == error_mark_node)
21585 return unify_invalid (explain_p);
21587 /* Simple cases: Value already set, does match or doesn't. */
21588 if (targ != NULL_TREE && same_type_p (targ, arg))
21589 return unify_success (explain_p);
21590 else if (targ)
21591 return unify_inconsistency (explain_p, parm, targ, arg);
21593 /* Make sure that ARG is not a variable-sized array. (Note
21594 that were talking about variable-sized arrays (like
21595 `int[n]'), rather than arrays of unknown size (like
21596 `int[]').) We'll get very confused by such a type since
21597 the bound of the array is not constant, and therefore
21598 not mangleable. Besides, such types are not allowed in
21599 ISO C++, so we can do as we please here. We do allow
21600 them for 'auto' deduction, since that isn't ABI-exposed. */
21601 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21602 return unify_vla_arg (explain_p, arg);
21604 /* Strip typedefs as in convert_template_argument. */
21605 arg = canonicalize_type_argument (arg, tf_none);
21608 /* If ARG is a parameter pack or an expansion, we cannot unify
21609 against it unless PARM is also a parameter pack. */
21610 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21611 && !template_parameter_pack_p (parm))
21612 return unify_parameter_pack_mismatch (explain_p, parm, arg);
21614 /* If the argument deduction results is a METHOD_TYPE,
21615 then there is a problem.
21616 METHOD_TYPE doesn't map to any real C++ type the result of
21617 the deduction can not be of that type. */
21618 if (TREE_CODE (arg) == METHOD_TYPE)
21619 return unify_method_type_error (explain_p, arg);
21621 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21622 return unify_success (explain_p);
21624 case TEMPLATE_PARM_INDEX:
21625 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21626 if (error_operand_p (tparm))
21627 return unify_invalid (explain_p);
21629 if (TEMPLATE_PARM_LEVEL (parm)
21630 != template_decl_level (tparm))
21632 /* The PARM is not one we're trying to unify. Just check
21633 to see if it matches ARG. */
21634 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21635 && cp_tree_equal (parm, arg));
21636 if (result)
21637 unify_expression_unequal (explain_p, parm, arg);
21638 return result;
21641 idx = TEMPLATE_PARM_IDX (parm);
21642 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21644 if (targ)
21646 if ((strict & UNIFY_ALLOW_INTEGER)
21647 && TREE_TYPE (targ) && TREE_TYPE (arg)
21648 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21649 /* We're deducing from an array bound, the type doesn't matter. */
21650 arg = fold_convert (TREE_TYPE (targ), arg);
21651 int x = !cp_tree_equal (targ, arg);
21652 if (x)
21653 unify_inconsistency (explain_p, parm, targ, arg);
21654 return x;
21657 /* [temp.deduct.type] If, in the declaration of a function template
21658 with a non-type template-parameter, the non-type
21659 template-parameter is used in an expression in the function
21660 parameter-list and, if the corresponding template-argument is
21661 deduced, the template-argument type shall match the type of the
21662 template-parameter exactly, except that a template-argument
21663 deduced from an array bound may be of any integral type.
21664 The non-type parameter might use already deduced type parameters. */
21665 tparm = TREE_TYPE (parm);
21666 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
21667 /* We don't have enough levels of args to do any substitution. This
21668 can happen in the context of -fnew-ttp-matching. */;
21669 else
21671 ++processing_template_decl;
21672 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
21673 --processing_template_decl;
21675 if (tree a = type_uses_auto (tparm))
21677 tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21678 if (tparm == error_mark_node)
21679 return 1;
21683 if (!TREE_TYPE (arg))
21684 /* Template-parameter dependent expression. Just accept it for now.
21685 It will later be processed in convert_template_argument. */
21687 else if (same_type_p (non_reference (TREE_TYPE (arg)),
21688 non_reference (tparm)))
21689 /* OK */;
21690 else if ((strict & UNIFY_ALLOW_INTEGER)
21691 && CP_INTEGRAL_TYPE_P (tparm))
21692 /* Convert the ARG to the type of PARM; the deduced non-type
21693 template argument must exactly match the types of the
21694 corresponding parameter. */
21695 arg = fold (build_nop (tparm, arg));
21696 else if (uses_template_parms (tparm))
21698 /* We haven't deduced the type of this parameter yet. */
21699 if (cxx_dialect >= cxx17
21700 /* We deduce from array bounds in try_array_deduction. */
21701 && !(strict & UNIFY_ALLOW_INTEGER))
21703 /* Deduce it from the non-type argument. */
21704 tree atype = TREE_TYPE (arg);
21705 RECUR_AND_CHECK_FAILURE (tparms, targs,
21706 tparm, atype,
21707 UNIFY_ALLOW_NONE, explain_p);
21709 else
21710 /* Try again later. */
21711 return unify_success (explain_p);
21713 else
21714 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21716 /* If ARG is a parameter pack or an expansion, we cannot unify
21717 against it unless PARM is also a parameter pack. */
21718 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21719 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21720 return unify_parameter_pack_mismatch (explain_p, parm, arg);
21723 bool removed_attr = false;
21724 arg = strip_typedefs_expr (arg, &removed_attr);
21726 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21727 return unify_success (explain_p);
21729 case PTRMEM_CST:
21731 /* A pointer-to-member constant can be unified only with
21732 another constant. */
21733 if (TREE_CODE (arg) != PTRMEM_CST)
21734 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21736 /* Just unify the class member. It would be useless (and possibly
21737 wrong, depending on the strict flags) to unify also
21738 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21739 arg refer to the same variable, even if through different
21740 classes. For instance:
21742 struct A { int x; };
21743 struct B : A { };
21745 Unification of &A::x and &B::x must succeed. */
21746 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21747 PTRMEM_CST_MEMBER (arg), strict, explain_p);
21750 case POINTER_TYPE:
21752 if (!TYPE_PTR_P (arg))
21753 return unify_type_mismatch (explain_p, parm, arg);
21755 /* [temp.deduct.call]
21757 A can be another pointer or pointer to member type that can
21758 be converted to the deduced A via a qualification
21759 conversion (_conv.qual_).
21761 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21762 This will allow for additional cv-qualification of the
21763 pointed-to types if appropriate. */
21765 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21766 /* The derived-to-base conversion only persists through one
21767 level of pointers. */
21768 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21770 return unify (tparms, targs, TREE_TYPE (parm),
21771 TREE_TYPE (arg), strict, explain_p);
21774 case REFERENCE_TYPE:
21775 if (!TYPE_REF_P (arg))
21776 return unify_type_mismatch (explain_p, parm, arg);
21777 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21778 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21780 case ARRAY_TYPE:
21781 if (TREE_CODE (arg) != ARRAY_TYPE)
21782 return unify_type_mismatch (explain_p, parm, arg);
21783 if ((TYPE_DOMAIN (parm) == NULL_TREE)
21784 != (TYPE_DOMAIN (arg) == NULL_TREE))
21785 return unify_type_mismatch (explain_p, parm, arg);
21786 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21787 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21788 if (TYPE_DOMAIN (parm) != NULL_TREE)
21789 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21790 TYPE_DOMAIN (arg), explain_p);
21791 return unify_success (explain_p);
21793 case REAL_TYPE:
21794 case COMPLEX_TYPE:
21795 case VECTOR_TYPE:
21796 case INTEGER_TYPE:
21797 case BOOLEAN_TYPE:
21798 case ENUMERAL_TYPE:
21799 case VOID_TYPE:
21800 case NULLPTR_TYPE:
21801 if (TREE_CODE (arg) != TREE_CODE (parm))
21802 return unify_type_mismatch (explain_p, parm, arg);
21804 /* We have already checked cv-qualification at the top of the
21805 function. */
21806 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21807 return unify_type_mismatch (explain_p, parm, arg);
21809 /* As far as unification is concerned, this wins. Later checks
21810 will invalidate it if necessary. */
21811 return unify_success (explain_p);
21813 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
21814 /* Type INTEGER_CST can come from ordinary constant template args. */
21815 case INTEGER_CST:
21816 while (CONVERT_EXPR_P (arg))
21817 arg = TREE_OPERAND (arg, 0);
21819 if (TREE_CODE (arg) != INTEGER_CST)
21820 return unify_template_argument_mismatch (explain_p, parm, arg);
21821 return (tree_int_cst_equal (parm, arg)
21822 ? unify_success (explain_p)
21823 : unify_template_argument_mismatch (explain_p, parm, arg));
21825 case TREE_VEC:
21827 int i, len, argslen;
21828 int parm_variadic_p = 0;
21830 if (TREE_CODE (arg) != TREE_VEC)
21831 return unify_template_argument_mismatch (explain_p, parm, arg);
21833 len = TREE_VEC_LENGTH (parm);
21834 argslen = TREE_VEC_LENGTH (arg);
21836 /* Check for pack expansions in the parameters. */
21837 for (i = 0; i < len; ++i)
21839 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
21841 if (i == len - 1)
21842 /* We can unify against something with a trailing
21843 parameter pack. */
21844 parm_variadic_p = 1;
21845 else
21846 /* [temp.deduct.type]/9: If the template argument list of
21847 P contains a pack expansion that is not the last
21848 template argument, the entire template argument list
21849 is a non-deduced context. */
21850 return unify_success (explain_p);
21854 /* If we don't have enough arguments to satisfy the parameters
21855 (not counting the pack expression at the end), or we have
21856 too many arguments for a parameter list that doesn't end in
21857 a pack expression, we can't unify. */
21858 if (parm_variadic_p
21859 ? argslen < len - parm_variadic_p
21860 : argslen != len)
21861 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
21863 /* Unify all of the parameters that precede the (optional)
21864 pack expression. */
21865 for (i = 0; i < len - parm_variadic_p; ++i)
21867 RECUR_AND_CHECK_FAILURE (tparms, targs,
21868 TREE_VEC_ELT (parm, i),
21869 TREE_VEC_ELT (arg, i),
21870 UNIFY_ALLOW_NONE, explain_p);
21872 if (parm_variadic_p)
21873 return unify_pack_expansion (tparms, targs, parm, arg,
21874 DEDUCE_EXACT,
21875 /*subr=*/true, explain_p);
21876 return unify_success (explain_p);
21879 case RECORD_TYPE:
21880 case UNION_TYPE:
21881 if (TREE_CODE (arg) != TREE_CODE (parm))
21882 return unify_type_mismatch (explain_p, parm, arg);
21884 if (TYPE_PTRMEMFUNC_P (parm))
21886 if (!TYPE_PTRMEMFUNC_P (arg))
21887 return unify_type_mismatch (explain_p, parm, arg);
21889 return unify (tparms, targs,
21890 TYPE_PTRMEMFUNC_FN_TYPE (parm),
21891 TYPE_PTRMEMFUNC_FN_TYPE (arg),
21892 strict, explain_p);
21894 else if (TYPE_PTRMEMFUNC_P (arg))
21895 return unify_type_mismatch (explain_p, parm, arg);
21897 if (CLASSTYPE_TEMPLATE_INFO (parm))
21899 tree t = NULL_TREE;
21901 if (strict_in & UNIFY_ALLOW_DERIVED)
21903 /* First, we try to unify the PARM and ARG directly. */
21904 t = try_class_unification (tparms, targs,
21905 parm, arg, explain_p);
21907 if (!t)
21909 /* Fallback to the special case allowed in
21910 [temp.deduct.call]:
21912 If P is a class, and P has the form
21913 template-id, then A can be a derived class of
21914 the deduced A. Likewise, if P is a pointer to
21915 a class of the form template-id, A can be a
21916 pointer to a derived class pointed to by the
21917 deduced A. */
21918 enum template_base_result r;
21919 r = get_template_base (tparms, targs, parm, arg,
21920 explain_p, &t);
21922 if (!t)
21924 /* Don't give the derived diagnostic if we're
21925 already dealing with the same template. */
21926 bool same_template
21927 = (CLASSTYPE_TEMPLATE_INFO (arg)
21928 && (CLASSTYPE_TI_TEMPLATE (parm)
21929 == CLASSTYPE_TI_TEMPLATE (arg)));
21930 return unify_no_common_base (explain_p && !same_template,
21931 r, parm, arg);
21935 else if (CLASSTYPE_TEMPLATE_INFO (arg)
21936 && (CLASSTYPE_TI_TEMPLATE (parm)
21937 == CLASSTYPE_TI_TEMPLATE (arg)))
21938 /* Perhaps PARM is something like S<U> and ARG is S<int>.
21939 Then, we should unify `int' and `U'. */
21940 t = arg;
21941 else
21942 /* There's no chance of unification succeeding. */
21943 return unify_type_mismatch (explain_p, parm, arg);
21945 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
21946 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
21948 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
21949 return unify_type_mismatch (explain_p, parm, arg);
21950 return unify_success (explain_p);
21952 case METHOD_TYPE:
21953 case FUNCTION_TYPE:
21955 unsigned int nargs;
21956 tree *args;
21957 tree a;
21958 unsigned int i;
21960 if (TREE_CODE (arg) != TREE_CODE (parm))
21961 return unify_type_mismatch (explain_p, parm, arg);
21963 /* CV qualifications for methods can never be deduced, they must
21964 match exactly. We need to check them explicitly here,
21965 because type_unification_real treats them as any other
21966 cv-qualified parameter. */
21967 if (TREE_CODE (parm) == METHOD_TYPE
21968 && (!check_cv_quals_for_unify
21969 (UNIFY_ALLOW_NONE,
21970 class_of_this_parm (arg),
21971 class_of_this_parm (parm))))
21972 return unify_cv_qual_mismatch (explain_p, parm, arg);
21973 if (TREE_CODE (arg) == FUNCTION_TYPE
21974 && type_memfn_quals (parm) != type_memfn_quals (arg))
21975 return unify_cv_qual_mismatch (explain_p, parm, arg);
21976 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
21977 return unify_type_mismatch (explain_p, parm, arg);
21979 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
21980 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
21982 nargs = list_length (TYPE_ARG_TYPES (arg));
21983 args = XALLOCAVEC (tree, nargs);
21984 for (a = TYPE_ARG_TYPES (arg), i = 0;
21985 a != NULL_TREE && a != void_list_node;
21986 a = TREE_CHAIN (a), ++i)
21987 args[i] = TREE_VALUE (a);
21988 nargs = i;
21990 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
21991 args, nargs, 1, DEDUCE_EXACT,
21992 LOOKUP_NORMAL, NULL, explain_p))
21993 return 1;
21995 if (flag_noexcept_type)
21997 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
21998 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
21999 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
22000 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
22001 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
22002 && uses_template_parms (TREE_PURPOSE (pspec)))
22003 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
22004 TREE_PURPOSE (aspec),
22005 UNIFY_ALLOW_NONE, explain_p);
22006 else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
22007 return unify_type_mismatch (explain_p, parm, arg);
22010 return 0;
22013 case OFFSET_TYPE:
22014 /* Unify a pointer to member with a pointer to member function, which
22015 deduces the type of the member as a function type. */
22016 if (TYPE_PTRMEMFUNC_P (arg))
22018 /* Check top-level cv qualifiers */
22019 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
22020 return unify_cv_qual_mismatch (explain_p, parm, arg);
22022 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22023 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
22024 UNIFY_ALLOW_NONE, explain_p);
22026 /* Determine the type of the function we are unifying against. */
22027 tree fntype = static_fn_type (arg);
22029 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
22032 if (TREE_CODE (arg) != OFFSET_TYPE)
22033 return unify_type_mismatch (explain_p, parm, arg);
22034 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22035 TYPE_OFFSET_BASETYPE (arg),
22036 UNIFY_ALLOW_NONE, explain_p);
22037 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22038 strict, explain_p);
22040 case CONST_DECL:
22041 if (DECL_TEMPLATE_PARM_P (parm))
22042 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22043 if (arg != scalar_constant_value (parm))
22044 return unify_template_argument_mismatch (explain_p, parm, arg);
22045 return unify_success (explain_p);
22047 case FIELD_DECL:
22048 case TEMPLATE_DECL:
22049 /* Matched cases are handled by the ARG == PARM test above. */
22050 return unify_template_argument_mismatch (explain_p, parm, arg);
22052 case VAR_DECL:
22053 /* We might get a variable as a non-type template argument in parm if the
22054 corresponding parameter is type-dependent. Make any necessary
22055 adjustments based on whether arg is a reference. */
22056 if (CONSTANT_CLASS_P (arg))
22057 parm = fold_non_dependent_expr (parm);
22058 else if (REFERENCE_REF_P (arg))
22060 tree sub = TREE_OPERAND (arg, 0);
22061 STRIP_NOPS (sub);
22062 if (TREE_CODE (sub) == ADDR_EXPR)
22063 arg = TREE_OPERAND (sub, 0);
22065 /* Now use the normal expression code to check whether they match. */
22066 goto expr;
22068 case TYPE_ARGUMENT_PACK:
22069 case NONTYPE_ARGUMENT_PACK:
22070 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22071 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22073 case TYPEOF_TYPE:
22074 case DECLTYPE_TYPE:
22075 case UNDERLYING_TYPE:
22076 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22077 or UNDERLYING_TYPE nodes. */
22078 return unify_success (explain_p);
22080 case ERROR_MARK:
22081 /* Unification fails if we hit an error node. */
22082 return unify_invalid (explain_p);
22084 case INDIRECT_REF:
22085 if (REFERENCE_REF_P (parm))
22087 bool pexp = PACK_EXPANSION_P (arg);
22088 if (pexp)
22089 arg = PACK_EXPANSION_PATTERN (arg);
22090 if (REFERENCE_REF_P (arg))
22091 arg = TREE_OPERAND (arg, 0);
22092 if (pexp)
22093 arg = make_pack_expansion (arg, complain);
22094 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22095 strict, explain_p);
22097 /* FALLTHRU */
22099 default:
22100 /* An unresolved overload is a nondeduced context. */
22101 if (is_overloaded_fn (parm) || type_unknown_p (parm))
22102 return unify_success (explain_p);
22103 gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
22104 expr:
22105 /* We must be looking at an expression. This can happen with
22106 something like:
22108 template <int I>
22109 void foo(S<I>, S<I + 2>);
22111 This is a "nondeduced context":
22113 [deduct.type]
22115 The nondeduced contexts are:
22117 --A type that is a template-id in which one or more of
22118 the template-arguments is an expression that references
22119 a template-parameter.
22121 In these cases, we assume deduction succeeded, but don't
22122 actually infer any unifications. */
22124 if (!uses_template_parms (parm)
22125 && !template_args_equal (parm, arg))
22126 return unify_expression_unequal (explain_p, parm, arg);
22127 else
22128 return unify_success (explain_p);
22131 #undef RECUR_AND_CHECK_FAILURE
22133 /* Note that DECL can be defined in this translation unit, if
22134 required. */
22136 static void
22137 mark_definable (tree decl)
22139 tree clone;
22140 DECL_NOT_REALLY_EXTERN (decl) = 1;
22141 FOR_EACH_CLONE (clone, decl)
22142 DECL_NOT_REALLY_EXTERN (clone) = 1;
22145 /* Called if RESULT is explicitly instantiated, or is a member of an
22146 explicitly instantiated class. */
22148 void
22149 mark_decl_instantiated (tree result, int extern_p)
22151 SET_DECL_EXPLICIT_INSTANTIATION (result);
22153 /* If this entity has already been written out, it's too late to
22154 make any modifications. */
22155 if (TREE_ASM_WRITTEN (result))
22156 return;
22158 /* For anonymous namespace we don't need to do anything. */
22159 if (decl_anon_ns_mem_p (result))
22161 gcc_assert (!TREE_PUBLIC (result));
22162 return;
22165 if (TREE_CODE (result) != FUNCTION_DECL)
22166 /* The TREE_PUBLIC flag for function declarations will have been
22167 set correctly by tsubst. */
22168 TREE_PUBLIC (result) = 1;
22170 /* This might have been set by an earlier implicit instantiation. */
22171 DECL_COMDAT (result) = 0;
22173 if (extern_p)
22174 DECL_NOT_REALLY_EXTERN (result) = 0;
22175 else
22177 mark_definable (result);
22178 mark_needed (result);
22179 /* Always make artificials weak. */
22180 if (DECL_ARTIFICIAL (result) && flag_weak)
22181 comdat_linkage (result);
22182 /* For WIN32 we also want to put explicit instantiations in
22183 linkonce sections. */
22184 else if (TREE_PUBLIC (result))
22185 maybe_make_one_only (result);
22186 if (TREE_CODE (result) == FUNCTION_DECL
22187 && DECL_TEMPLATE_INSTANTIATED (result))
22188 /* If the function has already been instantiated, clear DECL_EXTERNAL,
22189 since start_preparsed_function wouldn't have if we had an earlier
22190 extern explicit instantiation. */
22191 DECL_EXTERNAL (result) = 0;
22194 /* If EXTERN_P, then this function will not be emitted -- unless
22195 followed by an explicit instantiation, at which point its linkage
22196 will be adjusted. If !EXTERN_P, then this function will be
22197 emitted here. In neither circumstance do we want
22198 import_export_decl to adjust the linkage. */
22199 DECL_INTERFACE_KNOWN (result) = 1;
22202 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22203 important template arguments. If any are missing, we check whether
22204 they're important by using error_mark_node for substituting into any
22205 args that were used for partial ordering (the ones between ARGS and END)
22206 and seeing if it bubbles up. */
22208 static bool
22209 check_undeduced_parms (tree targs, tree args, tree end)
22211 bool found = false;
22212 int i;
22213 for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22214 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22216 found = true;
22217 TREE_VEC_ELT (targs, i) = error_mark_node;
22219 if (found)
22221 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22222 if (substed == error_mark_node)
22223 return true;
22225 return false;
22228 /* Given two function templates PAT1 and PAT2, return:
22230 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22231 -1 if PAT2 is more specialized than PAT1.
22232 0 if neither is more specialized.
22234 LEN indicates the number of parameters we should consider
22235 (defaulted parameters should not be considered).
22237 The 1998 std underspecified function template partial ordering, and
22238 DR214 addresses the issue. We take pairs of arguments, one from
22239 each of the templates, and deduce them against each other. One of
22240 the templates will be more specialized if all the *other*
22241 template's arguments deduce against its arguments and at least one
22242 of its arguments *does* *not* deduce against the other template's
22243 corresponding argument. Deduction is done as for class templates.
22244 The arguments used in deduction have reference and top level cv
22245 qualifiers removed. Iff both arguments were originally reference
22246 types *and* deduction succeeds in both directions, an lvalue reference
22247 wins against an rvalue reference and otherwise the template
22248 with the more cv-qualified argument wins for that pairing (if
22249 neither is more cv-qualified, they both are equal). Unlike regular
22250 deduction, after all the arguments have been deduced in this way,
22251 we do *not* verify the deduced template argument values can be
22252 substituted into non-deduced contexts.
22254 The logic can be a bit confusing here, because we look at deduce1 and
22255 targs1 to see if pat2 is at least as specialized, and vice versa; if we
22256 can find template arguments for pat1 to make arg1 look like arg2, that
22257 means that arg2 is at least as specialized as arg1. */
22260 more_specialized_fn (tree pat1, tree pat2, int len)
22262 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22263 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22264 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22265 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22266 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22267 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22268 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22269 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22270 tree origs1, origs2;
22271 bool lose1 = false;
22272 bool lose2 = false;
22274 /* Remove the this parameter from non-static member functions. If
22275 one is a non-static member function and the other is not a static
22276 member function, remove the first parameter from that function
22277 also. This situation occurs for operator functions where we
22278 locate both a member function (with this pointer) and non-member
22279 operator (with explicit first operand). */
22280 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22282 len--; /* LEN is the number of significant arguments for DECL1 */
22283 args1 = TREE_CHAIN (args1);
22284 if (!DECL_STATIC_FUNCTION_P (decl2))
22285 args2 = TREE_CHAIN (args2);
22287 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22289 args2 = TREE_CHAIN (args2);
22290 if (!DECL_STATIC_FUNCTION_P (decl1))
22292 len--;
22293 args1 = TREE_CHAIN (args1);
22297 /* If only one is a conversion operator, they are unordered. */
22298 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
22299 return 0;
22301 /* Consider the return type for a conversion function */
22302 if (DECL_CONV_FN_P (decl1))
22304 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
22305 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
22306 len++;
22309 processing_template_decl++;
22311 origs1 = args1;
22312 origs2 = args2;
22314 while (len--
22315 /* Stop when an ellipsis is seen. */
22316 && args1 != NULL_TREE && args2 != NULL_TREE)
22318 tree arg1 = TREE_VALUE (args1);
22319 tree arg2 = TREE_VALUE (args2);
22320 int deduce1, deduce2;
22321 int quals1 = -1;
22322 int quals2 = -1;
22323 int ref1 = 0;
22324 int ref2 = 0;
22326 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22327 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22329 /* When both arguments are pack expansions, we need only
22330 unify the patterns themselves. */
22331 arg1 = PACK_EXPANSION_PATTERN (arg1);
22332 arg2 = PACK_EXPANSION_PATTERN (arg2);
22334 /* This is the last comparison we need to do. */
22335 len = 0;
22338 /* DR 1847: If a particular P contains no template-parameters that
22339 participate in template argument deduction, that P is not used to
22340 determine the ordering. */
22341 if (!uses_deducible_template_parms (arg1)
22342 && !uses_deducible_template_parms (arg2))
22343 goto next;
22345 if (TYPE_REF_P (arg1))
22347 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
22348 arg1 = TREE_TYPE (arg1);
22349 quals1 = cp_type_quals (arg1);
22352 if (TYPE_REF_P (arg2))
22354 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
22355 arg2 = TREE_TYPE (arg2);
22356 quals2 = cp_type_quals (arg2);
22359 arg1 = TYPE_MAIN_VARIANT (arg1);
22360 arg2 = TYPE_MAIN_VARIANT (arg2);
22362 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
22364 int i, len2 = remaining_arguments (args2);
22365 tree parmvec = make_tree_vec (1);
22366 tree argvec = make_tree_vec (len2);
22367 tree ta = args2;
22369 /* Setup the parameter vector, which contains only ARG1. */
22370 TREE_VEC_ELT (parmvec, 0) = arg1;
22372 /* Setup the argument vector, which contains the remaining
22373 arguments. */
22374 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
22375 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22377 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
22378 argvec, DEDUCE_EXACT,
22379 /*subr=*/true, /*explain_p=*/false)
22380 == 0);
22382 /* We cannot deduce in the other direction, because ARG1 is
22383 a pack expansion but ARG2 is not. */
22384 deduce2 = 0;
22386 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22388 int i, len1 = remaining_arguments (args1);
22389 tree parmvec = make_tree_vec (1);
22390 tree argvec = make_tree_vec (len1);
22391 tree ta = args1;
22393 /* Setup the parameter vector, which contains only ARG1. */
22394 TREE_VEC_ELT (parmvec, 0) = arg2;
22396 /* Setup the argument vector, which contains the remaining
22397 arguments. */
22398 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
22399 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22401 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
22402 argvec, DEDUCE_EXACT,
22403 /*subr=*/true, /*explain_p=*/false)
22404 == 0);
22406 /* We cannot deduce in the other direction, because ARG2 is
22407 a pack expansion but ARG1 is not.*/
22408 deduce1 = 0;
22411 else
22413 /* The normal case, where neither argument is a pack
22414 expansion. */
22415 deduce1 = (unify (tparms1, targs1, arg1, arg2,
22416 UNIFY_ALLOW_NONE, /*explain_p=*/false)
22417 == 0);
22418 deduce2 = (unify (tparms2, targs2, arg2, arg1,
22419 UNIFY_ALLOW_NONE, /*explain_p=*/false)
22420 == 0);
22423 /* If we couldn't deduce arguments for tparms1 to make arg1 match
22424 arg2, then arg2 is not as specialized as arg1. */
22425 if (!deduce1)
22426 lose2 = true;
22427 if (!deduce2)
22428 lose1 = true;
22430 /* "If, for a given type, deduction succeeds in both directions
22431 (i.e., the types are identical after the transformations above)
22432 and both P and A were reference types (before being replaced with
22433 the type referred to above):
22434 - if the type from the argument template was an lvalue reference and
22435 the type from the parameter template was not, the argument type is
22436 considered to be more specialized than the other; otherwise,
22437 - if the type from the argument template is more cv-qualified
22438 than the type from the parameter template (as described above),
22439 the argument type is considered to be more specialized than the other;
22440 otherwise,
22441 - neither type is more specialized than the other." */
22443 if (deduce1 && deduce2)
22445 if (ref1 && ref2 && ref1 != ref2)
22447 if (ref1 > ref2)
22448 lose1 = true;
22449 else
22450 lose2 = true;
22452 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
22454 if ((quals1 & quals2) == quals2)
22455 lose2 = true;
22456 if ((quals1 & quals2) == quals1)
22457 lose1 = true;
22461 if (lose1 && lose2)
22462 /* We've failed to deduce something in either direction.
22463 These must be unordered. */
22464 break;
22466 next:
22468 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22469 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22470 /* We have already processed all of the arguments in our
22471 handing of the pack expansion type. */
22472 len = 0;
22474 args1 = TREE_CHAIN (args1);
22475 args2 = TREE_CHAIN (args2);
22478 /* "In most cases, all template parameters must have values in order for
22479 deduction to succeed, but for partial ordering purposes a template
22480 parameter may remain without a value provided it is not used in the
22481 types being used for partial ordering."
22483 Thus, if we are missing any of the targs1 we need to substitute into
22484 origs1, then pat2 is not as specialized as pat1. This can happen when
22485 there is a nondeduced context. */
22486 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22487 lose2 = true;
22488 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22489 lose1 = true;
22491 processing_template_decl--;
22493 /* If both deductions succeed, the partial ordering selects the more
22494 constrained template. */
22495 if (!lose1 && !lose2)
22497 tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22498 tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22499 lose1 = !subsumes_constraints (c1, c2);
22500 lose2 = !subsumes_constraints (c2, c1);
22503 /* All things being equal, if the next argument is a pack expansion
22504 for one function but not for the other, prefer the
22505 non-variadic function. FIXME this is bogus; see c++/41958. */
22506 if (lose1 == lose2
22507 && args1 && TREE_VALUE (args1)
22508 && args2 && TREE_VALUE (args2))
22510 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22511 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22514 if (lose1 == lose2)
22515 return 0;
22516 else if (!lose1)
22517 return 1;
22518 else
22519 return -1;
22522 /* Determine which of two partial specializations of TMPL is more
22523 specialized.
22525 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22526 to the first partial specialization. The TREE_PURPOSE is the
22527 innermost set of template parameters for the partial
22528 specialization. PAT2 is similar, but for the second template.
22530 Return 1 if the first partial specialization is more specialized;
22531 -1 if the second is more specialized; 0 if neither is more
22532 specialized.
22534 See [temp.class.order] for information about determining which of
22535 two templates is more specialized. */
22537 static int
22538 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22540 tree targs;
22541 int winner = 0;
22542 bool any_deductions = false;
22544 tree tmpl1 = TREE_VALUE (pat1);
22545 tree tmpl2 = TREE_VALUE (pat2);
22546 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22547 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22549 /* Just like what happens for functions, if we are ordering between
22550 different template specializations, we may encounter dependent
22551 types in the arguments, and we need our dependency check functions
22552 to behave correctly. */
22553 ++processing_template_decl;
22554 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22555 if (targs)
22557 --winner;
22558 any_deductions = true;
22561 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22562 if (targs)
22564 ++winner;
22565 any_deductions = true;
22567 --processing_template_decl;
22569 /* If both deductions succeed, the partial ordering selects the more
22570 constrained template. */
22571 if (!winner && any_deductions)
22572 return more_constrained (tmpl1, tmpl2);
22574 /* In the case of a tie where at least one of the templates
22575 has a parameter pack at the end, the template with the most
22576 non-packed parameters wins. */
22577 if (winner == 0
22578 && any_deductions
22579 && (template_args_variadic_p (TREE_PURPOSE (pat1))
22580 || template_args_variadic_p (TREE_PURPOSE (pat2))))
22582 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22583 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22584 int len1 = TREE_VEC_LENGTH (args1);
22585 int len2 = TREE_VEC_LENGTH (args2);
22587 /* We don't count the pack expansion at the end. */
22588 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22589 --len1;
22590 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22591 --len2;
22593 if (len1 > len2)
22594 return 1;
22595 else if (len1 < len2)
22596 return -1;
22599 return winner;
22602 /* Return the template arguments that will produce the function signature
22603 DECL from the function template FN, with the explicit template
22604 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
22605 also match. Return NULL_TREE if no satisfactory arguments could be
22606 found. */
22608 static tree
22609 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22611 int ntparms = DECL_NTPARMS (fn);
22612 tree targs = make_tree_vec (ntparms);
22613 tree decl_type = TREE_TYPE (decl);
22614 tree decl_arg_types;
22615 tree *args;
22616 unsigned int nargs, ix;
22617 tree arg;
22619 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22621 /* Never do unification on the 'this' parameter. */
22622 decl_arg_types = skip_artificial_parms_for (decl,
22623 TYPE_ARG_TYPES (decl_type));
22625 nargs = list_length (decl_arg_types);
22626 args = XALLOCAVEC (tree, nargs);
22627 for (arg = decl_arg_types, ix = 0;
22628 arg != NULL_TREE && arg != void_list_node;
22629 arg = TREE_CHAIN (arg), ++ix)
22630 args[ix] = TREE_VALUE (arg);
22632 if (fn_type_unification (fn, explicit_args, targs,
22633 args, ix,
22634 (check_rettype || DECL_CONV_FN_P (fn)
22635 ? TREE_TYPE (decl_type) : NULL_TREE),
22636 DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22637 /*decltype*/false)
22638 == error_mark_node)
22639 return NULL_TREE;
22641 return targs;
22644 /* Return the innermost template arguments that, when applied to a partial
22645 specialization SPEC_TMPL of TMPL, yield the ARGS.
22647 For example, suppose we have:
22649 template <class T, class U> struct S {};
22650 template <class T> struct S<T*, int> {};
22652 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
22653 partial specialization and the ARGS will be {double*, int}. The resulting
22654 vector will be {double}, indicating that `T' is bound to `double'. */
22656 static tree
22657 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22659 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22660 tree spec_args
22661 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22662 int i, ntparms = TREE_VEC_LENGTH (tparms);
22663 tree deduced_args;
22664 tree innermost_deduced_args;
22666 innermost_deduced_args = make_tree_vec (ntparms);
22667 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22669 deduced_args = copy_node (args);
22670 SET_TMPL_ARGS_LEVEL (deduced_args,
22671 TMPL_ARGS_DEPTH (deduced_args),
22672 innermost_deduced_args);
22674 else
22675 deduced_args = innermost_deduced_args;
22677 bool tried_array_deduction = (cxx_dialect < cxx17);
22678 again:
22679 if (unify (tparms, deduced_args,
22680 INNERMOST_TEMPLATE_ARGS (spec_args),
22681 INNERMOST_TEMPLATE_ARGS (args),
22682 UNIFY_ALLOW_NONE, /*explain_p=*/false))
22683 return NULL_TREE;
22685 for (i = 0; i < ntparms; ++i)
22686 if (! TREE_VEC_ELT (innermost_deduced_args, i))
22688 if (!tried_array_deduction)
22690 try_array_deduction (tparms, innermost_deduced_args,
22691 INNERMOST_TEMPLATE_ARGS (spec_args));
22692 tried_array_deduction = true;
22693 if (TREE_VEC_ELT (innermost_deduced_args, i))
22694 goto again;
22696 return NULL_TREE;
22699 if (!push_tinst_level (spec_tmpl, deduced_args))
22701 excessive_deduction_depth = true;
22702 return NULL_TREE;
22705 /* Verify that nondeduced template arguments agree with the type
22706 obtained from argument deduction.
22708 For example:
22710 struct A { typedef int X; };
22711 template <class T, class U> struct C {};
22712 template <class T> struct C<T, typename T::X> {};
22714 Then with the instantiation `C<A, int>', we can deduce that
22715 `T' is `A' but unify () does not check whether `typename T::X'
22716 is `int'. */
22717 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22719 if (spec_args != error_mark_node)
22720 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22721 INNERMOST_TEMPLATE_ARGS (spec_args),
22722 tmpl, tf_none, false, false);
22724 pop_tinst_level ();
22726 if (spec_args == error_mark_node
22727 /* We only need to check the innermost arguments; the other
22728 arguments will always agree. */
22729 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22730 INNERMOST_TEMPLATE_ARGS (args)))
22731 return NULL_TREE;
22733 /* Now that we have bindings for all of the template arguments,
22734 ensure that the arguments deduced for the template template
22735 parameters have compatible template parameter lists. See the use
22736 of template_template_parm_bindings_ok_p in fn_type_unification
22737 for more information. */
22738 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22739 return NULL_TREE;
22741 return deduced_args;
22744 // Compare two function templates T1 and T2 by deducing bindings
22745 // from one against the other. If both deductions succeed, compare
22746 // constraints to see which is more constrained.
22747 static int
22748 more_specialized_inst (tree t1, tree t2)
22750 int fate = 0;
22751 int count = 0;
22753 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22755 --fate;
22756 ++count;
22759 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22761 ++fate;
22762 ++count;
22765 // If both deductions succeed, then one may be more constrained.
22766 if (count == 2 && fate == 0)
22767 fate = more_constrained (t1, t2);
22769 return fate;
22772 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
22773 Return the TREE_LIST node with the most specialized template, if
22774 any. If there is no most specialized template, the error_mark_node
22775 is returned.
22777 Note that this function does not look at, or modify, the
22778 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
22779 returned is one of the elements of INSTANTIATIONS, callers may
22780 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22781 and retrieve it from the value returned. */
22783 tree
22784 most_specialized_instantiation (tree templates)
22786 tree fn, champ;
22788 ++processing_template_decl;
22790 champ = templates;
22791 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22793 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22794 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22795 if (fate == -1)
22796 champ = fn;
22797 else if (!fate)
22799 /* Equally specialized, move to next function. If there
22800 is no next function, nothing's most specialized. */
22801 fn = TREE_CHAIN (fn);
22802 champ = fn;
22803 if (!fn)
22804 break;
22808 if (champ)
22809 /* Now verify that champ is better than everything earlier in the
22810 instantiation list. */
22811 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22812 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22814 champ = NULL_TREE;
22815 break;
22819 processing_template_decl--;
22821 if (!champ)
22822 return error_mark_node;
22824 return champ;
22827 /* If DECL is a specialization of some template, return the most
22828 general such template. Otherwise, returns NULL_TREE.
22830 For example, given:
22832 template <class T> struct S { template <class U> void f(U); };
22834 if TMPL is `template <class U> void S<int>::f(U)' this will return
22835 the full template. This function will not trace past partial
22836 specializations, however. For example, given in addition:
22838 template <class T> struct S<T*> { template <class U> void f(U); };
22840 if TMPL is `template <class U> void S<int*>::f(U)' this will return
22841 `template <class T> template <class U> S<T*>::f(U)'. */
22843 tree
22844 most_general_template (tree decl)
22846 if (TREE_CODE (decl) != TEMPLATE_DECL)
22848 if (tree tinfo = get_template_info (decl))
22849 decl = TI_TEMPLATE (tinfo);
22850 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
22851 template friend, or a FIELD_DECL for a capture pack. */
22852 if (TREE_CODE (decl) != TEMPLATE_DECL)
22853 return NULL_TREE;
22856 /* Look for more and more general templates. */
22857 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
22859 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
22860 (See cp-tree.h for details.) */
22861 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
22862 break;
22864 if (CLASS_TYPE_P (TREE_TYPE (decl))
22865 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
22866 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
22867 break;
22869 /* Stop if we run into an explicitly specialized class template. */
22870 if (!DECL_NAMESPACE_SCOPE_P (decl)
22871 && DECL_CONTEXT (decl)
22872 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
22873 break;
22875 decl = DECL_TI_TEMPLATE (decl);
22878 return decl;
22881 /* Return the most specialized of the template partial specializations
22882 which can produce TARGET, a specialization of some class or variable
22883 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
22884 a TEMPLATE_DECL node corresponding to the partial specialization, while
22885 the TREE_PURPOSE is the set of template arguments that must be
22886 substituted into the template pattern in order to generate TARGET.
22888 If the choice of partial specialization is ambiguous, a diagnostic
22889 is issued, and the error_mark_node is returned. If there are no
22890 partial specializations matching TARGET, then NULL_TREE is
22891 returned, indicating that the primary template should be used. */
22893 static tree
22894 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
22896 tree list = NULL_TREE;
22897 tree t;
22898 tree champ;
22899 int fate;
22900 bool ambiguous_p;
22901 tree outer_args = NULL_TREE;
22902 tree tmpl, args;
22904 if (TYPE_P (target))
22906 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
22907 tmpl = TI_TEMPLATE (tinfo);
22908 args = TI_ARGS (tinfo);
22910 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
22912 tmpl = TREE_OPERAND (target, 0);
22913 args = TREE_OPERAND (target, 1);
22915 else if (VAR_P (target))
22917 tree tinfo = DECL_TEMPLATE_INFO (target);
22918 tmpl = TI_TEMPLATE (tinfo);
22919 args = TI_ARGS (tinfo);
22921 else
22922 gcc_unreachable ();
22924 tree main_tmpl = most_general_template (tmpl);
22926 /* For determining which partial specialization to use, only the
22927 innermost args are interesting. */
22928 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22930 outer_args = strip_innermost_template_args (args, 1);
22931 args = INNERMOST_TEMPLATE_ARGS (args);
22934 for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
22936 tree spec_args;
22937 tree spec_tmpl = TREE_VALUE (t);
22939 if (outer_args)
22941 /* Substitute in the template args from the enclosing class. */
22942 ++processing_template_decl;
22943 spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
22944 --processing_template_decl;
22947 if (spec_tmpl == error_mark_node)
22948 return error_mark_node;
22950 spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
22951 if (spec_args)
22953 if (outer_args)
22954 spec_args = add_to_template_args (outer_args, spec_args);
22956 /* Keep the candidate only if the constraints are satisfied,
22957 or if we're not compiling with concepts. */
22958 if (!flag_concepts
22959 || constraints_satisfied_p (spec_tmpl, spec_args))
22961 list = tree_cons (spec_args, TREE_VALUE (t), list);
22962 TREE_TYPE (list) = TREE_TYPE (t);
22967 if (! list)
22968 return NULL_TREE;
22970 ambiguous_p = false;
22971 t = list;
22972 champ = t;
22973 t = TREE_CHAIN (t);
22974 for (; t; t = TREE_CHAIN (t))
22976 fate = more_specialized_partial_spec (tmpl, champ, t);
22977 if (fate == 1)
22979 else
22981 if (fate == 0)
22983 t = TREE_CHAIN (t);
22984 if (! t)
22986 ambiguous_p = true;
22987 break;
22990 champ = t;
22994 if (!ambiguous_p)
22995 for (t = list; t && t != champ; t = TREE_CHAIN (t))
22997 fate = more_specialized_partial_spec (tmpl, champ, t);
22998 if (fate != 1)
23000 ambiguous_p = true;
23001 break;
23005 if (ambiguous_p)
23007 const char *str;
23008 char *spaces = NULL;
23009 if (!(complain & tf_error))
23010 return error_mark_node;
23011 if (TYPE_P (target))
23012 error ("ambiguous template instantiation for %q#T", target);
23013 else
23014 error ("ambiguous template instantiation for %q#D", target);
23015 str = ngettext ("candidate is:", "candidates are:", list_length (list));
23016 for (t = list; t; t = TREE_CHAIN (t))
23018 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
23019 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
23020 "%s %#qS", spaces ? spaces : str, subst);
23021 spaces = spaces ? spaces : get_spaces (str);
23023 free (spaces);
23024 return error_mark_node;
23027 return champ;
23030 /* Explicitly instantiate DECL. */
23032 void
23033 do_decl_instantiation (tree decl, tree storage)
23035 tree result = NULL_TREE;
23036 int extern_p = 0;
23038 if (!decl || decl == error_mark_node)
23039 /* An error occurred, for which grokdeclarator has already issued
23040 an appropriate message. */
23041 return;
23042 else if (! DECL_LANG_SPECIFIC (decl))
23044 error ("explicit instantiation of non-template %q#D", decl);
23045 return;
23048 bool var_templ = (DECL_TEMPLATE_INFO (decl)
23049 && variable_template_p (DECL_TI_TEMPLATE (decl)));
23051 if (VAR_P (decl) && !var_templ)
23053 /* There is an asymmetry here in the way VAR_DECLs and
23054 FUNCTION_DECLs are handled by grokdeclarator. In the case of
23055 the latter, the DECL we get back will be marked as a
23056 template instantiation, and the appropriate
23057 DECL_TEMPLATE_INFO will be set up. This does not happen for
23058 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
23059 should handle VAR_DECLs as it currently handles
23060 FUNCTION_DECLs. */
23061 if (!DECL_CLASS_SCOPE_P (decl))
23063 error ("%qD is not a static data member of a class template", decl);
23064 return;
23066 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23067 if (!result || !VAR_P (result))
23069 error ("no matching template for %qD found", decl);
23070 return;
23072 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23074 error ("type %qT for explicit instantiation %qD does not match "
23075 "declared type %qT", TREE_TYPE (result), decl,
23076 TREE_TYPE (decl));
23077 return;
23080 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23082 error ("explicit instantiation of %q#D", decl);
23083 return;
23085 else
23086 result = decl;
23088 /* Check for various error cases. Note that if the explicit
23089 instantiation is valid the RESULT will currently be marked as an
23090 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23091 until we get here. */
23093 if (DECL_TEMPLATE_SPECIALIZATION (result))
23095 /* DR 259 [temp.spec].
23097 Both an explicit instantiation and a declaration of an explicit
23098 specialization shall not appear in a program unless the explicit
23099 instantiation follows a declaration of the explicit specialization.
23101 For a given set of template parameters, if an explicit
23102 instantiation of a template appears after a declaration of an
23103 explicit specialization for that template, the explicit
23104 instantiation has no effect. */
23105 return;
23107 else if (DECL_EXPLICIT_INSTANTIATION (result))
23109 /* [temp.spec]
23111 No program shall explicitly instantiate any template more
23112 than once.
23114 We check DECL_NOT_REALLY_EXTERN so as not to complain when
23115 the first instantiation was `extern' and the second is not,
23116 and EXTERN_P for the opposite case. */
23117 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23118 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23119 /* If an "extern" explicit instantiation follows an ordinary
23120 explicit instantiation, the template is instantiated. */
23121 if (extern_p)
23122 return;
23124 else if (!DECL_IMPLICIT_INSTANTIATION (result))
23126 error ("no matching template for %qD found", result);
23127 return;
23129 else if (!DECL_TEMPLATE_INFO (result))
23131 permerror (input_location, "explicit instantiation of non-template %q#D", result);
23132 return;
23135 if (storage == NULL_TREE)
23137 else if (storage == ridpointers[(int) RID_EXTERN])
23139 if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23140 pedwarn (input_location, OPT_Wpedantic,
23141 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23142 "instantiations");
23143 extern_p = 1;
23145 else
23146 error ("storage class %qD applied to template instantiation", storage);
23148 check_explicit_instantiation_namespace (result);
23149 mark_decl_instantiated (result, extern_p);
23150 if (! extern_p)
23151 instantiate_decl (result, /*defer_ok=*/true,
23152 /*expl_inst_class_mem_p=*/false);
23155 static void
23156 mark_class_instantiated (tree t, int extern_p)
23158 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23159 SET_CLASSTYPE_INTERFACE_KNOWN (t);
23160 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23161 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23162 if (! extern_p)
23164 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23165 rest_of_type_compilation (t, 1);
23169 /* Called from do_type_instantiation through binding_table_foreach to
23170 do recursive instantiation for the type bound in ENTRY. */
23171 static void
23172 bt_instantiate_type_proc (binding_entry entry, void *data)
23174 tree storage = *(tree *) data;
23176 if (MAYBE_CLASS_TYPE_P (entry->type)
23177 && CLASSTYPE_TEMPLATE_INFO (entry->type)
23178 && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23179 do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23182 /* Perform an explicit instantiation of template class T. STORAGE, if
23183 non-null, is the RID for extern, inline or static. COMPLAIN is
23184 nonzero if this is called from the parser, zero if called recursively,
23185 since the standard is unclear (as detailed below). */
23187 void
23188 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23190 int extern_p = 0;
23191 int nomem_p = 0;
23192 int static_p = 0;
23193 int previous_instantiation_extern_p = 0;
23195 if (TREE_CODE (t) == TYPE_DECL)
23196 t = TREE_TYPE (t);
23198 if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23200 tree tmpl =
23201 (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23202 if (tmpl)
23203 error ("explicit instantiation of non-class template %qD", tmpl);
23204 else
23205 error ("explicit instantiation of non-template type %qT", t);
23206 return;
23209 complete_type (t);
23211 if (!COMPLETE_TYPE_P (t))
23213 if (complain & tf_error)
23214 error ("explicit instantiation of %q#T before definition of template",
23216 return;
23219 if (storage != NULL_TREE)
23221 if (!in_system_header_at (input_location))
23223 if (storage == ridpointers[(int) RID_EXTERN])
23225 if (cxx_dialect == cxx98)
23226 pedwarn (input_location, OPT_Wpedantic,
23227 "ISO C++ 1998 forbids the use of %<extern%> on "
23228 "explicit instantiations");
23230 else
23231 pedwarn (input_location, OPT_Wpedantic,
23232 "ISO C++ forbids the use of %qE"
23233 " on explicit instantiations", storage);
23236 if (storage == ridpointers[(int) RID_INLINE])
23237 nomem_p = 1;
23238 else if (storage == ridpointers[(int) RID_EXTERN])
23239 extern_p = 1;
23240 else if (storage == ridpointers[(int) RID_STATIC])
23241 static_p = 1;
23242 else
23244 error ("storage class %qD applied to template instantiation",
23245 storage);
23246 extern_p = 0;
23250 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23252 /* DR 259 [temp.spec].
23254 Both an explicit instantiation and a declaration of an explicit
23255 specialization shall not appear in a program unless the explicit
23256 instantiation follows a declaration of the explicit specialization.
23258 For a given set of template parameters, if an explicit
23259 instantiation of a template appears after a declaration of an
23260 explicit specialization for that template, the explicit
23261 instantiation has no effect. */
23262 return;
23264 else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23266 /* [temp.spec]
23268 No program shall explicitly instantiate any template more
23269 than once.
23271 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23272 instantiation was `extern'. If EXTERN_P then the second is.
23273 These cases are OK. */
23274 previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23276 if (!previous_instantiation_extern_p && !extern_p
23277 && (complain & tf_error))
23278 permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23280 /* If we've already instantiated the template, just return now. */
23281 if (!CLASSTYPE_INTERFACE_ONLY (t))
23282 return;
23285 check_explicit_instantiation_namespace (TYPE_NAME (t));
23286 mark_class_instantiated (t, extern_p);
23288 if (nomem_p)
23289 return;
23291 /* In contrast to implicit instantiation, where only the
23292 declarations, and not the definitions, of members are
23293 instantiated, we have here:
23295 [temp.explicit]
23297 The explicit instantiation of a class template specialization
23298 implies the instantiation of all of its members not
23299 previously explicitly specialized in the translation unit
23300 containing the explicit instantiation.
23302 Of course, we can't instantiate member template classes, since we
23303 don't have any arguments for them. Note that the standard is
23304 unclear on whether the instantiation of the members are
23305 *explicit* instantiations or not. However, the most natural
23306 interpretation is that it should be an explicit
23307 instantiation. */
23308 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
23309 if ((VAR_P (fld)
23310 || (TREE_CODE (fld) == FUNCTION_DECL
23311 && !static_p
23312 && user_provided_p (fld)))
23313 && DECL_TEMPLATE_INSTANTIATION (fld))
23315 mark_decl_instantiated (fld, extern_p);
23316 if (! extern_p)
23317 instantiate_decl (fld, /*defer_ok=*/true,
23318 /*expl_inst_class_mem_p=*/true);
23321 if (CLASSTYPE_NESTED_UTDS (t))
23322 binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
23323 bt_instantiate_type_proc, &storage);
23326 /* Given a function DECL, which is a specialization of TMPL, modify
23327 DECL to be a re-instantiation of TMPL with the same template
23328 arguments. TMPL should be the template into which tsubst'ing
23329 should occur for DECL, not the most general template.
23331 One reason for doing this is a scenario like this:
23333 template <class T>
23334 void f(const T&, int i);
23336 void g() { f(3, 7); }
23338 template <class T>
23339 void f(const T& t, const int i) { }
23341 Note that when the template is first instantiated, with
23342 instantiate_template, the resulting DECL will have no name for the
23343 first parameter, and the wrong type for the second. So, when we go
23344 to instantiate the DECL, we regenerate it. */
23346 static void
23347 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
23349 /* The arguments used to instantiate DECL, from the most general
23350 template. */
23351 tree code_pattern;
23353 code_pattern = DECL_TEMPLATE_RESULT (tmpl);
23355 /* Make sure that we can see identifiers, and compute access
23356 correctly. */
23357 push_access_scope (decl);
23359 if (TREE_CODE (decl) == FUNCTION_DECL)
23361 tree decl_parm;
23362 tree pattern_parm;
23363 tree specs;
23364 int args_depth;
23365 int parms_depth;
23367 args_depth = TMPL_ARGS_DEPTH (args);
23368 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
23369 if (args_depth > parms_depth)
23370 args = get_innermost_template_args (args, parms_depth);
23372 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
23373 args, tf_error, NULL_TREE,
23374 /*defer_ok*/false);
23375 if (specs && specs != error_mark_node)
23376 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
23377 specs);
23379 /* Merge parameter declarations. */
23380 decl_parm = skip_artificial_parms_for (decl,
23381 DECL_ARGUMENTS (decl));
23382 pattern_parm
23383 = skip_artificial_parms_for (code_pattern,
23384 DECL_ARGUMENTS (code_pattern));
23385 while (decl_parm && !DECL_PACK_P (pattern_parm))
23387 tree parm_type;
23388 tree attributes;
23390 if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23391 DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
23392 parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
23393 NULL_TREE);
23394 parm_type = type_decays_to (parm_type);
23395 if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23396 TREE_TYPE (decl_parm) = parm_type;
23397 attributes = DECL_ATTRIBUTES (pattern_parm);
23398 if (DECL_ATTRIBUTES (decl_parm) != attributes)
23400 DECL_ATTRIBUTES (decl_parm) = attributes;
23401 cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23403 decl_parm = DECL_CHAIN (decl_parm);
23404 pattern_parm = DECL_CHAIN (pattern_parm);
23406 /* Merge any parameters that match with the function parameter
23407 pack. */
23408 if (pattern_parm && DECL_PACK_P (pattern_parm))
23410 int i, len;
23411 tree expanded_types;
23412 /* Expand the TYPE_PACK_EXPANSION that provides the types for
23413 the parameters in this function parameter pack. */
23414 expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
23415 args, tf_error, NULL_TREE);
23416 len = TREE_VEC_LENGTH (expanded_types);
23417 for (i = 0; i < len; i++)
23419 tree parm_type;
23420 tree attributes;
23422 if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23423 /* Rename the parameter to include the index. */
23424 DECL_NAME (decl_parm) =
23425 make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
23426 parm_type = TREE_VEC_ELT (expanded_types, i);
23427 parm_type = type_decays_to (parm_type);
23428 if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23429 TREE_TYPE (decl_parm) = parm_type;
23430 attributes = DECL_ATTRIBUTES (pattern_parm);
23431 if (DECL_ATTRIBUTES (decl_parm) != attributes)
23433 DECL_ATTRIBUTES (decl_parm) = attributes;
23434 cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23436 decl_parm = DECL_CHAIN (decl_parm);
23439 /* Merge additional specifiers from the CODE_PATTERN. */
23440 if (DECL_DECLARED_INLINE_P (code_pattern)
23441 && !DECL_DECLARED_INLINE_P (decl))
23442 DECL_DECLARED_INLINE_P (decl) = 1;
23444 else if (VAR_P (decl))
23446 start_lambda_scope (decl);
23447 DECL_INITIAL (decl) =
23448 tsubst_expr (DECL_INITIAL (code_pattern), args,
23449 tf_error, DECL_TI_TEMPLATE (decl),
23450 /*integral_constant_expression_p=*/false);
23451 finish_lambda_scope ();
23452 if (VAR_HAD_UNKNOWN_BOUND (decl))
23453 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
23454 tf_error, DECL_TI_TEMPLATE (decl));
23456 else
23457 gcc_unreachable ();
23459 pop_access_scope (decl);
23462 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
23463 substituted to get DECL. */
23465 tree
23466 template_for_substitution (tree decl)
23468 tree tmpl = DECL_TI_TEMPLATE (decl);
23470 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23471 for the instantiation. This is not always the most general
23472 template. Consider, for example:
23474 template <class T>
23475 struct S { template <class U> void f();
23476 template <> void f<int>(); };
23478 and an instantiation of S<double>::f<int>. We want TD to be the
23479 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
23480 while (/* An instantiation cannot have a definition, so we need a
23481 more general template. */
23482 DECL_TEMPLATE_INSTANTIATION (tmpl)
23483 /* We must also deal with friend templates. Given:
23485 template <class T> struct S {
23486 template <class U> friend void f() {};
23489 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23490 so far as the language is concerned, but that's still
23491 where we get the pattern for the instantiation from. On
23492 other hand, if the definition comes outside the class, say:
23494 template <class T> struct S {
23495 template <class U> friend void f();
23497 template <class U> friend void f() {}
23499 we don't need to look any further. That's what the check for
23500 DECL_INITIAL is for. */
23501 || (TREE_CODE (decl) == FUNCTION_DECL
23502 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23503 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23505 /* The present template, TD, should not be a definition. If it
23506 were a definition, we should be using it! Note that we
23507 cannot restructure the loop to just keep going until we find
23508 a template with a definition, since that might go too far if
23509 a specialization was declared, but not defined. */
23511 /* Fetch the more general template. */
23512 tmpl = DECL_TI_TEMPLATE (tmpl);
23515 return tmpl;
23518 /* Returns true if we need to instantiate this template instance even if we
23519 know we aren't going to emit it. */
23521 bool
23522 always_instantiate_p (tree decl)
23524 /* We always instantiate inline functions so that we can inline them. An
23525 explicit instantiation declaration prohibits implicit instantiation of
23526 non-inline functions. With high levels of optimization, we would
23527 normally inline non-inline functions -- but we're not allowed to do
23528 that for "extern template" functions. Therefore, we check
23529 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
23530 return ((TREE_CODE (decl) == FUNCTION_DECL
23531 && (DECL_DECLARED_INLINE_P (decl)
23532 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23533 /* And we need to instantiate static data members so that
23534 their initializers are available in integral constant
23535 expressions. */
23536 || (VAR_P (decl)
23537 && decl_maybe_constant_var_p (decl)));
23540 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23541 instantiate it now, modifying TREE_TYPE (fn). Returns false on
23542 error, true otherwise. */
23544 bool
23545 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23547 tree fntype, spec, noex, clone;
23549 /* Don't instantiate a noexcept-specification from template context. */
23550 if (processing_template_decl
23551 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
23552 return true;
23554 if (DECL_CLONED_FUNCTION_P (fn))
23555 fn = DECL_CLONED_FUNCTION (fn);
23556 fntype = TREE_TYPE (fn);
23557 spec = TYPE_RAISES_EXCEPTIONS (fntype);
23559 if (!spec || !TREE_PURPOSE (spec))
23560 return true;
23562 noex = TREE_PURPOSE (spec);
23564 if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23566 static hash_set<tree>* fns = new hash_set<tree>;
23567 bool added = false;
23568 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23569 spec = get_defaulted_eh_spec (fn, complain);
23570 else if (!(added = !fns->add (fn)))
23572 /* If hash_set::add returns true, the element was already there. */
23573 location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23574 DECL_SOURCE_LOCATION (fn));
23575 error_at (loc,
23576 "exception specification of %qD depends on itself",
23577 fn);
23578 spec = noexcept_false_spec;
23580 else if (push_tinst_level (fn))
23582 push_access_scope (fn);
23583 push_deferring_access_checks (dk_no_deferred);
23584 input_location = DECL_SOURCE_LOCATION (fn);
23585 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23586 DEFERRED_NOEXCEPT_ARGS (noex),
23587 tf_warning_or_error, fn,
23588 /*function_p=*/false,
23589 /*integral_constant_expression_p=*/true);
23590 spec = build_noexcept_spec (noex, tf_warning_or_error);
23591 pop_deferring_access_checks ();
23592 pop_access_scope (fn);
23593 pop_tinst_level ();
23594 if (spec == error_mark_node)
23595 spec = noexcept_false_spec;
23597 else
23598 spec = noexcept_false_spec;
23600 if (added)
23601 fns->remove (fn);
23603 if (spec == error_mark_node)
23604 return false;
23606 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23609 FOR_EACH_CLONE (clone, fn)
23611 if (TREE_TYPE (clone) == fntype)
23612 TREE_TYPE (clone) = TREE_TYPE (fn);
23613 else
23614 TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23617 return true;
23620 /* We're starting to process the function INST, an instantiation of PATTERN;
23621 add their parameters to local_specializations. */
23623 static void
23624 register_parameter_specializations (tree pattern, tree inst)
23626 tree tmpl_parm = DECL_ARGUMENTS (pattern);
23627 tree spec_parm = DECL_ARGUMENTS (inst);
23628 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23630 register_local_specialization (spec_parm, tmpl_parm);
23631 spec_parm = skip_artificial_parms_for (inst, spec_parm);
23632 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23634 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23636 if (!DECL_PACK_P (tmpl_parm))
23638 register_local_specialization (spec_parm, tmpl_parm);
23639 spec_parm = DECL_CHAIN (spec_parm);
23641 else
23643 /* Register the (value) argument pack as a specialization of
23644 TMPL_PARM, then move on. */
23645 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23646 register_local_specialization (argpack, tmpl_parm);
23649 gcc_assert (!spec_parm);
23652 /* Produce the definition of D, a _DECL generated from a template. If
23653 DEFER_OK is true, then we don't have to actually do the
23654 instantiation now; we just have to do it sometime. Normally it is
23655 an error if this is an explicit instantiation but D is undefined.
23656 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23657 instantiated class template. */
23659 tree
23660 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23662 tree tmpl = DECL_TI_TEMPLATE (d);
23663 tree gen_args;
23664 tree args;
23665 tree td;
23666 tree code_pattern;
23667 tree spec;
23668 tree gen_tmpl;
23669 bool pattern_defined;
23670 location_t saved_loc = input_location;
23671 int saved_unevaluated_operand = cp_unevaluated_operand;
23672 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23673 bool external_p;
23674 bool deleted_p;
23676 /* This function should only be used to instantiate templates for
23677 functions and static member variables. */
23678 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23680 /* A concept is never instantiated. */
23681 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23683 /* Variables are never deferred; if instantiation is required, they
23684 are instantiated right away. That allows for better code in the
23685 case that an expression refers to the value of the variable --
23686 if the variable has a constant value the referring expression can
23687 take advantage of that fact. */
23688 if (VAR_P (d))
23689 defer_ok = false;
23691 /* Don't instantiate cloned functions. Instead, instantiate the
23692 functions they cloned. */
23693 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23694 d = DECL_CLONED_FUNCTION (d);
23696 if (DECL_TEMPLATE_INSTANTIATED (d)
23697 || (TREE_CODE (d) == FUNCTION_DECL
23698 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23699 || DECL_TEMPLATE_SPECIALIZATION (d))
23700 /* D has already been instantiated or explicitly specialized, so
23701 there's nothing for us to do here.
23703 It might seem reasonable to check whether or not D is an explicit
23704 instantiation, and, if so, stop here. But when an explicit
23705 instantiation is deferred until the end of the compilation,
23706 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23707 the instantiation. */
23708 return d;
23710 /* Check to see whether we know that this template will be
23711 instantiated in some other file, as with "extern template"
23712 extension. */
23713 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23715 /* In general, we do not instantiate such templates. */
23716 if (external_p && !always_instantiate_p (d))
23717 return d;
23719 gen_tmpl = most_general_template (tmpl);
23720 gen_args = DECL_TI_ARGS (d);
23722 if (tmpl != gen_tmpl)
23723 /* We should already have the extra args. */
23724 gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23725 == TMPL_ARGS_DEPTH (gen_args));
23726 /* And what's in the hash table should match D. */
23727 gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23728 || spec == NULL_TREE);
23730 /* This needs to happen before any tsubsting. */
23731 if (! push_tinst_level (d))
23732 return d;
23734 timevar_push (TV_TEMPLATE_INST);
23736 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23737 for the instantiation. */
23738 td = template_for_substitution (d);
23739 args = gen_args;
23741 if (VAR_P (d))
23743 /* Look up an explicit specialization, if any. */
23744 tree tid = lookup_template_variable (gen_tmpl, gen_args);
23745 tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23746 if (elt && elt != error_mark_node)
23748 td = TREE_VALUE (elt);
23749 args = TREE_PURPOSE (elt);
23753 code_pattern = DECL_TEMPLATE_RESULT (td);
23755 /* We should never be trying to instantiate a member of a class
23756 template or partial specialization. */
23757 gcc_assert (d != code_pattern);
23759 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23760 || DECL_TEMPLATE_SPECIALIZATION (td))
23761 /* In the case of a friend template whose definition is provided
23762 outside the class, we may have too many arguments. Drop the
23763 ones we don't need. The same is true for specializations. */
23764 args = get_innermost_template_args
23765 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23767 if (TREE_CODE (d) == FUNCTION_DECL)
23769 deleted_p = DECL_DELETED_FN (code_pattern);
23770 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23771 && DECL_INITIAL (code_pattern) != error_mark_node)
23772 || DECL_DEFAULTED_FN (code_pattern)
23773 || deleted_p);
23775 else
23777 deleted_p = false;
23778 if (DECL_CLASS_SCOPE_P (code_pattern))
23779 pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23780 || DECL_INLINE_VAR_P (code_pattern));
23781 else
23782 pattern_defined = ! DECL_EXTERNAL (code_pattern);
23785 /* We may be in the middle of deferred access check. Disable it now. */
23786 push_deferring_access_checks (dk_no_deferred);
23788 /* Unless an explicit instantiation directive has already determined
23789 the linkage of D, remember that a definition is available for
23790 this entity. */
23791 if (pattern_defined
23792 && !DECL_INTERFACE_KNOWN (d)
23793 && !DECL_NOT_REALLY_EXTERN (d))
23794 mark_definable (d);
23796 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23797 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23798 input_location = DECL_SOURCE_LOCATION (d);
23800 /* If D is a member of an explicitly instantiated class template,
23801 and no definition is available, treat it like an implicit
23802 instantiation. */
23803 if (!pattern_defined && expl_inst_class_mem_p
23804 && DECL_EXPLICIT_INSTANTIATION (d))
23806 /* Leave linkage flags alone on instantiations with anonymous
23807 visibility. */
23808 if (TREE_PUBLIC (d))
23810 DECL_NOT_REALLY_EXTERN (d) = 0;
23811 DECL_INTERFACE_KNOWN (d) = 0;
23813 SET_DECL_IMPLICIT_INSTANTIATION (d);
23816 /* Defer all other templates, unless we have been explicitly
23817 forbidden from doing so. */
23818 if (/* If there is no definition, we cannot instantiate the
23819 template. */
23820 ! pattern_defined
23821 /* If it's OK to postpone instantiation, do so. */
23822 || defer_ok
23823 /* If this is a static data member that will be defined
23824 elsewhere, we don't want to instantiate the entire data
23825 member, but we do want to instantiate the initializer so that
23826 we can substitute that elsewhere. */
23827 || (external_p && VAR_P (d))
23828 /* Handle here a deleted function too, avoid generating
23829 its body (c++/61080). */
23830 || deleted_p)
23832 /* The definition of the static data member is now required so
23833 we must substitute the initializer. */
23834 if (VAR_P (d)
23835 && !DECL_INITIAL (d)
23836 && DECL_INITIAL (code_pattern))
23838 tree ns;
23839 tree init;
23840 bool const_init = false;
23841 bool enter_context = DECL_CLASS_SCOPE_P (d);
23843 ns = decl_namespace_context (d);
23844 push_nested_namespace (ns);
23845 if (enter_context)
23846 push_nested_class (DECL_CONTEXT (d));
23847 init = tsubst_expr (DECL_INITIAL (code_pattern),
23848 args,
23849 tf_warning_or_error, NULL_TREE,
23850 /*integral_constant_expression_p=*/false);
23851 /* If instantiating the initializer involved instantiating this
23852 again, don't call cp_finish_decl twice. */
23853 if (!DECL_INITIAL (d))
23855 /* Make sure the initializer is still constant, in case of
23856 circular dependency (template/instantiate6.C). */
23857 const_init
23858 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23859 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
23860 /*asmspec_tree=*/NULL_TREE,
23861 LOOKUP_ONLYCONVERTING);
23863 if (enter_context)
23864 pop_nested_class ();
23865 pop_nested_namespace (ns);
23868 /* We restore the source position here because it's used by
23869 add_pending_template. */
23870 input_location = saved_loc;
23872 if (at_eof && !pattern_defined
23873 && DECL_EXPLICIT_INSTANTIATION (d)
23874 && DECL_NOT_REALLY_EXTERN (d))
23875 /* [temp.explicit]
23877 The definition of a non-exported function template, a
23878 non-exported member function template, or a non-exported
23879 member function or static data member of a class template
23880 shall be present in every translation unit in which it is
23881 explicitly instantiated. */
23882 permerror (input_location, "explicit instantiation of %qD "
23883 "but no definition available", d);
23885 /* If we're in unevaluated context, we just wanted to get the
23886 constant value; this isn't an odr use, so don't queue
23887 a full instantiation. */
23888 if (cp_unevaluated_operand != 0)
23889 goto out;
23890 /* ??? Historically, we have instantiated inline functions, even
23891 when marked as "extern template". */
23892 if (!(external_p && VAR_P (d)))
23893 add_pending_template (d);
23894 goto out;
23896 /* Tell the repository that D is available in this translation unit
23897 -- and see if it is supposed to be instantiated here. */
23898 if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
23900 /* In a PCH file, despite the fact that the repository hasn't
23901 requested instantiation in the PCH it is still possible that
23902 an instantiation will be required in a file that includes the
23903 PCH. */
23904 if (pch_file)
23905 add_pending_template (d);
23906 /* Instantiate inline functions so that the inliner can do its
23907 job, even though we'll not be emitting a copy of this
23908 function. */
23909 if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
23910 goto out;
23913 bool push_to_top, nested;
23914 tree fn_context;
23915 fn_context = decl_function_context (d);
23916 if (LAMBDA_FUNCTION_P (d))
23917 /* tsubst_lambda_expr resolved any references to enclosing functions. */
23918 fn_context = NULL_TREE;
23919 nested = current_function_decl != NULL_TREE;
23920 push_to_top = !(nested && fn_context == current_function_decl);
23922 vec<tree> omp_privatization_save;
23923 if (nested)
23924 save_omp_privatization_clauses (omp_privatization_save);
23926 if (push_to_top)
23927 push_to_top_level ();
23928 else
23930 gcc_assert (!processing_template_decl);
23931 push_function_context ();
23932 cp_unevaluated_operand = 0;
23933 c_inhibit_evaluation_warnings = 0;
23936 /* Mark D as instantiated so that recursive calls to
23937 instantiate_decl do not try to instantiate it again. */
23938 DECL_TEMPLATE_INSTANTIATED (d) = 1;
23940 /* Regenerate the declaration in case the template has been modified
23941 by a subsequent redeclaration. */
23942 regenerate_decl_from_template (d, td, args);
23944 /* We already set the file and line above. Reset them now in case
23945 they changed as a result of calling regenerate_decl_from_template. */
23946 input_location = DECL_SOURCE_LOCATION (d);
23948 if (VAR_P (d))
23950 tree init;
23951 bool const_init = false;
23953 /* Clear out DECL_RTL; whatever was there before may not be right
23954 since we've reset the type of the declaration. */
23955 SET_DECL_RTL (d, NULL);
23956 DECL_IN_AGGR_P (d) = 0;
23958 /* The initializer is placed in DECL_INITIAL by
23959 regenerate_decl_from_template so we don't need to
23960 push/pop_access_scope again here. Pull it out so that
23961 cp_finish_decl can process it. */
23962 init = DECL_INITIAL (d);
23963 DECL_INITIAL (d) = NULL_TREE;
23964 DECL_INITIALIZED_P (d) = 0;
23966 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
23967 initializer. That function will defer actual emission until
23968 we have a chance to determine linkage. */
23969 DECL_EXTERNAL (d) = 0;
23971 /* Enter the scope of D so that access-checking works correctly. */
23972 bool enter_context = DECL_CLASS_SCOPE_P (d);
23973 if (enter_context)
23974 push_nested_class (DECL_CONTEXT (d));
23976 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23977 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
23979 if (enter_context)
23980 pop_nested_class ();
23982 if (variable_template_p (gen_tmpl))
23983 note_variable_template_instantiation (d);
23985 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
23986 synthesize_method (d);
23987 else if (TREE_CODE (d) == FUNCTION_DECL)
23989 /* Set up the list of local specializations. */
23990 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
23991 tree block = NULL_TREE;
23993 /* Set up context. */
23994 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
23995 && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
23996 block = push_stmt_list ();
23997 else
23998 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
24000 /* Some typedefs referenced from within the template code need to be
24001 access checked at template instantiation time, i.e now. These
24002 types were added to the template at parsing time. Let's get those
24003 and perform the access checks then. */
24004 perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
24005 args);
24007 /* Create substitution entries for the parameters. */
24008 register_parameter_specializations (code_pattern, d);
24010 /* Substitute into the body of the function. */
24011 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24012 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
24013 tf_warning_or_error, tmpl);
24014 else
24016 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
24017 tf_warning_or_error, tmpl,
24018 /*integral_constant_expression_p=*/false);
24020 /* Set the current input_location to the end of the function
24021 so that finish_function knows where we are. */
24022 input_location
24023 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
24025 /* Remember if we saw an infinite loop in the template. */
24026 current_function_infinite_loop
24027 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
24030 /* Finish the function. */
24031 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24032 && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24033 DECL_SAVED_TREE (d) = pop_stmt_list (block);
24034 else
24036 d = finish_function (/*inline_p=*/false);
24037 expand_or_defer_fn (d);
24040 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24041 cp_check_omp_declare_reduction (d);
24044 /* We're not deferring instantiation any more. */
24045 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24047 if (push_to_top)
24048 pop_from_top_level ();
24049 else
24050 pop_function_context ();
24052 if (nested)
24053 restore_omp_privatization_clauses (omp_privatization_save);
24055 out:
24056 pop_deferring_access_checks ();
24057 timevar_pop (TV_TEMPLATE_INST);
24058 pop_tinst_level ();
24059 input_location = saved_loc;
24060 cp_unevaluated_operand = saved_unevaluated_operand;
24061 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24063 return d;
24066 /* Run through the list of templates that we wish we could
24067 instantiate, and instantiate any we can. RETRIES is the
24068 number of times we retry pending template instantiation. */
24070 void
24071 instantiate_pending_templates (int retries)
24073 int reconsider;
24074 location_t saved_loc = input_location;
24076 /* Instantiating templates may trigger vtable generation. This in turn
24077 may require further template instantiations. We place a limit here
24078 to avoid infinite loop. */
24079 if (pending_templates && retries >= max_tinst_depth)
24081 tree decl = pending_templates->tinst->maybe_get_node ();
24083 fatal_error (input_location,
24084 "template instantiation depth exceeds maximum of %d"
24085 " instantiating %q+D, possibly from virtual table generation"
24086 " (use -ftemplate-depth= to increase the maximum)",
24087 max_tinst_depth, decl);
24088 if (TREE_CODE (decl) == FUNCTION_DECL)
24089 /* Pretend that we defined it. */
24090 DECL_INITIAL (decl) = error_mark_node;
24091 return;
24096 struct pending_template **t = &pending_templates;
24097 struct pending_template *last = NULL;
24098 reconsider = 0;
24099 while (*t)
24101 tree instantiation = reopen_tinst_level ((*t)->tinst);
24102 bool complete = false;
24104 if (TYPE_P (instantiation))
24106 if (!COMPLETE_TYPE_P (instantiation))
24108 instantiate_class_template (instantiation);
24109 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24110 for (tree fld = TYPE_FIELDS (instantiation);
24111 fld; fld = TREE_CHAIN (fld))
24112 if ((VAR_P (fld)
24113 || (TREE_CODE (fld) == FUNCTION_DECL
24114 && !DECL_ARTIFICIAL (fld)))
24115 && DECL_TEMPLATE_INSTANTIATION (fld))
24116 instantiate_decl (fld,
24117 /*defer_ok=*/false,
24118 /*expl_inst_class_mem_p=*/false);
24120 if (COMPLETE_TYPE_P (instantiation))
24121 reconsider = 1;
24124 complete = COMPLETE_TYPE_P (instantiation);
24126 else
24128 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24129 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24131 instantiation
24132 = instantiate_decl (instantiation,
24133 /*defer_ok=*/false,
24134 /*expl_inst_class_mem_p=*/false);
24135 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24136 reconsider = 1;
24139 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24140 || DECL_TEMPLATE_INSTANTIATED (instantiation));
24143 if (complete)
24145 /* If INSTANTIATION has been instantiated, then we don't
24146 need to consider it again in the future. */
24147 struct pending_template *drop = *t;
24148 *t = (*t)->next;
24149 set_refcount_ptr (drop->tinst);
24150 pending_template_freelist ().free (drop);
24152 else
24154 last = *t;
24155 t = &(*t)->next;
24157 tinst_depth = 0;
24158 set_refcount_ptr (current_tinst_level);
24160 last_pending_template = last;
24162 while (reconsider);
24164 input_location = saved_loc;
24167 /* Substitute ARGVEC into T, which is a list of initializers for
24168 either base class or a non-static data member. The TREE_PURPOSEs
24169 are DECLs, and the TREE_VALUEs are the initializer values. Used by
24170 instantiate_decl. */
24172 static tree
24173 tsubst_initializer_list (tree t, tree argvec)
24175 tree inits = NULL_TREE;
24176 tree target_ctor = error_mark_node;
24178 for (; t; t = TREE_CHAIN (t))
24180 tree decl;
24181 tree init;
24182 tree expanded_bases = NULL_TREE;
24183 tree expanded_arguments = NULL_TREE;
24184 int i, len = 1;
24186 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24188 tree expr;
24189 tree arg;
24191 /* Expand the base class expansion type into separate base
24192 classes. */
24193 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24194 tf_warning_or_error,
24195 NULL_TREE);
24196 if (expanded_bases == error_mark_node)
24197 continue;
24199 /* We'll be building separate TREE_LISTs of arguments for
24200 each base. */
24201 len = TREE_VEC_LENGTH (expanded_bases);
24202 expanded_arguments = make_tree_vec (len);
24203 for (i = 0; i < len; i++)
24204 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24206 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24207 expand each argument in the TREE_VALUE of t. */
24208 expr = make_node (EXPR_PACK_EXPANSION);
24209 PACK_EXPANSION_LOCAL_P (expr) = true;
24210 PACK_EXPANSION_PARAMETER_PACKS (expr) =
24211 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24213 if (TREE_VALUE (t) == void_type_node)
24214 /* VOID_TYPE_NODE is used to indicate
24215 value-initialization. */
24217 for (i = 0; i < len; i++)
24218 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24220 else
24222 /* Substitute parameter packs into each argument in the
24223 TREE_LIST. */
24224 in_base_initializer = 1;
24225 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
24227 tree expanded_exprs;
24229 /* Expand the argument. */
24230 SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
24231 expanded_exprs
24232 = tsubst_pack_expansion (expr, argvec,
24233 tf_warning_or_error,
24234 NULL_TREE);
24235 if (expanded_exprs == error_mark_node)
24236 continue;
24238 /* Prepend each of the expanded expressions to the
24239 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
24240 for (i = 0; i < len; i++)
24242 TREE_VEC_ELT (expanded_arguments, i) =
24243 tree_cons (NULL_TREE,
24244 TREE_VEC_ELT (expanded_exprs, i),
24245 TREE_VEC_ELT (expanded_arguments, i));
24248 in_base_initializer = 0;
24250 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
24251 since we built them backwards. */
24252 for (i = 0; i < len; i++)
24254 TREE_VEC_ELT (expanded_arguments, i) =
24255 nreverse (TREE_VEC_ELT (expanded_arguments, i));
24260 for (i = 0; i < len; ++i)
24262 if (expanded_bases)
24264 decl = TREE_VEC_ELT (expanded_bases, i);
24265 decl = expand_member_init (decl);
24266 init = TREE_VEC_ELT (expanded_arguments, i);
24268 else
24270 tree tmp;
24271 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
24272 tf_warning_or_error, NULL_TREE);
24274 decl = expand_member_init (decl);
24275 if (decl && !DECL_P (decl))
24276 in_base_initializer = 1;
24278 init = TREE_VALUE (t);
24279 tmp = init;
24280 if (init != void_type_node)
24281 init = tsubst_expr (init, argvec,
24282 tf_warning_or_error, NULL_TREE,
24283 /*integral_constant_expression_p=*/false);
24284 if (init == NULL_TREE && tmp != NULL_TREE)
24285 /* If we had an initializer but it instantiated to nothing,
24286 value-initialize the object. This will only occur when
24287 the initializer was a pack expansion where the parameter
24288 packs used in that expansion were of length zero. */
24289 init = void_type_node;
24290 in_base_initializer = 0;
24293 if (target_ctor != error_mark_node
24294 && init != error_mark_node)
24296 error ("mem-initializer for %qD follows constructor delegation",
24297 decl);
24298 return inits;
24300 /* Look for a target constructor. */
24301 if (init != error_mark_node
24302 && decl && CLASS_TYPE_P (decl)
24303 && same_type_p (decl, current_class_type))
24305 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
24306 if (inits)
24308 error ("constructor delegation follows mem-initializer for %qD",
24309 TREE_PURPOSE (inits));
24310 continue;
24312 target_ctor = init;
24315 if (decl)
24317 init = build_tree_list (decl, init);
24318 TREE_CHAIN (init) = inits;
24319 inits = init;
24323 return inits;
24326 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL. */
24328 static void
24329 set_current_access_from_decl (tree decl)
24331 if (TREE_PRIVATE (decl))
24332 current_access_specifier = access_private_node;
24333 else if (TREE_PROTECTED (decl))
24334 current_access_specifier = access_protected_node;
24335 else
24336 current_access_specifier = access_public_node;
24339 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
24340 is the instantiation (which should have been created with
24341 start_enum) and ARGS are the template arguments to use. */
24343 static void
24344 tsubst_enum (tree tag, tree newtag, tree args)
24346 tree e;
24348 if (SCOPED_ENUM_P (newtag))
24349 begin_scope (sk_scoped_enum, newtag);
24351 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
24353 tree value;
24354 tree decl;
24356 decl = TREE_VALUE (e);
24357 /* Note that in a template enum, the TREE_VALUE is the
24358 CONST_DECL, not the corresponding INTEGER_CST. */
24359 value = tsubst_expr (DECL_INITIAL (decl),
24360 args, tf_warning_or_error, NULL_TREE,
24361 /*integral_constant_expression_p=*/true);
24363 /* Give this enumeration constant the correct access. */
24364 set_current_access_from_decl (decl);
24366 /* Actually build the enumerator itself. Here we're assuming that
24367 enumerators can't have dependent attributes. */
24368 build_enumerator (DECL_NAME (decl), value, newtag,
24369 DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
24372 if (SCOPED_ENUM_P (newtag))
24373 finish_scope ();
24375 finish_enum_value_list (newtag);
24376 finish_enum (newtag);
24378 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
24379 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
24382 /* DECL is a FUNCTION_DECL that is a template specialization. Return
24383 its type -- but without substituting the innermost set of template
24384 arguments. So, innermost set of template parameters will appear in
24385 the type. */
24387 tree
24388 get_mostly_instantiated_function_type (tree decl)
24390 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
24391 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
24394 /* Return truthvalue if we're processing a template different from
24395 the last one involved in diagnostics. */
24396 bool
24397 problematic_instantiation_changed (void)
24399 return current_tinst_level != last_error_tinst_level;
24402 /* Remember current template involved in diagnostics. */
24403 void
24404 record_last_problematic_instantiation (void)
24406 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
24409 struct tinst_level *
24410 current_instantiation (void)
24412 return current_tinst_level;
24415 /* Return TRUE if current_function_decl is being instantiated, false
24416 otherwise. */
24418 bool
24419 instantiating_current_function_p (void)
24421 return (current_instantiation ()
24422 && (current_instantiation ()->maybe_get_node ()
24423 == current_function_decl));
24426 /* [temp.param] Check that template non-type parm TYPE is of an allowable
24427 type. Return false for ok, true for disallowed. Issue error and
24428 inform messages under control of COMPLAIN. */
24430 static bool
24431 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
24433 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
24434 return false;
24435 else if (TYPE_PTR_P (type))
24436 return false;
24437 else if (TYPE_REF_P (type)
24438 && !TYPE_REF_IS_RVALUE (type))
24439 return false;
24440 else if (TYPE_PTRMEM_P (type))
24441 return false;
24442 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
24443 return false;
24444 else if (TREE_CODE (type) == TYPENAME_TYPE)
24445 return false;
24446 else if (TREE_CODE (type) == DECLTYPE_TYPE)
24447 return false;
24448 else if (TREE_CODE (type) == NULLPTR_TYPE)
24449 return false;
24450 /* A bound template template parm could later be instantiated to have a valid
24451 nontype parm type via an alias template. */
24452 else if (cxx_dialect >= cxx11
24453 && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24454 return false;
24456 if (complain & tf_error)
24458 if (type == error_mark_node)
24459 inform (input_location, "invalid template non-type parameter");
24460 else
24461 error ("%q#T is not a valid type for a template non-type parameter",
24462 type);
24464 return true;
24467 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
24468 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
24470 static bool
24471 dependent_type_p_r (tree type)
24473 tree scope;
24475 /* [temp.dep.type]
24477 A type is dependent if it is:
24479 -- a template parameter. Template template parameters are types
24480 for us (since TYPE_P holds true for them) so we handle
24481 them here. */
24482 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24483 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
24484 return true;
24485 /* -- a qualified-id with a nested-name-specifier which contains a
24486 class-name that names a dependent type or whose unqualified-id
24487 names a dependent type. */
24488 if (TREE_CODE (type) == TYPENAME_TYPE)
24489 return true;
24491 /* An alias template specialization can be dependent even if the
24492 resulting type is not. */
24493 if (dependent_alias_template_spec_p (type))
24494 return true;
24496 /* -- a cv-qualified type where the cv-unqualified type is
24497 dependent.
24498 No code is necessary for this bullet; the code below handles
24499 cv-qualified types, and we don't want to strip aliases with
24500 TYPE_MAIN_VARIANT because of DR 1558. */
24501 /* -- a compound type constructed from any dependent type. */
24502 if (TYPE_PTRMEM_P (type))
24503 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24504 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24505 (type)));
24506 else if (INDIRECT_TYPE_P (type))
24507 return dependent_type_p (TREE_TYPE (type));
24508 else if (TREE_CODE (type) == FUNCTION_TYPE
24509 || TREE_CODE (type) == METHOD_TYPE)
24511 tree arg_type;
24513 if (dependent_type_p (TREE_TYPE (type)))
24514 return true;
24515 for (arg_type = TYPE_ARG_TYPES (type);
24516 arg_type;
24517 arg_type = TREE_CHAIN (arg_type))
24518 if (dependent_type_p (TREE_VALUE (arg_type)))
24519 return true;
24520 if (cxx_dialect >= cxx17)
24521 /* A value-dependent noexcept-specifier makes the type dependent. */
24522 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24523 if (tree noex = TREE_PURPOSE (spec))
24524 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24525 affect overload resolution and treating it as dependent breaks
24526 things. */
24527 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24528 && value_dependent_expression_p (noex))
24529 return true;
24530 return false;
24532 /* -- an array type constructed from any dependent type or whose
24533 size is specified by a constant expression that is
24534 value-dependent.
24536 We checked for type- and value-dependence of the bounds in
24537 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
24538 if (TREE_CODE (type) == ARRAY_TYPE)
24540 if (TYPE_DOMAIN (type)
24541 && dependent_type_p (TYPE_DOMAIN (type)))
24542 return true;
24543 return dependent_type_p (TREE_TYPE (type));
24546 /* -- a template-id in which either the template name is a template
24547 parameter ... */
24548 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24549 return true;
24550 /* ... or any of the template arguments is a dependent type or
24551 an expression that is type-dependent or value-dependent. */
24552 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24553 && (any_dependent_template_arguments_p
24554 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24555 return true;
24557 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24558 dependent; if the argument of the `typeof' expression is not
24559 type-dependent, then it should already been have resolved. */
24560 if (TREE_CODE (type) == TYPEOF_TYPE
24561 || TREE_CODE (type) == DECLTYPE_TYPE
24562 || TREE_CODE (type) == UNDERLYING_TYPE)
24563 return true;
24565 /* A template argument pack is dependent if any of its packed
24566 arguments are. */
24567 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24569 tree args = ARGUMENT_PACK_ARGS (type);
24570 int i, len = TREE_VEC_LENGTH (args);
24571 for (i = 0; i < len; ++i)
24572 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24573 return true;
24576 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24577 be template parameters. */
24578 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24579 return true;
24581 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24582 return true;
24584 /* The standard does not specifically mention types that are local
24585 to template functions or local classes, but they should be
24586 considered dependent too. For example:
24588 template <int I> void f() {
24589 enum E { a = I };
24590 S<sizeof (E)> s;
24593 The size of `E' cannot be known until the value of `I' has been
24594 determined. Therefore, `E' must be considered dependent. */
24595 scope = TYPE_CONTEXT (type);
24596 if (scope && TYPE_P (scope))
24597 return dependent_type_p (scope);
24598 /* Don't use type_dependent_expression_p here, as it can lead
24599 to infinite recursion trying to determine whether a lambda
24600 nested in a lambda is dependent (c++/47687). */
24601 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24602 && DECL_LANG_SPECIFIC (scope)
24603 && DECL_TEMPLATE_INFO (scope)
24604 && (any_dependent_template_arguments_p
24605 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24606 return true;
24608 /* Other types are non-dependent. */
24609 return false;
24612 /* Returns TRUE if TYPE is dependent, in the sense of
24613 [temp.dep.type]. Note that a NULL type is considered dependent. */
24615 bool
24616 dependent_type_p (tree type)
24618 /* If there are no template parameters in scope, then there can't be
24619 any dependent types. */
24620 if (!processing_template_decl)
24622 /* If we are not processing a template, then nobody should be
24623 providing us with a dependent type. */
24624 gcc_assert (type);
24625 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24626 return false;
24629 /* If the type is NULL, we have not computed a type for the entity
24630 in question; in that case, the type is dependent. */
24631 if (!type)
24632 return true;
24634 /* Erroneous types can be considered non-dependent. */
24635 if (type == error_mark_node)
24636 return false;
24638 /* Getting here with global_type_node means we improperly called this
24639 function on the TREE_TYPE of an IDENTIFIER_NODE. */
24640 gcc_checking_assert (type != global_type_node);
24642 /* If we have not already computed the appropriate value for TYPE,
24643 do so now. */
24644 if (!TYPE_DEPENDENT_P_VALID (type))
24646 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24647 TYPE_DEPENDENT_P_VALID (type) = 1;
24650 return TYPE_DEPENDENT_P (type);
24653 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24654 lookup. In other words, a dependent type that is not the current
24655 instantiation. */
24657 bool
24658 dependent_scope_p (tree scope)
24660 return (scope && TYPE_P (scope) && dependent_type_p (scope)
24661 && !currently_open_class (scope));
24664 /* T is a SCOPE_REF. Return whether it represents a non-static member of
24665 an unknown base of 'this' (and is therefore instantiation-dependent). */
24667 static bool
24668 unknown_base_ref_p (tree t)
24670 if (!current_class_ptr)
24671 return false;
24673 tree mem = TREE_OPERAND (t, 1);
24674 if (shared_member_p (mem))
24675 return false;
24677 tree cur = current_nonlambda_class_type ();
24678 if (!any_dependent_bases_p (cur))
24679 return false;
24681 tree ctx = TREE_OPERAND (t, 0);
24682 if (DERIVED_FROM_P (ctx, cur))
24683 return false;
24685 return true;
24688 /* T is a SCOPE_REF; return whether we need to consider it
24689 instantiation-dependent so that we can check access at instantiation
24690 time even though we know which member it resolves to. */
24692 static bool
24693 instantiation_dependent_scope_ref_p (tree t)
24695 if (DECL_P (TREE_OPERAND (t, 1))
24696 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24697 && !unknown_base_ref_p (t)
24698 && accessible_in_template_p (TREE_OPERAND (t, 0),
24699 TREE_OPERAND (t, 1)))
24700 return false;
24701 else
24702 return true;
24705 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24706 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
24707 expression. */
24709 /* Note that this predicate is not appropriate for general expressions;
24710 only constant expressions (that satisfy potential_constant_expression)
24711 can be tested for value dependence. */
24713 bool
24714 value_dependent_expression_p (tree expression)
24716 if (!processing_template_decl || expression == NULL_TREE)
24717 return false;
24719 /* A type-dependent expression is also value-dependent. */
24720 if (type_dependent_expression_p (expression))
24721 return true;
24723 switch (TREE_CODE (expression))
24725 case BASELINK:
24726 /* A dependent member function of the current instantiation. */
24727 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24729 case FUNCTION_DECL:
24730 /* A dependent member function of the current instantiation. */
24731 if (DECL_CLASS_SCOPE_P (expression)
24732 && dependent_type_p (DECL_CONTEXT (expression)))
24733 return true;
24734 break;
24736 case IDENTIFIER_NODE:
24737 /* A name that has not been looked up -- must be dependent. */
24738 return true;
24740 case TEMPLATE_PARM_INDEX:
24741 /* A non-type template parm. */
24742 return true;
24744 case CONST_DECL:
24745 /* A non-type template parm. */
24746 if (DECL_TEMPLATE_PARM_P (expression))
24747 return true;
24748 return value_dependent_expression_p (DECL_INITIAL (expression));
24750 case VAR_DECL:
24751 /* A constant with literal type and is initialized
24752 with an expression that is value-dependent. */
24753 if (DECL_DEPENDENT_INIT_P (expression)
24754 /* FIXME cp_finish_decl doesn't fold reference initializers. */
24755 || TYPE_REF_P (TREE_TYPE (expression)))
24756 return true;
24757 if (DECL_HAS_VALUE_EXPR_P (expression))
24759 tree value_expr = DECL_VALUE_EXPR (expression);
24760 if (value_dependent_expression_p (value_expr))
24761 return true;
24763 return false;
24765 case DYNAMIC_CAST_EXPR:
24766 case STATIC_CAST_EXPR:
24767 case CONST_CAST_EXPR:
24768 case REINTERPRET_CAST_EXPR:
24769 case CAST_EXPR:
24770 case IMPLICIT_CONV_EXPR:
24771 /* These expressions are value-dependent if the type to which
24772 the cast occurs is dependent or the expression being casted
24773 is value-dependent. */
24775 tree type = TREE_TYPE (expression);
24777 if (dependent_type_p (type))
24778 return true;
24780 /* A functional cast has a list of operands. */
24781 expression = TREE_OPERAND (expression, 0);
24782 if (!expression)
24784 /* If there are no operands, it must be an expression such
24785 as "int()". This should not happen for aggregate types
24786 because it would form non-constant expressions. */
24787 gcc_assert (cxx_dialect >= cxx11
24788 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24790 return false;
24793 if (TREE_CODE (expression) == TREE_LIST)
24794 return any_value_dependent_elements_p (expression);
24796 return value_dependent_expression_p (expression);
24799 case SIZEOF_EXPR:
24800 if (SIZEOF_EXPR_TYPE_P (expression))
24801 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24802 /* FALLTHRU */
24803 case ALIGNOF_EXPR:
24804 case TYPEID_EXPR:
24805 /* A `sizeof' expression is value-dependent if the operand is
24806 type-dependent or is a pack expansion. */
24807 expression = TREE_OPERAND (expression, 0);
24808 if (PACK_EXPANSION_P (expression))
24809 return true;
24810 else if (TYPE_P (expression))
24811 return dependent_type_p (expression);
24812 return instantiation_dependent_uneval_expression_p (expression);
24814 case AT_ENCODE_EXPR:
24815 /* An 'encode' expression is value-dependent if the operand is
24816 type-dependent. */
24817 expression = TREE_OPERAND (expression, 0);
24818 return dependent_type_p (expression);
24820 case NOEXCEPT_EXPR:
24821 expression = TREE_OPERAND (expression, 0);
24822 return instantiation_dependent_uneval_expression_p (expression);
24824 case SCOPE_REF:
24825 /* All instantiation-dependent expressions should also be considered
24826 value-dependent. */
24827 return instantiation_dependent_scope_ref_p (expression);
24829 case COMPONENT_REF:
24830 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
24831 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
24833 case NONTYPE_ARGUMENT_PACK:
24834 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
24835 is value-dependent. */
24837 tree values = ARGUMENT_PACK_ARGS (expression);
24838 int i, len = TREE_VEC_LENGTH (values);
24840 for (i = 0; i < len; ++i)
24841 if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
24842 return true;
24844 return false;
24847 case TRAIT_EXPR:
24849 tree type2 = TRAIT_EXPR_TYPE2 (expression);
24851 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
24852 return true;
24854 if (!type2)
24855 return false;
24857 if (TREE_CODE (type2) != TREE_LIST)
24858 return dependent_type_p (type2);
24860 for (; type2; type2 = TREE_CHAIN (type2))
24861 if (dependent_type_p (TREE_VALUE (type2)))
24862 return true;
24864 return false;
24867 case MODOP_EXPR:
24868 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24869 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
24871 case ARRAY_REF:
24872 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24873 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
24875 case ADDR_EXPR:
24877 tree op = TREE_OPERAND (expression, 0);
24878 return (value_dependent_expression_p (op)
24879 || has_value_dependent_address (op));
24882 case REQUIRES_EXPR:
24883 /* Treat all requires-expressions as value-dependent so
24884 we don't try to fold them. */
24885 return true;
24887 case TYPE_REQ:
24888 return dependent_type_p (TREE_OPERAND (expression, 0));
24890 case CALL_EXPR:
24892 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
24893 return true;
24894 tree fn = get_callee_fndecl (expression);
24895 int i, nargs;
24896 nargs = call_expr_nargs (expression);
24897 for (i = 0; i < nargs; ++i)
24899 tree op = CALL_EXPR_ARG (expression, i);
24900 /* In a call to a constexpr member function, look through the
24901 implicit ADDR_EXPR on the object argument so that it doesn't
24902 cause the call to be considered value-dependent. We also
24903 look through it in potential_constant_expression. */
24904 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
24905 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
24906 && TREE_CODE (op) == ADDR_EXPR)
24907 op = TREE_OPERAND (op, 0);
24908 if (value_dependent_expression_p (op))
24909 return true;
24911 return false;
24914 case TEMPLATE_ID_EXPR:
24915 return variable_concept_p (TREE_OPERAND (expression, 0));
24917 case CONSTRUCTOR:
24919 unsigned ix;
24920 tree val;
24921 if (dependent_type_p (TREE_TYPE (expression)))
24922 return true;
24923 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
24924 if (value_dependent_expression_p (val))
24925 return true;
24926 return false;
24929 case STMT_EXPR:
24930 /* Treat a GNU statement expression as dependent to avoid crashing
24931 under instantiate_non_dependent_expr; it can't be constant. */
24932 return true;
24934 default:
24935 /* A constant expression is value-dependent if any subexpression is
24936 value-dependent. */
24937 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
24939 case tcc_reference:
24940 case tcc_unary:
24941 case tcc_comparison:
24942 case tcc_binary:
24943 case tcc_expression:
24944 case tcc_vl_exp:
24946 int i, len = cp_tree_operand_length (expression);
24948 for (i = 0; i < len; i++)
24950 tree t = TREE_OPERAND (expression, i);
24952 /* In some cases, some of the operands may be missing.
24953 (For example, in the case of PREDECREMENT_EXPR, the
24954 amount to increment by may be missing.) That doesn't
24955 make the expression dependent. */
24956 if (t && value_dependent_expression_p (t))
24957 return true;
24960 break;
24961 default:
24962 break;
24964 break;
24967 /* The expression is not value-dependent. */
24968 return false;
24971 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
24972 [temp.dep.expr]. Note that an expression with no type is
24973 considered dependent. Other parts of the compiler arrange for an
24974 expression with type-dependent subexpressions to have no type, so
24975 this function doesn't have to be fully recursive. */
24977 bool
24978 type_dependent_expression_p (tree expression)
24980 if (!processing_template_decl)
24981 return false;
24983 if (expression == NULL_TREE || expression == error_mark_node)
24984 return false;
24986 STRIP_ANY_LOCATION_WRAPPER (expression);
24988 /* An unresolved name is always dependent. */
24989 if (identifier_p (expression)
24990 || TREE_CODE (expression) == USING_DECL
24991 || TREE_CODE (expression) == WILDCARD_DECL)
24992 return true;
24994 /* A fold expression is type-dependent. */
24995 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
24996 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
24997 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
24998 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
24999 return true;
25001 /* Some expression forms are never type-dependent. */
25002 if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
25003 || TREE_CODE (expression) == SIZEOF_EXPR
25004 || TREE_CODE (expression) == ALIGNOF_EXPR
25005 || TREE_CODE (expression) == AT_ENCODE_EXPR
25006 || TREE_CODE (expression) == NOEXCEPT_EXPR
25007 || TREE_CODE (expression) == TRAIT_EXPR
25008 || TREE_CODE (expression) == TYPEID_EXPR
25009 || TREE_CODE (expression) == DELETE_EXPR
25010 || TREE_CODE (expression) == VEC_DELETE_EXPR
25011 || TREE_CODE (expression) == THROW_EXPR
25012 || TREE_CODE (expression) == REQUIRES_EXPR)
25013 return false;
25015 /* The types of these expressions depends only on the type to which
25016 the cast occurs. */
25017 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
25018 || TREE_CODE (expression) == STATIC_CAST_EXPR
25019 || TREE_CODE (expression) == CONST_CAST_EXPR
25020 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
25021 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
25022 || TREE_CODE (expression) == CAST_EXPR)
25023 return dependent_type_p (TREE_TYPE (expression));
25025 /* The types of these expressions depends only on the type created
25026 by the expression. */
25027 if (TREE_CODE (expression) == NEW_EXPR
25028 || TREE_CODE (expression) == VEC_NEW_EXPR)
25030 /* For NEW_EXPR tree nodes created inside a template, either
25031 the object type itself or a TREE_LIST may appear as the
25032 operand 1. */
25033 tree type = TREE_OPERAND (expression, 1);
25034 if (TREE_CODE (type) == TREE_LIST)
25035 /* This is an array type. We need to check array dimensions
25036 as well. */
25037 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
25038 || value_dependent_expression_p
25039 (TREE_OPERAND (TREE_VALUE (type), 1));
25040 else
25041 return dependent_type_p (type);
25044 if (TREE_CODE (expression) == SCOPE_REF)
25046 tree scope = TREE_OPERAND (expression, 0);
25047 tree name = TREE_OPERAND (expression, 1);
25049 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25050 contains an identifier associated by name lookup with one or more
25051 declarations declared with a dependent type, or...a
25052 nested-name-specifier or qualified-id that names a member of an
25053 unknown specialization. */
25054 return (type_dependent_expression_p (name)
25055 || dependent_scope_p (scope));
25058 if (TREE_CODE (expression) == TEMPLATE_DECL
25059 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25060 return uses_outer_template_parms (expression);
25062 if (TREE_CODE (expression) == STMT_EXPR)
25063 expression = stmt_expr_value_expr (expression);
25065 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25067 tree elt;
25068 unsigned i;
25070 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25072 if (type_dependent_expression_p (elt))
25073 return true;
25075 return false;
25078 /* A static data member of the current instantiation with incomplete
25079 array type is type-dependent, as the definition and specializations
25080 can have different bounds. */
25081 if (VAR_P (expression)
25082 && DECL_CLASS_SCOPE_P (expression)
25083 && dependent_type_p (DECL_CONTEXT (expression))
25084 && VAR_HAD_UNKNOWN_BOUND (expression))
25085 return true;
25087 /* An array of unknown bound depending on a variadic parameter, eg:
25089 template<typename... Args>
25090 void foo (Args... args)
25092 int arr[] = { args... };
25095 template<int... vals>
25096 void bar ()
25098 int arr[] = { vals... };
25101 If the array has no length and has an initializer, it must be that
25102 we couldn't determine its length in cp_complete_array_type because
25103 it is dependent. */
25104 if (VAR_P (expression)
25105 && TREE_TYPE (expression) != NULL_TREE
25106 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25107 && !TYPE_DOMAIN (TREE_TYPE (expression))
25108 && DECL_INITIAL (expression))
25109 return true;
25111 /* A function or variable template-id is type-dependent if it has any
25112 dependent template arguments. */
25113 if (VAR_OR_FUNCTION_DECL_P (expression)
25114 && DECL_LANG_SPECIFIC (expression)
25115 && DECL_TEMPLATE_INFO (expression))
25117 /* Consider the innermost template arguments, since those are the ones
25118 that come from the template-id; the template arguments for the
25119 enclosing class do not make it type-dependent unless they are used in
25120 the type of the decl. */
25121 if (PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (expression))
25122 && (any_dependent_template_arguments_p
25123 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25124 return true;
25127 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25128 type-dependent. Checking this is important for functions with auto return
25129 type, which looks like a dependent type. */
25130 if (TREE_CODE (expression) == FUNCTION_DECL
25131 && !(DECL_CLASS_SCOPE_P (expression)
25132 && dependent_type_p (DECL_CONTEXT (expression)))
25133 && !(DECL_LANG_SPECIFIC (expression)
25134 && DECL_FRIEND_P (expression)
25135 && (!DECL_FRIEND_CONTEXT (expression)
25136 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25137 && !DECL_LOCAL_FUNCTION_P (expression))
25139 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25140 || undeduced_auto_decl (expression));
25141 return false;
25144 /* Always dependent, on the number of arguments if nothing else. */
25145 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25146 return true;
25148 if (TREE_TYPE (expression) == unknown_type_node)
25150 if (TREE_CODE (expression) == ADDR_EXPR)
25151 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25152 if (TREE_CODE (expression) == COMPONENT_REF
25153 || TREE_CODE (expression) == OFFSET_REF)
25155 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25156 return true;
25157 expression = TREE_OPERAND (expression, 1);
25158 if (identifier_p (expression))
25159 return false;
25161 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
25162 if (TREE_CODE (expression) == SCOPE_REF)
25163 return false;
25165 if (BASELINK_P (expression))
25167 if (BASELINK_OPTYPE (expression)
25168 && dependent_type_p (BASELINK_OPTYPE (expression)))
25169 return true;
25170 expression = BASELINK_FUNCTIONS (expression);
25173 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25175 if (any_dependent_template_arguments_p
25176 (TREE_OPERAND (expression, 1)))
25177 return true;
25178 expression = TREE_OPERAND (expression, 0);
25179 if (identifier_p (expression))
25180 return true;
25183 gcc_assert (TREE_CODE (expression) == OVERLOAD
25184 || TREE_CODE (expression) == FUNCTION_DECL);
25186 for (lkp_iterator iter (expression); iter; ++iter)
25187 if (type_dependent_expression_p (*iter))
25188 return true;
25190 return false;
25193 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
25195 /* Dependent type attributes might not have made it from the decl to
25196 the type yet. */
25197 if (DECL_P (expression)
25198 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
25199 return true;
25201 return (dependent_type_p (TREE_TYPE (expression)));
25204 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
25205 type-dependent if the expression refers to a member of the current
25206 instantiation and the type of the referenced member is dependent, or the
25207 class member access expression refers to a member of an unknown
25208 specialization.
25210 This function returns true if the OBJECT in such a class member access
25211 expression is of an unknown specialization. */
25213 bool
25214 type_dependent_object_expression_p (tree object)
25216 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
25217 dependent. */
25218 if (TREE_CODE (object) == IDENTIFIER_NODE)
25219 return true;
25220 tree scope = TREE_TYPE (object);
25221 return (!scope || dependent_scope_p (scope));
25224 /* walk_tree callback function for instantiation_dependent_expression_p,
25225 below. Returns non-zero if a dependent subexpression is found. */
25227 static tree
25228 instantiation_dependent_r (tree *tp, int *walk_subtrees,
25229 void * /*data*/)
25231 if (TYPE_P (*tp))
25233 /* We don't have to worry about decltype currently because decltype
25234 of an instantiation-dependent expr is a dependent type. This
25235 might change depending on the resolution of DR 1172. */
25236 *walk_subtrees = false;
25237 return NULL_TREE;
25239 enum tree_code code = TREE_CODE (*tp);
25240 switch (code)
25242 /* Don't treat an argument list as dependent just because it has no
25243 TREE_TYPE. */
25244 case TREE_LIST:
25245 case TREE_VEC:
25246 case NONTYPE_ARGUMENT_PACK:
25247 return NULL_TREE;
25249 case TEMPLATE_PARM_INDEX:
25250 return *tp;
25252 /* Handle expressions with type operands. */
25253 case SIZEOF_EXPR:
25254 case ALIGNOF_EXPR:
25255 case TYPEID_EXPR:
25256 case AT_ENCODE_EXPR:
25258 tree op = TREE_OPERAND (*tp, 0);
25259 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
25260 op = TREE_TYPE (op);
25261 if (TYPE_P (op))
25263 if (dependent_type_p (op))
25264 return *tp;
25265 else
25267 *walk_subtrees = false;
25268 return NULL_TREE;
25271 break;
25274 case COMPONENT_REF:
25275 if (identifier_p (TREE_OPERAND (*tp, 1)))
25276 /* In a template, finish_class_member_access_expr creates a
25277 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
25278 type-dependent, so that we can check access control at
25279 instantiation time (PR 42277). See also Core issue 1273. */
25280 return *tp;
25281 break;
25283 case SCOPE_REF:
25284 if (instantiation_dependent_scope_ref_p (*tp))
25285 return *tp;
25286 else
25287 break;
25289 /* Treat statement-expressions as dependent. */
25290 case BIND_EXPR:
25291 return *tp;
25293 /* Treat requires-expressions as dependent. */
25294 case REQUIRES_EXPR:
25295 return *tp;
25297 case CALL_EXPR:
25298 /* Treat calls to function concepts as dependent. */
25299 if (function_concept_check_p (*tp))
25300 return *tp;
25301 break;
25303 case TEMPLATE_ID_EXPR:
25304 /* And variable concepts. */
25305 if (variable_concept_p (TREE_OPERAND (*tp, 0)))
25306 return *tp;
25307 break;
25309 default:
25310 break;
25313 if (type_dependent_expression_p (*tp))
25314 return *tp;
25315 else
25316 return NULL_TREE;
25319 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
25320 sense defined by the ABI:
25322 "An expression is instantiation-dependent if it is type-dependent
25323 or value-dependent, or it has a subexpression that is type-dependent
25324 or value-dependent."
25326 Except don't actually check value-dependence for unevaluated expressions,
25327 because in sizeof(i) we don't care about the value of i. Checking
25328 type-dependence will in turn check value-dependence of array bounds/template
25329 arguments as needed. */
25331 bool
25332 instantiation_dependent_uneval_expression_p (tree expression)
25334 tree result;
25336 if (!processing_template_decl)
25337 return false;
25339 if (expression == error_mark_node)
25340 return false;
25342 result = cp_walk_tree_without_duplicates (&expression,
25343 instantiation_dependent_r, NULL);
25344 return result != NULL_TREE;
25347 /* As above, but also check value-dependence of the expression as a whole. */
25349 bool
25350 instantiation_dependent_expression_p (tree expression)
25352 return (instantiation_dependent_uneval_expression_p (expression)
25353 || value_dependent_expression_p (expression));
25356 /* Like type_dependent_expression_p, but it also works while not processing
25357 a template definition, i.e. during substitution or mangling. */
25359 bool
25360 type_dependent_expression_p_push (tree expr)
25362 bool b;
25363 ++processing_template_decl;
25364 b = type_dependent_expression_p (expr);
25365 --processing_template_decl;
25366 return b;
25369 /* Returns TRUE if ARGS contains a type-dependent expression. */
25371 bool
25372 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
25374 unsigned int i;
25375 tree arg;
25377 FOR_EACH_VEC_SAFE_ELT (args, i, arg)
25379 if (type_dependent_expression_p (arg))
25380 return true;
25382 return false;
25385 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25386 expressions) contains any type-dependent expressions. */
25388 bool
25389 any_type_dependent_elements_p (const_tree list)
25391 for (; list; list = TREE_CHAIN (list))
25392 if (type_dependent_expression_p (TREE_VALUE (list)))
25393 return true;
25395 return false;
25398 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25399 expressions) contains any value-dependent expressions. */
25401 bool
25402 any_value_dependent_elements_p (const_tree list)
25404 for (; list; list = TREE_CHAIN (list))
25405 if (value_dependent_expression_p (TREE_VALUE (list)))
25406 return true;
25408 return false;
25411 /* Returns TRUE if the ARG (a template argument) is dependent. */
25413 bool
25414 dependent_template_arg_p (tree arg)
25416 if (!processing_template_decl)
25417 return false;
25419 /* Assume a template argument that was wrongly written by the user
25420 is dependent. This is consistent with what
25421 any_dependent_template_arguments_p [that calls this function]
25422 does. */
25423 if (!arg || arg == error_mark_node)
25424 return true;
25426 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
25427 arg = argument_pack_select_arg (arg);
25429 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
25430 return true;
25431 if (TREE_CODE (arg) == TEMPLATE_DECL)
25433 if (DECL_TEMPLATE_PARM_P (arg))
25434 return true;
25435 /* A member template of a dependent class is not necessarily
25436 type-dependent, but it is a dependent template argument because it
25437 will be a member of an unknown specialization to that template. */
25438 tree scope = CP_DECL_CONTEXT (arg);
25439 return TYPE_P (scope) && dependent_type_p (scope);
25441 else if (ARGUMENT_PACK_P (arg))
25443 tree args = ARGUMENT_PACK_ARGS (arg);
25444 int i, len = TREE_VEC_LENGTH (args);
25445 for (i = 0; i < len; ++i)
25447 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25448 return true;
25451 return false;
25453 else if (TYPE_P (arg))
25454 return dependent_type_p (arg);
25455 else
25456 return (type_dependent_expression_p (arg)
25457 || value_dependent_expression_p (arg));
25460 /* Returns true if ARGS (a collection of template arguments) contains
25461 any types that require structural equality testing. */
25463 bool
25464 any_template_arguments_need_structural_equality_p (tree args)
25466 int i;
25467 int j;
25469 if (!args)
25470 return false;
25471 if (args == error_mark_node)
25472 return true;
25474 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25476 tree level = TMPL_ARGS_LEVEL (args, i + 1);
25477 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25479 tree arg = TREE_VEC_ELT (level, j);
25480 tree packed_args = NULL_TREE;
25481 int k, len = 1;
25483 if (ARGUMENT_PACK_P (arg))
25485 /* Look inside the argument pack. */
25486 packed_args = ARGUMENT_PACK_ARGS (arg);
25487 len = TREE_VEC_LENGTH (packed_args);
25490 for (k = 0; k < len; ++k)
25492 if (packed_args)
25493 arg = TREE_VEC_ELT (packed_args, k);
25495 if (error_operand_p (arg))
25496 return true;
25497 else if (TREE_CODE (arg) == TEMPLATE_DECL)
25498 continue;
25499 else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25500 return true;
25501 else if (!TYPE_P (arg) && TREE_TYPE (arg)
25502 && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25503 return true;
25508 return false;
25511 /* Returns true if ARGS (a collection of template arguments) contains
25512 any dependent arguments. */
25514 bool
25515 any_dependent_template_arguments_p (const_tree args)
25517 int i;
25518 int j;
25520 if (!args)
25521 return false;
25522 if (args == error_mark_node)
25523 return true;
25525 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25527 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25528 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25529 if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25530 return true;
25533 return false;
25536 /* Returns true if ARGS contains any errors. */
25538 bool
25539 any_erroneous_template_args_p (const_tree args)
25541 int i;
25542 int j;
25544 if (args == error_mark_node)
25545 return true;
25547 if (args && TREE_CODE (args) != TREE_VEC)
25549 if (tree ti = get_template_info (args))
25550 args = TI_ARGS (ti);
25551 else
25552 args = NULL_TREE;
25555 if (!args)
25556 return false;
25558 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25560 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25561 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25562 if (error_operand_p (TREE_VEC_ELT (level, j)))
25563 return true;
25566 return false;
25569 /* Returns TRUE if the template TMPL is type-dependent. */
25571 bool
25572 dependent_template_p (tree tmpl)
25574 if (TREE_CODE (tmpl) == OVERLOAD)
25576 for (lkp_iterator iter (tmpl); iter; ++iter)
25577 if (dependent_template_p (*iter))
25578 return true;
25579 return false;
25582 /* Template template parameters are dependent. */
25583 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25584 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25585 return true;
25586 /* So are names that have not been looked up. */
25587 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25588 return true;
25589 return false;
25592 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
25594 bool
25595 dependent_template_id_p (tree tmpl, tree args)
25597 return (dependent_template_p (tmpl)
25598 || any_dependent_template_arguments_p (args));
25601 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25602 are dependent. */
25604 bool
25605 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25607 int i;
25609 if (!processing_template_decl)
25610 return false;
25612 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25614 tree decl = TREE_VEC_ELT (declv, i);
25615 tree init = TREE_VEC_ELT (initv, i);
25616 tree cond = TREE_VEC_ELT (condv, i);
25617 tree incr = TREE_VEC_ELT (incrv, i);
25619 if (type_dependent_expression_p (decl)
25620 || TREE_CODE (decl) == SCOPE_REF)
25621 return true;
25623 if (init && type_dependent_expression_p (init))
25624 return true;
25626 if (type_dependent_expression_p (cond))
25627 return true;
25629 if (COMPARISON_CLASS_P (cond)
25630 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25631 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25632 return true;
25634 if (TREE_CODE (incr) == MODOP_EXPR)
25636 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25637 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25638 return true;
25640 else if (type_dependent_expression_p (incr))
25641 return true;
25642 else if (TREE_CODE (incr) == MODIFY_EXPR)
25644 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25645 return true;
25646 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25648 tree t = TREE_OPERAND (incr, 1);
25649 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25650 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25651 return true;
25656 return false;
25659 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
25660 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
25661 no such TYPE can be found. Note that this function peers inside
25662 uninstantiated templates and therefore should be used only in
25663 extremely limited situations. ONLY_CURRENT_P restricts this
25664 peering to the currently open classes hierarchy (which is required
25665 when comparing types). */
25667 tree
25668 resolve_typename_type (tree type, bool only_current_p)
25670 tree scope;
25671 tree name;
25672 tree decl;
25673 int quals;
25674 tree pushed_scope;
25675 tree result;
25677 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25679 scope = TYPE_CONTEXT (type);
25680 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
25681 gcc_checking_assert (uses_template_parms (scope));
25683 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25684 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25685 a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25686 the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25687 identifier of the TYPENAME_TYPE anymore.
25688 So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25689 TYPENAME_TYPE instead, we avoid messing up with a possible
25690 typedef variant case. */
25691 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25693 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25694 it first before we can figure out what NAME refers to. */
25695 if (TREE_CODE (scope) == TYPENAME_TYPE)
25697 if (TYPENAME_IS_RESOLVING_P (scope))
25698 /* Given a class template A with a dependent base with nested type C,
25699 typedef typename A::C::C C will land us here, as trying to resolve
25700 the initial A::C leads to the local C typedef, which leads back to
25701 A::C::C. So we break the recursion now. */
25702 return type;
25703 else
25704 scope = resolve_typename_type (scope, only_current_p);
25706 /* If we don't know what SCOPE refers to, then we cannot resolve the
25707 TYPENAME_TYPE. */
25708 if (!CLASS_TYPE_P (scope))
25709 return type;
25710 /* If this is a typedef, we don't want to look inside (c++/11987). */
25711 if (typedef_variant_p (type))
25712 return type;
25713 /* If SCOPE isn't the template itself, it will not have a valid
25714 TYPE_FIELDS list. */
25715 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25716 /* scope is either the template itself or a compatible instantiation
25717 like X<T>, so look up the name in the original template. */
25718 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25719 /* If scope has no fields, it can't be a current instantiation. Check this
25720 before currently_open_class to avoid infinite recursion (71515). */
25721 if (!TYPE_FIELDS (scope))
25722 return type;
25723 /* If the SCOPE is not the current instantiation, there's no reason
25724 to look inside it. */
25725 if (only_current_p && !currently_open_class (scope))
25726 return type;
25727 /* Enter the SCOPE so that name lookup will be resolved as if we
25728 were in the class definition. In particular, SCOPE will no
25729 longer be considered a dependent type. */
25730 pushed_scope = push_scope (scope);
25731 /* Look up the declaration. */
25732 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25733 tf_warning_or_error);
25735 result = NULL_TREE;
25737 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25738 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
25739 tree fullname = TYPENAME_TYPE_FULLNAME (type);
25740 if (!decl)
25741 /*nop*/;
25742 else if (identifier_p (fullname)
25743 && TREE_CODE (decl) == TYPE_DECL)
25745 result = TREE_TYPE (decl);
25746 if (result == error_mark_node)
25747 result = NULL_TREE;
25749 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25750 && DECL_CLASS_TEMPLATE_P (decl))
25752 /* Obtain the template and the arguments. */
25753 tree tmpl = TREE_OPERAND (fullname, 0);
25754 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25756 /* We get here with a plain identifier because a previous tentative
25757 parse of the nested-name-specifier as part of a ptr-operator saw
25758 ::template X<A>. The use of ::template is necessary in a
25759 ptr-operator, but wrong in a declarator-id.
25761 [temp.names]: In a qualified-id of a declarator-id, the keyword
25762 template shall not appear at the top level. */
25763 pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25764 "keyword %<template%> not allowed in declarator-id");
25765 tmpl = decl;
25767 tree args = TREE_OPERAND (fullname, 1);
25768 /* Instantiate the template. */
25769 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25770 /*entering_scope=*/true,
25771 tf_error | tf_user);
25772 if (result == error_mark_node)
25773 result = NULL_TREE;
25776 /* Leave the SCOPE. */
25777 if (pushed_scope)
25778 pop_scope (pushed_scope);
25780 /* If we failed to resolve it, return the original typename. */
25781 if (!result)
25782 return type;
25784 /* If lookup found a typename type, resolve that too. */
25785 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25787 /* Ill-formed programs can cause infinite recursion here, so we
25788 must catch that. */
25789 TYPENAME_IS_RESOLVING_P (result) = 1;
25790 result = resolve_typename_type (result, only_current_p);
25791 TYPENAME_IS_RESOLVING_P (result) = 0;
25794 /* Qualify the resulting type. */
25795 quals = cp_type_quals (type);
25796 if (quals)
25797 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25799 return result;
25802 /* EXPR is an expression which is not type-dependent. Return a proxy
25803 for EXPR that can be used to compute the types of larger
25804 expressions containing EXPR. */
25806 tree
25807 build_non_dependent_expr (tree expr)
25809 tree orig_expr = expr;
25810 tree inner_expr;
25812 /* When checking, try to get a constant value for all non-dependent
25813 expressions in order to expose bugs in *_dependent_expression_p
25814 and constexpr. This can affect code generation, see PR70704, so
25815 only do this for -fchecking=2. */
25816 if (flag_checking > 1
25817 && cxx_dialect >= cxx11
25818 /* Don't do this during nsdmi parsing as it can lead to
25819 unexpected recursive instantiations. */
25820 && !parsing_nsdmi ()
25821 /* Don't do this during concept expansion either and for
25822 the same reason. */
25823 && !expanding_concept ())
25824 fold_non_dependent_expr (expr);
25826 STRIP_ANY_LOCATION_WRAPPER (expr);
25828 /* Preserve OVERLOADs; the functions must be available to resolve
25829 types. */
25830 inner_expr = expr;
25831 if (TREE_CODE (inner_expr) == STMT_EXPR)
25832 inner_expr = stmt_expr_value_expr (inner_expr);
25833 if (TREE_CODE (inner_expr) == ADDR_EXPR)
25834 inner_expr = TREE_OPERAND (inner_expr, 0);
25835 if (TREE_CODE (inner_expr) == COMPONENT_REF)
25836 inner_expr = TREE_OPERAND (inner_expr, 1);
25837 if (is_overloaded_fn (inner_expr)
25838 || TREE_CODE (inner_expr) == OFFSET_REF)
25839 return orig_expr;
25840 /* There is no need to return a proxy for a variable or enumerator. */
25841 if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
25842 return orig_expr;
25843 /* Preserve string constants; conversions from string constants to
25844 "char *" are allowed, even though normally a "const char *"
25845 cannot be used to initialize a "char *". */
25846 if (TREE_CODE (expr) == STRING_CST)
25847 return orig_expr;
25848 /* Preserve void and arithmetic constants, as an optimization -- there is no
25849 reason to create a new node. */
25850 if (TREE_CODE (expr) == VOID_CST
25851 || TREE_CODE (expr) == INTEGER_CST
25852 || TREE_CODE (expr) == REAL_CST)
25853 return orig_expr;
25854 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
25855 There is at least one place where we want to know that a
25856 particular expression is a throw-expression: when checking a ?:
25857 expression, there are special rules if the second or third
25858 argument is a throw-expression. */
25859 if (TREE_CODE (expr) == THROW_EXPR)
25860 return orig_expr;
25862 /* Don't wrap an initializer list, we need to be able to look inside. */
25863 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
25864 return orig_expr;
25866 /* Don't wrap a dummy object, we need to be able to test for it. */
25867 if (is_dummy_object (expr))
25868 return orig_expr;
25870 if (TREE_CODE (expr) == COND_EXPR)
25871 return build3 (COND_EXPR,
25872 TREE_TYPE (expr),
25873 TREE_OPERAND (expr, 0),
25874 (TREE_OPERAND (expr, 1)
25875 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
25876 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
25877 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
25878 if (TREE_CODE (expr) == COMPOUND_EXPR
25879 && !COMPOUND_EXPR_OVERLOADED (expr))
25880 return build2 (COMPOUND_EXPR,
25881 TREE_TYPE (expr),
25882 TREE_OPERAND (expr, 0),
25883 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
25885 /* If the type is unknown, it can't really be non-dependent */
25886 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
25888 /* Otherwise, build a NON_DEPENDENT_EXPR. */
25889 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
25890 TREE_TYPE (expr), expr);
25893 /* ARGS is a vector of expressions as arguments to a function call.
25894 Replace the arguments with equivalent non-dependent expressions.
25895 This modifies ARGS in place. */
25897 void
25898 make_args_non_dependent (vec<tree, va_gc> *args)
25900 unsigned int ix;
25901 tree arg;
25903 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
25905 tree newarg = build_non_dependent_expr (arg);
25906 if (newarg != arg)
25907 (*args)[ix] = newarg;
25911 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
25912 TEMPLATE_TYPE_PARM with a level one deeper than the actual template
25913 parms. If set_canonical is true, we set TYPE_CANONICAL on it. */
25915 static tree
25916 make_auto_1 (tree name, bool set_canonical)
25918 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
25919 TYPE_NAME (au) = build_decl (input_location,
25920 TYPE_DECL, name, au);
25921 TYPE_STUB_DECL (au) = TYPE_NAME (au);
25922 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
25923 (0, processing_template_decl + 1, processing_template_decl + 1,
25924 TYPE_NAME (au), NULL_TREE);
25925 if (set_canonical)
25926 TYPE_CANONICAL (au) = canonical_type_parameter (au);
25927 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
25928 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
25930 return au;
25933 tree
25934 make_decltype_auto (void)
25936 return make_auto_1 (decltype_auto_identifier, true);
25939 tree
25940 make_auto (void)
25942 return make_auto_1 (auto_identifier, true);
25945 /* Return a C++17 deduction placeholder for class template TMPL. */
25947 tree
25948 make_template_placeholder (tree tmpl)
25950 tree t = make_auto_1 (DECL_NAME (tmpl), true);
25951 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
25952 return t;
25955 /* True iff T is a C++17 class template deduction placeholder. */
25957 bool
25958 template_placeholder_p (tree t)
25960 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
25963 /* Make a "constrained auto" type-specifier. This is an
25964 auto type with constraints that must be associated after
25965 deduction. The constraint is formed from the given
25966 CONC and its optional sequence of arguments, which are
25967 non-null if written as partial-concept-id. */
25969 tree
25970 make_constrained_auto (tree con, tree args)
25972 tree type = make_auto_1 (auto_identifier, false);
25974 /* Build the constraint. */
25975 tree tmpl = DECL_TI_TEMPLATE (con);
25976 tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
25977 expr = build_concept_check (expr, type, args);
25979 tree constr = normalize_expression (expr);
25980 PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
25982 /* Our canonical type depends on the constraint. */
25983 TYPE_CANONICAL (type) = canonical_type_parameter (type);
25985 /* Attach the constraint to the type declaration. */
25986 tree decl = TYPE_NAME (type);
25987 return decl;
25990 /* Given type ARG, return std::initializer_list<ARG>. */
25992 static tree
25993 listify (tree arg)
25995 tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
25997 if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
25999 gcc_rich_location richloc (input_location);
26000 maybe_add_include_fixit (&richloc, "<initializer_list>");
26001 error_at (&richloc,
26002 "deducing from brace-enclosed initializer list"
26003 " requires %<#include <initializer_list>%>");
26005 return error_mark_node;
26007 tree argvec = make_tree_vec (1);
26008 TREE_VEC_ELT (argvec, 0) = arg;
26010 return lookup_template_class (std_init_list, argvec, NULL_TREE,
26011 NULL_TREE, 0, tf_warning_or_error);
26014 /* Replace auto in TYPE with std::initializer_list<auto>. */
26016 static tree
26017 listify_autos (tree type, tree auto_node)
26019 tree init_auto = listify (auto_node);
26020 tree argvec = make_tree_vec (1);
26021 TREE_VEC_ELT (argvec, 0) = init_auto;
26022 if (processing_template_decl)
26023 argvec = add_to_template_args (current_template_args (), argvec);
26024 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
26027 /* Hash traits for hashing possibly constrained 'auto'
26028 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
26030 struct auto_hash : default_hash_traits<tree>
26032 static inline hashval_t hash (tree);
26033 static inline bool equal (tree, tree);
26036 /* Hash the 'auto' T. */
26038 inline hashval_t
26039 auto_hash::hash (tree t)
26041 if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
26042 /* Matching constrained-type-specifiers denote the same template
26043 parameter, so hash the constraint. */
26044 return hash_placeholder_constraint (c);
26045 else
26046 /* But unconstrained autos are all separate, so just hash the pointer. */
26047 return iterative_hash_object (t, 0);
26050 /* Compare two 'auto's. */
26052 inline bool
26053 auto_hash::equal (tree t1, tree t2)
26055 if (t1 == t2)
26056 return true;
26058 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26059 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26061 /* Two unconstrained autos are distinct. */
26062 if (!c1 || !c2)
26063 return false;
26065 return equivalent_placeholder_constraints (c1, c2);
26068 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26069 constrained) auto, add it to the vector. */
26071 static int
26072 extract_autos_r (tree t, void *data)
26074 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26075 if (is_auto (t))
26077 /* All the autos were built with index 0; fix that up now. */
26078 tree *p = hash.find_slot (t, INSERT);
26079 unsigned idx;
26080 if (*p)
26081 /* If this is a repeated constrained-type-specifier, use the index we
26082 chose before. */
26083 idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26084 else
26086 /* Otherwise this is new, so use the current count. */
26087 *p = t;
26088 idx = hash.elements () - 1;
26090 TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26093 /* Always keep walking. */
26094 return 0;
26097 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26098 says they can appear anywhere in the type. */
26100 static tree
26101 extract_autos (tree type)
26103 hash_set<tree> visited;
26104 hash_table<auto_hash> hash (2);
26106 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26108 tree tree_vec = make_tree_vec (hash.elements());
26109 for (hash_table<auto_hash>::iterator iter = hash.begin();
26110 iter != hash.end(); ++iter)
26112 tree elt = *iter;
26113 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26114 TREE_VEC_ELT (tree_vec, i)
26115 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
26118 return tree_vec;
26121 /* The stem for deduction guide names. */
26122 const char *const dguide_base = "__dguide_";
26124 /* Return the name for a deduction guide for class template TMPL. */
26126 tree
26127 dguide_name (tree tmpl)
26129 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26130 tree tname = TYPE_IDENTIFIER (type);
26131 char *buf = (char *) alloca (1 + strlen (dguide_base)
26132 + IDENTIFIER_LENGTH (tname));
26133 memcpy (buf, dguide_base, strlen (dguide_base));
26134 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26135 IDENTIFIER_LENGTH (tname) + 1);
26136 tree dname = get_identifier (buf);
26137 TREE_TYPE (dname) = type;
26138 return dname;
26141 /* True if NAME is the name of a deduction guide. */
26143 bool
26144 dguide_name_p (tree name)
26146 return (TREE_CODE (name) == IDENTIFIER_NODE
26147 && TREE_TYPE (name)
26148 && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
26149 strlen (dguide_base)));
26152 /* True if FN is a deduction guide. */
26154 bool
26155 deduction_guide_p (const_tree fn)
26157 if (DECL_P (fn))
26158 if (tree name = DECL_NAME (fn))
26159 return dguide_name_p (name);
26160 return false;
26163 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
26165 bool
26166 copy_guide_p (const_tree fn)
26168 gcc_assert (deduction_guide_p (fn));
26169 if (!DECL_ARTIFICIAL (fn))
26170 return false;
26171 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
26172 return (TREE_CHAIN (parms) == void_list_node
26173 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
26176 /* True if FN is a guide generated from a constructor template. */
26178 bool
26179 template_guide_p (const_tree fn)
26181 gcc_assert (deduction_guide_p (fn));
26182 if (!DECL_ARTIFICIAL (fn))
26183 return false;
26184 tree tmpl = DECL_TI_TEMPLATE (fn);
26185 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
26186 return PRIMARY_TEMPLATE_P (org);
26187 return false;
26190 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
26191 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
26192 template parameter types. Note that the handling of template template
26193 parameters relies on current_template_parms being set appropriately for the
26194 new template. */
26196 static tree
26197 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
26198 tree tsubst_args, tsubst_flags_t complain)
26200 if (olddecl == error_mark_node)
26201 return error_mark_node;
26203 tree oldidx = get_template_parm_index (olddecl);
26205 tree newtype;
26206 if (TREE_CODE (olddecl) == TYPE_DECL
26207 || TREE_CODE (olddecl) == TEMPLATE_DECL)
26209 tree oldtype = TREE_TYPE (olddecl);
26210 newtype = cxx_make_type (TREE_CODE (oldtype));
26211 TYPE_MAIN_VARIANT (newtype) = newtype;
26212 if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
26213 TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
26214 = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
26216 else
26218 newtype = TREE_TYPE (olddecl);
26219 if (type_uses_auto (newtype))
26221 // Substitute once to fix references to other template parameters.
26222 newtype = tsubst (newtype, tsubst_args,
26223 complain|tf_partial, NULL_TREE);
26224 // Now substitute again to reduce the level of the auto.
26225 newtype = tsubst (newtype, current_template_args (),
26226 complain, NULL_TREE);
26228 else
26229 newtype = tsubst (newtype, tsubst_args,
26230 complain, NULL_TREE);
26233 tree newdecl
26234 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
26235 DECL_NAME (olddecl), newtype);
26236 SET_DECL_TEMPLATE_PARM_P (newdecl);
26238 tree newidx;
26239 if (TREE_CODE (olddecl) == TYPE_DECL
26240 || TREE_CODE (olddecl) == TEMPLATE_DECL)
26242 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
26243 = build_template_parm_index (index, level, level,
26244 newdecl, newtype);
26245 TEMPLATE_PARM_PARAMETER_PACK (newidx)
26246 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26247 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
26248 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
26250 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
26252 DECL_TEMPLATE_RESULT (newdecl)
26253 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
26254 DECL_NAME (olddecl), newtype);
26255 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
26256 // First create a copy (ttargs) of tsubst_args with an
26257 // additional level for the template template parameter's own
26258 // template parameters (ttparms).
26259 tree ttparms = (INNERMOST_TEMPLATE_PARMS
26260 (DECL_TEMPLATE_PARMS (olddecl)));
26261 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
26262 tree ttargs = make_tree_vec (depth + 1);
26263 for (int i = 0; i < depth; ++i)
26264 TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
26265 TREE_VEC_ELT (ttargs, depth)
26266 = template_parms_level_to_args (ttparms);
26267 // Substitute ttargs into ttparms to fix references to
26268 // other template parameters.
26269 ttparms = tsubst_template_parms_level (ttparms, ttargs,
26270 complain|tf_partial);
26271 // Now substitute again with args based on tparms, to reduce
26272 // the level of the ttparms.
26273 ttargs = current_template_args ();
26274 ttparms = tsubst_template_parms_level (ttparms, ttargs,
26275 complain);
26276 // Finally, tack the adjusted parms onto tparms.
26277 ttparms = tree_cons (size_int (depth), ttparms,
26278 current_template_parms);
26279 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
26282 else
26284 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
26285 tree newconst
26286 = build_decl (DECL_SOURCE_LOCATION (oldconst),
26287 TREE_CODE (oldconst),
26288 DECL_NAME (oldconst), newtype);
26289 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
26290 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
26291 SET_DECL_TEMPLATE_PARM_P (newconst);
26292 newidx = build_template_parm_index (index, level, level,
26293 newconst, newtype);
26294 TEMPLATE_PARM_PARAMETER_PACK (newidx)
26295 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26296 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
26299 return newdecl;
26302 /* Returns a C++17 class deduction guide template based on the constructor
26303 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
26304 guide, or REFERENCE_TYPE for an implicit copy/move guide. */
26306 static tree
26307 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
26309 tree type, tparms, targs, fparms, fargs, ci;
26310 bool memtmpl = false;
26311 bool explicit_p;
26312 location_t loc;
26313 tree fn_tmpl = NULL_TREE;
26315 if (TYPE_P (ctor))
26317 type = ctor;
26318 bool copy_p = TYPE_REF_P (type);
26319 if (copy_p)
26321 type = TREE_TYPE (type);
26322 fparms = tree_cons (NULL_TREE, type, void_list_node);
26324 else
26325 fparms = void_list_node;
26327 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
26328 tparms = DECL_TEMPLATE_PARMS (ctmpl);
26329 targs = CLASSTYPE_TI_ARGS (type);
26330 ci = NULL_TREE;
26331 fargs = NULL_TREE;
26332 loc = DECL_SOURCE_LOCATION (ctmpl);
26333 explicit_p = false;
26335 else
26337 ++processing_template_decl;
26338 bool ok = true;
26340 fn_tmpl
26341 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
26342 : DECL_TI_TEMPLATE (ctor));
26343 if (outer_args)
26344 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
26345 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
26347 type = DECL_CONTEXT (ctor);
26349 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
26350 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
26351 fully specialized args for the enclosing class. Strip those off, as
26352 the deduction guide won't have those template parameters. */
26353 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
26354 TMPL_PARMS_DEPTH (tparms));
26355 /* Discard the 'this' parameter. */
26356 fparms = FUNCTION_ARG_CHAIN (ctor);
26357 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
26358 ci = get_constraints (ctor);
26359 loc = DECL_SOURCE_LOCATION (ctor);
26360 explicit_p = DECL_NONCONVERTING_P (ctor);
26362 if (PRIMARY_TEMPLATE_P (fn_tmpl))
26364 memtmpl = true;
26366 /* For a member template constructor, we need to flatten the two
26367 template parameter lists into one, and then adjust the function
26368 signature accordingly. This gets...complicated. */
26369 tree save_parms = current_template_parms;
26371 /* For a member template we should have two levels of parms/args, one
26372 for the class and one for the constructor. We stripped
26373 specialized args for further enclosing classes above. */
26374 const int depth = 2;
26375 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
26377 /* Template args for translating references to the two-level template
26378 parameters into references to the one-level template parameters we
26379 are creating. */
26380 tree tsubst_args = copy_node (targs);
26381 TMPL_ARGS_LEVEL (tsubst_args, depth)
26382 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
26384 /* Template parms for the constructor template. */
26385 tree ftparms = TREE_VALUE (tparms);
26386 unsigned flen = TREE_VEC_LENGTH (ftparms);
26387 /* Template parms for the class template. */
26388 tparms = TREE_CHAIN (tparms);
26389 tree ctparms = TREE_VALUE (tparms);
26390 unsigned clen = TREE_VEC_LENGTH (ctparms);
26391 /* Template parms for the deduction guide start as a copy of the
26392 template parms for the class. We set current_template_parms for
26393 lookup_template_class_1. */
26394 current_template_parms = tparms = copy_node (tparms);
26395 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
26396 for (unsigned i = 0; i < clen; ++i)
26397 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
26399 /* Now we need to rewrite the constructor parms to append them to the
26400 class parms. */
26401 for (unsigned i = 0; i < flen; ++i)
26403 unsigned index = i + clen;
26404 unsigned level = 1;
26405 tree oldelt = TREE_VEC_ELT (ftparms, i);
26406 tree olddecl = TREE_VALUE (oldelt);
26407 tree newdecl = rewrite_template_parm (olddecl, index, level,
26408 tsubst_args, complain);
26409 if (newdecl == error_mark_node)
26410 ok = false;
26411 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
26412 tsubst_args, complain, ctor);
26413 tree list = build_tree_list (newdef, newdecl);
26414 TEMPLATE_PARM_CONSTRAINTS (list)
26415 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
26416 tsubst_args, complain, ctor);
26417 TREE_VEC_ELT (new_vec, index) = list;
26418 TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
26421 /* Now we have a final set of template parms to substitute into the
26422 function signature. */
26423 targs = template_parms_to_args (tparms);
26424 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
26425 complain, ctor);
26426 fargs = tsubst (fargs, tsubst_args, complain, ctor);
26427 if (ci)
26428 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
26430 current_template_parms = save_parms;
26433 --processing_template_decl;
26434 if (!ok)
26435 return error_mark_node;
26438 if (!memtmpl)
26440 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
26441 tparms = copy_node (tparms);
26442 INNERMOST_TEMPLATE_PARMS (tparms)
26443 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
26446 tree fntype = build_function_type (type, fparms);
26447 tree ded_fn = build_lang_decl_loc (loc,
26448 FUNCTION_DECL,
26449 dguide_name (type), fntype);
26450 DECL_ARGUMENTS (ded_fn) = fargs;
26451 DECL_ARTIFICIAL (ded_fn) = true;
26452 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
26453 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
26454 DECL_ARTIFICIAL (ded_tmpl) = true;
26455 DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
26456 TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
26457 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
26458 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
26459 if (DECL_P (ctor))
26460 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
26461 if (ci)
26462 set_constraints (ded_tmpl, ci);
26464 return ded_tmpl;
26467 /* Deduce template arguments for the class template placeholder PTYPE for
26468 template TMPL based on the initializer INIT, and return the resulting
26469 type. */
26471 static tree
26472 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
26473 tsubst_flags_t complain)
26475 if (!DECL_CLASS_TEMPLATE_P (tmpl))
26477 /* We should have handled this in the caller. */
26478 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
26479 return ptype;
26480 if (complain & tf_error)
26481 error ("non-class template %qT used without template arguments", tmpl);
26482 return error_mark_node;
26485 tree type = TREE_TYPE (tmpl);
26487 bool try_list_ctor = false;
26489 vec<tree,va_gc> *args;
26490 if (init == NULL_TREE
26491 || TREE_CODE (init) == TREE_LIST)
26492 args = make_tree_vector_from_list (init);
26493 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
26495 try_list_ctor = TYPE_HAS_LIST_CTOR (type);
26496 if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
26498 /* As an exception, the first phase in 16.3.1.7 (considering the
26499 initializer list as a single argument) is omitted if the
26500 initializer list consists of a single expression of type cv U,
26501 where U is a specialization of C or a class derived from a
26502 specialization of C. */
26503 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
26504 tree etype = TREE_TYPE (elt);
26506 tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
26507 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26508 int err = unify (tparms, targs, type, etype,
26509 UNIFY_ALLOW_DERIVED, /*explain*/false);
26510 if (err == 0)
26511 try_list_ctor = false;
26512 ggc_free (targs);
26514 if (try_list_ctor || is_std_init_list (type))
26515 args = make_tree_vector_single (init);
26516 else
26517 args = make_tree_vector_from_ctor (init);
26519 else
26520 args = make_tree_vector_single (init);
26522 tree dname = dguide_name (tmpl);
26523 tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
26524 /*type*/false, /*complain*/false,
26525 /*hidden*/false);
26526 bool elided = false;
26527 if (cands == error_mark_node)
26528 cands = NULL_TREE;
26530 /* Prune explicit deduction guides in copy-initialization context. */
26531 if (flags & LOOKUP_ONLYCONVERTING)
26533 for (lkp_iterator iter (cands); !elided && iter; ++iter)
26534 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26535 elided = true;
26537 if (elided)
26539 /* Found a nonconverting guide, prune the candidates. */
26540 tree pruned = NULL_TREE;
26541 for (lkp_iterator iter (cands); iter; ++iter)
26542 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26543 pruned = lookup_add (*iter, pruned);
26545 cands = pruned;
26549 tree outer_args = NULL_TREE;
26550 if (DECL_CLASS_SCOPE_P (tmpl)
26551 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (tmpl)))
26553 outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26554 type = TREE_TYPE (most_general_template (tmpl));
26557 bool saw_ctor = false;
26558 // FIXME cache artificial deduction guides
26559 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26561 /* Skip inherited constructors. */
26562 if (iter.using_p ())
26563 continue;
26565 tree guide = build_deduction_guide (*iter, outer_args, complain);
26566 if (guide == error_mark_node)
26567 return error_mark_node;
26568 if ((flags & LOOKUP_ONLYCONVERTING)
26569 && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26570 elided = true;
26571 else
26572 cands = lookup_add (guide, cands);
26574 saw_ctor = true;
26577 tree call = error_mark_node;
26579 /* If this is list-initialization and the class has a list constructor, first
26580 try deducing from the list as a single argument, as [over.match.list]. */
26581 tree list_cands = NULL_TREE;
26582 if (try_list_ctor && cands)
26583 for (lkp_iterator iter (cands); iter; ++iter)
26585 tree dg = *iter;
26586 if (is_list_ctor (dg))
26587 list_cands = lookup_add (dg, list_cands);
26589 if (list_cands)
26591 ++cp_unevaluated_operand;
26592 call = build_new_function_call (list_cands, &args, tf_decltype);
26593 --cp_unevaluated_operand;
26595 if (call == error_mark_node)
26597 /* That didn't work, now try treating the list as a sequence of
26598 arguments. */
26599 release_tree_vector (args);
26600 args = make_tree_vector_from_ctor (init);
26604 /* Maybe generate an implicit deduction guide. */
26605 if (call == error_mark_node && args->length () < 2)
26607 tree gtype = NULL_TREE;
26609 if (args->length () == 1)
26610 /* Generate a copy guide. */
26611 gtype = build_reference_type (type);
26612 else if (!saw_ctor)
26613 /* Generate a default guide. */
26614 gtype = type;
26616 if (gtype)
26618 tree guide = build_deduction_guide (gtype, outer_args, complain);
26619 if (guide == error_mark_node)
26620 return error_mark_node;
26621 cands = lookup_add (guide, cands);
26625 if (elided && !cands)
26627 error ("cannot deduce template arguments for copy-initialization"
26628 " of %qT, as it has no non-explicit deduction guides or "
26629 "user-declared constructors", type);
26630 return error_mark_node;
26632 else if (!cands && call == error_mark_node)
26634 error ("cannot deduce template arguments of %qT, as it has no viable "
26635 "deduction guides", type);
26636 return error_mark_node;
26639 if (call == error_mark_node)
26641 ++cp_unevaluated_operand;
26642 call = build_new_function_call (cands, &args, tf_decltype);
26643 --cp_unevaluated_operand;
26646 if (call == error_mark_node && (complain & tf_warning_or_error))
26648 error ("class template argument deduction failed:");
26650 ++cp_unevaluated_operand;
26651 call = build_new_function_call (cands, &args, complain | tf_decltype);
26652 --cp_unevaluated_operand;
26654 if (elided)
26655 inform (input_location, "explicit deduction guides not considered "
26656 "for copy-initialization");
26659 release_tree_vector (args);
26661 return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26664 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26665 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26666 The CONTEXT determines the context in which auto deduction is performed
26667 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
26668 OUTER_TARGS are used during template argument deduction
26669 (context == adc_unify) to properly substitute the result, and is ignored
26670 in other contexts.
26672 For partial-concept-ids, extra args may be appended to the list of deduced
26673 template arguments prior to determining constraint satisfaction. */
26675 tree
26676 do_auto_deduction (tree type, tree init, tree auto_node,
26677 tsubst_flags_t complain, auto_deduction_context context,
26678 tree outer_targs, int flags)
26680 tree targs;
26682 if (init == error_mark_node)
26683 return error_mark_node;
26685 if (init && type_dependent_expression_p (init)
26686 && context != adc_unify)
26687 /* Defining a subset of type-dependent expressions that we can deduce
26688 from ahead of time isn't worth the trouble. */
26689 return type;
26691 /* Similarly, we can't deduce from another undeduced decl. */
26692 if (init && undeduced_auto_decl (init))
26693 return type;
26695 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26696 /* C++17 class template argument deduction. */
26697 return do_class_deduction (type, tmpl, init, flags, complain);
26699 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26700 /* Nothing we can do with this, even in deduction context. */
26701 return type;
26703 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26704 with either a new invented type template parameter U or, if the
26705 initializer is a braced-init-list (8.5.4), with
26706 std::initializer_list<U>. */
26707 if (BRACE_ENCLOSED_INITIALIZER_P (init))
26709 if (!DIRECT_LIST_INIT_P (init))
26710 type = listify_autos (type, auto_node);
26711 else if (CONSTRUCTOR_NELTS (init) == 1)
26712 init = CONSTRUCTOR_ELT (init, 0)->value;
26713 else
26715 if (complain & tf_warning_or_error)
26717 if (permerror (input_location, "direct-list-initialization of "
26718 "%<auto%> requires exactly one element"))
26719 inform (input_location,
26720 "for deduction to %<std::initializer_list%>, use copy-"
26721 "list-initialization (i.e. add %<=%> before the %<{%>)");
26723 type = listify_autos (type, auto_node);
26727 if (type == error_mark_node)
26728 return error_mark_node;
26730 init = resolve_nondeduced_context (init, complain);
26732 if (context == adc_decomp_type
26733 && auto_node == type
26734 && init != error_mark_node
26735 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26736 /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26737 and initializer has array type, deduce cv-qualified array type. */
26738 return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26739 complain);
26740 else if (AUTO_IS_DECLTYPE (auto_node))
26742 bool id = (DECL_P (init)
26743 || ((TREE_CODE (init) == COMPONENT_REF
26744 || TREE_CODE (init) == SCOPE_REF)
26745 && !REF_PARENTHESIZED_P (init)));
26746 targs = make_tree_vec (1);
26747 TREE_VEC_ELT (targs, 0)
26748 = finish_decltype_type (init, id, tf_warning_or_error);
26749 if (type != auto_node)
26751 if (complain & tf_error)
26752 error ("%qT as type rather than plain %<decltype(auto)%>", type);
26753 return error_mark_node;
26756 else
26758 tree parms = build_tree_list (NULL_TREE, type);
26759 tree tparms;
26761 if (flag_concepts)
26762 tparms = extract_autos (type);
26763 else
26765 tparms = make_tree_vec (1);
26766 TREE_VEC_ELT (tparms, 0)
26767 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26770 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26771 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26772 DEDUCE_CALL, LOOKUP_NORMAL,
26773 NULL, /*explain_p=*/false);
26774 if (val > 0)
26776 if (processing_template_decl)
26777 /* Try again at instantiation time. */
26778 return type;
26779 if (type && type != error_mark_node
26780 && (complain & tf_error))
26781 /* If type is error_mark_node a diagnostic must have been
26782 emitted by now. Also, having a mention to '<type error>'
26783 in the diagnostic is not really useful to the user. */
26785 if (cfun && auto_node == current_function_auto_return_pattern
26786 && LAMBDA_FUNCTION_P (current_function_decl))
26787 error ("unable to deduce lambda return type from %qE", init);
26788 else
26789 error ("unable to deduce %qT from %qE", type, init);
26790 type_unification_real (tparms, targs, parms, &init, 1, 0,
26791 DEDUCE_CALL, LOOKUP_NORMAL,
26792 NULL, /*explain_p=*/true);
26794 return error_mark_node;
26798 /* Check any placeholder constraints against the deduced type. */
26799 if (flag_concepts && !processing_template_decl)
26800 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26802 /* Use the deduced type to check the associated constraints. If we
26803 have a partial-concept-id, rebuild the argument list so that
26804 we check using the extra arguments. */
26805 gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26806 tree cargs = CHECK_CONSTR_ARGS (constr);
26807 if (TREE_VEC_LENGTH (cargs) > 1)
26809 cargs = copy_node (cargs);
26810 TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
26812 else
26813 cargs = targs;
26814 if (!constraints_satisfied_p (constr, cargs))
26816 if (complain & tf_warning_or_error)
26818 switch (context)
26820 case adc_unspecified:
26821 case adc_unify:
26822 error("placeholder constraints not satisfied");
26823 break;
26824 case adc_variable_type:
26825 case adc_decomp_type:
26826 error ("deduced initializer does not satisfy "
26827 "placeholder constraints");
26828 break;
26829 case adc_return_type:
26830 error ("deduced return type does not satisfy "
26831 "placeholder constraints");
26832 break;
26833 case adc_requirement:
26834 error ("deduced expression type does not satisfy "
26835 "placeholder constraints");
26836 break;
26838 diagnose_constraints (input_location, constr, targs);
26840 return error_mark_node;
26844 if (processing_template_decl && context != adc_unify)
26845 outer_targs = current_template_args ();
26846 targs = add_to_template_args (outer_targs, targs);
26847 return tsubst (type, targs, complain, NULL_TREE);
26850 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
26851 result. */
26853 tree
26854 splice_late_return_type (tree type, tree late_return_type)
26856 if (is_auto (type))
26858 if (late_return_type)
26859 return late_return_type;
26861 tree idx = get_template_parm_index (type);
26862 if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
26863 /* In an abbreviated function template we didn't know we were dealing
26864 with a function template when we saw the auto return type, so update
26865 it to have the correct level. */
26866 return make_auto_1 (TYPE_IDENTIFIER (type), true);
26868 return type;
26871 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
26872 'decltype(auto)' or a deduced class template. */
26874 bool
26875 is_auto (const_tree type)
26877 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26878 && (TYPE_IDENTIFIER (type) == auto_identifier
26879 || TYPE_IDENTIFIER (type) == decltype_auto_identifier
26880 || CLASS_PLACEHOLDER_TEMPLATE (type)))
26881 return true;
26882 else
26883 return false;
26886 /* for_each_template_parm callback for type_uses_auto. */
26889 is_auto_r (tree tp, void */*data*/)
26891 return is_auto (tp);
26894 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
26895 a use of `auto'. Returns NULL_TREE otherwise. */
26897 tree
26898 type_uses_auto (tree type)
26900 if (type == NULL_TREE)
26901 return NULL_TREE;
26902 else if (flag_concepts)
26904 /* The Concepts TS allows multiple autos in one type-specifier; just
26905 return the first one we find, do_auto_deduction will collect all of
26906 them. */
26907 if (uses_template_parms (type))
26908 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
26909 /*visited*/NULL, /*nondeduced*/false);
26910 else
26911 return NULL_TREE;
26913 else
26914 return find_type_usage (type, is_auto);
26917 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
26918 concepts are enabled, auto is acceptable in template arguments, but
26919 only when TEMPL identifies a template class. Return TRUE if any
26920 such errors were reported. */
26922 bool
26923 check_auto_in_tmpl_args (tree tmpl, tree args)
26925 /* If there were previous errors, nevermind. */
26926 if (!args || TREE_CODE (args) != TREE_VEC)
26927 return false;
26929 /* If TMPL is an identifier, we're parsing and we can't tell yet
26930 whether TMPL is supposed to be a type, a function or a variable.
26931 We'll only be able to tell during template substitution, so we
26932 expect to be called again then. If concepts are enabled and we
26933 know we have a type, we're ok. */
26934 if (flag_concepts
26935 && (identifier_p (tmpl)
26936 || (DECL_P (tmpl)
26937 && (DECL_TYPE_TEMPLATE_P (tmpl)
26938 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
26939 return false;
26941 /* Quickly search for any occurrences of auto; usually there won't
26942 be any, and then we'll avoid allocating the vector. */
26943 if (!type_uses_auto (args))
26944 return false;
26946 bool errors = false;
26948 tree vec = extract_autos (args);
26949 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
26951 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
26952 error_at (DECL_SOURCE_LOCATION (xauto),
26953 "invalid use of %qT in template argument", xauto);
26954 errors = true;
26957 return errors;
26960 /* For a given template T, return the vector of typedefs referenced
26961 in T for which access check is needed at T instantiation time.
26962 T is either a FUNCTION_DECL or a RECORD_TYPE.
26963 Those typedefs were added to T by the function
26964 append_type_to_template_for_access_check. */
26966 vec<qualified_typedef_usage_t, va_gc> *
26967 get_types_needing_access_check (tree t)
26969 tree ti;
26970 vec<qualified_typedef_usage_t, va_gc> *result = NULL;
26972 if (!t || t == error_mark_node)
26973 return NULL;
26975 if (!(ti = get_template_info (t)))
26976 return NULL;
26978 if (CLASS_TYPE_P (t)
26979 || TREE_CODE (t) == FUNCTION_DECL)
26981 if (!TI_TEMPLATE (ti))
26982 return NULL;
26984 result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
26987 return result;
26990 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
26991 tied to T. That list of typedefs will be access checked at
26992 T instantiation time.
26993 T is either a FUNCTION_DECL or a RECORD_TYPE.
26994 TYPE_DECL is a TYPE_DECL node representing a typedef.
26995 SCOPE is the scope through which TYPE_DECL is accessed.
26996 LOCATION is the location of the usage point of TYPE_DECL.
26998 This function is a subroutine of
26999 append_type_to_template_for_access_check. */
27001 static void
27002 append_type_to_template_for_access_check_1 (tree t,
27003 tree type_decl,
27004 tree scope,
27005 location_t location)
27007 qualified_typedef_usage_t typedef_usage;
27008 tree ti;
27010 if (!t || t == error_mark_node)
27011 return;
27013 gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
27014 || CLASS_TYPE_P (t))
27015 && type_decl
27016 && TREE_CODE (type_decl) == TYPE_DECL
27017 && scope);
27019 if (!(ti = get_template_info (t)))
27020 return;
27022 gcc_assert (TI_TEMPLATE (ti));
27024 typedef_usage.typedef_decl = type_decl;
27025 typedef_usage.context = scope;
27026 typedef_usage.locus = location;
27028 vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
27031 /* Append TYPE_DECL to the template TEMPL.
27032 TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
27033 At TEMPL instanciation time, TYPE_DECL will be checked to see
27034 if it can be accessed through SCOPE.
27035 LOCATION is the location of the usage point of TYPE_DECL.
27037 e.g. consider the following code snippet:
27039 class C
27041 typedef int myint;
27044 template<class U> struct S
27046 C::myint mi; // <-- usage point of the typedef C::myint
27049 S<char> s;
27051 At S<char> instantiation time, we need to check the access of C::myint
27052 In other words, we need to check the access of the myint typedef through
27053 the C scope. For that purpose, this function will add the myint typedef
27054 and the scope C through which its being accessed to a list of typedefs
27055 tied to the template S. That list will be walked at template instantiation
27056 time and access check performed on each typedefs it contains.
27057 Note that this particular code snippet should yield an error because
27058 myint is private to C. */
27060 void
27061 append_type_to_template_for_access_check (tree templ,
27062 tree type_decl,
27063 tree scope,
27064 location_t location)
27066 qualified_typedef_usage_t *iter;
27067 unsigned i;
27069 gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27071 /* Make sure we don't append the type to the template twice. */
27072 FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27073 if (iter->typedef_decl == type_decl && scope == iter->context)
27074 return;
27076 append_type_to_template_for_access_check_1 (templ, type_decl,
27077 scope, location);
27080 /* Convert the generic type parameters in PARM that match the types given in the
27081 range [START_IDX, END_IDX) from the current_template_parms into generic type
27082 packs. */
27084 tree
27085 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27087 tree current = current_template_parms;
27088 int depth = TMPL_PARMS_DEPTH (current);
27089 current = INNERMOST_TEMPLATE_PARMS (current);
27090 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27092 for (int i = 0; i < start_idx; ++i)
27093 TREE_VEC_ELT (replacement, i)
27094 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27096 for (int i = start_idx; i < end_idx; ++i)
27098 /* Create a distinct parameter pack type from the current parm and add it
27099 to the replacement args to tsubst below into the generic function
27100 parameter. */
27102 tree o = TREE_TYPE (TREE_VALUE
27103 (TREE_VEC_ELT (current, i)));
27104 tree t = copy_type (o);
27105 TEMPLATE_TYPE_PARM_INDEX (t)
27106 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27107 o, 0, 0, tf_none);
27108 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27109 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27110 TYPE_MAIN_VARIANT (t) = t;
27111 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27112 TYPE_CANONICAL (t) = canonical_type_parameter (t);
27113 TREE_VEC_ELT (replacement, i) = t;
27114 TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27117 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27118 TREE_VEC_ELT (replacement, i)
27119 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27121 /* If there are more levels then build up the replacement with the outer
27122 template parms. */
27123 if (depth > 1)
27124 replacement = add_to_template_args (template_parms_to_args
27125 (TREE_CHAIN (current_template_parms)),
27126 replacement);
27128 return tsubst (parm, replacement, tf_none, NULL_TREE);
27131 /* Entries in the decl_constraint hash table. */
27132 struct GTY((for_user)) constr_entry
27134 tree decl;
27135 tree ci;
27138 /* Hashing function and equality for constraint entries. */
27139 struct constr_hasher : ggc_ptr_hash<constr_entry>
27141 static hashval_t hash (constr_entry *e)
27143 return (hashval_t)DECL_UID (e->decl);
27146 static bool equal (constr_entry *e1, constr_entry *e2)
27148 return e1->decl == e2->decl;
27152 /* A mapping from declarations to constraint information. Note that
27153 both templates and their underlying declarations are mapped to the
27154 same constraint information.
27156 FIXME: This is defined in pt.c because garbage collection
27157 code is not being generated for constraint.cc. */
27159 static GTY (()) hash_table<constr_hasher> *decl_constraints;
27161 /* Returns the template constraints of declaration T. If T is not
27162 constrained, return NULL_TREE. Note that T must be non-null. */
27164 tree
27165 get_constraints (tree t)
27167 if (!flag_concepts)
27168 return NULL_TREE;
27170 gcc_assert (DECL_P (t));
27171 if (TREE_CODE (t) == TEMPLATE_DECL)
27172 t = DECL_TEMPLATE_RESULT (t);
27173 constr_entry elt = { t, NULL_TREE };
27174 constr_entry* found = decl_constraints->find (&elt);
27175 if (found)
27176 return found->ci;
27177 else
27178 return NULL_TREE;
27181 /* Associate the given constraint information CI with the declaration
27182 T. If T is a template, then the constraints are associated with
27183 its underlying declaration. Don't build associations if CI is
27184 NULL_TREE. */
27186 void
27187 set_constraints (tree t, tree ci)
27189 if (!ci)
27190 return;
27191 gcc_assert (t && flag_concepts);
27192 if (TREE_CODE (t) == TEMPLATE_DECL)
27193 t = DECL_TEMPLATE_RESULT (t);
27194 gcc_assert (!get_constraints (t));
27195 constr_entry elt = {t, ci};
27196 constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
27197 constr_entry* entry = ggc_alloc<constr_entry> ();
27198 *entry = elt;
27199 *slot = entry;
27202 /* Remove the associated constraints of the declaration T. */
27204 void
27205 remove_constraints (tree t)
27207 gcc_assert (DECL_P (t));
27208 if (TREE_CODE (t) == TEMPLATE_DECL)
27209 t = DECL_TEMPLATE_RESULT (t);
27211 constr_entry elt = {t, NULL_TREE};
27212 constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
27213 if (slot)
27214 decl_constraints->clear_slot (slot);
27217 /* Memoized satisfaction results for declarations. This
27218 maps the pair (constraint_info, arguments) to the result computed
27219 by constraints_satisfied_p. */
27221 struct GTY((for_user)) constraint_sat_entry
27223 tree ci;
27224 tree args;
27225 tree result;
27228 /* Hashing function and equality for constraint entries. */
27230 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
27232 static hashval_t hash (constraint_sat_entry *e)
27234 hashval_t val = iterative_hash_object(e->ci, 0);
27235 return iterative_hash_template_arg (e->args, val);
27238 static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
27240 return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
27244 /* Memoized satisfaction results for concept checks. */
27246 struct GTY((for_user)) concept_spec_entry
27248 tree tmpl;
27249 tree args;
27250 tree result;
27253 /* Hashing function and equality for constraint entries. */
27255 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
27257 static hashval_t hash (concept_spec_entry *e)
27259 return hash_tmpl_and_args (e->tmpl, e->args);
27262 static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
27264 ++comparing_specializations;
27265 bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
27266 --comparing_specializations;
27267 return eq;
27271 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
27272 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
27274 /* Search for a memoized satisfaction result. Returns one of the
27275 truth value nodes if previously memoized, or NULL_TREE otherwise. */
27277 tree
27278 lookup_constraint_satisfaction (tree ci, tree args)
27280 constraint_sat_entry elt = { ci, args, NULL_TREE };
27281 constraint_sat_entry* found = constraint_memos->find (&elt);
27282 if (found)
27283 return found->result;
27284 else
27285 return NULL_TREE;
27288 /* Memoize the result of a satisfication test. Returns the saved result. */
27290 tree
27291 memoize_constraint_satisfaction (tree ci, tree args, tree result)
27293 constraint_sat_entry elt = {ci, args, result};
27294 constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
27295 constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
27296 *entry = elt;
27297 *slot = entry;
27298 return result;
27301 /* Search for a memoized satisfaction result for a concept. */
27303 tree
27304 lookup_concept_satisfaction (tree tmpl, tree args)
27306 concept_spec_entry elt = { tmpl, args, NULL_TREE };
27307 concept_spec_entry* found = concept_memos->find (&elt);
27308 if (found)
27309 return found->result;
27310 else
27311 return NULL_TREE;
27314 /* Memoize the result of a concept check. Returns the saved result. */
27316 tree
27317 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
27319 concept_spec_entry elt = {tmpl, args, result};
27320 concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
27321 concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27322 *entry = elt;
27323 *slot = entry;
27324 return result;
27327 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
27329 /* Returns a prior concept specialization. This returns the substituted
27330 and normalized constraints defined by the concept. */
27332 tree
27333 get_concept_expansion (tree tmpl, tree args)
27335 concept_spec_entry elt = { tmpl, args, NULL_TREE };
27336 concept_spec_entry* found = concept_expansions->find (&elt);
27337 if (found)
27338 return found->result;
27339 else
27340 return NULL_TREE;
27343 /* Save a concept expansion for later. */
27345 tree
27346 save_concept_expansion (tree tmpl, tree args, tree def)
27348 concept_spec_entry elt = {tmpl, args, def};
27349 concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
27350 concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27351 *entry = elt;
27352 *slot = entry;
27353 return def;
27356 static hashval_t
27357 hash_subsumption_args (tree t1, tree t2)
27359 gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
27360 gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
27361 int val = 0;
27362 val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
27363 val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
27364 val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
27365 val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
27366 return val;
27369 /* Compare the constraints of two subsumption entries. The LEFT1 and
27370 LEFT2 arguments comprise the first subsumption pair and the RIGHT1
27371 and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
27373 static bool
27374 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
27376 if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
27377 if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
27378 if (comp_template_args (CHECK_CONSTR_ARGS (left1),
27379 CHECK_CONSTR_ARGS (right1)))
27380 return comp_template_args (CHECK_CONSTR_ARGS (left2),
27381 CHECK_CONSTR_ARGS (right2));
27382 return false;
27385 /* Key/value pair for learning and memoizing subsumption results. This
27386 associates a pair of check constraints (including arguments) with
27387 a boolean value indicating the result. */
27389 struct GTY((for_user)) subsumption_entry
27391 tree t1;
27392 tree t2;
27393 bool result;
27396 /* Hashing function and equality for constraint entries. */
27398 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
27400 static hashval_t hash (subsumption_entry *e)
27402 return hash_subsumption_args (e->t1, e->t2);
27405 static bool equal (subsumption_entry *e1, subsumption_entry *e2)
27407 ++comparing_specializations;
27408 bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
27409 --comparing_specializations;
27410 return eq;
27414 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
27416 /* Search for a previously cached subsumption result. */
27418 bool*
27419 lookup_subsumption_result (tree t1, tree t2)
27421 subsumption_entry elt = { t1, t2, false };
27422 subsumption_entry* found = subsumption_table->find (&elt);
27423 if (found)
27424 return &found->result;
27425 else
27426 return 0;
27429 /* Save a subsumption result. */
27431 bool
27432 save_subsumption_result (tree t1, tree t2, bool result)
27434 subsumption_entry elt = {t1, t2, result};
27435 subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
27436 subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
27437 *entry = elt;
27438 *slot = entry;
27439 return result;
27442 /* Set up the hash table for constraint association. */
27444 void
27445 init_constraint_processing (void)
27447 if (!flag_concepts)
27448 return;
27450 decl_constraints = hash_table<constr_hasher>::create_ggc(37);
27451 constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
27452 concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
27453 concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
27454 subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
27457 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
27458 0..N-1. */
27460 void
27461 declare_integer_pack (void)
27463 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
27464 build_function_type_list (integer_type_node,
27465 integer_type_node,
27466 NULL_TREE),
27467 NULL_TREE, ECF_CONST);
27468 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
27469 DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
27472 /* Set up the hash tables for template instantiations. */
27474 void
27475 init_template_processing (void)
27477 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
27478 type_specializations = hash_table<spec_hasher>::create_ggc (37);
27480 if (cxx_dialect >= cxx11)
27481 declare_integer_pack ();
27484 /* Print stats about the template hash tables for -fstats. */
27486 void
27487 print_template_statistics (void)
27489 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
27490 "%f collisions\n", (long) decl_specializations->size (),
27491 (long) decl_specializations->elements (),
27492 decl_specializations->collisions ());
27493 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
27494 "%f collisions\n", (long) type_specializations->size (),
27495 (long) type_specializations->elements (),
27496 type_specializations->collisions ());
27499 #if CHECKING_P
27501 namespace selftest {
27503 /* Verify that build_non_dependent_expr () works, for various expressions,
27504 and that location wrappers don't affect the results. */
27506 static void
27507 test_build_non_dependent_expr ()
27509 location_t loc = BUILTINS_LOCATION;
27511 /* Verify constants, without and with location wrappers. */
27512 tree int_cst = build_int_cst (integer_type_node, 42);
27513 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
27515 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
27516 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
27517 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
27519 tree string_lit = build_string (4, "foo");
27520 TREE_TYPE (string_lit) = char_array_type_node;
27521 string_lit = fix_string_type (string_lit);
27522 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
27524 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
27525 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
27526 ASSERT_EQ (wrapped_string_lit,
27527 build_non_dependent_expr (wrapped_string_lit));
27530 /* Verify that type_dependent_expression_p () works correctly, even
27531 in the presence of location wrapper nodes. */
27533 static void
27534 test_type_dependent_expression_p ()
27536 location_t loc = BUILTINS_LOCATION;
27538 tree name = get_identifier ("foo");
27540 /* If no templates are involved, nothing is type-dependent. */
27541 gcc_assert (!processing_template_decl);
27542 ASSERT_FALSE (type_dependent_expression_p (name));
27544 ++processing_template_decl;
27546 /* Within a template, an unresolved name is always type-dependent. */
27547 ASSERT_TRUE (type_dependent_expression_p (name));
27549 /* Ensure it copes with NULL_TREE and errors. */
27550 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
27551 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
27553 /* A USING_DECL in a template should be type-dependent, even if wrapped
27554 with a location wrapper (PR c++/83799). */
27555 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
27556 TREE_TYPE (using_decl) = integer_type_node;
27557 ASSERT_TRUE (type_dependent_expression_p (using_decl));
27558 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
27559 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
27560 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
27562 --processing_template_decl;
27565 /* Run all of the selftests within this file. */
27567 void
27568 cp_pt_c_tests ()
27570 test_build_non_dependent_expr ();
27571 test_type_dependent_expression_p ();
27574 } // namespace selftest
27576 #endif /* #if CHECKING_P */
27578 #include "gt-cp-pt.h"