c++: -Wdangling-reference with reference wrapper [PR107532]
[official-gcc.git] / gcc / cp / call.cc
blob3dfa12a07336739bf728fa8717f29f9b29b2f7e6
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2023 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com) and
4 modified by Brendan Kehoe (brendan@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/>. */
23 /* High-level class interface. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "target.h"
29 #include "cp-tree.h"
30 #include "timevar.h"
31 #include "stringpool.h"
32 #include "cgraph.h"
33 #include "stor-layout.h"
34 #include "trans-mem.h"
35 #include "flags.h"
36 #include "toplev.h"
37 #include "intl.h"
38 #include "convert.h"
39 #include "langhooks.h"
40 #include "c-family/c-objc.h"
41 #include "internal-fn.h"
42 #include "stringpool.h"
43 #include "attribs.h"
44 #include "gcc-rich-location.h"
46 /* The various kinds of conversion. */
48 enum conversion_kind {
49 ck_identity,
50 ck_lvalue,
51 ck_fnptr,
52 ck_qual,
53 ck_std,
54 ck_ptr,
55 ck_pmem,
56 ck_base,
57 ck_ref_bind,
58 ck_user,
59 ck_ambig,
60 ck_list,
61 ck_aggr,
62 ck_rvalue,
63 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
64 this kind whenever we know the true conversion is either bad or outright
65 invalid, but we don't want to attempt to compute the bad conversion (for
66 sake of avoiding unnecessary instantiation). bad_p should always be set
67 for these. */
68 ck_deferred_bad,
71 /* The rank of the conversion. Order of the enumerals matters; better
72 conversions should come earlier in the list. */
74 enum conversion_rank {
75 cr_identity,
76 cr_exact,
77 cr_promotion,
78 cr_std,
79 cr_pbool,
80 cr_user,
81 cr_ellipsis,
82 cr_bad
85 /* An implicit conversion sequence, in the sense of [over.best.ics].
86 The first conversion to be performed is at the end of the chain.
87 That conversion is always a cr_identity conversion. */
89 struct conversion {
90 /* The kind of conversion represented by this step. */
91 conversion_kind kind;
92 /* The rank of this conversion. */
93 conversion_rank rank;
94 BOOL_BITFIELD user_conv_p : 1;
95 BOOL_BITFIELD ellipsis_p : 1;
96 BOOL_BITFIELD this_p : 1;
97 /* True if this conversion would be permitted with a bending of
98 language standards, e.g. disregarding pointer qualifiers or
99 converting integers to pointers. */
100 BOOL_BITFIELD bad_p : 1;
101 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
102 temporary should be created to hold the result of the
103 conversion. If KIND is ck_ambig or ck_user, true means force
104 copy-initialization. */
105 BOOL_BITFIELD need_temporary_p : 1;
106 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
107 from a pointer-to-derived to pointer-to-base is being performed. */
108 BOOL_BITFIELD base_p : 1;
109 /* If KIND is ck_ref_bind, true when either an lvalue reference is
110 being bound to an lvalue expression or an rvalue reference is
111 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
112 true when we are treating an lvalue as an rvalue (12.8p33). If
113 ck_identity, we will be binding a reference directly or decaying to
114 a pointer. */
115 BOOL_BITFIELD rvaluedness_matches_p: 1;
116 BOOL_BITFIELD check_narrowing: 1;
117 /* Whether check_narrowing should only check TREE_CONSTANTs; used
118 in build_converted_constant_expr. */
119 BOOL_BITFIELD check_narrowing_const_only: 1;
120 /* True if this conversion is taking place in a copy-initialization context
121 and we should only consider converting constructors. Only set in
122 ck_base and ck_rvalue. */
123 BOOL_BITFIELD copy_init_p : 1;
124 /* The type of the expression resulting from the conversion. */
125 tree type;
126 union {
127 /* The next conversion in the chain. Since the conversions are
128 arranged from outermost to innermost, the NEXT conversion will
129 actually be performed before this conversion. This variant is
130 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
131 ck_list. Please use the next_conversion function instead
132 of using this field directly. */
133 conversion *next;
134 /* The expression at the beginning of the conversion chain. This
135 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
136 You can use conv_get_original_expr to get this expression. */
137 tree expr;
138 /* The array of conversions for an initializer_list, so this
139 variant is used only when KIN D is ck_list. */
140 conversion **list;
141 } u;
142 /* The function candidate corresponding to this conversion
143 sequence. This field is only used if KIND is ck_user. */
144 struct z_candidate *cand;
147 #define CONVERSION_RANK(NODE) \
148 ((NODE)->bad_p ? cr_bad \
149 : (NODE)->ellipsis_p ? cr_ellipsis \
150 : (NODE)->user_conv_p ? cr_user \
151 : (NODE)->rank)
153 #define BAD_CONVERSION_RANK(NODE) \
154 ((NODE)->ellipsis_p ? cr_ellipsis \
155 : (NODE)->user_conv_p ? cr_user \
156 : (NODE)->rank)
158 static struct obstack conversion_obstack;
159 static bool conversion_obstack_initialized;
160 struct rejection_reason;
162 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
163 static int equal_functions (tree, tree);
164 static int joust (struct z_candidate *, struct z_candidate *, bool,
165 tsubst_flags_t);
166 static int compare_ics (conversion *, conversion *);
167 static void maybe_warn_class_memaccess (location_t, tree,
168 const vec<tree, va_gc> *);
169 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
170 static tree convert_like (conversion *, tree, tsubst_flags_t);
171 static tree convert_like_with_context (conversion *, tree, tree, int,
172 tsubst_flags_t);
173 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
174 tree, tree, tree, bool);
175 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
176 tsubst_flags_t);
177 static void print_z_candidate (location_t, const char *, struct z_candidate *);
178 static void print_z_candidates (location_t, struct z_candidate *);
179 static tree build_this (tree);
180 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
181 static bool any_strictly_viable (struct z_candidate *);
182 static struct z_candidate *add_template_candidate
183 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
184 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
185 static struct z_candidate *add_template_candidate_real
186 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
187 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
188 static bool is_complete (tree);
189 static struct z_candidate *add_conv_candidate
190 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
191 tree, tsubst_flags_t);
192 static struct z_candidate *add_function_candidate
193 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
194 tree, int, conversion**, bool, tsubst_flags_t);
195 static conversion *implicit_conversion (tree, tree, tree, bool, int,
196 tsubst_flags_t);
197 static conversion *reference_binding (tree, tree, tree, bool, int,
198 tsubst_flags_t);
199 static conversion *build_conv (conversion_kind, tree, conversion *);
200 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
201 static conversion *next_conversion (conversion *);
202 static bool is_subseq (conversion *, conversion *);
203 static conversion *maybe_handle_ref_bind (conversion **);
204 static void maybe_handle_implicit_object (conversion **);
205 static struct z_candidate *add_candidate
206 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
207 conversion **, tree, tree, int, struct rejection_reason *, int);
208 static tree source_type (conversion *);
209 static void add_warning (struct z_candidate *, struct z_candidate *);
210 static conversion *direct_reference_binding (tree, conversion *);
211 static bool promoted_arithmetic_type_p (tree);
212 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
213 static char *name_as_c_string (tree, tree, bool *);
214 static tree prep_operand (tree);
215 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
216 bool, tree, tree, int, struct z_candidate **,
217 tsubst_flags_t);
218 static conversion *merge_conversion_sequences (conversion *, conversion *);
219 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
220 static conversion *build_identity_conv (tree, tree);
221 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
222 static bool conv_is_prvalue (conversion *);
223 static tree prevent_lifetime_extension (tree);
225 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
226 NAME can take many forms... */
228 bool
229 check_dtor_name (tree basetype, tree name)
231 /* Just accept something we've already complained about. */
232 if (name == error_mark_node)
233 return true;
235 if (TREE_CODE (name) == TYPE_DECL)
236 name = TREE_TYPE (name);
237 else if (TYPE_P (name))
238 /* OK */;
239 else if (identifier_p (name))
241 if ((MAYBE_CLASS_TYPE_P (basetype)
242 || TREE_CODE (basetype) == ENUMERAL_TYPE)
243 && name == constructor_name (basetype))
244 return true;
246 /* Otherwise lookup the name, it could be an unrelated typedef
247 of the correct type. */
248 name = lookup_name (name, LOOK_want::TYPE);
249 if (!name)
250 return false;
251 name = TREE_TYPE (name);
252 if (name == error_mark_node)
253 return false;
255 else
257 /* In the case of:
259 template <class T> struct S { ~S(); };
260 int i;
261 i.~S();
263 NAME will be a class template. */
264 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
265 return false;
268 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
271 /* We want the address of a function or method. We avoid creating a
272 pointer-to-member function. */
274 tree
275 build_addr_func (tree function, tsubst_flags_t complain)
277 tree type = TREE_TYPE (function);
279 /* We have to do these by hand to avoid real pointer to member
280 functions. */
281 if (TREE_CODE (type) == METHOD_TYPE)
283 if (TREE_CODE (function) == OFFSET_REF)
285 tree object = build_address (TREE_OPERAND (function, 0));
286 return get_member_function_from_ptrfunc (&object,
287 TREE_OPERAND (function, 1),
288 complain);
290 function = build_address (function);
292 else if (TREE_CODE (function) == FUNCTION_DECL
293 && DECL_IMMEDIATE_FUNCTION_P (function))
294 function = build_address (function);
295 else
296 function = decay_conversion (function, complain, /*reject_builtin=*/false);
298 return function;
301 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
302 POINTER_TYPE to those. Note, pointer to member function types
303 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
304 two variants. build_call_a is the primitive taking an array of
305 arguments, while build_call_n is a wrapper that handles varargs. */
307 tree
308 build_call_n (tree function, int n, ...)
310 if (n == 0)
311 return build_call_a (function, 0, NULL);
312 else
314 tree *argarray = XALLOCAVEC (tree, n);
315 va_list ap;
316 int i;
318 va_start (ap, n);
319 for (i = 0; i < n; i++)
320 argarray[i] = va_arg (ap, tree);
321 va_end (ap);
322 return build_call_a (function, n, argarray);
326 /* Update various flags in cfun and the call itself based on what is being
327 called. Split out of build_call_a so that bot_manip can use it too. */
329 void
330 set_flags_from_callee (tree call)
332 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
333 tree decl = cp_get_callee_fndecl_nofold (call);
335 /* We check both the decl and the type; a function may be known not to
336 throw without being declared throw(). */
337 bool nothrow = decl && TREE_NOTHROW (decl);
338 tree callee = cp_get_callee (call);
339 if (callee)
340 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
341 else if (TREE_CODE (call) == CALL_EXPR
342 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
343 nothrow = true;
345 if (cfun && cp_function_chain && !cp_unevaluated_operand)
347 if (!nothrow && at_function_scope_p ())
348 cp_function_chain->can_throw = 1;
350 if (decl && TREE_THIS_VOLATILE (decl))
351 current_function_returns_abnormally = 1;
354 TREE_NOTHROW (call) = nothrow;
357 tree
358 build_call_a (tree function, int n, tree *argarray)
360 tree decl;
361 tree result_type;
362 tree fntype;
363 int i;
365 function = build_addr_func (function, tf_warning_or_error);
367 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
368 fntype = TREE_TYPE (TREE_TYPE (function));
369 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
370 result_type = TREE_TYPE (fntype);
371 /* An rvalue has no cv-qualifiers. */
372 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
373 result_type = cv_unqualified (result_type);
375 function = build_call_array_loc (input_location,
376 result_type, function, n, argarray);
377 set_flags_from_callee (function);
379 decl = get_callee_fndecl (function);
381 if (decl && !TREE_USED (decl))
383 /* We invoke build_call directly for several library
384 functions. These may have been declared normally if
385 we're building libgcc, so we can't just check
386 DECL_ARTIFICIAL. */
387 gcc_assert (DECL_ARTIFICIAL (decl)
388 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
389 "__", 2));
390 mark_used (decl);
393 require_complete_eh_spec_types (fntype, decl);
395 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
397 /* Don't pass empty class objects by value. This is useful
398 for tags in STL, which are used to control overload resolution.
399 We don't need to handle other cases of copying empty classes. */
400 if (!decl || !fndecl_built_in_p (decl))
401 for (i = 0; i < n; i++)
403 tree arg = CALL_EXPR_ARG (function, i);
404 if (is_empty_class (TREE_TYPE (arg))
405 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
407 while (TREE_CODE (arg) == TARGET_EXPR)
408 /* We're disconnecting the initializer from its target,
409 don't create a temporary. */
410 arg = TARGET_EXPR_INITIAL (arg);
411 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
412 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
413 CALL_EXPR_ARG (function, i) = arg;
417 return function;
420 /* New overloading code. */
422 struct z_candidate;
424 struct candidate_warning {
425 z_candidate *loser;
426 candidate_warning *next;
429 /* Information for providing diagnostics about why overloading failed. */
431 enum rejection_reason_code {
432 rr_none,
433 rr_arity,
434 rr_explicit_conversion,
435 rr_template_conversion,
436 rr_arg_conversion,
437 rr_bad_arg_conversion,
438 rr_template_unification,
439 rr_invalid_copy,
440 rr_inherited_ctor,
441 rr_constraint_failure
444 struct conversion_info {
445 /* The index of the argument, 0-based. */
446 int n_arg;
447 /* The actual argument or its type. */
448 tree from;
449 /* The type of the parameter. */
450 tree to_type;
451 /* The location of the argument. */
452 location_t loc;
455 struct rejection_reason {
456 enum rejection_reason_code code;
457 union {
458 /* Information about an arity mismatch. */
459 struct {
460 /* The expected number of arguments. */
461 int expected;
462 /* The actual number of arguments in the call. */
463 int actual;
464 /* Whether EXPECTED should be treated as a lower bound. */
465 bool least_p;
466 } arity;
467 /* Information about an argument conversion mismatch. */
468 struct conversion_info conversion;
469 /* Same, but for bad argument conversions. */
470 struct conversion_info bad_conversion;
471 /* Information about template unification failures. These are the
472 parameters passed to fn_type_unification. */
473 struct {
474 tree tmpl;
475 tree explicit_targs;
476 int num_targs;
477 const tree *args;
478 unsigned int nargs;
479 tree return_type;
480 unification_kind_t strict;
481 int flags;
482 } template_unification;
483 /* Information about template instantiation failures. These are the
484 parameters passed to instantiate_template. */
485 struct {
486 tree tmpl;
487 tree targs;
488 } template_instantiation;
489 } u;
492 struct z_candidate {
493 /* The FUNCTION_DECL that will be called if this candidate is
494 selected by overload resolution. */
495 tree fn;
496 /* If not NULL_TREE, the first argument to use when calling this
497 function. */
498 tree first_arg;
499 /* The rest of the arguments to use when calling this function. If
500 there are no further arguments this may be NULL or it may be an
501 empty vector. */
502 const vec<tree, va_gc> *args;
503 /* The implicit conversion sequences for each of the arguments to
504 FN. */
505 conversion **convs;
506 /* The number of implicit conversion sequences. */
507 size_t num_convs;
508 /* If FN is a user-defined conversion, the standard conversion
509 sequence from the type returned by FN to the desired destination
510 type. */
511 conversion *second_conv;
512 struct rejection_reason *reason;
513 /* If FN is a member function, the binfo indicating the path used to
514 qualify the name of FN at the call site. This path is used to
515 determine whether or not FN is accessible if it is selected by
516 overload resolution. The DECL_CONTEXT of FN will always be a
517 (possibly improper) base of this binfo. */
518 tree access_path;
519 /* If FN is a non-static member function, the binfo indicating the
520 subobject to which the `this' pointer should be converted if FN
521 is selected by overload resolution. The type pointed to by
522 the `this' pointer must correspond to the most derived class
523 indicated by the CONVERSION_PATH. */
524 tree conversion_path;
525 tree template_decl;
526 tree explicit_targs;
527 candidate_warning *warnings;
528 z_candidate *next;
529 int viable;
531 /* The flags active in add_candidate. */
532 int flags;
534 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
535 bool reversed () const { return (flags & LOOKUP_REVERSED); }
538 /* Returns true iff T is a null pointer constant in the sense of
539 [conv.ptr]. */
541 bool
542 null_ptr_cst_p (tree t)
544 tree type = TREE_TYPE (t);
546 /* [conv.ptr]
548 A null pointer constant is an integer literal ([lex.icon]) with value
549 zero or a prvalue of type std::nullptr_t. */
550 if (NULLPTR_TYPE_P (type))
551 return true;
553 if (cxx_dialect >= cxx11)
555 STRIP_ANY_LOCATION_WRAPPER (t);
557 /* Core issue 903 says only literal 0 is a null pointer constant. */
558 if (TREE_CODE (t) == INTEGER_CST
559 && !TREE_OVERFLOW (t)
560 && TREE_CODE (type) == INTEGER_TYPE
561 && integer_zerop (t)
562 && !char_type_p (type))
563 return true;
565 else if (CP_INTEGRAL_TYPE_P (type))
567 t = fold_non_dependent_expr (t, tf_none);
568 STRIP_NOPS (t);
569 if (integer_zerop (t) && !TREE_OVERFLOW (t))
570 return true;
573 return false;
576 /* Returns true iff T is a null member pointer value (4.11). */
578 bool
579 null_member_pointer_value_p (tree t)
581 tree type = TREE_TYPE (t);
582 if (!type)
583 return false;
584 else if (TYPE_PTRMEMFUNC_P (type))
585 return (TREE_CODE (t) == CONSTRUCTOR
586 && CONSTRUCTOR_NELTS (t)
587 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
588 else if (TYPE_PTRDATAMEM_P (type))
589 return integer_all_onesp (t);
590 else
591 return false;
594 /* Returns nonzero if PARMLIST consists of only default parms,
595 ellipsis, and/or undeduced parameter packs. */
597 bool
598 sufficient_parms_p (const_tree parmlist)
600 for (; parmlist && parmlist != void_list_node;
601 parmlist = TREE_CHAIN (parmlist))
602 if (!TREE_PURPOSE (parmlist)
603 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
604 return false;
605 return true;
608 /* Allocate N bytes of memory from the conversion obstack. The memory
609 is zeroed before being returned. */
611 static void *
612 conversion_obstack_alloc (size_t n)
614 void *p;
615 if (!conversion_obstack_initialized)
617 gcc_obstack_init (&conversion_obstack);
618 conversion_obstack_initialized = true;
620 p = obstack_alloc (&conversion_obstack, n);
621 memset (p, 0, n);
622 return p;
625 /* RAII class to discard anything added to conversion_obstack. */
627 struct conversion_obstack_sentinel
629 void *p;
630 conversion_obstack_sentinel (): p (conversion_obstack_alloc (0)) {}
631 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
634 /* Allocate rejection reasons. */
636 static struct rejection_reason *
637 alloc_rejection (enum rejection_reason_code code)
639 struct rejection_reason *p;
640 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
641 p->code = code;
642 return p;
645 static struct rejection_reason *
646 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
648 struct rejection_reason *r = alloc_rejection (rr_arity);
649 int adjust = first_arg != NULL_TREE;
650 r->u.arity.expected = expected - adjust;
651 r->u.arity.actual = actual - adjust;
652 r->u.arity.least_p = least_p;
653 return r;
656 static struct rejection_reason *
657 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
658 location_t loc)
660 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
661 int adjust = first_arg != NULL_TREE;
662 r->u.conversion.n_arg = n_arg - adjust;
663 r->u.conversion.from = from;
664 r->u.conversion.to_type = to;
665 r->u.conversion.loc = loc;
666 return r;
669 static struct rejection_reason *
670 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
671 location_t loc)
673 struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
674 int adjust = first_arg != NULL_TREE;
675 r->u.bad_conversion.n_arg = n_arg - adjust;
676 r->u.bad_conversion.from = from;
677 r->u.bad_conversion.to_type = to;
678 r->u.bad_conversion.loc = loc;
679 return r;
682 static struct rejection_reason *
683 explicit_conversion_rejection (tree from, tree to)
685 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
686 r->u.conversion.n_arg = 0;
687 r->u.conversion.from = from;
688 r->u.conversion.to_type = to;
689 r->u.conversion.loc = UNKNOWN_LOCATION;
690 return r;
693 static struct rejection_reason *
694 template_conversion_rejection (tree from, tree to)
696 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
697 r->u.conversion.n_arg = 0;
698 r->u.conversion.from = from;
699 r->u.conversion.to_type = to;
700 r->u.conversion.loc = UNKNOWN_LOCATION;
701 return r;
704 static struct rejection_reason *
705 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
706 const tree *args, unsigned int nargs,
707 tree return_type, unification_kind_t strict,
708 int flags)
710 size_t args_n_bytes = sizeof (*args) * nargs;
711 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
712 struct rejection_reason *r = alloc_rejection (rr_template_unification);
713 r->u.template_unification.tmpl = tmpl;
714 r->u.template_unification.explicit_targs = explicit_targs;
715 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
716 /* Copy args to our own storage. */
717 memcpy (args1, args, args_n_bytes);
718 r->u.template_unification.args = args1;
719 r->u.template_unification.nargs = nargs;
720 r->u.template_unification.return_type = return_type;
721 r->u.template_unification.strict = strict;
722 r->u.template_unification.flags = flags;
723 return r;
726 static struct rejection_reason *
727 template_unification_error_rejection (void)
729 return alloc_rejection (rr_template_unification);
732 static struct rejection_reason *
733 invalid_copy_with_fn_template_rejection (void)
735 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
736 return r;
739 static struct rejection_reason *
740 inherited_ctor_rejection (void)
742 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
743 return r;
746 /* Build a constraint failure record. */
748 static struct rejection_reason *
749 constraint_failure (void)
751 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
752 return r;
755 /* Dynamically allocate a conversion. */
757 static conversion *
758 alloc_conversion (conversion_kind kind)
760 conversion *c;
761 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
762 c->kind = kind;
763 return c;
766 /* Make sure that all memory on the conversion obstack has been
767 freed. */
769 void
770 validate_conversion_obstack (void)
772 if (conversion_obstack_initialized)
773 gcc_assert ((obstack_next_free (&conversion_obstack)
774 == obstack_base (&conversion_obstack)));
777 /* Dynamically allocate an array of N conversions. */
779 static conversion **
780 alloc_conversions (size_t n)
782 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
785 /* True iff the active member of conversion::u for code CODE is NEXT. */
787 static inline bool
788 has_next (conversion_kind code)
790 return !(code == ck_identity
791 || code == ck_ambig
792 || code == ck_list
793 || code == ck_aggr
794 || code == ck_deferred_bad);
797 static conversion *
798 build_conv (conversion_kind code, tree type, conversion *from)
800 conversion *t;
801 conversion_rank rank = CONVERSION_RANK (from);
803 /* Only call this function for conversions that use u.next. */
804 gcc_assert (from == NULL || has_next (code));
806 /* Note that the caller is responsible for filling in t->cand for
807 user-defined conversions. */
808 t = alloc_conversion (code);
809 t->type = type;
810 t->u.next = from;
812 switch (code)
814 case ck_ptr:
815 case ck_pmem:
816 case ck_base:
817 case ck_std:
818 if (rank < cr_std)
819 rank = cr_std;
820 break;
822 case ck_qual:
823 case ck_fnptr:
824 if (rank < cr_exact)
825 rank = cr_exact;
826 break;
828 default:
829 break;
831 t->rank = rank;
832 t->user_conv_p = (code == ck_user || from->user_conv_p);
833 t->bad_p = from->bad_p;
834 t->base_p = false;
835 return t;
838 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
839 specialization of std::initializer_list<T>, if such a conversion is
840 possible. */
842 static conversion *
843 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
845 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
846 unsigned len = CONSTRUCTOR_NELTS (ctor);
847 conversion **subconvs = alloc_conversions (len);
848 conversion *t;
849 unsigned i;
850 tree val;
852 /* Within a list-initialization we can have more user-defined
853 conversions. */
854 flags &= ~LOOKUP_NO_CONVERSION;
855 /* But no narrowing conversions. */
856 flags |= LOOKUP_NO_NARROWING;
858 /* Can't make an array of these types. */
859 if (TYPE_REF_P (elttype)
860 || TREE_CODE (elttype) == FUNCTION_TYPE
861 || VOID_TYPE_P (elttype))
862 return NULL;
864 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
866 conversion *sub
867 = implicit_conversion (elttype, TREE_TYPE (val), val,
868 false, flags, complain);
869 if (sub == NULL)
870 return NULL;
872 subconvs[i] = sub;
875 t = alloc_conversion (ck_list);
876 t->type = type;
877 t->u.list = subconvs;
878 t->rank = cr_exact;
880 for (i = 0; i < len; ++i)
882 conversion *sub = subconvs[i];
883 if (sub->rank > t->rank)
884 t->rank = sub->rank;
885 if (sub->user_conv_p)
886 t->user_conv_p = true;
887 if (sub->bad_p)
888 t->bad_p = true;
891 return t;
894 /* Return the next conversion of the conversion chain (if applicable),
895 or NULL otherwise. Please use this function instead of directly
896 accessing fields of struct conversion. */
898 static conversion *
899 next_conversion (conversion *conv)
901 if (conv == NULL
902 || !has_next (conv->kind))
903 return NULL;
904 return conv->u.next;
907 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
908 encountered. */
910 static conversion *
911 strip_standard_conversion (conversion *conv)
913 while (conv
914 && conv->kind != ck_user
915 && has_next (conv->kind))
916 conv = next_conversion (conv);
917 return conv;
920 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
921 initializer for array type ATYPE. */
923 static bool
924 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
926 tree elttype = TREE_TYPE (atype);
927 unsigned i;
929 if (TREE_CODE (from) == CONSTRUCTOR)
931 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
933 tree val = CONSTRUCTOR_ELT (from, i)->value;
934 bool ok;
935 if (TREE_CODE (elttype) == ARRAY_TYPE)
936 ok = can_convert_array (elttype, val, flags, complain);
937 else
938 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
939 complain);
940 if (!ok)
941 return false;
943 return true;
946 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
947 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
948 return array_string_literal_compatible_p (atype, from);
950 /* No other valid way to aggregate initialize an array. */
951 return false;
954 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
955 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
956 is in PSET. */
958 static bool
959 field_in_pset (hash_set<tree, true> &pset, tree field)
961 if (pset.contains (field))
962 return true;
963 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
964 for (field = TYPE_FIELDS (TREE_TYPE (field));
965 field; field = DECL_CHAIN (field))
967 field = next_aggregate_field (field);
968 if (field == NULL_TREE)
969 break;
970 if (field_in_pset (pset, field))
971 return true;
973 return false;
976 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
977 aggregate class, if such a conversion is possible. */
979 static conversion *
980 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
982 unsigned HOST_WIDE_INT i = 0;
983 conversion *c;
984 tree field = next_aggregate_field (TYPE_FIELDS (type));
985 tree empty_ctor = NULL_TREE;
986 hash_set<tree, true> pset;
988 /* We already called reshape_init in implicit_conversion, but it might not
989 have done anything in the case of parenthesized aggr init. */
991 /* The conversions within the init-list aren't affected by the enclosing
992 context; they're always simple copy-initialization. */
993 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
995 /* For designated initializers, verify that each initializer is convertible
996 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
997 visited. In the following loop then ignore already visited
998 FIELD_DECLs. */
999 tree idx, val;
1000 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1002 if (!idx)
1003 break;
1005 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1007 tree ftype = TREE_TYPE (idx);
1008 bool ok;
1010 if (TREE_CODE (ftype) == ARRAY_TYPE)
1011 ok = can_convert_array (ftype, val, flags, complain);
1012 else
1013 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1014 complain);
1016 if (!ok)
1017 return NULL;
1019 /* For unions, there should be just one initializer. */
1020 if (TREE_CODE (type) == UNION_TYPE)
1022 field = NULL_TREE;
1023 i = 1;
1024 break;
1026 pset.add (idx);
1029 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1031 tree ftype = TREE_TYPE (field);
1032 bool ok;
1034 if (!pset.is_empty () && field_in_pset (pset, field))
1035 continue;
1036 if (i < CONSTRUCTOR_NELTS (ctor))
1038 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1039 gcc_checking_assert (!ce->index);
1040 val = ce->value;
1041 ++i;
1043 else if (DECL_INITIAL (field))
1044 val = get_nsdmi (field, /*ctor*/false, complain);
1045 else if (TYPE_REF_P (ftype))
1046 /* Value-initialization of reference is ill-formed. */
1047 return NULL;
1048 else
1050 if (empty_ctor == NULL_TREE)
1051 empty_ctor = build_constructor (init_list_type_node, NULL);
1052 val = empty_ctor;
1055 if (TREE_CODE (ftype) == ARRAY_TYPE)
1056 ok = can_convert_array (ftype, val, flags, complain);
1057 else
1058 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1059 complain);
1061 if (!ok)
1062 return NULL;
1064 if (TREE_CODE (type) == UNION_TYPE)
1065 break;
1068 if (i < CONSTRUCTOR_NELTS (ctor))
1069 return NULL;
1071 c = alloc_conversion (ck_aggr);
1072 c->type = type;
1073 c->rank = cr_exact;
1074 c->user_conv_p = true;
1075 c->check_narrowing = true;
1076 c->u.expr = ctor;
1077 return c;
1080 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1081 array type, if such a conversion is possible. */
1083 static conversion *
1084 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1086 conversion *c;
1087 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1088 tree elttype = TREE_TYPE (type);
1089 bool bad = false;
1090 bool user = false;
1091 enum conversion_rank rank = cr_exact;
1093 /* We might need to propagate the size from the element to the array. */
1094 complete_type (type);
1096 if (TYPE_DOMAIN (type)
1097 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1099 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1100 if (alen < len)
1101 return NULL;
1104 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1106 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1108 conversion *sub
1109 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1110 false, flags, complain);
1111 if (sub == NULL)
1112 return NULL;
1114 if (sub->rank > rank)
1115 rank = sub->rank;
1116 if (sub->user_conv_p)
1117 user = true;
1118 if (sub->bad_p)
1119 bad = true;
1122 c = alloc_conversion (ck_aggr);
1123 c->type = type;
1124 c->rank = rank;
1125 c->user_conv_p = user;
1126 c->bad_p = bad;
1127 c->u.expr = ctor;
1128 return c;
1131 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1132 complex type, if such a conversion is possible. */
1134 static conversion *
1135 build_complex_conv (tree type, tree ctor, int flags,
1136 tsubst_flags_t complain)
1138 conversion *c;
1139 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1140 tree elttype = TREE_TYPE (type);
1141 bool bad = false;
1142 bool user = false;
1143 enum conversion_rank rank = cr_exact;
1145 if (len != 2)
1146 return NULL;
1148 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1150 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1152 conversion *sub
1153 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1154 false, flags, complain);
1155 if (sub == NULL)
1156 return NULL;
1158 if (sub->rank > rank)
1159 rank = sub->rank;
1160 if (sub->user_conv_p)
1161 user = true;
1162 if (sub->bad_p)
1163 bad = true;
1166 c = alloc_conversion (ck_aggr);
1167 c->type = type;
1168 c->rank = rank;
1169 c->user_conv_p = user;
1170 c->bad_p = bad;
1171 c->u.expr = ctor;
1172 return c;
1175 /* Build a representation of the identity conversion from EXPR to
1176 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1178 static conversion *
1179 build_identity_conv (tree type, tree expr)
1181 conversion *c;
1183 c = alloc_conversion (ck_identity);
1184 c->type = type;
1185 c->u.expr = expr;
1187 return c;
1190 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1191 were multiple user-defined conversions to accomplish the job.
1192 Build a conversion that indicates that ambiguity. */
1194 static conversion *
1195 build_ambiguous_conv (tree type, tree expr)
1197 conversion *c;
1199 c = alloc_conversion (ck_ambig);
1200 c->type = type;
1201 c->u.expr = expr;
1203 return c;
1206 tree
1207 strip_top_quals (tree t)
1209 if (TREE_CODE (t) == ARRAY_TYPE)
1210 return t;
1211 return cp_build_qualified_type (t, 0);
1214 /* Returns the standard conversion path (see [conv]) from type FROM to type
1215 TO, if any. For proper handling of null pointer constants, you must
1216 also pass the expression EXPR to convert from. If C_CAST_P is true,
1217 this conversion is coming from a C-style cast. */
1219 static conversion *
1220 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1221 int flags, tsubst_flags_t complain)
1223 enum tree_code fcode, tcode;
1224 conversion *conv;
1225 bool fromref = false;
1226 tree qualified_to;
1228 to = non_reference (to);
1229 if (TYPE_REF_P (from))
1231 fromref = true;
1232 from = TREE_TYPE (from);
1234 qualified_to = to;
1235 to = strip_top_quals (to);
1236 from = strip_top_quals (from);
1238 if (expr && type_unknown_p (expr))
1240 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1242 tsubst_flags_t tflags = tf_conv;
1243 expr = instantiate_type (to, expr, tflags);
1244 if (expr == error_mark_node)
1245 return NULL;
1246 from = TREE_TYPE (expr);
1248 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1250 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1251 expr = resolve_nondeduced_context (expr, complain);
1252 from = TREE_TYPE (expr);
1256 fcode = TREE_CODE (from);
1257 tcode = TREE_CODE (to);
1259 conv = build_identity_conv (from, expr);
1260 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1262 from = type_decays_to (from);
1263 fcode = TREE_CODE (from);
1264 /* Tell convert_like that we're using the address. */
1265 conv->rvaluedness_matches_p = true;
1266 conv = build_conv (ck_lvalue, from, conv);
1268 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1269 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1270 express the copy constructor call required by copy-initialization. */
1271 else if (fromref || (expr && obvalue_p (expr)))
1273 if (expr)
1275 tree bitfield_type;
1276 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1277 if (bitfield_type)
1279 from = strip_top_quals (bitfield_type);
1280 fcode = TREE_CODE (from);
1283 conv = build_conv (ck_rvalue, from, conv);
1284 /* If we're performing copy-initialization, remember to skip
1285 explicit constructors. */
1286 if (flags & LOOKUP_ONLYCONVERTING)
1287 conv->copy_init_p = true;
1290 /* Allow conversion between `__complex__' data types. */
1291 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1293 /* The standard conversion sequence to convert FROM to TO is
1294 the standard conversion sequence to perform componentwise
1295 conversion. */
1296 conversion *part_conv = standard_conversion
1297 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1298 complain);
1300 if (!part_conv)
1301 conv = NULL;
1302 else if (part_conv->kind == ck_identity)
1303 /* Leave conv alone. */;
1304 else
1306 conv = build_conv (part_conv->kind, to, conv);
1307 conv->rank = part_conv->rank;
1310 return conv;
1313 if (same_type_p (from, to))
1315 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1316 conv->type = qualified_to;
1317 return conv;
1320 /* [conv.ptr]
1321 A null pointer constant can be converted to a pointer type; ... A
1322 null pointer constant of integral type can be converted to an
1323 rvalue of type std::nullptr_t. */
1324 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1325 || NULLPTR_TYPE_P (to))
1326 && ((expr && null_ptr_cst_p (expr))
1327 || NULLPTR_TYPE_P (from)))
1328 conv = build_conv (ck_std, to, conv);
1329 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1330 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1332 /* For backwards brain damage compatibility, allow interconversion of
1333 pointers and integers with a pedwarn. */
1334 conv = build_conv (ck_std, to, conv);
1335 conv->bad_p = true;
1337 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1339 /* For backwards brain damage compatibility, allow interconversion of
1340 enums and integers with a pedwarn. */
1341 conv = build_conv (ck_std, to, conv);
1342 conv->bad_p = true;
1344 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1345 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1347 tree to_pointee;
1348 tree from_pointee;
1350 if (tcode == POINTER_TYPE)
1352 to_pointee = TREE_TYPE (to);
1353 from_pointee = TREE_TYPE (from);
1355 /* Since this is the target of a pointer, it can't have function
1356 qualifiers, so any TYPE_QUALS must be for attributes const or
1357 noreturn. Strip them. */
1358 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1359 && TYPE_QUALS (to_pointee))
1360 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1361 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1362 && TYPE_QUALS (from_pointee))
1363 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1365 else
1367 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1368 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1371 if (tcode == POINTER_TYPE
1372 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1373 to_pointee))
1375 else if (VOID_TYPE_P (to_pointee)
1376 && !TYPE_PTRDATAMEM_P (from)
1377 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1379 tree nfrom = TREE_TYPE (from);
1380 /* Don't try to apply restrict to void. */
1381 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1382 from_pointee = cp_build_qualified_type (void_type_node, quals);
1383 from = build_pointer_type (from_pointee);
1384 conv = build_conv (ck_ptr, from, conv);
1386 else if (TYPE_PTRDATAMEM_P (from))
1388 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1389 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1391 if (same_type_p (fbase, tbase))
1392 /* No base conversion needed. */;
1393 else if (DERIVED_FROM_P (fbase, tbase)
1394 && (same_type_ignoring_top_level_qualifiers_p
1395 (from_pointee, to_pointee)))
1397 from = build_ptrmem_type (tbase, from_pointee);
1398 conv = build_conv (ck_pmem, from, conv);
1400 else
1401 return NULL;
1403 else if (CLASS_TYPE_P (from_pointee)
1404 && CLASS_TYPE_P (to_pointee)
1405 /* [conv.ptr]
1407 An rvalue of type "pointer to cv D," where D is a
1408 class type, can be converted to an rvalue of type
1409 "pointer to cv B," where B is a base class (clause
1410 _class.derived_) of D. If B is an inaccessible
1411 (clause _class.access_) or ambiguous
1412 (_class.member.lookup_) base class of D, a program
1413 that necessitates this conversion is ill-formed.
1414 Therefore, we use DERIVED_FROM_P, and do not check
1415 access or uniqueness. */
1416 && DERIVED_FROM_P (to_pointee, from_pointee))
1418 from_pointee
1419 = cp_build_qualified_type (to_pointee,
1420 cp_type_quals (from_pointee));
1421 from = build_pointer_type (from_pointee);
1422 conv = build_conv (ck_ptr, from, conv);
1423 conv->base_p = true;
1426 if (same_type_p (from, to))
1427 /* OK */;
1428 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1429 /* In a C-style cast, we ignore CV-qualification because we
1430 are allowed to perform a static_cast followed by a
1431 const_cast. */
1432 conv = build_conv (ck_qual, to, conv);
1433 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1434 conv = build_conv (ck_qual, to, conv);
1435 else if (expr && string_conv_p (to, expr, 0))
1436 /* converting from string constant to char *. */
1437 conv = build_conv (ck_qual, to, conv);
1438 else if (fnptr_conv_p (to, from))
1439 conv = build_conv (ck_fnptr, to, conv);
1440 /* Allow conversions among compatible ObjC pointer types (base
1441 conversions have been already handled above). */
1442 else if (c_dialect_objc ()
1443 && objc_compare_types (to, from, -4, NULL_TREE))
1444 conv = build_conv (ck_ptr, to, conv);
1445 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1447 conv = build_conv (ck_ptr, to, conv);
1448 conv->bad_p = true;
1450 else
1451 return NULL;
1453 from = to;
1455 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1457 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1458 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1459 tree fbase = class_of_this_parm (fromfn);
1460 tree tbase = class_of_this_parm (tofn);
1462 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1463 yields false. But a pointer to member of incomplete class is OK. */
1464 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1465 return NULL;
1467 tree fstat = static_fn_type (fromfn);
1468 tree tstat = static_fn_type (tofn);
1469 if (same_type_p (tstat, fstat)
1470 || fnptr_conv_p (tstat, fstat))
1471 /* OK */;
1472 else
1473 return NULL;
1475 if (!same_type_p (fbase, tbase))
1477 from = build_memfn_type (fstat,
1478 tbase,
1479 cp_type_quals (tbase),
1480 type_memfn_rqual (tofn));
1481 from = build_ptrmemfunc_type (build_pointer_type (from));
1482 conv = build_conv (ck_pmem, from, conv);
1483 conv->base_p = true;
1485 if (fnptr_conv_p (tstat, fstat))
1486 conv = build_conv (ck_fnptr, to, conv);
1488 else if (tcode == BOOLEAN_TYPE)
1490 /* [conv.bool]
1492 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1493 to member type can be converted to a prvalue of type bool. ...
1494 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1495 std::nullptr_t can be converted to a prvalue of type bool; */
1496 if (ARITHMETIC_TYPE_P (from)
1497 || UNSCOPED_ENUM_P (from)
1498 || fcode == POINTER_TYPE
1499 || TYPE_PTRMEM_P (from)
1500 || NULLPTR_TYPE_P (from))
1502 conv = build_conv (ck_std, to, conv);
1503 if (fcode == POINTER_TYPE
1504 || TYPE_PTRDATAMEM_P (from)
1505 || (TYPE_PTRMEMFUNC_P (from)
1506 && conv->rank < cr_pbool)
1507 || NULLPTR_TYPE_P (from))
1508 conv->rank = cr_pbool;
1509 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1510 conv->bad_p = true;
1511 if (flags & LOOKUP_NO_NARROWING)
1512 conv->check_narrowing = true;
1513 return conv;
1516 return NULL;
1518 /* We don't check for ENUMERAL_TYPE here because there are no standard
1519 conversions to enum type. */
1520 /* As an extension, allow conversion to complex type. */
1521 else if (ARITHMETIC_TYPE_P (to))
1523 if (! (INTEGRAL_CODE_P (fcode)
1524 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1525 || SCOPED_ENUM_P (from))
1526 return NULL;
1528 /* If we're parsing an enum with no fixed underlying type, we're
1529 dealing with an incomplete type, which renders the conversion
1530 ill-formed. */
1531 if (!COMPLETE_TYPE_P (from))
1532 return NULL;
1534 conv = build_conv (ck_std, to, conv);
1536 tree underlying_type = NULL_TREE;
1537 if (TREE_CODE (from) == ENUMERAL_TYPE
1538 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1539 underlying_type = ENUM_UNDERLYING_TYPE (from);
1541 /* Give this a better rank if it's a promotion.
1543 To handle CWG 1601, also bump the rank if we are converting
1544 an enumeration with a fixed underlying type to the underlying
1545 type. */
1546 if ((same_type_p (to, type_promotes_to (from))
1547 || (underlying_type && same_type_p (to, underlying_type)))
1548 && next_conversion (conv)->rank <= cr_promotion)
1549 conv->rank = cr_promotion;
1551 /* A prvalue of floating-point type can be converted to a prvalue of
1552 another floating-point type with a greater or equal conversion
1553 rank ([conv.rank]). A prvalue of standard floating-point type can
1554 be converted to a prvalue of another standard floating-point type.
1555 For backwards compatibility with handling __float128 and other
1556 non-standard floating point types, allow all implicit floating
1557 point conversions if neither type is extended floating-point
1558 type and if at least one of them is, fail if they have unordered
1559 conversion rank or from has higher conversion rank. */
1560 if (fcode == REAL_TYPE
1561 && tcode == REAL_TYPE
1562 && (extended_float_type_p (from)
1563 || extended_float_type_p (to))
1564 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1565 conv->bad_p = true;
1567 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1568 && vector_types_convertible_p (from, to, false))
1569 return build_conv (ck_std, to, conv);
1570 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1571 && is_properly_derived_from (from, to))
1573 if (conv->kind == ck_rvalue)
1574 conv = next_conversion (conv);
1575 conv = build_conv (ck_base, to, conv);
1576 /* The derived-to-base conversion indicates the initialization
1577 of a parameter with base type from an object of a derived
1578 type. A temporary object is created to hold the result of
1579 the conversion unless we're binding directly to a reference. */
1580 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1581 /* If we're performing copy-initialization, remember to skip
1582 explicit constructors. */
1583 if (flags & LOOKUP_ONLYCONVERTING)
1584 conv->copy_init_p = true;
1586 else
1587 return NULL;
1589 if (flags & LOOKUP_NO_NARROWING)
1590 conv->check_narrowing = true;
1592 return conv;
1595 /* Returns nonzero if T1 is reference-related to T2. */
1597 bool
1598 reference_related_p (tree t1, tree t2)
1600 if (t1 == error_mark_node || t2 == error_mark_node)
1601 return false;
1603 t1 = TYPE_MAIN_VARIANT (t1);
1604 t2 = TYPE_MAIN_VARIANT (t2);
1606 /* [dcl.init.ref]
1608 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1609 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1610 return (similar_type_p (t1, t2)
1611 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1612 && DERIVED_FROM_P (t1, t2)));
1615 /* Returns nonzero if T1 is reference-compatible with T2. */
1617 bool
1618 reference_compatible_p (tree t1, tree t2)
1620 /* [dcl.init.ref]
1622 "cv1 T1" is reference compatible with "cv2 T2" if
1623 a prvalue of type "pointer to cv2 T2" can be converted to the type
1624 "pointer to cv1 T1" via a standard conversion sequence. */
1625 tree ptype1 = build_pointer_type (t1);
1626 tree ptype2 = build_pointer_type (t2);
1627 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1628 /*c_cast_p=*/false, 0, tf_none);
1629 if (!conv || conv->bad_p)
1630 return false;
1631 return true;
1634 /* Return true if converting FROM to TO would involve a qualification
1635 conversion. */
1637 static bool
1638 involves_qualification_conversion_p (tree to, tree from)
1640 /* If we're not convering a pointer to another one, we won't get
1641 a qualification conversion. */
1642 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1643 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1644 return false;
1646 conversion *conv = standard_conversion (to, from, NULL_TREE,
1647 /*c_cast_p=*/false, 0, tf_none);
1648 for (conversion *t = conv; t; t = next_conversion (t))
1649 if (t->kind == ck_qual)
1650 return true;
1652 return false;
1655 /* A reference of the indicated TYPE is being bound directly to the
1656 expression represented by the implicit conversion sequence CONV.
1657 Return a conversion sequence for this binding. */
1659 static conversion *
1660 direct_reference_binding (tree type, conversion *conv)
1662 tree t;
1664 gcc_assert (TYPE_REF_P (type));
1665 gcc_assert (!TYPE_REF_P (conv->type));
1667 t = TREE_TYPE (type);
1669 if (conv->kind == ck_identity)
1670 /* Mark the identity conv as to not decay to rvalue. */
1671 conv->rvaluedness_matches_p = true;
1673 /* [over.ics.rank]
1675 When a parameter of reference type binds directly
1676 (_dcl.init.ref_) to an argument expression, the implicit
1677 conversion sequence is the identity conversion, unless the
1678 argument expression has a type that is a derived class of the
1679 parameter type, in which case the implicit conversion sequence is
1680 a derived-to-base Conversion.
1682 If the parameter binds directly to the result of applying a
1683 conversion function to the argument expression, the implicit
1684 conversion sequence is a user-defined conversion sequence
1685 (_over.ics.user_), with the second standard conversion sequence
1686 either an identity conversion or, if the conversion function
1687 returns an entity of a type that is a derived class of the
1688 parameter type, a derived-to-base conversion. */
1689 if (is_properly_derived_from (conv->type, t))
1691 /* Represent the derived-to-base conversion. */
1692 conv = build_conv (ck_base, t, conv);
1693 /* We will actually be binding to the base-class subobject in
1694 the derived class, so we mark this conversion appropriately.
1695 That way, convert_like knows not to generate a temporary. */
1696 conv->need_temporary_p = false;
1698 else if (involves_qualification_conversion_p (t, conv->type))
1699 /* Represent the qualification conversion. After DR 2352
1700 #1 and #2 were indistinguishable conversion sequences:
1702 void f(int*); // #1
1703 void f(const int* const &); // #2
1704 void g(int* p) { f(p); }
1706 because the types "int *" and "const int *const" are
1707 reference-related and we were binding both directly and they
1708 had the same rank. To break it up, we add a ck_qual under the
1709 ck_ref_bind so that conversion sequence ranking chooses #1.
1711 We strip_top_quals here which is also what standard_conversion
1712 does. Failure to do so would confuse comp_cv_qual_signature
1713 into thinking that in
1715 void f(const int * const &); // #1
1716 void f(const int *); // #2
1717 int *x;
1718 f(x);
1720 #2 is a better match than #1 even though they're ambiguous (97296). */
1721 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1723 return build_conv (ck_ref_bind, type, conv);
1726 /* Returns the conversion path from type FROM to reference type TO for
1727 purposes of reference binding. For lvalue binding, either pass a
1728 reference type to FROM or an lvalue expression to EXPR. If the
1729 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1730 the conversion returned. If C_CAST_P is true, this
1731 conversion is coming from a C-style cast. */
1733 static conversion *
1734 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1735 tsubst_flags_t complain)
1737 conversion *conv = NULL;
1738 tree to = TREE_TYPE (rto);
1739 tree from = rfrom;
1740 tree tfrom;
1741 bool related_p;
1742 bool compatible_p;
1743 cp_lvalue_kind gl_kind;
1744 bool is_lvalue;
1746 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1748 expr = instantiate_type (to, expr, tf_none);
1749 if (expr == error_mark_node)
1750 return NULL;
1751 from = TREE_TYPE (expr);
1754 bool copy_list_init = false;
1755 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1757 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1758 /* DR 1288: Otherwise, if the initializer list has a single element
1759 of type E and ... [T's] referenced type is reference-related to E,
1760 the object or reference is initialized from that element...
1762 ??? With P0388R4, we should bind 't' directly to U{}:
1763 using U = A[2];
1764 A (&&t)[] = {U{}};
1765 because A[] and A[2] are reference-related. But we don't do it
1766 because grok_reference_init has deduced the array size (to 1), and
1767 A[1] and A[2] aren't reference-related. */
1768 if (CONSTRUCTOR_NELTS (expr) == 1
1769 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1771 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1772 if (error_operand_p (elt))
1773 return NULL;
1774 tree etype = TREE_TYPE (elt);
1775 if (reference_related_p (to, etype))
1777 expr = elt;
1778 from = etype;
1779 goto skip;
1782 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1783 referenced by T is copy-list-initialized, and the reference is bound
1784 to that temporary. */
1785 copy_list_init = true;
1786 skip:;
1789 if (TYPE_REF_P (from))
1791 from = TREE_TYPE (from);
1792 if (!TYPE_REF_IS_RVALUE (rfrom)
1793 || TREE_CODE (from) == FUNCTION_TYPE)
1794 gl_kind = clk_ordinary;
1795 else
1796 gl_kind = clk_rvalueref;
1798 else if (expr)
1799 gl_kind = lvalue_kind (expr);
1800 else if (CLASS_TYPE_P (from)
1801 || TREE_CODE (from) == ARRAY_TYPE)
1802 gl_kind = clk_class;
1803 else
1804 gl_kind = clk_none;
1806 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1807 if ((flags & LOOKUP_NO_TEMP_BIND)
1808 && (gl_kind & clk_class))
1809 gl_kind = clk_none;
1811 /* Same mask as real_lvalue_p. */
1812 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1814 tfrom = from;
1815 if ((gl_kind & clk_bitfield) != 0)
1816 tfrom = unlowered_expr_type (expr);
1818 /* Figure out whether or not the types are reference-related and
1819 reference compatible. We have to do this after stripping
1820 references from FROM. */
1821 related_p = reference_related_p (to, tfrom);
1822 /* If this is a C cast, first convert to an appropriately qualified
1823 type, so that we can later do a const_cast to the desired type. */
1824 if (related_p && c_cast_p
1825 && !at_least_as_qualified_p (to, tfrom))
1826 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1827 compatible_p = reference_compatible_p (to, tfrom);
1829 /* Directly bind reference when target expression's type is compatible with
1830 the reference and expression is an lvalue. In DR391, the wording in
1831 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1832 const and rvalue references to rvalues of compatible class type.
1833 We should also do direct bindings for non-class xvalues. */
1834 if ((related_p || compatible_p) && gl_kind)
1836 /* [dcl.init.ref]
1838 If the initializer expression
1840 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1841 is reference-compatible with "cv2 T2,"
1843 the reference is bound directly to the initializer expression
1844 lvalue.
1846 [...]
1847 If the initializer expression is an rvalue, with T2 a class type,
1848 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1849 is bound to the object represented by the rvalue or to a sub-object
1850 within that object. */
1852 conv = build_identity_conv (tfrom, expr);
1853 conv = direct_reference_binding (rto, conv);
1855 if (TYPE_REF_P (rfrom))
1856 /* Handle rvalue reference to function properly. */
1857 conv->rvaluedness_matches_p
1858 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1859 else
1860 conv->rvaluedness_matches_p
1861 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1863 if ((gl_kind & clk_bitfield) != 0
1864 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1865 /* For the purposes of overload resolution, we ignore the fact
1866 this expression is a bitfield or packed field. (In particular,
1867 [over.ics.ref] says specifically that a function with a
1868 non-const reference parameter is viable even if the
1869 argument is a bitfield.)
1871 However, when we actually call the function we must create
1872 a temporary to which to bind the reference. If the
1873 reference is volatile, or isn't const, then we cannot make
1874 a temporary, so we just issue an error when the conversion
1875 actually occurs. */
1876 conv->need_temporary_p = true;
1878 /* Don't allow binding of lvalues (other than function lvalues) to
1879 rvalue references. */
1880 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1881 && TREE_CODE (to) != FUNCTION_TYPE)
1882 conv->bad_p = true;
1884 /* Nor the reverse. */
1885 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1886 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1887 But in C++23, such an expression is just an xvalue, not a special
1888 lvalue, so the binding is once again ill-formed. */
1889 && !(cxx_dialect <= cxx20
1890 && (gl_kind & clk_implicit_rval))
1891 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1892 || (flags & LOOKUP_NO_RVAL_BIND))
1893 && TREE_CODE (to) != FUNCTION_TYPE)
1894 conv->bad_p = true;
1896 if (!compatible_p)
1897 conv->bad_p = true;
1899 return conv;
1901 /* [class.conv.fct] A conversion function is never used to convert a
1902 (possibly cv-qualified) object to the (possibly cv-qualified) same
1903 object type (or a reference to it), to a (possibly cv-qualified) base
1904 class of that type (or a reference to it).... */
1905 else if (CLASS_TYPE_P (from) && !related_p
1906 && !(flags & LOOKUP_NO_CONVERSION))
1908 /* [dcl.init.ref]
1910 If the initializer expression
1912 -- has a class type (i.e., T2 is a class type) can be
1913 implicitly converted to an lvalue of type "cv3 T3," where
1914 "cv1 T1" is reference-compatible with "cv3 T3". (this
1915 conversion is selected by enumerating the applicable
1916 conversion functions (_over.match.ref_) and choosing the
1917 best one through overload resolution. (_over.match_).
1919 the reference is bound to the lvalue result of the conversion
1920 in the second case. */
1921 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1922 complain);
1923 if (cand)
1924 return cand->second_conv;
1927 /* From this point on, we conceptually need temporaries, even if we
1928 elide them. Only the cases above are "direct bindings". */
1929 if (flags & LOOKUP_NO_TEMP_BIND)
1930 return NULL;
1932 /* [over.ics.rank]
1934 When a parameter of reference type is not bound directly to an
1935 argument expression, the conversion sequence is the one required
1936 to convert the argument expression to the underlying type of the
1937 reference according to _over.best.ics_. Conceptually, this
1938 conversion sequence corresponds to copy-initializing a temporary
1939 of the underlying type with the argument expression. Any
1940 difference in top-level cv-qualification is subsumed by the
1941 initialization itself and does not constitute a conversion. */
1943 bool maybe_valid_p = true;
1945 /* [dcl.init.ref]
1947 Otherwise, the reference shall be an lvalue reference to a
1948 non-volatile const type, or the reference shall be an rvalue
1949 reference. */
1950 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1951 maybe_valid_p = false;
1953 /* [dcl.init.ref]
1955 Otherwise, a temporary of type "cv1 T1" is created and
1956 initialized from the initializer expression using the rules for a
1957 non-reference copy initialization. If T1 is reference-related to
1958 T2, cv1 must be the same cv-qualification as, or greater
1959 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1960 if (related_p && !at_least_as_qualified_p (to, from))
1961 maybe_valid_p = false;
1963 /* We try below to treat an invalid reference binding as a bad conversion
1964 to improve diagnostics, but doing so may cause otherwise unnecessary
1965 instantiations that can lead to a hard error. So during the first pass
1966 of overload resolution wherein we shortcut bad conversions, instead just
1967 produce a special conversion indicating a second pass is necessary if
1968 there's no strictly viable candidate. */
1969 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1971 conv = alloc_conversion (ck_deferred_bad);
1972 conv->bad_p = true;
1973 return conv;
1976 /* We're generating a temporary now, but don't bind any more in the
1977 conversion (specifically, don't slice the temporary returned by a
1978 conversion operator). */
1979 flags |= LOOKUP_NO_TEMP_BIND;
1981 /* Core issue 899: When [copy-]initializing a temporary to be bound
1982 to the first parameter of a copy constructor (12.8) called with
1983 a single argument in the context of direct-initialization,
1984 explicit conversion functions are also considered.
1986 So don't set LOOKUP_ONLYCONVERTING in that case. */
1987 if (!(flags & LOOKUP_COPY_PARM))
1988 flags |= LOOKUP_ONLYCONVERTING;
1990 if (!conv)
1991 conv = implicit_conversion (to, from, expr, c_cast_p,
1992 flags, complain);
1993 if (!conv)
1994 return NULL;
1996 if (conv->user_conv_p)
1998 if (copy_list_init)
1999 /* Remember this was copy-list-initialization. */
2000 conv->need_temporary_p = true;
2002 /* If initializing the temporary used a conversion function,
2003 recalculate the second conversion sequence. */
2004 for (conversion *t = conv; t; t = next_conversion (t))
2005 if (t->kind == ck_user
2006 && DECL_CONV_FN_P (t->cand->fn))
2008 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2009 /* A prvalue of non-class type is cv-unqualified. */
2010 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2011 ftype = cv_unqualified (ftype);
2012 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2013 conversion *new_second
2014 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2015 sflags, complain);
2016 if (!new_second)
2017 return NULL;
2018 conv = merge_conversion_sequences (t, new_second);
2019 gcc_assert (maybe_valid_p || conv->bad_p);
2020 return conv;
2024 conv = build_conv (ck_ref_bind, rto, conv);
2025 /* This reference binding, unlike those above, requires the
2026 creation of a temporary. */
2027 conv->need_temporary_p = true;
2028 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2029 conv->bad_p |= !maybe_valid_p;
2031 return conv;
2034 /* Most of the implementation of implicit_conversion, with the same
2035 parameters. */
2037 static conversion *
2038 implicit_conversion_1 (tree to, tree from, tree expr, bool c_cast_p,
2039 int flags, tsubst_flags_t complain)
2041 conversion *conv;
2043 if (from == error_mark_node || to == error_mark_node
2044 || expr == error_mark_node)
2045 return NULL;
2047 /* Other flags only apply to the primary function in overload
2048 resolution, or after we've chosen one. */
2049 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2050 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2051 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2053 /* FIXME: actually we don't want warnings either, but we can't just
2054 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2055 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2056 We really ought not to issue that warning until we've committed
2057 to that conversion. */
2058 complain &= ~tf_error;
2060 /* Call reshape_init early to remove redundant braces. */
2061 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr)
2062 && CLASS_TYPE_P (to)
2063 && COMPLETE_TYPE_P (complete_type (to))
2064 && !CLASSTYPE_NON_AGGREGATE (to))
2066 expr = reshape_init (to, expr, complain);
2067 if (expr == error_mark_node)
2068 return NULL;
2069 from = TREE_TYPE (expr);
2072 if (TYPE_REF_P (to))
2073 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2074 else
2075 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2077 if (conv)
2078 return conv;
2080 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2082 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2083 return build_list_conv (to, expr, flags, complain);
2085 /* As an extension, allow list-initialization of _Complex. */
2086 if (TREE_CODE (to) == COMPLEX_TYPE
2087 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2089 conv = build_complex_conv (to, expr, flags, complain);
2090 if (conv)
2091 return conv;
2094 /* Allow conversion from an initializer-list with one element to a
2095 scalar type. */
2096 if (SCALAR_TYPE_P (to))
2098 int nelts = CONSTRUCTOR_NELTS (expr);
2099 tree elt;
2101 if (nelts == 0)
2102 elt = build_value_init (to, tf_none);
2103 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2104 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2105 else
2106 elt = error_mark_node;
2108 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2109 c_cast_p, flags, complain);
2110 if (conv)
2112 conv->check_narrowing = true;
2113 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2114 /* Too many levels of braces, i.e. '{{1}}'. */
2115 conv->bad_p = true;
2116 return conv;
2119 else if (TREE_CODE (to) == ARRAY_TYPE)
2120 return build_array_conv (to, expr, flags, complain);
2123 if (expr != NULL_TREE
2124 && (MAYBE_CLASS_TYPE_P (from)
2125 || MAYBE_CLASS_TYPE_P (to))
2126 && (flags & LOOKUP_NO_CONVERSION) == 0)
2128 struct z_candidate *cand;
2130 if (CLASS_TYPE_P (to)
2131 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2132 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2133 return build_aggr_conv (to, expr, flags, complain);
2135 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2136 if (cand)
2138 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2139 && CONSTRUCTOR_NELTS (expr) == 1
2140 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2141 && !is_list_ctor (cand->fn))
2143 /* "If C is not an initializer-list constructor and the
2144 initializer list has a single element of type cv U, where U is
2145 X or a class derived from X, the implicit conversion sequence
2146 has Exact Match rank if U is X, or Conversion rank if U is
2147 derived from X." */
2148 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2149 tree elttype = TREE_TYPE (elt);
2150 if (reference_related_p (to, elttype))
2151 return implicit_conversion (to, elttype, elt,
2152 c_cast_p, flags, complain);
2154 conv = cand->second_conv;
2157 /* We used to try to bind a reference to a temporary here, but that
2158 is now handled after the recursive call to this function at the end
2159 of reference_binding. */
2160 return conv;
2163 return NULL;
2166 /* Returns the implicit conversion sequence (see [over.ics]) from type
2167 FROM to type TO. The optional expression EXPR may affect the
2168 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2169 true, this conversion is coming from a C-style cast. */
2171 static conversion *
2172 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2173 int flags, tsubst_flags_t complain)
2175 conversion *conv = implicit_conversion_1 (to, from, expr, c_cast_p,
2176 flags, complain);
2177 if (!conv || conv->bad_p)
2178 return conv;
2179 if (conv_is_prvalue (conv)
2180 && CLASS_TYPE_P (conv->type)
2181 && CLASSTYPE_PURE_VIRTUALS (conv->type))
2182 conv->bad_p = true;
2183 return conv;
2186 /* Like implicit_conversion, but return NULL if the conversion is bad.
2188 This is not static so that check_non_deducible_conversion can call it within
2189 add_template_candidate_real as part of overload resolution; it should not be
2190 called outside of overload resolution. */
2192 conversion *
2193 good_conversion (tree to, tree from, tree expr,
2194 int flags, tsubst_flags_t complain)
2196 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2197 flags, complain);
2198 if (c && c->bad_p)
2199 c = NULL;
2200 return c;
2203 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2204 functions. ARGS will not be changed until a single candidate is
2205 selected. */
2207 static struct z_candidate *
2208 add_candidate (struct z_candidate **candidates,
2209 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2210 size_t num_convs, conversion **convs,
2211 tree access_path, tree conversion_path,
2212 int viable, struct rejection_reason *reason,
2213 int flags)
2215 struct z_candidate *cand = (struct z_candidate *)
2216 conversion_obstack_alloc (sizeof (struct z_candidate));
2218 cand->fn = fn;
2219 cand->first_arg = first_arg;
2220 cand->args = args;
2221 cand->convs = convs;
2222 cand->num_convs = num_convs;
2223 cand->access_path = access_path;
2224 cand->conversion_path = conversion_path;
2225 cand->viable = viable;
2226 cand->reason = reason;
2227 cand->next = *candidates;
2228 cand->flags = flags;
2229 *candidates = cand;
2231 if (convs && cand->reversed ())
2232 /* Swap the conversions for comparison in joust; we'll swap them back
2233 before build_over_call. */
2234 std::swap (convs[0], convs[1]);
2236 return cand;
2239 /* Return the number of remaining arguments in the parameter list
2240 beginning with ARG. */
2243 remaining_arguments (tree arg)
2245 int n;
2247 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2248 arg = TREE_CHAIN (arg))
2249 n++;
2251 return n;
2254 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2255 to the first parameter of a constructor where the parameter is of type
2256 "reference to possibly cv-qualified T" and the constructor is called with a
2257 single argument in the context of direct-initialization of an object of type
2258 "cv2 T", explicit conversion functions are also considered.
2260 So set LOOKUP_COPY_PARM to let reference_binding know that
2261 it's being called in that context. */
2264 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2266 int lflags = flags;
2267 tree t;
2268 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2269 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2270 && (same_type_ignoring_top_level_qualifiers_p
2271 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2273 if (!(flags & LOOKUP_ONLYCONVERTING))
2274 lflags |= LOOKUP_COPY_PARM;
2275 if ((flags & LOOKUP_LIST_INIT_CTOR)
2276 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2277 lflags |= LOOKUP_NO_CONVERSION;
2279 else
2280 lflags |= LOOKUP_ONLYCONVERTING;
2282 return lflags;
2285 /* Build an appropriate 'this' conversion for the method FN and class
2286 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2287 This function modifies PARMTYPE, ARGTYPE and ARG. */
2289 static conversion *
2290 build_this_conversion (tree fn, tree ctype,
2291 tree& parmtype, tree& argtype, tree& arg,
2292 int flags, tsubst_flags_t complain)
2294 gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2295 && !DECL_CONSTRUCTOR_P (fn));
2297 /* The type of the implicit object parameter ('this') for
2298 overload resolution is not always the same as for the
2299 function itself; conversion functions are considered to
2300 be members of the class being converted, and functions
2301 introduced by a using-declaration are considered to be
2302 members of the class that uses them.
2304 Since build_over_call ignores the ICS for the `this'
2305 parameter, we can just change the parm type. */
2306 parmtype = cp_build_qualified_type (ctype,
2307 cp_type_quals (TREE_TYPE (parmtype)));
2308 bool this_p = true;
2309 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2311 /* If the function has a ref-qualifier, the implicit
2312 object parameter has reference type. */
2313 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2314 parmtype = cp_build_reference_type (parmtype, rv);
2315 /* The special handling of 'this' conversions in compare_ics
2316 does not apply if there is a ref-qualifier. */
2317 this_p = false;
2319 else
2321 parmtype = build_pointer_type (parmtype);
2322 /* We don't use build_this here because we don't want to
2323 capture the object argument until we've chosen a
2324 non-static member function. */
2325 arg = build_address (arg);
2326 argtype = lvalue_type (arg);
2328 flags |= LOOKUP_ONLYCONVERTING;
2329 conversion *t = implicit_conversion (parmtype, argtype, arg,
2330 /*c_cast_p=*/false, flags, complain);
2331 t->this_p = this_p;
2332 return t;
2335 /* Create an overload candidate for the function or method FN called
2336 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2337 FLAGS is passed on to implicit_conversion.
2339 This does not change ARGS.
2341 CTYPE, if non-NULL, is the type we want to pretend this function
2342 comes from for purposes of overload resolution.
2344 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2345 If true, we stop computing conversions upon seeing the first bad
2346 conversion. This is used by add_candidates to avoid computing
2347 more conversions than necessary in the presence of a strictly viable
2348 candidate, while preserving the defacto behavior of overload resolution
2349 when it turns out there are only non-strictly viable candidates. */
2351 static struct z_candidate *
2352 add_function_candidate (struct z_candidate **candidates,
2353 tree fn, tree ctype, tree first_arg,
2354 const vec<tree, va_gc> *args, tree access_path,
2355 tree conversion_path, int flags,
2356 conversion **convs,
2357 bool shortcut_bad_convs,
2358 tsubst_flags_t complain)
2360 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2361 int i, len;
2362 tree parmnode;
2363 tree orig_first_arg = first_arg;
2364 int skip;
2365 int viable = 1;
2366 struct rejection_reason *reason = NULL;
2368 /* The `this', `in_chrg' and VTT arguments to constructors are not
2369 considered in overload resolution. */
2370 if (DECL_CONSTRUCTOR_P (fn))
2372 if (ctor_omit_inherited_parms (fn))
2373 /* Bring back parameters omitted from an inherited ctor. */
2374 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2375 else
2376 parmlist = skip_artificial_parms_for (fn, parmlist);
2377 skip = num_artificial_parms_for (fn);
2378 if (skip > 0 && first_arg != NULL_TREE)
2380 --skip;
2381 first_arg = NULL_TREE;
2384 else
2385 skip = 0;
2387 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2388 if (!convs)
2389 convs = alloc_conversions (len);
2391 /* 13.3.2 - Viable functions [over.match.viable]
2392 First, to be a viable function, a candidate function shall have enough
2393 parameters to agree in number with the arguments in the list.
2395 We need to check this first; otherwise, checking the ICSes might cause
2396 us to produce an ill-formed template instantiation. */
2398 parmnode = parmlist;
2399 for (i = 0; i < len; ++i)
2401 if (parmnode == NULL_TREE || parmnode == void_list_node)
2402 break;
2403 parmnode = TREE_CHAIN (parmnode);
2406 if ((i < len && parmnode)
2407 || !sufficient_parms_p (parmnode))
2409 int remaining = remaining_arguments (parmnode);
2410 viable = 0;
2411 reason = arity_rejection (first_arg, i + remaining, len);
2414 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2415 parameter of type "reference to cv C" (including such a constructor
2416 instantiated from a template) is excluded from the set of candidate
2417 functions when used to construct an object of type D with an argument list
2418 containing a single argument if C is reference-related to D. */
2419 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2420 && flag_new_inheriting_ctors
2421 && DECL_INHERITED_CTOR (fn))
2423 tree ptype = non_reference (TREE_VALUE (parmlist));
2424 tree dtype = DECL_CONTEXT (fn);
2425 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2426 if (reference_related_p (ptype, dtype)
2427 && reference_related_p (btype, ptype))
2429 viable = false;
2430 reason = inherited_ctor_rejection ();
2434 /* Second, for a function to be viable, its constraints must be
2435 satisfied. */
2436 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2438 reason = constraint_failure ();
2439 viable = false;
2442 /* When looking for a function from a subobject from an implicit
2443 copy/move constructor/operator=, don't consider anything that takes (a
2444 reference to) an unrelated type. See c++/44909 and core 1092. */
2445 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2447 if (DECL_CONSTRUCTOR_P (fn))
2448 i = 1;
2449 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2450 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2451 i = 2;
2452 else
2453 i = 0;
2454 if (i && len == i)
2456 parmnode = chain_index (i-1, parmlist);
2457 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2458 ctype))
2459 viable = 0;
2462 /* This only applies at the top level. */
2463 flags &= ~LOOKUP_DEFAULTED;
2466 if (! viable)
2467 goto out;
2469 if (shortcut_bad_convs)
2470 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2471 else
2472 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2474 /* Third, for F to be a viable function, there shall exist for each
2475 argument an implicit conversion sequence that converts that argument
2476 to the corresponding parameter of F. */
2478 parmnode = parmlist;
2480 for (i = 0; i < len; ++i)
2482 tree argtype, to_type;
2483 tree arg;
2485 if (parmnode == void_list_node)
2486 break;
2488 if (convs[i])
2490 /* Already set during deduction. */
2491 parmnode = TREE_CHAIN (parmnode);
2492 continue;
2495 if (i == 0 && first_arg != NULL_TREE)
2496 arg = first_arg;
2497 else
2498 arg = CONST_CAST_TREE (
2499 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2500 argtype = lvalue_type (arg);
2502 conversion *t;
2503 if (parmnode)
2505 tree parmtype = TREE_VALUE (parmnode);
2506 if (i == 0
2507 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2508 && !DECL_CONSTRUCTOR_P (fn))
2509 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2510 flags, complain);
2511 else
2513 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2514 t = implicit_conversion (parmtype, argtype, arg,
2515 /*c_cast_p=*/false, lflags, complain);
2517 to_type = parmtype;
2518 parmnode = TREE_CHAIN (parmnode);
2520 else
2522 t = build_identity_conv (argtype, arg);
2523 t->ellipsis_p = true;
2524 to_type = argtype;
2527 convs[i] = t;
2528 if (! t)
2530 viable = 0;
2531 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2532 EXPR_LOCATION (arg));
2533 break;
2536 if (t->bad_p)
2538 viable = -1;
2539 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2540 EXPR_LOCATION (arg));
2541 if (shortcut_bad_convs)
2542 break;
2546 out:
2547 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2548 access_path, conversion_path, viable, reason, flags);
2551 /* Create an overload candidate for the conversion function FN which will
2552 be invoked for expression OBJ, producing a pointer-to-function which
2553 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2554 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2555 passed on to implicit_conversion.
2557 Actually, we don't really care about FN; we care about the type it
2558 converts to. There may be multiple conversion functions that will
2559 convert to that type, and we rely on build_user_type_conversion_1 to
2560 choose the best one; so when we create our candidate, we record the type
2561 instead of the function. */
2563 static struct z_candidate *
2564 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2565 const vec<tree, va_gc> *arglist,
2566 tree access_path, tree conversion_path,
2567 tsubst_flags_t complain)
2569 tree totype = TREE_TYPE (TREE_TYPE (fn));
2570 int i, len, viable, flags;
2571 tree parmlist, parmnode;
2572 conversion **convs;
2573 struct rejection_reason *reason;
2575 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2576 parmlist = TREE_TYPE (parmlist);
2577 parmlist = TYPE_ARG_TYPES (parmlist);
2579 len = vec_safe_length (arglist) + 1;
2580 convs = alloc_conversions (len);
2581 parmnode = parmlist;
2582 viable = 1;
2583 flags = LOOKUP_IMPLICIT;
2584 reason = NULL;
2586 /* Don't bother looking up the same type twice. */
2587 if (*candidates && (*candidates)->fn == totype)
2588 return NULL;
2590 for (i = 0; i < len; ++i)
2592 tree arg, argtype, convert_type = NULL_TREE;
2593 conversion *t;
2595 if (i == 0)
2596 arg = obj;
2597 else
2598 arg = (*arglist)[i - 1];
2599 argtype = lvalue_type (arg);
2601 if (i == 0)
2603 t = build_identity_conv (argtype, NULL_TREE);
2604 t = build_conv (ck_user, totype, t);
2605 /* Leave the 'cand' field null; we'll figure out the conversion in
2606 convert_like if this candidate is chosen. */
2607 convert_type = totype;
2609 else if (parmnode == void_list_node)
2610 break;
2611 else if (parmnode)
2613 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2614 /*c_cast_p=*/false, flags, complain);
2615 convert_type = TREE_VALUE (parmnode);
2617 else
2619 t = build_identity_conv (argtype, arg);
2620 t->ellipsis_p = true;
2621 convert_type = argtype;
2624 convs[i] = t;
2625 if (! t)
2626 break;
2628 if (t->bad_p)
2630 viable = -1;
2631 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2632 EXPR_LOCATION (arg));
2635 if (i == 0)
2636 continue;
2638 if (parmnode)
2639 parmnode = TREE_CHAIN (parmnode);
2642 if (i < len
2643 || ! sufficient_parms_p (parmnode))
2645 int remaining = remaining_arguments (parmnode);
2646 viable = 0;
2647 reason = arity_rejection (NULL_TREE, i + remaining, len);
2650 return add_candidate (candidates, totype, obj, arglist, len, convs,
2651 access_path, conversion_path, viable, reason, flags);
2654 static void
2655 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2656 tree type1, tree type2, const vec<tree,va_gc> &args,
2657 tree *argtypes, int flags, tsubst_flags_t complain)
2659 conversion *t;
2660 conversion **convs;
2661 size_t num_convs;
2662 int viable = 1;
2663 tree types[2];
2664 struct rejection_reason *reason = NULL;
2666 types[0] = type1;
2667 types[1] = type2;
2669 num_convs = args.length ();
2670 convs = alloc_conversions (num_convs);
2672 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2673 conversion ops are allowed. We handle that here by just checking for
2674 boolean_type_node because other operators don't ask for it. COND_EXPR
2675 also does contextual conversion to bool for the first operand, but we
2676 handle that in build_conditional_expr, and type1 here is operand 2. */
2677 if (type1 != boolean_type_node)
2678 flags |= LOOKUP_ONLYCONVERTING;
2680 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2682 t = implicit_conversion (types[i], argtypes[i], args[i],
2683 /*c_cast_p=*/false, flags, complain);
2684 if (! t)
2686 viable = 0;
2687 /* We need something for printing the candidate. */
2688 t = build_identity_conv (types[i], NULL_TREE);
2689 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2690 types[i], EXPR_LOCATION (args[i]));
2692 else if (t->bad_p)
2694 viable = 0;
2695 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2696 types[i],
2697 EXPR_LOCATION (args[i]));
2699 convs[i] = t;
2702 /* For COND_EXPR we rearranged the arguments; undo that now. */
2703 if (num_convs == 3)
2705 convs[2] = convs[1];
2706 convs[1] = convs[0];
2707 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2708 /*c_cast_p=*/false, flags,
2709 complain);
2710 if (t)
2711 convs[0] = t;
2712 else
2714 viable = 0;
2715 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2716 boolean_type_node,
2717 EXPR_LOCATION (args[2]));
2721 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2722 num_convs, convs,
2723 /*access_path=*/NULL_TREE,
2724 /*conversion_path=*/NULL_TREE,
2725 viable, reason, flags);
2728 static bool
2729 is_complete (tree t)
2731 return COMPLETE_TYPE_P (complete_type (t));
2734 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2736 static bool
2737 promoted_arithmetic_type_p (tree type)
2739 /* [over.built]
2741 In this section, the term promoted integral type is used to refer
2742 to those integral types which are preserved by integral promotion
2743 (including e.g. int and long but excluding e.g. char).
2744 Similarly, the term promoted arithmetic type refers to promoted
2745 integral types plus floating types. */
2746 return ((CP_INTEGRAL_TYPE_P (type)
2747 && same_type_p (type_promotes_to (type), type))
2748 || TREE_CODE (type) == REAL_TYPE);
2751 /* Create any builtin operator overload candidates for the operator in
2752 question given the converted operand types TYPE1 and TYPE2. The other
2753 args are passed through from add_builtin_candidates to
2754 build_builtin_candidate.
2756 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2757 If CODE is requires candidates operands of the same type of the kind
2758 of which TYPE1 and TYPE2 are, we add both candidates
2759 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2761 static void
2762 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2763 enum tree_code code2, tree fnname, tree type1,
2764 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2765 int flags, tsubst_flags_t complain)
2767 switch (code)
2769 case POSTINCREMENT_EXPR:
2770 case POSTDECREMENT_EXPR:
2771 args[1] = integer_zero_node;
2772 type2 = integer_type_node;
2773 break;
2774 default:
2775 break;
2778 switch (code)
2781 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2782 and VQ is either volatile or empty, there exist candidate operator
2783 functions of the form
2784 VQ T& operator++(VQ T&);
2785 T operator++(VQ T&, int);
2786 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2787 and VQ is either volatile or empty, there exist candidate operator
2788 functions of the form
2789 VQ T& operator--(VQ T&);
2790 T operator--(VQ T&, int);
2791 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2792 type, and VQ is either volatile or empty, there exist candidate operator
2793 functions of the form
2794 T*VQ& operator++(T*VQ&);
2795 T*VQ& operator--(T*VQ&);
2796 T* operator++(T*VQ&, int);
2797 T* operator--(T*VQ&, int); */
2799 case POSTDECREMENT_EXPR:
2800 case PREDECREMENT_EXPR:
2801 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2802 return;
2803 /* FALLTHRU */
2804 case POSTINCREMENT_EXPR:
2805 case PREINCREMENT_EXPR:
2806 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2807 to p4. */
2808 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2809 return;
2810 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2812 type1 = build_reference_type (type1);
2813 break;
2815 return;
2817 /* 7 For every cv-qualified or cv-unqualified object type T, there
2818 exist candidate operator functions of the form
2820 T& operator*(T*);
2823 8 For every function type T that does not have cv-qualifiers or
2824 a ref-qualifier, there exist candidate operator functions of the form
2825 T& operator*(T*); */
2827 case INDIRECT_REF:
2828 if (TYPE_PTR_P (type1)
2829 && (TYPE_PTROB_P (type1)
2830 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2831 break;
2832 return;
2834 /* 9 For every type T, there exist candidate operator functions of the form
2835 T* operator+(T*);
2837 10 For every floating-point or promoted integral type T, there exist
2838 candidate operator functions of the form
2839 T operator+(T);
2840 T operator-(T); */
2842 case UNARY_PLUS_EXPR: /* unary + */
2843 if (TYPE_PTR_P (type1))
2844 break;
2845 /* FALLTHRU */
2846 case NEGATE_EXPR:
2847 if (ARITHMETIC_TYPE_P (type1))
2848 break;
2849 return;
2851 /* 11 For every promoted integral type T, there exist candidate operator
2852 functions of the form
2853 T operator~(T); */
2855 case BIT_NOT_EXPR:
2856 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2857 break;
2858 return;
2860 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2861 is the same type as C2 or is a derived class of C2, and T is an object
2862 type or a function type there exist candidate operator functions of the
2863 form
2864 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2865 where CV12 is the union of CV1 and CV2. */
2867 case MEMBER_REF:
2868 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2870 tree c1 = TREE_TYPE (type1);
2871 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2873 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2874 && (TYPE_PTRMEMFUNC_P (type2)
2875 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2876 break;
2878 return;
2880 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2881 or promoted integral type, there exist candidate operator functions of the
2882 form
2883 LR operator*(L, R);
2884 LR operator/(L, R);
2885 LR operator+(L, R);
2886 LR operator-(L, R);
2887 bool operator<(L, R);
2888 bool operator>(L, R);
2889 bool operator<=(L, R);
2890 bool operator>=(L, R);
2891 bool operator==(L, R);
2892 bool operator!=(L, R);
2893 where LR is the result of the usual arithmetic conversions between
2894 types L and R.
2896 14 For every integral type T there exists a candidate operator function of
2897 the form
2899 std::strong_ordering operator<=>(T, T);
2901 15 For every pair of floating-point types L and R, there exists a candidate
2902 operator function of the form
2904 std::partial_ordering operator<=>(L, R);
2906 16 For every cv-qualified or cv-unqualified object type T there exist
2907 candidate operator functions of the form
2908 T* operator+(T*, std::ptrdiff_t);
2909 T& operator[](T*, std::ptrdiff_t);
2910 T* operator-(T*, std::ptrdiff_t);
2911 T* operator+(std::ptrdiff_t, T*);
2912 T& operator[](std::ptrdiff_t, T*);
2914 17 For every T, where T is a pointer to object type, there exist candidate
2915 operator functions of the form
2916 std::ptrdiff_t operator-(T, T);
2918 18 For every T, where T is an enumeration type or a pointer type, there
2919 exist candidate operator functions of the form
2920 bool operator<(T, T);
2921 bool operator>(T, T);
2922 bool operator<=(T, T);
2923 bool operator>=(T, T);
2924 bool operator==(T, T);
2925 bool operator!=(T, T);
2926 R operator<=>(T, T);
2928 where R is the result type specified in [expr.spaceship].
2930 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2931 there exist candidate operator functions of the form
2932 bool operator==(T, T);
2933 bool operator!=(T, T); */
2935 case MINUS_EXPR:
2936 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2937 break;
2938 if (TYPE_PTROB_P (type1)
2939 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2941 type2 = ptrdiff_type_node;
2942 break;
2944 /* FALLTHRU */
2945 case MULT_EXPR:
2946 case TRUNC_DIV_EXPR:
2947 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2948 break;
2949 return;
2951 /* This isn't exactly what's specified above for operator<=>, but it's
2952 close enough. In particular, we don't care about the return type
2953 specified above; it doesn't participate in overload resolution and it
2954 doesn't affect the semantics of the built-in operator. */
2955 case SPACESHIP_EXPR:
2956 case EQ_EXPR:
2957 case NE_EXPR:
2958 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2959 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2960 break;
2961 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2962 break;
2963 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2965 type2 = type1;
2966 break;
2968 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2970 type1 = type2;
2971 break;
2973 /* Fall through. */
2974 case LT_EXPR:
2975 case GT_EXPR:
2976 case LE_EXPR:
2977 case GE_EXPR:
2978 case MAX_EXPR:
2979 case MIN_EXPR:
2980 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2981 break;
2982 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2983 break;
2984 if (TREE_CODE (type1) == ENUMERAL_TYPE
2985 && TREE_CODE (type2) == ENUMERAL_TYPE)
2986 break;
2987 if (TYPE_PTR_P (type1)
2988 && null_ptr_cst_p (args[1]))
2990 type2 = type1;
2991 break;
2993 if (null_ptr_cst_p (args[0])
2994 && TYPE_PTR_P (type2))
2996 type1 = type2;
2997 break;
2999 return;
3001 case PLUS_EXPR:
3002 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3003 break;
3004 /* FALLTHRU */
3005 case ARRAY_REF:
3006 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3008 type1 = ptrdiff_type_node;
3009 break;
3011 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3013 type2 = ptrdiff_type_node;
3014 break;
3016 return;
3018 /* 18For every pair of promoted integral types L and R, there exist candi-
3019 date operator functions of the form
3020 LR operator%(L, R);
3021 LR operator&(L, R);
3022 LR operator^(L, R);
3023 LR operator|(L, R);
3024 L operator<<(L, R);
3025 L operator>>(L, R);
3026 where LR is the result of the usual arithmetic conversions between
3027 types L and R. */
3029 case TRUNC_MOD_EXPR:
3030 case BIT_AND_EXPR:
3031 case BIT_IOR_EXPR:
3032 case BIT_XOR_EXPR:
3033 case LSHIFT_EXPR:
3034 case RSHIFT_EXPR:
3035 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3036 break;
3037 return;
3039 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3040 type, VQ is either volatile or empty, and R is a promoted arithmetic
3041 type, there exist candidate operator functions of the form
3042 VQ L& operator=(VQ L&, R);
3043 VQ L& operator*=(VQ L&, R);
3044 VQ L& operator/=(VQ L&, R);
3045 VQ L& operator+=(VQ L&, R);
3046 VQ L& operator-=(VQ L&, R);
3048 20For every pair T, VQ), where T is any type and VQ is either volatile
3049 or empty, there exist candidate operator functions of the form
3050 T*VQ& operator=(T*VQ&, T*);
3052 21For every pair T, VQ), where T is a pointer to member type and VQ is
3053 either volatile or empty, there exist candidate operator functions of
3054 the form
3055 VQ T& operator=(VQ T&, T);
3057 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3058 unqualified complete object type, VQ is either volatile or empty, and
3059 I is a promoted integral type, there exist candidate operator func-
3060 tions of the form
3061 T*VQ& operator+=(T*VQ&, I);
3062 T*VQ& operator-=(T*VQ&, I);
3064 23For every triple L, VQ, R), where L is an integral or enumeration
3065 type, VQ is either volatile or empty, and R is a promoted integral
3066 type, there exist candidate operator functions of the form
3068 VQ L& operator%=(VQ L&, R);
3069 VQ L& operator<<=(VQ L&, R);
3070 VQ L& operator>>=(VQ L&, R);
3071 VQ L& operator&=(VQ L&, R);
3072 VQ L& operator^=(VQ L&, R);
3073 VQ L& operator|=(VQ L&, R); */
3075 case MODIFY_EXPR:
3076 switch (code2)
3078 case PLUS_EXPR:
3079 case MINUS_EXPR:
3080 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3082 type2 = ptrdiff_type_node;
3083 break;
3085 /* FALLTHRU */
3086 case MULT_EXPR:
3087 case TRUNC_DIV_EXPR:
3088 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3089 break;
3090 return;
3092 case TRUNC_MOD_EXPR:
3093 case BIT_AND_EXPR:
3094 case BIT_IOR_EXPR:
3095 case BIT_XOR_EXPR:
3096 case LSHIFT_EXPR:
3097 case RSHIFT_EXPR:
3098 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3099 break;
3100 return;
3102 case NOP_EXPR:
3103 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3104 break;
3105 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3106 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3107 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3108 || ((TYPE_PTRMEMFUNC_P (type1)
3109 || TYPE_PTR_P (type1))
3110 && null_ptr_cst_p (args[1])))
3112 type2 = type1;
3113 break;
3115 return;
3117 default:
3118 gcc_unreachable ();
3120 type1 = build_reference_type (type1);
3121 break;
3123 case COND_EXPR:
3124 /* [over.built]
3126 For every pair of promoted arithmetic types L and R, there
3127 exist candidate operator functions of the form
3129 LR operator?(bool, L, R);
3131 where LR is the result of the usual arithmetic conversions
3132 between types L and R.
3134 For every type T, where T is a pointer or pointer-to-member
3135 type, there exist candidate operator functions of the form T
3136 operator?(bool, T, T); */
3138 if (promoted_arithmetic_type_p (type1)
3139 && promoted_arithmetic_type_p (type2))
3140 /* That's OK. */
3141 break;
3143 /* Otherwise, the types should be pointers. */
3144 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3145 return;
3147 /* We don't check that the two types are the same; the logic
3148 below will actually create two candidates; one in which both
3149 parameter types are TYPE1, and one in which both parameter
3150 types are TYPE2. */
3151 break;
3153 case REALPART_EXPR:
3154 case IMAGPART_EXPR:
3155 if (ARITHMETIC_TYPE_P (type1))
3156 break;
3157 return;
3159 default:
3160 gcc_unreachable ();
3163 /* Make sure we don't create builtin candidates with dependent types. */
3164 bool u1 = uses_template_parms (type1);
3165 bool u2 = type2 ? uses_template_parms (type2) : false;
3166 if (u1 || u2)
3168 /* Try to recover if one of the types is non-dependent. But if
3169 there's only one type, there's nothing we can do. */
3170 if (!type2)
3171 return;
3172 /* And we lose if both are dependent. */
3173 if (u1 && u2)
3174 return;
3175 /* Or if they have different forms. */
3176 if (TREE_CODE (type1) != TREE_CODE (type2))
3177 return;
3179 if (u1 && !u2)
3180 type1 = type2;
3181 else if (u2 && !u1)
3182 type2 = type1;
3185 /* If we're dealing with two pointer types or two enumeral types,
3186 we need candidates for both of them. */
3187 if (type2 && !same_type_p (type1, type2)
3188 && TREE_CODE (type1) == TREE_CODE (type2)
3189 && (TYPE_REF_P (type1)
3190 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3191 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3192 || TYPE_PTRMEMFUNC_P (type1)
3193 || MAYBE_CLASS_TYPE_P (type1)
3194 || TREE_CODE (type1) == ENUMERAL_TYPE))
3196 if (TYPE_PTR_OR_PTRMEM_P (type1))
3198 tree cptype = composite_pointer_type (input_location,
3199 type1, type2,
3200 error_mark_node,
3201 error_mark_node,
3202 CPO_CONVERSION,
3203 tf_none);
3204 if (cptype != error_mark_node)
3206 build_builtin_candidate
3207 (candidates, fnname, cptype, cptype, args, argtypes,
3208 flags, complain);
3209 return;
3213 build_builtin_candidate
3214 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3215 build_builtin_candidate
3216 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3217 return;
3220 build_builtin_candidate
3221 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3224 tree
3225 type_decays_to (tree type)
3227 if (TREE_CODE (type) == ARRAY_TYPE)
3228 return build_pointer_type (TREE_TYPE (type));
3229 if (TREE_CODE (type) == FUNCTION_TYPE)
3230 return build_pointer_type (type);
3231 return type;
3234 /* There are three conditions of builtin candidates:
3236 1) bool-taking candidates. These are the same regardless of the input.
3237 2) pointer-pair taking candidates. These are generated for each type
3238 one of the input types converts to.
3239 3) arithmetic candidates. According to the standard, we should generate
3240 all of these, but I'm trying not to...
3242 Here we generate a superset of the possible candidates for this particular
3243 case. That is a subset of the full set the standard defines, plus some
3244 other cases which the standard disallows. add_builtin_candidate will
3245 filter out the invalid set. */
3247 static void
3248 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3249 enum tree_code code2, tree fnname,
3250 vec<tree, va_gc> *argv,
3251 int flags, tsubst_flags_t complain)
3253 int ref1;
3254 int enum_p = 0;
3255 tree type, argtypes[3], t;
3256 /* TYPES[i] is the set of possible builtin-operator parameter types
3257 we will consider for the Ith argument. */
3258 vec<tree, va_gc> *types[2];
3259 unsigned ix;
3260 vec<tree, va_gc> &args = *argv;
3261 unsigned len = args.length ();
3263 for (unsigned i = 0; i < len; ++i)
3265 if (args[i])
3266 argtypes[i] = unlowered_expr_type (args[i]);
3267 else
3268 argtypes[i] = NULL_TREE;
3271 switch (code)
3273 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3274 and VQ is either volatile or empty, there exist candidate operator
3275 functions of the form
3276 VQ T& operator++(VQ T&); */
3278 case POSTINCREMENT_EXPR:
3279 case PREINCREMENT_EXPR:
3280 case POSTDECREMENT_EXPR:
3281 case PREDECREMENT_EXPR:
3282 case MODIFY_EXPR:
3283 ref1 = 1;
3284 break;
3286 /* 24There also exist candidate operator functions of the form
3287 bool operator!(bool);
3288 bool operator&&(bool, bool);
3289 bool operator||(bool, bool); */
3291 case TRUTH_NOT_EXPR:
3292 build_builtin_candidate
3293 (candidates, fnname, boolean_type_node,
3294 NULL_TREE, args, argtypes, flags, complain);
3295 return;
3297 case TRUTH_ORIF_EXPR:
3298 case TRUTH_ANDIF_EXPR:
3299 build_builtin_candidate
3300 (candidates, fnname, boolean_type_node,
3301 boolean_type_node, args, argtypes, flags, complain);
3302 return;
3304 case ADDR_EXPR:
3305 case COMPOUND_EXPR:
3306 case COMPONENT_REF:
3307 case CO_AWAIT_EXPR:
3308 return;
3310 case COND_EXPR:
3311 case EQ_EXPR:
3312 case NE_EXPR:
3313 case LT_EXPR:
3314 case LE_EXPR:
3315 case GT_EXPR:
3316 case GE_EXPR:
3317 case SPACESHIP_EXPR:
3318 enum_p = 1;
3319 /* Fall through. */
3321 default:
3322 ref1 = 0;
3325 types[0] = make_tree_vector ();
3326 types[1] = make_tree_vector ();
3328 if (len == 3)
3329 len = 2;
3330 for (unsigned i = 0; i < len; ++i)
3332 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3334 tree convs;
3336 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3337 return;
3339 convs = lookup_conversions (argtypes[i]);
3341 if (code == COND_EXPR)
3343 if (lvalue_p (args[i]))
3344 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3346 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3349 else if (! convs)
3350 return;
3352 for (; convs; convs = TREE_CHAIN (convs))
3354 type = TREE_TYPE (convs);
3356 if (i == 0 && ref1
3357 && (!TYPE_REF_P (type)
3358 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3359 continue;
3361 if (code == COND_EXPR && TYPE_REF_P (type))
3362 vec_safe_push (types[i], type);
3364 type = non_reference (type);
3365 if (i != 0 || ! ref1)
3367 type = cv_unqualified (type_decays_to (type));
3368 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3369 vec_safe_push (types[i], type);
3370 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3371 type = type_promotes_to (type);
3374 if (! vec_member (type, types[i]))
3375 vec_safe_push (types[i], type);
3378 else
3380 if (code == COND_EXPR && lvalue_p (args[i]))
3381 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3382 type = non_reference (argtypes[i]);
3383 if (i != 0 || ! ref1)
3385 type = cv_unqualified (type_decays_to (type));
3386 if (enum_p && UNSCOPED_ENUM_P (type))
3387 vec_safe_push (types[i], type);
3388 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3389 type = type_promotes_to (type);
3391 vec_safe_push (types[i], type);
3395 /* Run through the possible parameter types of both arguments,
3396 creating candidates with those parameter types. */
3397 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3399 unsigned jx;
3400 tree u;
3402 if (!types[1]->is_empty ())
3403 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3404 add_builtin_candidate
3405 (candidates, code, code2, fnname, t,
3406 u, args, argtypes, flags, complain);
3407 else
3408 add_builtin_candidate
3409 (candidates, code, code2, fnname, t,
3410 NULL_TREE, args, argtypes, flags, complain);
3413 release_tree_vector (types[0]);
3414 release_tree_vector (types[1]);
3418 /* If TMPL can be successfully instantiated as indicated by
3419 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3421 TMPL is the template. EXPLICIT_TARGS are any explicit template
3422 arguments. ARGLIST is the arguments provided at the call-site.
3423 This does not change ARGLIST. The RETURN_TYPE is the desired type
3424 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3425 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3426 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3428 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3430 static struct z_candidate*
3431 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3432 tree ctype, tree explicit_targs, tree first_arg,
3433 const vec<tree, va_gc> *arglist, tree return_type,
3434 tree access_path, tree conversion_path,
3435 int flags, tree obj, unification_kind_t strict,
3436 bool shortcut_bad_convs, tsubst_flags_t complain)
3438 int ntparms = DECL_NTPARMS (tmpl);
3439 tree targs = make_tree_vec (ntparms);
3440 unsigned int len = vec_safe_length (arglist);
3441 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3442 unsigned int skip_without_in_chrg = 0;
3443 tree first_arg_without_in_chrg = first_arg;
3444 tree *args_without_in_chrg;
3445 unsigned int nargs_without_in_chrg;
3446 unsigned int ia, ix;
3447 tree arg;
3448 struct z_candidate *cand;
3449 tree fn;
3450 struct rejection_reason *reason = NULL;
3451 int errs;
3452 conversion **convs = NULL;
3454 /* We don't do deduction on the in-charge parameter, the VTT
3455 parameter or 'this'. */
3456 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3458 if (first_arg_without_in_chrg != NULL_TREE)
3459 first_arg_without_in_chrg = NULL_TREE;
3460 else if (return_type && strict == DEDUCE_CALL)
3461 /* We're deducing for a call to the result of a template conversion
3462 function, so the args don't contain 'this'; leave them alone. */;
3463 else
3464 ++skip_without_in_chrg;
3467 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3468 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3469 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3471 if (first_arg_without_in_chrg != NULL_TREE)
3472 first_arg_without_in_chrg = NULL_TREE;
3473 else
3474 ++skip_without_in_chrg;
3477 if (len < skip_without_in_chrg)
3478 return NULL;
3480 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3481 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3482 TREE_TYPE ((*arglist)[0])))
3484 /* 12.8/6 says, "A declaration of a constructor for a class X is
3485 ill-formed if its first parameter is of type (optionally cv-qualified)
3486 X and either there are no other parameters or else all other
3487 parameters have default arguments. A member function template is never
3488 instantiated to produce such a constructor signature."
3490 So if we're trying to copy an object of the containing class, don't
3491 consider a template constructor that has a first parameter type that
3492 is just a template parameter, as we would deduce a signature that we
3493 would then reject in the code below. */
3494 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3496 firstparm = TREE_VALUE (firstparm);
3497 if (PACK_EXPANSION_P (firstparm))
3498 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3499 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3501 gcc_assert (!explicit_targs);
3502 reason = invalid_copy_with_fn_template_rejection ();
3503 goto fail;
3508 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3509 + (len - skip_without_in_chrg));
3510 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3511 ia = 0;
3512 if (first_arg_without_in_chrg != NULL_TREE)
3514 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3515 ++ia;
3517 for (ix = skip_without_in_chrg;
3518 vec_safe_iterate (arglist, ix, &arg);
3519 ++ix)
3521 args_without_in_chrg[ia] = arg;
3522 ++ia;
3524 gcc_assert (ia == nargs_without_in_chrg);
3526 if (!obj && explicit_targs)
3528 /* Check that there's no obvious arity mismatch before proceeding with
3529 deduction. This avoids substituting explicit template arguments
3530 into the template (which could result in an error outside the
3531 immediate context) when the resulting candidate would be unviable
3532 anyway. */
3533 int min_arity = 0, max_arity = 0;
3534 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3535 parms = skip_artificial_parms_for (tmpl, parms);
3536 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3538 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3540 max_arity = -1;
3541 break;
3543 if (TREE_PURPOSE (parms))
3544 /* A parameter with a default argument. */
3545 ++max_arity;
3546 else
3547 ++min_arity, ++max_arity;
3549 if (ia < (unsigned)min_arity)
3551 /* Too few arguments. */
3552 reason = arity_rejection (NULL_TREE, min_arity, ia,
3553 /*least_p=*/(max_arity == -1));
3554 goto fail;
3556 else if (max_arity != -1 && ia > (unsigned)max_arity)
3558 /* Too many arguments. */
3559 reason = arity_rejection (NULL_TREE, max_arity, ia);
3560 goto fail;
3564 errs = errorcount+sorrycount;
3565 if (!obj)
3567 convs = alloc_conversions (nargs);
3569 if (shortcut_bad_convs
3570 && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3571 && !DECL_CONSTRUCTOR_P (tmpl))
3573 /* Check the 'this' conversion before proceeding with deduction.
3574 This is effectively an extension of the DR 1391 resolution
3575 that we perform in check_non_deducible_conversions, though it's
3576 convenient to do this extra check here instead of there. */
3577 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3578 tree argtype = lvalue_type (first_arg);
3579 tree arg = first_arg;
3580 conversion *t = build_this_conversion (tmpl, ctype,
3581 parmtype, argtype, arg,
3582 flags, complain);
3583 convs[0] = t;
3584 if (t->bad_p)
3586 reason = bad_arg_conversion_rejection (first_arg, 0,
3587 arg, parmtype,
3588 EXPR_LOCATION (arg));
3589 goto fail;
3593 fn = fn_type_unification (tmpl, explicit_targs, targs,
3594 args_without_in_chrg,
3595 nargs_without_in_chrg,
3596 return_type, strict, flags, convs,
3597 false, complain & tf_decltype);
3599 if (fn == error_mark_node)
3601 /* Don't repeat unification later if it already resulted in errors. */
3602 if (errorcount+sorrycount == errs)
3603 reason = template_unification_rejection (tmpl, explicit_targs,
3604 targs, args_without_in_chrg,
3605 nargs_without_in_chrg,
3606 return_type, strict, flags);
3607 else
3608 reason = template_unification_error_rejection ();
3609 goto fail;
3612 /* Now the explicit specifier might have been deduced; check if this
3613 declaration is explicit. If it is and we're ignoring non-converting
3614 constructors, don't add this function to the set of candidates. */
3615 if ((flags & LOOKUP_ONLYCONVERTING) && DECL_NONCONVERTING_P (fn))
3616 return NULL;
3618 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3620 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3621 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3622 ctype))
3624 /* We're trying to produce a constructor with a prohibited signature,
3625 as discussed above; handle here any cases we didn't catch then,
3626 such as X(X<T>). */
3627 reason = invalid_copy_with_fn_template_rejection ();
3628 goto fail;
3632 if (obj != NULL_TREE)
3633 /* Aha, this is a conversion function. */
3634 cand = add_conv_candidate (candidates, fn, obj, arglist,
3635 access_path, conversion_path, complain);
3636 else
3637 cand = add_function_candidate (candidates, fn, ctype,
3638 first_arg, arglist, access_path,
3639 conversion_path, flags, convs,
3640 shortcut_bad_convs, complain);
3641 if (DECL_TI_TEMPLATE (fn) != tmpl)
3642 /* This situation can occur if a member template of a template
3643 class is specialized. Then, instantiate_template might return
3644 an instantiation of the specialization, in which case the
3645 DECL_TI_TEMPLATE field will point at the original
3646 specialization. For example:
3648 template <class T> struct S { template <class U> void f(U);
3649 template <> void f(int) {}; };
3650 S<double> sd;
3651 sd.f(3);
3653 Here, TMPL will be template <class U> S<double>::f(U).
3654 And, instantiate template will give us the specialization
3655 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3656 for this will point at template <class T> template <> S<T>::f(int),
3657 so that we can find the definition. For the purposes of
3658 overload resolution, however, we want the original TMPL. */
3659 cand->template_decl = build_template_info (tmpl, targs);
3660 else
3661 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3662 cand->explicit_targs = explicit_targs;
3664 return cand;
3665 fail:
3666 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3667 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3668 access_path, conversion_path, viable, reason, flags);
3672 static struct z_candidate *
3673 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3674 tree explicit_targs, tree first_arg,
3675 const vec<tree, va_gc> *arglist, tree return_type,
3676 tree access_path, tree conversion_path, int flags,
3677 unification_kind_t strict, bool shortcut_bad_convs,
3678 tsubst_flags_t complain)
3680 return
3681 add_template_candidate_real (candidates, tmpl, ctype,
3682 explicit_targs, first_arg, arglist,
3683 return_type, access_path, conversion_path,
3684 flags, NULL_TREE, strict, shortcut_bad_convs,
3685 complain);
3688 /* Create an overload candidate for the conversion function template TMPL,
3689 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3690 pointer-to-function which will in turn be called with the argument list
3691 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3692 passed on to implicit_conversion. */
3694 static struct z_candidate *
3695 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3696 tree obj,
3697 const vec<tree, va_gc> *arglist,
3698 tree return_type, tree access_path,
3699 tree conversion_path, tsubst_flags_t complain)
3701 /* Making this work broke PR 71117 and 85118, so until the committee resolves
3702 core issue 2189, let's disable this candidate if there are any call
3703 operators. */
3704 if (*candidates)
3705 return NULL;
3707 return
3708 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3709 NULL_TREE, arglist, return_type, access_path,
3710 conversion_path, 0, obj, DEDUCE_CALL,
3711 /*shortcut_bad_convs=*/false, complain);
3714 /* The CANDS are the set of candidates that were considered for
3715 overload resolution. Return the set of viable candidates, or CANDS
3716 if none are viable. If any of the candidates were viable, set
3717 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3718 considered viable only if it is strictly viable. */
3720 static struct z_candidate*
3721 splice_viable (struct z_candidate *cands,
3722 bool strict_p,
3723 bool *any_viable_p)
3725 struct z_candidate *viable;
3726 struct z_candidate **last_viable;
3727 struct z_candidate **cand;
3728 bool found_strictly_viable = false;
3730 /* Be strict inside templates, since build_over_call won't actually
3731 do the conversions to get pedwarns. */
3732 if (processing_template_decl)
3733 strict_p = true;
3735 viable = NULL;
3736 last_viable = &viable;
3737 *any_viable_p = false;
3739 cand = &cands;
3740 while (*cand)
3742 struct z_candidate *c = *cand;
3743 if (!strict_p
3744 && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3746 /* Be strict in the presence of a viable candidate. Also if
3747 there are template candidates, so that we get deduction errors
3748 for them instead of silently preferring a bad conversion. */
3749 strict_p = true;
3750 if (viable && !found_strictly_viable)
3752 /* Put any spliced near matches back onto the main list so
3753 that we see them if there is no strict match. */
3754 *any_viable_p = false;
3755 *last_viable = cands;
3756 cands = viable;
3757 viable = NULL;
3758 last_viable = &viable;
3762 if (strict_p ? c->viable == 1 : c->viable)
3764 *last_viable = c;
3765 *cand = c->next;
3766 c->next = NULL;
3767 last_viable = &c->next;
3768 *any_viable_p = true;
3769 if (c->viable == 1)
3770 found_strictly_viable = true;
3772 else
3773 cand = &c->next;
3776 return viable ? viable : cands;
3779 static bool
3780 any_strictly_viable (struct z_candidate *cands)
3782 for (; cands; cands = cands->next)
3783 if (cands->viable == 1)
3784 return true;
3785 return false;
3788 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3789 words, it is about to become the "this" pointer for a member
3790 function call. Take the address of the object. */
3792 static tree
3793 build_this (tree obj)
3795 /* In a template, we are only concerned about the type of the
3796 expression, so we can take a shortcut. */
3797 if (processing_template_decl)
3798 return build_address (obj);
3800 return cp_build_addr_expr (obj, tf_warning_or_error);
3803 /* Returns true iff functions are equivalent. Equivalent functions are
3804 not '==' only if one is a function-local extern function or if
3805 both are extern "C". */
3807 static inline int
3808 equal_functions (tree fn1, tree fn2)
3810 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3811 return 0;
3812 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3813 return fn1 == fn2;
3814 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3815 || DECL_EXTERN_C_FUNCTION_P (fn1))
3816 return decls_match (fn1, fn2);
3817 return fn1 == fn2;
3820 /* Print information about a candidate FN being rejected due to INFO. */
3822 static void
3823 print_conversion_rejection (location_t loc, struct conversion_info *info,
3824 tree fn)
3826 tree from = info->from;
3827 if (!TYPE_P (from))
3828 from = lvalue_type (from);
3829 if (info->n_arg == -1)
3831 /* Conversion of implicit `this' argument failed. */
3832 if (!TYPE_P (info->from))
3833 /* A bad conversion for 'this' must be discarding cv-quals. */
3834 inform (loc, " passing %qT as %<this%> "
3835 "argument discards qualifiers",
3836 from);
3837 else
3838 inform (loc, " no known conversion for implicit "
3839 "%<this%> parameter from %qH to %qI",
3840 from, info->to_type);
3842 else if (!TYPE_P (info->from))
3844 if (info->n_arg >= 0)
3845 inform (loc, " conversion of argument %d would be ill-formed:",
3846 info->n_arg + 1);
3847 perform_implicit_conversion (info->to_type, info->from,
3848 tf_warning_or_error);
3850 else if (info->n_arg == -2)
3851 /* Conversion of conversion function return value failed. */
3852 inform (loc, " no known conversion from %qH to %qI",
3853 from, info->to_type);
3854 else
3856 if (TREE_CODE (fn) == FUNCTION_DECL)
3857 loc = get_fndecl_argument_location (fn, info->n_arg);
3858 inform (loc, " no known conversion for argument %d from %qH to %qI",
3859 info->n_arg + 1, from, info->to_type);
3863 /* Print information about a candidate with WANT parameters and we found
3864 HAVE. */
3866 static void
3867 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3868 bool least_p)
3870 if (least_p)
3871 inform_n (loc, want,
3872 " candidate expects at least %d argument, %d provided",
3873 " candidate expects at least %d arguments, %d provided",
3874 want, have);
3875 else
3876 inform_n (loc, want,
3877 " candidate expects %d argument, %d provided",
3878 " candidate expects %d arguments, %d provided",
3879 want, have);
3882 /* Print information about one overload candidate CANDIDATE. MSGSTR
3883 is the text to print before the candidate itself.
3885 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3886 to have been run through gettext by the caller. This wart makes
3887 life simpler in print_z_candidates and for the translators. */
3889 static void
3890 print_z_candidate (location_t loc, const char *msgstr,
3891 struct z_candidate *candidate)
3893 const char *msg = (msgstr == NULL
3894 ? ""
3895 : ACONCAT ((_(msgstr), " ", NULL)));
3896 tree fn = candidate->fn;
3897 if (flag_new_inheriting_ctors)
3898 fn = strip_inheriting_ctors (fn);
3899 location_t cloc = location_of (fn);
3901 if (identifier_p (fn))
3903 cloc = loc;
3904 if (candidate->num_convs == 3)
3905 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3906 candidate->convs[0]->type,
3907 candidate->convs[1]->type,
3908 candidate->convs[2]->type);
3909 else if (candidate->num_convs == 2)
3910 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3911 candidate->convs[0]->type,
3912 candidate->convs[1]->type);
3913 else
3914 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3915 candidate->convs[0]->type);
3917 else if (TYPE_P (fn))
3918 inform (cloc, "%s%qT (conversion)", msg, fn);
3919 else if (candidate->viable == -1)
3920 inform (cloc, "%s%#qD (near match)", msg, fn);
3921 else if (DECL_DELETED_FN (fn))
3922 inform (cloc, "%s%#qD (deleted)", msg, fn);
3923 else if (candidate->reversed ())
3924 inform (cloc, "%s%#qD (reversed)", msg, fn);
3925 else if (candidate->rewritten ())
3926 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3927 else
3928 inform (cloc, "%s%#qD", msg, fn);
3929 if (fn != candidate->fn)
3931 cloc = location_of (candidate->fn);
3932 inform (cloc, " inherited here");
3934 /* Give the user some information about why this candidate failed. */
3935 if (candidate->reason != NULL)
3937 struct rejection_reason *r = candidate->reason;
3939 switch (r->code)
3941 case rr_arity:
3942 print_arity_information (cloc, r->u.arity.actual,
3943 r->u.arity.expected,
3944 r->u.arity.least_p);
3945 break;
3946 case rr_arg_conversion:
3947 print_conversion_rejection (cloc, &r->u.conversion, fn);
3948 break;
3949 case rr_bad_arg_conversion:
3950 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3951 break;
3952 case rr_explicit_conversion:
3953 inform (cloc, " return type %qT of explicit conversion function "
3954 "cannot be converted to %qT with a qualification "
3955 "conversion", r->u.conversion.from,
3956 r->u.conversion.to_type);
3957 break;
3958 case rr_template_conversion:
3959 inform (cloc, " conversion from return type %qT of template "
3960 "conversion function specialization to %qT is not an "
3961 "exact match", r->u.conversion.from,
3962 r->u.conversion.to_type);
3963 break;
3964 case rr_template_unification:
3965 /* We use template_unification_error_rejection if unification caused
3966 actual non-SFINAE errors, in which case we don't need to repeat
3967 them here. */
3968 if (r->u.template_unification.tmpl == NULL_TREE)
3970 inform (cloc, " substitution of deduced template arguments "
3971 "resulted in errors seen above");
3972 break;
3974 /* Re-run template unification with diagnostics. */
3975 inform (cloc, " template argument deduction/substitution failed:");
3976 fn_type_unification (r->u.template_unification.tmpl,
3977 r->u.template_unification.explicit_targs,
3978 (make_tree_vec
3979 (r->u.template_unification.num_targs)),
3980 r->u.template_unification.args,
3981 r->u.template_unification.nargs,
3982 r->u.template_unification.return_type,
3983 r->u.template_unification.strict,
3984 r->u.template_unification.flags,
3985 NULL, true, false);
3986 break;
3987 case rr_invalid_copy:
3988 inform (cloc,
3989 " a constructor taking a single argument of its own "
3990 "class type is invalid");
3991 break;
3992 case rr_constraint_failure:
3993 diagnose_constraints (cloc, fn, NULL_TREE);
3994 break;
3995 case rr_inherited_ctor:
3996 inform (cloc, " an inherited constructor is not a candidate for "
3997 "initialization from an expression of the same or derived "
3998 "type");
3999 break;
4000 case rr_none:
4001 default:
4002 /* This candidate didn't have any issues or we failed to
4003 handle a particular code. Either way... */
4004 gcc_unreachable ();
4009 static void
4010 print_z_candidates (location_t loc, struct z_candidate *candidates)
4012 struct z_candidate *cand1;
4013 struct z_candidate **cand2;
4015 if (!candidates)
4016 return;
4018 /* Remove non-viable deleted candidates. */
4019 cand1 = candidates;
4020 for (cand2 = &cand1; *cand2; )
4022 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4023 && !(*cand2)->viable
4024 && DECL_DELETED_FN ((*cand2)->fn))
4025 *cand2 = (*cand2)->next;
4026 else
4027 cand2 = &(*cand2)->next;
4029 /* ...if there are any non-deleted ones. */
4030 if (cand1)
4031 candidates = cand1;
4033 /* There may be duplicates in the set of candidates. We put off
4034 checking this condition as long as possible, since we have no way
4035 to eliminate duplicates from a set of functions in less than n^2
4036 time. Now we are about to emit an error message, so it is more
4037 permissible to go slowly. */
4038 for (cand1 = candidates; cand1; cand1 = cand1->next)
4040 tree fn = cand1->fn;
4041 /* Skip builtin candidates and conversion functions. */
4042 if (!DECL_P (fn))
4043 continue;
4044 cand2 = &cand1->next;
4045 while (*cand2)
4047 if (DECL_P ((*cand2)->fn)
4048 && equal_functions (fn, (*cand2)->fn))
4049 *cand2 = (*cand2)->next;
4050 else
4051 cand2 = &(*cand2)->next;
4055 for (; candidates; candidates = candidates->next)
4056 print_z_candidate (loc, N_("candidate:"), candidates);
4059 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4060 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4061 the result of the conversion function to convert it to the final
4062 desired type. Merge the two sequences into a single sequence,
4063 and return the merged sequence. */
4065 static conversion *
4066 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4068 conversion **t;
4069 bool bad = user_seq->bad_p;
4071 gcc_assert (user_seq->kind == ck_user);
4073 /* Find the end of the second conversion sequence. */
4074 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4076 /* The entire sequence is a user-conversion sequence. */
4077 (*t)->user_conv_p = true;
4078 if (bad)
4079 (*t)->bad_p = true;
4082 if ((*t)->rvaluedness_matches_p)
4083 /* We're binding a reference directly to the result of the conversion.
4084 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4085 type, but we want it back. */
4086 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4088 /* Replace the identity conversion with the user conversion
4089 sequence. */
4090 *t = user_seq;
4092 return std_seq;
4095 /* Handle overload resolution for initializing an object of class type from
4096 an initializer list. First we look for a suitable constructor that
4097 takes a std::initializer_list; if we don't find one, we then look for a
4098 non-list constructor.
4100 Parameters are as for add_candidates, except that the arguments are in
4101 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4102 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4104 static void
4105 add_list_candidates (tree fns, tree first_arg,
4106 const vec<tree, va_gc> *args, tree totype,
4107 tree explicit_targs, bool template_only,
4108 tree conversion_path, tree access_path,
4109 int flags,
4110 struct z_candidate **candidates,
4111 tsubst_flags_t complain)
4113 gcc_assert (*candidates == NULL);
4115 /* We're looking for a ctor for list-initialization. */
4116 flags |= LOOKUP_LIST_INIT_CTOR;
4117 /* And we don't allow narrowing conversions. We also use this flag to
4118 avoid the copy constructor call for copy-list-initialization. */
4119 flags |= LOOKUP_NO_NARROWING;
4121 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4122 tree init_list = (*args)[nart];
4124 /* Always use the default constructor if the list is empty (DR 990). */
4125 if (CONSTRUCTOR_NELTS (init_list) == 0
4126 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4128 /* If the class has a list ctor, try passing the list as a single
4129 argument first, but only consider list ctors. */
4130 else if (TYPE_HAS_LIST_CTOR (totype))
4132 flags |= LOOKUP_LIST_ONLY;
4133 add_candidates (fns, first_arg, args, NULL_TREE,
4134 explicit_targs, template_only, conversion_path,
4135 access_path, flags, candidates, complain);
4136 if (any_strictly_viable (*candidates))
4137 return;
4139 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4140 && !CP_AGGREGATE_TYPE_P (totype))
4142 if (complain & tf_error)
4143 error ("designated initializers cannot be used with a "
4144 "non-aggregate type %qT", totype);
4145 return;
4148 /* Expand the CONSTRUCTOR into a new argument vec. */
4149 vec<tree, va_gc> *new_args;
4150 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4151 for (unsigned i = 0; i < nart; ++i)
4152 new_args->quick_push ((*args)[i]);
4153 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4154 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4156 /* We aren't looking for list-ctors anymore. */
4157 flags &= ~LOOKUP_LIST_ONLY;
4158 /* We allow more user-defined conversions within an init-list. */
4159 flags &= ~LOOKUP_NO_CONVERSION;
4161 add_candidates (fns, first_arg, new_args, NULL_TREE,
4162 explicit_targs, template_only, conversion_path,
4163 access_path, flags, candidates, complain);
4166 /* Given C(std::initializer_list<A>), return A. */
4168 static tree
4169 list_ctor_element_type (tree fn)
4171 gcc_checking_assert (is_list_ctor (fn));
4173 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4174 parm = non_reference (TREE_VALUE (parm));
4175 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4178 /* If EXPR is a braced-init-list where the elements all decay to the same type,
4179 return that type. */
4181 static tree
4182 braced_init_element_type (tree expr)
4184 if (TREE_CODE (expr) == CONSTRUCTOR
4185 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4186 return TREE_TYPE (TREE_TYPE (expr));
4187 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4188 return NULL_TREE;
4190 tree elttype = NULL_TREE;
4191 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4193 tree type = TREE_TYPE (e.value);
4194 type = type_decays_to (type);
4195 if (!elttype)
4196 elttype = type;
4197 else if (!same_type_p (type, elttype))
4198 return NULL_TREE;
4200 return elttype;
4203 /* True iff EXPR contains any temporaries with non-trivial destruction.
4205 ??? Also ignore classes with non-trivial but no-op destruction other than
4206 std::allocator? */
4208 static bool
4209 has_non_trivial_temporaries (tree expr)
4211 auto_vec<tree*> temps;
4212 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4213 for (tree *p : temps)
4215 tree t = TREE_TYPE (*p);
4216 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4217 && !is_std_allocator (t))
4218 return true;
4220 return false;
4223 /* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4224 return INIT as an array (of its own type) so the caller can initialize the
4225 target array in a loop. */
4227 static tree
4228 maybe_init_list_as_array (tree elttype, tree init)
4230 /* Only do this if the array can go in rodata but not once converted. */
4231 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4232 return NULL_TREE;
4233 tree init_elttype = braced_init_element_type (init);
4234 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4235 return NULL_TREE;
4237 /* Check with a stub expression to weed out special cases, and check whether
4238 we call the same function for direct-init as copy-list-init. */
4239 conversion_obstack_sentinel cos;
4240 tree arg = build_stub_object (init_elttype);
4241 conversion *c = implicit_conversion (elttype, init_elttype, arg, false,
4242 LOOKUP_NORMAL, tf_none);
4243 if (c && c->kind == ck_rvalue)
4244 c = next_conversion (c);
4245 if (!c || c->kind != ck_user)
4246 return NULL_TREE;
4248 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4249 conversion *fc = implicit_conversion (elttype, init_elttype, first, false,
4250 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4251 tf_none);
4252 if (fc && fc->kind == ck_rvalue)
4253 fc = next_conversion (fc);
4254 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4255 return NULL_TREE;
4256 first = convert_like (fc, first, tf_none);
4257 if (first == error_mark_node)
4258 /* Let the normal code give the error. */
4259 return NULL_TREE;
4261 /* Don't do this if the conversion would be constant. */
4262 first = maybe_constant_init (first);
4263 if (TREE_CONSTANT (first))
4264 return NULL_TREE;
4266 /* We can't do this if the conversion creates temporaries that need
4267 to live until the whole array is initialized. */
4268 if (has_non_trivial_temporaries (first))
4269 return NULL_TREE;
4271 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4272 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4273 return finish_compound_literal (arr, init, tf_none);
4276 /* If we were going to call e.g. vector(initializer_list<string>) starting
4277 with a list of string-literals (which is inefficient, see PR105838),
4278 instead build an array of const char* and pass it to the range constructor.
4279 But only do this for standard library types, where we can assume the
4280 transformation makes sense.
4282 Really the container classes should have initializer_list<U> constructors to
4283 get the same effect more simply; this is working around that lack. */
4285 static tree
4286 maybe_init_list_as_range (tree fn, tree expr)
4288 if (!processing_template_decl
4289 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4290 && is_list_ctor (fn)
4291 && decl_in_std_namespace_p (fn))
4293 tree to = list_ctor_element_type (fn);
4294 if (tree init = maybe_init_list_as_array (to, expr))
4296 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4297 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4298 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4299 nelts, tf_none);
4300 begin = cp_build_compound_expr (init, begin, tf_none);
4301 return build_constructor_va (init_list_type_node, 2,
4302 NULL_TREE, begin, NULL_TREE, end);
4306 return NULL_TREE;
4309 /* Returns the best overload candidate to perform the requested
4310 conversion. This function is used for three the overloading situations
4311 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4312 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4313 per [dcl.init.ref], so we ignore temporary bindings. */
4315 static struct z_candidate *
4316 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4317 tsubst_flags_t complain)
4319 struct z_candidate *candidates, *cand;
4320 tree fromtype;
4321 tree ctors = NULL_TREE;
4322 tree conv_fns = NULL_TREE;
4323 conversion *conv = NULL;
4324 tree first_arg = NULL_TREE;
4325 vec<tree, va_gc> *args = NULL;
4326 bool any_viable_p;
4327 int convflags;
4329 if (!expr)
4330 return NULL;
4332 fromtype = TREE_TYPE (expr);
4334 /* We represent conversion within a hierarchy using RVALUE_CONV and
4335 BASE_CONV, as specified by [over.best.ics]; these become plain
4336 constructor calls, as specified in [dcl.init]. */
4337 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4338 || !DERIVED_FROM_P (totype, fromtype));
4340 if (CLASS_TYPE_P (totype))
4341 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4342 creating a garbage BASELINK; constructors can't be inherited. */
4343 ctors = get_class_binding (totype, complete_ctor_identifier);
4345 tree to_nonref = non_reference (totype);
4346 if (MAYBE_CLASS_TYPE_P (fromtype))
4348 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4349 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4350 && DERIVED_FROM_P (to_nonref, fromtype)))
4352 /* [class.conv.fct] A conversion function is never used to
4353 convert a (possibly cv-qualified) object to the (possibly
4354 cv-qualified) same object type (or a reference to it), to a
4355 (possibly cv-qualified) base class of that type (or a
4356 reference to it)... */
4358 else
4359 conv_fns = lookup_conversions (fromtype);
4362 candidates = 0;
4363 flags |= LOOKUP_NO_CONVERSION;
4364 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4365 flags |= LOOKUP_NO_NARROWING;
4366 /* Prevent add_candidates from treating a non-strictly viable candidate
4367 as unviable. */
4368 complain |= tf_conv;
4370 /* It's OK to bind a temporary for converting constructor arguments, but
4371 not in converting the return value of a conversion operator. */
4372 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4373 | (flags & LOOKUP_NO_NARROWING));
4374 flags &= ~LOOKUP_NO_TEMP_BIND;
4376 if (ctors)
4378 int ctorflags = flags;
4380 first_arg = build_dummy_object (totype);
4382 /* We should never try to call the abstract or base constructor
4383 from here. */
4384 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4385 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4387 args = make_tree_vector_single (expr);
4388 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4390 /* List-initialization. */
4391 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4392 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4393 ctorflags, &candidates, complain);
4395 else
4397 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4398 TYPE_BINFO (totype), TYPE_BINFO (totype),
4399 ctorflags, &candidates, complain);
4402 for (cand = candidates; cand; cand = cand->next)
4404 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4406 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4407 set, then this is copy-initialization. In that case, "The
4408 result of the call is then used to direct-initialize the
4409 object that is the destination of the copy-initialization."
4410 [dcl.init]
4412 We represent this in the conversion sequence with an
4413 rvalue conversion, which means a constructor call. */
4414 if (!TYPE_REF_P (totype)
4415 && cxx_dialect < cxx17
4416 && (flags & LOOKUP_ONLYCONVERTING)
4417 && !(convflags & LOOKUP_NO_TEMP_BIND))
4418 cand->second_conv
4419 = build_conv (ck_rvalue, totype, cand->second_conv);
4423 if (conv_fns)
4425 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4426 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4427 else
4428 first_arg = expr;
4431 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4433 tree conversion_path = TREE_PURPOSE (conv_fns);
4434 struct z_candidate *old_candidates;
4436 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4437 would need an addional user-defined conversion, i.e. if the return
4438 type differs in class-ness from the desired type. So we avoid
4439 considering operator bool when calling a copy constructor.
4441 This optimization avoids the failure in PR97600, and is allowed by
4442 [temp.inst]/9: "If the function selected by overload resolution can be
4443 determined without instantiating a class template definition, it is
4444 unspecified whether that instantiation actually takes place." */
4445 tree convtype = non_reference (TREE_TYPE (conv_fns));
4446 if ((flags & LOOKUP_NO_CONVERSION)
4447 && !WILDCARD_TYPE_P (convtype)
4448 && (CLASS_TYPE_P (to_nonref)
4449 != CLASS_TYPE_P (convtype)))
4450 continue;
4452 /* If we are called to convert to a reference type, we are trying to
4453 find a direct binding, so don't even consider temporaries. If
4454 we don't find a direct binding, the caller will try again to
4455 look for a temporary binding. */
4456 if (TYPE_REF_P (totype))
4457 convflags |= LOOKUP_NO_TEMP_BIND;
4459 old_candidates = candidates;
4460 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4461 NULL_TREE, false,
4462 conversion_path, TYPE_BINFO (fromtype),
4463 flags, &candidates, complain);
4465 for (cand = candidates; cand != old_candidates; cand = cand->next)
4467 if (cand->viable == 0)
4468 /* Already rejected, don't change to -1. */
4469 continue;
4471 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4472 conversion *ics
4473 = implicit_conversion (totype,
4474 rettype,
4476 /*c_cast_p=*/false, convflags,
4477 complain);
4479 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4480 copy-initialization. In that case, "The result of the
4481 call is then used to direct-initialize the object that is
4482 the destination of the copy-initialization." [dcl.init]
4484 We represent this in the conversion sequence with an
4485 rvalue conversion, which means a constructor call. But
4486 don't add a second rvalue conversion if there's already
4487 one there. Which there really shouldn't be, but it's
4488 harmless since we'd add it here anyway. */
4489 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4490 && !(convflags & LOOKUP_NO_TEMP_BIND))
4491 ics = build_conv (ck_rvalue, totype, ics);
4493 cand->second_conv = ics;
4495 if (!ics)
4497 cand->viable = 0;
4498 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4499 rettype, totype,
4500 EXPR_LOCATION (expr));
4502 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4503 /* Limit this to non-templates for now (PR90546). */
4504 && !cand->template_decl
4505 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4507 /* If we are called to convert to a reference type, we are trying
4508 to find a direct binding per [over.match.ref], so rvaluedness
4509 must match for non-functions. */
4510 cand->viable = 0;
4512 else if (DECL_NONCONVERTING_P (cand->fn)
4513 && ics->rank > cr_exact)
4515 /* 13.3.1.5: For direct-initialization, those explicit
4516 conversion functions that are not hidden within S and
4517 yield type T or a type that can be converted to type T
4518 with a qualification conversion (4.4) are also candidate
4519 functions. */
4520 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4521 I've raised this issue with the committee. --jason 9/2011 */
4522 cand->viable = -1;
4523 cand->reason = explicit_conversion_rejection (rettype, totype);
4525 else if (cand->viable == 1 && ics->bad_p)
4527 cand->viable = -1;
4528 cand->reason
4529 = bad_arg_conversion_rejection (NULL_TREE, -2,
4530 rettype, totype,
4531 EXPR_LOCATION (expr));
4533 else if (primary_template_specialization_p (cand->fn)
4534 && ics->rank > cr_exact)
4536 /* 13.3.3.1.2: If the user-defined conversion is specified by
4537 a specialization of a conversion function template, the
4538 second standard conversion sequence shall have exact match
4539 rank. */
4540 cand->viable = -1;
4541 cand->reason = template_conversion_rejection (rettype, totype);
4546 candidates = splice_viable (candidates, false, &any_viable_p);
4547 if (!any_viable_p)
4549 if (args)
4550 release_tree_vector (args);
4551 return NULL;
4554 cand = tourney (candidates, complain);
4555 if (cand == NULL)
4557 if (complain & tf_error)
4559 auto_diagnostic_group d;
4560 error_at (cp_expr_loc_or_input_loc (expr),
4561 "conversion from %qH to %qI is ambiguous",
4562 fromtype, totype);
4563 print_z_candidates (location_of (expr), candidates);
4566 cand = candidates; /* any one will do */
4567 cand->second_conv = build_ambiguous_conv (totype, expr);
4568 cand->second_conv->user_conv_p = true;
4569 if (!any_strictly_viable (candidates))
4570 cand->second_conv->bad_p = true;
4571 if (flags & LOOKUP_ONLYCONVERTING)
4572 cand->second_conv->need_temporary_p = true;
4573 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4574 ambiguous conversion is no worse than another user-defined
4575 conversion. */
4577 return cand;
4580 /* Maybe pass { } as iterators instead of an initializer_list. */
4581 if (tree iters = maybe_init_list_as_range (cand->fn, expr))
4582 if (z_candidate *cand2
4583 = build_user_type_conversion_1 (totype, iters, flags, tf_none))
4584 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4586 cand = cand2;
4587 expr = iters;
4590 tree convtype;
4591 if (!DECL_CONSTRUCTOR_P (cand->fn))
4592 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4593 else if (cand->second_conv->kind == ck_rvalue)
4594 /* DR 5: [in the first step of copy-initialization]...if the function
4595 is a constructor, the call initializes a temporary of the
4596 cv-unqualified version of the destination type. */
4597 convtype = cv_unqualified (totype);
4598 else
4599 convtype = totype;
4600 /* Build the user conversion sequence. */
4601 conv = build_conv
4602 (ck_user,
4603 convtype,
4604 build_identity_conv (TREE_TYPE (expr), expr));
4605 conv->cand = cand;
4606 if (cand->viable == -1)
4607 conv->bad_p = true;
4609 /* Remember that this was a list-initialization. */
4610 if (flags & LOOKUP_NO_NARROWING)
4611 conv->check_narrowing = true;
4613 /* Combine it with the second conversion sequence. */
4614 cand->second_conv = merge_conversion_sequences (conv,
4615 cand->second_conv);
4617 return cand;
4620 /* Wrapper for above. */
4622 tree
4623 build_user_type_conversion (tree totype, tree expr, int flags,
4624 tsubst_flags_t complain)
4626 struct z_candidate *cand;
4627 tree ret;
4629 auto_cond_timevar tv (TV_OVERLOAD);
4630 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4632 if (cand)
4634 if (cand->second_conv->kind == ck_ambig)
4635 ret = error_mark_node;
4636 else
4638 expr = convert_like (cand->second_conv, expr, complain);
4639 ret = convert_from_reference (expr);
4642 else
4643 ret = NULL_TREE;
4645 return ret;
4648 /* Give a helpful diagnostic when implicit_conversion fails. */
4650 static void
4651 implicit_conversion_error (location_t loc, tree type, tree expr)
4653 tsubst_flags_t complain = tf_warning_or_error;
4655 /* If expr has unknown type, then it is an overloaded function.
4656 Call instantiate_type to get good error messages. */
4657 if (TREE_TYPE (expr) == unknown_type_node)
4658 instantiate_type (type, expr, complain);
4659 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4660 /* We gave an error. */;
4661 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4662 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4663 && !CP_AGGREGATE_TYPE_P (type))
4664 error_at (loc, "designated initializers cannot be used with a "
4665 "non-aggregate type %qT", type);
4666 else
4668 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4669 gcc_rich_location rich_loc (loc, &label);
4670 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4671 expr, TREE_TYPE (expr), type);
4675 /* Worker for build_converted_constant_expr. */
4677 static tree
4678 build_converted_constant_expr_internal (tree type, tree expr,
4679 int flags, tsubst_flags_t complain)
4681 conversion *conv;
4682 void *p;
4683 tree t;
4684 location_t loc = cp_expr_loc_or_input_loc (expr);
4686 if (error_operand_p (expr))
4687 return error_mark_node;
4689 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4690 p = conversion_obstack_alloc (0);
4692 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4693 /*c_cast_p=*/false, flags, complain);
4695 /* A converted constant expression of type T is an expression, implicitly
4696 converted to type T, where the converted expression is a constant
4697 expression and the implicit conversion sequence contains only
4699 * user-defined conversions,
4700 * lvalue-to-rvalue conversions (7.1),
4701 * array-to-pointer conversions (7.2),
4702 * function-to-pointer conversions (7.3),
4703 * qualification conversions (7.5),
4704 * integral promotions (7.6),
4705 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4706 * null pointer conversions (7.11) from std::nullptr_t,
4707 * null member pointer conversions (7.12) from std::nullptr_t, and
4708 * function pointer conversions (7.13),
4710 and where the reference binding (if any) binds directly. */
4712 for (conversion *c = conv;
4713 c && c->kind != ck_identity;
4714 c = next_conversion (c))
4716 switch (c->kind)
4718 /* A conversion function is OK. If it isn't constexpr, we'll
4719 complain later that the argument isn't constant. */
4720 case ck_user:
4721 /* List-initialization is OK. */
4722 case ck_aggr:
4723 /* The lvalue-to-rvalue conversion is OK. */
4724 case ck_rvalue:
4725 /* Array-to-pointer and function-to-pointer. */
4726 case ck_lvalue:
4727 /* Function pointer conversions. */
4728 case ck_fnptr:
4729 /* Qualification conversions. */
4730 case ck_qual:
4731 break;
4733 case ck_ref_bind:
4734 if (c->need_temporary_p)
4736 if (complain & tf_error)
4737 error_at (loc, "initializing %qH with %qI in converted "
4738 "constant expression does not bind directly",
4739 type, next_conversion (c)->type);
4740 conv = NULL;
4742 break;
4744 case ck_base:
4745 case ck_pmem:
4746 case ck_ptr:
4747 case ck_std:
4748 t = next_conversion (c)->type;
4749 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4750 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4751 /* Integral promotion or conversion. */
4752 break;
4753 if (NULLPTR_TYPE_P (t))
4754 /* Conversion from nullptr to pointer or pointer-to-member. */
4755 break;
4757 if (complain & tf_error)
4758 error_at (loc, "conversion from %qH to %qI in a "
4759 "converted constant expression", t, type);
4760 /* fall through. */
4762 default:
4763 conv = NULL;
4764 break;
4768 /* Avoid confusing convert_nontype_argument by introducing
4769 a redundant conversion to the same reference type. */
4770 if (conv && conv->kind == ck_ref_bind
4771 && REFERENCE_REF_P (expr))
4773 tree ref = TREE_OPERAND (expr, 0);
4774 if (same_type_p (type, TREE_TYPE (ref)))
4775 return ref;
4778 if (conv)
4780 /* Don't copy a class in a template. */
4781 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4782 && processing_template_decl)
4783 conv = next_conversion (conv);
4785 /* Issuing conversion warnings for value-dependent expressions is
4786 likely too noisy. */
4787 warning_sentinel w (warn_conversion);
4788 conv->check_narrowing = true;
4789 conv->check_narrowing_const_only = true;
4790 expr = convert_like (conv, expr, complain);
4792 else
4794 if (complain & tf_error)
4795 implicit_conversion_error (loc, type, expr);
4796 expr = error_mark_node;
4799 /* Free all the conversions we allocated. */
4800 obstack_free (&conversion_obstack, p);
4802 return expr;
4805 /* Subroutine of convert_nontype_argument.
4807 EXPR is an expression used in a context that requires a converted
4808 constant-expression, such as a template non-type parameter. Do any
4809 necessary conversions (that are permitted for converted
4810 constant-expressions) to convert it to the desired type.
4812 This function doesn't consider explicit conversion functions. If
4813 you mean to use "a contextually converted constant expression of type
4814 bool", use build_converted_constant_bool_expr.
4816 If conversion is successful, returns the converted expression;
4817 otherwise, returns error_mark_node. */
4819 tree
4820 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4822 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4823 complain);
4826 /* Used to create "a contextually converted constant expression of type
4827 bool". This differs from build_converted_constant_expr in that it
4828 also considers explicit conversion functions. */
4830 tree
4831 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4833 return build_converted_constant_expr_internal (boolean_type_node, expr,
4834 LOOKUP_NORMAL, complain);
4837 /* Do any initial processing on the arguments to a function call. */
4839 vec<tree, va_gc> *
4840 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4842 unsigned int ix;
4843 tree arg;
4845 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4847 if (error_operand_p (arg))
4848 return NULL;
4849 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4851 if (complain & tf_error)
4852 error_at (cp_expr_loc_or_input_loc (arg),
4853 "invalid use of void expression");
4854 return NULL;
4856 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4857 return NULL;
4859 /* Force auto deduction now. Omit tf_warning to avoid redundant
4860 deprecated warning on deprecated-14.C. */
4861 if (!mark_single_function (arg, complain & ~tf_warning))
4862 return NULL;
4864 return args;
4867 /* Perform overload resolution on FN, which is called with the ARGS.
4869 Return the candidate function selected by overload resolution, or
4870 NULL if the event that overload resolution failed. In the case
4871 that overload resolution fails, *CANDIDATES will be the set of
4872 candidates considered, and ANY_VIABLE_P will be set to true or
4873 false to indicate whether or not any of the candidates were
4874 viable.
4876 The ARGS should already have gone through RESOLVE_ARGS before this
4877 function is called. */
4879 static struct z_candidate *
4880 perform_overload_resolution (tree fn,
4881 const vec<tree, va_gc> *args,
4882 struct z_candidate **candidates,
4883 bool *any_viable_p, tsubst_flags_t complain)
4885 struct z_candidate *cand;
4886 tree explicit_targs;
4887 int template_only;
4889 auto_cond_timevar tv (TV_OVERLOAD);
4891 explicit_targs = NULL_TREE;
4892 template_only = 0;
4894 *candidates = NULL;
4895 *any_viable_p = true;
4897 /* Check FN. */
4898 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4900 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4902 explicit_targs = TREE_OPERAND (fn, 1);
4903 fn = TREE_OPERAND (fn, 0);
4904 template_only = 1;
4907 /* Add the various candidate functions. */
4908 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4909 explicit_targs, template_only,
4910 /*conversion_path=*/NULL_TREE,
4911 /*access_path=*/NULL_TREE,
4912 LOOKUP_NORMAL,
4913 candidates, complain);
4915 *candidates = splice_viable (*candidates, false, any_viable_p);
4916 if (*any_viable_p)
4917 cand = tourney (*candidates, complain);
4918 else
4919 cand = NULL;
4921 return cand;
4924 /* Print an error message about being unable to build a call to FN with
4925 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4926 be located; CANDIDATES is a possibly empty list of such
4927 functions. */
4929 static void
4930 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4931 struct z_candidate *candidates)
4933 tree targs = NULL_TREE;
4934 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4936 targs = TREE_OPERAND (fn, 1);
4937 fn = TREE_OPERAND (fn, 0);
4939 tree name = OVL_NAME (fn);
4940 location_t loc = location_of (name);
4941 if (targs)
4942 name = lookup_template_function (name, targs);
4944 auto_diagnostic_group d;
4945 if (!any_strictly_viable (candidates))
4946 error_at (loc, "no matching function for call to %<%D(%A)%>",
4947 name, build_tree_list_vec (args));
4948 else
4949 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4950 name, build_tree_list_vec (args));
4951 if (candidates)
4952 print_z_candidates (loc, candidates);
4955 /* Perform overload resolution on the set of deduction guides DGUIDES
4956 using ARGS. Returns the selected deduction guide, or error_mark_node
4957 if overload resolution fails. */
4959 tree
4960 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4961 tsubst_flags_t complain)
4963 z_candidate *candidates;
4964 bool any_viable_p;
4965 tree result;
4967 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4969 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4970 void *p = conversion_obstack_alloc (0);
4972 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
4973 &any_viable_p, complain);
4974 if (!cand)
4976 if (complain & tf_error)
4977 print_error_for_call_failure (dguides, args, candidates);
4978 result = error_mark_node;
4980 else
4981 result = cand->fn;
4983 /* Free all the conversions we allocated. */
4984 obstack_free (&conversion_obstack, p);
4986 return result;
4989 /* Return an expression for a call to FN (a namespace-scope function,
4990 or a static member function) with the ARGS. This may change
4991 ARGS. */
4993 tree
4994 build_new_function_call (tree fn, vec<tree, va_gc> **args,
4995 tsubst_flags_t complain)
4997 struct z_candidate *candidates, *cand;
4998 bool any_viable_p;
4999 void *p;
5000 tree result;
5002 if (args != NULL && *args != NULL)
5004 *args = resolve_args (*args, complain);
5005 if (*args == NULL)
5006 return error_mark_node;
5009 if (flag_tm)
5010 tm_malloc_replacement (fn);
5012 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5013 p = conversion_obstack_alloc (0);
5015 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
5016 complain);
5018 if (!cand)
5020 if (complain & tf_error)
5022 // If there is a single (non-viable) function candidate,
5023 // let the error be diagnosed by cp_build_function_call_vec.
5024 if (!any_viable_p && candidates && ! candidates->next
5025 && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
5026 return cp_build_function_call_vec (candidates->fn, args, complain);
5028 // Otherwise, emit notes for non-viable candidates.
5029 print_error_for_call_failure (fn, *args, candidates);
5031 result = error_mark_node;
5033 else
5035 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5038 if (flag_coroutines
5039 && result
5040 && TREE_CODE (result) == CALL_EXPR
5041 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5042 == BUILT_IN_NORMAL)
5043 result = coro_validate_builtin_call (result);
5045 /* Free all the conversions we allocated. */
5046 obstack_free (&conversion_obstack, p);
5048 return result;
5051 /* Build a call to a global operator new. FNNAME is the name of the
5052 operator (either "operator new" or "operator new[]") and ARGS are
5053 the arguments provided. This may change ARGS. *SIZE points to the
5054 total number of bytes required by the allocation, and is updated if
5055 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5056 be used. If this function determines that no cookie should be
5057 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5058 is not NULL_TREE, it is evaluated before calculating the final
5059 array size, and if it fails, the array size is replaced with
5060 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5061 is non-NULL, it will be set, upon return, to the allocation
5062 function called. */
5064 tree
5065 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5066 tree *size, tree *cookie_size,
5067 tree align_arg, tree size_check,
5068 tree *fn, tsubst_flags_t complain)
5070 tree original_size = *size;
5071 tree fns;
5072 struct z_candidate *candidates;
5073 struct z_candidate *cand = NULL;
5074 bool any_viable_p;
5076 if (fn)
5077 *fn = NULL_TREE;
5078 /* Set to (size_t)-1 if the size check fails. */
5079 if (size_check != NULL_TREE)
5081 tree errval = TYPE_MAX_VALUE (sizetype);
5082 if (cxx_dialect >= cxx11 && flag_exceptions)
5083 errval = throw_bad_array_new_length ();
5084 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5085 original_size, errval);
5087 vec_safe_insert (*args, 0, *size);
5088 *args = resolve_args (*args, complain);
5089 if (*args == NULL)
5090 return error_mark_node;
5092 /* Based on:
5094 [expr.new]
5096 If this lookup fails to find the name, or if the allocated type
5097 is not a class type, the allocation function's name is looked
5098 up in the global scope.
5100 we disregard block-scope declarations of "operator new". */
5101 fns = lookup_qualified_name (global_namespace, fnname);
5103 if (align_arg)
5105 vec<tree, va_gc>* align_args
5106 = vec_copy_and_insert (*args, align_arg, 1);
5107 cand = perform_overload_resolution (fns, align_args, &candidates,
5108 &any_viable_p, tf_none);
5109 if (cand)
5110 *args = align_args;
5111 /* If no aligned allocation function matches, try again without the
5112 alignment. */
5115 /* Figure out what function is being called. */
5116 if (!cand)
5117 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
5118 complain);
5120 /* If no suitable function could be found, issue an error message
5121 and give up. */
5122 if (!cand)
5124 if (complain & tf_error)
5125 print_error_for_call_failure (fns, *args, candidates);
5126 return error_mark_node;
5129 /* If a cookie is required, add some extra space. Whether
5130 or not a cookie is required cannot be determined until
5131 after we know which function was called. */
5132 if (*cookie_size)
5134 bool use_cookie = true;
5135 tree arg_types;
5137 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5138 /* Skip the size_t parameter. */
5139 arg_types = TREE_CHAIN (arg_types);
5140 /* Check the remaining parameters (if any). */
5141 if (arg_types
5142 && TREE_CHAIN (arg_types) == void_list_node
5143 && same_type_p (TREE_VALUE (arg_types),
5144 ptr_type_node))
5145 use_cookie = false;
5146 /* If we need a cookie, adjust the number of bytes allocated. */
5147 if (use_cookie)
5149 /* Update the total size. */
5150 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5151 if (size_check)
5153 /* Set to (size_t)-1 if the size check fails. */
5154 gcc_assert (size_check != NULL_TREE);
5155 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5156 *size, TYPE_MAX_VALUE (sizetype));
5158 /* Update the argument list to reflect the adjusted size. */
5159 (**args)[0] = *size;
5161 else
5162 *cookie_size = NULL_TREE;
5165 /* Tell our caller which function we decided to call. */
5166 if (fn)
5167 *fn = cand->fn;
5169 /* Build the CALL_EXPR. */
5170 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5172 /* Set this flag for all callers of this function. In addition to
5173 new-expressions, this is called for allocating coroutine state; treat
5174 that as an implicit new-expression. */
5175 tree call = extract_call_expr (ret);
5176 if (TREE_CODE (call) == CALL_EXPR)
5177 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5179 return ret;
5182 /* Evaluate side-effects from OBJ before evaluating call
5183 to FN in RESULT expression.
5184 This is for expressions of the form `obj->fn(...)'
5185 where `fn' turns out to be a static member function and
5186 `obj' needs to be evaluated. `fn' could be also static operator[]
5187 or static operator(), in which cases the source expression
5188 would be `obj[...]' or `obj(...)'. */
5190 tree
5191 keep_unused_object_arg (tree result, tree obj, tree fn)
5193 if (result == NULL_TREE
5194 || result == error_mark_node
5195 || TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
5196 || !TREE_SIDE_EFFECTS (obj))
5197 return result;
5199 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5200 volatile. */
5201 tree a = obj;
5202 if (TREE_THIS_VOLATILE (a))
5203 a = build_this (a);
5204 if (TREE_SIDE_EFFECTS (a))
5205 return build2 (COMPOUND_EXPR, TREE_TYPE (result), a, result);
5206 return result;
5209 /* Build a new call to operator(). This may change ARGS. */
5211 tree
5212 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5214 struct z_candidate *candidates = 0, *cand;
5215 tree fns, convs, first_mem_arg = NULL_TREE;
5216 bool any_viable_p;
5217 tree result = NULL_TREE;
5218 void *p;
5220 auto_cond_timevar tv (TV_OVERLOAD);
5222 obj = mark_lvalue_use (obj);
5224 if (error_operand_p (obj))
5225 return error_mark_node;
5227 tree type = TREE_TYPE (obj);
5229 obj = prep_operand (obj);
5231 if (TYPE_PTRMEMFUNC_P (type))
5233 if (complain & tf_error)
5234 /* It's no good looking for an overloaded operator() on a
5235 pointer-to-member-function. */
5236 error ("pointer-to-member function %qE cannot be called without "
5237 "an object; consider using %<.*%> or %<->*%>", obj);
5238 return error_mark_node;
5241 if (TYPE_BINFO (type))
5243 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5244 if (fns == error_mark_node)
5245 return error_mark_node;
5247 else
5248 fns = NULL_TREE;
5250 if (args != NULL && *args != NULL)
5252 *args = resolve_args (*args, complain);
5253 if (*args == NULL)
5254 return error_mark_node;
5257 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5258 p = conversion_obstack_alloc (0);
5260 if (fns)
5262 first_mem_arg = obj;
5264 add_candidates (BASELINK_FUNCTIONS (fns),
5265 first_mem_arg, *args, NULL_TREE,
5266 NULL_TREE, false,
5267 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5268 LOOKUP_NORMAL, &candidates, complain);
5271 convs = lookup_conversions (type);
5273 for (; convs; convs = TREE_CHAIN (convs))
5275 tree totype = TREE_TYPE (convs);
5277 if (TYPE_PTRFN_P (totype)
5278 || TYPE_REFFN_P (totype)
5279 || (TYPE_REF_P (totype)
5280 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5281 for (tree fn : ovl_range (TREE_VALUE (convs)))
5283 if (DECL_NONCONVERTING_P (fn))
5284 continue;
5286 if (TREE_CODE (fn) == TEMPLATE_DECL)
5287 add_template_conv_candidate
5288 (&candidates, fn, obj, *args, totype,
5289 /*access_path=*/NULL_TREE,
5290 /*conversion_path=*/NULL_TREE, complain);
5291 else
5292 add_conv_candidate (&candidates, fn, obj,
5293 *args, /*conversion_path=*/NULL_TREE,
5294 /*access_path=*/NULL_TREE, complain);
5298 /* Be strict here because if we choose a bad conversion candidate, the
5299 errors we get won't mention the call context. */
5300 candidates = splice_viable (candidates, true, &any_viable_p);
5301 if (!any_viable_p)
5303 if (complain & tf_error)
5305 auto_diagnostic_group d;
5306 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5307 build_tree_list_vec (*args));
5308 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5310 result = error_mark_node;
5312 else
5314 cand = tourney (candidates, complain);
5315 if (cand == 0)
5317 if (complain & tf_error)
5319 auto_diagnostic_group d;
5320 error ("call of %<(%T) (%A)%> is ambiguous",
5321 TREE_TYPE (obj), build_tree_list_vec (*args));
5322 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5324 result = error_mark_node;
5326 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5327 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5328 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5330 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5331 /* In an expression of the form `a()' where cand->fn
5332 which is operator() turns out to be a static member function,
5333 `a' is none-the-less evaluated. */
5334 result = keep_unused_object_arg (result, obj, cand->fn);
5336 else
5338 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5339 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5340 -1, complain);
5341 else
5343 gcc_checking_assert (TYPE_P (cand->fn));
5344 obj = convert_like (cand->convs[0], obj, complain);
5346 obj = convert_from_reference (obj);
5347 result = cp_build_function_call_vec (obj, args, complain);
5351 /* Free all the conversions we allocated. */
5352 obstack_free (&conversion_obstack, p);
5354 return result;
5357 /* Called by op_error to prepare format strings suitable for the error
5358 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5359 and a suffix (controlled by NTYPES). */
5361 static const char *
5362 op_error_string (const char *errmsg, int ntypes, bool match)
5364 const char *msg;
5366 const char *msgp = concat (match ? G_("ambiguous overload for ")
5367 : G_("no match for "), errmsg, NULL);
5369 if (ntypes == 3)
5370 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5371 else if (ntypes == 2)
5372 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5373 else
5374 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5376 return msg;
5379 static void
5380 op_error (const op_location_t &loc,
5381 enum tree_code code, enum tree_code code2,
5382 tree arg1, tree arg2, tree arg3, bool match)
5384 bool assop = code == MODIFY_EXPR;
5385 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5387 switch (code)
5389 case COND_EXPR:
5390 if (flag_diagnostics_show_caret)
5391 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5392 3, match),
5393 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5394 else
5395 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5396 "in %<%E ? %E : %E%>"), 3, match),
5397 arg1, arg2, arg3,
5398 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5399 break;
5401 case POSTINCREMENT_EXPR:
5402 case POSTDECREMENT_EXPR:
5403 if (flag_diagnostics_show_caret)
5404 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5405 opname, TREE_TYPE (arg1));
5406 else
5407 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5408 1, match),
5409 opname, arg1, opname, TREE_TYPE (arg1));
5410 break;
5412 case ARRAY_REF:
5413 if (flag_diagnostics_show_caret)
5414 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5415 TREE_TYPE (arg1), TREE_TYPE (arg2));
5416 else
5417 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5418 2, match),
5419 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5420 break;
5422 case REALPART_EXPR:
5423 case IMAGPART_EXPR:
5424 if (flag_diagnostics_show_caret)
5425 error_at (loc, op_error_string (G_("%qs"), 1, match),
5426 opname, TREE_TYPE (arg1));
5427 else
5428 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5429 opname, opname, arg1, TREE_TYPE (arg1));
5430 break;
5432 case CO_AWAIT_EXPR:
5433 if (flag_diagnostics_show_caret)
5434 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5435 opname, TREE_TYPE (arg1));
5436 else
5437 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5438 1, match),
5439 opname, opname, arg1, TREE_TYPE (arg1));
5440 break;
5442 default:
5443 if (arg2)
5444 if (flag_diagnostics_show_caret)
5446 binary_op_rich_location richloc (loc, arg1, arg2, true);
5447 error_at (&richloc,
5448 op_error_string (G_("%<operator%s%>"), 2, match),
5449 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5451 else
5452 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5453 2, match),
5454 opname, arg1, opname, arg2,
5455 TREE_TYPE (arg1), TREE_TYPE (arg2));
5456 else
5457 if (flag_diagnostics_show_caret)
5458 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5459 opname, TREE_TYPE (arg1));
5460 else
5461 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5462 1, match),
5463 opname, opname, arg1, TREE_TYPE (arg1));
5464 break;
5468 /* Return the implicit conversion sequence that could be used to
5469 convert E1 to E2 in [expr.cond]. */
5471 static conversion *
5472 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5474 tree t1 = non_reference (TREE_TYPE (e1));
5475 tree t2 = non_reference (TREE_TYPE (e2));
5476 conversion *conv;
5477 bool good_base;
5479 /* [expr.cond]
5481 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5482 implicitly converted (clause _conv_) to the type "lvalue reference to
5483 T2", subject to the constraint that in the conversion the
5484 reference must bind directly (_dcl.init.ref_) to an lvalue.
5486 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5487 implicitly converted to the type "rvalue reference to T2", subject to
5488 the constraint that the reference must bind directly. */
5489 if (glvalue_p (e2))
5491 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5492 conv = implicit_conversion (rtype,
5495 /*c_cast_p=*/false,
5496 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5497 |LOOKUP_ONLYCONVERTING,
5498 complain);
5499 if (conv && !conv->bad_p)
5500 return conv;
5503 /* If E2 is a prvalue or if neither of the conversions above can be done
5504 and at least one of the operands has (possibly cv-qualified) class
5505 type: */
5506 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5507 return NULL;
5509 /* [expr.cond]
5511 If E1 and E2 have class type, and the underlying class types are
5512 the same or one is a base class of the other: E1 can be converted
5513 to match E2 if the class of T2 is the same type as, or a base
5514 class of, the class of T1, and the cv-qualification of T2 is the
5515 same cv-qualification as, or a greater cv-qualification than, the
5516 cv-qualification of T1. If the conversion is applied, E1 is
5517 changed to an rvalue of type T2 that still refers to the original
5518 source class object (or the appropriate subobject thereof). */
5519 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5520 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5522 if (good_base && at_least_as_qualified_p (t2, t1))
5524 conv = build_identity_conv (t1, e1);
5525 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5526 TYPE_MAIN_VARIANT (t2)))
5527 conv = build_conv (ck_base, t2, conv);
5528 else
5529 conv = build_conv (ck_rvalue, t2, conv);
5530 return conv;
5532 else
5533 return NULL;
5535 else
5536 /* [expr.cond]
5538 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5539 converted to the type that expression E2 would have if E2 were
5540 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5541 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5542 LOOKUP_IMPLICIT, complain);
5545 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5546 arguments to the conditional expression. */
5548 tree
5549 build_conditional_expr (const op_location_t &loc,
5550 tree arg1, tree arg2, tree arg3,
5551 tsubst_flags_t complain)
5553 tree arg2_type;
5554 tree arg3_type;
5555 tree result = NULL_TREE;
5556 tree result_type = NULL_TREE;
5557 tree semantic_result_type = NULL_TREE;
5558 bool is_glvalue = true;
5559 struct z_candidate *candidates = 0;
5560 struct z_candidate *cand;
5561 void *p;
5562 tree orig_arg2, orig_arg3;
5564 auto_cond_timevar tv (TV_OVERLOAD);
5566 /* As a G++ extension, the second argument to the conditional can be
5567 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5568 c'.) If the second operand is omitted, make sure it is
5569 calculated only once. */
5570 if (!arg2)
5572 if (complain & tf_error)
5573 pedwarn (loc, OPT_Wpedantic,
5574 "ISO C++ forbids omitting the middle term of "
5575 "a %<?:%> expression");
5577 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5578 warn_for_omitted_condop (loc, arg1);
5580 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5581 if (glvalue_p (arg1))
5583 arg1 = cp_stabilize_reference (arg1);
5584 arg2 = arg1 = prevent_lifetime_extension (arg1);
5586 else if (TREE_CODE (arg1) == TARGET_EXPR)
5587 /* arg1 can't be a prvalue result of the conditional
5588 expression, since it needs to be materialized for the
5589 conversion to bool, so treat it as an xvalue in arg2. */
5590 arg2 = move (TARGET_EXPR_SLOT (arg1));
5591 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5592 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5593 cp_save_expr (TREE_OPERAND (arg1, 0)));
5594 else
5595 arg2 = arg1 = cp_save_expr (arg1);
5598 /* If something has already gone wrong, just pass that fact up the
5599 tree. */
5600 if (error_operand_p (arg1)
5601 || error_operand_p (arg2)
5602 || error_operand_p (arg3))
5603 return error_mark_node;
5605 orig_arg2 = arg2;
5606 orig_arg3 = arg3;
5608 if (gnu_vector_type_p (TREE_TYPE (arg1))
5609 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5611 tree arg1_type = TREE_TYPE (arg1);
5613 /* If arg1 is another cond_expr choosing between -1 and 0,
5614 then we can use its comparison. It may help to avoid
5615 additional comparison, produce more accurate diagnostics
5616 and enables folding. */
5617 if (TREE_CODE (arg1) == VEC_COND_EXPR
5618 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5619 && integer_zerop (TREE_OPERAND (arg1, 2)))
5620 arg1 = TREE_OPERAND (arg1, 0);
5622 arg1 = force_rvalue (arg1, complain);
5623 arg2 = force_rvalue (arg2, complain);
5624 arg3 = force_rvalue (arg3, complain);
5626 /* force_rvalue can return error_mark on valid arguments. */
5627 if (error_operand_p (arg1)
5628 || error_operand_p (arg2)
5629 || error_operand_p (arg3))
5630 return error_mark_node;
5632 arg2_type = TREE_TYPE (arg2);
5633 arg3_type = TREE_TYPE (arg3);
5635 if (!VECTOR_TYPE_P (arg2_type)
5636 && !VECTOR_TYPE_P (arg3_type))
5638 /* Rely on the error messages of the scalar version. */
5639 tree scal = build_conditional_expr (loc, integer_one_node,
5640 orig_arg2, orig_arg3, complain);
5641 if (scal == error_mark_node)
5642 return error_mark_node;
5643 tree stype = TREE_TYPE (scal);
5644 tree ctype = TREE_TYPE (arg1_type);
5645 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5646 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5648 if (complain & tf_error)
5649 error_at (loc, "inferred scalar type %qT is not an integer or "
5650 "floating-point type of the same size as %qT", stype,
5651 COMPARISON_CLASS_P (arg1)
5652 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5653 : ctype);
5654 return error_mark_node;
5657 tree vtype = build_opaque_vector_type (stype,
5658 TYPE_VECTOR_SUBPARTS (arg1_type));
5659 /* We could pass complain & tf_warning to unsafe_conversion_p,
5660 but the warnings (like Wsign-conversion) have already been
5661 given by the scalar build_conditional_expr_1. We still check
5662 unsafe_conversion_p to forbid truncating long long -> float. */
5663 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5665 if (complain & tf_error)
5666 error_at (loc, "conversion of scalar %qH to vector %qI "
5667 "involves truncation", arg2_type, vtype);
5668 return error_mark_node;
5670 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5672 if (complain & tf_error)
5673 error_at (loc, "conversion of scalar %qH to vector %qI "
5674 "involves truncation", arg3_type, vtype);
5675 return error_mark_node;
5678 arg2 = cp_convert (stype, arg2, complain);
5679 arg2 = save_expr (arg2);
5680 arg2 = build_vector_from_val (vtype, arg2);
5681 arg2_type = vtype;
5682 arg3 = cp_convert (stype, arg3, complain);
5683 arg3 = save_expr (arg3);
5684 arg3 = build_vector_from_val (vtype, arg3);
5685 arg3_type = vtype;
5688 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5689 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5691 enum stv_conv convert_flag =
5692 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5693 complain & tf_error);
5695 switch (convert_flag)
5697 case stv_error:
5698 return error_mark_node;
5699 case stv_firstarg:
5701 arg2 = save_expr (arg2);
5702 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5703 arg2 = build_vector_from_val (arg3_type, arg2);
5704 arg2_type = TREE_TYPE (arg2);
5705 break;
5707 case stv_secondarg:
5709 arg3 = save_expr (arg3);
5710 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5711 arg3 = build_vector_from_val (arg2_type, arg3);
5712 arg3_type = TREE_TYPE (arg3);
5713 break;
5715 default:
5716 break;
5720 if (!gnu_vector_type_p (arg2_type)
5721 || !gnu_vector_type_p (arg3_type)
5722 || !same_type_p (arg2_type, arg3_type)
5723 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5724 TYPE_VECTOR_SUBPARTS (arg2_type))
5725 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5727 if (complain & tf_error)
5728 error_at (loc,
5729 "incompatible vector types in conditional expression: "
5730 "%qT, %qT and %qT", TREE_TYPE (arg1),
5731 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5732 return error_mark_node;
5735 if (!COMPARISON_CLASS_P (arg1))
5737 tree cmp_type = truth_type_for (arg1_type);
5738 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5740 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5743 /* [expr.cond]
5745 The first expression is implicitly converted to bool (clause
5746 _conv_). */
5747 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5748 LOOKUP_NORMAL);
5749 if (error_operand_p (arg1))
5750 return error_mark_node;
5752 arg2_type = unlowered_expr_type (arg2);
5753 arg3_type = unlowered_expr_type (arg3);
5755 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5756 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5757 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5758 || TREE_CODE (arg2_type) == REAL_TYPE
5759 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5760 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5761 || TREE_CODE (arg3_type) == REAL_TYPE
5762 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5764 semantic_result_type
5765 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5766 if (semantic_result_type == error_mark_node)
5768 tree t1 = arg2_type;
5769 tree t2 = arg3_type;
5770 if (TREE_CODE (t1) == COMPLEX_TYPE)
5771 t1 = TREE_TYPE (t1);
5772 if (TREE_CODE (t2) == COMPLEX_TYPE)
5773 t2 = TREE_TYPE (t2);
5774 gcc_checking_assert (TREE_CODE (t1) == REAL_TYPE
5775 && TREE_CODE (t2) == REAL_TYPE
5776 && (extended_float_type_p (t1)
5777 || extended_float_type_p (t2))
5778 && cp_compare_floating_point_conversion_ranks
5779 (t1, t2) == 3);
5780 if (complain & tf_error)
5781 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5782 "have unordered conversion rank",
5783 arg2_type, arg3_type);
5784 return error_mark_node;
5786 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5788 arg2 = TREE_OPERAND (arg2, 0);
5789 arg2_type = TREE_TYPE (arg2);
5791 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5793 arg3 = TREE_OPERAND (arg3, 0);
5794 arg3_type = TREE_TYPE (arg3);
5798 /* [expr.cond]
5800 If either the second or the third operand has type (possibly
5801 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5802 array-to-pointer (_conv.array_), and function-to-pointer
5803 (_conv.func_) standard conversions are performed on the second
5804 and third operands. */
5805 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5807 /* 'void' won't help in resolving an overloaded expression on the
5808 other side, so require it to resolve by itself. */
5809 if (arg2_type == unknown_type_node)
5811 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5812 arg2_type = TREE_TYPE (arg2);
5814 if (arg3_type == unknown_type_node)
5816 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5817 arg3_type = TREE_TYPE (arg3);
5820 /* [expr.cond]
5822 One of the following shall hold:
5824 --The second or the third operand (but not both) is a
5825 throw-expression (_except.throw_); the result is of the type
5826 and value category of the other.
5828 --Both the second and the third operands have type void; the
5829 result is of type void and is a prvalue. */
5830 if (TREE_CODE (arg2) == THROW_EXPR
5831 && TREE_CODE (arg3) != THROW_EXPR)
5833 result_type = arg3_type;
5834 is_glvalue = glvalue_p (arg3);
5836 else if (TREE_CODE (arg2) != THROW_EXPR
5837 && TREE_CODE (arg3) == THROW_EXPR)
5839 result_type = arg2_type;
5840 is_glvalue = glvalue_p (arg2);
5842 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5844 result_type = void_type_node;
5845 is_glvalue = false;
5847 else
5849 if (complain & tf_error)
5851 if (VOID_TYPE_P (arg2_type))
5852 error_at (cp_expr_loc_or_loc (arg3, loc),
5853 "second operand to the conditional operator "
5854 "is of type %<void%>, but the third operand is "
5855 "neither a throw-expression nor of type %<void%>");
5856 else
5857 error_at (cp_expr_loc_or_loc (arg2, loc),
5858 "third operand to the conditional operator "
5859 "is of type %<void%>, but the second operand is "
5860 "neither a throw-expression nor of type %<void%>");
5862 return error_mark_node;
5865 goto valid_operands;
5867 /* [expr.cond]
5869 Otherwise, if the second and third operand have different types,
5870 and either has (possibly cv-qualified) class type, or if both are
5871 glvalues of the same value category and the same type except for
5872 cv-qualification, an attempt is made to convert each of those operands
5873 to the type of the other. */
5874 else if (!same_type_p (arg2_type, arg3_type)
5875 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5876 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5877 arg3_type)
5878 && glvalue_p (arg2) && glvalue_p (arg3)
5879 && lvalue_p (arg2) == lvalue_p (arg3))))
5881 conversion *conv2;
5882 conversion *conv3;
5883 bool converted = false;
5885 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5886 p = conversion_obstack_alloc (0);
5888 conv2 = conditional_conversion (arg2, arg3, complain);
5889 conv3 = conditional_conversion (arg3, arg2, complain);
5891 /* [expr.cond]
5893 If both can be converted, or one can be converted but the
5894 conversion is ambiguous, the program is ill-formed. If
5895 neither can be converted, the operands are left unchanged and
5896 further checking is performed as described below. If exactly
5897 one conversion is possible, that conversion is applied to the
5898 chosen operand and the converted operand is used in place of
5899 the original operand for the remainder of this section. */
5900 if ((conv2 && !conv2->bad_p
5901 && conv3 && !conv3->bad_p)
5902 || (conv2 && conv2->kind == ck_ambig)
5903 || (conv3 && conv3->kind == ck_ambig))
5905 if (complain & tf_error)
5907 error_at (loc, "operands to %<?:%> have different types "
5908 "%qT and %qT",
5909 arg2_type, arg3_type);
5910 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5911 inform (loc, " and each type can be converted to the other");
5912 else if (conv2 && conv2->kind == ck_ambig)
5913 convert_like (conv2, arg2, complain);
5914 else
5915 convert_like (conv3, arg3, complain);
5917 result = error_mark_node;
5919 else if (conv2 && !conv2->bad_p)
5921 arg2 = convert_like (conv2, arg2, complain);
5922 arg2 = convert_from_reference (arg2);
5923 arg2_type = TREE_TYPE (arg2);
5924 /* Even if CONV2 is a valid conversion, the result of the
5925 conversion may be invalid. For example, if ARG3 has type
5926 "volatile X", and X does not have a copy constructor
5927 accepting a "volatile X&", then even if ARG2 can be
5928 converted to X, the conversion will fail. */
5929 if (error_operand_p (arg2))
5930 result = error_mark_node;
5931 converted = true;
5933 else if (conv3 && !conv3->bad_p)
5935 arg3 = convert_like (conv3, arg3, complain);
5936 arg3 = convert_from_reference (arg3);
5937 arg3_type = TREE_TYPE (arg3);
5938 if (error_operand_p (arg3))
5939 result = error_mark_node;
5940 converted = true;
5943 /* Free all the conversions we allocated. */
5944 obstack_free (&conversion_obstack, p);
5946 if (result)
5947 return result;
5949 /* If, after the conversion, both operands have class type,
5950 treat the cv-qualification of both operands as if it were the
5951 union of the cv-qualification of the operands.
5953 The standard is not clear about what to do in this
5954 circumstance. For example, if the first operand has type
5955 "const X" and the second operand has a user-defined
5956 conversion to "volatile X", what is the type of the second
5957 operand after this step? Making it be "const X" (matching
5958 the first operand) seems wrong, as that discards the
5959 qualification without actually performing a copy. Leaving it
5960 as "volatile X" seems wrong as that will result in the
5961 conditional expression failing altogether, even though,
5962 according to this step, the one operand could be converted to
5963 the type of the other. */
5964 if (converted
5965 && CLASS_TYPE_P (arg2_type)
5966 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5967 arg2_type = arg3_type =
5968 cp_build_qualified_type (arg2_type,
5969 cp_type_quals (arg2_type)
5970 | cp_type_quals (arg3_type));
5973 /* [expr.cond]
5975 If the second and third operands are glvalues of the same value
5976 category and have the same type, the result is of that type and
5977 value category. */
5978 if (((lvalue_p (arg2) && lvalue_p (arg3))
5979 || (xvalue_p (arg2) && xvalue_p (arg3)))
5980 && same_type_p (arg2_type, arg3_type))
5982 result_type = arg2_type;
5983 goto valid_operands;
5986 /* [expr.cond]
5988 Otherwise, the result is an rvalue. If the second and third
5989 operand do not have the same type, and either has (possibly
5990 cv-qualified) class type, overload resolution is used to
5991 determine the conversions (if any) to be applied to the operands
5992 (_over.match.oper_, _over.built_). */
5993 is_glvalue = false;
5994 if (!same_type_p (arg2_type, arg3_type)
5995 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
5997 releasing_vec args;
5998 conversion *conv;
5999 bool any_viable_p;
6001 /* Rearrange the arguments so that add_builtin_candidate only has
6002 to know about two args. In build_builtin_candidate, the
6003 arguments are unscrambled. */
6004 args->quick_push (arg2);
6005 args->quick_push (arg3);
6006 args->quick_push (arg1);
6007 add_builtin_candidates (&candidates,
6008 COND_EXPR,
6009 NOP_EXPR,
6010 ovl_op_identifier (false, COND_EXPR),
6011 args,
6012 LOOKUP_NORMAL, complain);
6014 /* [expr.cond]
6016 If the overload resolution fails, the program is
6017 ill-formed. */
6018 candidates = splice_viable (candidates, false, &any_viable_p);
6019 if (!any_viable_p)
6021 if (complain & tf_error)
6022 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6023 arg2_type, arg3_type);
6024 return error_mark_node;
6026 cand = tourney (candidates, complain);
6027 if (!cand)
6029 if (complain & tf_error)
6031 auto_diagnostic_group d;
6032 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
6033 print_z_candidates (loc, candidates);
6035 return error_mark_node;
6038 /* [expr.cond]
6040 Otherwise, the conversions thus determined are applied, and
6041 the converted operands are used in place of the original
6042 operands for the remainder of this section. */
6043 conv = cand->convs[0];
6044 arg1 = convert_like (conv, arg1, complain);
6045 conv = cand->convs[1];
6046 arg2 = convert_like (conv, arg2, complain);
6047 arg2_type = TREE_TYPE (arg2);
6048 conv = cand->convs[2];
6049 arg3 = convert_like (conv, arg3, complain);
6050 arg3_type = TREE_TYPE (arg3);
6053 /* [expr.cond]
6055 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6056 and function-to-pointer (_conv.func_) standard conversions are
6057 performed on the second and third operands.
6059 We need to force the lvalue-to-rvalue conversion here for class types,
6060 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6061 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6062 regions. */
6064 arg2 = force_rvalue (arg2, complain);
6065 if (!CLASS_TYPE_P (arg2_type))
6066 arg2_type = TREE_TYPE (arg2);
6068 arg3 = force_rvalue (arg3, complain);
6069 if (!CLASS_TYPE_P (arg3_type))
6070 arg3_type = TREE_TYPE (arg3);
6072 if (arg2 == error_mark_node || arg3 == error_mark_node)
6073 return error_mark_node;
6075 /* [expr.cond]
6077 After those conversions, one of the following shall hold:
6079 --The second and third operands have the same type; the result is of
6080 that type. */
6081 if (same_type_p (arg2_type, arg3_type))
6082 result_type = arg2_type;
6083 /* [expr.cond]
6085 --The second and third operands have arithmetic or enumeration
6086 type; the usual arithmetic conversions are performed to bring
6087 them to a common type, and the result is of that type. */
6088 else if ((ARITHMETIC_TYPE_P (arg2_type)
6089 || UNSCOPED_ENUM_P (arg2_type))
6090 && (ARITHMETIC_TYPE_P (arg3_type)
6091 || UNSCOPED_ENUM_P (arg3_type)))
6093 /* A conditional expression between a floating-point
6094 type and an integer type should convert the integer type to
6095 the evaluation format of the floating-point type, with
6096 possible excess precision. */
6097 tree eptype2 = arg2_type;
6098 tree eptype3 = arg3_type;
6099 tree eptype;
6100 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6101 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6103 eptype3 = eptype;
6104 if (!semantic_result_type)
6105 semantic_result_type
6106 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6108 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6109 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6111 eptype2 = eptype;
6112 if (!semantic_result_type)
6113 semantic_result_type
6114 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6116 result_type = type_after_usual_arithmetic_conversions (eptype2,
6117 eptype3);
6118 if (result_type == error_mark_node)
6120 tree t1 = eptype2;
6121 tree t2 = eptype3;
6122 if (TREE_CODE (t1) == COMPLEX_TYPE)
6123 t1 = TREE_TYPE (t1);
6124 if (TREE_CODE (t2) == COMPLEX_TYPE)
6125 t2 = TREE_TYPE (t2);
6126 gcc_checking_assert (TREE_CODE (t1) == REAL_TYPE
6127 && TREE_CODE (t2) == REAL_TYPE
6128 && (extended_float_type_p (t1)
6129 || extended_float_type_p (t2))
6130 && cp_compare_floating_point_conversion_ranks
6131 (t1, t2) == 3);
6132 if (complain & tf_error)
6133 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6134 "have unordered conversion rank",
6135 eptype2, eptype3);
6136 return error_mark_node;
6138 if (semantic_result_type == error_mark_node)
6140 tree t1 = arg2_type;
6141 tree t2 = arg3_type;
6142 if (TREE_CODE (t1) == COMPLEX_TYPE)
6143 t1 = TREE_TYPE (t1);
6144 if (TREE_CODE (t2) == COMPLEX_TYPE)
6145 t2 = TREE_TYPE (t2);
6146 gcc_checking_assert (TREE_CODE (t1) == REAL_TYPE
6147 && TREE_CODE (t2) == REAL_TYPE
6148 && (extended_float_type_p (t1)
6149 || extended_float_type_p (t2))
6150 && cp_compare_floating_point_conversion_ranks
6151 (t1, t2) == 3);
6152 if (complain & tf_error)
6153 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6154 "have unordered conversion rank",
6155 arg2_type, arg3_type);
6156 return error_mark_node;
6159 if (complain & tf_warning)
6160 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6161 "implicit conversion from %qH to %qI to "
6162 "match other result of conditional",
6163 loc);
6165 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6166 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6168 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
6169 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
6170 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6171 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6172 && (DECL_CONTEXT (stripped_orig_arg2)
6173 == DECL_CONTEXT (stripped_orig_arg3)))
6174 /* Two enumerators from the same enumeration can have different
6175 types when the enumeration is still being defined. */;
6176 else if (complain & tf_warning)
6177 warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
6178 "in conditional expression: %qT vs %qT",
6179 arg2_type, arg3_type);
6181 else if ((complain & tf_warning)
6182 && warn_deprecated_enum_float_conv
6183 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6184 && TREE_CODE (arg3_type) == REAL_TYPE)
6185 || (TREE_CODE (arg2_type) == REAL_TYPE
6186 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6188 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6189 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6190 "conditional expression between enumeration type "
6191 "%qT and floating-point type %qT is deprecated",
6192 arg2_type, arg3_type);
6193 else
6194 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6195 "conditional expression between floating-point "
6196 "type %qT and enumeration type %qT is deprecated",
6197 arg2_type, arg3_type);
6199 else if ((extra_warnings || warn_enum_conversion)
6200 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6201 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6202 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6203 && !same_type_p (arg2_type,
6204 type_promotes_to (arg3_type)))))
6206 if (complain & tf_warning)
6208 enum opt_code opt = (warn_enum_conversion
6209 ? OPT_Wenum_conversion
6210 : OPT_Wextra);
6211 warning_at (loc, opt, "enumerated and "
6212 "non-enumerated type in conditional expression");
6216 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6217 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6219 /* [expr.cond]
6221 --The second and third operands have pointer type, or one has
6222 pointer type and the other is a null pointer constant; pointer
6223 conversions (_conv.ptr_) and qualification conversions
6224 (_conv.qual_) are performed to bring them to their composite
6225 pointer type (_expr.rel_). The result is of the composite
6226 pointer type.
6228 --The second and third operands have pointer to member type, or
6229 one has pointer to member type and the other is a null pointer
6230 constant; pointer to member conversions (_conv.mem_) and
6231 qualification conversions (_conv.qual_) are performed to bring
6232 them to a common type, whose cv-qualification shall match the
6233 cv-qualification of either the second or the third operand.
6234 The result is of the common type. */
6235 else if ((null_ptr_cst_p (arg2)
6236 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6237 || (null_ptr_cst_p (arg3)
6238 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6239 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6240 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6241 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6243 result_type = composite_pointer_type (loc,
6244 arg2_type, arg3_type, arg2,
6245 arg3, CPO_CONDITIONAL_EXPR,
6246 complain);
6247 if (result_type == error_mark_node)
6248 return error_mark_node;
6249 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6250 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6253 if (!result_type)
6255 if (complain & tf_error)
6256 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6257 arg2_type, arg3_type);
6258 return error_mark_node;
6261 if (arg2 == error_mark_node || arg3 == error_mark_node)
6262 return error_mark_node;
6264 valid_operands:
6265 if (processing_template_decl && is_glvalue)
6267 /* Let lvalue_kind know this was a glvalue. */
6268 tree arg = (result_type == arg2_type ? arg2 : arg3);
6269 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6272 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
6274 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6275 warn here, because the COND_EXPR will be turned into ARG2. */
6276 if (warn_duplicated_branches
6277 && (complain & tf_warning)
6278 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6279 OEP_ADDRESS_OF_SAME_FIELD)))
6280 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6281 "this condition has identical branches");
6283 /* We can't use result_type below, as fold might have returned a
6284 throw_expr. */
6286 if (!is_glvalue)
6288 /* Expand both sides into the same slot, hopefully the target of
6289 the ?: expression. We used to check for TARGET_EXPRs here,
6290 but now we sometimes wrap them in NOP_EXPRs so the test would
6291 fail. */
6292 if (CLASS_TYPE_P (TREE_TYPE (result)))
6294 result = get_target_expr (result, complain);
6295 /* Tell gimplify_modify_expr_rhs not to strip this in
6296 assignment context: we want both arms to initialize
6297 the same temporary. */
6298 TARGET_EXPR_NO_ELIDE (result) = true;
6300 /* If this expression is an rvalue, but might be mistaken for an
6301 lvalue, we must add a NON_LVALUE_EXPR. */
6302 result = rvalue (result);
6303 if (semantic_result_type)
6304 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6305 result);
6307 else
6309 result = force_paren_expr (result);
6310 gcc_assert (semantic_result_type == NULL_TREE);
6313 return result;
6316 /* OPERAND is an operand to an expression. Perform necessary steps
6317 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6318 returned. */
6320 static tree
6321 prep_operand (tree operand)
6323 if (operand)
6325 if (CLASS_TYPE_P (TREE_TYPE (operand))
6326 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6327 /* Make sure the template type is instantiated now. */
6328 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6331 return operand;
6334 /* True iff CONV represents a conversion sequence which no other can be better
6335 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6336 type (including binding to a reference to the same type). This is stronger
6337 than the standard's "identity" category, which also includes reference
6338 bindings that add cv-qualifiers or change rvalueness. */
6340 static bool
6341 perfect_conversion_p (conversion *conv)
6343 if (CONVERSION_RANK (conv) != cr_identity)
6344 return false;
6345 if (conv->kind == ck_ref_bind)
6347 if (!conv->rvaluedness_matches_p)
6348 return false;
6349 if (!same_type_p (TREE_TYPE (conv->type),
6350 next_conversion (conv)->type))
6351 return false;
6353 if (conv->check_narrowing)
6354 /* Brace elision is imperfect. */
6355 return false;
6356 return true;
6359 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6360 other candidate can be a better match. Since the template/non-template
6361 tiebreaker comes immediately after the conversion comparison in
6362 [over.match.best], a perfect non-template candidate is better than all
6363 templates. */
6365 static bool
6366 perfect_candidate_p (z_candidate *cand)
6368 if (cand->viable < 1)
6369 return false;
6370 /* CWG1402 makes an implicitly deleted move op worse than other
6371 candidates. */
6372 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6373 && move_fn_p (cand->fn))
6374 return false;
6375 int len = cand->num_convs;
6376 for (int i = 0; i < len; ++i)
6377 if (!perfect_conversion_p (cand->convs[i]))
6378 return false;
6379 if (conversion *conv = cand->second_conv)
6380 if (!perfect_conversion_p (conv))
6381 return false;
6382 return true;
6385 /* True iff one of CAND's argument conversions is missing. */
6387 static bool
6388 missing_conversion_p (const z_candidate *cand)
6390 for (unsigned i = 0; i < cand->num_convs; ++i)
6392 conversion *conv = cand->convs[i];
6393 if (!conv)
6394 return true;
6395 if (conv->kind == ck_deferred_bad)
6397 /* We don't know whether this conversion is outright invalid or
6398 just bad, so conservatively assume it's missing. */
6399 gcc_checking_assert (conv->bad_p);
6400 return true;
6403 return false;
6406 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6407 OVERLOAD) to the CANDIDATES, returning an updated list of
6408 CANDIDATES. The ARGS are the arguments provided to the call;
6409 if FIRST_ARG is non-null it is the implicit object argument,
6410 otherwise the first element of ARGS is used if needed. The
6411 EXPLICIT_TARGS are explicit template arguments provided.
6412 TEMPLATE_ONLY is true if only template functions should be
6413 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6414 add_function_candidate. */
6416 static void
6417 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6418 tree return_type,
6419 tree explicit_targs, bool template_only,
6420 tree conversion_path, tree access_path,
6421 int flags,
6422 struct z_candidate **candidates,
6423 tsubst_flags_t complain)
6425 tree ctype;
6426 const vec<tree, va_gc> *non_static_args;
6427 bool check_list_ctor = false;
6428 bool check_converting = false;
6429 unification_kind_t strict;
6430 tree ne_fns = NULL_TREE;
6432 if (!fns)
6433 return;
6435 /* Precalculate special handling of constructors and conversion ops. */
6436 tree fn = OVL_FIRST (fns);
6437 if (DECL_CONV_FN_P (fn))
6439 check_list_ctor = false;
6440 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6441 if (flags & LOOKUP_NO_CONVERSION)
6442 /* We're doing return_type(x). */
6443 strict = DEDUCE_CONV;
6444 else
6445 /* We're doing x.operator return_type(). */
6446 strict = DEDUCE_EXACT;
6447 /* [over.match.funcs] For conversion functions, the function
6448 is considered to be a member of the class of the implicit
6449 object argument for the purpose of defining the type of
6450 the implicit object parameter. */
6451 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6453 else
6455 if (DECL_CONSTRUCTOR_P (fn))
6457 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6458 /* For list-initialization we consider explicit constructors
6459 and complain if one is chosen. */
6460 check_converting
6461 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6462 == LOOKUP_ONLYCONVERTING);
6464 strict = DEDUCE_CALL;
6465 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6468 /* P2468: Check if operator== is a rewrite target with first operand
6469 (*args)[0]; for now just do the lookups. */
6470 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6471 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6473 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6474 if (DECL_CLASS_SCOPE_P (fn))
6476 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6477 1, tf_none);
6478 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6479 ne_fns = NULL_TREE;
6480 else
6481 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6483 else
6485 tree context = decl_namespace_context (fn);
6486 ne_fns = lookup_qualified_name (context, ne_name, LOOK_want::NORMAL,
6487 /*complain*/false);
6488 if (ne_fns == error_mark_node
6489 || !is_overloaded_fn (ne_fns))
6490 ne_fns = NULL_TREE;
6494 if (first_arg)
6495 non_static_args = args;
6496 else
6497 /* Delay creating the implicit this parameter until it is needed. */
6498 non_static_args = NULL;
6500 bool seen_strictly_viable = any_strictly_viable (*candidates);
6501 /* If there's a non-template perfect match, we don't need to consider
6502 templates. So check non-templates first. This optimization is only
6503 really needed for the defaulted copy constructor of tuple and the like
6504 (96926), but it seems like we might as well enable it more generally. */
6505 bool seen_perfect = false;
6506 enum { templates, non_templates, either } which = either;
6507 if (template_only)
6508 which = templates;
6509 else /*if (flags & LOOKUP_DEFAULTED)*/
6510 which = non_templates;
6512 /* During overload resolution, we first consider each function under the
6513 assumption that we'll eventually find a strictly viable candidate.
6514 This allows us to circumvent our defacto behavior when checking
6515 argument conversions and shortcut consideration of the candidate
6516 upon encountering the first bad conversion. If this assumption
6517 turns out to be false, and all candidates end up being non-strictly
6518 viable, then we reconsider such candidates under the defacto behavior.
6519 This trick is important for pruning member function overloads according
6520 to their const/ref-qualifiers (since all 'this' conversions are at
6521 worst bad) without breaking -fpermissive. */
6522 tree bad_fns = NULL_TREE;
6523 bool shortcut_bad_convs = true;
6525 again:
6526 for (tree fn : lkp_range (fns))
6528 if (check_converting && DECL_NONCONVERTING_P (fn))
6529 continue;
6530 if (check_list_ctor && !is_list_ctor (fn))
6531 continue;
6532 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6533 continue;
6534 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6535 continue;
6537 tree fn_first_arg = NULL_TREE;
6538 const vec<tree, va_gc> *fn_args = args;
6540 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6542 /* Figure out where the object arg comes from. If this
6543 function is a non-static member and we didn't get an
6544 implicit object argument, move it out of args. */
6545 if (first_arg == NULL_TREE)
6547 unsigned int ix;
6548 tree arg;
6549 vec<tree, va_gc> *tempvec;
6550 vec_alloc (tempvec, args->length () - 1);
6551 for (ix = 1; args->iterate (ix, &arg); ++ix)
6552 tempvec->quick_push (arg);
6553 non_static_args = tempvec;
6554 first_arg = (*args)[0];
6557 fn_first_arg = first_arg;
6558 fn_args = non_static_args;
6561 /* Don't bother reversing an operator with two identical parameters. */
6562 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6564 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6565 if (same_type_p (TREE_VALUE (parmlist),
6566 TREE_VALUE (TREE_CHAIN (parmlist))))
6567 continue;
6570 /* When considering reversed operator==, if there's a corresponding
6571 operator!= in the same scope, it's not a rewrite target. */
6572 if (ne_fns)
6574 bool found = false;
6575 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6576 if (0 && !ne.using_p ()
6577 && DECL_NAMESPACE_SCOPE_P (fn)
6578 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6579 /* ??? This kludge excludes inline namespace members for the H
6580 test in spaceship-eq15.C, but I don't see why we would want
6581 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6582 else if (fns_correspond (fn, *ne))
6584 found = true;
6585 break;
6587 if (found)
6588 continue;
6591 if (TREE_CODE (fn) == TEMPLATE_DECL)
6593 if (!add_template_candidate (candidates,
6595 ctype,
6596 explicit_targs,
6597 fn_first_arg,
6598 fn_args,
6599 return_type,
6600 access_path,
6601 conversion_path,
6602 flags,
6603 strict,
6604 shortcut_bad_convs,
6605 complain))
6606 continue;
6608 else
6610 add_function_candidate (candidates,
6612 ctype,
6613 fn_first_arg,
6614 fn_args,
6615 access_path,
6616 conversion_path,
6617 flags,
6618 NULL,
6619 shortcut_bad_convs,
6620 complain);
6621 if (perfect_candidate_p (*candidates))
6622 seen_perfect = true;
6625 z_candidate *cand = *candidates;
6626 if (cand->viable == 1)
6627 seen_strictly_viable = true;
6629 if (cand->viable == -1
6630 && shortcut_bad_convs
6631 && missing_conversion_p (cand))
6633 /* This candidate has been tentatively marked non-strictly viable,
6634 and we didn't compute all argument conversions for it (having
6635 stopped at the first bad conversion). Add the function to BAD_FNS
6636 to fully reconsider later if we don't find any strictly viable
6637 candidates. */
6638 if (complain & (tf_error | tf_conv))
6640 bad_fns = lookup_add (fn, bad_fns);
6641 *candidates = (*candidates)->next;
6643 else
6644 /* But if we're in a SFINAE context, just mark this candidate as
6645 unviable outright and avoid potentially reconsidering it.
6646 This is safe to do because in a SFINAE context, performing a bad
6647 conversion is always an error (even with -fpermissive), so a
6648 non-strictly viable candidate is effectively unviable anyway. */
6649 cand->viable = 0;
6652 if (which == non_templates && !seen_perfect)
6654 which = templates;
6655 goto again;
6657 else if (which == templates
6658 && !seen_strictly_viable
6659 && shortcut_bad_convs
6660 && bad_fns)
6662 /* None of the candidates are strictly viable, so consider again those
6663 functions in BAD_FNS, this time without shortcutting bad conversions
6664 so that all their argument conversions are computed. */
6665 which = either;
6666 fns = bad_fns;
6667 shortcut_bad_convs = false;
6668 goto again;
6672 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6673 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6675 static int
6676 op_is_ordered (tree_code code)
6678 switch (code)
6680 // 5. b @= a
6681 case MODIFY_EXPR:
6682 return (flag_strong_eval_order > 1 ? -1 : 0);
6684 // 6. a[b]
6685 case ARRAY_REF:
6686 return (flag_strong_eval_order > 1 ? 1 : 0);
6688 // 1. a.b
6689 // Not overloadable (yet).
6690 // 2. a->b
6691 // Only one argument.
6692 // 3. a->*b
6693 case MEMBER_REF:
6694 // 7. a << b
6695 case LSHIFT_EXPR:
6696 // 8. a >> b
6697 case RSHIFT_EXPR:
6698 // a && b
6699 // Predates P0145R3.
6700 case TRUTH_ANDIF_EXPR:
6701 // a || b
6702 // Predates P0145R3.
6703 case TRUTH_ORIF_EXPR:
6704 // a , b
6705 // Predates P0145R3.
6706 case COMPOUND_EXPR:
6707 return (flag_strong_eval_order ? 1 : 0);
6709 default:
6710 return 0;
6714 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6715 operator indicated by CODE/CODE2. This function calls itself recursively to
6716 handle C++20 rewritten comparison operator candidates.
6718 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6719 overloads to consider. This parameter is used when instantiating a
6720 dependent operator expression and has the same structure as
6721 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6723 static tree
6724 add_operator_candidates (z_candidate **candidates,
6725 tree_code code, tree_code code2,
6726 vec<tree, va_gc> *arglist, tree lookups,
6727 int flags, tsubst_flags_t complain)
6729 z_candidate *start_candidates = *candidates;
6730 bool ismodop = code2 != ERROR_MARK;
6731 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6733 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6734 rewrite from, and also when we're looking for the e.g. < operator to use
6735 on the result of <=>. In the latter case, we don't want the flag set in
6736 the candidate, we just want to suppress looking for rewrites. */
6737 bool rewritten = (flags & LOOKUP_REWRITTEN);
6738 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6739 flags &= ~LOOKUP_REWRITTEN;
6741 bool memonly = false;
6742 switch (code)
6744 /* =, ->, [], () must be non-static member functions. */
6745 case MODIFY_EXPR:
6746 if (code2 != NOP_EXPR)
6747 break;
6748 /* FALLTHRU */
6749 case COMPONENT_REF:
6750 case ARRAY_REF:
6751 memonly = true;
6752 break;
6754 default:
6755 break;
6758 /* Add namespace-scope operators to the list of functions to
6759 consider. */
6760 if (!memonly)
6762 tree fns;
6763 if (!lookups)
6764 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6765 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6766 expression, and LOOKUPS is the result of stage 1 name lookup. */
6767 else if (tree found = purpose_member (fnname, lookups))
6768 fns = TREE_VALUE (found);
6769 else
6770 fns = NULL_TREE;
6771 fns = lookup_arg_dependent (fnname, fns, arglist);
6772 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6773 NULL_TREE, false, NULL_TREE, NULL_TREE,
6774 flags, candidates, complain);
6777 /* Add class-member operators to the candidate set. */
6778 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6779 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6780 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6781 if (CLASS_TYPE_P (arg1_type))
6783 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6784 if (fns == error_mark_node)
6785 return error_mark_node;
6786 if (fns)
6788 if (code == ARRAY_REF)
6790 vec<tree,va_gc> *restlist = make_tree_vector ();
6791 for (unsigned i = 1; i < nargs; ++i)
6792 vec_safe_push (restlist, (*arglist)[i]);
6793 z_candidate *save_cand = *candidates;
6794 add_candidates (BASELINK_FUNCTIONS (fns),
6795 (*arglist)[0], restlist, NULL_TREE,
6796 NULL_TREE, false,
6797 BASELINK_BINFO (fns),
6798 BASELINK_ACCESS_BINFO (fns),
6799 flags, candidates, complain);
6800 /* Release the vec if we didn't add a candidate that uses it. */
6801 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6802 if (c->args == restlist)
6804 restlist = NULL;
6805 break;
6807 release_tree_vector (restlist);
6809 else
6810 add_candidates (BASELINK_FUNCTIONS (fns),
6811 NULL_TREE, arglist, NULL_TREE,
6812 NULL_TREE, false,
6813 BASELINK_BINFO (fns),
6814 BASELINK_ACCESS_BINFO (fns),
6815 flags, candidates, complain);
6818 /* Per [over.match.oper]3.2, if no operand has a class type, then
6819 only non-member functions that have type T1 or reference to
6820 cv-qualified-opt T1 for the first argument, if the first argument
6821 has an enumeration type, or T2 or reference to cv-qualified-opt
6822 T2 for the second argument, if the second argument has an
6823 enumeration type. Filter out those that don't match. */
6824 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6826 struct z_candidate **candp, **next;
6828 for (candp = candidates; *candp != start_candidates; candp = next)
6830 unsigned i;
6831 z_candidate *cand = *candp;
6832 next = &cand->next;
6834 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6836 for (i = 0; i < nargs; ++i)
6838 tree parmtype = TREE_VALUE (parmlist);
6839 tree argtype = unlowered_expr_type ((*arglist)[i]);
6841 if (TYPE_REF_P (parmtype))
6842 parmtype = TREE_TYPE (parmtype);
6843 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6844 && (same_type_ignoring_top_level_qualifiers_p
6845 (argtype, parmtype)))
6846 break;
6848 parmlist = TREE_CHAIN (parmlist);
6851 /* No argument has an appropriate type, so remove this
6852 candidate function from the list. */
6853 if (i == nargs)
6855 *candp = cand->next;
6856 next = candp;
6861 if (!rewritten)
6863 /* The standard says to rewrite built-in candidates, too,
6864 but there's no point. */
6865 add_builtin_candidates (candidates, code, code2, fnname, arglist,
6866 flags, complain);
6868 /* Maybe add C++20 rewritten comparison candidates. */
6869 tree_code rewrite_code = ERROR_MARK;
6870 if (cxx_dialect >= cxx20
6871 && nargs == 2
6872 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6873 switch (code)
6875 case LT_EXPR:
6876 case LE_EXPR:
6877 case GT_EXPR:
6878 case GE_EXPR:
6879 case SPACESHIP_EXPR:
6880 rewrite_code = SPACESHIP_EXPR;
6881 break;
6883 case NE_EXPR:
6884 case EQ_EXPR:
6885 rewrite_code = EQ_EXPR;
6886 break;
6888 default:;
6891 if (rewrite_code)
6893 flags |= LOOKUP_REWRITTEN;
6894 if (rewrite_code != code)
6895 /* Add rewritten candidates in same order. */
6896 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6897 arglist, lookups, flags, complain);
6899 z_candidate *save_cand = *candidates;
6901 /* Add rewritten candidates in reverse order. */
6902 flags |= LOOKUP_REVERSED;
6903 vec<tree,va_gc> *revlist = make_tree_vector ();
6904 revlist->quick_push ((*arglist)[1]);
6905 revlist->quick_push ((*arglist)[0]);
6906 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6907 revlist, lookups, flags, complain);
6909 /* Release the vec if we didn't add a candidate that uses it. */
6910 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6911 if (c->args == revlist)
6913 revlist = NULL;
6914 break;
6916 release_tree_vector (revlist);
6920 return NULL_TREE;
6923 tree
6924 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6925 tree arg1, tree arg2, tree arg3, tree lookups,
6926 tree *overload, tsubst_flags_t complain)
6928 struct z_candidate *candidates = 0, *cand;
6929 releasing_vec arglist;
6930 tree result = NULL_TREE;
6931 bool result_valid_p = false;
6932 enum tree_code code2 = ERROR_MARK;
6933 enum tree_code code_orig_arg1 = ERROR_MARK;
6934 enum tree_code code_orig_arg2 = ERROR_MARK;
6935 void *p;
6936 bool strict_p;
6937 bool any_viable_p;
6939 auto_cond_timevar tv (TV_OVERLOAD);
6941 if (error_operand_p (arg1)
6942 || error_operand_p (arg2)
6943 || error_operand_p (arg3))
6944 return error_mark_node;
6946 bool ismodop = code == MODIFY_EXPR;
6947 if (ismodop)
6949 code2 = TREE_CODE (arg3);
6950 arg3 = NULL_TREE;
6953 tree arg1_type = unlowered_expr_type (arg1);
6954 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6956 arg1 = prep_operand (arg1);
6958 switch (code)
6960 case NEW_EXPR:
6961 case VEC_NEW_EXPR:
6962 case VEC_DELETE_EXPR:
6963 case DELETE_EXPR:
6964 /* Use build_operator_new_call and build_op_delete_call instead. */
6965 gcc_unreachable ();
6967 case CALL_EXPR:
6968 /* Use build_op_call instead. */
6969 gcc_unreachable ();
6971 case TRUTH_ORIF_EXPR:
6972 case TRUTH_ANDIF_EXPR:
6973 case TRUTH_AND_EXPR:
6974 case TRUTH_OR_EXPR:
6975 /* These are saved for the sake of warn_logical_operator. */
6976 code_orig_arg1 = TREE_CODE (arg1);
6977 code_orig_arg2 = TREE_CODE (arg2);
6978 break;
6979 case GT_EXPR:
6980 case LT_EXPR:
6981 case GE_EXPR:
6982 case LE_EXPR:
6983 case EQ_EXPR:
6984 case NE_EXPR:
6985 /* These are saved for the sake of maybe_warn_bool_compare. */
6986 code_orig_arg1 = TREE_CODE (arg1_type);
6987 code_orig_arg2 = TREE_CODE (arg2_type);
6988 break;
6990 default:
6991 break;
6994 arg2 = prep_operand (arg2);
6995 arg3 = prep_operand (arg3);
6997 if (code == COND_EXPR)
6998 /* Use build_conditional_expr instead. */
6999 gcc_unreachable ();
7000 else if (! OVERLOAD_TYPE_P (arg1_type)
7001 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7002 goto builtin;
7004 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7006 arg2 = integer_zero_node;
7007 arg2_type = integer_type_node;
7010 arglist->quick_push (arg1);
7011 if (arg2 != NULL_TREE)
7012 arglist->quick_push (arg2);
7013 if (arg3 != NULL_TREE)
7014 arglist->quick_push (arg3);
7016 /* Get the high-water mark for the CONVERSION_OBSTACK. */
7017 p = conversion_obstack_alloc (0);
7019 result = add_operator_candidates (&candidates, code, code2, arglist,
7020 lookups, flags, complain);
7021 if (result == error_mark_node)
7022 goto user_defined_result_ready;
7024 switch (code)
7026 case COMPOUND_EXPR:
7027 case ADDR_EXPR:
7028 /* For these, the built-in candidates set is empty
7029 [over.match.oper]/3. We don't want non-strict matches
7030 because exact matches are always possible with built-in
7031 operators. The built-in candidate set for COMPONENT_REF
7032 would be empty too, but since there are no such built-in
7033 operators, we accept non-strict matches for them. */
7034 strict_p = true;
7035 break;
7037 default:
7038 strict_p = false;
7039 break;
7042 candidates = splice_viable (candidates, strict_p, &any_viable_p);
7043 if (!any_viable_p)
7045 switch (code)
7047 case POSTINCREMENT_EXPR:
7048 case POSTDECREMENT_EXPR:
7049 /* Don't try anything fancy if we're not allowed to produce
7050 errors. */
7051 if (!(complain & tf_error))
7052 return error_mark_node;
7054 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7055 distinguish between prefix and postfix ++ and
7056 operator++() was used for both, so we allow this with
7057 -fpermissive. */
7058 else
7060 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7061 const char *msg = (flag_permissive)
7062 ? G_("no %<%D(int)%> declared for postfix %qs,"
7063 " trying prefix operator instead")
7064 : G_("no %<%D(int)%> declared for postfix %qs");
7065 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7068 if (!flag_permissive)
7069 return error_mark_node;
7071 if (code == POSTINCREMENT_EXPR)
7072 code = PREINCREMENT_EXPR;
7073 else
7074 code = PREDECREMENT_EXPR;
7075 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7076 NULL_TREE, lookups, overload, complain);
7077 break;
7079 /* The caller will deal with these. */
7080 case ADDR_EXPR:
7081 case COMPOUND_EXPR:
7082 case COMPONENT_REF:
7083 case CO_AWAIT_EXPR:
7084 result = NULL_TREE;
7085 result_valid_p = true;
7086 break;
7088 default:
7089 if (complain & tf_error)
7091 /* If one of the arguments of the operator represents
7092 an invalid use of member function pointer, try to report
7093 a meaningful error ... */
7094 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7095 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7096 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7097 /* We displayed the error message. */;
7098 else
7100 /* ... Otherwise, report the more generic
7101 "no matching operator found" error */
7102 auto_diagnostic_group d;
7103 op_error (loc, code, code2, arg1, arg2, arg3, FALSE);
7104 print_z_candidates (loc, candidates);
7107 result = error_mark_node;
7108 break;
7111 else
7113 cand = tourney (candidates, complain);
7114 if (cand == 0)
7116 if (complain & tf_error)
7118 auto_diagnostic_group d;
7119 op_error (loc, code, code2, arg1, arg2, arg3, TRUE);
7120 print_z_candidates (loc, candidates);
7122 result = error_mark_node;
7123 if (overload)
7124 *overload = error_mark_node;
7126 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7128 if (overload)
7129 *overload = cand->fn;
7131 if (resolve_args (arglist, complain) == NULL)
7132 result = error_mark_node;
7133 else
7135 tsubst_flags_t ocomplain = complain;
7136 if (cand->rewritten ())
7137 /* We'll wrap this call in another one. */
7138 ocomplain &= ~tf_decltype;
7139 if (cand->reversed ())
7141 /* We swapped these in add_candidate, swap them back now. */
7142 std::swap (cand->convs[0], cand->convs[1]);
7143 if (cand->fn == current_function_decl)
7144 warning_at (loc, 0, "in C++20 this comparison calls the "
7145 "current function recursively with reversed "
7146 "arguments");
7148 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7151 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7152 /* There won't be a CALL_EXPR. */;
7153 else if (result && result != error_mark_node)
7155 tree call = extract_call_expr (result);
7156 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7158 /* Specify evaluation order as per P0145R2. */
7159 CALL_EXPR_ORDERED_ARGS (call) = false;
7160 switch (op_is_ordered (code))
7162 case -1:
7163 CALL_EXPR_REVERSE_ARGS (call) = true;
7164 break;
7166 case 1:
7167 CALL_EXPR_ORDERED_ARGS (call) = true;
7168 break;
7170 default:
7171 break;
7175 /* If this was a C++20 rewritten comparison, adjust the result. */
7176 if (cand->rewritten ())
7178 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7179 if (overload)
7180 *overload = NULL_TREE;
7181 switch (code)
7183 case EQ_EXPR:
7184 gcc_checking_assert (cand->reversed ());
7185 gcc_fallthrough ();
7186 case NE_EXPR:
7187 if (result == error_mark_node)
7189 /* If a rewritten operator== candidate is selected by
7190 overload resolution for an operator @, its return type
7191 shall be cv bool.... */
7192 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7194 if (complain & tf_error)
7196 auto_diagnostic_group d;
7197 error_at (loc, "return type of %qD is not %qs",
7198 cand->fn, "bool");
7199 inform (loc, "used as rewritten candidate for "
7200 "comparison of %qT and %qT",
7201 arg1_type, arg2_type);
7203 result = error_mark_node;
7205 else if (code == NE_EXPR)
7206 /* !(y == x) or !(x == y) */
7207 result = build1_loc (loc, TRUTH_NOT_EXPR,
7208 boolean_type_node, result);
7209 break;
7211 /* If a rewritten operator<=> candidate is selected by
7212 overload resolution for an operator @, x @ y is
7213 interpreted as 0 @ (y <=> x) if the selected candidate is
7214 a synthesized candidate with reversed order of parameters,
7215 or (x <=> y) @ 0 otherwise, using the selected rewritten
7216 operator<=> candidate. */
7217 case SPACESHIP_EXPR:
7218 if (!cand->reversed ())
7219 /* We're in the build_new_op call below for an outer
7220 reversed call; we don't need to do anything more. */
7221 break;
7222 gcc_fallthrough ();
7223 case LT_EXPR:
7224 case LE_EXPR:
7225 case GT_EXPR:
7226 case GE_EXPR:
7228 tree lhs = result;
7229 tree rhs = integer_zero_node;
7230 if (cand->reversed ())
7231 std::swap (lhs, rhs);
7232 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7233 result = build_new_op (loc, code,
7234 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7235 lhs, rhs, NULL_TREE, lookups,
7236 NULL, complain);
7238 break;
7240 default:
7241 gcc_unreachable ();
7245 /* In an expression of the form `a[]' where cand->fn
7246 which is operator[] turns out to be a static member function,
7247 `a' is none-the-less evaluated. */
7248 if (code == ARRAY_REF)
7249 result = keep_unused_object_arg (result, arg1, cand->fn);
7251 else
7253 /* Give any warnings we noticed during overload resolution. */
7254 if (cand->warnings && (complain & tf_warning))
7256 struct candidate_warning *w;
7257 for (w = cand->warnings; w; w = w->next)
7258 joust (cand, w->loser, 1, complain);
7261 /* Check for comparison of different enum types. */
7262 switch (code)
7264 case GT_EXPR:
7265 case LT_EXPR:
7266 case GE_EXPR:
7267 case LE_EXPR:
7268 case EQ_EXPR:
7269 case NE_EXPR:
7270 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7271 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7272 && (TYPE_MAIN_VARIANT (arg1_type)
7273 != TYPE_MAIN_VARIANT (arg2_type))
7274 && (complain & tf_warning))
7275 warning_at (loc, OPT_Wenum_compare,
7276 "comparison between %q#T and %q#T",
7277 arg1_type, arg2_type);
7278 break;
7279 default:
7280 break;
7283 /* "If a built-in candidate is selected by overload resolution, the
7284 operands of class type are converted to the types of the
7285 corresponding parameters of the selected operation function,
7286 except that the second standard conversion sequence of a
7287 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7288 conversion *conv = cand->convs[0];
7289 if (conv->user_conv_p)
7291 conv = strip_standard_conversion (conv);
7292 arg1 = convert_like (conv, arg1, complain);
7295 if (arg2)
7297 conv = cand->convs[1];
7298 if (conv->user_conv_p)
7300 conv = strip_standard_conversion (conv);
7301 arg2 = convert_like (conv, arg2, complain);
7305 if (arg3)
7307 conv = cand->convs[2];
7308 if (conv->user_conv_p)
7310 conv = strip_standard_conversion (conv);
7311 arg3 = convert_like (conv, arg3, complain);
7317 user_defined_result_ready:
7319 /* Free all the conversions we allocated. */
7320 obstack_free (&conversion_obstack, p);
7322 if (result || result_valid_p)
7323 return result;
7325 builtin:
7326 switch (code)
7328 case MODIFY_EXPR:
7329 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7331 case INDIRECT_REF:
7332 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7334 case TRUTH_ANDIF_EXPR:
7335 case TRUTH_ORIF_EXPR:
7336 case TRUTH_AND_EXPR:
7337 case TRUTH_OR_EXPR:
7338 if ((complain & tf_warning) && !processing_template_decl)
7339 warn_logical_operator (loc, code, boolean_type_node,
7340 code_orig_arg1, arg1,
7341 code_orig_arg2, arg2);
7342 /* Fall through. */
7343 case GT_EXPR:
7344 case LT_EXPR:
7345 case GE_EXPR:
7346 case LE_EXPR:
7347 case EQ_EXPR:
7348 case NE_EXPR:
7349 if ((complain & tf_warning)
7350 && ((code_orig_arg1 == BOOLEAN_TYPE)
7351 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7352 maybe_warn_bool_compare (loc, code, arg1, arg2);
7353 if (complain & tf_warning && warn_tautological_compare)
7354 warn_tautological_cmp (loc, code, arg1, arg2);
7355 /* Fall through. */
7356 case SPACESHIP_EXPR:
7357 case PLUS_EXPR:
7358 case MINUS_EXPR:
7359 case MULT_EXPR:
7360 case TRUNC_DIV_EXPR:
7361 case MAX_EXPR:
7362 case MIN_EXPR:
7363 case LSHIFT_EXPR:
7364 case RSHIFT_EXPR:
7365 case TRUNC_MOD_EXPR:
7366 case BIT_AND_EXPR:
7367 case BIT_IOR_EXPR:
7368 case BIT_XOR_EXPR:
7369 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7371 case UNARY_PLUS_EXPR:
7372 case NEGATE_EXPR:
7373 case BIT_NOT_EXPR:
7374 case TRUTH_NOT_EXPR:
7375 case PREINCREMENT_EXPR:
7376 case POSTINCREMENT_EXPR:
7377 case PREDECREMENT_EXPR:
7378 case POSTDECREMENT_EXPR:
7379 case REALPART_EXPR:
7380 case IMAGPART_EXPR:
7381 case ABS_EXPR:
7382 case CO_AWAIT_EXPR:
7383 return cp_build_unary_op (code, arg1, false, complain);
7385 case ARRAY_REF:
7386 return cp_build_array_ref (input_location, arg1, arg2, complain);
7388 case MEMBER_REF:
7389 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7390 RO_ARROW_STAR,
7391 complain),
7392 arg2, complain);
7394 /* The caller will deal with these. */
7395 case ADDR_EXPR:
7396 case COMPONENT_REF:
7397 case COMPOUND_EXPR:
7398 return NULL_TREE;
7400 default:
7401 gcc_unreachable ();
7403 return NULL_TREE;
7406 /* Build a new call to operator[]. This may change ARGS. */
7408 tree
7409 build_op_subscript (const op_location_t &loc, tree obj,
7410 vec<tree, va_gc> **args, tree *overload,
7411 tsubst_flags_t complain)
7413 struct z_candidate *candidates = 0, *cand;
7414 tree fns, first_mem_arg = NULL_TREE;
7415 bool any_viable_p;
7416 tree result = NULL_TREE;
7417 void *p;
7419 auto_cond_timevar tv (TV_OVERLOAD);
7421 obj = mark_lvalue_use (obj);
7423 if (error_operand_p (obj))
7424 return error_mark_node;
7426 tree type = TREE_TYPE (obj);
7428 obj = prep_operand (obj);
7430 if (TYPE_BINFO (type))
7432 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7433 1, complain);
7434 if (fns == error_mark_node)
7435 return error_mark_node;
7437 else
7438 fns = NULL_TREE;
7440 if (args != NULL && *args != NULL)
7442 *args = resolve_args (*args, complain);
7443 if (*args == NULL)
7444 return error_mark_node;
7447 /* Get the high-water mark for the CONVERSION_OBSTACK. */
7448 p = conversion_obstack_alloc (0);
7450 if (fns)
7452 first_mem_arg = obj;
7454 add_candidates (BASELINK_FUNCTIONS (fns),
7455 first_mem_arg, *args, NULL_TREE,
7456 NULL_TREE, false,
7457 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7458 LOOKUP_NORMAL, &candidates, complain);
7461 /* Be strict here because if we choose a bad conversion candidate, the
7462 errors we get won't mention the call context. */
7463 candidates = splice_viable (candidates, true, &any_viable_p);
7464 if (!any_viable_p)
7466 if (complain & tf_error)
7468 auto_diagnostic_group d;
7469 error ("no match for call to %<%T::operator[] (%A)%>",
7470 TREE_TYPE (obj), build_tree_list_vec (*args));
7471 print_z_candidates (loc, candidates);
7473 result = error_mark_node;
7475 else
7477 cand = tourney (candidates, complain);
7478 if (cand == 0)
7480 if (complain & tf_error)
7482 auto_diagnostic_group d;
7483 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7484 TREE_TYPE (obj), build_tree_list_vec (*args));
7485 print_z_candidates (loc, candidates);
7487 result = error_mark_node;
7489 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7490 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7491 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7493 if (overload)
7494 *overload = cand->fn;
7495 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7496 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7497 /* There won't be a CALL_EXPR. */;
7498 else if (result && result != error_mark_node)
7500 tree call = extract_call_expr (result);
7501 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7503 /* Specify evaluation order as per P0145R2. */
7504 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7507 /* In an expression of the form `a[]' where cand->fn
7508 which is operator[] turns out to be a static member function,
7509 `a' is none-the-less evaluated. */
7510 result = keep_unused_object_arg (result, obj, cand->fn);
7512 else
7513 gcc_unreachable ();
7516 /* Free all the conversions we allocated. */
7517 obstack_free (&conversion_obstack, p);
7519 return result;
7522 /* CALL was returned by some call-building function; extract the actual
7523 CALL_EXPR from any bits that have been tacked on, e.g. by
7524 convert_from_reference. */
7526 tree
7527 extract_call_expr (tree call)
7529 while (TREE_CODE (call) == COMPOUND_EXPR)
7530 call = TREE_OPERAND (call, 1);
7531 if (REFERENCE_REF_P (call))
7532 call = TREE_OPERAND (call, 0);
7533 if (TREE_CODE (call) == TARGET_EXPR)
7534 call = TARGET_EXPR_INITIAL (call);
7535 if (cxx_dialect >= cxx20)
7536 switch (TREE_CODE (call))
7538 /* C++20 rewritten comparison operators. */
7539 case TRUTH_NOT_EXPR:
7540 call = TREE_OPERAND (call, 0);
7541 break;
7542 case LT_EXPR:
7543 case LE_EXPR:
7544 case GT_EXPR:
7545 case GE_EXPR:
7546 case SPACESHIP_EXPR:
7548 tree op0 = TREE_OPERAND (call, 0);
7549 if (integer_zerop (op0))
7550 call = TREE_OPERAND (call, 1);
7551 else
7552 call = op0;
7554 break;
7555 default:;
7558 if (TREE_CODE (call) != CALL_EXPR
7559 && TREE_CODE (call) != AGGR_INIT_EXPR
7560 && call != error_mark_node)
7561 return NULL_TREE;
7562 return call;
7565 /* Returns true if FN has two parameters, of which the second has type
7566 size_t. */
7568 static bool
7569 second_parm_is_size_t (tree fn)
7571 tree t = FUNCTION_ARG_CHAIN (fn);
7572 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7573 return false;
7574 t = TREE_CHAIN (t);
7575 if (t == void_list_node)
7576 return true;
7577 return false;
7580 /* True if T, an allocation function, has std::align_val_t as its second
7581 argument. */
7583 bool
7584 aligned_allocation_fn_p (tree t)
7586 if (!aligned_new_threshold)
7587 return false;
7589 tree a = FUNCTION_ARG_CHAIN (t);
7590 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7593 /* True if T is std::destroying_delete_t. */
7595 static bool
7596 std_destroying_delete_t_p (tree t)
7598 return (TYPE_CONTEXT (t) == std_node
7599 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7602 /* A deallocation function with at least two parameters whose second parameter
7603 type is of type std::destroying_delete_t is a destroying operator delete. A
7604 destroying operator delete shall be a class member function named operator
7605 delete. [ Note: Array deletion cannot use a destroying operator
7606 delete. --end note ] */
7608 tree
7609 destroying_delete_p (tree t)
7611 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7612 if (!a || !TREE_CHAIN (a))
7613 return NULL_TREE;
7614 tree type = TREE_VALUE (TREE_CHAIN (a));
7615 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7618 struct dealloc_info
7620 bool sized;
7621 bool aligned;
7622 tree destroying;
7625 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7626 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7627 non-null, also set *DI. */
7629 static bool
7630 usual_deallocation_fn_p (tree t, dealloc_info *di)
7632 if (di) *di = dealloc_info();
7634 /* A template instance is never a usual deallocation function,
7635 regardless of its signature. */
7636 if (TREE_CODE (t) == TEMPLATE_DECL
7637 || primary_template_specialization_p (t))
7638 return false;
7640 /* A usual deallocation function is a deallocation function whose parameters
7641 after the first are
7642 - optionally, a parameter of type std::destroying_delete_t, then
7643 - optionally, a parameter of type std::size_t, then
7644 - optionally, a parameter of type std::align_val_t. */
7645 bool global = DECL_NAMESPACE_SCOPE_P (t);
7646 tree chain = FUNCTION_ARG_CHAIN (t);
7647 if (chain && destroying_delete_p (t))
7649 if (di) di->destroying = TREE_VALUE (chain);
7650 chain = TREE_CHAIN (chain);
7652 if (chain
7653 && (!global || flag_sized_deallocation)
7654 && same_type_p (TREE_VALUE (chain), size_type_node))
7656 if (di) di->sized = true;
7657 chain = TREE_CHAIN (chain);
7659 if (chain && aligned_new_threshold
7660 && same_type_p (TREE_VALUE (chain), align_type_node))
7662 if (di) di->aligned = true;
7663 chain = TREE_CHAIN (chain);
7665 return (chain == void_list_node);
7668 /* Just return whether FN is a usual deallocation function. */
7670 bool
7671 usual_deallocation_fn_p (tree fn)
7673 return usual_deallocation_fn_p (fn, NULL);
7676 /* Build a call to operator delete. This has to be handled very specially,
7677 because the restrictions on what signatures match are different from all
7678 other call instances. For a normal delete, only a delete taking (void *)
7679 or (void *, size_t) is accepted. For a placement delete, only an exact
7680 match with the placement new is accepted.
7682 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7683 ADDR is the pointer to be deleted.
7684 SIZE is the size of the memory block to be deleted.
7685 GLOBAL_P is true if the delete-expression should not consider
7686 class-specific delete operators.
7687 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7689 If this call to "operator delete" is being generated as part to
7690 deallocate memory allocated via a new-expression (as per [expr.new]
7691 which requires that if the initialization throws an exception then
7692 we call a deallocation function), then ALLOC_FN is the allocation
7693 function. */
7695 tree
7696 build_op_delete_call (enum tree_code code, tree addr, tree size,
7697 bool global_p, tree placement,
7698 tree alloc_fn, tsubst_flags_t complain)
7700 tree fn = NULL_TREE;
7701 tree fns, fnname, type, t;
7702 dealloc_info di_fn = { };
7704 if (addr == error_mark_node)
7705 return error_mark_node;
7707 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7709 fnname = ovl_op_identifier (false, code);
7711 if (CLASS_TYPE_P (type)
7712 && COMPLETE_TYPE_P (complete_type (type))
7713 && !global_p)
7714 /* In [class.free]
7716 If the result of the lookup is ambiguous or inaccessible, or if
7717 the lookup selects a placement deallocation function, the
7718 program is ill-formed.
7720 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7722 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7723 if (fns == error_mark_node)
7724 return error_mark_node;
7726 else
7727 fns = NULL_TREE;
7729 if (fns == NULL_TREE)
7730 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7732 /* Strip const and volatile from addr. */
7733 tree oaddr = addr;
7734 addr = cp_convert (ptr_type_node, addr, complain);
7736 tree excluded_destroying = NULL_TREE;
7738 if (placement)
7740 /* "A declaration of a placement deallocation function matches the
7741 declaration of a placement allocation function if it has the same
7742 number of parameters and, after parameter transformations (8.3.5),
7743 all parameter types except the first are identical."
7745 So we build up the function type we want and ask instantiate_type
7746 to get it for us. */
7747 t = FUNCTION_ARG_CHAIN (alloc_fn);
7748 t = tree_cons (NULL_TREE, ptr_type_node, t);
7749 t = build_function_type (void_type_node, t);
7751 fn = instantiate_type (t, fns, tf_none);
7752 if (fn == error_mark_node)
7753 return NULL_TREE;
7755 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7757 /* "If the lookup finds the two-parameter form of a usual deallocation
7758 function (3.7.4.2) and that function, considered as a placement
7759 deallocation function, would have been selected as a match for the
7760 allocation function, the program is ill-formed." */
7761 if (second_parm_is_size_t (fn))
7763 const char *const msg1
7764 = G_("exception cleanup for this placement new selects "
7765 "non-placement %<operator delete%>");
7766 const char *const msg2
7767 = G_("%qD is a usual (non-placement) deallocation "
7768 "function in C++14 (or with %<-fsized-deallocation%>)");
7770 /* But if the class has an operator delete (void *), then that is
7771 the usual deallocation function, so we shouldn't complain
7772 about using the operator delete (void *, size_t). */
7773 if (DECL_CLASS_SCOPE_P (fn))
7774 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7776 if (usual_deallocation_fn_p (elt)
7777 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7778 goto ok;
7780 /* Before C++14 a two-parameter global deallocation function is
7781 always a placement deallocation function, but warn if
7782 -Wc++14-compat. */
7783 else if (!flag_sized_deallocation)
7785 if (complain & tf_warning)
7787 auto_diagnostic_group d;
7788 if (warning (OPT_Wc__14_compat, msg1))
7789 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7791 goto ok;
7794 if (complain & tf_warning_or_error)
7796 auto_diagnostic_group d;
7797 if (permerror (input_location, msg1))
7799 /* Only mention C++14 for namespace-scope delete. */
7800 if (DECL_NAMESPACE_SCOPE_P (fn))
7801 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7802 else
7803 inform (DECL_SOURCE_LOCATION (fn),
7804 "%qD is a usual (non-placement) deallocation "
7805 "function", fn);
7808 else
7809 return error_mark_node;
7810 ok:;
7813 else
7814 /* "Any non-placement deallocation function matches a non-placement
7815 allocation function. If the lookup finds a single matching
7816 deallocation function, that function will be called; otherwise, no
7817 deallocation function will be called." */
7818 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7820 dealloc_info di_elt;
7821 if (usual_deallocation_fn_p (elt, &di_elt))
7823 /* If we're called for an EH cleanup in a new-expression, we can't
7824 use a destroying delete; the exception was thrown before the
7825 object was constructed. */
7826 if (alloc_fn && di_elt.destroying)
7828 excluded_destroying = elt;
7829 continue;
7832 if (!fn)
7834 fn = elt;
7835 di_fn = di_elt;
7836 continue;
7839 /* -- If any of the deallocation functions is a destroying
7840 operator delete, all deallocation functions that are not
7841 destroying operator deletes are eliminated from further
7842 consideration. */
7843 if (di_elt.destroying != di_fn.destroying)
7845 if (di_elt.destroying)
7847 fn = elt;
7848 di_fn = di_elt;
7850 continue;
7853 /* -- If the type has new-extended alignment, a function with a
7854 parameter of type std::align_val_t is preferred; otherwise a
7855 function without such a parameter is preferred. If exactly one
7856 preferred function is found, that function is selected and the
7857 selection process terminates. If more than one preferred
7858 function is found, all non-preferred functions are eliminated
7859 from further consideration. */
7860 if (aligned_new_threshold)
7862 bool want_align = type_has_new_extended_alignment (type);
7863 if (di_elt.aligned != di_fn.aligned)
7865 if (want_align == di_elt.aligned)
7867 fn = elt;
7868 di_fn = di_elt;
7870 continue;
7874 /* -- If the deallocation functions have class scope, the one
7875 without a parameter of type std::size_t is selected. */
7876 bool want_size;
7877 if (DECL_CLASS_SCOPE_P (fn))
7878 want_size = false;
7880 /* -- If the type is complete and if, for the second alternative
7881 (delete array) only, the operand is a pointer to a class type
7882 with a non-trivial destructor or a (possibly multi-dimensional)
7883 array thereof, the function with a parameter of type std::size_t
7884 is selected.
7886 -- Otherwise, it is unspecified whether a deallocation function
7887 with a parameter of type std::size_t is selected. */
7888 else
7890 want_size = COMPLETE_TYPE_P (type);
7891 if (code == VEC_DELETE_EXPR
7892 && !TYPE_VEC_NEW_USES_COOKIE (type))
7893 /* We need a cookie to determine the array size. */
7894 want_size = false;
7896 gcc_assert (di_fn.sized != di_elt.sized);
7897 if (want_size == di_elt.sized)
7899 fn = elt;
7900 di_fn = di_elt;
7905 /* If we have a matching function, call it. */
7906 if (fn)
7908 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7910 /* If the FN is a member function, make sure that it is
7911 accessible. */
7912 if (BASELINK_P (fns))
7913 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7914 complain);
7916 /* Core issue 901: It's ok to new a type with deleted delete. */
7917 if (DECL_DELETED_FN (fn) && alloc_fn)
7918 return NULL_TREE;
7920 tree ret;
7921 if (placement)
7923 /* The placement args might not be suitable for overload
7924 resolution at this point, so build the call directly. */
7925 int nargs = call_expr_nargs (placement);
7926 tree *argarray = XALLOCAVEC (tree, nargs);
7927 int i;
7928 argarray[0] = addr;
7929 for (i = 1; i < nargs; i++)
7930 argarray[i] = CALL_EXPR_ARG (placement, i);
7931 if (!mark_used (fn, complain) && !(complain & tf_error))
7932 return error_mark_node;
7933 ret = build_cxx_call (fn, nargs, argarray, complain);
7935 else
7937 tree destroying = di_fn.destroying;
7938 if (destroying)
7940 /* Strip const and volatile from addr but retain the type of the
7941 object. */
7942 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7943 rtype = cv_unqualified (rtype);
7944 rtype = TYPE_POINTER_TO (rtype);
7945 addr = cp_convert (rtype, oaddr, complain);
7946 destroying = build_functional_cast (input_location,
7947 destroying, NULL_TREE,
7948 complain);
7951 releasing_vec args;
7952 args->quick_push (addr);
7953 if (destroying)
7954 args->quick_push (destroying);
7955 if (di_fn.sized)
7956 args->quick_push (size);
7957 if (di_fn.aligned)
7959 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7960 args->quick_push (al);
7962 ret = cp_build_function_call_vec (fn, &args, complain);
7965 /* Set this flag for all callers of this function. In addition to
7966 delete-expressions, this is called for deallocating coroutine state;
7967 treat that as an implicit delete-expression. This is also called for
7968 the delete if the constructor throws in a new-expression, and for a
7969 deleting destructor (which implements a delete-expression). */
7970 /* But leave this flag off for destroying delete to avoid wrong
7971 assumptions in the optimizers. */
7972 tree call = extract_call_expr (ret);
7973 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
7974 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7976 return ret;
7979 /* If there's only a destroying delete that we can't use because the
7980 object isn't constructed yet, and we used global new, use global
7981 delete as well. */
7982 if (excluded_destroying
7983 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
7984 return build_op_delete_call (code, addr, size, true, placement,
7985 alloc_fn, complain);
7987 /* [expr.new]
7989 If no unambiguous matching deallocation function can be found,
7990 propagating the exception does not cause the object's memory to
7991 be freed. */
7992 if (alloc_fn)
7994 if ((complain & tf_warning)
7995 && !placement)
7997 bool w = warning (0,
7998 "no corresponding deallocation function for %qD",
7999 alloc_fn);
8000 if (w && excluded_destroying)
8001 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8002 "delete %qD cannot be used to release the allocated memory"
8003 " if the initialization throws because the object is not "
8004 "constructed yet", excluded_destroying);
8006 return NULL_TREE;
8009 if (complain & tf_error)
8010 error ("no suitable %<operator %s%> for %qT",
8011 OVL_OP_INFO (false, code)->name, type);
8012 return error_mark_node;
8015 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8016 in the diagnostics.
8018 If ISSUE_ERROR is true, then issue an error about the access, followed
8019 by a note showing the declaration. Otherwise, just show the note.
8021 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8022 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8023 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8024 would be because DECL was private). If not using NO_ACCESS_REASON,
8025 then it must be ak_none, and the access failure reason will be
8026 figured out by looking at the protection of DECL. */
8028 void
8029 complain_about_access (tree decl, tree diag_decl, tree diag_location,
8030 bool issue_error, access_kind no_access_reason)
8032 /* If we have not already figured out why DECL is inaccessible... */
8033 if (no_access_reason == ak_none)
8035 /* Examine the access of DECL to find out why. */
8036 if (TREE_PRIVATE (decl))
8037 no_access_reason = ak_private;
8038 else if (TREE_PROTECTED (decl))
8039 no_access_reason = ak_protected;
8042 /* Now generate an error message depending on calculated access. */
8043 if (no_access_reason == ak_private)
8045 if (issue_error)
8046 error ("%q#D is private within this context", diag_decl);
8047 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8049 else if (no_access_reason == ak_protected)
8051 if (issue_error)
8052 error ("%q#D is protected within this context", diag_decl);
8053 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8055 /* Couldn't figure out why DECL is inaccesible, so just say it's
8056 inaccessible. */
8057 else
8059 if (issue_error)
8060 error ("%q#D is inaccessible within this context", diag_decl);
8061 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8065 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8066 bitwise or of LOOKUP_* values. If any errors are warnings are
8067 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8068 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8069 to NULL. */
8071 static tree
8072 build_temp (tree expr, tree type, int flags,
8073 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8075 int savew, savee;
8077 *diagnostic_kind = DK_UNSPECIFIED;
8079 /* If the source is a packed field, calling the copy constructor will require
8080 binding the field to the reference parameter to the copy constructor, and
8081 we'll end up with an infinite loop. If we can use a bitwise copy, then
8082 do that now. */
8083 if ((lvalue_kind (expr) & clk_packed)
8084 && CLASS_TYPE_P (TREE_TYPE (expr))
8085 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8086 return get_target_expr (expr, complain);
8088 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8089 But it turns out to be a subexpression, so perform temporary
8090 materialization now. */
8091 if (TREE_CODE (expr) == CALL_EXPR
8092 && CLASS_TYPE_P (type)
8093 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8094 expr = build_cplus_new (type, expr, complain);
8096 savew = warningcount + werrorcount, savee = errorcount;
8097 releasing_vec args (make_tree_vector_single (expr));
8098 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8099 &args, type, flags, complain);
8100 if (warningcount + werrorcount > savew)
8101 *diagnostic_kind = DK_WARNING;
8102 else if (errorcount > savee)
8103 *diagnostic_kind = DK_ERROR;
8104 return expr;
8107 /* Get any location for EXPR, falling back to input_location.
8109 If the result is in a system header and is the virtual location for
8110 a token coming from the expansion of a macro, unwind it to the
8111 location of the expansion point of the macro (e.g. to avoid the
8112 diagnostic being suppressed for expansions of NULL where "NULL" is
8113 in a system header). */
8115 static location_t
8116 get_location_for_expr_unwinding_for_system_header (tree expr)
8118 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8119 loc = expansion_point_location_if_in_system_header (loc);
8120 return loc;
8123 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
8124 Also handle a subset of zero as null warnings.
8125 EXPR is implicitly converted to type TOTYPE.
8126 FN and ARGNUM are used for diagnostics. */
8128 static void
8129 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8131 /* Issue warnings about peculiar, but valid, uses of NULL. */
8132 if (TREE_CODE (totype) != BOOLEAN_TYPE
8133 && ARITHMETIC_TYPE_P (totype)
8134 && null_node_p (expr))
8136 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8137 if (fn)
8139 auto_diagnostic_group d;
8140 if (warning_at (loc, OPT_Wconversion_null,
8141 "passing NULL to non-pointer argument %P of %qD",
8142 argnum, fn))
8143 inform (get_fndecl_argument_location (fn, argnum),
8144 " declared here");
8146 else
8147 warning_at (loc, OPT_Wconversion_null,
8148 "converting to non-pointer type %qT from NULL", totype);
8151 /* Issue warnings if "false" is converted to a NULL pointer */
8152 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8153 && TYPE_PTR_P (totype))
8155 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8156 if (fn)
8158 auto_diagnostic_group d;
8159 if (warning_at (loc, OPT_Wconversion_null,
8160 "converting %<false%> to pointer type for argument "
8161 "%P of %qD", argnum, fn))
8162 inform (get_fndecl_argument_location (fn, argnum),
8163 " declared here");
8165 else
8166 warning_at (loc, OPT_Wconversion_null,
8167 "converting %<false%> to pointer type %qT", totype);
8169 /* Handle zero as null pointer warnings for cases other
8170 than EQ_EXPR and NE_EXPR */
8171 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8172 && null_ptr_cst_p (expr))
8174 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8175 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8179 /* We gave a diagnostic during a conversion. If this was in the second
8180 standard conversion sequence of a user-defined conversion sequence, say
8181 which user-defined conversion. */
8183 static void
8184 maybe_print_user_conv_context (conversion *convs)
8186 if (convs->user_conv_p)
8187 for (conversion *t = convs; t; t = next_conversion (t))
8188 if (t->kind == ck_user)
8190 print_z_candidate (0, N_(" after user-defined conversion:"),
8191 t->cand);
8192 break;
8196 /* Locate the parameter with the given index within FNDECL.
8197 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8198 Return the location of the FNDECL itself if there are problems. */
8200 location_t
8201 get_fndecl_argument_location (tree fndecl, int argnum)
8203 /* The locations of implicitly-declared functions are likely to be
8204 more meaningful than those of their parameters. */
8205 if (DECL_ARTIFICIAL (fndecl))
8206 return DECL_SOURCE_LOCATION (fndecl);
8208 int i;
8209 tree param;
8211 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8212 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8213 i < argnum && param;
8214 i++, param = TREE_CHAIN (param))
8217 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8218 return the location of FNDECL. */
8219 if (param == NULL)
8220 return DECL_SOURCE_LOCATION (fndecl);
8222 return DECL_SOURCE_LOCATION (param);
8225 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8226 within its declaration (or the fndecl itself if something went
8227 wrong). */
8229 void
8230 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
8232 if (fn)
8233 inform (get_fndecl_argument_location (fn, argnum),
8234 " initializing argument %P of %qD", argnum, fn);
8237 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8238 the conversion, EXPR is the expression we're converting. */
8240 static void
8241 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8243 if (cxx_dialect >= cxx20)
8244 return;
8246 tree type = TREE_TYPE (expr);
8247 type = strip_pointer_operator (type);
8249 if (TREE_CODE (type) != ARRAY_TYPE
8250 || TYPE_DOMAIN (type) == NULL_TREE)
8251 return;
8253 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8254 pedwarn (loc, OPT_Wc__20_extensions,
8255 "conversions to arrays of unknown bound "
8256 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8259 /* We call this recursively in convert_like_internal. */
8260 static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8261 tsubst_flags_t);
8263 /* Perform the conversions in CONVS on the expression EXPR. FN and
8264 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8265 indicates the `this' argument of a method. INNER is nonzero when
8266 being called to continue a conversion chain. It is negative when a
8267 reference binding will be applied, positive otherwise. If
8268 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8269 conversions will be emitted if appropriate. If C_CAST_P is true,
8270 this conversion is coming from a C-style cast; in that case,
8271 conversions to inaccessible bases are permitted. */
8273 static tree
8274 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8275 bool issue_conversion_warnings, bool c_cast_p,
8276 bool nested_p, tsubst_flags_t complain)
8278 tree totype = convs->type;
8279 diagnostic_t diag_kind;
8280 int flags;
8281 location_t loc = cp_expr_loc_or_input_loc (expr);
8283 if (convs->bad_p && !(complain & tf_error))
8284 return error_mark_node;
8286 if (convs->bad_p
8287 && convs->kind != ck_user
8288 && convs->kind != ck_list
8289 && convs->kind != ck_ambig
8290 && (convs->kind != ck_ref_bind
8291 || (convs->user_conv_p && next_conversion (convs)->bad_p))
8292 && (convs->kind != ck_rvalue
8293 || SCALAR_TYPE_P (totype))
8294 && convs->kind != ck_base)
8296 bool complained = false;
8297 conversion *t = convs;
8299 /* Give a helpful error if this is bad because of excess braces. */
8300 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8301 && SCALAR_TYPE_P (totype)
8302 && CONSTRUCTOR_NELTS (expr) > 0
8303 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8305 complained = permerror (loc, "too many braces around initializer "
8306 "for %qT", totype);
8307 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8308 && CONSTRUCTOR_NELTS (expr) == 1)
8309 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8312 /* Give a helpful error if this is bad because a conversion to bool
8313 from std::nullptr_t requires direct-initialization. */
8314 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8315 && TREE_CODE (totype) == BOOLEAN_TYPE)
8316 complained = permerror (loc, "converting to %qH from %qI requires "
8317 "direct-initialization",
8318 totype, TREE_TYPE (expr));
8320 if (TREE_CODE (TREE_TYPE (expr)) == REAL_TYPE
8321 && TREE_CODE (totype) == REAL_TYPE
8322 && (extended_float_type_p (TREE_TYPE (expr))
8323 || extended_float_type_p (totype)))
8324 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8325 totype))
8327 case 2:
8328 pedwarn (loc, 0, "converting to %qH from %qI with greater "
8329 "conversion rank", totype, TREE_TYPE (expr));
8330 complained = true;
8331 break;
8332 case 3:
8333 pedwarn (loc, 0, "converting to %qH from %qI with unordered "
8334 "conversion ranks", totype, TREE_TYPE (expr));
8335 complained = true;
8336 break;
8337 default:
8338 break;
8341 for (; t ; t = next_conversion (t))
8343 if (t->kind == ck_user && t->cand->reason)
8345 auto_diagnostic_group d;
8346 complained = permerror (loc, "invalid user-defined conversion "
8347 "from %qH to %qI", TREE_TYPE (expr),
8348 totype);
8349 if (complained)
8350 print_z_candidate (loc, N_("candidate is:"), t->cand);
8351 expr = convert_like (t, expr, fn, argnum,
8352 /*issue_conversion_warnings=*/false,
8353 /*c_cast_p=*/false, /*nested_p=*/true,
8354 complain);
8355 if (convs->kind == ck_ref_bind)
8356 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8357 LOOKUP_NORMAL, NULL_TREE,
8358 complain);
8359 else
8360 expr = cp_convert (totype, expr, complain);
8361 if (complained)
8362 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8363 return expr;
8365 else if (t->kind == ck_user || !t->bad_p)
8367 expr = convert_like (t, expr, fn, argnum,
8368 /*issue_conversion_warnings=*/false,
8369 /*c_cast_p=*/false, /*nested_p=*/true,
8370 complain);
8371 break;
8373 else if (t->kind == ck_ambig)
8374 return convert_like (t, expr, fn, argnum,
8375 /*issue_conversion_warnings=*/false,
8376 /*c_cast_p=*/false, /*nested_p=*/true,
8377 complain);
8378 else if (t->kind == ck_identity)
8379 break;
8381 if (!complained && expr != error_mark_node)
8383 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8384 gcc_rich_location richloc (loc, &label);
8385 complained = permerror (&richloc,
8386 "invalid conversion from %qH to %qI",
8387 TREE_TYPE (expr), totype);
8389 if (complained)
8390 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8392 return cp_convert (totype, expr, complain);
8395 if (issue_conversion_warnings && (complain & tf_warning))
8396 conversion_null_warnings (totype, expr, fn, argnum);
8398 switch (convs->kind)
8400 case ck_user:
8402 struct z_candidate *cand = convs->cand;
8404 if (cand == NULL)
8405 /* We chose the surrogate function from add_conv_candidate, now we
8406 actually need to build the conversion. */
8407 cand = build_user_type_conversion_1 (totype, expr,
8408 LOOKUP_NO_CONVERSION, complain);
8410 tree convfn = cand->fn;
8412 /* When converting from an init list we consider explicit
8413 constructors, but actually trying to call one is an error. */
8414 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8415 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8416 /* Unless this is for direct-list-initialization. */
8417 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8418 /* And in C++98 a default constructor can't be explicit. */
8419 && cxx_dialect >= cxx11)
8421 if (!(complain & tf_error))
8422 return error_mark_node;
8423 location_t loc = location_of (expr);
8424 if (CONSTRUCTOR_NELTS (expr) == 0
8425 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8427 auto_diagnostic_group d;
8428 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8429 "would use explicit constructor %qD",
8430 totype, convfn))
8431 inform (loc, "in C++11 and above a default constructor "
8432 "can be explicit");
8434 else
8435 error ("converting to %qT from initializer list would use "
8436 "explicit constructor %qD", totype, convfn);
8439 /* If we're initializing from {}, it's value-initialization. */
8440 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8441 && CONSTRUCTOR_NELTS (expr) == 0
8442 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8443 && !processing_template_decl)
8445 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8446 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8447 return error_mark_node;
8448 expr = build_value_init (totype, complain);
8449 expr = get_target_expr (expr, complain);
8450 if (expr != error_mark_node)
8452 TARGET_EXPR_LIST_INIT_P (expr) = true;
8453 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8455 return expr;
8458 /* We don't know here whether EXPR is being used as an lvalue or
8459 rvalue, but we know it's read. */
8460 mark_exp_read (expr);
8462 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8463 any more UDCs. */
8464 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8465 complain);
8467 /* If this is a constructor or a function returning an aggr type,
8468 we need to build up a TARGET_EXPR. */
8469 if (DECL_CONSTRUCTOR_P (convfn))
8471 expr = build_cplus_new (totype, expr, complain);
8473 /* Remember that this was list-initialization. */
8474 if (convs->check_narrowing && expr != error_mark_node)
8475 TARGET_EXPR_LIST_INIT_P (expr) = true;
8478 return expr;
8480 case ck_identity:
8481 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8483 int nelts = CONSTRUCTOR_NELTS (expr);
8484 if (nelts == 0)
8485 expr = build_value_init (totype, complain);
8486 else if (nelts == 1)
8487 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8488 else
8489 gcc_unreachable ();
8491 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8492 /*read_p=*/true, UNKNOWN_LOCATION,
8493 /*reject_builtin=*/true);
8495 if (type_unknown_p (expr))
8496 expr = instantiate_type (totype, expr, complain);
8497 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8498 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8499 if (expr == null_node
8500 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8501 /* If __null has been converted to an integer type, we do not want to
8502 continue to warn about uses of EXPR as an integer, rather than as a
8503 pointer. */
8504 expr = build_int_cst (totype, 0);
8505 return expr;
8506 case ck_ambig:
8507 /* We leave bad_p off ck_ambig because overload resolution considers
8508 it valid, it just fails when we try to perform it. So we need to
8509 check complain here, too. */
8510 if (complain & tf_error)
8512 /* Call build_user_type_conversion again for the error. */
8513 int flags = (convs->need_temporary_p
8514 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8515 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8516 gcc_assert (seen_error ());
8517 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8519 return error_mark_node;
8521 case ck_list:
8523 /* Conversion to std::initializer_list<T>. */
8524 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8525 unsigned len = CONSTRUCTOR_NELTS (expr);
8526 tree array;
8528 if (len)
8530 tree val; unsigned ix;
8532 tree new_ctor = build_constructor (init_list_type_node, NULL);
8534 /* Convert all the elements. */
8535 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8537 tree sub = convert_like (convs->u.list[ix], val, fn,
8538 argnum, false, false,
8539 /*nested_p=*/true, complain);
8540 if (sub == error_mark_node)
8541 return sub;
8542 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8543 && !check_narrowing (TREE_TYPE (sub), val, complain))
8544 return error_mark_node;
8545 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8546 NULL_TREE, sub);
8547 if (!TREE_CONSTANT (sub))
8548 TREE_CONSTANT (new_ctor) = false;
8550 /* Build up the array. */
8551 elttype = cp_build_qualified_type
8552 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8553 array = build_array_of_n_type (elttype, len);
8554 array = finish_compound_literal (array, new_ctor, complain);
8555 /* Take the address explicitly rather than via decay_conversion
8556 to avoid the error about taking the address of a temporary. */
8557 array = cp_build_addr_expr (array, complain);
8559 else
8560 array = nullptr_node;
8562 array = cp_convert (build_pointer_type (elttype), array, complain);
8563 if (array == error_mark_node)
8564 return error_mark_node;
8566 /* Build up the initializer_list object. Note: fail gracefully
8567 if the object cannot be completed because, for example, no
8568 definition is provided (c++/80956). */
8569 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8570 if (!totype)
8571 return error_mark_node;
8572 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8573 vec<constructor_elt, va_gc> *vec = NULL;
8574 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8575 field = next_aggregate_field (DECL_CHAIN (field));
8576 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8577 tree new_ctor = build_constructor (totype, vec);
8578 return get_target_expr (new_ctor, complain);
8581 case ck_aggr:
8582 if (TREE_CODE (totype) == COMPLEX_TYPE)
8584 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8585 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8586 real = perform_implicit_conversion (TREE_TYPE (totype),
8587 real, complain);
8588 imag = perform_implicit_conversion (TREE_TYPE (totype),
8589 imag, complain);
8590 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8591 return expr;
8593 expr = reshape_init (totype, expr, complain);
8594 expr = get_target_expr (digest_init (totype, expr, complain),
8595 complain);
8596 if (expr != error_mark_node)
8597 TARGET_EXPR_LIST_INIT_P (expr) = true;
8598 return expr;
8600 default:
8601 break;
8604 expr = convert_like (next_conversion (convs), expr, fn, argnum,
8605 convs->kind == ck_ref_bind
8606 ? issue_conversion_warnings : false,
8607 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8608 if (expr == error_mark_node)
8609 return error_mark_node;
8611 switch (convs->kind)
8613 case ck_rvalue:
8614 expr = decay_conversion (expr, complain);
8615 if (expr == error_mark_node)
8617 if (complain & tf_error)
8619 auto_diagnostic_group d;
8620 maybe_print_user_conv_context (convs);
8621 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8623 return error_mark_node;
8626 if (! MAYBE_CLASS_TYPE_P (totype))
8627 return expr;
8629 /* Don't introduce copies when passing arguments along to the inherited
8630 constructor. */
8631 if (current_function_decl
8632 && flag_new_inheriting_ctors
8633 && DECL_INHERITED_CTOR (current_function_decl))
8634 return expr;
8636 if (TREE_CODE (expr) == TARGET_EXPR
8637 && TARGET_EXPR_LIST_INIT_P (expr))
8638 /* Copy-list-initialization doesn't actually involve a copy. */
8639 return expr;
8641 /* Fall through. */
8642 case ck_base:
8643 if (convs->kind == ck_base && !convs->need_temporary_p)
8645 /* We are going to bind a reference directly to a base-class
8646 subobject of EXPR. */
8647 /* Build an expression for `*((base*) &expr)'. */
8648 expr = convert_to_base (expr, totype,
8649 !c_cast_p, /*nonnull=*/true, complain);
8650 return expr;
8653 /* Copy-initialization where the cv-unqualified version of the source
8654 type is the same class as, or a derived class of, the class of the
8655 destination [is treated as direct-initialization]. [dcl.init] */
8656 flags = LOOKUP_NORMAL;
8657 /* This conversion is being done in the context of a user-defined
8658 conversion (i.e. the second step of copy-initialization), so
8659 don't allow any more. */
8660 if (convs->user_conv_p)
8661 flags |= LOOKUP_NO_CONVERSION;
8662 /* We might be performing a conversion of the argument
8663 to the user-defined conversion, i.e., not a conversion of the
8664 result of the user-defined conversion. In which case we skip
8665 explicit constructors. */
8666 if (convs->copy_init_p)
8667 flags |= LOOKUP_ONLYCONVERTING;
8668 expr = build_temp (expr, totype, flags, &diag_kind, complain);
8669 if (diag_kind && complain)
8671 auto_diagnostic_group d;
8672 maybe_print_user_conv_context (convs);
8673 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8676 return build_cplus_new (totype, expr, complain);
8678 case ck_ref_bind:
8680 tree ref_type = totype;
8682 /* direct_reference_binding might have inserted a ck_qual under
8683 this ck_ref_bind for the benefit of conversion sequence ranking.
8684 Ignore the conversion; we'll create our own below. */
8685 if (next_conversion (convs)->kind == ck_qual
8686 && !convs->need_temporary_p)
8688 gcc_assert (same_type_p (TREE_TYPE (expr),
8689 next_conversion (convs)->type));
8690 /* Strip the cast created by the ck_qual; cp_build_addr_expr
8691 below expects an lvalue. */
8692 STRIP_NOPS (expr);
8695 if (convs->bad_p && !next_conversion (convs)->bad_p)
8697 tree extype = TREE_TYPE (expr);
8698 auto_diagnostic_group d;
8699 if (TYPE_REF_IS_RVALUE (ref_type)
8700 && lvalue_p (expr))
8701 error_at (loc, "cannot bind rvalue reference of type %qH to "
8702 "lvalue of type %qI", totype, extype);
8703 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8704 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8706 conversion *next = next_conversion (convs);
8707 if (next->kind == ck_std)
8709 next = next_conversion (next);
8710 error_at (loc, "cannot bind non-const lvalue reference of "
8711 "type %qH to a value of type %qI",
8712 totype, next->type);
8714 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8715 error_at (loc, "cannot bind non-const lvalue reference of "
8716 "type %qH to an rvalue of type %qI", totype, extype);
8717 else // extype is volatile
8718 error_at (loc, "cannot bind lvalue reference of type "
8719 "%qH to an rvalue of type %qI", totype,
8720 extype);
8722 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8724 /* If we're converting from T[] to T[N], don't talk
8725 about discarding qualifiers. (Converting from T[N] to
8726 T[] is allowed by P0388R4.) */
8727 if (TREE_CODE (extype) == ARRAY_TYPE
8728 && TYPE_DOMAIN (extype) == NULL_TREE
8729 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8730 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8731 error_at (loc, "cannot bind reference of type %qH to %qI "
8732 "due to different array bounds", totype, extype);
8733 else
8734 error_at (loc, "binding reference of type %qH to %qI "
8735 "discards qualifiers", totype, extype);
8737 else
8738 gcc_unreachable ();
8739 maybe_print_user_conv_context (convs);
8740 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8742 return error_mark_node;
8744 else if (complain & tf_warning)
8745 maybe_warn_array_conv (loc, convs, expr);
8747 /* If necessary, create a temporary.
8749 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8750 that need temporaries, even when their types are reference
8751 compatible with the type of reference being bound, so the
8752 upcoming call to cp_build_addr_expr doesn't fail. */
8753 if (convs->need_temporary_p
8754 || TREE_CODE (expr) == CONSTRUCTOR
8755 || TREE_CODE (expr) == VA_ARG_EXPR)
8757 /* Otherwise, a temporary of type "cv1 T1" is created and
8758 initialized from the initializer expression using the rules
8759 for a non-reference copy-initialization (8.5). */
8761 tree type = TREE_TYPE (ref_type);
8762 cp_lvalue_kind lvalue = lvalue_kind (expr);
8764 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8765 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8766 && !TYPE_REF_IS_RVALUE (ref_type))
8768 /* If the reference is volatile or non-const, we
8769 cannot create a temporary. */
8770 if (complain & tf_error)
8772 if (lvalue & clk_bitfield)
8773 error_at (loc, "cannot bind bit-field %qE to %qT",
8774 expr, ref_type);
8775 else if (lvalue & clk_packed)
8776 error_at (loc, "cannot bind packed field %qE to %qT",
8777 expr, ref_type);
8778 else
8779 error_at (loc, "cannot bind rvalue %qE to %qT",
8780 expr, ref_type);
8782 return error_mark_node;
8784 /* If the source is a packed field, and we must use a copy
8785 constructor, then building the target expr will require
8786 binding the field to the reference parameter to the
8787 copy constructor, and we'll end up with an infinite
8788 loop. If we can use a bitwise copy, then we'll be
8789 OK. */
8790 if ((lvalue & clk_packed)
8791 && CLASS_TYPE_P (type)
8792 && type_has_nontrivial_copy_init (type))
8794 error_at (loc, "cannot bind packed field %qE to %qT",
8795 expr, ref_type);
8796 return error_mark_node;
8798 if (lvalue & clk_bitfield)
8800 expr = convert_bitfield_to_declared_type (expr);
8801 expr = fold_convert (type, expr);
8804 /* Creating &TARGET_EXPR<> in a template would break when
8805 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8806 instead. This can happen even when there's no class
8807 involved, e.g., when converting an integer to a reference
8808 type. */
8809 if (processing_template_decl)
8810 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8811 expr = build_target_expr_with_type (expr, type, complain);
8814 /* Take the address of the thing to which we will bind the
8815 reference. */
8816 expr = cp_build_addr_expr (expr, complain);
8817 if (expr == error_mark_node)
8818 return error_mark_node;
8820 /* Convert it to a pointer to the type referred to by the
8821 reference. This will adjust the pointer if a derived to
8822 base conversion is being performed. */
8823 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8824 expr, complain);
8825 /* Convert the pointer to the desired reference type. */
8826 return build_nop (ref_type, expr);
8829 case ck_lvalue:
8830 return decay_conversion (expr, complain);
8832 case ck_fnptr:
8833 /* ??? Should the address of a transaction-safe pointer point to the TM
8834 clone, and this conversion look up the primary function? */
8835 return build_nop (totype, expr);
8837 case ck_qual:
8838 /* Warn about deprecated conversion if appropriate. */
8839 if (complain & tf_warning)
8841 string_conv_p (totype, expr, 1);
8842 maybe_warn_array_conv (loc, convs, expr);
8844 break;
8846 case ck_ptr:
8847 if (convs->base_p)
8848 expr = convert_to_base (expr, totype, !c_cast_p,
8849 /*nonnull=*/false, complain);
8850 return build_nop (totype, expr);
8852 case ck_pmem:
8853 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8854 c_cast_p, complain);
8856 default:
8857 break;
8860 if (convs->check_narrowing
8861 && !check_narrowing (totype, expr, complain,
8862 convs->check_narrowing_const_only))
8863 return error_mark_node;
8865 warning_sentinel w (warn_zero_as_null_pointer_constant);
8866 if (issue_conversion_warnings)
8867 expr = cp_convert_and_check (totype, expr, complain);
8868 else
8870 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8871 expr = TREE_OPERAND (expr, 0);
8872 expr = cp_convert (totype, expr, complain);
8875 return expr;
8878 /* Return true if converting FROM to TO is unsafe in a template. */
8880 static bool
8881 conv_unsafe_in_template_p (tree to, tree from)
8883 /* Converting classes involves TARGET_EXPR. */
8884 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8885 return true;
8887 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8888 doesn't handle. */
8889 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8890 return true;
8892 /* Converting integer to real isn't a trivial conversion, either. */
8893 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8894 return true;
8896 return false;
8899 /* Wrapper for convert_like_internal that handles creating
8900 IMPLICIT_CONV_EXPR. */
8902 static tree
8903 convert_like (conversion *convs, tree expr, tree fn, int argnum,
8904 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
8905 tsubst_flags_t complain)
8907 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8908 and creating a CALL_EXPR in a template breaks in finish_call_expr
8909 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
8910 created such codes e.g. when calling a user-defined conversion
8911 function. */
8912 tree conv_expr = NULL_TREE;
8913 if (processing_template_decl
8914 && convs->kind != ck_identity
8915 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
8917 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8918 if (convs->kind != ck_ref_bind)
8919 conv_expr = convert_from_reference (conv_expr);
8920 if (!convs->bad_p)
8921 return conv_expr;
8922 /* Do the normal processing to give the bad_p errors. But we still
8923 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8924 error_mark_node. */
8926 expr = convert_like_internal (convs, expr, fn, argnum,
8927 issue_conversion_warnings, c_cast_p,
8928 nested_p, complain);
8929 if (expr == error_mark_node)
8930 return error_mark_node;
8931 return conv_expr ? conv_expr : expr;
8934 /* Convenience wrapper for convert_like. */
8936 static inline tree
8937 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8939 return convert_like (convs, expr, NULL_TREE, 0,
8940 /*issue_conversion_warnings=*/true,
8941 /*c_cast_p=*/false, /*nested_p=*/false, complain);
8944 /* Convenience wrapper for convert_like. */
8946 static inline tree
8947 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8948 tsubst_flags_t complain)
8950 return convert_like (convs, expr, fn, argnum,
8951 /*issue_conversion_warnings=*/true,
8952 /*c_cast_p=*/false, /*nested_p=*/false, complain);
8955 /* ARG is being passed to a varargs function. Perform any conversions
8956 required. Return the converted value. */
8958 tree
8959 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8961 tree arg_type = TREE_TYPE (arg);
8962 location_t loc = cp_expr_loc_or_input_loc (arg);
8964 /* [expr.call]
8966 If the argument has integral or enumeration type that is subject
8967 to the integral promotions (_conv.prom_), or a floating-point
8968 type that is subject to the floating-point promotion
8969 (_conv.fpprom_), the value of the argument is converted to the
8970 promoted type before the call. */
8971 if (TREE_CODE (arg_type) == REAL_TYPE
8972 && (TYPE_PRECISION (arg_type)
8973 < TYPE_PRECISION (double_type_node))
8974 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
8975 && !extended_float_type_p (arg_type))
8977 if ((complain & tf_warning)
8978 && warn_double_promotion && !c_inhibit_evaluation_warnings)
8979 warning_at (loc, OPT_Wdouble_promotion,
8980 "implicit conversion from %qH to %qI when passing "
8981 "argument to function",
8982 arg_type, double_type_node);
8983 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
8984 arg = TREE_OPERAND (arg, 0);
8985 arg = mark_rvalue_use (arg);
8986 arg = convert_to_real_nofold (double_type_node, arg);
8988 else if (NULLPTR_TYPE_P (arg_type))
8990 arg = mark_rvalue_use (arg);
8991 if (TREE_SIDE_EFFECTS (arg))
8993 warning_sentinel w(warn_unused_result);
8994 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
8996 else
8997 arg = null_pointer_node;
8999 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9001 if (SCOPED_ENUM_P (arg_type))
9003 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9004 complain);
9005 prom = cp_perform_integral_promotions (prom, complain);
9006 if (abi_version_crosses (6)
9007 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9008 && (complain & tf_warning))
9009 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9010 " as %qT before %<-fabi-version=6%>, %qT after",
9011 arg_type,
9012 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9013 if (!abi_version_at_least (6))
9014 arg = prom;
9016 else
9017 arg = cp_perform_integral_promotions (arg, complain);
9019 else
9020 /* [expr.call]
9022 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9023 standard conversions are performed. */
9024 arg = decay_conversion (arg, complain);
9026 arg = require_complete_type (arg, complain);
9027 arg_type = TREE_TYPE (arg);
9029 if (arg != error_mark_node
9030 /* In a template (or ill-formed code), we can have an incomplete type
9031 even after require_complete_type, in which case we don't know
9032 whether it has trivial copy or not. */
9033 && COMPLETE_TYPE_P (arg_type)
9034 && !cp_unevaluated_operand)
9036 /* [expr.call] 5.2.2/7:
9037 Passing a potentially-evaluated argument of class type (Clause 9)
9038 with a non-trivial copy constructor or a non-trivial destructor
9039 with no corresponding parameter is conditionally-supported, with
9040 implementation-defined semantics.
9042 We support it as pass-by-invisible-reference, just like a normal
9043 value parameter.
9045 If the call appears in the context of a sizeof expression,
9046 it is not potentially-evaluated. */
9047 if (type_has_nontrivial_copy_init (arg_type)
9048 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9050 arg = force_rvalue (arg, complain);
9051 if (complain & tf_warning)
9052 warning (OPT_Wconditionally_supported,
9053 "passing objects of non-trivially-copyable "
9054 "type %q#T through %<...%> is conditionally supported",
9055 arg_type);
9056 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9058 /* Build up a real lvalue-to-rvalue conversion in case the
9059 copy constructor is trivial but not callable. */
9060 else if (CLASS_TYPE_P (arg_type))
9061 force_rvalue (arg, complain);
9065 return arg;
9068 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9070 tree
9071 build_x_va_arg (location_t loc, tree expr, tree type)
9073 if (processing_template_decl)
9075 tree r = build_min (VA_ARG_EXPR, type, expr);
9076 SET_EXPR_LOCATION (r, loc);
9077 return r;
9080 type = complete_type_or_else (type, NULL_TREE);
9082 if (expr == error_mark_node || !type)
9083 return error_mark_node;
9085 expr = mark_lvalue_use (expr);
9087 if (TYPE_REF_P (type))
9089 error ("cannot receive reference type %qT through %<...%>", type);
9090 return error_mark_node;
9093 if (type_has_nontrivial_copy_init (type)
9094 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9096 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9097 it as pass by invisible reference. */
9098 warning_at (loc, OPT_Wconditionally_supported,
9099 "receiving objects of non-trivially-copyable type %q#T "
9100 "through %<...%> is conditionally-supported", type);
9102 tree ref = cp_build_reference_type (type, false);
9103 expr = build_va_arg (loc, expr, ref);
9104 return convert_from_reference (expr);
9107 tree ret = build_va_arg (loc, expr, type);
9108 if (CLASS_TYPE_P (type))
9109 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9110 know how to handle it. */
9111 ret = get_target_expr (ret);
9112 return ret;
9115 /* TYPE has been given to va_arg. Apply the default conversions which
9116 would have happened when passed via ellipsis. Return the promoted
9117 type, or the passed type if there is no change. */
9119 tree
9120 cxx_type_promotes_to (tree type)
9122 tree promote;
9124 /* Perform the array-to-pointer and function-to-pointer
9125 conversions. */
9126 type = type_decays_to (type);
9128 promote = type_promotes_to (type);
9129 if (same_type_p (type, promote))
9130 promote = type;
9132 return promote;
9135 /* ARG is a default argument expression being passed to a parameter of
9136 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9137 zero-based argument number. Do any required conversions. Return
9138 the converted value. */
9140 static GTY(()) vec<tree, va_gc> *default_arg_context;
9141 void
9142 push_defarg_context (tree fn)
9143 { vec_safe_push (default_arg_context, fn); }
9145 void
9146 pop_defarg_context (void)
9147 { default_arg_context->pop (); }
9149 tree
9150 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9151 tsubst_flags_t complain)
9153 int i;
9154 tree t;
9156 /* See through clones. */
9157 fn = DECL_ORIGIN (fn);
9158 /* And inheriting ctors. */
9159 if (flag_new_inheriting_ctors)
9160 fn = strip_inheriting_ctors (fn);
9162 /* Detect recursion. */
9163 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9164 if (t == fn)
9166 if (complain & tf_error)
9167 error ("recursive evaluation of default argument for %q#D", fn);
9168 return error_mark_node;
9171 /* If the ARG is an unparsed default argument expression, the
9172 conversion cannot be performed. */
9173 if (TREE_CODE (arg) == DEFERRED_PARSE)
9175 if (complain & tf_error)
9176 error ("call to %qD uses the default argument for parameter %P, which "
9177 "is not yet defined", fn, parmnum);
9178 return error_mark_node;
9181 push_defarg_context (fn);
9183 if (fn && DECL_TEMPLATE_INFO (fn))
9184 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9186 /* Due to:
9188 [dcl.fct.default]
9190 The names in the expression are bound, and the semantic
9191 constraints are checked, at the point where the default
9192 expressions appears.
9194 we must not perform access checks here. */
9195 push_deferring_access_checks (dk_no_check);
9196 /* We must make a copy of ARG, in case subsequent processing
9197 alters any part of it. */
9198 arg = break_out_target_exprs (arg, /*clear location*/true);
9200 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9201 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9202 complain);
9203 arg = convert_for_arg_passing (type, arg, complain);
9204 pop_deferring_access_checks();
9206 pop_defarg_context ();
9208 return arg;
9211 /* Returns the type which will really be used for passing an argument of
9212 type TYPE. */
9214 tree
9215 type_passed_as (tree type)
9217 /* Pass classes with copy ctors by invisible reference. */
9218 if (TREE_ADDRESSABLE (type))
9219 type = build_reference_type (type);
9220 else if (targetm.calls.promote_prototypes (NULL_TREE)
9221 && INTEGRAL_TYPE_P (type)
9222 && COMPLETE_TYPE_P (type)
9223 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9224 type = integer_type_node;
9226 return type;
9229 /* Actually perform the appropriate conversion. */
9231 tree
9232 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9234 tree bitfield_type;
9236 /* If VAL is a bitfield, then -- since it has already been converted
9237 to TYPE -- it cannot have a precision greater than TYPE.
9239 If it has a smaller precision, we must widen it here. For
9240 example, passing "int f:3;" to a function expecting an "int" will
9241 not result in any conversion before this point.
9243 If the precision is the same we must not risk widening. For
9244 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9245 often have type "int", even though the C++ type for the field is
9246 "long long". If the value is being passed to a function
9247 expecting an "int", then no conversions will be required. But,
9248 if we call convert_bitfield_to_declared_type, the bitfield will
9249 be converted to "long long". */
9250 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9251 if (bitfield_type
9252 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9253 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
9255 if (val == error_mark_node)
9257 /* Pass classes with copy ctors by invisible reference. */
9258 else if (TREE_ADDRESSABLE (type))
9259 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9260 else if (targetm.calls.promote_prototypes (NULL_TREE)
9261 && INTEGRAL_TYPE_P (type)
9262 && COMPLETE_TYPE_P (type)
9263 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9264 val = cp_perform_integral_promotions (val, complain);
9265 if (complain & tf_warning)
9267 if (warn_suggest_attribute_format)
9269 tree rhstype = TREE_TYPE (val);
9270 const enum tree_code coder = TREE_CODE (rhstype);
9271 const enum tree_code codel = TREE_CODE (type);
9272 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9273 && coder == codel
9274 && check_missing_format_attribute (type, rhstype))
9275 warning (OPT_Wsuggest_attribute_format,
9276 "argument of function call might be a candidate "
9277 "for a format attribute");
9279 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
9282 if (complain & tf_warning)
9283 warn_for_address_or_pointer_of_packed_member (type, val);
9285 return val;
9288 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9289 which just decay_conversion or no conversions at all should be done.
9290 This is true for some builtins which don't act like normal functions.
9291 Return 2 if just decay_conversion and removal of excess precision should
9292 be done, 1 if just decay_conversion. Return 3 for special treatment of
9293 the 3rd argument for __builtin_*_overflow_p. */
9296 magic_varargs_p (tree fn)
9298 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9299 switch (DECL_FUNCTION_CODE (fn))
9301 case BUILT_IN_CLASSIFY_TYPE:
9302 case BUILT_IN_CONSTANT_P:
9303 case BUILT_IN_NEXT_ARG:
9304 case BUILT_IN_VA_START:
9305 return 1;
9307 case BUILT_IN_ADD_OVERFLOW_P:
9308 case BUILT_IN_SUB_OVERFLOW_P:
9309 case BUILT_IN_MUL_OVERFLOW_P:
9310 return 3;
9312 case BUILT_IN_ISFINITE:
9313 case BUILT_IN_ISINF:
9314 case BUILT_IN_ISINF_SIGN:
9315 case BUILT_IN_ISNAN:
9316 case BUILT_IN_ISNORMAL:
9317 case BUILT_IN_FPCLASSIFY:
9318 return 2;
9320 default:
9321 return lookup_attribute ("type generic",
9322 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9325 return 0;
9328 /* Returns the decl of the dispatcher function if FN is a function version. */
9330 tree
9331 get_function_version_dispatcher (tree fn)
9333 tree dispatcher_decl = NULL;
9335 if (DECL_LOCAL_DECL_P (fn))
9336 fn = DECL_LOCAL_DECL_ALIAS (fn);
9338 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9339 && DECL_FUNCTION_VERSIONED (fn));
9341 gcc_assert (targetm.get_function_versions_dispatcher);
9342 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9344 if (dispatcher_decl == NULL)
9346 error_at (input_location, "use of multiversioned function "
9347 "without a default");
9348 return NULL;
9351 retrofit_lang_decl (dispatcher_decl);
9352 gcc_assert (dispatcher_decl != NULL);
9353 return dispatcher_decl;
9356 /* fn is a function version dispatcher that is marked used. Mark all the
9357 semantically identical function versions it will dispatch as used. */
9359 void
9360 mark_versions_used (tree fn)
9362 struct cgraph_node *node;
9363 struct cgraph_function_version_info *node_v;
9364 struct cgraph_function_version_info *it_v;
9366 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9368 node = cgraph_node::get (fn);
9369 if (node == NULL)
9370 return;
9372 gcc_assert (node->dispatcher_function);
9374 node_v = node->function_version ();
9375 if (node_v == NULL)
9376 return;
9378 /* All semantically identical versions are chained. Traverse and mark each
9379 one of them as used. */
9380 it_v = node_v->next;
9381 while (it_v != NULL)
9383 mark_used (it_v->this_node->decl);
9384 it_v = it_v->next;
9388 /* Build a call to "the copy constructor" for the type of A, even if it
9389 wouldn't be selected by normal overload resolution. Used for
9390 diagnostics. */
9392 static tree
9393 call_copy_ctor (tree a, tsubst_flags_t complain)
9395 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9396 tree binfo = TYPE_BINFO (ctype);
9397 tree copy = get_copy_ctor (ctype, complain);
9398 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9399 tree ob = build_dummy_object (ctype);
9400 releasing_vec args (make_tree_vector_single (a));
9401 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9402 LOOKUP_NORMAL, NULL, complain);
9403 return r;
9406 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9408 static tree
9409 base_ctor_for (tree complete_ctor)
9411 tree clone;
9412 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9413 if (DECL_BASE_CONSTRUCTOR_P (clone))
9414 return clone;
9415 return NULL_TREE;
9418 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9419 and return whether we were successful. EXP must have already been cleared
9420 by unsafe_copy_elision_p{,_opt}. */
9422 static bool
9423 make_base_init_ok (tree exp)
9425 if (TREE_CODE (exp) == TARGET_EXPR)
9426 exp = TARGET_EXPR_INITIAL (exp);
9427 while (TREE_CODE (exp) == COMPOUND_EXPR)
9428 exp = TREE_OPERAND (exp, 1);
9429 if (TREE_CODE (exp) == COND_EXPR)
9431 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9432 if (tree op1 = TREE_OPERAND (exp, 1))
9434 bool r1 = make_base_init_ok (op1);
9435 /* If unsafe_copy_elision_p was false, the arms should match. */
9436 gcc_assert (r1 == ret);
9438 return ret;
9440 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9441 /* A trivial copy is OK. */
9442 return true;
9443 if (!AGGR_INIT_VIA_CTOR_P (exp))
9444 /* unsafe_copy_elision_p_opt must have said this is OK. */
9445 return true;
9446 tree fn = cp_get_callee_fndecl_nofold (exp);
9447 if (DECL_BASE_CONSTRUCTOR_P (fn))
9448 return true;
9449 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9450 fn = base_ctor_for (fn);
9451 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9452 /* The base constructor has more parameters, so we can't just change the
9453 call target. It would be possible to splice in the appropriate
9454 arguments, but probably not worth the complexity. */
9455 return false;
9456 mark_used (fn);
9457 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9458 return true;
9461 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9462 neither of which can be used for return by invisible reference. We avoid
9463 doing C++17 mandatory copy elision for either of these cases.
9465 This returns non-zero even if the type of T has no tail padding that other
9466 data could be allocated into, because that depends on the particular ABI.
9467 unsafe_copy_elision_p_opt does consider whether there is padding. */
9470 unsafe_return_slot_p (tree t)
9472 /* Check empty bases separately, they don't have fields. */
9473 if (is_empty_base_ref (t))
9474 return 2;
9476 /* A delegating constructor might be used to initialize a base. */
9477 if (current_function_decl
9478 && DECL_CONSTRUCTOR_P (current_function_decl)
9479 && (t == current_class_ref
9480 || tree_strip_nop_conversions (t) == current_class_ptr))
9481 return 2;
9483 STRIP_NOPS (t);
9484 if (TREE_CODE (t) == ADDR_EXPR)
9485 t = TREE_OPERAND (t, 0);
9486 if (TREE_CODE (t) == COMPONENT_REF)
9487 t = TREE_OPERAND (t, 1);
9488 if (TREE_CODE (t) != FIELD_DECL)
9489 return false;
9490 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9491 /* The middle-end will do the right thing for scalar types. */
9492 return false;
9493 if (DECL_FIELD_IS_BASE (t))
9494 return 2;
9495 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9496 return 1;
9497 return 0;
9500 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9502 static bool
9503 init_by_return_slot_p (tree exp)
9505 /* Copy elision only happens with a TARGET_EXPR. */
9506 if (TREE_CODE (exp) != TARGET_EXPR)
9507 return false;
9508 tree init = TARGET_EXPR_INITIAL (exp);
9509 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9510 while (TREE_CODE (init) == COMPOUND_EXPR)
9511 init = TREE_OPERAND (init, 1);
9512 if (TREE_CODE (init) == COND_EXPR)
9514 /* We'll end up copying from each of the arms of the COND_EXPR directly
9515 into the target, so look at them. */
9516 if (tree op = TREE_OPERAND (init, 1))
9517 if (init_by_return_slot_p (op))
9518 return true;
9519 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9521 return (TREE_CODE (init) == AGGR_INIT_EXPR
9522 && !AGGR_INIT_VIA_CTOR_P (init));
9525 /* We can't elide a copy from a function returning by value to a
9526 potentially-overlapping subobject, as the callee might clobber tail padding.
9527 Return true iff this could be that case.
9529 Places that use this function (or _opt) to decide to elide a copy should
9530 probably use make_safe_copy_elision instead. */
9532 bool
9533 unsafe_copy_elision_p (tree target, tree exp)
9535 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9538 /* As above, but for optimization allow more cases that are actually safe. */
9540 static bool
9541 unsafe_copy_elision_p_opt (tree target, tree exp)
9543 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9544 /* It's safe to elide the copy for a class with no tail padding. */
9545 if (!is_empty_class (type)
9546 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9547 return false;
9548 return unsafe_copy_elision_p (target, exp);
9551 /* Try to make EXP suitable to be used as the initializer for TARGET,
9552 and return whether we were successful. */
9554 bool
9555 make_safe_copy_elision (tree target, tree exp)
9557 int uns = unsafe_return_slot_p (target);
9558 if (!uns)
9559 return true;
9560 if (init_by_return_slot_p (exp))
9561 return false;
9562 if (uns == 1)
9563 return true;
9564 return make_base_init_ok (exp);
9567 /* True IFF the result of the conversion C is a prvalue. */
9569 static bool
9570 conv_is_prvalue (conversion *c)
9572 if (c->kind == ck_rvalue)
9573 return true;
9574 if (c->kind == ck_base && c->need_temporary_p)
9575 return true;
9576 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9577 return true;
9578 if (c->kind == ck_identity && c->u.expr
9579 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9580 return true;
9582 return false;
9585 /* True iff C is a conversion that binds a reference to a prvalue. */
9587 static bool
9588 conv_binds_ref_to_prvalue (conversion *c)
9590 if (c->kind != ck_ref_bind)
9591 return false;
9592 if (c->need_temporary_p)
9593 return true;
9595 return conv_is_prvalue (next_conversion (c));
9598 /* True iff EXPR represents a (subobject of a) temporary. */
9600 static bool
9601 expr_represents_temporary_p (tree expr)
9603 while (handled_component_p (expr))
9604 expr = TREE_OPERAND (expr, 0);
9605 return TREE_CODE (expr) == TARGET_EXPR;
9608 /* True iff C is a conversion that binds a reference to a temporary.
9609 This is a superset of conv_binds_ref_to_prvalue: here we're also
9610 interested in xvalues. */
9612 static bool
9613 conv_binds_ref_to_temporary (conversion *c)
9615 if (conv_binds_ref_to_prvalue (c))
9616 return true;
9617 if (c->kind != ck_ref_bind)
9618 return false;
9619 c = next_conversion (c);
9620 /* This is the case for
9621 struct Base {};
9622 struct Derived : Base {};
9623 const Base& b(Derived{});
9624 where we bind 'b' to the Base subobject of a temporary object of type
9625 Derived. The subobject is an xvalue; the whole object is a prvalue.
9627 The ck_base doesn't have to be present for cases like X{}.m. */
9628 if (c->kind == ck_base)
9629 c = next_conversion (c);
9630 if (c->kind == ck_identity && c->u.expr
9631 && expr_represents_temporary_p (c->u.expr))
9632 return true;
9633 return false;
9636 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9637 the reference to a temporary. Return tristate::TS_FALSE if converting
9638 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9639 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9640 says whether the conversion should be done in direct- or copy-initialization
9641 context. */
9643 tristate
9644 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9646 gcc_assert (TYPE_REF_P (type));
9648 /* Get the high-water mark for the CONVERSION_OBSTACK. */
9649 void *p = conversion_obstack_alloc (0);
9651 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9652 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9653 /*c_cast_p=*/false, flags, tf_none);
9654 tristate ret (tristate::TS_UNKNOWN);
9655 if (conv && !conv->bad_p)
9656 ret = tristate (conv_binds_ref_to_temporary (conv));
9658 /* Free all the conversions we allocated. */
9659 obstack_free (&conversion_obstack, p);
9661 return ret;
9664 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9665 class type or a pointer to class type. If NO_PTR_DEREF is true and
9666 INSTANCE has pointer type, clobber the pointer rather than what it points
9667 to. */
9669 tree
9670 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9672 gcc_assert (!is_dummy_object (instance));
9674 if (!flag_lifetime_dse)
9676 no_clobber:
9677 return fold_convert (void_type_node, instance);
9680 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9681 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9683 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9684 goto no_clobber;
9685 instance = cp_build_fold_indirect_ref (instance);
9688 /* A trivial destructor should still clobber the object. */
9689 tree clobber = build_clobber (TREE_TYPE (instance));
9690 return build2 (MODIFY_EXPR, void_type_node,
9691 instance, clobber);
9694 /* Return true if in an immediate function context, or an unevaluated operand,
9695 or a default argument/member initializer, or a subexpression of an immediate
9696 invocation. */
9698 bool
9699 in_immediate_context ()
9701 return (cp_unevaluated_operand != 0
9702 || (current_function_decl != NULL_TREE
9703 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9704 /* DR 2631: default args and DMI aren't immediately evaluated.
9705 Return true here so immediate_invocation_p returns false. */
9706 || current_binding_level->kind == sk_function_parms
9707 || current_binding_level->kind == sk_template_parms
9708 || parsing_nsdmi ()
9709 || in_consteval_if_p);
9712 /* Return true if a call to FN with number of arguments NARGS
9713 is an immediate invocation. */
9715 static bool
9716 immediate_invocation_p (tree fn)
9718 return (TREE_CODE (fn) == FUNCTION_DECL
9719 && DECL_IMMEDIATE_FUNCTION_P (fn)
9720 && !in_immediate_context ());
9723 /* Subroutine of the various build_*_call functions. Overload resolution
9724 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9725 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9726 bitmask of various LOOKUP_* flags which apply to the call itself. */
9728 static tree
9729 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9731 tree fn = cand->fn;
9732 const vec<tree, va_gc> *args = cand->args;
9733 tree first_arg = cand->first_arg;
9734 conversion **convs = cand->convs;
9735 conversion *conv;
9736 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9737 int parmlen;
9738 tree val;
9739 int i = 0;
9740 int j = 0;
9741 unsigned int arg_index = 0;
9742 int is_method = 0;
9743 int nargs;
9744 tree *argarray;
9745 bool already_used = false;
9747 /* In a template, there is no need to perform all of the work that
9748 is normally done. We are only interested in the type of the call
9749 expression, i.e., the return type of the function. Any semantic
9750 errors will be deferred until the template is instantiated. */
9751 if (processing_template_decl)
9753 if (undeduced_auto_decl (fn))
9754 mark_used (fn, complain);
9755 else
9756 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9757 See PR80598. */
9758 TREE_USED (fn) = 1;
9760 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9761 tree callee;
9762 if (first_arg == NULL_TREE)
9764 callee = build_addr_func (fn, complain);
9765 if (callee == error_mark_node)
9766 return error_mark_node;
9768 else
9770 callee = build_baselink (cand->conversion_path, cand->access_path,
9771 fn, NULL_TREE);
9772 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9773 first_arg, callee, NULL_TREE);
9776 tree expr = build_call_vec (return_type, callee, args);
9777 SET_EXPR_LOCATION (expr, input_location);
9778 if (TREE_THIS_VOLATILE (fn) && cfun)
9779 current_function_returns_abnormally = 1;
9780 if (immediate_invocation_p (fn))
9782 tree obj_arg = NULL_TREE, exprimm = expr;
9783 if (DECL_CONSTRUCTOR_P (fn))
9784 obj_arg = first_arg;
9785 if (obj_arg
9786 && is_dummy_object (obj_arg)
9787 && !type_dependent_expression_p (obj_arg))
9789 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9790 obj_arg = NULL_TREE;
9792 /* Look through *(const T *)&obj. */
9793 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9795 tree addr = TREE_OPERAND (obj_arg, 0);
9796 STRIP_NOPS (addr);
9797 if (TREE_CODE (addr) == ADDR_EXPR)
9799 tree typeo = TREE_TYPE (obj_arg);
9800 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9801 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9802 obj_arg = TREE_OPERAND (addr, 0);
9805 fold_non_dependent_expr (exprimm, complain,
9806 /*manifestly_const_eval=*/true,
9807 obj_arg);
9809 return convert_from_reference (expr);
9812 /* Give any warnings we noticed during overload resolution. */
9813 if (cand->warnings && (complain & tf_warning))
9815 struct candidate_warning *w;
9816 for (w = cand->warnings; w; w = w->next)
9817 joust (cand, w->loser, 1, complain);
9820 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9821 argument to the copy constructor ends up being a prvalue after
9822 conversion. Let's do the normal processing, but pretend we aren't
9823 actually using the copy constructor. */
9824 bool force_elide = false;
9825 if (cxx_dialect >= cxx17
9826 && cand->num_convs == 1
9827 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9828 && (DECL_COPY_CONSTRUCTOR_P (fn)
9829 || DECL_MOVE_CONSTRUCTOR_P (fn))
9830 && !unsafe_return_slot_p (first_arg)
9831 && conv_binds_ref_to_prvalue (convs[0]))
9833 force_elide = true;
9834 goto not_really_used;
9837 /* OK, we're actually calling this inherited constructor; set its deletedness
9838 appropriately. We can get away with doing this here because calling is
9839 the only way to refer to a constructor. */
9840 if (DECL_INHERITED_CTOR (fn)
9841 && !deduce_inheriting_ctor (fn))
9843 if (complain & tf_error)
9844 mark_used (fn);
9845 return error_mark_node;
9848 /* Make =delete work with SFINAE. */
9849 if (DECL_DELETED_FN (fn))
9851 if (complain & tf_error)
9852 mark_used (fn);
9853 return error_mark_node;
9856 if (DECL_FUNCTION_MEMBER_P (fn))
9858 tree access_fn;
9859 /* If FN is a template function, two cases must be considered.
9860 For example:
9862 struct A {
9863 protected:
9864 template <class T> void f();
9866 template <class T> struct B {
9867 protected:
9868 void g();
9870 struct C : A, B<int> {
9871 using A::f; // #1
9872 using B<int>::g; // #2
9875 In case #1 where `A::f' is a member template, DECL_ACCESS is
9876 recorded in the primary template but not in its specialization.
9877 We check access of FN using its primary template.
9879 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9880 because it is a member of class template B, DECL_ACCESS is
9881 recorded in the specialization `B<int>::g'. We cannot use its
9882 primary template because `B<T>::g' and `B<int>::g' may have
9883 different access. */
9884 if (DECL_TEMPLATE_INFO (fn)
9885 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9886 access_fn = DECL_TI_TEMPLATE (fn);
9887 else
9888 access_fn = fn;
9889 if (!perform_or_defer_access_check (cand->access_path, access_fn,
9890 fn, complain))
9891 return error_mark_node;
9894 /* If we're checking for implicit delete, don't bother with argument
9895 conversions. */
9896 if (flags & LOOKUP_SPECULATIVE)
9898 if (cand->viable == 1)
9899 return fn;
9900 else if (!(complain & tf_error))
9901 /* Reject bad conversions now. */
9902 return error_mark_node;
9903 /* else continue to get conversion error. */
9906 not_really_used:
9908 /* N3276 magic doesn't apply to nested calls. */
9909 tsubst_flags_t decltype_flag = (complain & tf_decltype);
9910 complain &= ~tf_decltype;
9911 /* No-Cleanup doesn't apply to nested calls either. */
9912 tsubst_flags_t no_cleanup_complain = complain;
9913 complain &= ~tf_no_cleanup;
9915 /* Find maximum size of vector to hold converted arguments. */
9916 parmlen = list_length (parm);
9917 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
9918 if (parmlen > nargs)
9919 nargs = parmlen;
9920 argarray = XALLOCAVEC (tree, nargs);
9922 in_consteval_if_p_temp_override icip;
9923 /* If the call is immediate function invocation, make sure
9924 taking address of immediate functions is allowed in its arguments. */
9925 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
9926 in_consteval_if_p = true;
9928 /* The implicit parameters to a constructor are not considered by overload
9929 resolution, and must be of the proper type. */
9930 if (DECL_CONSTRUCTOR_P (fn))
9932 tree object_arg;
9933 if (first_arg != NULL_TREE)
9935 object_arg = first_arg;
9936 first_arg = NULL_TREE;
9938 else
9940 object_arg = (*args)[arg_index];
9941 ++arg_index;
9943 argarray[j++] = build_this (object_arg);
9944 parm = TREE_CHAIN (parm);
9945 /* We should never try to call the abstract constructor. */
9946 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9948 if (DECL_HAS_VTT_PARM_P (fn))
9950 argarray[j++] = (*args)[arg_index];
9951 ++arg_index;
9952 parm = TREE_CHAIN (parm);
9955 /* Bypass access control for 'this' parameter. */
9956 else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9958 tree arg = build_this (first_arg != NULL_TREE
9959 ? first_arg
9960 : (*args)[arg_index]);
9961 tree argtype = TREE_TYPE (arg);
9963 if (arg == error_mark_node)
9964 return error_mark_node;
9966 if (convs[i]->bad_p)
9968 if (complain & tf_error)
9970 auto_diagnostic_group d;
9971 if (permerror (input_location, "passing %qT as %<this%> "
9972 "argument discards qualifiers",
9973 TREE_TYPE (argtype)))
9974 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
9976 else
9977 return error_mark_node;
9980 /* The class where FN is defined. */
9981 tree ctx = DECL_CONTEXT (fn);
9983 /* See if the function member or the whole class type is declared
9984 final and the call can be devirtualized. */
9985 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9986 flags |= LOOKUP_NONVIRTUAL;
9988 /* [class.mfct.non-static]: If a non-static member function of a class
9989 X is called for an object that is not of type X, or of a type
9990 derived from X, the behavior is undefined.
9992 So we can assume that anything passed as 'this' is non-null, and
9993 optimize accordingly. */
9994 /* Check that the base class is accessible. */
9995 if (!accessible_base_p (TREE_TYPE (argtype),
9996 BINFO_TYPE (cand->conversion_path), true))
9998 if (complain & tf_error)
9999 error ("%qT is not an accessible base of %qT",
10000 BINFO_TYPE (cand->conversion_path),
10001 TREE_TYPE (argtype));
10002 else
10003 return error_mark_node;
10005 /* If fn was found by a using declaration, the conversion path
10006 will be to the derived class, not the base declaring fn. We
10007 must convert to the base. */
10008 tree base_binfo = cand->conversion_path;
10009 if (BINFO_TYPE (base_binfo) != ctx)
10011 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10012 if (base_binfo == error_mark_node)
10013 return error_mark_node;
10016 /* If we know the dynamic type of the object, look up the final overrider
10017 in the BINFO. */
10018 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10019 && resolves_to_fixed_type_p (arg))
10021 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10023 /* And unwind base_binfo to match. If we don't find the type we're
10024 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10025 inheritance; for now do a normal virtual call in that case. */
10026 tree octx = DECL_CONTEXT (ov);
10027 tree obinfo = base_binfo;
10028 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10029 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10030 if (obinfo)
10032 fn = ov;
10033 base_binfo = obinfo;
10034 flags |= LOOKUP_NONVIRTUAL;
10038 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10039 base_binfo, 1, complain);
10041 argarray[j++] = converted_arg;
10042 parm = TREE_CHAIN (parm);
10043 if (first_arg != NULL_TREE)
10044 first_arg = NULL_TREE;
10045 else
10046 ++arg_index;
10047 ++i;
10048 is_method = 1;
10051 gcc_assert (first_arg == NULL_TREE);
10052 for (; arg_index < vec_safe_length (args) && parm;
10053 parm = TREE_CHAIN (parm), ++arg_index, ++i)
10055 tree type = TREE_VALUE (parm);
10056 tree arg = (*args)[arg_index];
10057 bool conversion_warning = true;
10059 conv = convs[i];
10061 /* If the argument is NULL and used to (implicitly) instantiate a
10062 template function (and bind one of the template arguments to
10063 the type of 'long int'), we don't want to warn about passing NULL
10064 to non-pointer argument.
10065 For example, if we have this template function:
10067 template<typename T> void func(T x) {}
10069 we want to warn (when -Wconversion is enabled) in this case:
10071 void foo() {
10072 func<int>(NULL);
10075 but not in this case:
10077 void foo() {
10078 func(NULL);
10081 if (null_node_p (arg)
10082 && DECL_TEMPLATE_INFO (fn)
10083 && cand->template_decl
10084 && !cand->explicit_targs)
10085 conversion_warning = false;
10087 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10088 knows not to allow any more UDCs. This needs to happen after we
10089 process cand->warnings. */
10090 if (flags & LOOKUP_NO_CONVERSION)
10091 conv->user_conv_p = true;
10093 tsubst_flags_t arg_complain = complain;
10094 if (!conversion_warning)
10095 arg_complain &= ~tf_warning;
10097 if (arg_complain & tf_warning)
10098 maybe_warn_pessimizing_move (arg, type, /*return_p*/false);
10100 val = convert_like_with_context (conv, arg, fn, i - is_method,
10101 arg_complain);
10102 val = convert_for_arg_passing (type, val, arg_complain);
10104 if (val == error_mark_node)
10105 return error_mark_node;
10106 else
10107 argarray[j++] = val;
10110 /* Default arguments */
10111 for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
10113 if (TREE_VALUE (parm) == error_mark_node)
10114 return error_mark_node;
10115 val = convert_default_arg (TREE_VALUE (parm),
10116 TREE_PURPOSE (parm),
10117 fn, i - is_method,
10118 complain);
10119 if (val == error_mark_node)
10120 return error_mark_node;
10121 argarray[j++] = val;
10124 /* Ellipsis */
10125 int magic = magic_varargs_p (fn);
10126 for (; arg_index < vec_safe_length (args); ++arg_index)
10128 tree a = (*args)[arg_index];
10129 if (magic == 3 && arg_index == 2)
10131 /* Do no conversions for certain magic varargs. */
10132 a = mark_type_use (a);
10133 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10134 return error_mark_node;
10136 else if (magic != 0)
10138 /* Don't truncate excess precision to the semantic type. */
10139 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10140 a = TREE_OPERAND (a, 0);
10141 /* For other magic varargs only do decay_conversion. */
10142 a = decay_conversion (a, complain);
10144 else if (DECL_CONSTRUCTOR_P (fn)
10145 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10146 TREE_TYPE (a)))
10148 /* Avoid infinite recursion trying to call A(...). */
10149 if (complain & tf_error)
10150 /* Try to call the actual copy constructor for a good error. */
10151 call_copy_ctor (a, complain);
10152 return error_mark_node;
10154 else
10155 a = convert_arg_to_ellipsis (a, complain);
10156 if (a == error_mark_node)
10157 return error_mark_node;
10158 argarray[j++] = a;
10161 gcc_assert (j <= nargs);
10162 nargs = j;
10163 icip.reset ();
10165 /* Avoid performing argument transformation if warnings are disabled.
10166 When tf_warning is set and at least one of the warnings is active
10167 the check_function_arguments function might warn about something. */
10169 bool warned_p = false;
10170 if ((complain & tf_warning)
10171 && (warn_nonnull
10172 || warn_format
10173 || warn_suggest_attribute_format
10174 || warn_restrict))
10176 tree *fargs = (!nargs ? argarray
10177 : (tree *) alloca (nargs * sizeof (tree)));
10178 for (j = 0; j < nargs; j++)
10180 /* For -Wformat undo the implicit passing by hidden reference
10181 done by convert_arg_to_ellipsis. */
10182 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10183 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10184 fargs[j] = TREE_OPERAND (argarray[j], 0);
10185 else
10186 fargs[j] = argarray[j];
10189 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
10190 nargs, fargs, NULL);
10193 if (DECL_INHERITED_CTOR (fn))
10195 /* Check for passing ellipsis arguments to an inherited constructor. We
10196 could handle this by open-coding the inherited constructor rather than
10197 defining it, but let's not bother now. */
10198 if (!cp_unevaluated_operand
10199 && cand->num_convs
10200 && cand->convs[cand->num_convs-1]->ellipsis_p)
10202 if (complain & tf_error)
10204 sorry ("passing arguments to ellipsis of inherited constructor "
10205 "%qD", cand->fn);
10206 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10208 return error_mark_node;
10211 /* A base constructor inheriting from a virtual base doesn't get the
10212 inherited arguments, just this and __vtt. */
10213 if (ctor_omit_inherited_parms (fn))
10214 nargs = 2;
10217 /* Avoid actually calling copy constructors and copy assignment operators,
10218 if possible. */
10220 if (! flag_elide_constructors && !force_elide)
10221 /* Do things the hard way. */;
10222 else if (cand->num_convs == 1
10223 && (DECL_COPY_CONSTRUCTOR_P (fn)
10224 || DECL_MOVE_CONSTRUCTOR_P (fn))
10225 /* It's unsafe to elide the constructor when handling
10226 a noexcept-expression, it may evaluate to the wrong
10227 value (c++/53025). */
10228 && (force_elide || cp_noexcept_operand == 0))
10230 tree targ;
10231 tree arg = argarray[num_artificial_parms_for (fn)];
10232 tree fa = argarray[0];
10233 bool trivial = trivial_fn_p (fn);
10235 /* Pull out the real argument, disregarding const-correctness. */
10236 targ = arg;
10237 /* Strip the reference binding for the constructor parameter. */
10238 if (CONVERT_EXPR_P (targ)
10239 && TYPE_REF_P (TREE_TYPE (targ)))
10240 targ = TREE_OPERAND (targ, 0);
10241 /* But don't strip any other reference bindings; binding a temporary to a
10242 reference prevents copy elision. */
10243 while ((CONVERT_EXPR_P (targ)
10244 && !TYPE_REF_P (TREE_TYPE (targ)))
10245 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10246 targ = TREE_OPERAND (targ, 0);
10247 if (TREE_CODE (targ) == ADDR_EXPR)
10249 targ = TREE_OPERAND (targ, 0);
10250 if (!same_type_ignoring_top_level_qualifiers_p
10251 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10252 targ = NULL_TREE;
10254 else
10255 targ = NULL_TREE;
10257 if (targ)
10258 arg = targ;
10259 else
10260 arg = cp_build_fold_indirect_ref (arg);
10262 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10263 potentially-overlapping subobject. */
10264 if (CHECKING_P && cxx_dialect >= cxx17)
10265 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10266 || force_elide
10267 /* It's from binding the ref parm to a packed field. */
10268 || convs[0]->need_temporary_p
10269 || seen_error ()
10270 /* See unsafe_copy_elision_p. */
10271 || unsafe_return_slot_p (fa));
10273 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
10274 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10276 /* [class.copy]: the copy constructor is implicitly defined even if the
10277 implementation elided its use. But don't warn about deprecation when
10278 eliding a temporary, as then no copy is actually performed. */
10279 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10280 if (force_elide)
10281 /* The language says this isn't called. */;
10282 else if (!trivial)
10284 if (!mark_used (fn, complain) && !(complain & tf_error))
10285 return error_mark_node;
10286 already_used = true;
10288 else
10289 cp_handle_deprecated_or_unavailable (fn, complain);
10291 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10292 && !make_base_init_ok (arg))
10293 unsafe = true;
10295 /* If we're creating a temp and we already have one, don't create a
10296 new one. If we're not creating a temp but we get one, use
10297 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10298 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10299 temp or an INIT_EXPR otherwise. */
10300 if (is_dummy_object (fa))
10302 if (TREE_CODE (arg) == TARGET_EXPR)
10303 return arg;
10304 else if (trivial)
10305 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10307 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10308 && !unsafe)
10310 tree to = cp_build_fold_indirect_ref (fa);
10311 val = cp_build_init_expr (to, arg);
10312 return val;
10315 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10316 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10317 && trivial_fn_p (fn))
10319 /* Don't use cp_build_fold_indirect_ref, op= returns an lvalue even if
10320 the object argument isn't one. */
10321 tree to = cp_build_indirect_ref (input_location, argarray[0],
10322 RO_ARROW, complain);
10323 tree type = TREE_TYPE (to);
10324 tree as_base = CLASSTYPE_AS_BASE (type);
10325 tree arg = argarray[1];
10326 location_t loc = cp_expr_loc_or_input_loc (arg);
10328 if (is_really_empty_class (type, /*ignore_vptr*/true))
10330 /* Avoid copying empty classes. */
10331 val = build2 (COMPOUND_EXPR, type, arg, to);
10332 suppress_warning (val, OPT_Wunused);
10334 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10336 if (is_std_init_list (type)
10337 && conv_binds_ref_to_prvalue (convs[1]))
10338 warning_at (loc, OPT_Winit_list_lifetime,
10339 "assignment from temporary %<initializer_list%> does "
10340 "not extend the lifetime of the underlying array");
10341 arg = cp_build_fold_indirect_ref (arg);
10342 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10344 else
10346 /* We must only copy the non-tail padding parts. */
10347 tree arg0, arg2, t;
10348 tree array_type, alias_set;
10350 arg2 = TYPE_SIZE_UNIT (as_base);
10351 to = cp_stabilize_reference (to);
10352 arg0 = cp_build_addr_expr (to, complain);
10354 array_type = build_array_type (unsigned_char_type_node,
10355 build_index_type
10356 (size_binop (MINUS_EXPR,
10357 arg2, size_int (1))));
10358 alias_set = build_int_cst (build_pointer_type (type), 0);
10359 t = build2 (MODIFY_EXPR, void_type_node,
10360 build2 (MEM_REF, array_type, arg0, alias_set),
10361 build2 (MEM_REF, array_type, arg, alias_set));
10362 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10363 suppress_warning (val, OPT_Wunused);
10366 cp_handle_deprecated_or_unavailable (fn, complain);
10368 return val;
10370 else if (trivial_fn_p (fn))
10372 if (DECL_DESTRUCTOR_P (fn))
10373 return build_trivial_dtor_call (argarray[0]);
10374 else if (default_ctor_p (fn))
10376 if (is_dummy_object (argarray[0]))
10377 return force_target_expr (DECL_CONTEXT (fn), void_node,
10378 no_cleanup_complain);
10379 else
10380 return cp_build_fold_indirect_ref (argarray[0]);
10384 gcc_assert (!force_elide);
10386 if (!already_used
10387 && !mark_used (fn, complain))
10388 return error_mark_node;
10390 /* Warn if the built-in writes to an object of a non-trivial type. */
10391 if (warn_class_memaccess
10392 && vec_safe_length (args) >= 2
10393 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10394 maybe_warn_class_memaccess (input_location, fn, args);
10396 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10398 tree t;
10399 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10400 DECL_CONTEXT (fn),
10401 ba_any, NULL, complain);
10402 gcc_assert (binfo && binfo != error_mark_node);
10404 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10405 complain);
10406 if (TREE_SIDE_EFFECTS (argarray[0]))
10407 argarray[0] = save_expr (argarray[0]);
10408 t = build_pointer_type (TREE_TYPE (fn));
10409 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10410 TREE_TYPE (fn) = t;
10412 else
10414 /* If FN is marked deprecated, then we've already issued a deprecated-use
10415 warning from mark_used above, so avoid redundantly issuing another one
10416 from build_addr_func. */
10417 warning_sentinel w (warn_deprecated_decl);
10419 fn = build_addr_func (fn, complain);
10420 if (fn == error_mark_node)
10421 return error_mark_node;
10424 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10425 if (call == error_mark_node)
10426 return call;
10427 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10429 tree c = extract_call_expr (call);
10430 /* build_new_op will clear this when appropriate. */
10431 CALL_EXPR_ORDERED_ARGS (c) = true;
10433 if (warned_p)
10435 tree c = extract_call_expr (call);
10436 if (TREE_CODE (c) == CALL_EXPR)
10437 suppress_warning (c /* Suppress all warnings. */);
10439 if (TREE_CODE (fn) == ADDR_EXPR)
10441 tree fndecl = STRIP_TEMPLATE (TREE_OPERAND (fn, 0));
10442 if (immediate_invocation_p (fndecl))
10444 tree obj_arg = NULL_TREE;
10445 /* Undo convert_from_reference called by build_cxx_call. */
10446 if (REFERENCE_REF_P (call))
10447 call = TREE_OPERAND (call, 0);
10448 if (DECL_CONSTRUCTOR_P (fndecl))
10449 obj_arg = cand->first_arg ? cand->first_arg : (*args)[0];
10450 if (obj_arg && is_dummy_object (obj_arg))
10452 call = build_cplus_new (DECL_CONTEXT (fndecl), call, complain);
10453 obj_arg = NULL_TREE;
10455 /* Look through *(const T *)&obj. */
10456 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
10458 tree addr = TREE_OPERAND (obj_arg, 0);
10459 STRIP_NOPS (addr);
10460 if (TREE_CODE (addr) == ADDR_EXPR)
10462 tree typeo = TREE_TYPE (obj_arg);
10463 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
10464 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
10465 obj_arg = TREE_OPERAND (addr, 0);
10468 call = cxx_constant_value (call, obj_arg, complain);
10469 if (obj_arg && !error_operand_p (call))
10470 call = cp_build_init_expr (obj_arg, call);
10471 call = convert_from_reference (call);
10474 return call;
10477 namespace
10480 /* Return the DECL of the first non-static subobject of class TYPE
10481 that satisfies the predicate PRED or null if none can be found. */
10483 template <class Predicate>
10484 tree
10485 first_non_static_field (tree type, Predicate pred)
10487 if (!type || !CLASS_TYPE_P (type))
10488 return NULL_TREE;
10490 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10492 if (TREE_CODE (field) != FIELD_DECL)
10493 continue;
10494 if (TREE_STATIC (field))
10495 continue;
10496 if (pred (field))
10497 return field;
10500 int i = 0;
10502 for (tree base_binfo, binfo = TYPE_BINFO (type);
10503 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10505 tree base = TREE_TYPE (base_binfo);
10506 if (pred (base))
10507 return base;
10508 if (tree field = first_non_static_field (base, pred))
10509 return field;
10512 return NULL_TREE;
10515 struct NonPublicField
10517 bool operator() (const_tree t) const
10519 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10523 /* Return the DECL of the first non-public subobject of class TYPE
10524 or null if none can be found. */
10526 static inline tree
10527 first_non_public_field (tree type)
10529 return first_non_static_field (type, NonPublicField ());
10532 struct NonTrivialField
10534 bool operator() (const_tree t) const
10536 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10540 /* Return the DECL of the first non-trivial subobject of class TYPE
10541 or null if none can be found. */
10543 static inline tree
10544 first_non_trivial_field (tree type)
10546 return first_non_static_field (type, NonTrivialField ());
10549 } /* unnamed namespace */
10551 /* Return true if all copy and move assignment operator overloads for
10552 class TYPE are trivial and at least one of them is not deleted and,
10553 when ACCESS is set, accessible. Return false otherwise. Set
10554 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10555 copy or move assignment. */
10557 static bool
10558 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10560 tree fns = get_class_binding (type, assign_op_identifier);
10561 bool all_trivial = true;
10563 /* Iterate over overloads of the assignment operator, checking
10564 accessible copy assignments for triviality. */
10566 for (tree f : ovl_range (fns))
10568 /* Skip operators that aren't copy assignments. */
10569 if (!copy_fn_p (f))
10570 continue;
10572 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10573 || accessible_p (TYPE_BINFO (type), f, true));
10575 /* Skip template assignment operators and deleted functions. */
10576 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10577 continue;
10579 if (accessible)
10580 *hasassign = true;
10582 if (!accessible || !trivial_fn_p (f))
10583 all_trivial = false;
10585 /* Break early when both properties have been determined. */
10586 if (*hasassign && !all_trivial)
10587 break;
10590 /* Return true if they're all trivial and one of the expressions
10591 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10592 tree ref = cp_build_reference_type (type, false);
10593 return (all_trivial
10594 && (is_trivially_xible (MODIFY_EXPR, type, type)
10595 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10598 /* Return true if all copy and move ctor overloads for class TYPE are
10599 trivial and at least one of them is not deleted and, when ACCESS is
10600 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10601 to true when the TYPE has a (not necessarily trivial) default and copy
10602 (or move) ctor, respectively. */
10604 static bool
10605 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10607 tree fns = get_class_binding (type, complete_ctor_identifier);
10608 bool all_trivial = true;
10610 for (tree f : ovl_range (fns))
10612 /* Skip template constructors. */
10613 if (TREE_CODE (f) != FUNCTION_DECL)
10614 continue;
10616 bool cpy_or_move_ctor_p = copy_fn_p (f);
10618 /* Skip ctors other than default, copy, and move. */
10619 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10620 continue;
10622 if (DECL_DELETED_FN (f))
10623 continue;
10625 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10626 || accessible_p (TYPE_BINFO (type), f, true));
10628 if (accessible)
10629 hasctor[cpy_or_move_ctor_p] = true;
10631 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10632 all_trivial = false;
10634 /* Break early when both properties have been determined. */
10635 if (hasctor[0] && hasctor[1] && !all_trivial)
10636 break;
10639 return all_trivial;
10642 /* Issue a warning on a call to the built-in function FNDECL if it is
10643 a raw memory write whose destination is not an object of (something
10644 like) trivial or standard layout type with a non-deleted assignment
10645 and copy ctor. Detects const correctness violations, corrupting
10646 references, virtual table pointers, and bypassing non-trivial
10647 assignments. */
10649 static void
10650 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10651 const vec<tree, va_gc> *args)
10653 /* Except for bcopy where it's second, the destination pointer is
10654 the first argument for all functions handled here. Compute
10655 the index of the destination and source arguments. */
10656 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10657 unsigned srcidx = !dstidx;
10659 tree dest = (*args)[dstidx];
10660 if (!TREE_TYPE (dest)
10661 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10662 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10663 return;
10665 tree srctype = NULL_TREE;
10667 /* Determine the type of the pointed-to object and whether it's
10668 a complete class type. */
10669 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10671 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10672 return;
10674 /* Check to see if the raw memory call is made by a non-static member
10675 function with THIS as the destination argument for the destination
10676 type. If so, and if the class has no non-trivial bases or members,
10677 be more permissive. */
10678 if (current_function_decl
10679 && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10680 && is_this_parameter (tree_strip_nop_conversions (dest)))
10682 tree ctx = DECL_CONTEXT (current_function_decl);
10683 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10684 tree binfo = TYPE_BINFO (ctx);
10686 if (special
10687 && !BINFO_VTABLE (binfo)
10688 && !first_non_trivial_field (desttype))
10689 return;
10692 /* True if the class is trivial. */
10693 bool trivial = trivial_type_p (desttype);
10695 /* Set to true if DESTYPE has an accessible copy assignment. */
10696 bool hasassign = false;
10697 /* True if all of the class' overloaded copy assignment operators
10698 are all trivial (and not deleted) and at least one of them is
10699 accessible. */
10700 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10702 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10703 respectively. */
10704 bool hasctors[2] = { false, false };
10706 /* True if all of the class' overloaded copy constructors are all
10707 trivial (and not deleted) and at least one of them is accessible. */
10708 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10710 /* Set FLD to the first private/protected member of the class. */
10711 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10713 /* The warning format string. */
10714 const char *warnfmt = NULL;
10715 /* A suggested alternative to offer instead of the raw memory call.
10716 Empty string when none can be come up with. */
10717 const char *suggest = "";
10718 bool warned = false;
10720 switch (DECL_FUNCTION_CODE (fndecl))
10722 case BUILT_IN_MEMSET:
10723 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10725 /* Diagnose setting non-copy-assignable or non-trivial types,
10726 or types with a private member, to (potentially) non-zero
10727 bytes. Since the value of the bytes being written is unknown,
10728 suggest using assignment instead (if one exists). Also warn
10729 for writes into objects for which zero-initialization doesn't
10730 mean all bits clear (pointer-to-member data, where null is all
10731 bits set). Since the value being written is (most likely)
10732 non-zero, simply suggest assignment (but not copy assignment). */
10733 suggest = "; use assignment instead";
10734 if (!trivassign)
10735 warnfmt = G_("%qD writing to an object of type %#qT with "
10736 "no trivial copy-assignment");
10737 else if (!trivial)
10738 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10739 else if (fld)
10741 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10742 warned = warning_at (loc, OPT_Wclass_memaccess,
10743 "%qD writing to an object of type %#qT with "
10744 "%qs member %qD",
10745 fndecl, desttype, access, fld);
10747 else if (!zero_init_p (desttype))
10748 warnfmt = G_("%qD writing to an object of type %#qT containing "
10749 "a pointer to data member%s");
10751 break;
10753 /* Fall through. */
10755 case BUILT_IN_BZERO:
10756 /* Similarly to the above, diagnose clearing non-trivial or non-
10757 standard layout objects, or objects of types with no assignmenmt.
10758 Since the value being written is known to be zero, suggest either
10759 copy assignment, copy ctor, or default ctor as an alternative,
10760 depending on what's available. */
10762 if (hasassign && hasctors[0])
10763 suggest = G_("; use assignment or value-initialization instead");
10764 else if (hasassign)
10765 suggest = G_("; use assignment instead");
10766 else if (hasctors[0])
10767 suggest = G_("; use value-initialization instead");
10769 if (!trivassign)
10770 warnfmt = G_("%qD clearing an object of type %#qT with "
10771 "no trivial copy-assignment%s");
10772 else if (!trivial)
10773 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10774 else if (!zero_init_p (desttype))
10775 warnfmt = G_("%qD clearing an object of type %#qT containing "
10776 "a pointer-to-member%s");
10777 break;
10779 case BUILT_IN_BCOPY:
10780 case BUILT_IN_MEMCPY:
10781 case BUILT_IN_MEMMOVE:
10782 case BUILT_IN_MEMPCPY:
10783 /* Determine the type of the source object. */
10784 srctype = TREE_TYPE ((*args)[srcidx]);
10785 if (!srctype || !INDIRECT_TYPE_P (srctype))
10786 srctype = void_type_node;
10787 else
10788 srctype = TREE_TYPE (srctype);
10790 /* Since it's impossible to determine wheter the byte copy is
10791 being used in place of assignment to an existing object or
10792 as a substitute for initialization, assume it's the former.
10793 Determine the best alternative to use instead depending on
10794 what's not deleted. */
10795 if (hasassign && hasctors[1])
10796 suggest = G_("; use copy-assignment or copy-initialization instead");
10797 else if (hasassign)
10798 suggest = G_("; use copy-assignment instead");
10799 else if (hasctors[1])
10800 suggest = G_("; use copy-initialization instead");
10802 if (!trivassign)
10803 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10804 "copy-assignment%s");
10805 else if (!trivially_copyable_p (desttype))
10806 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10807 "type %#qT%s");
10808 else if (!trivcopy)
10809 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10811 else if (!trivial
10812 && !VOID_TYPE_P (srctype)
10813 && !is_byte_access_type (srctype)
10814 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10815 srctype))
10817 /* Warn when copying into a non-trivial object from an object
10818 of a different type other than void or char. */
10819 warned = warning_at (loc, OPT_Wclass_memaccess,
10820 "%qD copying an object of non-trivial type "
10821 "%#qT from an array of %#qT",
10822 fndecl, desttype, srctype);
10824 else if (fld
10825 && !VOID_TYPE_P (srctype)
10826 && !is_byte_access_type (srctype)
10827 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10828 srctype))
10830 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10831 warned = warning_at (loc, OPT_Wclass_memaccess,
10832 "%qD copying an object of type %#qT with "
10833 "%qs member %qD from an array of %#qT; use "
10834 "assignment or copy-initialization instead",
10835 fndecl, desttype, access, fld, srctype);
10837 else if (!trivial && vec_safe_length (args) > 2)
10839 tree sz = maybe_constant_value ((*args)[2]);
10840 if (!tree_fits_uhwi_p (sz))
10841 break;
10843 /* Finally, warn on partial copies. */
10844 unsigned HOST_WIDE_INT typesize
10845 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10846 if (typesize == 0)
10847 break;
10848 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10849 warned = warning_at (loc, OPT_Wclass_memaccess,
10850 (typesize - partial > 1
10851 ? G_("%qD writing to an object of "
10852 "a non-trivial type %#qT leaves %wu "
10853 "bytes unchanged")
10854 : G_("%qD writing to an object of "
10855 "a non-trivial type %#qT leaves %wu "
10856 "byte unchanged")),
10857 fndecl, desttype, typesize - partial);
10859 break;
10861 case BUILT_IN_REALLOC:
10863 if (!trivially_copyable_p (desttype))
10864 warnfmt = G_("%qD moving an object of non-trivially copyable type "
10865 "%#qT; use %<new%> and %<delete%> instead");
10866 else if (!trivcopy)
10867 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10868 "constructor; use %<new%> and %<delete%> instead");
10869 else if (!get_dtor (desttype, tf_none))
10870 warnfmt = G_("%qD moving an object of type %#qT with deleted "
10871 "destructor");
10872 else if (!trivial)
10874 tree sz = maybe_constant_value ((*args)[1]);
10875 if (TREE_CODE (sz) == INTEGER_CST
10876 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10877 /* Finally, warn on reallocation into insufficient space. */
10878 warned = warning_at (loc, OPT_Wclass_memaccess,
10879 "%qD moving an object of non-trivial type "
10880 "%#qT and size %E into a region of size %E",
10881 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10882 sz);
10884 break;
10886 default:
10887 return;
10890 if (warnfmt)
10892 if (suggest)
10893 warned = warning_at (loc, OPT_Wclass_memaccess,
10894 warnfmt, fndecl, desttype, suggest);
10895 else
10896 warned = warning_at (loc, OPT_Wclass_memaccess,
10897 warnfmt, fndecl, desttype);
10900 if (warned)
10901 inform (location_of (desttype), "%#qT declared here", desttype);
10904 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10905 If FN is the result of resolving an overloaded target built-in,
10906 ORIG_FNDECL is the original function decl, otherwise it is null.
10907 This function performs no overload resolution, conversion, or other
10908 high-level operations. */
10910 tree
10911 build_cxx_call (tree fn, int nargs, tree *argarray,
10912 tsubst_flags_t complain, tree orig_fndecl)
10914 tree fndecl;
10916 /* Remember roughly where this call is. */
10917 location_t loc = cp_expr_loc_or_input_loc (fn);
10918 fn = build_call_a (fn, nargs, argarray);
10919 SET_EXPR_LOCATION (fn, loc);
10921 fndecl = get_callee_fndecl (fn);
10922 if (!orig_fndecl)
10923 orig_fndecl = fndecl;
10925 /* Check that arguments to builtin functions match the expectations. */
10926 if (fndecl
10927 && !processing_template_decl
10928 && fndecl_built_in_p (fndecl))
10930 int i;
10932 /* We need to take care that values to BUILT_IN_NORMAL
10933 are reduced. */
10934 for (i = 0; i < nargs; i++)
10935 argarray[i] = maybe_constant_value (argarray[i]);
10937 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10938 orig_fndecl, nargs, argarray))
10939 return error_mark_node;
10940 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
10942 tree arg0 = argarray[0];
10943 STRIP_NOPS (arg0);
10944 if (TREE_CODE (arg0) == ADDR_EXPR
10945 && DECL_P (TREE_OPERAND (arg0, 0))
10946 && same_type_ignoring_top_level_qualifiers_p
10947 (TREE_TYPE (TREE_TYPE (argarray[0])),
10948 TREE_TYPE (TREE_TYPE (arg0))))
10949 /* For __builtin_clear_padding (&var) we know the type
10950 is for a complete object, so there is no risk in clearing
10951 padding that is reused in some derived class member. */;
10952 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
10954 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
10955 "argument %u in call to function %qE "
10956 "has pointer to a non-trivially-copyable type (%qT)",
10957 1, fndecl, TREE_TYPE (argarray[0]));
10958 return error_mark_node;
10963 if (VOID_TYPE_P (TREE_TYPE (fn)))
10964 return fn;
10966 /* 5.2.2/11: If a function call is a prvalue of object type: if the
10967 function call is either the operand of a decltype-specifier or the
10968 right operand of a comma operator that is the operand of a
10969 decltype-specifier, a temporary object is not introduced for the
10970 prvalue. The type of the prvalue may be incomplete. */
10971 if (!(complain & tf_decltype))
10973 fn = require_complete_type (fn, complain);
10974 if (fn == error_mark_node)
10975 return error_mark_node;
10977 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10979 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10980 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10983 return convert_from_reference (fn);
10986 /* Returns the value to use for the in-charge parameter when making a
10987 call to a function with the indicated NAME.
10989 FIXME:Can't we find a neater way to do this mapping? */
10991 tree
10992 in_charge_arg_for_name (tree name)
10994 if (IDENTIFIER_CTOR_P (name))
10996 if (name == complete_ctor_identifier)
10997 return integer_one_node;
10998 gcc_checking_assert (name == base_ctor_identifier);
11000 else
11002 if (name == complete_dtor_identifier)
11003 return integer_two_node;
11004 else if (name == deleting_dtor_identifier)
11005 return integer_three_node;
11006 gcc_checking_assert (name == base_dtor_identifier);
11009 return integer_zero_node;
11012 /* We've built up a constructor call RET. Complain if it delegates to the
11013 constructor we're currently compiling. */
11015 static void
11016 check_self_delegation (tree ret)
11018 if (TREE_CODE (ret) == TARGET_EXPR)
11019 ret = TARGET_EXPR_INITIAL (ret);
11020 tree fn = cp_get_callee_fndecl_nofold (ret);
11021 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11022 error ("constructor delegates to itself");
11025 /* Build a call to a constructor, destructor, or an assignment
11026 operator for INSTANCE, an expression with class type. NAME
11027 indicates the special member function to call; *ARGS are the
11028 arguments. ARGS may be NULL. This may change ARGS. BINFO
11029 indicates the base of INSTANCE that is to be passed as the `this'
11030 parameter to the member function called.
11032 FLAGS are the LOOKUP_* flags to use when processing the call.
11034 If NAME indicates a complete object constructor, INSTANCE may be
11035 NULL_TREE. In this case, the caller will call build_cplus_new to
11036 store the newly constructed object into a VAR_DECL. */
11038 tree
11039 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11040 tree binfo, int flags, tsubst_flags_t complain)
11042 tree fns;
11043 /* The type of the subobject to be constructed or destroyed. */
11044 tree class_type;
11045 vec<tree, va_gc> *allocated = NULL;
11046 tree ret;
11048 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11050 if (error_operand_p (instance))
11051 return error_mark_node;
11053 if (IDENTIFIER_DTOR_P (name))
11055 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11056 if (!type_build_dtor_call (TREE_TYPE (instance)))
11057 /* Shortcut to avoid lazy destructor declaration. */
11058 return build_trivial_dtor_call (instance);
11061 if (TYPE_P (binfo))
11063 /* Resolve the name. */
11064 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11065 return error_mark_node;
11067 binfo = TYPE_BINFO (binfo);
11070 gcc_assert (binfo != NULL_TREE);
11072 class_type = BINFO_TYPE (binfo);
11074 /* Handle the special case where INSTANCE is NULL_TREE. */
11075 if (name == complete_ctor_identifier && !instance)
11076 instance = build_dummy_object (class_type);
11077 else
11079 /* Convert to the base class, if necessary. */
11080 if (!same_type_ignoring_top_level_qualifiers_p
11081 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11083 if (IDENTIFIER_CDTOR_P (name))
11084 /* For constructors and destructors, either the base is
11085 non-virtual, or it is virtual but we are doing the
11086 conversion from a constructor or destructor for the
11087 complete object. In either case, we can convert
11088 statically. */
11089 instance = convert_to_base_statically (instance, binfo);
11090 else
11092 /* However, for assignment operators, we must convert
11093 dynamically if the base is virtual. */
11094 gcc_checking_assert (name == assign_op_identifier);
11095 instance = build_base_path (PLUS_EXPR, instance,
11096 binfo, /*nonnull=*/1, complain);
11101 gcc_assert (instance != NULL_TREE);
11103 /* In C++17, "If the initializer expression is a prvalue and the
11104 cv-unqualified version of the source type is the same class as the class
11105 of the destination, the initializer expression is used to initialize the
11106 destination object." Handle that here to avoid doing overload
11107 resolution. */
11108 if (cxx_dialect >= cxx17
11109 && args && vec_safe_length (*args) == 1
11110 && !unsafe_return_slot_p (instance))
11112 tree arg = (**args)[0];
11114 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11115 && !TYPE_HAS_LIST_CTOR (class_type)
11116 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11117 && CONSTRUCTOR_NELTS (arg) == 1)
11118 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11120 if ((TREE_CODE (arg) == TARGET_EXPR
11121 || TREE_CODE (arg) == CONSTRUCTOR)
11122 && (same_type_ignoring_top_level_qualifiers_p
11123 (class_type, TREE_TYPE (arg))))
11125 if (is_dummy_object (instance))
11126 return arg;
11127 else if (TREE_CODE (arg) == TARGET_EXPR)
11128 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11130 if ((complain & tf_error)
11131 && (flags & LOOKUP_DELEGATING_CONS))
11132 check_self_delegation (arg);
11133 /* Avoid change of behavior on Wunused-var-2.C. */
11134 instance = mark_lvalue_use (instance);
11135 return cp_build_init_expr (instance, arg);
11139 fns = lookup_fnfields (binfo, name, 1, complain);
11141 /* When making a call to a constructor or destructor for a subobject
11142 that uses virtual base classes, pass down a pointer to a VTT for
11143 the subobject. */
11144 if ((name == base_ctor_identifier
11145 || name == base_dtor_identifier)
11146 && CLASSTYPE_VBASECLASSES (class_type))
11148 tree vtt;
11149 tree sub_vtt;
11151 /* If the current function is a complete object constructor
11152 or destructor, then we fetch the VTT directly.
11153 Otherwise, we look it up using the VTT we were given. */
11154 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11155 vtt = decay_conversion (vtt, complain);
11156 if (vtt == error_mark_node)
11157 return error_mark_node;
11158 vtt = build_if_in_charge (vtt, current_vtt_parm);
11159 if (BINFO_SUBVTT_INDEX (binfo))
11160 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11161 else
11162 sub_vtt = vtt;
11164 if (args == NULL)
11166 allocated = make_tree_vector ();
11167 args = &allocated;
11170 vec_safe_insert (*args, 0, sub_vtt);
11173 ret = build_new_method_call (instance, fns, args,
11174 TYPE_BINFO (BINFO_TYPE (binfo)),
11175 flags, /*fn=*/NULL,
11176 complain);
11178 if (allocated != NULL)
11179 release_tree_vector (allocated);
11181 if ((complain & tf_error)
11182 && (flags & LOOKUP_DELEGATING_CONS)
11183 && name == complete_ctor_identifier)
11184 check_self_delegation (ret);
11186 return ret;
11189 /* Return the NAME, as a C string. The NAME indicates a function that
11190 is a member of TYPE. *FREE_P is set to true if the caller must
11191 free the memory returned.
11193 Rather than go through all of this, we should simply set the names
11194 of constructors and destructors appropriately, and dispense with
11195 ctor_identifier, dtor_identifier, etc. */
11197 static char *
11198 name_as_c_string (tree name, tree type, bool *free_p)
11200 const char *pretty_name;
11202 /* Assume that we will not allocate memory. */
11203 *free_p = false;
11204 /* Constructors and destructors are special. */
11205 if (IDENTIFIER_CDTOR_P (name))
11207 pretty_name
11208 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11209 /* For a destructor, add the '~'. */
11210 if (IDENTIFIER_DTOR_P (name))
11212 pretty_name = concat ("~", pretty_name, NULL);
11213 /* Remember that we need to free the memory allocated. */
11214 *free_p = true;
11217 else if (IDENTIFIER_CONV_OP_P (name))
11219 pretty_name = concat ("operator ",
11220 type_as_string_translate (TREE_TYPE (name),
11221 TFF_PLAIN_IDENTIFIER),
11222 NULL);
11223 /* Remember that we need to free the memory allocated. */
11224 *free_p = true;
11226 else
11227 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11229 return CONST_CAST (char *, pretty_name);
11232 /* If CANDIDATES contains exactly one candidate, return it, otherwise
11233 return NULL. */
11235 static z_candidate *
11236 single_z_candidate (z_candidate *candidates)
11238 if (candidates == NULL)
11239 return NULL;
11241 if (candidates->next)
11242 return NULL;
11244 return candidates;
11247 /* If CANDIDATE is invalid due to a bad argument type, return the
11248 pertinent conversion_info.
11250 Otherwise, return NULL. */
11252 static const conversion_info *
11253 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11255 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11256 rejection_reason *r = candidate->reason;
11258 if (r == NULL)
11259 return NULL;
11261 switch (r->code)
11263 default:
11264 return NULL;
11266 case rr_arg_conversion:
11267 return &r->u.conversion;
11269 case rr_bad_arg_conversion:
11270 return &r->u.bad_conversion;
11274 /* Issue an error and note complaining about a bad argument type at a
11275 callsite with a single candidate FNDECL.
11277 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11278 case input_location is used).
11279 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11280 the formal parameter. */
11282 void
11283 complain_about_bad_argument (location_t arg_loc,
11284 tree from_type, tree to_type,
11285 tree fndecl, int parmnum)
11287 auto_diagnostic_group d;
11288 range_label_for_type_mismatch rhs_label (from_type, to_type);
11289 range_label *label = &rhs_label;
11290 if (arg_loc == UNKNOWN_LOCATION)
11292 arg_loc = input_location;
11293 label = NULL;
11295 gcc_rich_location richloc (arg_loc, label);
11296 error_at (&richloc,
11297 "cannot convert %qH to %qI",
11298 from_type, to_type);
11299 maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
11300 parmnum);
11303 /* Subroutine of build_new_method_call_1, for where there are no viable
11304 candidates for the call. */
11306 static void
11307 complain_about_no_candidates_for_method_call (tree instance,
11308 z_candidate *candidates,
11309 tree explicit_targs,
11310 tree basetype,
11311 tree optype, tree name,
11312 bool skip_first_for_error,
11313 vec<tree, va_gc> *user_args)
11315 auto_diagnostic_group d;
11316 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11317 cxx_incomplete_type_error (instance, basetype);
11318 else if (optype)
11319 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11320 basetype, optype, build_tree_list_vec (user_args),
11321 TREE_TYPE (instance));
11322 else
11324 /* Special-case for when there's a single candidate that's failing
11325 due to a bad argument type. */
11326 if (z_candidate *candidate = single_z_candidate (candidates))
11327 if (const conversion_info *conv
11328 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11330 tree from_type = conv->from;
11331 if (!TYPE_P (conv->from))
11332 from_type = lvalue_type (conv->from);
11333 complain_about_bad_argument (conv->loc,
11334 from_type, conv->to_type,
11335 candidate->fn, conv->n_arg);
11336 return;
11339 tree arglist = build_tree_list_vec (user_args);
11340 tree errname = name;
11341 bool twiddle = false;
11342 if (IDENTIFIER_CDTOR_P (errname))
11344 twiddle = IDENTIFIER_DTOR_P (errname);
11345 errname = constructor_name (basetype);
11347 if (explicit_targs)
11348 errname = lookup_template_function (errname, explicit_targs);
11349 if (skip_first_for_error)
11350 arglist = TREE_CHAIN (arglist);
11351 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11352 basetype, &"~"[!twiddle], errname, arglist,
11353 TREE_TYPE (instance));
11355 print_z_candidates (location_of (name), candidates);
11358 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11359 be set, upon return, to the function called. ARGS may be NULL.
11360 This may change ARGS. */
11362 tree
11363 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11364 tree conversion_path, int flags,
11365 tree *fn_p, tsubst_flags_t complain)
11367 struct z_candidate *candidates = 0, *cand;
11368 tree explicit_targs = NULL_TREE;
11369 tree basetype = NULL_TREE;
11370 tree access_binfo;
11371 tree optype;
11372 tree first_mem_arg = NULL_TREE;
11373 tree name;
11374 bool skip_first_for_error;
11375 vec<tree, va_gc> *user_args;
11376 tree call;
11377 tree fn;
11378 int template_only = 0;
11379 bool any_viable_p;
11380 tree orig_instance;
11381 tree orig_fns;
11382 vec<tree, va_gc> *orig_args = NULL;
11383 void *p;
11385 auto_cond_timevar tv (TV_OVERLOAD);
11387 gcc_assert (instance != NULL_TREE);
11389 /* We don't know what function we're going to call, yet. */
11390 if (fn_p)
11391 *fn_p = NULL_TREE;
11393 if (error_operand_p (instance)
11394 || !fns || error_operand_p (fns))
11395 return error_mark_node;
11397 if (!BASELINK_P (fns))
11399 if (complain & tf_error)
11400 error ("call to non-function %qD", fns);
11401 return error_mark_node;
11404 orig_instance = instance;
11405 orig_fns = fns;
11407 /* Dismantle the baselink to collect all the information we need. */
11408 if (!conversion_path)
11409 conversion_path = BASELINK_BINFO (fns);
11410 access_binfo = BASELINK_ACCESS_BINFO (fns);
11411 optype = BASELINK_OPTYPE (fns);
11412 fns = BASELINK_FUNCTIONS (fns);
11413 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11415 explicit_targs = TREE_OPERAND (fns, 1);
11416 fns = TREE_OPERAND (fns, 0);
11417 template_only = 1;
11419 gcc_assert (OVL_P (fns));
11420 fn = OVL_FIRST (fns);
11421 name = DECL_NAME (fn);
11423 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11424 gcc_assert (CLASS_TYPE_P (basetype));
11426 user_args = args == NULL ? NULL : *args;
11427 /* Under DR 147 A::A() is an invalid constructor call,
11428 not a functional cast. */
11429 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11431 if (! (complain & tf_error))
11432 return error_mark_node;
11434 basetype = DECL_CONTEXT (fn);
11435 name = constructor_name (basetype);
11436 auto_diagnostic_group d;
11437 if (permerror (input_location,
11438 "cannot call constructor %<%T::%D%> directly",
11439 basetype, name))
11440 inform (input_location, "for a function-style cast, remove the "
11441 "redundant %<::%D%>", name);
11442 call = build_functional_cast (input_location, basetype,
11443 build_tree_list_vec (user_args),
11444 complain);
11445 return call;
11448 if (processing_template_decl)
11450 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11451 instance = build_non_dependent_expr (instance);
11452 if (args != NULL)
11453 make_args_non_dependent (*args);
11456 /* Process the argument list. */
11457 if (args != NULL && *args != NULL)
11459 *args = resolve_args (*args, complain);
11460 if (*args == NULL)
11461 return error_mark_node;
11462 user_args = *args;
11465 /* Consider the object argument to be used even if we end up selecting a
11466 static member function. */
11467 instance = mark_type_use (instance);
11469 /* Figure out whether to skip the first argument for the error
11470 message we will display to users if an error occurs. We don't
11471 want to display any compiler-generated arguments. The "this"
11472 pointer hasn't been added yet. However, we must remove the VTT
11473 pointer if this is a call to a base-class constructor or
11474 destructor. */
11475 skip_first_for_error = false;
11476 if (IDENTIFIER_CDTOR_P (name))
11478 /* Callers should explicitly indicate whether they want to ctor
11479 the complete object or just the part without virtual bases. */
11480 gcc_assert (name != ctor_identifier);
11482 /* Remove the VTT pointer, if present. */
11483 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11484 && CLASSTYPE_VBASECLASSES (basetype))
11485 skip_first_for_error = true;
11487 /* It's OK to call destructors and constructors on cv-qualified
11488 objects. Therefore, convert the INSTANCE to the unqualified
11489 type, if necessary. */
11490 if (!same_type_p (basetype, TREE_TYPE (instance)))
11492 instance = build_this (instance);
11493 instance = build_nop (build_pointer_type (basetype), instance);
11494 instance = build_fold_indirect_ref (instance);
11497 else
11498 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11500 /* For the overload resolution we need to find the actual `this`
11501 that would be captured if the call turns out to be to a
11502 non-static member function. Do not actually capture it at this
11503 point. */
11504 if (DECL_CONSTRUCTOR_P (fn))
11505 /* Constructors don't use the enclosing 'this'. */
11506 first_mem_arg = instance;
11507 else
11508 first_mem_arg = maybe_resolve_dummy (instance, false);
11510 /* Get the high-water mark for the CONVERSION_OBSTACK. */
11511 p = conversion_obstack_alloc (0);
11513 /* The number of arguments artificial parms in ARGS; we subtract one because
11514 there's no 'this' in ARGS. */
11515 unsigned skip = num_artificial_parms_for (fn) - 1;
11517 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11518 initializer, not T({ }). */
11519 if (DECL_CONSTRUCTOR_P (fn)
11520 && vec_safe_length (user_args) > skip
11521 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11523 tree init_list = (*user_args)[skip];
11524 tree init = NULL_TREE;
11526 gcc_assert (user_args->length () == skip + 1
11527 && !(flags & LOOKUP_ONLYCONVERTING));
11529 /* If the initializer list has no elements and T is a class type with
11530 a default constructor, the object is value-initialized. Handle
11531 this here so we don't need to handle it wherever we use
11532 build_special_member_call. */
11533 if (CONSTRUCTOR_NELTS (init_list) == 0
11534 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11535 /* For a user-provided default constructor, use the normal
11536 mechanisms so that protected access works. */
11537 && type_has_non_user_provided_default_constructor (basetype)
11538 && !processing_template_decl)
11539 init = build_value_init (basetype, complain);
11541 /* If BASETYPE is an aggregate, we need to do aggregate
11542 initialization. */
11543 else if (CP_AGGREGATE_TYPE_P (basetype))
11545 init = reshape_init (basetype, init_list, complain);
11546 init = digest_init (basetype, init, complain);
11549 if (init)
11551 if (is_dummy_object (instance))
11552 return get_target_expr (init, complain);
11553 return cp_build_init_expr (instance, init);
11556 /* Otherwise go ahead with overload resolution. */
11557 add_list_candidates (fns, first_mem_arg, user_args,
11558 basetype, explicit_targs, template_only,
11559 conversion_path, access_binfo, flags,
11560 &candidates, complain);
11562 else
11563 add_candidates (fns, first_mem_arg, user_args, optype,
11564 explicit_targs, template_only, conversion_path,
11565 access_binfo, flags, &candidates, complain);
11567 any_viable_p = false;
11568 candidates = splice_viable (candidates, false, &any_viable_p);
11570 if (!any_viable_p)
11572 /* [dcl.init], 17.6.2.2:
11574 Otherwise, if no constructor is viable, the destination type is
11575 a (possibly cv-qualified) aggregate class A, and the initializer
11576 is a parenthesized expression-list, the object is initialized as
11577 follows...
11579 We achieve this by building up a CONSTRUCTOR, as for list-init,
11580 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11581 the two. */
11582 if (DECL_CONSTRUCTOR_P (fn)
11583 && !(flags & LOOKUP_ONLYCONVERTING)
11584 && cxx_dialect >= cxx20
11585 && CP_AGGREGATE_TYPE_P (basetype)
11586 && !vec_safe_is_empty (user_args))
11588 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11589 tree ctor = build_constructor_from_vec (init_list_type_node,
11590 user_args);
11591 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11592 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11593 if (is_dummy_object (instance))
11594 return ctor;
11595 else
11597 ctor = digest_init (basetype, ctor, complain);
11598 if (ctor == error_mark_node)
11599 return error_mark_node;
11600 return cp_build_init_expr (instance, ctor);
11603 if (complain & tf_error)
11604 complain_about_no_candidates_for_method_call (instance, candidates,
11605 explicit_targs, basetype,
11606 optype, name,
11607 skip_first_for_error,
11608 user_args);
11609 call = error_mark_node;
11611 else
11613 cand = tourney (candidates, complain);
11614 if (cand == 0)
11616 char *pretty_name;
11617 bool free_p;
11618 tree arglist;
11620 if (complain & tf_error)
11622 pretty_name = name_as_c_string (name, basetype, &free_p);
11623 arglist = build_tree_list_vec (user_args);
11624 if (skip_first_for_error)
11625 arglist = TREE_CHAIN (arglist);
11626 auto_diagnostic_group d;
11627 if (!any_strictly_viable (candidates))
11628 error ("no matching function for call to %<%s(%A)%>",
11629 pretty_name, arglist);
11630 else
11631 error ("call of overloaded %<%s(%A)%> is ambiguous",
11632 pretty_name, arglist);
11633 print_z_candidates (location_of (name), candidates);
11634 if (free_p)
11635 free (pretty_name);
11637 call = error_mark_node;
11638 if (fn_p)
11639 *fn_p = error_mark_node;
11641 else
11643 fn = cand->fn;
11644 call = NULL_TREE;
11646 if (!(flags & LOOKUP_NONVIRTUAL)
11647 && DECL_PURE_VIRTUAL_P (fn)
11648 && instance == current_class_ref
11649 && (complain & tf_warning))
11651 /* This is not an error, it is runtime undefined
11652 behavior. */
11653 if (!current_function_decl)
11654 warning (0, "pure virtual %q#D called from "
11655 "non-static data member initializer", fn);
11656 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11657 || DECL_DESTRUCTOR_P (current_function_decl))
11658 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11659 ? G_("pure virtual %q#D called from constructor")
11660 : G_("pure virtual %q#D called from destructor")),
11661 fn);
11664 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11665 && !DECL_CONSTRUCTOR_P (fn)
11666 && is_dummy_object (instance))
11668 instance = maybe_resolve_dummy (instance, true);
11669 if (instance == error_mark_node)
11670 call = error_mark_node;
11671 else if (!is_dummy_object (instance))
11673 /* We captured 'this' in the current lambda now that
11674 we know we really need it. */
11675 cand->first_arg = instance;
11677 else if (current_class_ptr && any_dependent_bases_p ())
11678 /* We can't tell until instantiation time whether we can use
11679 *this as the implicit object argument. */;
11680 else
11682 if (complain & tf_error)
11683 error ("cannot call member function %qD without object",
11684 fn);
11685 call = error_mark_node;
11689 if (call != error_mark_node)
11691 /* Now we know what function is being called. */
11692 if (fn_p)
11693 *fn_p = fn;
11694 /* Build the actual CALL_EXPR. */
11695 call = build_over_call (cand, flags, complain);
11697 /* Suppress warnings for if (my_struct.operator= (x)) where
11698 my_struct is implicitly converted to bool. */
11699 if (TREE_CODE (call) == MODIFY_EXPR)
11700 suppress_warning (call, OPT_Wparentheses);
11702 /* In an expression of the form `a->f()' where `f' turns
11703 out to be a static member function, `a' is
11704 none-the-less evaluated. */
11705 if (!is_dummy_object (instance))
11706 call = keep_unused_object_arg (call, instance, fn);
11707 if (call != error_mark_node
11708 && DECL_DESTRUCTOR_P (cand->fn)
11709 && !VOID_TYPE_P (TREE_TYPE (call)))
11710 /* An explicit call of the form "x->~X()" has type
11711 "void". However, on platforms where destructors
11712 return "this" (i.e., those where
11713 targetm.cxx.cdtor_returns_this is true), such calls
11714 will appear to have a return value of pointer type
11715 to the low-level call machinery. We do not want to
11716 change the low-level machinery, since we want to be
11717 able to optimize "delete f()" on such platforms as
11718 "operator delete(~X(f()))" (rather than generating
11719 "t = f(), ~X(t), operator delete (t)"). */
11720 call = build_nop (void_type_node, call);
11725 if (processing_template_decl && call != error_mark_node)
11727 bool cast_to_void = false;
11729 if (TREE_CODE (call) == COMPOUND_EXPR)
11730 call = TREE_OPERAND (call, 1);
11731 else if (TREE_CODE (call) == NOP_EXPR)
11733 cast_to_void = true;
11734 call = TREE_OPERAND (call, 0);
11736 if (INDIRECT_REF_P (call))
11737 call = TREE_OPERAND (call, 0);
11739 /* Prune all but the selected function from the original overload
11740 set so that we can avoid some duplicate work at instantiation time. */
11741 if (really_overloaded_fn (fns))
11743 if (DECL_TEMPLATE_INFO (fn)
11744 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11746 /* Use the selected template, not the specialization, so that
11747 this looks like an actual lookup result for sake of
11748 filter_memfn_lookup. */
11750 if (OVL_SINGLE_P (fns))
11751 /* If the original overload set consists of a single function
11752 template, this isn't beneficial. */
11753 goto skip_prune;
11755 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11756 if (template_only)
11757 fn = lookup_template_function (fn, explicit_targs);
11759 orig_fns = copy_node (orig_fns);
11760 BASELINK_FUNCTIONS (orig_fns) = fn;
11761 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11764 skip_prune:
11765 call = (build_min_non_dep_call_vec
11766 (call,
11767 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11768 orig_instance, orig_fns, NULL_TREE),
11769 orig_args));
11770 SET_EXPR_LOCATION (call, input_location);
11771 call = convert_from_reference (call);
11772 if (cast_to_void)
11773 call = build_nop (void_type_node, call);
11776 /* Free all the conversions we allocated. */
11777 obstack_free (&conversion_obstack, p);
11779 if (orig_args != NULL)
11780 release_tree_vector (orig_args);
11782 return call;
11785 /* Returns true iff standard conversion sequence ICS1 is a proper
11786 subsequence of ICS2. */
11788 static bool
11789 is_subseq (conversion *ics1, conversion *ics2)
11791 /* We can assume that a conversion of the same code
11792 between the same types indicates a subsequence since we only get
11793 here if the types we are converting from are the same. */
11795 while (ics1->kind == ck_rvalue
11796 || ics1->kind == ck_lvalue)
11797 ics1 = next_conversion (ics1);
11799 while (1)
11801 while (ics2->kind == ck_rvalue
11802 || ics2->kind == ck_lvalue)
11803 ics2 = next_conversion (ics2);
11805 if (ics2->kind == ck_user
11806 || !has_next (ics2->kind))
11807 /* At this point, ICS1 cannot be a proper subsequence of
11808 ICS2. We can get a USER_CONV when we are comparing the
11809 second standard conversion sequence of two user conversion
11810 sequences. */
11811 return false;
11813 ics2 = next_conversion (ics2);
11815 while (ics2->kind == ck_rvalue
11816 || ics2->kind == ck_lvalue)
11817 ics2 = next_conversion (ics2);
11819 if (ics2->kind == ics1->kind
11820 && same_type_p (ics2->type, ics1->type)
11821 && (ics1->kind == ck_identity
11822 || same_type_p (next_conversion (ics2)->type,
11823 next_conversion (ics1)->type)))
11824 return true;
11828 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11829 be any _TYPE nodes. */
11831 bool
11832 is_properly_derived_from (tree derived, tree base)
11834 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11835 return false;
11837 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11838 considers every class derived from itself. */
11839 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11840 && DERIVED_FROM_P (base, derived));
11843 /* We build the ICS for an implicit object parameter as a pointer
11844 conversion sequence. However, such a sequence should be compared
11845 as if it were a reference conversion sequence. If ICS is the
11846 implicit conversion sequence for an implicit object parameter,
11847 modify it accordingly. */
11849 static void
11850 maybe_handle_implicit_object (conversion **ics)
11852 if ((*ics)->this_p)
11854 /* [over.match.funcs]
11856 For non-static member functions, the type of the
11857 implicit object parameter is "reference to cv X"
11858 where X is the class of which the function is a
11859 member and cv is the cv-qualification on the member
11860 function declaration. */
11861 conversion *t = *ics;
11862 tree reference_type;
11864 /* The `this' parameter is a pointer to a class type. Make the
11865 implicit conversion talk about a reference to that same class
11866 type. */
11867 reference_type = TREE_TYPE (t->type);
11868 reference_type = build_reference_type (reference_type);
11870 if (t->kind == ck_qual)
11871 t = next_conversion (t);
11872 if (t->kind == ck_ptr)
11873 t = next_conversion (t);
11874 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11875 t = direct_reference_binding (reference_type, t);
11876 t->this_p = 1;
11877 t->rvaluedness_matches_p = 0;
11878 *ics = t;
11882 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11883 and return the initial reference binding conversion. Otherwise,
11884 leave *ICS unchanged and return NULL. */
11886 static conversion *
11887 maybe_handle_ref_bind (conversion **ics)
11889 if ((*ics)->kind == ck_ref_bind)
11891 conversion *old_ics = *ics;
11892 *ics = next_conversion (old_ics);
11893 (*ics)->user_conv_p = old_ics->user_conv_p;
11894 return old_ics;
11897 return NULL;
11900 /* Get the expression at the beginning of the conversion chain C. */
11902 static tree
11903 conv_get_original_expr (conversion *c)
11905 for (; c; c = next_conversion (c))
11906 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11907 return c->u.expr;
11908 return NULL_TREE;
11911 /* Return a tree representing the number of elements initialized by the
11912 list-initialization C. The caller must check that C converts to an
11913 array type. */
11915 static tree
11916 nelts_initialized_by_list_init (conversion *c)
11918 /* If the array we're converting to has a dimension, we'll use that. */
11919 if (TYPE_DOMAIN (c->type))
11920 return array_type_nelts_top (c->type);
11921 else
11923 /* Otherwise, we look at how many elements the constructor we're
11924 initializing from has. */
11925 tree ctor = conv_get_original_expr (c);
11926 return size_int (CONSTRUCTOR_NELTS (ctor));
11930 /* True iff C is a conversion that binds a reference or a pointer to
11931 an array of unknown bound. */
11933 static inline bool
11934 conv_binds_to_array_of_unknown_bound (conversion *c)
11936 /* ck_ref_bind won't have the reference stripped. */
11937 tree type = non_reference (c->type);
11938 /* ck_qual won't have the pointer stripped. */
11939 type = strip_pointer_operator (type);
11940 return (TREE_CODE (type) == ARRAY_TYPE
11941 && TYPE_DOMAIN (type) == NULL_TREE);
11944 /* Compare two implicit conversion sequences according to the rules set out in
11945 [over.ics.rank]. Return values:
11947 1: ics1 is better than ics2
11948 -1: ics2 is better than ics1
11949 0: ics1 and ics2 are indistinguishable */
11951 static int
11952 compare_ics (conversion *ics1, conversion *ics2)
11954 tree from_type1;
11955 tree from_type2;
11956 tree to_type1;
11957 tree to_type2;
11958 tree deref_from_type1 = NULL_TREE;
11959 tree deref_from_type2 = NULL_TREE;
11960 tree deref_to_type1 = NULL_TREE;
11961 tree deref_to_type2 = NULL_TREE;
11962 conversion_rank rank1, rank2;
11964 /* REF_BINDING is nonzero if the result of the conversion sequence
11965 is a reference type. In that case REF_CONV is the reference
11966 binding conversion. */
11967 conversion *ref_conv1;
11968 conversion *ref_conv2;
11970 /* Compare badness before stripping the reference conversion. */
11971 if (ics1->bad_p > ics2->bad_p)
11972 return -1;
11973 else if (ics1->bad_p < ics2->bad_p)
11974 return 1;
11976 /* Handle implicit object parameters. */
11977 maybe_handle_implicit_object (&ics1);
11978 maybe_handle_implicit_object (&ics2);
11980 /* Handle reference parameters. */
11981 ref_conv1 = maybe_handle_ref_bind (&ics1);
11982 ref_conv2 = maybe_handle_ref_bind (&ics2);
11984 /* List-initialization sequence L1 is a better conversion sequence than
11985 list-initialization sequence L2 if L1 converts to
11986 std::initializer_list<X> for some X and L2 does not. */
11987 if (ics1->kind == ck_list && ics2->kind != ck_list)
11988 return 1;
11989 if (ics2->kind == ck_list && ics1->kind != ck_list)
11990 return -1;
11992 /* [over.ics.rank]
11994 When comparing the basic forms of implicit conversion sequences (as
11995 defined in _over.best.ics_)
11997 --a standard conversion sequence (_over.ics.scs_) is a better
11998 conversion sequence than a user-defined conversion sequence
11999 or an ellipsis conversion sequence, and
12001 --a user-defined conversion sequence (_over.ics.user_) is a
12002 better conversion sequence than an ellipsis conversion sequence
12003 (_over.ics.ellipsis_). */
12004 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12005 mismatch. If both ICS are bad, we try to make a decision based on
12006 what would have happened if they'd been good. This is not an
12007 extension, we'll still give an error when we build up the call; this
12008 just helps us give a more helpful error message. */
12009 rank1 = BAD_CONVERSION_RANK (ics1);
12010 rank2 = BAD_CONVERSION_RANK (ics2);
12012 if (rank1 > rank2)
12013 return -1;
12014 else if (rank1 < rank2)
12015 return 1;
12017 if (ics1->ellipsis_p)
12018 /* Both conversions are ellipsis conversions. */
12019 return 0;
12021 /* User-defined conversion sequence U1 is a better conversion sequence
12022 than another user-defined conversion sequence U2 if they contain the
12023 same user-defined conversion operator or constructor and if the sec-
12024 ond standard conversion sequence of U1 is better than the second
12025 standard conversion sequence of U2. */
12027 /* Handle list-conversion with the same code even though it isn't always
12028 ranked as a user-defined conversion and it doesn't have a second
12029 standard conversion sequence; it will still have the desired effect.
12030 Specifically, we need to do the reference binding comparison at the
12031 end of this function. */
12033 if (ics1->user_conv_p || ics1->kind == ck_list
12034 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12036 conversion *t1 = strip_standard_conversion (ics1);
12037 conversion *t2 = strip_standard_conversion (ics2);
12039 if (!t1 || !t2 || t1->kind != t2->kind)
12040 return 0;
12041 else if (t1->kind == ck_user)
12043 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12044 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12045 if (f1 != f2)
12046 return 0;
12048 /* List-initialization sequence L1 is a better conversion sequence than
12049 list-initialization sequence L2 if
12051 -- L1 and L2 convert to arrays of the same element type, and either
12052 the number of elements n1 initialized by L1 is less than the number
12053 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12054 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12055 P0388R4.) */
12056 else if (t1->kind == ck_aggr
12057 && TREE_CODE (t1->type) == ARRAY_TYPE
12058 && TREE_CODE (t2->type) == ARRAY_TYPE
12059 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12061 tree n1 = nelts_initialized_by_list_init (t1);
12062 tree n2 = nelts_initialized_by_list_init (t2);
12063 if (tree_int_cst_lt (n1, n2))
12064 return 1;
12065 else if (tree_int_cst_lt (n2, n1))
12066 return -1;
12067 /* The n1 == n2 case. */
12068 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
12069 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
12070 if (c1 && !c2)
12071 return -1;
12072 else if (!c1 && c2)
12073 return 1;
12074 else
12075 return 0;
12077 else
12079 /* For ambiguous or aggregate conversions, use the target type as
12080 a proxy for the conversion function. */
12081 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12082 return 0;
12085 /* We can just fall through here, after setting up
12086 FROM_TYPE1 and FROM_TYPE2. */
12087 from_type1 = t1->type;
12088 from_type2 = t2->type;
12090 else
12092 conversion *t1;
12093 conversion *t2;
12095 /* We're dealing with two standard conversion sequences.
12097 [over.ics.rank]
12099 Standard conversion sequence S1 is a better conversion
12100 sequence than standard conversion sequence S2 if
12102 --S1 is a proper subsequence of S2 (comparing the conversion
12103 sequences in the canonical form defined by _over.ics.scs_,
12104 excluding any Lvalue Transformation; the identity
12105 conversion sequence is considered to be a subsequence of
12106 any non-identity conversion sequence */
12108 t1 = ics1;
12109 while (t1->kind != ck_identity)
12110 t1 = next_conversion (t1);
12111 from_type1 = t1->type;
12113 t2 = ics2;
12114 while (t2->kind != ck_identity)
12115 t2 = next_conversion (t2);
12116 from_type2 = t2->type;
12119 /* One sequence can only be a subsequence of the other if they start with
12120 the same type. They can start with different types when comparing the
12121 second standard conversion sequence in two user-defined conversion
12122 sequences. */
12123 if (same_type_p (from_type1, from_type2))
12125 if (is_subseq (ics1, ics2))
12126 return 1;
12127 if (is_subseq (ics2, ics1))
12128 return -1;
12131 /* [over.ics.rank]
12133 Or, if not that,
12135 --the rank of S1 is better than the rank of S2 (by the rules
12136 defined below):
12138 Standard conversion sequences are ordered by their ranks: an Exact
12139 Match is a better conversion than a Promotion, which is a better
12140 conversion than a Conversion.
12142 Two conversion sequences with the same rank are indistinguishable
12143 unless one of the following rules applies:
12145 --A conversion that does not a convert a pointer, pointer to member,
12146 or std::nullptr_t to bool is better than one that does.
12148 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12149 so that we do not have to check it explicitly. */
12150 if (ics1->rank < ics2->rank)
12151 return 1;
12152 else if (ics2->rank < ics1->rank)
12153 return -1;
12155 to_type1 = ics1->type;
12156 to_type2 = ics2->type;
12158 /* A conversion from scalar arithmetic type to complex is worse than a
12159 conversion between scalar arithmetic types. */
12160 if (same_type_p (from_type1, from_type2)
12161 && ARITHMETIC_TYPE_P (from_type1)
12162 && ARITHMETIC_TYPE_P (to_type1)
12163 && ARITHMETIC_TYPE_P (to_type2)
12164 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12165 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12167 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12168 return -1;
12169 else
12170 return 1;
12174 /* A conversion in either direction between floating-point type FP1 and
12175 floating-point type FP2 is better than a conversion in the same
12176 direction between FP1 and arithmetic type T3 if
12177 - the floating-point conversion rank of FP1 is equal to the rank of
12178 FP2, and
12179 - T3 is not a floating-point type, or T3 is a floating-point type
12180 whose rank is not equal to the rank of FP1, or the floating-point
12181 conversion subrank of FP2 is greater than the subrank of T3. */
12182 tree fp1 = from_type1;
12183 tree fp2 = to_type1;
12184 tree fp3 = from_type2;
12185 tree t3 = to_type2;
12186 int ret = 1;
12187 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12189 std::swap (fp1, fp2);
12190 std::swap (fp3, t3);
12192 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12193 && TREE_CODE (fp1) == REAL_TYPE
12194 /* Only apply this rule if at least one of the 3 types is
12195 extended floating-point type, otherwise keep them as
12196 before for compatibility reasons with types like __float128.
12197 float, double and long double alone have different conversion
12198 ranks and so when just those 3 types are involved, this
12199 rule doesn't trigger. */
12200 && (extended_float_type_p (fp1)
12201 || (TREE_CODE (fp2) == REAL_TYPE && extended_float_type_p (fp2))
12202 || (TREE_CODE (t3) == REAL_TYPE && extended_float_type_p (t3))))
12204 if (TREE_CODE (fp2) != REAL_TYPE)
12206 ret = -ret;
12207 std::swap (fp2, t3);
12209 if (TREE_CODE (fp2) == REAL_TYPE)
12211 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12212 if the conversion rank is equal (-1 or 1 if the subrank is
12213 different). */
12214 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12215 fp2),
12216 -1, 1))
12218 /* Conversion ranks of FP1 and FP2 are equal. */
12219 if (TREE_CODE (t3) != REAL_TYPE
12220 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12221 (fp1, t3),
12222 -1, 1))
12223 /* FP1 <-> FP2 conversion is better. */
12224 return ret;
12225 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12226 gcc_assert (IN_RANGE (c, -1, 1));
12227 if (c == 1)
12228 /* Conversion subrank of FP2 is greater than subrank of T3.
12229 FP1 <-> FP2 conversion is better. */
12230 return ret;
12231 else if (c == -1)
12232 /* Conversion subrank of FP2 is less than subrank of T3.
12233 FP1 <-> T3 conversion is better. */
12234 return -ret;
12236 else if (TREE_CODE (t3) == REAL_TYPE
12237 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12238 (fp1, t3),
12239 -1, 1))
12240 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12241 ranks of FP1 and T3 are equal.
12242 FP1 <-> T3 conversion is better. */
12243 return -ret;
12248 if (TYPE_PTR_P (from_type1)
12249 && TYPE_PTR_P (from_type2)
12250 && TYPE_PTR_P (to_type1)
12251 && TYPE_PTR_P (to_type2))
12253 deref_from_type1 = TREE_TYPE (from_type1);
12254 deref_from_type2 = TREE_TYPE (from_type2);
12255 deref_to_type1 = TREE_TYPE (to_type1);
12256 deref_to_type2 = TREE_TYPE (to_type2);
12258 /* The rules for pointers to members A::* are just like the rules
12259 for pointers A*, except opposite: if B is derived from A then
12260 A::* converts to B::*, not vice versa. For that reason, we
12261 switch the from_ and to_ variables here. */
12262 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12263 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12264 || (TYPE_PTRMEMFUNC_P (from_type1)
12265 && TYPE_PTRMEMFUNC_P (from_type2)
12266 && TYPE_PTRMEMFUNC_P (to_type1)
12267 && TYPE_PTRMEMFUNC_P (to_type2)))
12269 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12270 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12271 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12272 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12275 if (deref_from_type1 != NULL_TREE
12276 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12277 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12279 /* This was one of the pointer or pointer-like conversions.
12281 [over.ics.rank]
12283 --If class B is derived directly or indirectly from class A,
12284 conversion of B* to A* is better than conversion of B* to
12285 void*, and conversion of A* to void* is better than
12286 conversion of B* to void*. */
12287 if (VOID_TYPE_P (deref_to_type1)
12288 && VOID_TYPE_P (deref_to_type2))
12290 if (is_properly_derived_from (deref_from_type1,
12291 deref_from_type2))
12292 return -1;
12293 else if (is_properly_derived_from (deref_from_type2,
12294 deref_from_type1))
12295 return 1;
12297 else if (VOID_TYPE_P (deref_to_type1)
12298 || VOID_TYPE_P (deref_to_type2))
12300 if (same_type_p (deref_from_type1, deref_from_type2))
12302 if (VOID_TYPE_P (deref_to_type2))
12304 if (is_properly_derived_from (deref_from_type1,
12305 deref_to_type1))
12306 return 1;
12308 /* We know that DEREF_TO_TYPE1 is `void' here. */
12309 else if (is_properly_derived_from (deref_from_type1,
12310 deref_to_type2))
12311 return -1;
12314 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12315 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12317 /* [over.ics.rank]
12319 --If class B is derived directly or indirectly from class A
12320 and class C is derived directly or indirectly from B,
12322 --conversion of C* to B* is better than conversion of C* to
12325 --conversion of B* to A* is better than conversion of C* to
12326 A* */
12327 if (same_type_p (deref_from_type1, deref_from_type2))
12329 if (is_properly_derived_from (deref_to_type1,
12330 deref_to_type2))
12331 return 1;
12332 else if (is_properly_derived_from (deref_to_type2,
12333 deref_to_type1))
12334 return -1;
12336 else if (same_type_p (deref_to_type1, deref_to_type2))
12338 if (is_properly_derived_from (deref_from_type2,
12339 deref_from_type1))
12340 return 1;
12341 else if (is_properly_derived_from (deref_from_type1,
12342 deref_from_type2))
12343 return -1;
12347 else if (CLASS_TYPE_P (non_reference (from_type1))
12348 && same_type_p (from_type1, from_type2))
12350 tree from = non_reference (from_type1);
12352 /* [over.ics.rank]
12354 --binding of an expression of type C to a reference of type
12355 B& is better than binding an expression of type C to a
12356 reference of type A&
12358 --conversion of C to B is better than conversion of C to A, */
12359 if (is_properly_derived_from (from, to_type1)
12360 && is_properly_derived_from (from, to_type2))
12362 if (is_properly_derived_from (to_type1, to_type2))
12363 return 1;
12364 else if (is_properly_derived_from (to_type2, to_type1))
12365 return -1;
12368 else if (CLASS_TYPE_P (non_reference (to_type1))
12369 && same_type_p (to_type1, to_type2))
12371 tree to = non_reference (to_type1);
12373 /* [over.ics.rank]
12375 --binding of an expression of type B to a reference of type
12376 A& is better than binding an expression of type C to a
12377 reference of type A&,
12379 --conversion of B to A is better than conversion of C to A */
12380 if (is_properly_derived_from (from_type1, to)
12381 && is_properly_derived_from (from_type2, to))
12383 if (is_properly_derived_from (from_type2, from_type1))
12384 return 1;
12385 else if (is_properly_derived_from (from_type1, from_type2))
12386 return -1;
12390 /* [over.ics.rank]
12392 --S1 and S2 differ only in their qualification conversion and yield
12393 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12394 qualification signature of type T1 is a proper subset of the cv-
12395 qualification signature of type T2 */
12396 if (ics1->kind == ck_qual
12397 && ics2->kind == ck_qual
12398 && same_type_p (from_type1, from_type2))
12400 int result = comp_cv_qual_signature (to_type1, to_type2);
12401 if (result != 0)
12402 return result;
12405 /* [over.ics.rank]
12407 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12408 to an implicit object parameter of a non-static member function
12409 declared without a ref-qualifier, and either S1 binds an lvalue
12410 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12411 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12412 draft standard, 13.3.3.2)
12414 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12415 types to which the references refer are the same type except for
12416 top-level cv-qualifiers, and the type to which the reference
12417 initialized by S2 refers is more cv-qualified than the type to
12418 which the reference initialized by S1 refers.
12420 DR 1328 [over.match.best]: the context is an initialization by
12421 conversion function for direct reference binding (13.3.1.6) of a
12422 reference to function type, the return type of F1 is the same kind of
12423 reference (i.e. lvalue or rvalue) as the reference being initialized,
12424 and the return type of F2 is not. */
12426 if (ref_conv1 && ref_conv2)
12428 if (!ref_conv1->this_p && !ref_conv2->this_p
12429 && (ref_conv1->rvaluedness_matches_p
12430 != ref_conv2->rvaluedness_matches_p)
12431 && (same_type_p (ref_conv1->type, ref_conv2->type)
12432 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12433 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12435 if (ref_conv1->bad_p
12436 && !same_type_p (TREE_TYPE (ref_conv1->type),
12437 TREE_TYPE (ref_conv2->type)))
12438 /* Don't prefer a bad conversion that drops cv-quals to a bad
12439 conversion with the wrong rvalueness. */
12440 return 0;
12441 return (ref_conv1->rvaluedness_matches_p
12442 - ref_conv2->rvaluedness_matches_p);
12445 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12447 /* Per P0388R4:
12449 void f (int(&)[]), // (1)
12450 f (int(&)[1]), // (2)
12451 f (int*); // (3)
12453 (2) is better than (1), but (3) should be equal to (1) and to
12454 (2). For that reason we don't use ck_qual for (1) which would
12455 give it the cr_exact rank while (3) remains ck_identity.
12456 Therefore we compare (1) and (2) here. For (1) we'll have
12458 ck_ref_bind <- ck_identity
12459 int[] & int[1]
12461 so to handle this we must look at ref_conv. */
12462 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12463 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12464 if (c1 && !c2)
12465 return -1;
12466 else if (!c1 && c2)
12467 return 1;
12469 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12470 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12471 if (ref_conv1->bad_p)
12473 /* Prefer the one that drops fewer cv-quals. */
12474 tree ftype = next_conversion (ref_conv1)->type;
12475 int fquals = cp_type_quals (ftype);
12476 q1 ^= fquals;
12477 q2 ^= fquals;
12479 return comp_cv_qualification (q2, q1);
12483 /* [over.ics.rank]
12485 Per CWG 1601:
12486 -- A conversion that promotes an enumeration whose underlying type
12487 is fixed to its underlying type is better than one that promotes to
12488 the promoted underlying type, if the two are different. */
12489 if (ics1->rank == cr_promotion
12490 && ics2->rank == cr_promotion
12491 && UNSCOPED_ENUM_P (from_type1)
12492 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12493 && same_type_p (from_type1, from_type2))
12495 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12496 tree prom = type_promotes_to (from_type1);
12497 if (!same_type_p (utype, prom))
12499 if (same_type_p (to_type1, utype)
12500 && same_type_p (to_type2, prom))
12501 return 1;
12502 else if (same_type_p (to_type2, utype)
12503 && same_type_p (to_type1, prom))
12504 return -1;
12508 /* Neither conversion sequence is better than the other. */
12509 return 0;
12512 /* The source type for this standard conversion sequence. */
12514 static tree
12515 source_type (conversion *t)
12517 return strip_standard_conversion (t)->type;
12520 /* Note a warning about preferring WINNER to LOSER. We do this by storing
12521 a pointer to LOSER and re-running joust to produce the warning if WINNER
12522 is actually used. */
12524 static void
12525 add_warning (struct z_candidate *winner, struct z_candidate *loser)
12527 candidate_warning *cw = (candidate_warning *)
12528 conversion_obstack_alloc (sizeof (candidate_warning));
12529 cw->loser = loser;
12530 cw->next = winner->warnings;
12531 winner->warnings = cw;
12534 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12535 prvalue returned from a conversion function, replace CAND with the candidate
12536 for the conversion and return true. Otherwise, return false. */
12538 static bool
12539 joust_maybe_elide_copy (z_candidate *&cand)
12541 tree fn = cand->fn;
12542 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12543 return false;
12544 conversion *conv = cand->convs[0];
12545 if (conv->kind == ck_ambig)
12546 return false;
12547 gcc_checking_assert (conv->kind == ck_ref_bind);
12548 conv = next_conversion (conv);
12549 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12551 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12552 (conv->type, DECL_CONTEXT (fn)));
12553 z_candidate *uc = conv->cand;
12554 if (DECL_CONV_FN_P (uc->fn))
12556 cand = uc;
12557 return true;
12560 return false;
12563 /* True if the defining declarations of the two candidates have equivalent
12564 parameters. */
12566 static bool
12567 cand_parms_match (z_candidate *c1, z_candidate *c2)
12569 tree fn1 = c1->fn;
12570 tree fn2 = c2->fn;
12571 if (fn1 == fn2)
12572 return true;
12573 if (identifier_p (fn1) || identifier_p (fn2))
12574 return false;
12575 /* We don't look at c1->template_decl because that's only set for primary
12576 templates, not e.g. non-template member functions of class templates. */
12577 tree t1 = most_general_template (fn1);
12578 tree t2 = most_general_template (fn2);
12579 if (t1 || t2)
12581 if (!t1 || !t2)
12582 return false;
12583 if (t1 == t2)
12584 return true;
12585 fn1 = DECL_TEMPLATE_RESULT (t1);
12586 fn2 = DECL_TEMPLATE_RESULT (t2);
12588 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12589 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12590 if (DECL_FUNCTION_MEMBER_P (fn1)
12591 && DECL_FUNCTION_MEMBER_P (fn2)
12592 && (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn1)
12593 != DECL_NONSTATIC_MEMBER_FUNCTION_P (fn2)))
12595 /* Ignore 'this' when comparing the parameters of a static member
12596 function with those of a non-static one. */
12597 parms1 = skip_artificial_parms_for (fn1, parms1);
12598 parms2 = skip_artificial_parms_for (fn2, parms2);
12600 return compparms (parms1, parms2);
12603 /* Compare two candidates for overloading as described in
12604 [over.match.best]. Return values:
12606 1: cand1 is better than cand2
12607 -1: cand2 is better than cand1
12608 0: cand1 and cand2 are indistinguishable */
12610 static int
12611 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12612 tsubst_flags_t complain)
12614 int winner = 0;
12615 int off1 = 0, off2 = 0;
12616 size_t i;
12617 size_t len;
12619 /* Candidates that involve bad conversions are always worse than those
12620 that don't. */
12621 if (cand1->viable > cand2->viable)
12622 return 1;
12623 if (cand1->viable < cand2->viable)
12624 return -1;
12626 /* If we have two pseudo-candidates for conversions to the same type,
12627 or two candidates for the same function, arbitrarily pick one. */
12628 if (cand1->fn == cand2->fn
12629 && cand1->reversed () == cand2->reversed ()
12630 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12631 return 1;
12633 /* Prefer a non-deleted function over an implicitly deleted move
12634 constructor or assignment operator. This differs slightly from the
12635 wording for issue 1402 (which says the move op is ignored by overload
12636 resolution), but this way produces better error messages. */
12637 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12638 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12639 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12641 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12642 && move_fn_p (cand1->fn))
12643 return -1;
12644 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12645 && move_fn_p (cand2->fn))
12646 return 1;
12649 /* a viable function F1
12650 is defined to be a better function than another viable function F2 if
12651 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12652 ICSi(F2), and then */
12654 /* for some argument j, ICSj(F1) is a better conversion sequence than
12655 ICSj(F2) */
12657 /* For comparing static and non-static member functions, we ignore
12658 the implicit object parameter of the non-static function. The
12659 standard says to pretend that the static function has an object
12660 parm, but that won't work with operator overloading. */
12661 len = cand1->num_convs;
12662 if (len != cand2->num_convs)
12664 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12665 && DECL_STATIC_FUNCTION_P (cand1->fn));
12666 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12667 && DECL_STATIC_FUNCTION_P (cand2->fn));
12669 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12670 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12671 && DECL_CONSTRUCTOR_P (cand1->fn)
12672 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12673 /* We're comparing a near-match list constructor and a near-match
12674 non-list constructor. Just treat them as unordered. */
12675 return 0;
12677 gcc_assert (static_1 != static_2);
12679 if (static_1)
12681 /* C++23 [over.best.ics.general] says:
12682 When the parameter is the implicit object parameter of a static
12683 member function, the implicit conversion sequence is a standard
12684 conversion sequence that is neither better nor worse than any
12685 other standard conversion sequence. */
12686 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12687 winner = 1;
12688 off2 = 1;
12690 else
12692 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12693 winner = -1;
12694 off1 = 1;
12695 --len;
12699 /* Handle C++17 copy elision in [over.match.ctor] (direct-init) context. The
12700 standard currently says that only constructors are candidates, but if one
12701 copies a prvalue returned by a conversion function we want to treat the
12702 conversion as the candidate instead.
12704 Clang does something similar, as discussed at
12705 http://lists.isocpp.org/core/2017/10/3166.php
12706 http://lists.isocpp.org/core/2019/03/5721.php */
12707 int elided_tiebreaker = 0;
12708 if (len == 1 && cxx_dialect >= cxx17
12709 && DECL_P (cand1->fn)
12710 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
12711 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
12713 bool elided1 = joust_maybe_elide_copy (cand1);
12714 bool elided2 = joust_maybe_elide_copy (cand2);
12715 /* As a tiebreaker below we will prefer a constructor to a conversion
12716 operator exposed this way. */
12717 elided_tiebreaker = elided2 - elided1;
12720 for (i = 0; i < len; ++i)
12722 conversion *t1 = cand1->convs[i + off1];
12723 conversion *t2 = cand2->convs[i + off2];
12724 int comp = compare_ics (t1, t2);
12726 if (comp != 0)
12728 if ((complain & tf_warning)
12729 && warn_sign_promo
12730 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12731 == cr_std + cr_promotion)
12732 && t1->kind == ck_std
12733 && t2->kind == ck_std
12734 && TREE_CODE (t1->type) == INTEGER_TYPE
12735 && TREE_CODE (t2->type) == INTEGER_TYPE
12736 && (TYPE_PRECISION (t1->type)
12737 == TYPE_PRECISION (t2->type))
12738 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12739 || (TREE_CODE (next_conversion (t1)->type)
12740 == ENUMERAL_TYPE)))
12742 tree type = next_conversion (t1)->type;
12743 tree type1, type2;
12744 struct z_candidate *w, *l;
12745 if (comp > 0)
12746 type1 = t1->type, type2 = t2->type,
12747 w = cand1, l = cand2;
12748 else
12749 type1 = t2->type, type2 = t1->type,
12750 w = cand2, l = cand1;
12752 if (warn)
12754 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12755 type, type1, type2);
12756 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12758 else
12759 add_warning (w, l);
12762 if (winner && comp != winner)
12764 /* Ambiguity between normal and reversed comparison operators
12765 with the same parameter types. P2468 decided not to go with
12766 this approach to resolving the ambiguity, so pedwarn. */
12767 if ((complain & tf_warning_or_error)
12768 && (cand1->reversed () != cand2->reversed ())
12769 && cand_parms_match (cand1, cand2))
12771 struct z_candidate *w, *l;
12772 if (cand2->reversed ())
12773 winner = 1, w = cand1, l = cand2;
12774 else
12775 winner = -1, w = cand2, l = cand1;
12776 if (warn)
12778 auto_diagnostic_group d;
12779 if (pedwarn (input_location, 0,
12780 "C++20 says that these are ambiguous, "
12781 "even though the second is reversed:"))
12783 print_z_candidate (input_location,
12784 N_("candidate 1:"), w);
12785 print_z_candidate (input_location,
12786 N_("candidate 2:"), l);
12787 if (w->fn == l->fn
12788 && DECL_NONSTATIC_MEMBER_FUNCTION_P (w->fn)
12789 && (type_memfn_quals (TREE_TYPE (w->fn))
12790 & TYPE_QUAL_CONST) == 0)
12792 /* Suggest adding const to
12793 struct A { bool operator==(const A&); }; */
12794 tree parmtype
12795 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
12796 parmtype = TREE_VALUE (parmtype);
12797 if (TYPE_REF_P (parmtype)
12798 && TYPE_READONLY (TREE_TYPE (parmtype))
12799 && (same_type_ignoring_top_level_qualifiers_p
12800 (TREE_TYPE (parmtype),
12801 DECL_CONTEXT (w->fn))))
12802 inform (DECL_SOURCE_LOCATION (w->fn),
12803 "try making the operator a %<const%> "
12804 "member function");
12808 else
12809 add_warning (w, l);
12810 return winner;
12813 winner = 0;
12814 goto tweak;
12816 winner = comp;
12820 /* warn about confusing overload resolution for user-defined conversions,
12821 either between a constructor and a conversion op, or between two
12822 conversion ops. */
12823 if ((complain & tf_warning)
12824 /* In C++17, the constructor might have been elided, which means that
12825 an originally null ->second_conv could become non-null. */
12826 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12827 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12828 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
12830 struct z_candidate *w, *l;
12831 bool give_warning = false;
12833 if (winner == 1)
12834 w = cand1, l = cand2;
12835 else
12836 w = cand2, l = cand1;
12838 /* We don't want to complain about `X::operator T1 ()'
12839 beating `X::operator T2 () const', when T2 is a no less
12840 cv-qualified version of T1. */
12841 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12842 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12844 tree t = TREE_TYPE (TREE_TYPE (l->fn));
12845 tree f = TREE_TYPE (TREE_TYPE (w->fn));
12847 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12849 t = TREE_TYPE (t);
12850 f = TREE_TYPE (f);
12852 if (!comp_ptr_ttypes (t, f))
12853 give_warning = true;
12855 else
12856 give_warning = true;
12858 if (!give_warning)
12859 /*NOP*/;
12860 else if (warn)
12862 tree source = source_type (w->convs[0]);
12863 if (INDIRECT_TYPE_P (source))
12864 source = TREE_TYPE (source);
12865 auto_diagnostic_group d;
12866 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12867 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
12868 source, w->second_conv->type))
12870 inform (input_location, " because conversion sequence "
12871 "for the argument is better");
12874 else
12875 add_warning (w, l);
12878 if (winner)
12879 return winner;
12881 /* Put this tiebreaker first, so that we don't try to look at second_conv of
12882 a constructor candidate that doesn't have one. */
12883 if (elided_tiebreaker)
12884 return elided_tiebreaker;
12886 /* DR 495 moved this tiebreaker above the template ones. */
12887 /* or, if not that,
12888 the context is an initialization by user-defined conversion (see
12889 _dcl.init_ and _over.match.user_) and the standard conversion
12890 sequence from the return type of F1 to the destination type (i.e.,
12891 the type of the entity being initialized) is a better conversion
12892 sequence than the standard conversion sequence from the return type
12893 of F2 to the destination type. */
12895 if (cand1->second_conv)
12897 winner = compare_ics (cand1->second_conv, cand2->second_conv);
12898 if (winner)
12899 return winner;
12902 /* or, if not that,
12903 F1 is a non-template function and F2 is a template function
12904 specialization. */
12906 if (!cand1->template_decl && cand2->template_decl)
12907 return 1;
12908 else if (cand1->template_decl && !cand2->template_decl)
12909 return -1;
12911 /* or, if not that,
12912 F1 and F2 are template functions and the function template for F1 is
12913 more specialized than the template for F2 according to the partial
12914 ordering rules. */
12916 if (cand1->template_decl && cand2->template_decl)
12918 winner = more_specialized_fn
12919 (TI_TEMPLATE (cand1->template_decl),
12920 TI_TEMPLATE (cand2->template_decl),
12921 /* [temp.func.order]: The presence of unused ellipsis and default
12922 arguments has no effect on the partial ordering of function
12923 templates. add_function_candidate() will not have
12924 counted the "this" argument for constructors. */
12925 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
12926 if (winner)
12927 return winner;
12930 /* Concepts: F1 and F2 are non-template functions with the same
12931 parameter-type-lists, and F1 is more constrained than F2 according to the
12932 partial ordering of constraints described in 13.5.4. */
12934 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
12935 && !cand1->template_decl && !cand2->template_decl
12936 && cand_parms_match (cand1, cand2))
12938 winner = more_constrained (cand1->fn, cand2->fn);
12939 if (winner)
12940 return winner;
12943 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
12944 rewritten candidates, and F2 is a synthesized candidate with reversed
12945 order of parameters and F1 is not. */
12946 if (cand1->rewritten ())
12948 if (!cand2->rewritten ())
12949 return -1;
12950 if (!cand1->reversed () && cand2->reversed ())
12951 return 1;
12952 if (cand1->reversed () && !cand2->reversed ())
12953 return -1;
12955 else if (cand2->rewritten ())
12956 return 1;
12958 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
12959 if (deduction_guide_p (cand1->fn))
12961 gcc_assert (deduction_guide_p (cand2->fn));
12962 /* We distinguish between candidates from an explicit deduction guide and
12963 candidates built from a constructor based on DECL_ARTIFICIAL. */
12964 int art1 = DECL_ARTIFICIAL (cand1->fn);
12965 int art2 = DECL_ARTIFICIAL (cand2->fn);
12966 if (art1 != art2)
12967 return art2 - art1;
12969 if (art1)
12971 /* Prefer the special copy guide over a declared copy/move
12972 constructor. */
12973 if (copy_guide_p (cand1->fn))
12974 return 1;
12975 if (copy_guide_p (cand2->fn))
12976 return -1;
12978 /* Prefer a candidate generated from a non-template constructor. */
12979 int tg1 = template_guide_p (cand1->fn);
12980 int tg2 = template_guide_p (cand2->fn);
12981 if (tg1 != tg2)
12982 return tg2 - tg1;
12986 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
12987 for all arguments the corresponding parameters of F1 and F2 have the same
12988 type (CWG 2273/2277). */
12989 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
12990 && !DECL_CONV_FN_P (cand1->fn)
12991 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
12992 && !DECL_CONV_FN_P (cand2->fn))
12994 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
12995 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
12997 bool used1 = false;
12998 bool used2 = false;
12999 if (base1 == base2)
13000 /* No difference. */;
13001 else if (DERIVED_FROM_P (base1, base2))
13002 used1 = true;
13003 else if (DERIVED_FROM_P (base2, base1))
13004 used2 = true;
13006 if (int diff = used2 - used1)
13008 for (i = 0; i < len; ++i)
13010 conversion *t1 = cand1->convs[i + off1];
13011 conversion *t2 = cand2->convs[i + off2];
13012 if (!same_type_p (t1->type, t2->type))
13013 break;
13015 if (i == len)
13016 return diff;
13020 /* Check whether we can discard a builtin candidate, either because we
13021 have two identical ones or matching builtin and non-builtin candidates.
13023 (Pedantically in the latter case the builtin which matched the user
13024 function should not be added to the overload set, but we spot it here.
13026 [over.match.oper]
13027 ... the builtin candidates include ...
13028 - do not have the same parameter type list as any non-template
13029 non-member candidate. */
13031 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
13033 for (i = 0; i < len; ++i)
13034 if (!same_type_p (cand1->convs[i]->type,
13035 cand2->convs[i]->type))
13036 break;
13037 if (i == cand1->num_convs)
13039 if (cand1->fn == cand2->fn)
13040 /* Two built-in candidates; arbitrarily pick one. */
13041 return 1;
13042 else if (identifier_p (cand1->fn))
13043 /* cand1 is built-in; prefer cand2. */
13044 return -1;
13045 else
13046 /* cand2 is built-in; prefer cand1. */
13047 return 1;
13051 /* For candidates of a multi-versioned function, make the version with
13052 the highest priority win. This version will be checked for dispatching
13053 first. If this version can be inlined into the caller, the front-end
13054 will simply make a direct call to this function. */
13056 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13057 && DECL_FUNCTION_VERSIONED (cand1->fn)
13058 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13059 && DECL_FUNCTION_VERSIONED (cand2->fn))
13061 tree f1 = TREE_TYPE (cand1->fn);
13062 tree f2 = TREE_TYPE (cand2->fn);
13063 tree p1 = TYPE_ARG_TYPES (f1);
13064 tree p2 = TYPE_ARG_TYPES (f2);
13066 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13067 is possible that cand1->fn and cand2->fn are function versions but of
13068 different functions. Check types to see if they are versions of the same
13069 function. */
13070 if (compparms (p1, p2)
13071 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13073 /* Always make the version with the higher priority, more
13074 specialized, win. */
13075 gcc_assert (targetm.compare_version_priority);
13076 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13077 return 1;
13078 else
13079 return -1;
13083 /* If the two function declarations represent the same function (this can
13084 happen with declarations in multiple scopes and arg-dependent lookup),
13085 arbitrarily choose one. But first make sure the default args we're
13086 using match. */
13087 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13088 && equal_functions (cand1->fn, cand2->fn))
13090 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13091 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13093 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13095 for (i = 0; i < len; ++i)
13097 /* Don't crash if the fn is variadic. */
13098 if (!parms1)
13099 break;
13100 parms1 = TREE_CHAIN (parms1);
13101 parms2 = TREE_CHAIN (parms2);
13104 if (off1)
13105 parms1 = TREE_CHAIN (parms1);
13106 else if (off2)
13107 parms2 = TREE_CHAIN (parms2);
13109 for (; parms1; ++i)
13111 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13112 TREE_PURPOSE (parms2)))
13114 if (warn)
13116 if (complain & tf_error)
13118 auto_diagnostic_group d;
13119 if (permerror (input_location,
13120 "default argument mismatch in "
13121 "overload resolution"))
13123 inform (DECL_SOURCE_LOCATION (cand1->fn),
13124 " candidate 1: %q#F", cand1->fn);
13125 inform (DECL_SOURCE_LOCATION (cand2->fn),
13126 " candidate 2: %q#F", cand2->fn);
13129 else
13130 return 0;
13132 else
13133 add_warning (cand1, cand2);
13134 break;
13136 parms1 = TREE_CHAIN (parms1);
13137 parms2 = TREE_CHAIN (parms2);
13140 return 1;
13143 tweak:
13145 /* Extension: If the worst conversion for one candidate is better than the
13146 worst conversion for the other, take the first. */
13147 if (!pedantic && (complain & tf_warning_or_error))
13149 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13150 struct z_candidate *w = 0, *l = 0;
13152 for (i = 0; i < len; ++i)
13154 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13155 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13156 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13157 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13159 if (rank1 < rank2)
13160 winner = 1, w = cand1, l = cand2;
13161 if (rank1 > rank2)
13162 winner = -1, w = cand2, l = cand1;
13163 if (winner)
13165 /* Don't choose a deleted function over ambiguity. */
13166 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13167 return 0;
13168 if (warn)
13170 auto_diagnostic_group d;
13171 if (pedwarn (input_location, 0,
13172 "ISO C++ says that these are ambiguous, even "
13173 "though the worst conversion for the first is "
13174 "better than the worst conversion for the second:"))
13176 print_z_candidate (input_location, N_("candidate 1:"), w);
13177 print_z_candidate (input_location, N_("candidate 2:"), l);
13180 else
13181 add_warning (w, l);
13182 return winner;
13186 gcc_assert (!winner);
13187 return 0;
13190 /* Given a list of candidates for overloading, find the best one, if any.
13191 This algorithm has a worst case of O(2n) (winner is last), and a best
13192 case of O(n/2) (totally ambiguous); much better than a sorting
13193 algorithm. */
13195 static struct z_candidate *
13196 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13198 struct z_candidate *champ = candidates, *challenger;
13199 int fate;
13200 struct z_candidate *champ_compared_to_predecessor = nullptr;
13202 /* Walk through the list once, comparing each current champ to the next
13203 candidate, knocking out a candidate or two with each comparison. */
13205 for (challenger = champ->next; challenger; )
13207 fate = joust (champ, challenger, 0, complain);
13208 if (fate == 1)
13209 challenger = challenger->next;
13210 else
13212 if (fate == 0)
13214 champ = challenger->next;
13215 if (champ == 0)
13216 return NULL;
13217 champ_compared_to_predecessor = nullptr;
13219 else
13221 champ_compared_to_predecessor = champ;
13222 champ = challenger;
13225 challenger = champ->next;
13229 /* Make sure the champ is better than all the candidates it hasn't yet
13230 been compared to. */
13232 for (challenger = candidates;
13233 challenger != champ
13234 && challenger != champ_compared_to_predecessor;
13235 challenger = challenger->next)
13237 fate = joust (champ, challenger, 0, complain);
13238 if (fate != 1)
13239 return NULL;
13242 return champ;
13245 /* Returns nonzero if things of type FROM can be converted to TO. */
13247 bool
13248 can_convert (tree to, tree from, tsubst_flags_t complain)
13250 tree arg = NULL_TREE;
13251 /* implicit_conversion only considers user-defined conversions
13252 if it has an expression for the call argument list. */
13253 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13254 arg = build_stub_object (from);
13255 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13258 /* Returns nonzero if things of type FROM can be converted to TO with a
13259 standard conversion. */
13261 bool
13262 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13264 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13267 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13269 bool
13270 can_convert_arg (tree to, tree from, tree arg, int flags,
13271 tsubst_flags_t complain)
13273 conversion *t;
13274 void *p;
13275 bool ok_p;
13277 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13278 p = conversion_obstack_alloc (0);
13279 /* We want to discard any access checks done for this test,
13280 as we might not be in the appropriate access context and
13281 we'll do the check again when we actually perform the
13282 conversion. */
13283 push_deferring_access_checks (dk_deferred);
13285 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13286 flags, complain);
13287 ok_p = (t && !t->bad_p);
13289 /* Discard the access checks now. */
13290 pop_deferring_access_checks ();
13291 /* Free all the conversions we allocated. */
13292 obstack_free (&conversion_obstack, p);
13294 return ok_p;
13297 /* Like can_convert_arg, but allows dubious conversions as well. */
13299 bool
13300 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13301 tsubst_flags_t complain)
13303 conversion *t;
13304 void *p;
13306 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13307 p = conversion_obstack_alloc (0);
13308 /* Try to perform the conversion. */
13309 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13310 flags, complain);
13311 /* Free all the conversions we allocated. */
13312 obstack_free (&conversion_obstack, p);
13314 return t != NULL;
13317 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13318 resolution FLAGS. */
13320 tree
13321 build_implicit_conv_flags (tree type, tree expr, int flags)
13323 /* In a template, we are only concerned about determining the
13324 type of non-dependent expressions, so we do not have to
13325 perform the actual conversion. But for initializers, we
13326 need to be able to perform it at instantiation
13327 (or instantiate_non_dependent_expr) time. */
13328 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13329 if (!(flags & LOOKUP_ONLYCONVERTING))
13330 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13331 if (flags & LOOKUP_NO_NARROWING)
13332 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13333 return expr;
13336 /* Convert EXPR to TYPE. Return the converted expression.
13338 Note that we allow bad conversions here because by the time we get to
13339 this point we are committed to doing the conversion. If we end up
13340 doing a bad conversion, convert_like will complain. */
13342 tree
13343 perform_implicit_conversion_flags (tree type, tree expr,
13344 tsubst_flags_t complain, int flags)
13346 conversion *conv;
13347 void *p;
13348 location_t loc = cp_expr_loc_or_input_loc (expr);
13350 if (TYPE_REF_P (type))
13351 expr = mark_lvalue_use (expr);
13352 else
13353 expr = mark_rvalue_use (expr);
13355 if (error_operand_p (expr))
13356 return error_mark_node;
13358 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13359 p = conversion_obstack_alloc (0);
13361 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13362 /*c_cast_p=*/false,
13363 flags, complain);
13365 if (!conv)
13367 if (complain & tf_error)
13368 implicit_conversion_error (loc, type, expr);
13369 expr = error_mark_node;
13371 else if (processing_template_decl && conv->kind != ck_identity)
13372 expr = build_implicit_conv_flags (type, expr, flags);
13373 else
13375 /* Give a conversion call the same location as expr. */
13376 iloc_sentinel il (loc);
13377 expr = convert_like (conv, expr, complain);
13380 /* Free all the conversions we allocated. */
13381 obstack_free (&conversion_obstack, p);
13383 return expr;
13386 tree
13387 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13389 return perform_implicit_conversion_flags (type, expr, complain,
13390 LOOKUP_IMPLICIT);
13393 /* Convert EXPR to TYPE (as a direct-initialization) if that is
13394 permitted. If the conversion is valid, the converted expression is
13395 returned. Otherwise, NULL_TREE is returned, except in the case
13396 that TYPE is a class type; in that case, an error is issued. If
13397 C_CAST_P is true, then this direct-initialization is taking
13398 place as part of a static_cast being attempted as part of a C-style
13399 cast. */
13401 tree
13402 perform_direct_initialization_if_possible (tree type,
13403 tree expr,
13404 bool c_cast_p,
13405 tsubst_flags_t complain)
13407 conversion *conv;
13408 void *p;
13410 if (type == error_mark_node || error_operand_p (expr))
13411 return error_mark_node;
13412 /* [dcl.init]
13414 If the destination type is a (possibly cv-qualified) class type:
13416 -- If the initialization is direct-initialization ...,
13417 constructors are considered.
13419 -- If overload resolution is successful, the selected constructor
13420 is called to initialize the object, with the initializer expression
13421 or expression-list as its argument(s).
13423 -- Otherwise, if no constructor is viable, the destination type is
13424 a (possibly cv-qualified) aggregate class A, and the initializer is
13425 a parenthesized expression-list, the object is initialized as
13426 follows... */
13427 if (CLASS_TYPE_P (type))
13429 releasing_vec args (make_tree_vector_single (expr));
13430 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13431 &args, type, LOOKUP_NORMAL, complain);
13432 return build_cplus_new (type, expr, complain);
13435 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13436 p = conversion_obstack_alloc (0);
13438 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13439 c_cast_p,
13440 LOOKUP_NORMAL, complain);
13441 if (!conv || conv->bad_p)
13442 expr = NULL_TREE;
13443 else if (processing_template_decl && conv->kind != ck_identity)
13445 /* In a template, we are only concerned about determining the
13446 type of non-dependent expressions, so we do not have to
13447 perform the actual conversion. But for initializers, we
13448 need to be able to perform it at instantiation
13449 (or instantiate_non_dependent_expr) time. */
13450 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13451 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13453 else
13454 expr = convert_like (conv, expr, NULL_TREE, 0,
13455 /*issue_conversion_warnings=*/false,
13456 c_cast_p, /*nested_p=*/false, complain);
13458 /* Free all the conversions we allocated. */
13459 obstack_free (&conversion_obstack, p);
13461 return expr;
13464 /* When initializing a reference that lasts longer than a full-expression,
13465 this special rule applies:
13467 [class.temporary]
13469 The temporary to which the reference is bound or the temporary
13470 that is the complete object to which the reference is bound
13471 persists for the lifetime of the reference.
13473 The temporaries created during the evaluation of the expression
13474 initializing the reference, except the temporary to which the
13475 reference is bound, are destroyed at the end of the
13476 full-expression in which they are created.
13478 In that case, we store the converted expression into a new
13479 VAR_DECL in a new scope.
13481 However, we want to be careful not to create temporaries when
13482 they are not required. For example, given:
13484 struct B {};
13485 struct D : public B {};
13486 D f();
13487 const B& b = f();
13489 there is no need to copy the return value from "f"; we can just
13490 extend its lifetime. Similarly, given:
13492 struct S {};
13493 struct T { operator S(); };
13494 T t;
13495 const S& s = t;
13497 we can extend the lifetime of the return value of the conversion
13498 operator.
13500 The next several functions are involved in this lifetime extension. */
13502 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13503 reference is being bound to a temporary. Create and return a new
13504 VAR_DECL with the indicated TYPE; this variable will store the value to
13505 which the reference is bound. */
13507 tree
13508 make_temporary_var_for_ref_to_temp (tree decl, tree type)
13510 tree var = create_temporary_var (type);
13512 /* Register the variable. */
13513 if (VAR_P (decl)
13514 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13516 /* Namespace-scope or local static; give it a mangled name. */
13518 /* If an initializer is visible to multiple translation units, those
13519 translation units must agree on the addresses of the
13520 temporaries. Therefore the temporaries must be given a consistent name
13521 and vague linkage. The mangled name of a temporary is the name of the
13522 non-temporary object in whose initializer they appear, prefixed with
13523 GR and suffixed with a sequence number mangled using the usual rules
13524 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13525 left-to-right walk of the complete initializer. */
13526 copy_linkage (var, decl);
13528 tree name = mangle_ref_init_variable (decl);
13529 DECL_NAME (var) = name;
13530 SET_DECL_ASSEMBLER_NAME (var, name);
13532 else
13533 /* Create a new cleanup level if necessary. */
13534 maybe_push_cleanup_level (type);
13536 return pushdecl (var);
13539 /* EXPR is the initializer for a variable DECL of reference or
13540 std::initializer_list type. Create, push and return a new VAR_DECL
13541 for the initializer so that it will live as long as DECL. Any
13542 cleanup for the new variable is returned through CLEANUP, and the
13543 code to initialize the new variable is returned through INITP. */
13545 static tree
13546 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13547 tree *initp, tree *cond_guard)
13549 tree init;
13550 tree type;
13551 tree var;
13553 /* Create the temporary variable. */
13554 type = TREE_TYPE (expr);
13555 var = make_temporary_var_for_ref_to_temp (decl, type);
13556 layout_decl (var, 0);
13557 /* If the rvalue is the result of a function call it will be
13558 a TARGET_EXPR. If it is some other construct (such as a
13559 member access expression where the underlying object is
13560 itself the result of a function call), turn it into a
13561 TARGET_EXPR here. It is important that EXPR be a
13562 TARGET_EXPR below since otherwise the INIT_EXPR will
13563 attempt to make a bitwise copy of EXPR to initialize
13564 VAR. */
13565 if (TREE_CODE (expr) != TARGET_EXPR)
13566 expr = get_target_expr (expr);
13567 else if (TREE_ADDRESSABLE (expr))
13568 TREE_ADDRESSABLE (var) = 1;
13570 if (TREE_CODE (decl) == FIELD_DECL
13571 && extra_warnings && !warning_suppressed_p (decl))
13573 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13574 "until the constructor exits", decl);
13575 suppress_warning (decl);
13578 /* Recursively extend temps in this initializer. */
13579 TARGET_EXPR_INITIAL (expr)
13580 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13581 cond_guard);
13583 /* Any reference temp has a non-trivial initializer. */
13584 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13586 /* If the initializer is constant, put it in DECL_INITIAL so we get
13587 static initialization and use in constant expressions. */
13588 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13589 /* As in store_init_value. */
13590 init = cp_fully_fold (init);
13591 if (TREE_CONSTANT (init))
13593 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13595 /* 5.19 says that a constant expression can include an
13596 lvalue-rvalue conversion applied to "a glvalue of literal type
13597 that refers to a non-volatile temporary object initialized
13598 with a constant expression". Rather than try to communicate
13599 that this VAR_DECL is a temporary, just mark it constexpr. */
13600 DECL_DECLARED_CONSTEXPR_P (var) = true;
13601 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13602 TREE_CONSTANT (var) = true;
13603 TREE_READONLY (var) = true;
13605 DECL_INITIAL (var) = init;
13606 init = NULL_TREE;
13608 else
13609 /* Create the INIT_EXPR that will initialize the temporary
13610 variable. */
13611 init = split_nonconstant_init (var, expr);
13612 if (at_function_scope_p ())
13614 add_decl_expr (var);
13616 if (TREE_STATIC (var))
13617 init = add_stmt_to_compound (init, register_dtor_fn (var));
13618 else
13620 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13621 if (cleanup)
13623 if (cond_guard && cleanup != error_mark_node)
13625 if (*cond_guard == NULL_TREE)
13627 *cond_guard = build_local_temp (boolean_type_node);
13628 add_decl_expr (*cond_guard);
13629 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13630 *cond_guard, NOP_EXPR,
13631 boolean_false_node,
13632 tf_warning_or_error);
13633 finish_expr_stmt (set);
13635 cleanup = build3 (COND_EXPR, void_type_node,
13636 *cond_guard, cleanup, NULL_TREE);
13638 vec_safe_push (*cleanups, cleanup);
13642 /* We must be careful to destroy the temporary only
13643 after its initialization has taken place. If the
13644 initialization throws an exception, then the
13645 destructor should not be run. We cannot simply
13646 transform INIT into something like:
13648 (INIT, ({ CLEANUP_STMT; }))
13650 because emit_local_var always treats the
13651 initializer as a full-expression. Thus, the
13652 destructor would run too early; it would run at the
13653 end of initializing the reference variable, rather
13654 than at the end of the block enclosing the
13655 reference variable.
13657 The solution is to pass back a cleanup expression
13658 which the caller is responsible for attaching to
13659 the statement tree. */
13661 else
13663 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13664 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13666 if (CP_DECL_THREAD_LOCAL_P (var))
13667 tls_aggregates = tree_cons (NULL_TREE, var,
13668 tls_aggregates);
13669 else
13670 static_aggregates = tree_cons (NULL_TREE, var,
13671 static_aggregates);
13673 else
13674 /* Check whether the dtor is callable. */
13675 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13677 /* Avoid -Wunused-variable warning (c++/38958). */
13678 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13679 && VAR_P (decl))
13680 TREE_USED (decl) = DECL_READ_P (decl) = true;
13682 *initp = init;
13683 return var;
13686 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
13687 initializing a variable of that TYPE. */
13689 tree
13690 initialize_reference (tree type, tree expr,
13691 int flags, tsubst_flags_t complain)
13693 conversion *conv;
13694 void *p;
13695 location_t loc = cp_expr_loc_or_input_loc (expr);
13697 if (type == error_mark_node || error_operand_p (expr))
13698 return error_mark_node;
13700 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13701 p = conversion_obstack_alloc (0);
13703 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13704 flags, complain);
13705 /* If this conversion failed, we're in C++20, and we have something like
13706 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13707 if ((!conv || conv->bad_p)
13708 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13710 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13711 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13712 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13713 conversion *c = reference_binding (type, TREE_TYPE (e), e,
13714 /*c_cast_p=*/false, flags, complain);
13715 /* If this worked, use it. */
13716 if (c && !c->bad_p)
13717 expr = e, conv = c;
13719 if (!conv || conv->bad_p)
13721 if (complain & tf_error)
13723 if (conv)
13724 convert_like (conv, expr, complain);
13725 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13726 && !TYPE_REF_IS_RVALUE (type)
13727 && !lvalue_p (expr))
13728 error_at (loc, "invalid initialization of non-const reference of "
13729 "type %qH from an rvalue of type %qI",
13730 type, TREE_TYPE (expr));
13731 else
13732 error_at (loc, "invalid initialization of reference of type "
13733 "%qH from expression of type %qI", type,
13734 TREE_TYPE (expr));
13736 return error_mark_node;
13739 if (conv->kind == ck_ref_bind)
13740 /* Perform the conversion. */
13741 expr = convert_like (conv, expr, complain);
13742 else if (conv->kind == ck_ambig)
13743 /* We gave an error in build_user_type_conversion_1. */
13744 expr = error_mark_node;
13745 else
13746 gcc_unreachable ();
13748 /* Free all the conversions we allocated. */
13749 obstack_free (&conversion_obstack, p);
13751 return expr;
13754 /* Return true if T is std::pair<const T&, const T&>. */
13756 static bool
13757 std_pair_ref_ref_p (tree t)
13759 /* First, check if we have std::pair. */
13760 if (!NON_UNION_CLASS_TYPE_P (t)
13761 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
13762 return false;
13763 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
13764 if (!decl_in_std_namespace_p (tdecl))
13765 return false;
13766 tree name = DECL_NAME (tdecl);
13767 if (!name || !id_equal (name, "pair"))
13768 return false;
13770 /* Now see if the template arguments are both const T&. */
13771 tree args = CLASSTYPE_TI_ARGS (t);
13772 if (TREE_VEC_LENGTH (args) != 2)
13773 return false;
13774 for (int i = 0; i < 2; i++)
13775 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
13776 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
13777 return false;
13779 return true;
13782 /* Return true if a class CTYPE is either std::reference_wrapper or
13783 std::ref_view, or a reference wrapper class. We consider a class
13784 a reference wrapper class if it has a reference member and a
13785 constructor taking the same reference type. */
13787 static bool
13788 reference_like_class_p (tree ctype)
13790 if (!CLASS_TYPE_P (ctype))
13791 return false;
13793 /* Also accept a std::pair<const T&, const T&>. */
13794 if (std_pair_ref_ref_p (ctype))
13795 return true;
13797 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
13798 if (decl_in_std_namespace_p (tdecl))
13800 tree name = DECL_NAME (tdecl);
13801 return (name
13802 && (id_equal (name, "reference_wrapper")
13803 || id_equal (name, "ref_view")));
13805 for (tree fields = TYPE_FIELDS (ctype);
13806 fields;
13807 fields = DECL_CHAIN (fields))
13809 if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
13810 continue;
13811 tree type = TREE_TYPE (fields);
13812 if (!TYPE_REF_P (type))
13813 continue;
13814 /* OK, the field is a reference member. Do we have a constructor
13815 taking its type? */
13816 for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
13818 tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
13819 if (args
13820 && same_type_p (TREE_VALUE (args), type)
13821 && TREE_CHAIN (args) == void_list_node)
13822 return true;
13825 return false;
13828 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
13829 that initializes the LHS (and at least one of its arguments represents
13830 a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
13831 if none found. For instance:
13833 const S& s = S().self(); // S::self (&TARGET_EXPR <...>)
13834 const int& r = (42, f(1)); // f(1)
13835 const int& t = b ? f(1) : f(2); // f(1)
13836 const int& u = b ? f(1) : f(g); // f(1)
13837 const int& v = b ? f(g) : f(2); // f(2)
13838 const int& w = b ? f(g) : f(g); // NULL_TREE
13839 const int& y = (f(1), 42); // NULL_TREE
13840 const int& z = f(f(1)); // f(f(1))
13842 EXPR is the initializer. If ARG_P is true, we're processing an argument
13843 to a function; the point is to distinguish between, for example,
13845 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
13847 where we shouldn't warn, and
13849 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
13851 where we should warn (Ref is a reference_like_class_p so we see through
13852 it. */
13854 static tree
13855 do_warn_dangling_reference (tree expr, bool arg_p)
13857 STRIP_NOPS (expr);
13859 if (arg_p && expr_represents_temporary_p (expr))
13861 /* An attempt to reduce the number of -Wdangling-reference
13862 false positives concerning reference wrappers (c++/107532).
13863 When we encounter a reference_like_class_p, we don't warn
13864 just yet; instead, we keep recursing to see if there were
13865 any temporaries behind the reference-wrapper class. */
13866 tree e = expr;
13867 while (handled_component_p (e))
13868 e = TREE_OPERAND (e, 0);
13869 if (!reference_like_class_p (TREE_TYPE (e)))
13870 return expr;
13873 switch (TREE_CODE (expr))
13875 case CALL_EXPR:
13877 tree fndecl = cp_get_callee_fndecl_nofold (expr);
13878 if (!fndecl
13879 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
13880 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
13881 OPT_Wdangling_reference)
13882 /* Don't emit a false positive for:
13883 std::vector<int> v = ...;
13884 std::vector<int>::const_iterator it = v.begin();
13885 const int &r = *it++;
13886 because R refers to one of the int elements of V, not to
13887 a temporary object. Member operator* may return a reference
13888 but probably not to one of its arguments. */
13889 || (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13890 && DECL_OVERLOADED_OPERATOR_P (fndecl)
13891 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF)))
13892 return NULL_TREE;
13894 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
13895 /* If the function doesn't return a reference, don't warn. This
13896 can be e.g.
13897 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
13898 which doesn't dangle: std::min here returns an int.
13900 If the function returns a std::pair<const T&, const T&>, we
13901 warn, to detect e.g.
13902 std::pair<const int&, const int&> v = std::minmax(1, 2);
13903 which also creates a dangling reference, because std::minmax
13904 returns std::pair<const T&, const T&>(b, a). */
13905 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
13906 return NULL_TREE;
13908 /* Here we're looking to see if any of the arguments is a temporary
13909 initializing a reference parameter. */
13910 for (int i = 0; i < call_expr_nargs (expr); ++i)
13912 tree arg = CALL_EXPR_ARG (expr, i);
13913 /* Check that this argument initializes a reference, except for
13914 the argument initializing the object of a member function. */
13915 if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13916 && !TYPE_REF_P (TREE_TYPE (arg)))
13917 continue;
13918 STRIP_NOPS (arg);
13919 if (TREE_CODE (arg) == ADDR_EXPR)
13920 arg = TREE_OPERAND (arg, 0);
13921 /* Recurse to see if the argument is a temporary. It could also
13922 be another call taking a temporary and returning it and
13923 initializing this reference parameter. */
13924 if (do_warn_dangling_reference (arg, /*arg_p=*/true))
13925 return expr;
13926 /* Don't warn about member function like:
13927 std::any a(...);
13928 S& s = a.emplace<S>({0}, 0);
13929 which constructs a new object and returns a reference to it, but
13930 we still want to detect:
13931 struct S { const S& self () { return *this; } };
13932 const S& s = S().self();
13933 where 's' dangles. If we've gotten here, the object this function
13934 is invoked on is not a temporary. */
13935 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl))
13936 break;
13938 return NULL_TREE;
13940 case COMPOUND_EXPR:
13941 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
13942 case COND_EXPR:
13943 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
13944 return t;
13945 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
13946 case PAREN_EXPR:
13947 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
13948 case TARGET_EXPR:
13949 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
13950 default:
13951 return NULL_TREE;
13955 /* Implement -Wdangling-reference, to detect cases like
13957 int n = 1;
13958 const int& r = std::max(n - 1, n + 1); // r is dangling
13960 This creates temporaries from the arguments, returns a reference to
13961 one of the temporaries, but both temporaries are destroyed at the end
13962 of the full expression.
13964 This works by checking if a reference is initialized with a function
13965 that returns a reference, and at least one parameter of the function
13966 is a reference that is bound to a temporary. It assumes that such a
13967 function actually returns one of its arguments.
13969 DECL is the reference being initialized, INIT is the initializer. */
13971 static void
13972 maybe_warn_dangling_reference (const_tree decl, tree init)
13974 if (!warn_dangling_reference)
13975 return;
13976 tree type = TREE_TYPE (decl);
13977 /* Only warn if what we're initializing has type T&& or const T&, or
13978 std::pair<const T&, const T&>. (A non-const lvalue reference can't
13979 bind to a temporary.) */
13980 if (!((TYPE_REF_OBJ_P (type)
13981 && (TYPE_REF_IS_RVALUE (type)
13982 || CP_TYPE_CONST_P (TREE_TYPE (type))))
13983 || std_pair_ref_ref_p (type)))
13984 return;
13985 /* Don't suppress the diagnostic just because the call comes from
13986 a system header. If the DECL is not in a system header, or if
13987 -Wsystem-headers was provided, warn. */
13988 auto wsh
13989 = make_temp_override (global_dc->dc_warn_system_headers,
13990 (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
13991 || global_dc->dc_warn_system_headers));
13992 if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
13994 auto_diagnostic_group d;
13995 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
13996 "possibly dangling reference to a temporary"))
13997 inform (EXPR_LOCATION (call), "the temporary was destroyed at "
13998 "the end of the full expression %qE", call);
14002 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
14003 gets used to initialize a reference. */
14005 static tree
14006 prevent_lifetime_extension (tree t)
14008 tree *p = &t;
14009 while (TREE_CODE (*p) == COMPOUND_EXPR)
14010 p = &TREE_OPERAND (*p, 1);
14011 while (handled_component_p (*p))
14012 p = &TREE_OPERAND (*p, 0);
14013 /* Change a TARGET_EXPR from prvalue to xvalue. */
14014 if (TREE_CODE (*p) == TARGET_EXPR)
14015 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14016 move (TARGET_EXPR_SLOT (*p)));
14017 return t;
14020 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14021 which is bound either to a reference or a std::initializer_list. */
14023 static tree
14024 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14025 tree *cond_guard)
14027 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14028 the temporary object that is the complete object of a subobject to which
14029 the reference is bound persists for the lifetime of the reference if the
14030 glvalue to which the reference is bound was obtained through one of the
14031 following:
14032 - a temporary materialization conversion ([conv.rval]),
14033 - ( expression ), where expression is one of these expressions,
14034 - subscripting ([expr.sub]) of an array operand, where that operand is one
14035 of these expressions,
14036 - a class member access ([expr.ref]) using the . operator where the left
14037 operand is one of these expressions and the right operand designates a
14038 non-static data member of non-reference type,
14039 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14040 where the left operand is one of these expressions and the right operand
14041 is a pointer to data member of non-reference type,
14042 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14043 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14044 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14045 a glvalue operand that is one of these expressions to a glvalue that
14046 refers to the object designated by the operand, or to its complete
14047 object or a subobject thereof,
14048 - a conditional expression ([expr.cond]) that is a glvalue where the
14049 second or third operand is one of these expressions, or
14050 - a comma expression ([expr.comma]) that is a glvalue where the right
14051 operand is one of these expressions. */
14053 /* FIXME several cases are still handled wrong (101572, 81420). */
14055 tree sub = init;
14056 tree *p;
14057 STRIP_NOPS (sub);
14058 if (TREE_CODE (sub) == COMPOUND_EXPR)
14060 TREE_OPERAND (sub, 1)
14061 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14062 cond_guard);
14063 return init;
14065 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14066 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14067 (TREE_OPERAND (sub, 1)))))
14069 /* A pointer-to-member operation. */
14070 TREE_OPERAND (sub, 0)
14071 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14072 cond_guard);
14073 return init;
14075 if (TREE_CODE (sub) == COND_EXPR)
14077 tree cur_cond_guard = NULL_TREE;
14078 if (TREE_OPERAND (sub, 1))
14079 TREE_OPERAND (sub, 1)
14080 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14081 &cur_cond_guard);
14082 if (cur_cond_guard)
14084 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14085 NOP_EXPR, boolean_true_node,
14086 tf_warning_or_error);
14087 TREE_OPERAND (sub, 1)
14088 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14089 tf_warning_or_error);
14091 cur_cond_guard = NULL_TREE;
14092 if (TREE_OPERAND (sub, 2))
14093 TREE_OPERAND (sub, 2)
14094 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14095 &cur_cond_guard);
14096 if (cur_cond_guard)
14098 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14099 NOP_EXPR, boolean_true_node,
14100 tf_warning_or_error);
14101 TREE_OPERAND (sub, 2)
14102 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14103 tf_warning_or_error);
14105 return init;
14107 if (TREE_CODE (sub) != ADDR_EXPR)
14108 return init;
14109 /* Deal with binding to a subobject. */
14110 for (p = &TREE_OPERAND (sub, 0);
14111 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14112 p = &TREE_OPERAND (*p, 0);
14113 if (TREE_CODE (*p) == TARGET_EXPR)
14115 tree subinit = NULL_TREE;
14116 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
14117 recompute_tree_invariant_for_addr_expr (sub);
14118 if (init != sub)
14119 init = fold_convert (TREE_TYPE (init), sub);
14120 if (subinit)
14121 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14123 return init;
14126 /* INIT is part of the initializer for DECL. If there are any
14127 reference or initializer lists being initialized, extend their
14128 lifetime to match that of DECL. */
14130 tree
14131 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14132 tree *cond_guard)
14134 tree type = TREE_TYPE (init);
14135 if (processing_template_decl)
14136 return init;
14138 maybe_warn_dangling_reference (decl, init);
14140 if (TYPE_REF_P (type))
14141 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14142 else
14144 tree ctor = init;
14145 if (TREE_CODE (ctor) == TARGET_EXPR)
14146 ctor = TARGET_EXPR_INITIAL (ctor);
14147 if (TREE_CODE (ctor) == CONSTRUCTOR)
14149 /* [dcl.init] When initializing an aggregate from a parenthesized list
14150 of values... a temporary object bound to a reference does not have
14151 its lifetime extended. */
14152 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14153 return init;
14155 if (is_std_init_list (type))
14157 /* The temporary array underlying a std::initializer_list
14158 is handled like a reference temporary. */
14159 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14160 array = extend_ref_init_temps_1 (decl, array, cleanups,
14161 cond_guard);
14162 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14164 else
14166 unsigned i;
14167 constructor_elt *p;
14168 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14169 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14170 p->value = extend_ref_init_temps (decl, p->value, cleanups,
14171 cond_guard);
14173 recompute_constructor_flags (ctor);
14174 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14175 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14179 return init;
14182 /* Returns true iff an initializer for TYPE could contain temporaries that
14183 need to be extended because they are bound to references or
14184 std::initializer_list. */
14186 bool
14187 type_has_extended_temps (tree type)
14189 type = strip_array_types (type);
14190 if (TYPE_REF_P (type))
14191 return true;
14192 if (CLASS_TYPE_P (type))
14194 if (is_std_init_list (type))
14195 return true;
14196 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14197 f; f = next_aggregate_field (DECL_CHAIN (f)))
14198 if (type_has_extended_temps (TREE_TYPE (f)))
14199 return true;
14201 return false;
14204 /* Returns true iff TYPE is some variant of std::initializer_list. */
14206 bool
14207 is_std_init_list (tree type)
14209 if (!TYPE_P (type))
14210 return false;
14211 if (cxx_dialect == cxx98)
14212 return false;
14213 /* Look through typedefs. */
14214 type = TYPE_MAIN_VARIANT (type);
14215 return (CLASS_TYPE_P (type)
14216 && CP_TYPE_CONTEXT (type) == std_node
14217 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14220 /* Returns true iff DECL is a list constructor: i.e. a constructor which
14221 will accept an argument list of a single std::initializer_list<T>. */
14223 bool
14224 is_list_ctor (tree decl)
14226 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14227 tree arg;
14229 if (!args || args == void_list_node)
14230 return false;
14232 arg = non_reference (TREE_VALUE (args));
14233 if (!is_std_init_list (arg))
14234 return false;
14236 args = TREE_CHAIN (args);
14238 if (args && args != void_list_node && !TREE_PURPOSE (args))
14239 /* There are more non-defaulted parms. */
14240 return false;
14242 return true;
14245 #include "gt-cp-call.h"