c++: binding reference to comma expr [PR114561]
[official-gcc.git] / gcc / cp / call.cc
blob9568b5eb2c447c705da1ef24644e2436d83296b9
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2024 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 "decl.h"
45 #include "gcc-rich-location.h"
46 #include "tristate.h"
48 /* The various kinds of conversion. */
50 enum conversion_kind {
51 ck_identity,
52 ck_lvalue,
53 ck_fnptr,
54 ck_qual,
55 ck_std,
56 ck_ptr,
57 ck_pmem,
58 ck_base,
59 ck_ref_bind,
60 ck_user,
61 ck_ambig,
62 ck_list,
63 ck_aggr,
64 ck_rvalue,
65 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
66 this kind whenever we know the true conversion is either bad or outright
67 invalid, but we don't want to attempt to compute the bad conversion (for
68 sake of avoiding unnecessary instantiation). bad_p should always be set
69 for these. */
70 ck_deferred_bad,
73 /* The rank of the conversion. Order of the enumerals matters; better
74 conversions should come earlier in the list. */
76 enum conversion_rank {
77 cr_identity,
78 cr_exact,
79 cr_promotion,
80 cr_std,
81 cr_pbool,
82 cr_user,
83 cr_ellipsis,
84 cr_bad
87 /* An implicit conversion sequence, in the sense of [over.best.ics].
88 The first conversion to be performed is at the end of the chain.
89 That conversion is always a cr_identity conversion. */
91 struct conversion {
92 /* The kind of conversion represented by this step. */
93 conversion_kind kind;
94 /* The rank of this conversion. */
95 conversion_rank rank;
96 BOOL_BITFIELD user_conv_p : 1;
97 BOOL_BITFIELD ellipsis_p : 1;
98 BOOL_BITFIELD this_p : 1;
99 /* True if this conversion would be permitted with a bending of
100 language standards, e.g. disregarding pointer qualifiers or
101 converting integers to pointers. */
102 BOOL_BITFIELD bad_p : 1;
103 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
104 temporary should be created to hold the result of the
105 conversion. If KIND is ck_ambig or ck_user, true means force
106 copy-initialization. */
107 BOOL_BITFIELD need_temporary_p : 1;
108 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
109 from a pointer-to-derived to pointer-to-base is being performed. */
110 BOOL_BITFIELD base_p : 1;
111 /* If KIND is ck_ref_bind, true when either an lvalue reference is
112 being bound to an lvalue expression or an rvalue reference is
113 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
114 true when we are treating an lvalue as an rvalue (12.8p33). If
115 ck_identity, we will be binding a reference directly or decaying to
116 a pointer. */
117 BOOL_BITFIELD rvaluedness_matches_p: 1;
118 BOOL_BITFIELD check_narrowing: 1;
119 /* Whether check_narrowing should only check TREE_CONSTANTs; used
120 in build_converted_constant_expr. */
121 BOOL_BITFIELD check_narrowing_const_only: 1;
122 /* True if this conversion is taking place in a copy-initialization context
123 and we should only consider converting constructors. Only set in
124 ck_base and ck_rvalue. */
125 BOOL_BITFIELD copy_init_p : 1;
126 /* The type of the expression resulting from the conversion. */
127 tree type;
128 union {
129 /* The next conversion in the chain. Since the conversions are
130 arranged from outermost to innermost, the NEXT conversion will
131 actually be performed before this conversion. This variant is
132 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
133 ck_list. Please use the next_conversion function instead
134 of using this field directly. */
135 conversion *next;
136 /* The expression at the beginning of the conversion chain. This
137 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
138 You can use conv_get_original_expr to get this expression. */
139 tree expr;
140 /* The array of conversions for an initializer_list, so this
141 variant is used only when KIN D is ck_list. */
142 conversion **list;
143 } u;
144 /* The function candidate corresponding to this conversion
145 sequence. This field is only used if KIND is ck_user. */
146 struct z_candidate *cand;
149 #define CONVERSION_RANK(NODE) \
150 ((NODE)->bad_p ? cr_bad \
151 : (NODE)->ellipsis_p ? cr_ellipsis \
152 : (NODE)->user_conv_p ? cr_user \
153 : (NODE)->rank)
155 #define BAD_CONVERSION_RANK(NODE) \
156 ((NODE)->ellipsis_p ? cr_ellipsis \
157 : (NODE)->user_conv_p ? cr_user \
158 : (NODE)->rank)
160 static struct obstack conversion_obstack;
161 static bool conversion_obstack_initialized;
162 struct rejection_reason;
164 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
165 static int equal_functions (tree, tree);
166 static int joust (struct z_candidate *, struct z_candidate *, bool,
167 tsubst_flags_t);
168 static int compare_ics (conversion *, conversion *);
169 static void maybe_warn_class_memaccess (location_t, tree,
170 const vec<tree, va_gc> *);
171 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
172 static tree convert_like (conversion *, tree, tsubst_flags_t);
173 static tree convert_like_with_context (conversion *, tree, tree, int,
174 tsubst_flags_t);
175 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
176 tree, tree, tree, bool);
177 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
178 tsubst_flags_t);
179 static void print_z_candidate (location_t, const char *, struct z_candidate *);
180 static void print_z_candidates (location_t, struct z_candidate *,
181 tristate = tristate::unknown ());
182 static tree build_this (tree);
183 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
184 static bool any_strictly_viable (struct z_candidate *);
185 static struct z_candidate *add_template_candidate
186 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
187 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
188 static struct z_candidate *add_template_candidate_real
189 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
190 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
191 static bool is_complete (tree);
192 static struct z_candidate *add_conv_candidate
193 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
194 tree, tsubst_flags_t);
195 static struct z_candidate *add_function_candidate
196 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
197 tree, int, conversion**, bool, tsubst_flags_t);
198 static conversion *implicit_conversion (tree, tree, tree, bool, int,
199 tsubst_flags_t);
200 static conversion *reference_binding (tree, tree, tree, bool, int,
201 tsubst_flags_t);
202 static conversion *build_conv (conversion_kind, tree, conversion *);
203 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
204 static conversion *next_conversion (conversion *);
205 static bool is_subseq (conversion *, conversion *);
206 static conversion *maybe_handle_ref_bind (conversion **);
207 static void maybe_handle_implicit_object (conversion **);
208 static struct z_candidate *add_candidate
209 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
210 conversion **, tree, tree, int, struct rejection_reason *, int);
211 static tree source_type (conversion *);
212 static void add_warning (struct z_candidate *, struct z_candidate *);
213 static conversion *direct_reference_binding (tree, conversion *);
214 static bool promoted_arithmetic_type_p (tree);
215 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
216 static char *name_as_c_string (tree, tree, bool *);
217 static tree prep_operand (tree);
218 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
219 bool, tree, tree, int, struct z_candidate **,
220 tsubst_flags_t);
221 static conversion *merge_conversion_sequences (conversion *, conversion *);
222 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
223 static conversion *build_identity_conv (tree, tree);
224 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
225 static bool conv_is_prvalue (conversion *);
226 static tree prevent_lifetime_extension (tree);
228 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
229 NAME can take many forms... */
231 bool
232 check_dtor_name (tree basetype, tree name)
234 /* Just accept something we've already complained about. */
235 if (name == error_mark_node)
236 return true;
238 if (TREE_CODE (name) == TYPE_DECL)
239 name = TREE_TYPE (name);
240 else if (TYPE_P (name))
241 /* OK */;
242 else if (identifier_p (name))
244 if ((MAYBE_CLASS_TYPE_P (basetype)
245 || TREE_CODE (basetype) == ENUMERAL_TYPE)
246 && name == constructor_name (basetype))
247 return true;
249 /* Otherwise lookup the name, it could be an unrelated typedef
250 of the correct type. */
251 name = lookup_name (name, LOOK_want::TYPE);
252 if (!name)
253 return false;
254 name = TREE_TYPE (name);
255 if (name == error_mark_node)
256 return false;
258 else
260 /* In the case of:
262 template <class T> struct S { ~S(); };
263 int i;
264 i.~S();
266 NAME will be a class template. */
267 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
268 return false;
271 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
274 /* We want the address of a function or method. We avoid creating a
275 pointer-to-member function. */
277 tree
278 build_addr_func (tree function, tsubst_flags_t complain)
280 tree type = TREE_TYPE (function);
282 /* We have to do these by hand to avoid real pointer to member
283 functions. */
284 if (TREE_CODE (type) == METHOD_TYPE)
286 if (TREE_CODE (function) == OFFSET_REF)
288 tree object = build_address (TREE_OPERAND (function, 0));
289 return get_member_function_from_ptrfunc (&object,
290 TREE_OPERAND (function, 1),
291 complain);
293 function = build_address (function);
295 else if (TREE_CODE (function) == FUNCTION_DECL
296 && DECL_IMMEDIATE_FUNCTION_P (function))
297 function = build_address (function);
298 else
299 function = decay_conversion (function, complain, /*reject_builtin=*/false);
301 return function;
304 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
305 POINTER_TYPE to those. Note, pointer to member function types
306 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
307 two variants. build_call_a is the primitive taking an array of
308 arguments, while build_call_n is a wrapper that handles varargs. */
310 tree
311 build_call_n (tree function, int n, ...)
313 if (n == 0)
314 return build_call_a (function, 0, NULL);
315 else
317 tree *argarray = XALLOCAVEC (tree, n);
318 va_list ap;
319 int i;
321 va_start (ap, n);
322 for (i = 0; i < n; i++)
323 argarray[i] = va_arg (ap, tree);
324 va_end (ap);
325 return build_call_a (function, n, argarray);
329 /* Update various flags in cfun and the call itself based on what is being
330 called. Split out of build_call_a so that bot_manip can use it too. */
332 void
333 set_flags_from_callee (tree call)
335 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
336 tree decl = cp_get_callee_fndecl_nofold (call);
338 /* We check both the decl and the type; a function may be known not to
339 throw without being declared throw(). */
340 bool nothrow = decl && TREE_NOTHROW (decl);
341 tree callee = cp_get_callee (call);
342 if (callee)
343 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
344 else if (TREE_CODE (call) == CALL_EXPR
345 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
346 nothrow = true;
348 if (cfun && cp_function_chain && !cp_unevaluated_operand)
350 if (!nothrow && at_function_scope_p ())
351 cp_function_chain->can_throw = 1;
353 if (decl && TREE_THIS_VOLATILE (decl))
354 current_function_returns_abnormally = 1;
357 TREE_NOTHROW (call) = nothrow;
360 tree
361 build_call_a (tree function, int n, tree *argarray)
363 tree decl;
364 tree result_type;
365 tree fntype;
366 int i;
368 function = build_addr_func (function, tf_warning_or_error);
370 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
371 fntype = TREE_TYPE (TREE_TYPE (function));
372 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
373 result_type = TREE_TYPE (fntype);
374 /* An rvalue has no cv-qualifiers. */
375 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
376 result_type = cv_unqualified (result_type);
378 function = build_call_array_loc (input_location,
379 result_type, function, n, argarray);
380 set_flags_from_callee (function);
382 decl = get_callee_fndecl (function);
384 if (decl && !TREE_USED (decl))
386 /* We invoke build_call directly for several library
387 functions. These may have been declared normally if
388 we're building libgcc, so we can't just check
389 DECL_ARTIFICIAL. */
390 gcc_assert (DECL_ARTIFICIAL (decl)
391 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
392 "__", 2));
393 mark_used (decl);
396 require_complete_eh_spec_types (fntype, decl);
398 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
400 /* Don't pass empty class objects by value. This is useful
401 for tags in STL, which are used to control overload resolution.
402 We don't need to handle other cases of copying empty classes. */
403 if (!decl || !fndecl_built_in_p (decl))
404 for (i = 0; i < n; i++)
406 tree arg = CALL_EXPR_ARG (function, i);
407 if (is_empty_class (TREE_TYPE (arg))
408 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
410 while (TREE_CODE (arg) == TARGET_EXPR)
411 /* We're disconnecting the initializer from its target,
412 don't create a temporary. */
413 arg = TARGET_EXPR_INITIAL (arg);
414 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
415 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
416 CALL_EXPR_ARG (function, i) = arg;
420 return function;
423 /* New overloading code. */
425 struct z_candidate;
427 struct candidate_warning {
428 z_candidate *loser;
429 candidate_warning *next;
432 /* Information for providing diagnostics about why overloading failed. */
434 enum rejection_reason_code {
435 rr_none,
436 rr_arity,
437 rr_explicit_conversion,
438 rr_template_conversion,
439 rr_arg_conversion,
440 rr_bad_arg_conversion,
441 rr_template_unification,
442 rr_invalid_copy,
443 rr_inherited_ctor,
444 rr_constraint_failure,
445 rr_ignored,
448 struct conversion_info {
449 /* The index of the argument, 0-based. */
450 int n_arg;
451 /* The actual argument or its type. */
452 tree from;
453 /* The type of the parameter. */
454 tree to_type;
455 /* The location of the argument. */
456 location_t loc;
459 struct rejection_reason {
460 enum rejection_reason_code code;
461 union {
462 /* Information about an arity mismatch. */
463 struct {
464 /* The expected number of arguments. */
465 int expected;
466 /* The actual number of arguments in the call. */
467 int actual;
468 /* Whether EXPECTED should be treated as a lower bound. */
469 bool least_p;
470 } arity;
471 /* Information about an argument conversion mismatch. */
472 struct conversion_info conversion;
473 /* Same, but for bad argument conversions. */
474 struct conversion_info bad_conversion;
475 /* Information about template unification failures. These are the
476 parameters passed to fn_type_unification. */
477 struct {
478 tree tmpl;
479 tree explicit_targs;
480 int num_targs;
481 const tree *args;
482 unsigned int nargs;
483 tree return_type;
484 unification_kind_t strict;
485 int flags;
486 } template_unification;
487 /* Information about template instantiation failures. These are the
488 parameters passed to instantiate_template. */
489 struct {
490 tree tmpl;
491 tree targs;
492 } template_instantiation;
493 } u;
496 struct z_candidate {
497 /* The FUNCTION_DECL that will be called if this candidate is
498 selected by overload resolution. */
499 tree fn;
500 /* If not NULL_TREE, the first argument to use when calling this
501 function. */
502 tree first_arg;
503 /* The rest of the arguments to use when calling this function. If
504 there are no further arguments this may be NULL or it may be an
505 empty vector. */
506 const vec<tree, va_gc> *args;
507 /* The implicit conversion sequences for each of the arguments to
508 FN. */
509 conversion **convs;
510 /* The number of implicit conversion sequences. */
511 size_t num_convs;
512 /* If FN is a user-defined conversion, the standard conversion
513 sequence from the type returned by FN to the desired destination
514 type. */
515 conversion *second_conv;
516 struct rejection_reason *reason;
517 /* If FN is a member function, the binfo indicating the path used to
518 qualify the name of FN at the call site. This path is used to
519 determine whether or not FN is accessible if it is selected by
520 overload resolution. The DECL_CONTEXT of FN will always be a
521 (possibly improper) base of this binfo. */
522 tree access_path;
523 /* If FN is a non-static member function, the binfo indicating the
524 subobject to which the `this' pointer should be converted if FN
525 is selected by overload resolution. The type pointed to by
526 the `this' pointer must correspond to the most derived class
527 indicated by the CONVERSION_PATH. */
528 tree conversion_path;
529 tree template_decl;
530 tree explicit_targs;
531 candidate_warning *warnings;
532 z_candidate *next;
533 int viable;
535 /* The flags active in add_candidate. */
536 int flags;
538 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
539 bool reversed () const { return (flags & LOOKUP_REVERSED); }
542 /* Returns true iff T is a null pointer constant in the sense of
543 [conv.ptr]. */
545 bool
546 null_ptr_cst_p (tree t)
548 tree type = TREE_TYPE (t);
550 /* [conv.ptr]
552 A null pointer constant is an integer literal ([lex.icon]) with value
553 zero or a prvalue of type std::nullptr_t. */
554 if (NULLPTR_TYPE_P (type))
555 return true;
557 if (cxx_dialect >= cxx11)
559 STRIP_ANY_LOCATION_WRAPPER (t);
561 /* Core issue 903 says only literal 0 is a null pointer constant. */
562 if (TREE_CODE (t) == INTEGER_CST
563 && !TREE_OVERFLOW (t)
564 && TREE_CODE (type) == INTEGER_TYPE
565 && integer_zerop (t)
566 && !char_type_p (type))
567 return true;
569 else if (CP_INTEGRAL_TYPE_P (type))
571 t = fold_non_dependent_expr (t, tf_none);
572 STRIP_NOPS (t);
573 if (integer_zerop (t) && !TREE_OVERFLOW (t))
574 return true;
577 return false;
580 /* Returns true iff T is a null member pointer value (4.11). */
582 bool
583 null_member_pointer_value_p (tree t)
585 tree type = TREE_TYPE (t);
586 if (!type)
587 return false;
588 else if (TYPE_PTRMEMFUNC_P (type))
589 return (TREE_CODE (t) == CONSTRUCTOR
590 && CONSTRUCTOR_NELTS (t)
591 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
592 else if (TYPE_PTRDATAMEM_P (type))
593 return integer_all_onesp (t);
594 else
595 return false;
598 /* Returns nonzero if PARMLIST consists of only default parms,
599 ellipsis, and/or undeduced parameter packs. */
601 bool
602 sufficient_parms_p (const_tree parmlist)
604 for (; parmlist && parmlist != void_list_node;
605 parmlist = TREE_CHAIN (parmlist))
606 if (!TREE_PURPOSE (parmlist)
607 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
608 return false;
609 return true;
612 /* Allocate N bytes of memory from the conversion obstack. The memory
613 is zeroed before being returned. */
615 static void *
616 conversion_obstack_alloc (size_t n)
618 void *p;
619 if (!conversion_obstack_initialized)
621 gcc_obstack_init (&conversion_obstack);
622 conversion_obstack_initialized = true;
624 p = obstack_alloc (&conversion_obstack, n);
625 memset (p, 0, n);
626 return p;
629 /* RAII class to discard anything added to conversion_obstack. */
631 struct conversion_obstack_sentinel
633 void *p;
634 conversion_obstack_sentinel (): p (conversion_obstack_alloc (0)) {}
635 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
638 /* Allocate rejection reasons. */
640 static struct rejection_reason *
641 alloc_rejection (enum rejection_reason_code code)
643 struct rejection_reason *p;
644 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
645 p->code = code;
646 return p;
649 static struct rejection_reason *
650 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
652 struct rejection_reason *r = alloc_rejection (rr_arity);
653 int adjust = first_arg != NULL_TREE;
654 r->u.arity.expected = expected - adjust;
655 r->u.arity.actual = actual - adjust;
656 r->u.arity.least_p = least_p;
657 return r;
660 static struct rejection_reason *
661 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
662 location_t loc)
664 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
665 int adjust = first_arg != NULL_TREE;
666 r->u.conversion.n_arg = n_arg - adjust;
667 r->u.conversion.from = from;
668 r->u.conversion.to_type = to;
669 r->u.conversion.loc = loc;
670 return r;
673 static struct rejection_reason *
674 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
675 location_t loc)
677 struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
678 int adjust = first_arg != NULL_TREE;
679 r->u.bad_conversion.n_arg = n_arg - adjust;
680 r->u.bad_conversion.from = from;
681 r->u.bad_conversion.to_type = to;
682 r->u.bad_conversion.loc = loc;
683 return r;
686 static struct rejection_reason *
687 explicit_conversion_rejection (tree from, tree to)
689 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
690 r->u.conversion.n_arg = 0;
691 r->u.conversion.from = from;
692 r->u.conversion.to_type = to;
693 r->u.conversion.loc = UNKNOWN_LOCATION;
694 return r;
697 static struct rejection_reason *
698 template_conversion_rejection (tree from, tree to)
700 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
701 r->u.conversion.n_arg = 0;
702 r->u.conversion.from = from;
703 r->u.conversion.to_type = to;
704 r->u.conversion.loc = UNKNOWN_LOCATION;
705 return r;
708 static struct rejection_reason *
709 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
710 const tree *args, unsigned int nargs,
711 tree return_type, unification_kind_t strict,
712 int flags)
714 size_t args_n_bytes = sizeof (*args) * nargs;
715 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
716 struct rejection_reason *r = alloc_rejection (rr_template_unification);
717 r->u.template_unification.tmpl = tmpl;
718 r->u.template_unification.explicit_targs = explicit_targs;
719 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
720 /* Copy args to our own storage. */
721 memcpy (args1, args, args_n_bytes);
722 r->u.template_unification.args = args1;
723 r->u.template_unification.nargs = nargs;
724 r->u.template_unification.return_type = return_type;
725 r->u.template_unification.strict = strict;
726 r->u.template_unification.flags = flags;
727 return r;
730 static struct rejection_reason *
731 template_unification_error_rejection (void)
733 return alloc_rejection (rr_template_unification);
736 static struct rejection_reason *
737 invalid_copy_with_fn_template_rejection (void)
739 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
740 return r;
743 static struct rejection_reason *
744 inherited_ctor_rejection (void)
746 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
747 return r;
750 /* Build a constraint failure record. */
752 static struct rejection_reason *
753 constraint_failure (void)
755 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
756 return r;
759 /* Dynamically allocate a conversion. */
761 static conversion *
762 alloc_conversion (conversion_kind kind)
764 conversion *c;
765 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
766 c->kind = kind;
767 return c;
770 /* Make sure that all memory on the conversion obstack has been
771 freed. */
773 void
774 validate_conversion_obstack (void)
776 if (conversion_obstack_initialized)
777 gcc_assert ((obstack_next_free (&conversion_obstack)
778 == obstack_base (&conversion_obstack)));
781 /* Dynamically allocate an array of N conversions. */
783 static conversion **
784 alloc_conversions (size_t n)
786 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
789 /* True iff the active member of conversion::u for code CODE is NEXT. */
791 static inline bool
792 has_next (conversion_kind code)
794 return !(code == ck_identity
795 || code == ck_ambig
796 || code == ck_list
797 || code == ck_aggr
798 || code == ck_deferred_bad);
801 static conversion *
802 build_conv (conversion_kind code, tree type, conversion *from)
804 conversion *t;
805 conversion_rank rank = CONVERSION_RANK (from);
807 /* Only call this function for conversions that use u.next. */
808 gcc_assert (from == NULL || has_next (code));
810 /* Note that the caller is responsible for filling in t->cand for
811 user-defined conversions. */
812 t = alloc_conversion (code);
813 t->type = type;
814 t->u.next = from;
816 switch (code)
818 case ck_ptr:
819 case ck_pmem:
820 case ck_base:
821 case ck_std:
822 if (rank < cr_std)
823 rank = cr_std;
824 break;
826 case ck_qual:
827 case ck_fnptr:
828 if (rank < cr_exact)
829 rank = cr_exact;
830 break;
832 default:
833 break;
835 t->rank = rank;
836 t->user_conv_p = (code == ck_user || from->user_conv_p);
837 t->bad_p = from->bad_p;
838 t->base_p = false;
839 return t;
842 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
843 specialization of std::initializer_list<T>, if such a conversion is
844 possible. */
846 static conversion *
847 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
849 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
850 unsigned len = CONSTRUCTOR_NELTS (ctor);
851 conversion **subconvs = alloc_conversions (len);
852 conversion *t;
853 unsigned i;
854 tree val;
856 /* Within a list-initialization we can have more user-defined
857 conversions. */
858 flags &= ~LOOKUP_NO_CONVERSION;
859 /* But no narrowing conversions. */
860 flags |= LOOKUP_NO_NARROWING;
862 /* Can't make an array of these types. */
863 if (TYPE_REF_P (elttype)
864 || TREE_CODE (elttype) == FUNCTION_TYPE
865 || VOID_TYPE_P (elttype))
866 return NULL;
868 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
870 conversion *sub
871 = implicit_conversion (elttype, TREE_TYPE (val), val,
872 false, flags, complain);
873 if (sub == NULL)
874 return NULL;
876 subconvs[i] = sub;
879 t = alloc_conversion (ck_list);
880 t->type = type;
881 t->u.list = subconvs;
882 t->rank = cr_exact;
884 for (i = 0; i < len; ++i)
886 conversion *sub = subconvs[i];
887 if (sub->rank > t->rank)
888 t->rank = sub->rank;
889 if (sub->user_conv_p)
890 t->user_conv_p = true;
891 if (sub->bad_p)
892 t->bad_p = true;
895 return t;
898 /* Return the next conversion of the conversion chain (if applicable),
899 or NULL otherwise. Please use this function instead of directly
900 accessing fields of struct conversion. */
902 static conversion *
903 next_conversion (conversion *conv)
905 if (conv == NULL
906 || !has_next (conv->kind))
907 return NULL;
908 return conv->u.next;
911 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
912 encountered. */
914 static conversion *
915 strip_standard_conversion (conversion *conv)
917 while (conv
918 && conv->kind != ck_user
919 && has_next (conv->kind))
920 conv = next_conversion (conv);
921 return conv;
924 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
925 initializer for array type ATYPE. */
927 static bool
928 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
930 tree elttype = TREE_TYPE (atype);
931 unsigned i;
933 if (TREE_CODE (from) == CONSTRUCTOR)
935 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
937 tree val = CONSTRUCTOR_ELT (from, i)->value;
938 bool ok;
939 if (TREE_CODE (elttype) == ARRAY_TYPE)
940 ok = can_convert_array (elttype, val, flags, complain);
941 else
942 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
943 complain);
944 if (!ok)
945 return false;
947 return true;
950 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
951 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
952 return array_string_literal_compatible_p (atype, from);
954 /* No other valid way to aggregate initialize an array. */
955 return false;
958 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
959 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
960 is in PSET. */
962 static bool
963 field_in_pset (hash_set<tree, true> &pset, tree field)
965 if (pset.contains (field))
966 return true;
967 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
968 for (field = TYPE_FIELDS (TREE_TYPE (field));
969 field; field = DECL_CHAIN (field))
971 field = next_aggregate_field (field);
972 if (field == NULL_TREE)
973 break;
974 if (field_in_pset (pset, field))
975 return true;
977 return false;
980 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
981 aggregate class, if such a conversion is possible. */
983 static conversion *
984 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
986 unsigned HOST_WIDE_INT i = 0;
987 conversion *c;
988 tree field = next_aggregate_field (TYPE_FIELDS (type));
989 tree empty_ctor = NULL_TREE;
990 hash_set<tree, true> pset;
992 /* We already called reshape_init in implicit_conversion, but it might not
993 have done anything in the case of parenthesized aggr init. */
995 /* The conversions within the init-list aren't affected by the enclosing
996 context; they're always simple copy-initialization. */
997 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
999 /* For designated initializers, verify that each initializer is convertible
1000 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
1001 visited. In the following loop then ignore already visited
1002 FIELD_DECLs. */
1003 tree idx, val;
1004 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1006 if (!idx)
1007 break;
1009 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1011 tree ftype = TREE_TYPE (idx);
1012 bool ok;
1014 if (TREE_CODE (ftype) == ARRAY_TYPE)
1015 ok = can_convert_array (ftype, val, flags, complain);
1016 else
1017 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1018 complain);
1020 if (!ok)
1021 return NULL;
1023 /* For unions, there should be just one initializer. */
1024 if (TREE_CODE (type) == UNION_TYPE)
1026 field = NULL_TREE;
1027 i = 1;
1028 break;
1030 pset.add (idx);
1033 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1035 tree ftype = TREE_TYPE (field);
1036 bool ok;
1038 if (!pset.is_empty () && field_in_pset (pset, field))
1039 continue;
1040 if (i < CONSTRUCTOR_NELTS (ctor))
1042 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1043 gcc_checking_assert (!ce->index);
1044 val = ce->value;
1045 ++i;
1047 else if (DECL_INITIAL (field))
1048 val = get_nsdmi (field, /*ctor*/false, complain);
1049 else if (TYPE_REF_P (ftype))
1050 /* Value-initialization of reference is ill-formed. */
1051 return NULL;
1052 else
1054 if (empty_ctor == NULL_TREE)
1055 empty_ctor = build_constructor (init_list_type_node, NULL);
1056 val = empty_ctor;
1059 if (TREE_CODE (ftype) == ARRAY_TYPE)
1060 ok = can_convert_array (ftype, val, flags, complain);
1061 else
1062 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1063 complain);
1065 if (!ok)
1066 return NULL;
1068 if (TREE_CODE (type) == UNION_TYPE)
1069 break;
1072 if (i < CONSTRUCTOR_NELTS (ctor))
1073 return NULL;
1075 c = alloc_conversion (ck_aggr);
1076 c->type = type;
1077 c->rank = cr_exact;
1078 c->user_conv_p = true;
1079 c->check_narrowing = true;
1080 c->u.expr = ctor;
1081 return c;
1084 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1085 array type, if such a conversion is possible. */
1087 static conversion *
1088 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1090 conversion *c;
1091 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1092 tree elttype = TREE_TYPE (type);
1093 bool bad = false;
1094 bool user = false;
1095 enum conversion_rank rank = cr_exact;
1097 /* We might need to propagate the size from the element to the array. */
1098 complete_type (type);
1100 if (TYPE_DOMAIN (type)
1101 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1103 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1104 if (alen < len)
1105 return NULL;
1108 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1110 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1112 conversion *sub
1113 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1114 false, flags, complain);
1115 if (sub == NULL)
1116 return NULL;
1118 if (sub->rank > rank)
1119 rank = sub->rank;
1120 if (sub->user_conv_p)
1121 user = true;
1122 if (sub->bad_p)
1123 bad = true;
1126 c = alloc_conversion (ck_aggr);
1127 c->type = type;
1128 c->rank = rank;
1129 c->user_conv_p = user;
1130 c->bad_p = bad;
1131 c->u.expr = ctor;
1132 return c;
1135 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1136 complex type, if such a conversion is possible. */
1138 static conversion *
1139 build_complex_conv (tree type, tree ctor, int flags,
1140 tsubst_flags_t complain)
1142 conversion *c;
1143 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1144 tree elttype = TREE_TYPE (type);
1145 bool bad = false;
1146 bool user = false;
1147 enum conversion_rank rank = cr_exact;
1149 if (len != 2)
1150 return NULL;
1152 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1154 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1156 conversion *sub
1157 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1158 false, flags, complain);
1159 if (sub == NULL)
1160 return NULL;
1162 if (sub->rank > rank)
1163 rank = sub->rank;
1164 if (sub->user_conv_p)
1165 user = true;
1166 if (sub->bad_p)
1167 bad = true;
1170 c = alloc_conversion (ck_aggr);
1171 c->type = type;
1172 c->rank = rank;
1173 c->user_conv_p = user;
1174 c->bad_p = bad;
1175 c->u.expr = ctor;
1176 return c;
1179 /* Build a representation of the identity conversion from EXPR to
1180 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1182 static conversion *
1183 build_identity_conv (tree type, tree expr)
1185 conversion *c;
1187 c = alloc_conversion (ck_identity);
1188 c->type = type;
1189 c->u.expr = expr;
1191 return c;
1194 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1195 were multiple user-defined conversions to accomplish the job.
1196 Build a conversion that indicates that ambiguity. */
1198 static conversion *
1199 build_ambiguous_conv (tree type, tree expr)
1201 conversion *c;
1203 c = alloc_conversion (ck_ambig);
1204 c->type = type;
1205 c->u.expr = expr;
1207 return c;
1210 tree
1211 strip_top_quals (tree t)
1213 if (TREE_CODE (t) == ARRAY_TYPE)
1214 return t;
1215 return cp_build_qualified_type (t, 0);
1218 /* Returns the standard conversion path (see [conv]) from type FROM to type
1219 TO, if any. For proper handling of null pointer constants, you must
1220 also pass the expression EXPR to convert from. If C_CAST_P is true,
1221 this conversion is coming from a C-style cast. */
1223 static conversion *
1224 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1225 int flags, tsubst_flags_t complain)
1227 enum tree_code fcode, tcode;
1228 conversion *conv;
1229 bool fromref = false;
1230 tree qualified_to;
1232 to = non_reference (to);
1233 if (TYPE_REF_P (from))
1235 fromref = true;
1236 from = TREE_TYPE (from);
1238 qualified_to = to;
1239 to = strip_top_quals (to);
1240 from = strip_top_quals (from);
1242 if (expr && type_unknown_p (expr))
1244 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1246 tsubst_flags_t tflags = tf_conv;
1247 expr = instantiate_type (to, expr, tflags);
1248 if (expr == error_mark_node)
1249 return NULL;
1250 from = TREE_TYPE (expr);
1252 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1254 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1255 expr = resolve_nondeduced_context (expr, complain);
1256 from = TREE_TYPE (expr);
1260 fcode = TREE_CODE (from);
1261 tcode = TREE_CODE (to);
1263 conv = build_identity_conv (from, expr);
1264 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1266 from = type_decays_to (from);
1267 fcode = TREE_CODE (from);
1268 /* Tell convert_like that we're using the address. */
1269 conv->rvaluedness_matches_p = true;
1270 conv = build_conv (ck_lvalue, from, conv);
1272 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1273 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1274 express the copy constructor call required by copy-initialization. */
1275 else if (fromref || (expr && obvalue_p (expr)))
1277 if (expr)
1279 tree bitfield_type;
1280 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1281 if (bitfield_type)
1283 from = strip_top_quals (bitfield_type);
1284 fcode = TREE_CODE (from);
1287 conv = build_conv (ck_rvalue, from, conv);
1288 /* If we're performing copy-initialization, remember to skip
1289 explicit constructors. */
1290 if (flags & LOOKUP_ONLYCONVERTING)
1291 conv->copy_init_p = true;
1294 /* Allow conversion between `__complex__' data types. */
1295 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1297 /* The standard conversion sequence to convert FROM to TO is
1298 the standard conversion sequence to perform componentwise
1299 conversion. */
1300 conversion *part_conv = standard_conversion
1301 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1302 complain);
1304 if (!part_conv)
1305 conv = NULL;
1306 else if (part_conv->kind == ck_identity)
1307 /* Leave conv alone. */;
1308 else
1310 conv = build_conv (part_conv->kind, to, conv);
1311 conv->rank = part_conv->rank;
1314 return conv;
1317 if (same_type_p (from, to))
1319 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1320 conv->type = qualified_to;
1321 return conv;
1324 /* [conv.ptr]
1325 A null pointer constant can be converted to a pointer type; ... A
1326 null pointer constant of integral type can be converted to an
1327 rvalue of type std::nullptr_t. */
1328 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1329 || NULLPTR_TYPE_P (to))
1330 && ((expr && null_ptr_cst_p (expr))
1331 || NULLPTR_TYPE_P (from)))
1332 conv = build_conv (ck_std, to, conv);
1333 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1334 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1336 /* For backwards brain damage compatibility, allow interconversion of
1337 pointers and integers with a pedwarn. */
1338 conv = build_conv (ck_std, to, conv);
1339 conv->bad_p = true;
1341 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1343 /* For backwards brain damage compatibility, allow interconversion of
1344 enums and integers with a pedwarn. */
1345 conv = build_conv (ck_std, to, conv);
1346 conv->bad_p = true;
1348 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1349 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1351 tree to_pointee;
1352 tree from_pointee;
1354 if (tcode == POINTER_TYPE)
1356 to_pointee = TREE_TYPE (to);
1357 from_pointee = TREE_TYPE (from);
1359 /* Since this is the target of a pointer, it can't have function
1360 qualifiers, so any TYPE_QUALS must be for attributes const or
1361 noreturn. Strip them. */
1362 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1363 && TYPE_QUALS (to_pointee))
1364 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1365 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1366 && TYPE_QUALS (from_pointee))
1367 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1369 else
1371 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1372 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1375 if (tcode == POINTER_TYPE
1376 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1377 to_pointee))
1379 else if (VOID_TYPE_P (to_pointee)
1380 && !TYPE_PTRDATAMEM_P (from)
1381 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1383 tree nfrom = TREE_TYPE (from);
1384 /* Don't try to apply restrict to void. */
1385 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1386 from_pointee = cp_build_qualified_type (void_type_node, quals);
1387 from = build_pointer_type (from_pointee);
1388 conv = build_conv (ck_ptr, from, conv);
1390 else if (TYPE_PTRDATAMEM_P (from))
1392 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1393 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1395 if (same_type_p (fbase, tbase))
1396 /* No base conversion needed. */;
1397 else if (DERIVED_FROM_P (fbase, tbase)
1398 && (same_type_ignoring_top_level_qualifiers_p
1399 (from_pointee, to_pointee)))
1401 from = build_ptrmem_type (tbase, from_pointee);
1402 conv = build_conv (ck_pmem, from, conv);
1404 else
1405 return NULL;
1407 else if (CLASS_TYPE_P (from_pointee)
1408 && CLASS_TYPE_P (to_pointee)
1409 /* [conv.ptr]
1411 An rvalue of type "pointer to cv D," where D is a
1412 class type, can be converted to an rvalue of type
1413 "pointer to cv B," where B is a base class (clause
1414 _class.derived_) of D. If B is an inaccessible
1415 (clause _class.access_) or ambiguous
1416 (_class.member.lookup_) base class of D, a program
1417 that necessitates this conversion is ill-formed.
1418 Therefore, we use DERIVED_FROM_P, and do not check
1419 access or uniqueness. */
1420 && DERIVED_FROM_P (to_pointee, from_pointee))
1422 from_pointee
1423 = cp_build_qualified_type (to_pointee,
1424 cp_type_quals (from_pointee));
1425 from = build_pointer_type (from_pointee);
1426 conv = build_conv (ck_ptr, from, conv);
1427 conv->base_p = true;
1430 if (same_type_p (from, to))
1431 /* OK */;
1432 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1433 /* In a C-style cast, we ignore CV-qualification because we
1434 are allowed to perform a static_cast followed by a
1435 const_cast. */
1436 conv = build_conv (ck_qual, to, conv);
1437 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1438 conv = build_conv (ck_qual, to, conv);
1439 else if (expr && string_conv_p (to, expr, 0))
1440 /* converting from string constant to char *. */
1441 conv = build_conv (ck_qual, to, conv);
1442 else if (fnptr_conv_p (to, from))
1443 conv = build_conv (ck_fnptr, to, conv);
1444 /* Allow conversions among compatible ObjC pointer types (base
1445 conversions have been already handled above). */
1446 else if (c_dialect_objc ()
1447 && objc_compare_types (to, from, -4, NULL_TREE))
1448 conv = build_conv (ck_ptr, to, conv);
1449 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1451 conv = build_conv (ck_ptr, to, conv);
1452 conv->bad_p = true;
1454 else
1455 return NULL;
1457 from = to;
1459 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1461 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1462 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1463 tree fbase = class_of_this_parm (fromfn);
1464 tree tbase = class_of_this_parm (tofn);
1466 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1467 yields false. But a pointer to member of incomplete class is OK. */
1468 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1469 return NULL;
1471 tree fstat = static_fn_type (fromfn);
1472 tree tstat = static_fn_type (tofn);
1473 if (same_type_p (tstat, fstat)
1474 || fnptr_conv_p (tstat, fstat))
1475 /* OK */;
1476 else
1477 return NULL;
1479 if (!same_type_p (fbase, tbase))
1481 from = build_memfn_type (fstat,
1482 tbase,
1483 cp_type_quals (tbase),
1484 type_memfn_rqual (tofn));
1485 from = build_ptrmemfunc_type (build_pointer_type (from));
1486 conv = build_conv (ck_pmem, from, conv);
1487 conv->base_p = true;
1489 if (fnptr_conv_p (tstat, fstat))
1490 conv = build_conv (ck_fnptr, to, conv);
1492 else if (tcode == BOOLEAN_TYPE)
1494 /* [conv.bool]
1496 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1497 to member type can be converted to a prvalue of type bool. ...
1498 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1499 std::nullptr_t can be converted to a prvalue of type bool; */
1500 if (ARITHMETIC_TYPE_P (from)
1501 || UNSCOPED_ENUM_P (from)
1502 || fcode == POINTER_TYPE
1503 || TYPE_PTRMEM_P (from)
1504 || NULLPTR_TYPE_P (from))
1506 conv = build_conv (ck_std, to, conv);
1507 if (fcode == POINTER_TYPE
1508 || TYPE_PTRDATAMEM_P (from)
1509 || (TYPE_PTRMEMFUNC_P (from)
1510 && conv->rank < cr_pbool)
1511 || NULLPTR_TYPE_P (from))
1512 conv->rank = cr_pbool;
1513 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1514 conv->bad_p = true;
1515 if (flags & LOOKUP_NO_NARROWING)
1516 conv->check_narrowing = true;
1517 return conv;
1520 return NULL;
1522 /* We don't check for ENUMERAL_TYPE here because there are no standard
1523 conversions to enum type. */
1524 /* As an extension, allow conversion to complex type. */
1525 else if (ARITHMETIC_TYPE_P (to))
1527 if (! (INTEGRAL_CODE_P (fcode)
1528 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1529 || SCOPED_ENUM_P (from))
1530 return NULL;
1532 /* If we're parsing an enum with no fixed underlying type, we're
1533 dealing with an incomplete type, which renders the conversion
1534 ill-formed. */
1535 if (!COMPLETE_TYPE_P (from))
1536 return NULL;
1538 conv = build_conv (ck_std, to, conv);
1540 tree underlying_type = NULL_TREE;
1541 if (TREE_CODE (from) == ENUMERAL_TYPE
1542 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1543 underlying_type = ENUM_UNDERLYING_TYPE (from);
1545 /* Give this a better rank if it's a promotion.
1547 To handle CWG 1601, also bump the rank if we are converting
1548 an enumeration with a fixed underlying type to the underlying
1549 type. */
1550 if ((same_type_p (to, type_promotes_to (from))
1551 || (underlying_type && same_type_p (to, underlying_type)))
1552 && next_conversion (conv)->rank <= cr_promotion)
1553 conv->rank = cr_promotion;
1555 /* A prvalue of floating-point type can be converted to a prvalue of
1556 another floating-point type with a greater or equal conversion
1557 rank ([conv.rank]). A prvalue of standard floating-point type can
1558 be converted to a prvalue of another standard floating-point type.
1559 For backwards compatibility with handling __float128 and other
1560 non-standard floating point types, allow all implicit floating
1561 point conversions if neither type is extended floating-point
1562 type and if at least one of them is, fail if they have unordered
1563 conversion rank or from has higher conversion rank. */
1564 if (fcode == REAL_TYPE
1565 && tcode == REAL_TYPE
1566 && (extended_float_type_p (from)
1567 || extended_float_type_p (to))
1568 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1569 conv->bad_p = true;
1571 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1572 && vector_types_convertible_p (from, to, false))
1573 return build_conv (ck_std, to, conv);
1574 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1575 && is_properly_derived_from (from, to))
1577 if (conv->kind == ck_rvalue)
1578 conv = next_conversion (conv);
1579 conv = build_conv (ck_base, to, conv);
1580 /* The derived-to-base conversion indicates the initialization
1581 of a parameter with base type from an object of a derived
1582 type. A temporary object is created to hold the result of
1583 the conversion unless we're binding directly to a reference. */
1584 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1585 /* If we're performing copy-initialization, remember to skip
1586 explicit constructors. */
1587 if (flags & LOOKUP_ONLYCONVERTING)
1588 conv->copy_init_p = true;
1590 else
1591 return NULL;
1593 if (flags & LOOKUP_NO_NARROWING)
1594 conv->check_narrowing = true;
1596 return conv;
1599 /* Returns nonzero if T1 is reference-related to T2. */
1601 bool
1602 reference_related_p (tree t1, tree t2)
1604 if (t1 == error_mark_node || t2 == error_mark_node)
1605 return false;
1607 t1 = TYPE_MAIN_VARIANT (t1);
1608 t2 = TYPE_MAIN_VARIANT (t2);
1610 /* [dcl.init.ref]
1612 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1613 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1614 return (similar_type_p (t1, t2)
1615 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1616 && DERIVED_FROM_P (t1, t2)));
1619 /* Returns nonzero if T1 is reference-compatible with T2. */
1621 bool
1622 reference_compatible_p (tree t1, tree t2)
1624 /* [dcl.init.ref]
1626 "cv1 T1" is reference compatible with "cv2 T2" if
1627 a prvalue of type "pointer to cv2 T2" can be converted to the type
1628 "pointer to cv1 T1" via a standard conversion sequence. */
1629 tree ptype1 = build_pointer_type (t1);
1630 tree ptype2 = build_pointer_type (t2);
1631 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1632 /*c_cast_p=*/false, 0, tf_none);
1633 if (!conv || conv->bad_p)
1634 return false;
1635 return true;
1638 /* Return true if converting FROM to TO would involve a qualification
1639 conversion. */
1641 static bool
1642 involves_qualification_conversion_p (tree to, tree from)
1644 /* If we're not convering a pointer to another one, we won't get
1645 a qualification conversion. */
1646 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1647 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1648 return false;
1650 conversion *conv = standard_conversion (to, from, NULL_TREE,
1651 /*c_cast_p=*/false, 0, tf_none);
1652 for (conversion *t = conv; t; t = next_conversion (t))
1653 if (t->kind == ck_qual)
1654 return true;
1656 return false;
1659 /* A reference of the indicated TYPE is being bound directly to the
1660 expression represented by the implicit conversion sequence CONV.
1661 Return a conversion sequence for this binding. */
1663 static conversion *
1664 direct_reference_binding (tree type, conversion *conv)
1666 tree t;
1668 gcc_assert (TYPE_REF_P (type));
1669 gcc_assert (!TYPE_REF_P (conv->type));
1671 t = TREE_TYPE (type);
1673 if (conv->kind == ck_identity)
1674 /* Mark the identity conv as to not decay to rvalue. */
1675 conv->rvaluedness_matches_p = true;
1677 /* [over.ics.rank]
1679 When a parameter of reference type binds directly
1680 (_dcl.init.ref_) to an argument expression, the implicit
1681 conversion sequence is the identity conversion, unless the
1682 argument expression has a type that is a derived class of the
1683 parameter type, in which case the implicit conversion sequence is
1684 a derived-to-base Conversion.
1686 If the parameter binds directly to the result of applying a
1687 conversion function to the argument expression, the implicit
1688 conversion sequence is a user-defined conversion sequence
1689 (_over.ics.user_), with the second standard conversion sequence
1690 either an identity conversion or, if the conversion function
1691 returns an entity of a type that is a derived class of the
1692 parameter type, a derived-to-base conversion. */
1693 if (is_properly_derived_from (conv->type, t))
1695 /* Represent the derived-to-base conversion. */
1696 conv = build_conv (ck_base, t, conv);
1697 /* We will actually be binding to the base-class subobject in
1698 the derived class, so we mark this conversion appropriately.
1699 That way, convert_like knows not to generate a temporary. */
1700 conv->need_temporary_p = false;
1702 else if (involves_qualification_conversion_p (t, conv->type))
1703 /* Represent the qualification conversion. After DR 2352
1704 #1 and #2 were indistinguishable conversion sequences:
1706 void f(int*); // #1
1707 void f(const int* const &); // #2
1708 void g(int* p) { f(p); }
1710 because the types "int *" and "const int *const" are
1711 reference-related and we were binding both directly and they
1712 had the same rank. To break it up, we add a ck_qual under the
1713 ck_ref_bind so that conversion sequence ranking chooses #1.
1715 We strip_top_quals here which is also what standard_conversion
1716 does. Failure to do so would confuse comp_cv_qual_signature
1717 into thinking that in
1719 void f(const int * const &); // #1
1720 void f(const int *); // #2
1721 int *x;
1722 f(x);
1724 #2 is a better match than #1 even though they're ambiguous (97296). */
1725 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1727 return build_conv (ck_ref_bind, type, conv);
1730 /* Returns the conversion path from type FROM to reference type TO for
1731 purposes of reference binding. For lvalue binding, either pass a
1732 reference type to FROM or an lvalue expression to EXPR. If the
1733 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1734 the conversion returned. If C_CAST_P is true, this
1735 conversion is coming from a C-style cast. */
1737 static conversion *
1738 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1739 tsubst_flags_t complain)
1741 conversion *conv = NULL;
1742 conversion *bad_direct_conv = nullptr;
1743 tree to = TREE_TYPE (rto);
1744 tree from = rfrom;
1745 tree tfrom;
1746 bool related_p;
1747 bool compatible_p;
1748 cp_lvalue_kind gl_kind;
1749 bool is_lvalue;
1751 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1753 expr = instantiate_type (to, expr, tf_none);
1754 if (expr == error_mark_node)
1755 return NULL;
1756 from = TREE_TYPE (expr);
1759 bool copy_list_init = false;
1760 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1762 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1763 /* DR 1288: Otherwise, if the initializer list has a single element
1764 of type E and ... [T's] referenced type is reference-related to E,
1765 the object or reference is initialized from that element...
1767 ??? With P0388R4, we should bind 't' directly to U{}:
1768 using U = A[2];
1769 A (&&t)[] = {U{}};
1770 because A[] and A[2] are reference-related. But we don't do it
1771 because grok_reference_init has deduced the array size (to 1), and
1772 A[1] and A[2] aren't reference-related. */
1773 if (CONSTRUCTOR_NELTS (expr) == 1
1774 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1776 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1777 if (error_operand_p (elt))
1778 return NULL;
1779 tree etype = TREE_TYPE (elt);
1780 if (reference_related_p (to, etype))
1782 expr = elt;
1783 from = etype;
1784 goto skip;
1787 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1788 referenced by T is copy-list-initialized, and the reference is bound
1789 to that temporary. */
1790 copy_list_init = true;
1791 skip:;
1794 if (TYPE_REF_P (from))
1796 from = TREE_TYPE (from);
1797 if (!TYPE_REF_IS_RVALUE (rfrom)
1798 || TREE_CODE (from) == FUNCTION_TYPE)
1799 gl_kind = clk_ordinary;
1800 else
1801 gl_kind = clk_rvalueref;
1803 else if (expr)
1804 gl_kind = lvalue_kind (expr);
1805 else if (CLASS_TYPE_P (from)
1806 || TREE_CODE (from) == ARRAY_TYPE)
1807 gl_kind = clk_class;
1808 else
1809 gl_kind = clk_none;
1811 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1812 if ((flags & LOOKUP_NO_TEMP_BIND)
1813 && (gl_kind & clk_class))
1814 gl_kind = clk_none;
1816 /* Same mask as real_lvalue_p. */
1817 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1819 tfrom = from;
1820 if ((gl_kind & clk_bitfield) != 0)
1821 tfrom = unlowered_expr_type (expr);
1823 /* Figure out whether or not the types are reference-related and
1824 reference compatible. We have to do this after stripping
1825 references from FROM. */
1826 related_p = reference_related_p (to, tfrom);
1827 /* If this is a C cast, first convert to an appropriately qualified
1828 type, so that we can later do a const_cast to the desired type. */
1829 if (related_p && c_cast_p
1830 && !at_least_as_qualified_p (to, tfrom))
1831 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1832 compatible_p = reference_compatible_p (to, tfrom);
1834 /* Directly bind reference when target expression's type is compatible with
1835 the reference and expression is an lvalue. In DR391, the wording in
1836 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1837 const and rvalue references to rvalues of compatible class type.
1838 We should also do direct bindings for non-class xvalues. */
1839 if ((related_p || compatible_p) && gl_kind)
1841 /* [dcl.init.ref]
1843 If the initializer expression
1845 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1846 is reference-compatible with "cv2 T2,"
1848 the reference is bound directly to the initializer expression
1849 lvalue.
1851 [...]
1852 If the initializer expression is an rvalue, with T2 a class type,
1853 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1854 is bound to the object represented by the rvalue or to a sub-object
1855 within that object. */
1857 conv = build_identity_conv (tfrom, expr);
1858 conv = direct_reference_binding (rto, conv);
1860 if (TYPE_REF_P (rfrom))
1861 /* Handle rvalue reference to function properly. */
1862 conv->rvaluedness_matches_p
1863 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1864 else
1865 conv->rvaluedness_matches_p
1866 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1868 if ((gl_kind & clk_bitfield) != 0
1869 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1870 /* For the purposes of overload resolution, we ignore the fact
1871 this expression is a bitfield or packed field. (In particular,
1872 [over.ics.ref] says specifically that a function with a
1873 non-const reference parameter is viable even if the
1874 argument is a bitfield.)
1876 However, when we actually call the function we must create
1877 a temporary to which to bind the reference. If the
1878 reference is volatile, or isn't const, then we cannot make
1879 a temporary, so we just issue an error when the conversion
1880 actually occurs. */
1881 conv->need_temporary_p = true;
1883 /* Don't allow binding of lvalues (other than function lvalues) to
1884 rvalue references. */
1885 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1886 && TREE_CODE (to) != FUNCTION_TYPE)
1887 conv->bad_p = true;
1889 /* Nor the reverse. */
1890 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1891 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1892 But in C++23, such an expression is just an xvalue, not a special
1893 lvalue, so the binding is once again ill-formed. */
1894 && !(cxx_dialect <= cxx20
1895 && (gl_kind & clk_implicit_rval))
1896 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1897 || (flags & LOOKUP_NO_RVAL_BIND))
1898 && TREE_CODE (to) != FUNCTION_TYPE)
1899 conv->bad_p = true;
1901 if (!compatible_p)
1902 conv->bad_p = true;
1904 return conv;
1906 /* [class.conv.fct] A conversion function is never used to convert a
1907 (possibly cv-qualified) object to the (possibly cv-qualified) same
1908 object type (or a reference to it), to a (possibly cv-qualified) base
1909 class of that type (or a reference to it).... */
1910 else if (CLASS_TYPE_P (from) && !related_p
1911 && !(flags & LOOKUP_NO_CONVERSION))
1913 /* [dcl.init.ref]
1915 If the initializer expression
1917 -- has a class type (i.e., T2 is a class type) can be
1918 implicitly converted to an lvalue of type "cv3 T3," where
1919 "cv1 T1" is reference-compatible with "cv3 T3". (this
1920 conversion is selected by enumerating the applicable
1921 conversion functions (_over.match.ref_) and choosing the
1922 best one through overload resolution. (_over.match_).
1924 the reference is bound to the lvalue result of the conversion
1925 in the second case. */
1926 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1927 complain);
1928 if (cand)
1930 if (!cand->second_conv->bad_p)
1931 return cand->second_conv;
1933 /* Direct reference binding wasn't successful and yielded a bad
1934 conversion. Proceed with trying to go through a temporary
1935 instead, and if that also fails then we'll return this bad
1936 conversion rather than no conversion for sake of better
1937 diagnostics. */
1938 bad_direct_conv = cand->second_conv;
1942 /* From this point on, we conceptually need temporaries, even if we
1943 elide them. Only the cases above are "direct bindings". */
1944 if (flags & LOOKUP_NO_TEMP_BIND)
1945 return bad_direct_conv ? bad_direct_conv : nullptr;
1947 /* [over.ics.rank]
1949 When a parameter of reference type is not bound directly to an
1950 argument expression, the conversion sequence is the one required
1951 to convert the argument expression to the underlying type of the
1952 reference according to _over.best.ics_. Conceptually, this
1953 conversion sequence corresponds to copy-initializing a temporary
1954 of the underlying type with the argument expression. Any
1955 difference in top-level cv-qualification is subsumed by the
1956 initialization itself and does not constitute a conversion. */
1958 bool maybe_valid_p = true;
1960 /* [dcl.init.ref]
1962 Otherwise, the reference shall be an lvalue reference to a
1963 non-volatile const type, or the reference shall be an rvalue
1964 reference. */
1965 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1966 maybe_valid_p = false;
1968 /* [dcl.init.ref]
1970 Otherwise, a temporary of type "cv1 T1" is created and
1971 initialized from the initializer expression using the rules for a
1972 non-reference copy initialization. If T1 is reference-related to
1973 T2, cv1 must be the same cv-qualification as, or greater
1974 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1975 if (related_p && !at_least_as_qualified_p (to, from))
1976 maybe_valid_p = false;
1978 /* We try below to treat an invalid reference binding as a bad conversion
1979 to improve diagnostics, but doing so may cause otherwise unnecessary
1980 instantiations that can lead to a hard error. So during the first pass
1981 of overload resolution wherein we shortcut bad conversions, instead just
1982 produce a special conversion indicating a second pass is necessary if
1983 there's no strictly viable candidate. */
1984 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1986 if (bad_direct_conv)
1987 return bad_direct_conv;
1989 conv = alloc_conversion (ck_deferred_bad);
1990 conv->bad_p = true;
1991 return conv;
1994 /* We're generating a temporary now, but don't bind any more in the
1995 conversion (specifically, don't slice the temporary returned by a
1996 conversion operator). */
1997 flags |= LOOKUP_NO_TEMP_BIND;
1999 /* Core issue 899: When [copy-]initializing a temporary to be bound
2000 to the first parameter of a copy constructor (12.8) called with
2001 a single argument in the context of direct-initialization,
2002 explicit conversion functions are also considered.
2004 So don't set LOOKUP_ONLYCONVERTING in that case. */
2005 if (!(flags & LOOKUP_COPY_PARM))
2006 flags |= LOOKUP_ONLYCONVERTING;
2008 if (!conv)
2009 conv = implicit_conversion (to, from, expr, c_cast_p,
2010 flags, complain);
2011 if (!conv)
2012 return bad_direct_conv ? bad_direct_conv : nullptr;
2014 if (conv->user_conv_p)
2016 if (copy_list_init)
2017 /* Remember this was copy-list-initialization. */
2018 conv->need_temporary_p = true;
2020 /* If initializing the temporary used a conversion function,
2021 recalculate the second conversion sequence. */
2022 for (conversion *t = conv; t; t = next_conversion (t))
2023 if (t->kind == ck_user
2024 && DECL_CONV_FN_P (t->cand->fn))
2026 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2027 /* A prvalue of non-class type is cv-unqualified. */
2028 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2029 ftype = cv_unqualified (ftype);
2030 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2031 conversion *new_second
2032 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2033 sflags, complain);
2034 if (!new_second)
2035 return bad_direct_conv ? bad_direct_conv : nullptr;
2036 conv = merge_conversion_sequences (t, new_second);
2037 gcc_assert (maybe_valid_p || conv->bad_p);
2038 return conv;
2042 conv = build_conv (ck_ref_bind, rto, conv);
2043 /* This reference binding, unlike those above, requires the
2044 creation of a temporary. */
2045 conv->need_temporary_p = true;
2046 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2047 conv->bad_p |= !maybe_valid_p;
2049 return conv;
2052 /* Returns the implicit conversion sequence (see [over.ics]) from type
2053 FROM to type TO. The optional expression EXPR may affect the
2054 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2055 true, this conversion is coming from a C-style cast. */
2057 static conversion *
2058 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2059 int flags, tsubst_flags_t complain)
2061 conversion *conv;
2063 if (from == error_mark_node || to == error_mark_node
2064 || expr == error_mark_node)
2065 return NULL;
2067 /* Other flags only apply to the primary function in overload
2068 resolution, or after we've chosen one. */
2069 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2070 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2071 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2073 /* FIXME: actually we don't want warnings either, but we can't just
2074 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2075 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2076 We really ought not to issue that warning until we've committed
2077 to that conversion. */
2078 complain &= ~tf_error;
2080 /* Call reshape_init early to remove redundant braces. */
2081 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2083 to = complete_type (to);
2084 if (!COMPLETE_TYPE_P (to))
2085 return nullptr;
2086 if (!CLASSTYPE_NON_AGGREGATE (to))
2088 expr = reshape_init (to, expr, complain);
2089 if (expr == error_mark_node)
2090 return nullptr;
2091 from = TREE_TYPE (expr);
2095 if (TYPE_REF_P (to))
2096 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2097 else
2098 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2100 if (conv)
2101 return conv;
2103 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2105 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2106 return build_list_conv (to, expr, flags, complain);
2108 /* As an extension, allow list-initialization of _Complex. */
2109 if (TREE_CODE (to) == COMPLEX_TYPE
2110 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2112 conv = build_complex_conv (to, expr, flags, complain);
2113 if (conv)
2114 return conv;
2117 /* Allow conversion from an initializer-list with one element to a
2118 scalar type. */
2119 if (SCALAR_TYPE_P (to))
2121 int nelts = CONSTRUCTOR_NELTS (expr);
2122 tree elt;
2124 if (nelts == 0)
2125 elt = build_value_init (to, tf_none);
2126 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2127 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2128 else
2129 elt = error_mark_node;
2131 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2132 c_cast_p, flags, complain);
2133 if (conv)
2135 conv->check_narrowing = true;
2136 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2137 /* Too many levels of braces, i.e. '{{1}}'. */
2138 conv->bad_p = true;
2139 return conv;
2142 else if (TREE_CODE (to) == ARRAY_TYPE)
2143 return build_array_conv (to, expr, flags, complain);
2146 if (expr != NULL_TREE
2147 && (MAYBE_CLASS_TYPE_P (from)
2148 || MAYBE_CLASS_TYPE_P (to))
2149 && (flags & LOOKUP_NO_CONVERSION) == 0)
2151 struct z_candidate *cand;
2153 if (CLASS_TYPE_P (to)
2154 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2155 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2156 return build_aggr_conv (to, expr, flags, complain);
2158 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2159 if (cand)
2161 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2162 && CONSTRUCTOR_NELTS (expr) == 1
2163 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2164 && !is_list_ctor (cand->fn))
2166 /* "If C is not an initializer-list constructor and the
2167 initializer list has a single element of type cv U, where U is
2168 X or a class derived from X, the implicit conversion sequence
2169 has Exact Match rank if U is X, or Conversion rank if U is
2170 derived from X." */
2171 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2172 tree elttype = TREE_TYPE (elt);
2173 if (reference_related_p (to, elttype))
2174 return implicit_conversion (to, elttype, elt,
2175 c_cast_p, flags, complain);
2177 conv = cand->second_conv;
2180 /* We used to try to bind a reference to a temporary here, but that
2181 is now handled after the recursive call to this function at the end
2182 of reference_binding. */
2183 return conv;
2186 return NULL;
2189 /* Like implicit_conversion, but return NULL if the conversion is bad.
2191 This is not static so that check_non_deducible_conversion can call it within
2192 add_template_candidate_real as part of overload resolution; it should not be
2193 called outside of overload resolution. */
2195 conversion *
2196 good_conversion (tree to, tree from, tree expr,
2197 int flags, tsubst_flags_t complain)
2199 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2200 flags, complain);
2201 if (c && c->bad_p)
2202 c = NULL;
2203 return c;
2206 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2207 functions. ARGS will not be changed until a single candidate is
2208 selected. */
2210 static struct z_candidate *
2211 add_candidate (struct z_candidate **candidates,
2212 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2213 size_t num_convs, conversion **convs,
2214 tree access_path, tree conversion_path,
2215 int viable, struct rejection_reason *reason,
2216 int flags)
2218 struct z_candidate *cand = (struct z_candidate *)
2219 conversion_obstack_alloc (sizeof (struct z_candidate));
2221 cand->fn = fn;
2222 cand->first_arg = first_arg;
2223 cand->args = args;
2224 cand->convs = convs;
2225 cand->num_convs = num_convs;
2226 cand->access_path = access_path;
2227 cand->conversion_path = conversion_path;
2228 cand->viable = viable;
2229 cand->reason = reason;
2230 cand->next = *candidates;
2231 cand->flags = flags;
2232 *candidates = cand;
2234 if (convs && cand->reversed ())
2235 /* Swap the conversions for comparison in joust; we'll swap them back
2236 before build_over_call. */
2237 std::swap (convs[0], convs[1]);
2239 return cand;
2242 /* FN is a function from the overload set that we outright didn't even
2243 consider (for some reason); add it to the list as an non-viable "ignored"
2244 candidate. */
2246 static z_candidate *
2247 add_ignored_candidate (z_candidate **candidates, tree fn)
2249 /* No need to dynamically allocate these. */
2250 static const rejection_reason reason_ignored = { rr_ignored, {} };
2252 struct z_candidate *cand = (struct z_candidate *)
2253 conversion_obstack_alloc (sizeof (struct z_candidate));
2255 cand->fn = fn;
2256 cand->reason = const_cast<rejection_reason *> (&reason_ignored);
2257 cand->next = *candidates;
2258 *candidates = cand;
2260 return cand;
2263 /* True iff CAND is a candidate added by add_ignored_candidate. */
2265 static bool
2266 ignored_candidate_p (const z_candidate *cand)
2268 return cand->reason && cand->reason->code == rr_ignored;
2271 /* Return the number of remaining arguments in the parameter list
2272 beginning with ARG. */
2275 remaining_arguments (tree arg)
2277 int n;
2279 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2280 arg = TREE_CHAIN (arg))
2281 n++;
2283 return n;
2286 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2287 to the first parameter of a constructor where the parameter is of type
2288 "reference to possibly cv-qualified T" and the constructor is called with a
2289 single argument in the context of direct-initialization of an object of type
2290 "cv2 T", explicit conversion functions are also considered.
2292 So set LOOKUP_COPY_PARM to let reference_binding know that
2293 it's being called in that context. */
2296 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2298 int lflags = flags;
2299 tree t;
2300 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2301 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2302 && (same_type_ignoring_top_level_qualifiers_p
2303 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2305 if (!(flags & LOOKUP_ONLYCONVERTING))
2306 lflags |= LOOKUP_COPY_PARM;
2307 if ((flags & LOOKUP_LIST_INIT_CTOR)
2308 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2309 lflags |= LOOKUP_NO_CONVERSION;
2311 else
2312 lflags |= LOOKUP_ONLYCONVERTING;
2314 return lflags;
2317 /* Build an appropriate 'this' conversion for the method FN and class
2318 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2319 This function modifies PARMTYPE, ARGTYPE and ARG. */
2321 static conversion *
2322 build_this_conversion (tree fn, tree ctype,
2323 tree& parmtype, tree& argtype, tree& arg,
2324 int flags, tsubst_flags_t complain)
2326 gcc_assert (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2327 && !DECL_CONSTRUCTOR_P (fn));
2329 /* The type of the implicit object parameter ('this') for
2330 overload resolution is not always the same as for the
2331 function itself; conversion functions are considered to
2332 be members of the class being converted, and functions
2333 introduced by a using-declaration are considered to be
2334 members of the class that uses them.
2336 Since build_over_call ignores the ICS for the `this'
2337 parameter, we can just change the parm type. */
2338 parmtype = cp_build_qualified_type (ctype,
2339 cp_type_quals (TREE_TYPE (parmtype)));
2340 bool this_p = true;
2341 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2343 /* If the function has a ref-qualifier, the implicit
2344 object parameter has reference type. */
2345 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2346 parmtype = cp_build_reference_type (parmtype, rv);
2347 /* The special handling of 'this' conversions in compare_ics
2348 does not apply if there is a ref-qualifier. */
2349 this_p = false;
2351 else
2353 parmtype = build_pointer_type (parmtype);
2354 /* We don't use build_this here because we don't want to
2355 capture the object argument until we've chosen a
2356 non-static member function. */
2357 arg = build_address (arg);
2358 argtype = lvalue_type (arg);
2360 flags |= LOOKUP_ONLYCONVERTING;
2361 conversion *t = implicit_conversion (parmtype, argtype, arg,
2362 /*c_cast_p=*/false, flags, complain);
2363 t->this_p = this_p;
2364 return t;
2367 /* Create an overload candidate for the function or method FN called
2368 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2369 FLAGS is passed on to implicit_conversion.
2371 This does not change ARGS.
2373 CTYPE, if non-NULL, is the type we want to pretend this function
2374 comes from for purposes of overload resolution.
2376 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2377 If true, we stop computing conversions upon seeing the first bad
2378 conversion. This is used by add_candidates to avoid computing
2379 more conversions than necessary in the presence of a strictly viable
2380 candidate, while preserving the defacto behavior of overload resolution
2381 when it turns out there are only non-strictly viable candidates. */
2383 static struct z_candidate *
2384 add_function_candidate (struct z_candidate **candidates,
2385 tree fn, tree ctype, tree first_arg,
2386 const vec<tree, va_gc> *args, tree access_path,
2387 tree conversion_path, int flags,
2388 conversion **convs,
2389 bool shortcut_bad_convs,
2390 tsubst_flags_t complain)
2392 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2393 int i, len;
2394 tree parmnode;
2395 tree orig_first_arg = first_arg;
2396 int skip;
2397 int viable = 1;
2398 struct rejection_reason *reason = NULL;
2400 /* The `this', `in_chrg' and VTT arguments to constructors are not
2401 considered in overload resolution. */
2402 if (DECL_CONSTRUCTOR_P (fn))
2404 if (ctor_omit_inherited_parms (fn))
2405 /* Bring back parameters omitted from an inherited ctor. */
2406 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2407 else
2408 parmlist = skip_artificial_parms_for (fn, parmlist);
2409 skip = num_artificial_parms_for (fn);
2410 if (skip > 0 && first_arg != NULL_TREE)
2412 --skip;
2413 first_arg = NULL_TREE;
2416 else
2417 skip = 0;
2419 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2420 if (!convs)
2421 convs = alloc_conversions (len);
2423 /* 13.3.2 - Viable functions [over.match.viable]
2424 First, to be a viable function, a candidate function shall have enough
2425 parameters to agree in number with the arguments in the list.
2427 We need to check this first; otherwise, checking the ICSes might cause
2428 us to produce an ill-formed template instantiation. */
2430 parmnode = parmlist;
2431 for (i = 0; i < len; ++i)
2433 if (parmnode == NULL_TREE || parmnode == void_list_node)
2434 break;
2435 parmnode = TREE_CHAIN (parmnode);
2438 if ((i < len && parmnode)
2439 || !sufficient_parms_p (parmnode))
2441 int remaining = remaining_arguments (parmnode);
2442 viable = 0;
2443 reason = arity_rejection (first_arg, i + remaining, len);
2446 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2447 parameter of type "reference to cv C" (including such a constructor
2448 instantiated from a template) is excluded from the set of candidate
2449 functions when used to construct an object of type D with an argument list
2450 containing a single argument if C is reference-related to D. */
2451 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2452 && flag_new_inheriting_ctors
2453 && DECL_INHERITED_CTOR (fn))
2455 tree ptype = non_reference (TREE_VALUE (parmlist));
2456 tree dtype = DECL_CONTEXT (fn);
2457 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2458 if (reference_related_p (ptype, dtype)
2459 && reference_related_p (btype, ptype))
2461 viable = false;
2462 reason = inherited_ctor_rejection ();
2466 /* Second, for a function to be viable, its constraints must be
2467 satisfied. */
2468 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2470 reason = constraint_failure ();
2471 viable = false;
2474 /* When looking for a function from a subobject from an implicit
2475 copy/move constructor/operator=, don't consider anything that takes (a
2476 reference to) an unrelated type. See c++/44909 and core 1092. */
2477 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2479 if (DECL_CONSTRUCTOR_P (fn))
2480 i = 1;
2481 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2482 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2483 i = 2;
2484 else
2485 i = 0;
2486 if (i && len == i)
2488 parmnode = chain_index (i-1, parmlist);
2489 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2490 ctype))
2491 viable = 0;
2494 /* This only applies at the top level. */
2495 flags &= ~LOOKUP_DEFAULTED;
2498 if (! viable)
2499 goto out;
2501 if (shortcut_bad_convs)
2502 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2503 else
2504 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2506 /* Third, for F to be a viable function, there shall exist for each
2507 argument an implicit conversion sequence that converts that argument
2508 to the corresponding parameter of F. */
2510 parmnode = parmlist;
2512 for (i = 0; i < len; ++i)
2514 tree argtype, to_type;
2515 tree arg;
2517 if (parmnode == void_list_node)
2518 break;
2520 if (convs[i])
2522 /* Already set during deduction. */
2523 parmnode = TREE_CHAIN (parmnode);
2524 continue;
2527 if (i == 0 && first_arg != NULL_TREE)
2528 arg = first_arg;
2529 else
2530 arg = CONST_CAST_TREE (
2531 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2532 argtype = lvalue_type (arg);
2534 conversion *t;
2535 if (parmnode)
2537 tree parmtype = TREE_VALUE (parmnode);
2538 if (i == 0
2539 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2540 && !DECL_CONSTRUCTOR_P (fn))
2541 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2542 flags, complain);
2543 else
2545 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2546 t = implicit_conversion (parmtype, argtype, arg,
2547 /*c_cast_p=*/false, lflags, complain);
2549 to_type = parmtype;
2550 parmnode = TREE_CHAIN (parmnode);
2552 else
2554 t = build_identity_conv (argtype, arg);
2555 t->ellipsis_p = true;
2556 to_type = argtype;
2559 convs[i] = t;
2560 if (! t)
2562 viable = 0;
2563 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2564 EXPR_LOCATION (arg));
2565 break;
2568 if (t->bad_p)
2570 viable = -1;
2571 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2572 EXPR_LOCATION (arg));
2573 if (shortcut_bad_convs)
2574 break;
2578 out:
2579 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2580 access_path, conversion_path, viable, reason, flags);
2583 /* Create an overload candidate for the conversion function FN which will
2584 be invoked for expression OBJ, producing a pointer-to-function which
2585 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2586 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2587 passed on to implicit_conversion.
2589 Actually, we don't really care about FN; we care about the type it
2590 converts to. There may be multiple conversion functions that will
2591 convert to that type, and we rely on build_user_type_conversion_1 to
2592 choose the best one; so when we create our candidate, we record the type
2593 instead of the function. */
2595 static struct z_candidate *
2596 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2597 const vec<tree, va_gc> *arglist,
2598 tree access_path, tree conversion_path,
2599 tsubst_flags_t complain)
2601 tree totype = TREE_TYPE (TREE_TYPE (fn));
2602 int i, len, viable, flags;
2603 tree parmlist, parmnode;
2604 conversion **convs;
2605 struct rejection_reason *reason;
2607 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2608 parmlist = TREE_TYPE (parmlist);
2609 parmlist = TYPE_ARG_TYPES (parmlist);
2611 len = vec_safe_length (arglist) + 1;
2612 convs = alloc_conversions (len);
2613 parmnode = parmlist;
2614 viable = 1;
2615 flags = LOOKUP_IMPLICIT;
2616 reason = NULL;
2618 /* Don't bother looking up the same type twice. */
2619 if (*candidates && (*candidates)->fn == totype)
2620 return NULL;
2622 if (!constraints_satisfied_p (fn))
2624 reason = constraint_failure ();
2625 viable = 0;
2626 return add_candidate (candidates, fn, obj, arglist, len, convs,
2627 access_path, conversion_path, viable, reason, flags);
2630 for (i = 0; i < len; ++i)
2632 tree arg, argtype, convert_type = NULL_TREE;
2633 conversion *t;
2635 if (i == 0)
2636 arg = obj;
2637 else
2638 arg = (*arglist)[i - 1];
2639 argtype = lvalue_type (arg);
2641 if (i == 0)
2643 t = build_identity_conv (argtype, NULL_TREE);
2644 t = build_conv (ck_user, totype, t);
2645 /* Leave the 'cand' field null; we'll figure out the conversion in
2646 convert_like if this candidate is chosen. */
2647 convert_type = totype;
2649 else if (parmnode == void_list_node)
2650 break;
2651 else if (parmnode)
2653 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2654 /*c_cast_p=*/false, flags, complain);
2655 convert_type = TREE_VALUE (parmnode);
2657 else
2659 t = build_identity_conv (argtype, arg);
2660 t->ellipsis_p = true;
2661 convert_type = argtype;
2664 convs[i] = t;
2665 if (! t)
2666 break;
2668 if (t->bad_p)
2670 viable = -1;
2671 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2672 EXPR_LOCATION (arg));
2675 if (i == 0)
2676 continue;
2678 if (parmnode)
2679 parmnode = TREE_CHAIN (parmnode);
2682 if (i < len
2683 || ! sufficient_parms_p (parmnode))
2685 int remaining = remaining_arguments (parmnode);
2686 viable = 0;
2687 reason = arity_rejection (NULL_TREE, i + remaining, len);
2690 return add_candidate (candidates, totype, obj, arglist, len, convs,
2691 access_path, conversion_path, viable, reason, flags);
2694 static void
2695 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2696 tree type1, tree type2, const vec<tree,va_gc> &args,
2697 tree *argtypes, int flags, tsubst_flags_t complain)
2699 conversion *t;
2700 conversion **convs;
2701 size_t num_convs;
2702 int viable = 1;
2703 tree types[2];
2704 struct rejection_reason *reason = NULL;
2706 types[0] = type1;
2707 types[1] = type2;
2709 num_convs = args.length ();
2710 convs = alloc_conversions (num_convs);
2712 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2713 conversion ops are allowed. We handle that here by just checking for
2714 boolean_type_node because other operators don't ask for it. COND_EXPR
2715 also does contextual conversion to bool for the first operand, but we
2716 handle that in build_conditional_expr, and type1 here is operand 2. */
2717 if (type1 != boolean_type_node)
2718 flags |= LOOKUP_ONLYCONVERTING;
2720 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2722 t = implicit_conversion (types[i], argtypes[i], args[i],
2723 /*c_cast_p=*/false, flags, complain);
2724 if (! t)
2726 viable = 0;
2727 /* We need something for printing the candidate. */
2728 t = build_identity_conv (types[i], NULL_TREE);
2729 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2730 types[i], EXPR_LOCATION (args[i]));
2732 else if (t->bad_p)
2734 viable = 0;
2735 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2736 types[i],
2737 EXPR_LOCATION (args[i]));
2739 convs[i] = t;
2742 /* For COND_EXPR we rearranged the arguments; undo that now. */
2743 if (num_convs == 3)
2745 convs[2] = convs[1];
2746 convs[1] = convs[0];
2747 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2748 /*c_cast_p=*/false, flags,
2749 complain);
2750 if (t)
2751 convs[0] = t;
2752 else
2754 viable = 0;
2755 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2756 boolean_type_node,
2757 EXPR_LOCATION (args[2]));
2761 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2762 num_convs, convs,
2763 /*access_path=*/NULL_TREE,
2764 /*conversion_path=*/NULL_TREE,
2765 viable, reason, flags);
2768 static bool
2769 is_complete (tree t)
2771 return COMPLETE_TYPE_P (complete_type (t));
2774 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2776 static bool
2777 promoted_arithmetic_type_p (tree type)
2779 /* [over.built]
2781 In this section, the term promoted integral type is used to refer
2782 to those integral types which are preserved by integral promotion
2783 (including e.g. int and long but excluding e.g. char).
2784 Similarly, the term promoted arithmetic type refers to promoted
2785 integral types plus floating types. */
2786 return ((CP_INTEGRAL_TYPE_P (type)
2787 && same_type_p (type_promotes_to (type), type))
2788 || SCALAR_FLOAT_TYPE_P (type));
2791 /* Create any builtin operator overload candidates for the operator in
2792 question given the converted operand types TYPE1 and TYPE2. The other
2793 args are passed through from add_builtin_candidates to
2794 build_builtin_candidate.
2796 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2797 If CODE is requires candidates operands of the same type of the kind
2798 of which TYPE1 and TYPE2 are, we add both candidates
2799 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2801 static void
2802 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2803 enum tree_code code2, tree fnname, tree type1,
2804 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2805 int flags, tsubst_flags_t complain)
2807 switch (code)
2809 case POSTINCREMENT_EXPR:
2810 case POSTDECREMENT_EXPR:
2811 args[1] = integer_zero_node;
2812 type2 = integer_type_node;
2813 break;
2814 default:
2815 break;
2818 switch (code)
2821 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2822 and VQ is either volatile or empty, there exist candidate operator
2823 functions of the form
2824 VQ T& operator++(VQ T&);
2825 T operator++(VQ T&, int);
2826 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2827 and VQ is either volatile or empty, there exist candidate operator
2828 functions of the form
2829 VQ T& operator--(VQ T&);
2830 T operator--(VQ T&, int);
2831 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2832 type, and VQ is either volatile or empty, there exist candidate operator
2833 functions of the form
2834 T*VQ& operator++(T*VQ&);
2835 T*VQ& operator--(T*VQ&);
2836 T* operator++(T*VQ&, int);
2837 T* operator--(T*VQ&, int); */
2839 case POSTDECREMENT_EXPR:
2840 case PREDECREMENT_EXPR:
2841 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2842 return;
2843 /* FALLTHRU */
2844 case POSTINCREMENT_EXPR:
2845 case PREINCREMENT_EXPR:
2846 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2847 to p4. */
2848 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2849 return;
2850 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2852 type1 = build_reference_type (type1);
2853 break;
2855 return;
2857 /* 7 For every cv-qualified or cv-unqualified object type T, there
2858 exist candidate operator functions of the form
2860 T& operator*(T*);
2863 8 For every function type T that does not have cv-qualifiers or
2864 a ref-qualifier, there exist candidate operator functions of the form
2865 T& operator*(T*); */
2867 case INDIRECT_REF:
2868 if (TYPE_PTR_P (type1)
2869 && (TYPE_PTROB_P (type1)
2870 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2871 break;
2872 return;
2874 /* 9 For every type T, there exist candidate operator functions of the form
2875 T* operator+(T*);
2877 10 For every floating-point or promoted integral type T, there exist
2878 candidate operator functions of the form
2879 T operator+(T);
2880 T operator-(T); */
2882 case UNARY_PLUS_EXPR: /* unary + */
2883 if (TYPE_PTR_P (type1))
2884 break;
2885 /* FALLTHRU */
2886 case NEGATE_EXPR:
2887 if (ARITHMETIC_TYPE_P (type1))
2888 break;
2889 return;
2891 /* 11 For every promoted integral type T, there exist candidate operator
2892 functions of the form
2893 T operator~(T); */
2895 case BIT_NOT_EXPR:
2896 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2897 break;
2898 return;
2900 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2901 is the same type as C2 or is a derived class of C2, and T is an object
2902 type or a function type there exist candidate operator functions of the
2903 form
2904 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2905 where CV12 is the union of CV1 and CV2. */
2907 case MEMBER_REF:
2908 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2910 tree c1 = TREE_TYPE (type1);
2911 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2913 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2914 && (TYPE_PTRMEMFUNC_P (type2)
2915 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2916 break;
2918 return;
2920 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2921 or promoted integral type, there exist candidate operator functions of the
2922 form
2923 LR operator*(L, R);
2924 LR operator/(L, R);
2925 LR operator+(L, R);
2926 LR operator-(L, R);
2927 bool operator<(L, R);
2928 bool operator>(L, R);
2929 bool operator<=(L, R);
2930 bool operator>=(L, R);
2931 bool operator==(L, R);
2932 bool operator!=(L, R);
2933 where LR is the result of the usual arithmetic conversions between
2934 types L and R.
2936 14 For every integral type T there exists a candidate operator function of
2937 the form
2939 std::strong_ordering operator<=>(T, T);
2941 15 For every pair of floating-point types L and R, there exists a candidate
2942 operator function of the form
2944 std::partial_ordering operator<=>(L, R);
2946 16 For every cv-qualified or cv-unqualified object type T there exist
2947 candidate operator functions of the form
2948 T* operator+(T*, std::ptrdiff_t);
2949 T& operator[](T*, std::ptrdiff_t);
2950 T* operator-(T*, std::ptrdiff_t);
2951 T* operator+(std::ptrdiff_t, T*);
2952 T& operator[](std::ptrdiff_t, T*);
2954 17 For every T, where T is a pointer to object type, there exist candidate
2955 operator functions of the form
2956 std::ptrdiff_t operator-(T, T);
2958 18 For every T, where T is an enumeration type or a pointer type, there
2959 exist candidate operator functions of the form
2960 bool operator<(T, T);
2961 bool operator>(T, T);
2962 bool operator<=(T, T);
2963 bool operator>=(T, T);
2964 bool operator==(T, T);
2965 bool operator!=(T, T);
2966 R operator<=>(T, T);
2968 where R is the result type specified in [expr.spaceship].
2970 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2971 there exist candidate operator functions of the form
2972 bool operator==(T, T);
2973 bool operator!=(T, T); */
2975 case MINUS_EXPR:
2976 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2977 break;
2978 if (TYPE_PTROB_P (type1)
2979 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2981 type2 = ptrdiff_type_node;
2982 break;
2984 /* FALLTHRU */
2985 case MULT_EXPR:
2986 case TRUNC_DIV_EXPR:
2987 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2988 break;
2989 return;
2991 /* This isn't exactly what's specified above for operator<=>, but it's
2992 close enough. In particular, we don't care about the return type
2993 specified above; it doesn't participate in overload resolution and it
2994 doesn't affect the semantics of the built-in operator. */
2995 case SPACESHIP_EXPR:
2996 case EQ_EXPR:
2997 case NE_EXPR:
2998 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2999 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
3000 break;
3001 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
3002 break;
3003 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
3005 type2 = type1;
3006 break;
3008 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
3010 type1 = type2;
3011 break;
3013 /* Fall through. */
3014 case LT_EXPR:
3015 case GT_EXPR:
3016 case LE_EXPR:
3017 case GE_EXPR:
3018 case MAX_EXPR:
3019 case MIN_EXPR:
3020 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3021 break;
3022 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3023 break;
3024 if (TREE_CODE (type1) == ENUMERAL_TYPE
3025 && TREE_CODE (type2) == ENUMERAL_TYPE)
3026 break;
3027 if (TYPE_PTR_P (type1)
3028 && null_ptr_cst_p (args[1]))
3030 type2 = type1;
3031 break;
3033 if (null_ptr_cst_p (args[0])
3034 && TYPE_PTR_P (type2))
3036 type1 = type2;
3037 break;
3039 return;
3041 case PLUS_EXPR:
3042 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3043 break;
3044 /* FALLTHRU */
3045 case ARRAY_REF:
3046 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3048 type1 = ptrdiff_type_node;
3049 break;
3051 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3053 type2 = ptrdiff_type_node;
3054 break;
3056 return;
3058 /* 18For every pair of promoted integral types L and R, there exist candi-
3059 date operator functions of the form
3060 LR operator%(L, R);
3061 LR operator&(L, R);
3062 LR operator^(L, R);
3063 LR operator|(L, R);
3064 L operator<<(L, R);
3065 L operator>>(L, R);
3066 where LR is the result of the usual arithmetic conversions between
3067 types L and R. */
3069 case TRUNC_MOD_EXPR:
3070 case BIT_AND_EXPR:
3071 case BIT_IOR_EXPR:
3072 case BIT_XOR_EXPR:
3073 case LSHIFT_EXPR:
3074 case RSHIFT_EXPR:
3075 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3076 break;
3077 return;
3079 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3080 type, VQ is either volatile or empty, and R is a promoted arithmetic
3081 type, there exist candidate operator functions of the form
3082 VQ L& operator=(VQ L&, R);
3083 VQ L& operator*=(VQ L&, R);
3084 VQ L& operator/=(VQ L&, R);
3085 VQ L& operator+=(VQ L&, R);
3086 VQ L& operator-=(VQ L&, R);
3088 20For every pair T, VQ), where T is any type and VQ is either volatile
3089 or empty, there exist candidate operator functions of the form
3090 T*VQ& operator=(T*VQ&, T*);
3092 21For every pair T, VQ), where T is a pointer to member type and VQ is
3093 either volatile or empty, there exist candidate operator functions of
3094 the form
3095 VQ T& operator=(VQ T&, T);
3097 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3098 unqualified complete object type, VQ is either volatile or empty, and
3099 I is a promoted integral type, there exist candidate operator func-
3100 tions of the form
3101 T*VQ& operator+=(T*VQ&, I);
3102 T*VQ& operator-=(T*VQ&, I);
3104 23For every triple L, VQ, R), where L is an integral or enumeration
3105 type, VQ is either volatile or empty, and R is a promoted integral
3106 type, there exist candidate operator functions of the form
3108 VQ L& operator%=(VQ L&, R);
3109 VQ L& operator<<=(VQ L&, R);
3110 VQ L& operator>>=(VQ L&, R);
3111 VQ L& operator&=(VQ L&, R);
3112 VQ L& operator^=(VQ L&, R);
3113 VQ L& operator|=(VQ L&, R); */
3115 case MODIFY_EXPR:
3116 switch (code2)
3118 case PLUS_EXPR:
3119 case MINUS_EXPR:
3120 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3122 type2 = ptrdiff_type_node;
3123 break;
3125 /* FALLTHRU */
3126 case MULT_EXPR:
3127 case TRUNC_DIV_EXPR:
3128 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3129 break;
3130 return;
3132 case TRUNC_MOD_EXPR:
3133 case BIT_AND_EXPR:
3134 case BIT_IOR_EXPR:
3135 case BIT_XOR_EXPR:
3136 case LSHIFT_EXPR:
3137 case RSHIFT_EXPR:
3138 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3139 break;
3140 return;
3142 case NOP_EXPR:
3143 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3144 break;
3145 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3146 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3147 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3148 || ((TYPE_PTRMEMFUNC_P (type1)
3149 || TYPE_PTR_P (type1))
3150 && null_ptr_cst_p (args[1])))
3152 type2 = type1;
3153 break;
3155 return;
3157 default:
3158 gcc_unreachable ();
3160 type1 = build_reference_type (type1);
3161 break;
3163 case COND_EXPR:
3164 /* [over.built]
3166 For every pair of promoted arithmetic types L and R, there
3167 exist candidate operator functions of the form
3169 LR operator?(bool, L, R);
3171 where LR is the result of the usual arithmetic conversions
3172 between types L and R.
3174 For every type T, where T is a pointer or pointer-to-member
3175 type, there exist candidate operator functions of the form T
3176 operator?(bool, T, T); */
3178 if (promoted_arithmetic_type_p (type1)
3179 && promoted_arithmetic_type_p (type2))
3180 /* That's OK. */
3181 break;
3183 /* Otherwise, the types should be pointers. */
3184 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3185 return;
3187 /* We don't check that the two types are the same; the logic
3188 below will actually create two candidates; one in which both
3189 parameter types are TYPE1, and one in which both parameter
3190 types are TYPE2. */
3191 break;
3193 case REALPART_EXPR:
3194 case IMAGPART_EXPR:
3195 if (ARITHMETIC_TYPE_P (type1))
3196 break;
3197 return;
3199 default:
3200 gcc_unreachable ();
3203 /* Make sure we don't create builtin candidates with dependent types. */
3204 bool u1 = uses_template_parms (type1);
3205 bool u2 = type2 ? uses_template_parms (type2) : false;
3206 if (u1 || u2)
3208 /* Try to recover if one of the types is non-dependent. But if
3209 there's only one type, there's nothing we can do. */
3210 if (!type2)
3211 return;
3212 /* And we lose if both are dependent. */
3213 if (u1 && u2)
3214 return;
3215 /* Or if they have different forms. */
3216 if (TREE_CODE (type1) != TREE_CODE (type2))
3217 return;
3219 if (u1 && !u2)
3220 type1 = type2;
3221 else if (u2 && !u1)
3222 type2 = type1;
3225 /* If we're dealing with two pointer types or two enumeral types,
3226 we need candidates for both of them. */
3227 if (type2 && !same_type_p (type1, type2)
3228 && TREE_CODE (type1) == TREE_CODE (type2)
3229 && (TYPE_REF_P (type1)
3230 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3231 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3232 || TYPE_PTRMEMFUNC_P (type1)
3233 || MAYBE_CLASS_TYPE_P (type1)
3234 || TREE_CODE (type1) == ENUMERAL_TYPE))
3236 if (TYPE_PTR_OR_PTRMEM_P (type1))
3238 tree cptype = composite_pointer_type (input_location,
3239 type1, type2,
3240 error_mark_node,
3241 error_mark_node,
3242 CPO_CONVERSION,
3243 tf_none);
3244 if (cptype != error_mark_node)
3246 build_builtin_candidate
3247 (candidates, fnname, cptype, cptype, args, argtypes,
3248 flags, complain);
3249 return;
3253 build_builtin_candidate
3254 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3255 build_builtin_candidate
3256 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3257 return;
3260 build_builtin_candidate
3261 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3264 tree
3265 type_decays_to (tree type)
3267 if (TREE_CODE (type) == ARRAY_TYPE)
3268 return build_pointer_type (TREE_TYPE (type));
3269 if (TREE_CODE (type) == FUNCTION_TYPE)
3270 return build_pointer_type (type);
3271 return type;
3274 /* There are three conditions of builtin candidates:
3276 1) bool-taking candidates. These are the same regardless of the input.
3277 2) pointer-pair taking candidates. These are generated for each type
3278 one of the input types converts to.
3279 3) arithmetic candidates. According to the standard, we should generate
3280 all of these, but I'm trying not to...
3282 Here we generate a superset of the possible candidates for this particular
3283 case. That is a subset of the full set the standard defines, plus some
3284 other cases which the standard disallows. add_builtin_candidate will
3285 filter out the invalid set. */
3287 static void
3288 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3289 enum tree_code code2, tree fnname,
3290 vec<tree, va_gc> *argv,
3291 int flags, tsubst_flags_t complain)
3293 int ref1;
3294 int enum_p = 0;
3295 tree type, argtypes[3], t;
3296 /* TYPES[i] is the set of possible builtin-operator parameter types
3297 we will consider for the Ith argument. */
3298 vec<tree, va_gc> *types[2];
3299 unsigned ix;
3300 vec<tree, va_gc> &args = *argv;
3301 unsigned len = args.length ();
3303 for (unsigned i = 0; i < len; ++i)
3305 if (args[i])
3306 argtypes[i] = unlowered_expr_type (args[i]);
3307 else
3308 argtypes[i] = NULL_TREE;
3311 switch (code)
3313 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3314 and VQ is either volatile or empty, there exist candidate operator
3315 functions of the form
3316 VQ T& operator++(VQ T&); */
3318 case POSTINCREMENT_EXPR:
3319 case PREINCREMENT_EXPR:
3320 case POSTDECREMENT_EXPR:
3321 case PREDECREMENT_EXPR:
3322 case MODIFY_EXPR:
3323 ref1 = 1;
3324 break;
3326 /* 24There also exist candidate operator functions of the form
3327 bool operator!(bool);
3328 bool operator&&(bool, bool);
3329 bool operator||(bool, bool); */
3331 case TRUTH_NOT_EXPR:
3332 build_builtin_candidate
3333 (candidates, fnname, boolean_type_node,
3334 NULL_TREE, args, argtypes, flags, complain);
3335 return;
3337 case TRUTH_ORIF_EXPR:
3338 case TRUTH_ANDIF_EXPR:
3339 build_builtin_candidate
3340 (candidates, fnname, boolean_type_node,
3341 boolean_type_node, args, argtypes, flags, complain);
3342 return;
3344 case ADDR_EXPR:
3345 case COMPOUND_EXPR:
3346 case COMPONENT_REF:
3347 case CO_AWAIT_EXPR:
3348 return;
3350 case COND_EXPR:
3351 case EQ_EXPR:
3352 case NE_EXPR:
3353 case LT_EXPR:
3354 case LE_EXPR:
3355 case GT_EXPR:
3356 case GE_EXPR:
3357 case SPACESHIP_EXPR:
3358 enum_p = 1;
3359 /* Fall through. */
3361 default:
3362 ref1 = 0;
3365 types[0] = make_tree_vector ();
3366 types[1] = make_tree_vector ();
3368 if (len == 3)
3369 len = 2;
3370 for (unsigned i = 0; i < len; ++i)
3372 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3374 tree convs;
3376 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3377 return;
3379 convs = lookup_conversions (argtypes[i]);
3381 if (code == COND_EXPR)
3383 if (lvalue_p (args[i]))
3384 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3386 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3389 else if (! convs)
3390 return;
3392 for (; convs; convs = TREE_CHAIN (convs))
3394 type = TREE_TYPE (convs);
3396 if (i == 0 && ref1
3397 && (!TYPE_REF_P (type)
3398 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3399 continue;
3401 if (code == COND_EXPR && TYPE_REF_P (type))
3402 vec_safe_push (types[i], type);
3404 type = non_reference (type);
3405 if (i != 0 || ! ref1)
3407 type = cv_unqualified (type_decays_to (type));
3408 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3409 vec_safe_push (types[i], type);
3410 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3411 type = type_promotes_to (type);
3414 if (! vec_member (type, types[i]))
3415 vec_safe_push (types[i], type);
3418 else
3420 if (code == COND_EXPR && lvalue_p (args[i]))
3421 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3422 type = non_reference (argtypes[i]);
3423 if (i != 0 || ! ref1)
3425 type = cv_unqualified (type_decays_to (type));
3426 if (enum_p && UNSCOPED_ENUM_P (type))
3427 vec_safe_push (types[i], type);
3428 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3429 type = type_promotes_to (type);
3431 vec_safe_push (types[i], type);
3435 /* Run through the possible parameter types of both arguments,
3436 creating candidates with those parameter types. */
3437 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3439 unsigned jx;
3440 tree u;
3442 if (!types[1]->is_empty ())
3443 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3444 add_builtin_candidate
3445 (candidates, code, code2, fnname, t,
3446 u, args, argtypes, flags, complain);
3447 else
3448 add_builtin_candidate
3449 (candidates, code, code2, fnname, t,
3450 NULL_TREE, args, argtypes, flags, complain);
3453 release_tree_vector (types[0]);
3454 release_tree_vector (types[1]);
3458 /* If TMPL can be successfully instantiated as indicated by
3459 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3461 TMPL is the template. EXPLICIT_TARGS are any explicit template
3462 arguments. ARGLIST is the arguments provided at the call-site.
3463 This does not change ARGLIST. The RETURN_TYPE is the desired type
3464 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3465 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3466 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3468 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3470 static struct z_candidate*
3471 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3472 tree ctype, tree explicit_targs, tree first_arg,
3473 const vec<tree, va_gc> *arglist, tree return_type,
3474 tree access_path, tree conversion_path,
3475 int flags, tree obj, unification_kind_t strict,
3476 bool shortcut_bad_convs, tsubst_flags_t complain)
3478 int ntparms = DECL_NTPARMS (tmpl);
3479 tree targs = make_tree_vec (ntparms);
3480 unsigned int len = vec_safe_length (arglist);
3481 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3482 unsigned int skip_without_in_chrg = 0;
3483 tree first_arg_without_in_chrg = first_arg;
3484 tree *args_without_in_chrg;
3485 unsigned int nargs_without_in_chrg;
3486 unsigned int ia, ix;
3487 tree arg;
3488 struct z_candidate *cand;
3489 tree fn;
3490 struct rejection_reason *reason = NULL;
3491 int errs;
3492 conversion **convs = NULL;
3494 /* We don't do deduction on the in-charge parameter, the VTT
3495 parameter or 'this'. */
3496 if (DECL_IOBJ_MEMBER_FUNCTION_P (tmpl))
3498 if (first_arg_without_in_chrg != NULL_TREE)
3499 first_arg_without_in_chrg = NULL_TREE;
3500 else if (return_type && strict == DEDUCE_CALL)
3501 /* We're deducing for a call to the result of a template conversion
3502 function, so the args don't contain 'this'; leave them alone. */;
3503 else
3504 ++skip_without_in_chrg;
3507 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3508 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3509 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3511 if (first_arg_without_in_chrg != NULL_TREE)
3512 first_arg_without_in_chrg = NULL_TREE;
3513 else
3514 ++skip_without_in_chrg;
3517 if (len < skip_without_in_chrg)
3518 return add_ignored_candidate (candidates, tmpl);
3520 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3521 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3522 TREE_TYPE ((*arglist)[0])))
3524 /* 12.8/6 says, "A declaration of a constructor for a class X is
3525 ill-formed if its first parameter is of type (optionally cv-qualified)
3526 X and either there are no other parameters or else all other
3527 parameters have default arguments. A member function template is never
3528 instantiated to produce such a constructor signature."
3530 So if we're trying to copy an object of the containing class, don't
3531 consider a template constructor that has a first parameter type that
3532 is just a template parameter, as we would deduce a signature that we
3533 would then reject in the code below. */
3534 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3536 firstparm = TREE_VALUE (firstparm);
3537 if (PACK_EXPANSION_P (firstparm))
3538 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3539 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3541 gcc_assert (!explicit_targs);
3542 reason = invalid_copy_with_fn_template_rejection ();
3543 goto fail;
3548 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3549 + (len - skip_without_in_chrg));
3550 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3551 ia = 0;
3552 if (first_arg_without_in_chrg != NULL_TREE)
3554 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3555 ++ia;
3557 for (ix = skip_without_in_chrg;
3558 vec_safe_iterate (arglist, ix, &arg);
3559 ++ix)
3561 args_without_in_chrg[ia] = arg;
3562 ++ia;
3564 gcc_assert (ia == nargs_without_in_chrg);
3566 if (!obj)
3568 /* Check that there's no obvious arity mismatch before proceeding with
3569 deduction. This avoids substituting explicit template arguments
3570 into the template or e.g. derived-to-base parm/arg unification
3571 (which could result in an error outside the immediate context) when
3572 the resulting candidate would be unviable anyway. */
3573 int min_arity = 0, max_arity = 0;
3574 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3575 parms = skip_artificial_parms_for (tmpl, parms);
3576 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3578 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3580 max_arity = -1;
3581 break;
3583 if (TREE_PURPOSE (parms))
3584 /* A parameter with a default argument. */
3585 ++max_arity;
3586 else
3587 ++min_arity, ++max_arity;
3589 if (ia < (unsigned)min_arity)
3591 /* Too few arguments. */
3592 reason = arity_rejection (NULL_TREE, min_arity, ia,
3593 /*least_p=*/(max_arity == -1));
3594 goto fail;
3596 else if (max_arity != -1 && ia > (unsigned)max_arity)
3598 /* Too many arguments. */
3599 reason = arity_rejection (NULL_TREE, max_arity, ia);
3600 goto fail;
3603 convs = alloc_conversions (nargs);
3605 if (shortcut_bad_convs
3606 && DECL_IOBJ_MEMBER_FUNCTION_P (tmpl)
3607 && !DECL_CONSTRUCTOR_P (tmpl))
3609 /* Check the 'this' conversion before proceeding with deduction.
3610 This is effectively an extension of the DR 1391 resolution
3611 that we perform in check_non_deducible_conversions, though it's
3612 convenient to do this extra check here instead of there. */
3613 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3614 tree argtype = lvalue_type (first_arg);
3615 tree arg = first_arg;
3616 conversion *t = build_this_conversion (tmpl, ctype,
3617 parmtype, argtype, arg,
3618 flags, complain);
3619 convs[0] = t;
3620 if (t->bad_p)
3622 reason = bad_arg_conversion_rejection (first_arg, 0,
3623 arg, parmtype,
3624 EXPR_LOCATION (arg));
3625 goto fail;
3630 errs = errorcount+sorrycount;
3631 fn = fn_type_unification (tmpl, explicit_targs, targs,
3632 args_without_in_chrg,
3633 nargs_without_in_chrg,
3634 return_type, strict, flags, convs,
3635 false, complain & tf_decltype);
3637 if (fn == error_mark_node)
3639 /* Don't repeat unification later if it already resulted in errors. */
3640 if (errorcount+sorrycount == errs)
3641 reason = template_unification_rejection (tmpl, explicit_targs,
3642 targs, args_without_in_chrg,
3643 nargs_without_in_chrg,
3644 return_type, strict, flags);
3645 else
3646 reason = template_unification_error_rejection ();
3647 goto fail;
3650 /* Now the explicit specifier might have been deduced; check if this
3651 declaration is explicit. If it is and we're ignoring non-converting
3652 constructors, don't add this function to the set of candidates. */
3653 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3654 == LOOKUP_ONLYCONVERTING)
3655 && DECL_NONCONVERTING_P (fn))
3656 return add_ignored_candidate (candidates, fn);
3658 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3660 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3661 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3662 ctype))
3664 /* We're trying to produce a constructor with a prohibited signature,
3665 as discussed above; handle here any cases we didn't catch then,
3666 such as X(X<T>). */
3667 reason = invalid_copy_with_fn_template_rejection ();
3668 goto fail;
3672 if (obj != NULL_TREE)
3673 /* Aha, this is a conversion function. */
3674 cand = add_conv_candidate (candidates, fn, obj, arglist,
3675 access_path, conversion_path, complain);
3676 else
3677 cand = add_function_candidate (candidates, fn, ctype,
3678 first_arg, arglist, access_path,
3679 conversion_path, flags, convs,
3680 shortcut_bad_convs, complain);
3681 if (DECL_TI_TEMPLATE (fn) != tmpl)
3682 /* This situation can occur if a member template of a template
3683 class is specialized. Then, instantiate_template might return
3684 an instantiation of the specialization, in which case the
3685 DECL_TI_TEMPLATE field will point at the original
3686 specialization. For example:
3688 template <class T> struct S { template <class U> void f(U);
3689 template <> void f(int) {}; };
3690 S<double> sd;
3691 sd.f(3);
3693 Here, TMPL will be template <class U> S<double>::f(U).
3694 And, instantiate template will give us the specialization
3695 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3696 for this will point at template <class T> template <> S<T>::f(int),
3697 so that we can find the definition. For the purposes of
3698 overload resolution, however, we want the original TMPL. */
3699 cand->template_decl = build_template_info (tmpl, targs);
3700 else
3701 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3702 cand->explicit_targs = explicit_targs;
3704 return cand;
3705 fail:
3706 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3707 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3708 access_path, conversion_path, viable, reason, flags);
3712 static struct z_candidate *
3713 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3714 tree explicit_targs, tree first_arg,
3715 const vec<tree, va_gc> *arglist, tree return_type,
3716 tree access_path, tree conversion_path, int flags,
3717 unification_kind_t strict, bool shortcut_bad_convs,
3718 tsubst_flags_t complain)
3720 return
3721 add_template_candidate_real (candidates, tmpl, ctype,
3722 explicit_targs, first_arg, arglist,
3723 return_type, access_path, conversion_path,
3724 flags, NULL_TREE, strict, shortcut_bad_convs,
3725 complain);
3728 /* Create an overload candidate for the conversion function template TMPL,
3729 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3730 pointer-to-function which will in turn be called with the argument list
3731 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3732 passed on to implicit_conversion. */
3734 static struct z_candidate *
3735 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3736 tree obj,
3737 const vec<tree, va_gc> *arglist,
3738 tree return_type, tree access_path,
3739 tree conversion_path, tsubst_flags_t complain)
3741 return
3742 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3743 NULL_TREE, arglist, return_type, access_path,
3744 conversion_path, 0, obj, DEDUCE_CALL,
3745 /*shortcut_bad_convs=*/false, complain);
3748 /* The CANDS are the set of candidates that were considered for
3749 overload resolution. Sort CANDS so that the strictly viable
3750 candidates appear first, followed by non-strictly viable candidates,
3751 followed by non-viable candidates. Returns the first candidate
3752 in this sorted list. If any of the candidates were viable, set
3753 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3754 considered viable only if it is strictly viable when setting
3755 *ANY_VIABLE_P. */
3757 static struct z_candidate*
3758 splice_viable (struct z_candidate *cands,
3759 bool strict_p,
3760 bool *any_viable_p)
3762 z_candidate *strictly_viable = nullptr;
3763 z_candidate **strictly_viable_tail = &strictly_viable;
3765 z_candidate *non_strictly_viable = nullptr;
3766 z_candidate **non_strictly_viable_tail = &non_strictly_viable;
3768 z_candidate *non_viable = nullptr;
3769 z_candidate **non_viable_tail = &non_viable;
3771 z_candidate *non_viable_ignored = nullptr;
3772 z_candidate **non_viable_ignored_tail = &non_viable_ignored;
3774 /* Be strict inside templates, since build_over_call won't actually
3775 do the conversions to get pedwarns. */
3776 if (processing_template_decl)
3777 strict_p = true;
3779 for (z_candidate *cand = cands; cand; cand = cand->next)
3781 if (!strict_p
3782 && (cand->viable == 1 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
3783 /* Be strict in the presence of a viable candidate. Also if
3784 there are template candidates, so that we get deduction errors
3785 for them instead of silently preferring a bad conversion. */
3786 strict_p = true;
3788 /* Move this candidate to the appropriate list according to
3789 its viability. */
3790 auto& tail = (cand->viable == 1 ? strictly_viable_tail
3791 : cand->viable == -1 ? non_strictly_viable_tail
3792 : ignored_candidate_p (cand) ? non_viable_ignored_tail
3793 : non_viable_tail);
3794 *tail = cand;
3795 tail = &cand->next;
3798 *any_viable_p = (strictly_viable != nullptr
3799 || (!strict_p && non_strictly_viable != nullptr));
3801 /* Combine the lists. */
3802 *non_viable_ignored_tail = nullptr;
3803 *non_viable_tail = non_viable_ignored;
3804 *non_strictly_viable_tail = non_viable;
3805 *strictly_viable_tail = non_strictly_viable;
3807 return strictly_viable;
3810 static bool
3811 any_strictly_viable (struct z_candidate *cands)
3813 for (; cands; cands = cands->next)
3814 if (cands->viable == 1)
3815 return true;
3816 return false;
3819 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3820 words, it is about to become the "this" pointer for a member
3821 function call. Take the address of the object. */
3823 static tree
3824 build_this (tree obj)
3826 /* In a template, we are only concerned about the type of the
3827 expression, so we can take a shortcut. */
3828 if (processing_template_decl)
3829 return build_address (obj);
3831 return cp_build_addr_expr (obj, tf_warning_or_error);
3834 /* Returns true iff functions are equivalent. Equivalent functions are
3835 not '==' only if one is a function-local extern function or if
3836 both are extern "C". */
3838 static inline int
3839 equal_functions (tree fn1, tree fn2)
3841 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3842 return 0;
3843 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3844 return fn1 == fn2;
3845 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3846 || DECL_EXTERN_C_FUNCTION_P (fn1))
3847 return decls_match (fn1, fn2);
3848 return fn1 == fn2;
3851 /* Print information about a candidate FN being rejected due to INFO. */
3853 static void
3854 print_conversion_rejection (location_t loc, struct conversion_info *info,
3855 tree fn)
3857 tree from = info->from;
3858 if (!TYPE_P (from))
3859 from = lvalue_type (from);
3860 if (info->n_arg == -1)
3862 /* Conversion of implicit `this' argument failed. */
3863 if (!TYPE_P (info->from))
3864 /* A bad conversion for 'this' must be discarding cv-quals. */
3865 inform (loc, " passing %qT as %<this%> "
3866 "argument discards qualifiers",
3867 from);
3868 else
3869 inform (loc, " no known conversion for implicit "
3870 "%<this%> parameter from %qH to %qI",
3871 from, info->to_type);
3873 else if (!TYPE_P (info->from))
3875 if (info->n_arg >= 0)
3876 inform (loc, " conversion of argument %d would be ill-formed:",
3877 info->n_arg + 1);
3878 iloc_sentinel ils = loc;
3879 perform_implicit_conversion (info->to_type, info->from,
3880 tf_warning_or_error);
3882 else if (info->n_arg == -2)
3883 /* Conversion of conversion function return value failed. */
3884 inform (loc, " no known conversion from %qH to %qI",
3885 from, info->to_type);
3886 else
3888 if (TREE_CODE (fn) == FUNCTION_DECL)
3889 loc = get_fndecl_argument_location (fn, info->n_arg);
3890 inform (loc, " no known conversion for argument %d from %qH to %qI",
3891 info->n_arg + 1, from, info->to_type);
3895 /* Print information about a candidate with WANT parameters and we found
3896 HAVE. */
3898 static void
3899 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3900 bool least_p)
3902 if (least_p)
3903 inform_n (loc, want,
3904 " candidate expects at least %d argument, %d provided",
3905 " candidate expects at least %d arguments, %d provided",
3906 want, have);
3907 else
3908 inform_n (loc, want,
3909 " candidate expects %d argument, %d provided",
3910 " candidate expects %d arguments, %d provided",
3911 want, have);
3914 /* Print information about one overload candidate CANDIDATE. MSGSTR
3915 is the text to print before the candidate itself.
3917 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3918 to have been run through gettext by the caller. This wart makes
3919 life simpler in print_z_candidates and for the translators. */
3921 static void
3922 print_z_candidate (location_t loc, const char *msgstr,
3923 struct z_candidate *candidate)
3925 const char *msg = (msgstr == NULL
3926 ? ""
3927 : ACONCAT ((_(msgstr), " ", NULL)));
3928 tree fn = candidate->fn;
3929 if (flag_new_inheriting_ctors)
3930 fn = strip_inheriting_ctors (fn);
3931 location_t cloc = location_of (fn);
3933 if (identifier_p (fn))
3935 cloc = loc;
3936 if (candidate->num_convs == 3)
3937 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3938 candidate->convs[0]->type,
3939 candidate->convs[1]->type,
3940 candidate->convs[2]->type);
3941 else if (candidate->num_convs == 2)
3942 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3943 candidate->convs[0]->type,
3944 candidate->convs[1]->type);
3945 else
3946 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3947 candidate->convs[0]->type);
3949 else if (TYPE_P (fn))
3950 inform (cloc, "%s%qT (conversion)", msg, fn);
3951 else if (candidate->viable == -1)
3952 inform (cloc, "%s%#qD (near match)", msg, fn);
3953 else if (ignored_candidate_p (candidate))
3954 inform (cloc, "%s%#qD (ignored)", msg, fn);
3955 else if (DECL_DELETED_FN (fn))
3956 inform (cloc, "%s%#qD (deleted)", msg, fn);
3957 else if (candidate->reversed ())
3958 inform (cloc, "%s%#qD (reversed)", msg, fn);
3959 else if (candidate->rewritten ())
3960 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3961 else
3962 inform (cloc, "%s%#qD", msg, fn);
3963 if (fn != candidate->fn)
3965 cloc = location_of (candidate->fn);
3966 inform (cloc, " inherited here");
3968 /* Give the user some information about why this candidate failed. */
3969 if (candidate->reason != NULL)
3971 struct rejection_reason *r = candidate->reason;
3973 switch (r->code)
3975 case rr_arity:
3976 print_arity_information (cloc, r->u.arity.actual,
3977 r->u.arity.expected,
3978 r->u.arity.least_p);
3979 break;
3980 case rr_arg_conversion:
3981 print_conversion_rejection (cloc, &r->u.conversion, fn);
3982 break;
3983 case rr_bad_arg_conversion:
3984 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3985 break;
3986 case rr_explicit_conversion:
3987 inform (cloc, " return type %qT of explicit conversion function "
3988 "cannot be converted to %qT with a qualification "
3989 "conversion", r->u.conversion.from,
3990 r->u.conversion.to_type);
3991 break;
3992 case rr_template_conversion:
3993 inform (cloc, " conversion from return type %qT of template "
3994 "conversion function specialization to %qT is not an "
3995 "exact match", r->u.conversion.from,
3996 r->u.conversion.to_type);
3997 break;
3998 case rr_template_unification:
3999 /* We use template_unification_error_rejection if unification caused
4000 actual non-SFINAE errors, in which case we don't need to repeat
4001 them here. */
4002 if (r->u.template_unification.tmpl == NULL_TREE)
4004 inform (cloc, " substitution of deduced template arguments "
4005 "resulted in errors seen above");
4006 break;
4008 /* Re-run template unification with diagnostics. */
4009 inform (cloc, " template argument deduction/substitution failed:");
4010 fn_type_unification (r->u.template_unification.tmpl,
4011 r->u.template_unification.explicit_targs,
4012 (make_tree_vec
4013 (r->u.template_unification.num_targs)),
4014 r->u.template_unification.args,
4015 r->u.template_unification.nargs,
4016 r->u.template_unification.return_type,
4017 r->u.template_unification.strict,
4018 r->u.template_unification.flags,
4019 NULL, true, false);
4020 break;
4021 case rr_invalid_copy:
4022 inform (cloc,
4023 " a constructor taking a single argument of its own "
4024 "class type is invalid");
4025 break;
4026 case rr_constraint_failure:
4027 diagnose_constraints (cloc, fn, NULL_TREE);
4028 break;
4029 case rr_inherited_ctor:
4030 inform (cloc, " an inherited constructor is not a candidate for "
4031 "initialization from an expression of the same or derived "
4032 "type");
4033 break;
4034 case rr_ignored:
4035 break;
4036 case rr_none:
4037 default:
4038 /* This candidate didn't have any issues or we failed to
4039 handle a particular code. Either way... */
4040 gcc_unreachable ();
4045 /* Print information about each overload candidate in CANDIDATES,
4046 which is assumed to have gone through splice_viable and tourney
4047 (if splice_viable succeeded). */
4049 static void
4050 print_z_candidates (location_t loc, struct z_candidate *candidates,
4051 tristate only_viable_p /* = tristate::unknown () */)
4053 struct z_candidate *cand1;
4054 struct z_candidate **cand2;
4056 if (!candidates)
4057 return;
4059 /* Remove non-viable deleted candidates. */
4060 cand1 = candidates;
4061 for (cand2 = &cand1; *cand2; )
4063 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4064 && !(*cand2)->viable
4065 && DECL_DELETED_FN ((*cand2)->fn))
4066 *cand2 = (*cand2)->next;
4067 else
4068 cand2 = &(*cand2)->next;
4070 /* ...if there are any non-deleted ones. */
4071 if (cand1)
4072 candidates = cand1;
4074 /* There may be duplicates in the set of candidates. We put off
4075 checking this condition as long as possible, since we have no way
4076 to eliminate duplicates from a set of functions in less than n^2
4077 time. Now we are about to emit an error message, so it is more
4078 permissible to go slowly. */
4079 for (cand1 = candidates; cand1; cand1 = cand1->next)
4081 tree fn = cand1->fn;
4082 /* Skip builtin candidates and conversion functions. */
4083 if (!DECL_P (fn))
4084 continue;
4085 cand2 = &cand1->next;
4086 while (*cand2)
4088 if (DECL_P ((*cand2)->fn)
4089 && equal_functions (fn, (*cand2)->fn))
4090 *cand2 = (*cand2)->next;
4091 else
4092 cand2 = &(*cand2)->next;
4096 /* Unless otherwise specified, if there's a (strictly) viable candidate
4097 then we assume we're being called as part of diagnosing ambiguity, in
4098 which case we want to print only viable candidates since non-viable
4099 candidates couldn't have contributed to the ambiguity. */
4100 if (only_viable_p.is_unknown ())
4101 only_viable_p = candidates->viable == 1;
4103 for (; candidates; candidates = candidates->next)
4105 if (only_viable_p.is_true () && candidates->viable != 1)
4106 break;
4107 if (ignored_candidate_p (candidates) && !flag_diagnostics_all_candidates)
4109 inform (loc, "some candidates omitted; "
4110 "use %<-fdiagnostics-all-candidates%> to display them");
4111 break;
4113 print_z_candidate (loc, N_("candidate:"), candidates);
4117 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4118 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4119 the result of the conversion function to convert it to the final
4120 desired type. Merge the two sequences into a single sequence,
4121 and return the merged sequence. */
4123 static conversion *
4124 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4126 conversion **t;
4127 bool bad = user_seq->bad_p;
4129 gcc_assert (user_seq->kind == ck_user);
4131 /* Find the end of the second conversion sequence. */
4132 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4134 /* The entire sequence is a user-conversion sequence. */
4135 (*t)->user_conv_p = true;
4136 if (bad)
4137 (*t)->bad_p = true;
4140 if ((*t)->rvaluedness_matches_p)
4141 /* We're binding a reference directly to the result of the conversion.
4142 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4143 type, but we want it back. */
4144 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4146 /* Replace the identity conversion with the user conversion
4147 sequence. */
4148 *t = user_seq;
4150 return std_seq;
4153 /* Handle overload resolution for initializing an object of class type from
4154 an initializer list. First we look for a suitable constructor that
4155 takes a std::initializer_list; if we don't find one, we then look for a
4156 non-list constructor.
4158 Parameters are as for add_candidates, except that the arguments are in
4159 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4160 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4162 static void
4163 add_list_candidates (tree fns, tree first_arg,
4164 const vec<tree, va_gc> *args, tree totype,
4165 tree explicit_targs, bool template_only,
4166 tree conversion_path, tree access_path,
4167 int flags,
4168 struct z_candidate **candidates,
4169 tsubst_flags_t complain)
4171 gcc_assert (*candidates == NULL);
4173 /* We're looking for a ctor for list-initialization. */
4174 flags |= LOOKUP_LIST_INIT_CTOR;
4175 /* And we don't allow narrowing conversions. We also use this flag to
4176 avoid the copy constructor call for copy-list-initialization. */
4177 flags |= LOOKUP_NO_NARROWING;
4179 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4180 tree init_list = (*args)[nart];
4182 /* Always use the default constructor if the list is empty (DR 990). */
4183 if (CONSTRUCTOR_NELTS (init_list) == 0
4184 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4186 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4187 && !CP_AGGREGATE_TYPE_P (totype))
4189 if (complain & tf_error)
4190 error ("designated initializers cannot be used with a "
4191 "non-aggregate type %qT", totype);
4192 return;
4194 /* If the class has a list ctor, try passing the list as a single
4195 argument first, but only consider list ctors. */
4196 else if (TYPE_HAS_LIST_CTOR (totype))
4198 flags |= LOOKUP_LIST_ONLY;
4199 add_candidates (fns, first_arg, args, NULL_TREE,
4200 explicit_targs, template_only, conversion_path,
4201 access_path, flags, candidates, complain);
4202 if (any_strictly_viable (*candidates))
4203 return;
4206 /* Expand the CONSTRUCTOR into a new argument vec. */
4207 vec<tree, va_gc> *new_args;
4208 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4209 for (unsigned i = 0; i < nart; ++i)
4210 new_args->quick_push ((*args)[i]);
4211 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4212 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4214 /* We aren't looking for list-ctors anymore. */
4215 flags &= ~LOOKUP_LIST_ONLY;
4216 /* We allow more user-defined conversions within an init-list. */
4217 flags &= ~LOOKUP_NO_CONVERSION;
4219 add_candidates (fns, first_arg, new_args, NULL_TREE,
4220 explicit_targs, template_only, conversion_path,
4221 access_path, flags, candidates, complain);
4224 /* Given C(std::initializer_list<A>), return A. */
4226 static tree
4227 list_ctor_element_type (tree fn)
4229 gcc_checking_assert (is_list_ctor (fn));
4231 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4232 parm = non_reference (TREE_VALUE (parm));
4233 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4236 /* If EXPR is a braced-init-list where the elements all decay to the same type,
4237 return that type. */
4239 static tree
4240 braced_init_element_type (tree expr)
4242 if (TREE_CODE (expr) == CONSTRUCTOR
4243 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4244 return TREE_TYPE (TREE_TYPE (expr));
4245 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4246 return NULL_TREE;
4248 tree elttype = NULL_TREE;
4249 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4251 tree type = TREE_TYPE (e.value);
4252 type = type_decays_to (type);
4253 if (!elttype)
4254 elttype = type;
4255 else if (!same_type_p (type, elttype))
4256 return NULL_TREE;
4258 return elttype;
4261 /* True iff EXPR contains any temporaries with non-trivial destruction.
4263 ??? Also ignore classes with non-trivial but no-op destruction other than
4264 std::allocator? */
4266 static bool
4267 has_non_trivial_temporaries (tree expr)
4269 auto_vec<tree*> temps;
4270 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4271 for (tree *p : temps)
4273 tree t = TREE_TYPE (*p);
4274 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4275 && !is_std_allocator (t))
4276 return true;
4278 return false;
4281 /* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4282 return INIT as an array (of its own type) so the caller can initialize the
4283 target array in a loop. */
4285 static tree
4286 maybe_init_list_as_array (tree elttype, tree init)
4288 /* Only do this if the array can go in rodata but not once converted. */
4289 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4290 return NULL_TREE;
4291 tree init_elttype = braced_init_element_type (init);
4292 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4293 return NULL_TREE;
4295 /* Check with a stub expression to weed out special cases, and check whether
4296 we call the same function for direct-init as copy-list-init. */
4297 conversion_obstack_sentinel cos;
4298 tree arg = build_stub_object (init_elttype);
4299 conversion *c = implicit_conversion (elttype, init_elttype, arg, false,
4300 LOOKUP_NORMAL, tf_none);
4301 if (c && c->kind == ck_rvalue)
4302 c = next_conversion (c);
4303 if (!c || c->kind != ck_user)
4304 return NULL_TREE;
4306 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4307 conversion *fc = implicit_conversion (elttype, init_elttype, first, false,
4308 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4309 tf_none);
4310 if (fc && fc->kind == ck_rvalue)
4311 fc = next_conversion (fc);
4312 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4313 return NULL_TREE;
4314 first = convert_like (fc, first, tf_none);
4315 if (first == error_mark_node)
4316 /* Let the normal code give the error. */
4317 return NULL_TREE;
4319 /* Don't do this if the conversion would be constant. */
4320 first = maybe_constant_init (first);
4321 if (TREE_CONSTANT (first))
4322 return NULL_TREE;
4324 /* We can't do this if the conversion creates temporaries that need
4325 to live until the whole array is initialized. */
4326 if (has_non_trivial_temporaries (first))
4327 return NULL_TREE;
4329 /* We can't do this if copying from the initializer_list would be
4330 ill-formed. */
4331 tree copy_argtypes = make_tree_vec (1);
4332 TREE_VEC_ELT (copy_argtypes, 0)
4333 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4334 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4335 return NULL_TREE;
4337 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4338 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4339 arr = finish_compound_literal (arr, init, tf_none);
4340 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4341 return arr;
4344 /* If we were going to call e.g. vector(initializer_list<string>) starting
4345 with a list of string-literals (which is inefficient, see PR105838),
4346 instead build an array of const char* and pass it to the range constructor.
4347 But only do this for standard library types, where we can assume the
4348 transformation makes sense.
4350 Really the container classes should have initializer_list<U> constructors to
4351 get the same effect more simply; this is working around that lack. */
4353 static tree
4354 maybe_init_list_as_range (tree fn, tree expr)
4356 if (!processing_template_decl
4357 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4358 && is_list_ctor (fn)
4359 && decl_in_std_namespace_p (fn))
4361 tree to = list_ctor_element_type (fn);
4362 if (tree init = maybe_init_list_as_array (to, expr))
4364 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4365 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4366 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4367 nelts, tf_none);
4368 begin = cp_build_compound_expr (init, begin, tf_none);
4369 return build_constructor_va (init_list_type_node, 2,
4370 NULL_TREE, begin, NULL_TREE, end);
4374 return NULL_TREE;
4377 /* Returns the best overload candidate to perform the requested
4378 conversion. This function is used for three the overloading situations
4379 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4380 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4381 per [dcl.init.ref], so we ignore temporary bindings. */
4383 static struct z_candidate *
4384 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4385 tsubst_flags_t complain)
4387 struct z_candidate *candidates, *cand;
4388 tree fromtype;
4389 tree ctors = NULL_TREE;
4390 tree conv_fns = NULL_TREE;
4391 conversion *conv = NULL;
4392 tree first_arg = NULL_TREE;
4393 vec<tree, va_gc> *args = NULL;
4394 bool any_viable_p;
4395 int convflags;
4397 if (!expr)
4398 return NULL;
4400 fromtype = TREE_TYPE (expr);
4402 /* We represent conversion within a hierarchy using RVALUE_CONV and
4403 BASE_CONV, as specified by [over.best.ics]; these become plain
4404 constructor calls, as specified in [dcl.init]. */
4405 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4406 || !DERIVED_FROM_P (totype, fromtype));
4408 if (CLASS_TYPE_P (totype))
4409 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4410 creating a garbage BASELINK; constructors can't be inherited. */
4411 ctors = get_class_binding (totype, complete_ctor_identifier);
4413 tree to_nonref = non_reference (totype);
4414 if (MAYBE_CLASS_TYPE_P (fromtype))
4416 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4417 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4418 && DERIVED_FROM_P (to_nonref, fromtype)))
4420 /* [class.conv.fct] A conversion function is never used to
4421 convert a (possibly cv-qualified) object to the (possibly
4422 cv-qualified) same object type (or a reference to it), to a
4423 (possibly cv-qualified) base class of that type (or a
4424 reference to it)... */
4426 else
4427 conv_fns = lookup_conversions (fromtype);
4430 candidates = 0;
4431 flags |= LOOKUP_NO_CONVERSION;
4432 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4433 flags |= LOOKUP_NO_NARROWING;
4434 /* Prevent add_candidates from treating a non-strictly viable candidate
4435 as unviable. */
4436 complain |= tf_conv;
4438 /* It's OK to bind a temporary for converting constructor arguments, but
4439 not in converting the return value of a conversion operator. */
4440 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4441 | (flags & LOOKUP_NO_NARROWING));
4442 flags &= ~LOOKUP_NO_TEMP_BIND;
4444 if (ctors)
4446 int ctorflags = flags;
4448 first_arg = build_dummy_object (totype);
4450 /* We should never try to call the abstract or base constructor
4451 from here. */
4452 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4453 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4455 args = make_tree_vector_single (expr);
4456 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4458 /* List-initialization. */
4459 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4460 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4461 ctorflags, &candidates, complain);
4463 else
4465 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4466 TYPE_BINFO (totype), TYPE_BINFO (totype),
4467 ctorflags, &candidates, complain);
4470 for (cand = candidates; cand; cand = cand->next)
4472 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4474 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4475 set, then this is copy-initialization. In that case, "The
4476 result of the call is then used to direct-initialize the
4477 object that is the destination of the copy-initialization."
4478 [dcl.init]
4480 We represent this in the conversion sequence with an
4481 rvalue conversion, which means a constructor call. */
4482 if (!TYPE_REF_P (totype)
4483 && cxx_dialect < cxx17
4484 && (flags & LOOKUP_ONLYCONVERTING)
4485 && !(convflags & LOOKUP_NO_TEMP_BIND))
4486 cand->second_conv
4487 = build_conv (ck_rvalue, totype, cand->second_conv);
4491 if (conv_fns)
4493 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4494 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4495 else
4496 first_arg = expr;
4499 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4501 tree conversion_path = TREE_PURPOSE (conv_fns);
4502 struct z_candidate *old_candidates;
4504 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4505 would need an addional user-defined conversion, i.e. if the return
4506 type differs in class-ness from the desired type. So we avoid
4507 considering operator bool when calling a copy constructor.
4509 This optimization avoids the failure in PR97600, and is allowed by
4510 [temp.inst]/9: "If the function selected by overload resolution can be
4511 determined without instantiating a class template definition, it is
4512 unspecified whether that instantiation actually takes place." */
4513 tree convtype = non_reference (TREE_TYPE (conv_fns));
4514 if ((flags & LOOKUP_NO_CONVERSION)
4515 && !WILDCARD_TYPE_P (convtype)
4516 && (CLASS_TYPE_P (to_nonref)
4517 != CLASS_TYPE_P (convtype)))
4518 continue;
4520 /* If we are called to convert to a reference type, we are trying to
4521 find a direct binding, so don't even consider temporaries. If
4522 we don't find a direct binding, the caller will try again to
4523 look for a temporary binding. */
4524 if (TYPE_REF_P (totype))
4525 convflags |= LOOKUP_NO_TEMP_BIND;
4527 old_candidates = candidates;
4528 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4529 NULL_TREE, false,
4530 conversion_path, TYPE_BINFO (fromtype),
4531 flags, &candidates, complain);
4533 for (cand = candidates; cand != old_candidates; cand = cand->next)
4535 if (cand->viable == 0)
4536 /* Already rejected, don't change to -1. */
4537 continue;
4539 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4540 conversion *ics
4541 = implicit_conversion (totype,
4542 rettype,
4544 /*c_cast_p=*/false, convflags,
4545 complain);
4547 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4548 copy-initialization. In that case, "The result of the
4549 call is then used to direct-initialize the object that is
4550 the destination of the copy-initialization." [dcl.init]
4552 We represent this in the conversion sequence with an
4553 rvalue conversion, which means a constructor call. But
4554 don't add a second rvalue conversion if there's already
4555 one there. Which there really shouldn't be, but it's
4556 harmless since we'd add it here anyway. */
4557 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4558 && !(convflags & LOOKUP_NO_TEMP_BIND))
4559 ics = build_conv (ck_rvalue, totype, ics);
4561 cand->second_conv = ics;
4563 if (!ics)
4565 cand->viable = 0;
4566 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4567 rettype, totype,
4568 EXPR_LOCATION (expr));
4570 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4571 /* Limit this to non-templates for now (PR90546). */
4572 && !cand->template_decl
4573 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4575 /* If we are called to convert to a reference type, we are trying
4576 to find a direct binding per [over.match.ref], so rvaluedness
4577 must match for non-functions. */
4578 cand->viable = 0;
4580 else if (DECL_NONCONVERTING_P (cand->fn)
4581 && ics->rank > cr_exact)
4583 /* 13.3.1.5: For direct-initialization, those explicit
4584 conversion functions that are not hidden within S and
4585 yield type T or a type that can be converted to type T
4586 with a qualification conversion (4.4) are also candidate
4587 functions. */
4588 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4589 I've raised this issue with the committee. --jason 9/2011 */
4590 cand->viable = -1;
4591 cand->reason = explicit_conversion_rejection (rettype, totype);
4593 else if (cand->viable == 1 && ics->bad_p)
4595 cand->viable = -1;
4596 cand->reason
4597 = bad_arg_conversion_rejection (NULL_TREE, -2,
4598 rettype, totype,
4599 EXPR_LOCATION (expr));
4601 else if (primary_template_specialization_p (cand->fn)
4602 && ics->rank > cr_exact)
4604 /* 13.3.3.1.2: If the user-defined conversion is specified by
4605 a specialization of a conversion function template, the
4606 second standard conversion sequence shall have exact match
4607 rank. */
4608 cand->viable = -1;
4609 cand->reason = template_conversion_rejection (rettype, totype);
4614 candidates = splice_viable (candidates, false, &any_viable_p);
4615 if (!any_viable_p)
4617 if (args)
4618 release_tree_vector (args);
4619 return NULL;
4622 cand = tourney (candidates, complain);
4623 if (cand == NULL)
4625 if (complain & tf_error)
4627 auto_diagnostic_group d;
4628 error_at (cp_expr_loc_or_input_loc (expr),
4629 "conversion from %qH to %qI is ambiguous",
4630 fromtype, totype);
4631 print_z_candidates (location_of (expr), candidates);
4634 cand = candidates; /* any one will do */
4635 cand->second_conv = build_ambiguous_conv (totype, expr);
4636 cand->second_conv->user_conv_p = true;
4637 if (!any_strictly_viable (candidates))
4638 cand->second_conv->bad_p = true;
4639 if (flags & LOOKUP_ONLYCONVERTING)
4640 cand->second_conv->need_temporary_p = true;
4641 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4642 ambiguous conversion is no worse than another user-defined
4643 conversion. */
4645 return cand;
4648 /* Maybe pass { } as iterators instead of an initializer_list. */
4649 if (tree iters = maybe_init_list_as_range (cand->fn, expr))
4650 if (z_candidate *cand2
4651 = build_user_type_conversion_1 (totype, iters, flags, tf_none))
4652 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4654 cand = cand2;
4655 expr = iters;
4658 tree convtype;
4659 if (!DECL_CONSTRUCTOR_P (cand->fn))
4660 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4661 else if (cand->second_conv->kind == ck_rvalue)
4662 /* DR 5: [in the first step of copy-initialization]...if the function
4663 is a constructor, the call initializes a temporary of the
4664 cv-unqualified version of the destination type. */
4665 convtype = cv_unqualified (totype);
4666 else
4667 convtype = totype;
4668 /* Build the user conversion sequence. */
4669 conv = build_conv
4670 (ck_user,
4671 convtype,
4672 build_identity_conv (TREE_TYPE (expr), expr));
4673 conv->cand = cand;
4674 if (cand->viable == -1)
4675 conv->bad_p = true;
4677 /* Remember that this was a list-initialization. */
4678 if (flags & LOOKUP_NO_NARROWING)
4679 conv->check_narrowing = true;
4681 /* Combine it with the second conversion sequence. */
4682 cand->second_conv = merge_conversion_sequences (conv,
4683 cand->second_conv);
4685 return cand;
4688 /* Wrapper for above. */
4690 tree
4691 build_user_type_conversion (tree totype, tree expr, int flags,
4692 tsubst_flags_t complain)
4694 struct z_candidate *cand;
4695 tree ret;
4697 auto_cond_timevar tv (TV_OVERLOAD);
4699 conversion_obstack_sentinel cos;
4701 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4703 if (cand)
4705 if (cand->second_conv->kind == ck_ambig)
4706 ret = error_mark_node;
4707 else
4709 expr = convert_like (cand->second_conv, expr, complain);
4710 ret = convert_from_reference (expr);
4713 else
4714 ret = NULL_TREE;
4716 return ret;
4719 /* Give a helpful diagnostic when implicit_conversion fails. */
4721 static void
4722 implicit_conversion_error (location_t loc, tree type, tree expr)
4724 tsubst_flags_t complain = tf_warning_or_error;
4726 /* If expr has unknown type, then it is an overloaded function.
4727 Call instantiate_type to get good error messages. */
4728 if (TREE_TYPE (expr) == unknown_type_node)
4729 instantiate_type (type, expr, complain);
4730 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4731 /* We gave an error. */;
4732 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4733 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4734 && !CP_AGGREGATE_TYPE_P (type))
4735 error_at (loc, "designated initializers cannot be used with a "
4736 "non-aggregate type %qT", type);
4737 else
4739 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4740 gcc_rich_location rich_loc (loc, &label);
4741 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4742 expr, TREE_TYPE (expr), type);
4746 /* Worker for build_converted_constant_expr. */
4748 static tree
4749 build_converted_constant_expr_internal (tree type, tree expr,
4750 int flags, tsubst_flags_t complain)
4752 conversion *conv;
4753 tree t;
4754 location_t loc = cp_expr_loc_or_input_loc (expr);
4756 if (error_operand_p (expr))
4757 return error_mark_node;
4759 conversion_obstack_sentinel cos;
4761 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4762 /*c_cast_p=*/false, flags, complain);
4764 /* A converted constant expression of type T is an expression, implicitly
4765 converted to type T, where the converted expression is a constant
4766 expression and the implicit conversion sequence contains only
4768 * user-defined conversions,
4769 * lvalue-to-rvalue conversions (7.1),
4770 * array-to-pointer conversions (7.2),
4771 * function-to-pointer conversions (7.3),
4772 * qualification conversions (7.5),
4773 * integral promotions (7.6),
4774 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4775 * null pointer conversions (7.11) from std::nullptr_t,
4776 * null member pointer conversions (7.12) from std::nullptr_t, and
4777 * function pointer conversions (7.13),
4779 and where the reference binding (if any) binds directly. */
4781 for (conversion *c = conv;
4782 c && c->kind != ck_identity;
4783 c = next_conversion (c))
4785 switch (c->kind)
4787 /* A conversion function is OK. If it isn't constexpr, we'll
4788 complain later that the argument isn't constant. */
4789 case ck_user:
4790 /* List-initialization is OK. */
4791 case ck_aggr:
4792 /* The lvalue-to-rvalue conversion is OK. */
4793 case ck_rvalue:
4794 /* Array-to-pointer and function-to-pointer. */
4795 case ck_lvalue:
4796 /* Function pointer conversions. */
4797 case ck_fnptr:
4798 /* Qualification conversions. */
4799 case ck_qual:
4800 break;
4802 case ck_ref_bind:
4803 if (c->need_temporary_p)
4805 if (complain & tf_error)
4806 error_at (loc, "initializing %qH with %qI in converted "
4807 "constant expression does not bind directly",
4808 type, next_conversion (c)->type);
4809 conv = NULL;
4811 break;
4813 case ck_base:
4814 case ck_pmem:
4815 case ck_ptr:
4816 case ck_std:
4817 t = next_conversion (c)->type;
4818 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4819 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4820 /* Integral promotion or conversion. */
4821 break;
4822 if (NULLPTR_TYPE_P (t))
4823 /* Conversion from nullptr to pointer or pointer-to-member. */
4824 break;
4826 if (complain & tf_error)
4827 error_at (loc, "conversion from %qH to %qI in a "
4828 "converted constant expression", t, type);
4829 /* fall through. */
4831 default:
4832 conv = NULL;
4833 break;
4837 /* Avoid confusing convert_nontype_argument by introducing
4838 a redundant conversion to the same reference type. */
4839 if (conv && conv->kind == ck_ref_bind
4840 && REFERENCE_REF_P (expr))
4842 tree ref = TREE_OPERAND (expr, 0);
4843 if (same_type_p (type, TREE_TYPE (ref)))
4844 return ref;
4847 if (conv)
4849 /* Don't copy a class in a template. */
4850 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4851 && processing_template_decl)
4852 conv = next_conversion (conv);
4854 /* Issuing conversion warnings for value-dependent expressions is
4855 likely too noisy. */
4856 warning_sentinel w (warn_conversion);
4857 conv->check_narrowing = true;
4858 conv->check_narrowing_const_only = true;
4859 expr = convert_like (conv, expr, complain);
4861 else
4863 if (complain & tf_error)
4864 implicit_conversion_error (loc, type, expr);
4865 expr = error_mark_node;
4868 return expr;
4871 /* Subroutine of convert_nontype_argument.
4873 EXPR is an expression used in a context that requires a converted
4874 constant-expression, such as a template non-type parameter. Do any
4875 necessary conversions (that are permitted for converted
4876 constant-expressions) to convert it to the desired type.
4878 This function doesn't consider explicit conversion functions. If
4879 you mean to use "a contextually converted constant expression of type
4880 bool", use build_converted_constant_bool_expr.
4882 If conversion is successful, returns the converted expression;
4883 otherwise, returns error_mark_node. */
4885 tree
4886 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4888 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4889 complain);
4892 /* Used to create "a contextually converted constant expression of type
4893 bool". This differs from build_converted_constant_expr in that it
4894 also considers explicit conversion functions. */
4896 tree
4897 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4899 return build_converted_constant_expr_internal (boolean_type_node, expr,
4900 LOOKUP_NORMAL, complain);
4903 /* Do any initial processing on the arguments to a function call. */
4905 vec<tree, va_gc> *
4906 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4908 unsigned int ix;
4909 tree arg;
4911 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4913 if (error_operand_p (arg))
4914 return NULL;
4915 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4917 if (complain & tf_error)
4918 error_at (cp_expr_loc_or_input_loc (arg),
4919 "invalid use of void expression");
4920 return NULL;
4922 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4923 return NULL;
4925 /* Force auto deduction now. Omit tf_warning to avoid redundant
4926 deprecated warning on deprecated-14.C. */
4927 if (!mark_single_function (arg, complain & ~tf_warning))
4928 return NULL;
4930 return args;
4933 /* Perform overload resolution on FN, which is called with the ARGS.
4935 Return the candidate function selected by overload resolution, or
4936 NULL if the event that overload resolution failed. In the case
4937 that overload resolution fails, *CANDIDATES will be the set of
4938 candidates considered, and ANY_VIABLE_P will be set to true or
4939 false to indicate whether or not any of the candidates were
4940 viable.
4942 The ARGS should already have gone through RESOLVE_ARGS before this
4943 function is called. */
4945 static struct z_candidate *
4946 perform_overload_resolution (tree fn,
4947 const vec<tree, va_gc> *args,
4948 struct z_candidate **candidates,
4949 bool *any_viable_p, tsubst_flags_t complain)
4951 struct z_candidate *cand;
4952 tree explicit_targs;
4953 int template_only;
4955 auto_cond_timevar tv (TV_OVERLOAD);
4957 explicit_targs = NULL_TREE;
4958 template_only = 0;
4960 *candidates = NULL;
4961 *any_viable_p = true;
4963 /* Check FN. */
4964 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4966 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4968 explicit_targs = TREE_OPERAND (fn, 1);
4969 fn = TREE_OPERAND (fn, 0);
4970 template_only = 1;
4973 /* Add the various candidate functions. */
4974 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4975 explicit_targs, template_only,
4976 /*conversion_path=*/NULL_TREE,
4977 /*access_path=*/NULL_TREE,
4978 LOOKUP_NORMAL,
4979 candidates, complain);
4981 *candidates = splice_viable (*candidates, false, any_viable_p);
4982 if (*any_viable_p)
4983 cand = tourney (*candidates, complain);
4984 else
4985 cand = NULL;
4987 return cand;
4990 /* Print an error message about being unable to build a call to FN with
4991 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4992 be located; CANDIDATES is a possibly empty list of such
4993 functions. */
4995 static void
4996 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4997 struct z_candidate *candidates)
4999 tree targs = NULL_TREE;
5000 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5002 targs = TREE_OPERAND (fn, 1);
5003 fn = TREE_OPERAND (fn, 0);
5005 tree name = OVL_NAME (fn);
5006 location_t loc = location_of (name);
5007 if (targs)
5008 name = lookup_template_function (name, targs);
5010 auto_diagnostic_group d;
5011 if (!any_strictly_viable (candidates))
5012 error_at (loc, "no matching function for call to %<%D(%A)%>",
5013 name, build_tree_list_vec (args));
5014 else
5015 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
5016 name, build_tree_list_vec (args));
5017 if (candidates)
5018 print_z_candidates (loc, candidates);
5021 /* Perform overload resolution on the set of deduction guides DGUIDES
5022 using ARGS. Returns the selected deduction guide, or error_mark_node
5023 if overload resolution fails. */
5025 tree
5026 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
5027 tsubst_flags_t complain)
5029 z_candidate *candidates;
5030 bool any_viable_p;
5031 tree result;
5033 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
5035 conversion_obstack_sentinel cos;
5037 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
5038 &any_viable_p, complain);
5039 if (!cand)
5041 if (complain & tf_error)
5042 print_error_for_call_failure (dguides, args, candidates);
5043 result = error_mark_node;
5045 else
5046 result = cand->fn;
5048 return result;
5051 /* Return an expression for a call to FN (a namespace-scope function,
5052 or a static member function) with the ARGS. This may change
5053 ARGS. */
5055 tree
5056 build_new_function_call (tree fn, vec<tree, va_gc> **args,
5057 tsubst_flags_t complain)
5059 struct z_candidate *candidates, *cand;
5060 bool any_viable_p;
5061 tree result;
5063 if (args != NULL && *args != NULL)
5065 *args = resolve_args (*args, complain);
5066 if (*args == NULL)
5067 return error_mark_node;
5070 if (flag_tm)
5071 tm_malloc_replacement (fn);
5073 conversion_obstack_sentinel cos;
5075 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
5076 complain);
5078 if (!cand)
5080 if (complain & tf_error)
5082 // If there is a single (non-viable) function candidate,
5083 // let the error be diagnosed by cp_build_function_call_vec.
5084 if (!any_viable_p && candidates && ! candidates->next
5085 && TREE_CODE (candidates->fn) == FUNCTION_DECL
5086 /* A template-id callee consisting of a single (ignored)
5087 non-template candidate needs to be diagnosed the
5088 ordinary way. */
5089 && (TREE_CODE (fn) != TEMPLATE_ID_EXPR
5090 || candidates->template_decl))
5091 return cp_build_function_call_vec (candidates->fn, args, complain);
5093 // Otherwise, emit notes for non-viable candidates.
5094 print_error_for_call_failure (fn, *args, candidates);
5096 result = error_mark_node;
5098 else
5100 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5103 if (flag_coroutines
5104 && result
5105 && TREE_CODE (result) == CALL_EXPR
5106 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5107 == BUILT_IN_NORMAL)
5108 result = coro_validate_builtin_call (result);
5110 return result;
5113 /* Build a call to a global operator new. FNNAME is the name of the
5114 operator (either "operator new" or "operator new[]") and ARGS are
5115 the arguments provided. This may change ARGS. *SIZE points to the
5116 total number of bytes required by the allocation, and is updated if
5117 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5118 be used. If this function determines that no cookie should be
5119 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5120 is not NULL_TREE, it is evaluated before calculating the final
5121 array size, and if it fails, the array size is replaced with
5122 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5123 is non-NULL, it will be set, upon return, to the allocation
5124 function called. */
5126 tree
5127 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5128 tree *size, tree *cookie_size,
5129 tree align_arg, tree size_check,
5130 tree *fn, tsubst_flags_t complain)
5132 tree original_size = *size;
5133 tree fns;
5134 struct z_candidate *candidates;
5135 struct z_candidate *cand = NULL;
5136 bool any_viable_p;
5138 if (fn)
5139 *fn = NULL_TREE;
5140 /* Set to (size_t)-1 if the size check fails. */
5141 if (size_check != NULL_TREE)
5143 tree errval = TYPE_MAX_VALUE (sizetype);
5144 if (cxx_dialect >= cxx11 && flag_exceptions)
5145 errval = throw_bad_array_new_length ();
5146 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5147 original_size, errval);
5149 vec_safe_insert (*args, 0, *size);
5150 *args = resolve_args (*args, complain);
5151 if (*args == NULL)
5152 return error_mark_node;
5154 conversion_obstack_sentinel cos;
5156 /* Based on:
5158 [expr.new]
5160 If this lookup fails to find the name, or if the allocated type
5161 is not a class type, the allocation function's name is looked
5162 up in the global scope.
5164 we disregard block-scope declarations of "operator new". */
5165 fns = lookup_qualified_name (global_namespace, fnname);
5167 if (align_arg)
5169 vec<tree, va_gc>* align_args
5170 = vec_copy_and_insert (*args, align_arg, 1);
5171 cand = perform_overload_resolution (fns, align_args, &candidates,
5172 &any_viable_p, tf_none);
5173 if (cand)
5174 *args = align_args;
5175 /* If no aligned allocation function matches, try again without the
5176 alignment. */
5179 /* Figure out what function is being called. */
5180 if (!cand)
5181 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
5182 complain);
5184 /* If no suitable function could be found, issue an error message
5185 and give up. */
5186 if (!cand)
5188 if (complain & tf_error)
5189 print_error_for_call_failure (fns, *args, candidates);
5190 return error_mark_node;
5193 /* If a cookie is required, add some extra space. Whether
5194 or not a cookie is required cannot be determined until
5195 after we know which function was called. */
5196 if (*cookie_size)
5198 bool use_cookie = true;
5199 tree arg_types;
5201 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5202 /* Skip the size_t parameter. */
5203 arg_types = TREE_CHAIN (arg_types);
5204 /* Check the remaining parameters (if any). */
5205 if (arg_types
5206 && TREE_CHAIN (arg_types) == void_list_node
5207 && same_type_p (TREE_VALUE (arg_types),
5208 ptr_type_node))
5209 use_cookie = false;
5210 /* If we need a cookie, adjust the number of bytes allocated. */
5211 if (use_cookie)
5213 /* Update the total size. */
5214 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5215 if (size_check)
5217 /* Set to (size_t)-1 if the size check fails. */
5218 gcc_assert (size_check != NULL_TREE);
5219 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5220 *size, TYPE_MAX_VALUE (sizetype));
5222 /* Update the argument list to reflect the adjusted size. */
5223 (**args)[0] = *size;
5225 else
5226 *cookie_size = NULL_TREE;
5229 /* Tell our caller which function we decided to call. */
5230 if (fn)
5231 *fn = cand->fn;
5233 /* Build the CALL_EXPR. */
5234 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5236 /* Set this flag for all callers of this function. In addition to
5237 new-expressions, this is called for allocating coroutine state; treat
5238 that as an implicit new-expression. */
5239 tree call = extract_call_expr (ret);
5240 if (TREE_CODE (call) == CALL_EXPR)
5241 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5243 return ret;
5246 /* Evaluate side-effects from OBJ before evaluating call
5247 to FN in RESULT expression.
5248 This is for expressions of the form `obj->fn(...)'
5249 where `fn' turns out to be a static member function and
5250 `obj' needs to be evaluated. `fn' could be also static operator[]
5251 or static operator(), in which cases the source expression
5252 would be `obj[...]' or `obj(...)'. */
5254 tree
5255 keep_unused_object_arg (tree result, tree obj, tree fn)
5257 if (result == NULL_TREE
5258 || result == error_mark_node
5259 || DECL_OBJECT_MEMBER_FUNCTION_P (fn)
5260 || !TREE_SIDE_EFFECTS (obj))
5261 return result;
5263 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5264 volatile. */
5265 tree a = obj;
5266 if (TREE_THIS_VOLATILE (a))
5267 a = build_this (a);
5268 if (TREE_SIDE_EFFECTS (a))
5269 return cp_build_compound_expr (a, result, tf_error);
5270 return result;
5273 /* Build a new call to operator(). This may change ARGS. */
5275 tree
5276 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5278 struct z_candidate *candidates = 0, *cand;
5279 tree fns, convs, first_mem_arg = NULL_TREE;
5280 bool any_viable_p;
5281 tree result = NULL_TREE;
5283 auto_cond_timevar tv (TV_OVERLOAD);
5285 obj = mark_lvalue_use (obj);
5287 if (error_operand_p (obj))
5288 return error_mark_node;
5290 tree type = TREE_TYPE (obj);
5292 obj = prep_operand (obj);
5294 if (TYPE_PTRMEMFUNC_P (type))
5296 if (complain & tf_error)
5297 /* It's no good looking for an overloaded operator() on a
5298 pointer-to-member-function. */
5299 error ("pointer-to-member function %qE cannot be called without "
5300 "an object; consider using %<.*%> or %<->*%>", obj);
5301 return error_mark_node;
5304 if (TYPE_BINFO (type))
5306 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5307 if (fns == error_mark_node)
5308 return error_mark_node;
5310 else
5311 fns = NULL_TREE;
5313 if (args != NULL && *args != NULL)
5315 *args = resolve_args (*args, complain);
5316 if (*args == NULL)
5317 return error_mark_node;
5320 conversion_obstack_sentinel cos;
5322 if (fns)
5324 first_mem_arg = obj;
5326 add_candidates (BASELINK_FUNCTIONS (fns),
5327 first_mem_arg, *args, NULL_TREE,
5328 NULL_TREE, false,
5329 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5330 LOOKUP_NORMAL, &candidates, complain);
5333 bool any_call_ops = candidates != nullptr;
5335 convs = lookup_conversions (type);
5337 for (; convs; convs = TREE_CHAIN (convs))
5339 tree totype = TREE_TYPE (convs);
5341 if (TYPE_PTRFN_P (totype)
5342 || TYPE_REFFN_P (totype)
5343 || (TYPE_REF_P (totype)
5344 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5345 for (tree fn : ovl_range (TREE_VALUE (convs)))
5347 if (DECL_NONCONVERTING_P (fn))
5348 continue;
5350 if (TREE_CODE (fn) == TEMPLATE_DECL)
5352 /* Making this work broke PR 71117 and 85118, so until the
5353 committee resolves core issue 2189, let's disable this
5354 candidate if there are any call operators. */
5355 if (any_call_ops)
5356 continue;
5358 add_template_conv_candidate
5359 (&candidates, fn, obj, *args, totype,
5360 /*access_path=*/NULL_TREE,
5361 /*conversion_path=*/NULL_TREE, complain);
5363 else
5364 add_conv_candidate (&candidates, fn, obj,
5365 *args, /*conversion_path=*/NULL_TREE,
5366 /*access_path=*/NULL_TREE, complain);
5370 /* Be strict here because if we choose a bad conversion candidate, the
5371 errors we get won't mention the call context. */
5372 candidates = splice_viable (candidates, true, &any_viable_p);
5373 if (!any_viable_p)
5375 if (complain & tf_error)
5377 auto_diagnostic_group d;
5378 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5379 build_tree_list_vec (*args));
5380 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5382 result = error_mark_node;
5384 else
5386 cand = tourney (candidates, complain);
5387 if (cand == 0)
5389 if (complain & tf_error)
5391 auto_diagnostic_group d;
5392 error ("call of %<(%T) (%A)%> is ambiguous",
5393 TREE_TYPE (obj), build_tree_list_vec (*args));
5394 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5396 result = error_mark_node;
5398 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5399 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5400 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5402 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5403 /* In an expression of the form `a()' where cand->fn
5404 which is operator() turns out to be a static member function,
5405 `a' is none-the-less evaluated. */
5406 result = keep_unused_object_arg (result, obj, cand->fn);
5408 else
5410 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5411 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5412 -1, complain);
5413 else
5415 gcc_checking_assert (TYPE_P (cand->fn));
5416 obj = convert_like (cand->convs[0], obj, complain);
5418 obj = convert_from_reference (obj);
5419 result = cp_build_function_call_vec (obj, args, complain);
5423 return result;
5426 /* Called by op_error to prepare format strings suitable for the error
5427 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5428 and a suffix (controlled by NTYPES). */
5430 static const char *
5431 op_error_string (const char *errmsg, int ntypes, bool match)
5433 const char *msg;
5435 const char *msgp = concat (match ? G_("ambiguous overload for ")
5436 : G_("no match for "), errmsg, NULL);
5438 if (ntypes == 3)
5439 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5440 else if (ntypes == 2)
5441 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5442 else
5443 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5445 return msg;
5448 static void
5449 op_error (const op_location_t &loc,
5450 enum tree_code code, enum tree_code code2,
5451 tree arg1, tree arg2, tree arg3, bool match)
5453 bool assop = code == MODIFY_EXPR;
5454 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5456 switch (code)
5458 case COND_EXPR:
5459 if (flag_diagnostics_show_caret)
5460 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5461 3, match),
5462 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5463 else
5464 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5465 "in %<%E ? %E : %E%>"), 3, match),
5466 arg1, arg2, arg3,
5467 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5468 break;
5470 case POSTINCREMENT_EXPR:
5471 case POSTDECREMENT_EXPR:
5472 if (flag_diagnostics_show_caret)
5473 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5474 opname, TREE_TYPE (arg1));
5475 else
5476 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5477 1, match),
5478 opname, arg1, opname, TREE_TYPE (arg1));
5479 break;
5481 case ARRAY_REF:
5482 if (flag_diagnostics_show_caret)
5483 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5484 TREE_TYPE (arg1), TREE_TYPE (arg2));
5485 else
5486 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5487 2, match),
5488 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5489 break;
5491 case REALPART_EXPR:
5492 case IMAGPART_EXPR:
5493 if (flag_diagnostics_show_caret)
5494 error_at (loc, op_error_string (G_("%qs"), 1, match),
5495 opname, TREE_TYPE (arg1));
5496 else
5497 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5498 opname, opname, arg1, TREE_TYPE (arg1));
5499 break;
5501 case CO_AWAIT_EXPR:
5502 if (flag_diagnostics_show_caret)
5503 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5504 opname, TREE_TYPE (arg1));
5505 else
5506 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5507 1, match),
5508 opname, opname, arg1, TREE_TYPE (arg1));
5509 break;
5511 default:
5512 if (arg2)
5513 if (flag_diagnostics_show_caret)
5515 binary_op_rich_location richloc (loc, arg1, arg2, true);
5516 error_at (&richloc,
5517 op_error_string (G_("%<operator%s%>"), 2, match),
5518 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5520 else
5521 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5522 2, match),
5523 opname, arg1, opname, arg2,
5524 TREE_TYPE (arg1), TREE_TYPE (arg2));
5525 else
5526 if (flag_diagnostics_show_caret)
5527 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5528 opname, TREE_TYPE (arg1));
5529 else
5530 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5531 1, match),
5532 opname, opname, arg1, TREE_TYPE (arg1));
5533 break;
5537 /* Return the implicit conversion sequence that could be used to
5538 convert E1 to E2 in [expr.cond]. */
5540 static conversion *
5541 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5543 tree t1 = non_reference (TREE_TYPE (e1));
5544 tree t2 = non_reference (TREE_TYPE (e2));
5545 conversion *conv;
5546 bool good_base;
5548 /* [expr.cond]
5550 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5551 implicitly converted (clause _conv_) to the type "lvalue reference to
5552 T2", subject to the constraint that in the conversion the
5553 reference must bind directly (_dcl.init.ref_) to an lvalue.
5555 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5556 implicitly converted to the type "rvalue reference to T2", subject to
5557 the constraint that the reference must bind directly. */
5558 if (glvalue_p (e2))
5560 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5561 conv = implicit_conversion (rtype,
5564 /*c_cast_p=*/false,
5565 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5566 |LOOKUP_ONLYCONVERTING,
5567 complain);
5568 if (conv && !conv->bad_p)
5569 return conv;
5572 /* If E2 is a prvalue or if neither of the conversions above can be done
5573 and at least one of the operands has (possibly cv-qualified) class
5574 type: */
5575 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5576 return NULL;
5578 /* [expr.cond]
5580 If E1 and E2 have class type, and the underlying class types are
5581 the same or one is a base class of the other: E1 can be converted
5582 to match E2 if the class of T2 is the same type as, or a base
5583 class of, the class of T1, and the cv-qualification of T2 is the
5584 same cv-qualification as, or a greater cv-qualification than, the
5585 cv-qualification of T1. If the conversion is applied, E1 is
5586 changed to an rvalue of type T2 that still refers to the original
5587 source class object (or the appropriate subobject thereof). */
5588 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5589 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5591 if (good_base && at_least_as_qualified_p (t2, t1))
5593 conv = build_identity_conv (t1, e1);
5594 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5595 TYPE_MAIN_VARIANT (t2)))
5596 conv = build_conv (ck_base, t2, conv);
5597 else
5598 conv = build_conv (ck_rvalue, t2, conv);
5599 return conv;
5601 else
5602 return NULL;
5604 else
5605 /* [expr.cond]
5607 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5608 converted to the type that expression E2 would have if E2 were
5609 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5610 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5611 LOOKUP_IMPLICIT, complain);
5614 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5615 arguments to the conditional expression. */
5617 tree
5618 build_conditional_expr (const op_location_t &loc,
5619 tree arg1, tree arg2, tree arg3,
5620 tsubst_flags_t complain)
5622 tree arg2_type;
5623 tree arg3_type;
5624 tree result = NULL_TREE;
5625 tree result_type = NULL_TREE;
5626 tree semantic_result_type = NULL_TREE;
5627 bool is_glvalue = true;
5628 struct z_candidate *candidates = 0;
5629 struct z_candidate *cand;
5630 tree orig_arg2, orig_arg3;
5632 auto_cond_timevar tv (TV_OVERLOAD);
5634 /* As a G++ extension, the second argument to the conditional can be
5635 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5636 c'.) If the second operand is omitted, make sure it is
5637 calculated only once. */
5638 if (!arg2)
5640 if (complain & tf_error)
5641 pedwarn (loc, OPT_Wpedantic,
5642 "ISO C++ forbids omitting the middle term of "
5643 "a %<?:%> expression");
5645 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5646 warn_for_omitted_condop (loc, arg1);
5648 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5649 if (glvalue_p (arg1))
5651 arg1 = cp_stabilize_reference (arg1);
5652 arg2 = arg1 = prevent_lifetime_extension (arg1);
5654 else if (TREE_CODE (arg1) == TARGET_EXPR)
5655 /* arg1 can't be a prvalue result of the conditional
5656 expression, since it needs to be materialized for the
5657 conversion to bool, so treat it as an xvalue in arg2. */
5658 arg2 = move (TARGET_EXPR_SLOT (arg1));
5659 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5660 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5661 cp_save_expr (TREE_OPERAND (arg1, 0)));
5662 else
5663 arg2 = arg1 = cp_save_expr (arg1);
5666 /* If something has already gone wrong, just pass that fact up the
5667 tree. */
5668 if (error_operand_p (arg1)
5669 || error_operand_p (arg2)
5670 || error_operand_p (arg3))
5671 return error_mark_node;
5673 conversion_obstack_sentinel cos;
5675 orig_arg2 = arg2;
5676 orig_arg3 = arg3;
5678 if (gnu_vector_type_p (TREE_TYPE (arg1))
5679 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5681 tree arg1_type = TREE_TYPE (arg1);
5683 /* If arg1 is another cond_expr choosing between -1 and 0,
5684 then we can use its comparison. It may help to avoid
5685 additional comparison, produce more accurate diagnostics
5686 and enables folding. */
5687 if (TREE_CODE (arg1) == VEC_COND_EXPR
5688 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5689 && integer_zerop (TREE_OPERAND (arg1, 2)))
5690 arg1 = TREE_OPERAND (arg1, 0);
5692 arg1 = force_rvalue (arg1, complain);
5693 arg2 = force_rvalue (arg2, complain);
5694 arg3 = force_rvalue (arg3, complain);
5696 /* force_rvalue can return error_mark on valid arguments. */
5697 if (error_operand_p (arg1)
5698 || error_operand_p (arg2)
5699 || error_operand_p (arg3))
5700 return error_mark_node;
5702 arg2_type = TREE_TYPE (arg2);
5703 arg3_type = TREE_TYPE (arg3);
5705 if (!VECTOR_TYPE_P (arg2_type)
5706 && !VECTOR_TYPE_P (arg3_type))
5708 /* Rely on the error messages of the scalar version. */
5709 tree scal = build_conditional_expr (loc, integer_one_node,
5710 orig_arg2, orig_arg3, complain);
5711 if (scal == error_mark_node)
5712 return error_mark_node;
5713 tree stype = TREE_TYPE (scal);
5714 tree ctype = TREE_TYPE (arg1_type);
5715 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5716 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5718 if (complain & tf_error)
5719 error_at (loc, "inferred scalar type %qT is not an integer or "
5720 "floating-point type of the same size as %qT", stype,
5721 COMPARISON_CLASS_P (arg1)
5722 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5723 : ctype);
5724 return error_mark_node;
5727 tree vtype = build_opaque_vector_type (stype,
5728 TYPE_VECTOR_SUBPARTS (arg1_type));
5729 /* We could pass complain & tf_warning to unsafe_conversion_p,
5730 but the warnings (like Wsign-conversion) have already been
5731 given by the scalar build_conditional_expr_1. We still check
5732 unsafe_conversion_p to forbid truncating long long -> float. */
5733 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5735 if (complain & tf_error)
5736 error_at (loc, "conversion of scalar %qH to vector %qI "
5737 "involves truncation", arg2_type, vtype);
5738 return error_mark_node;
5740 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5742 if (complain & tf_error)
5743 error_at (loc, "conversion of scalar %qH to vector %qI "
5744 "involves truncation", arg3_type, vtype);
5745 return error_mark_node;
5748 arg2 = cp_convert (stype, arg2, complain);
5749 arg2 = save_expr (arg2);
5750 arg2 = build_vector_from_val (vtype, arg2);
5751 arg2_type = vtype;
5752 arg3 = cp_convert (stype, arg3, complain);
5753 arg3 = save_expr (arg3);
5754 arg3 = build_vector_from_val (vtype, arg3);
5755 arg3_type = vtype;
5758 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5759 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5761 enum stv_conv convert_flag =
5762 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5763 complain & tf_error);
5765 switch (convert_flag)
5767 case stv_error:
5768 return error_mark_node;
5769 case stv_firstarg:
5771 arg2 = save_expr (arg2);
5772 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5773 arg2 = build_vector_from_val (arg3_type, arg2);
5774 arg2_type = TREE_TYPE (arg2);
5775 break;
5777 case stv_secondarg:
5779 arg3 = save_expr (arg3);
5780 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5781 arg3 = build_vector_from_val (arg2_type, arg3);
5782 arg3_type = TREE_TYPE (arg3);
5783 break;
5785 default:
5786 break;
5790 if (!gnu_vector_type_p (arg2_type)
5791 || !gnu_vector_type_p (arg3_type)
5792 || !same_type_p (arg2_type, arg3_type)
5793 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5794 TYPE_VECTOR_SUBPARTS (arg2_type))
5795 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5797 if (complain & tf_error)
5798 error_at (loc,
5799 "incompatible vector types in conditional expression: "
5800 "%qT, %qT and %qT", TREE_TYPE (arg1),
5801 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5802 return error_mark_node;
5805 if (!COMPARISON_CLASS_P (arg1))
5807 tree cmp_type = truth_type_for (arg1_type);
5808 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5810 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5813 /* [expr.cond]
5815 The first expression is implicitly converted to bool (clause
5816 _conv_). */
5817 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5818 LOOKUP_NORMAL);
5819 if (error_operand_p (arg1))
5820 return error_mark_node;
5822 arg2_type = unlowered_expr_type (arg2);
5823 arg3_type = unlowered_expr_type (arg3);
5825 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5826 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5827 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5828 || SCALAR_FLOAT_TYPE_P (arg2_type)
5829 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5830 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5831 || SCALAR_FLOAT_TYPE_P (arg3_type)
5832 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5834 semantic_result_type
5835 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5836 if (semantic_result_type == error_mark_node)
5838 tree t1 = arg2_type;
5839 tree t2 = arg3_type;
5840 if (TREE_CODE (t1) == COMPLEX_TYPE)
5841 t1 = TREE_TYPE (t1);
5842 if (TREE_CODE (t2) == COMPLEX_TYPE)
5843 t2 = TREE_TYPE (t2);
5844 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
5845 && SCALAR_FLOAT_TYPE_P (t2)
5846 && (extended_float_type_p (t1)
5847 || extended_float_type_p (t2))
5848 && cp_compare_floating_point_conversion_ranks
5849 (t1, t2) == 3);
5850 if (complain & tf_error)
5851 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5852 "have unordered conversion rank",
5853 arg2_type, arg3_type);
5854 return error_mark_node;
5856 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5858 arg2 = TREE_OPERAND (arg2, 0);
5859 arg2_type = TREE_TYPE (arg2);
5861 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5863 arg3 = TREE_OPERAND (arg3, 0);
5864 arg3_type = TREE_TYPE (arg3);
5868 /* [expr.cond]
5870 If either the second or the third operand has type (possibly
5871 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5872 array-to-pointer (_conv.array_), and function-to-pointer
5873 (_conv.func_) standard conversions are performed on the second
5874 and third operands. */
5875 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5877 /* 'void' won't help in resolving an overloaded expression on the
5878 other side, so require it to resolve by itself. */
5879 if (arg2_type == unknown_type_node)
5881 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5882 arg2_type = TREE_TYPE (arg2);
5884 if (arg3_type == unknown_type_node)
5886 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5887 arg3_type = TREE_TYPE (arg3);
5890 /* [expr.cond]
5892 One of the following shall hold:
5894 --The second or the third operand (but not both) is a
5895 throw-expression (_except.throw_); the result is of the type
5896 and value category of the other.
5898 --Both the second and the third operands have type void; the
5899 result is of type void and is a prvalue. */
5900 if (TREE_CODE (arg2) == THROW_EXPR
5901 && TREE_CODE (arg3) != THROW_EXPR)
5903 result_type = arg3_type;
5904 is_glvalue = glvalue_p (arg3);
5906 else if (TREE_CODE (arg2) != THROW_EXPR
5907 && TREE_CODE (arg3) == THROW_EXPR)
5909 result_type = arg2_type;
5910 is_glvalue = glvalue_p (arg2);
5912 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5914 result_type = void_type_node;
5915 is_glvalue = false;
5917 else
5919 if (complain & tf_error)
5921 if (VOID_TYPE_P (arg2_type))
5922 error_at (cp_expr_loc_or_loc (arg3, loc),
5923 "second operand to the conditional operator "
5924 "is of type %<void%>, but the third operand is "
5925 "neither a throw-expression nor of type %<void%>");
5926 else
5927 error_at (cp_expr_loc_or_loc (arg2, loc),
5928 "third operand to the conditional operator "
5929 "is of type %<void%>, but the second operand is "
5930 "neither a throw-expression nor of type %<void%>");
5932 return error_mark_node;
5935 goto valid_operands;
5937 /* [expr.cond]
5939 Otherwise, if the second and third operand have different types,
5940 and either has (possibly cv-qualified) class type, or if both are
5941 glvalues of the same value category and the same type except for
5942 cv-qualification, an attempt is made to convert each of those operands
5943 to the type of the other. */
5944 else if (!same_type_p (arg2_type, arg3_type)
5945 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5946 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5947 arg3_type)
5948 && glvalue_p (arg2) && glvalue_p (arg3)
5949 && lvalue_p (arg2) == lvalue_p (arg3))))
5951 conversion *conv2;
5952 conversion *conv3;
5953 bool converted = false;
5955 conv2 = conditional_conversion (arg2, arg3, complain);
5956 conv3 = conditional_conversion (arg3, arg2, complain);
5958 /* [expr.cond]
5960 If both can be converted, or one can be converted but the
5961 conversion is ambiguous, the program is ill-formed. If
5962 neither can be converted, the operands are left unchanged and
5963 further checking is performed as described below. If exactly
5964 one conversion is possible, that conversion is applied to the
5965 chosen operand and the converted operand is used in place of
5966 the original operand for the remainder of this section. */
5967 if ((conv2 && !conv2->bad_p
5968 && conv3 && !conv3->bad_p)
5969 || (conv2 && conv2->kind == ck_ambig)
5970 || (conv3 && conv3->kind == ck_ambig))
5972 if (complain & tf_error)
5974 error_at (loc, "operands to %<?:%> have different types "
5975 "%qT and %qT",
5976 arg2_type, arg3_type);
5977 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5978 inform (loc, " and each type can be converted to the other");
5979 else if (conv2 && conv2->kind == ck_ambig)
5980 convert_like (conv2, arg2, complain);
5981 else
5982 convert_like (conv3, arg3, complain);
5984 result = error_mark_node;
5986 else if (conv2 && !conv2->bad_p)
5988 arg2 = convert_like (conv2, arg2, complain);
5989 arg2 = convert_from_reference (arg2);
5990 arg2_type = TREE_TYPE (arg2);
5991 /* Even if CONV2 is a valid conversion, the result of the
5992 conversion may be invalid. For example, if ARG3 has type
5993 "volatile X", and X does not have a copy constructor
5994 accepting a "volatile X&", then even if ARG2 can be
5995 converted to X, the conversion will fail. */
5996 if (error_operand_p (arg2))
5997 result = error_mark_node;
5998 converted = true;
6000 else if (conv3 && !conv3->bad_p)
6002 arg3 = convert_like (conv3, arg3, complain);
6003 arg3 = convert_from_reference (arg3);
6004 arg3_type = TREE_TYPE (arg3);
6005 if (error_operand_p (arg3))
6006 result = error_mark_node;
6007 converted = true;
6010 if (result)
6011 return result;
6013 /* If, after the conversion, both operands have class type,
6014 treat the cv-qualification of both operands as if it were the
6015 union of the cv-qualification of the operands.
6017 The standard is not clear about what to do in this
6018 circumstance. For example, if the first operand has type
6019 "const X" and the second operand has a user-defined
6020 conversion to "volatile X", what is the type of the second
6021 operand after this step? Making it be "const X" (matching
6022 the first operand) seems wrong, as that discards the
6023 qualification without actually performing a copy. Leaving it
6024 as "volatile X" seems wrong as that will result in the
6025 conditional expression failing altogether, even though,
6026 according to this step, the one operand could be converted to
6027 the type of the other. */
6028 if (converted
6029 && CLASS_TYPE_P (arg2_type)
6030 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
6031 arg2_type = arg3_type =
6032 cp_build_qualified_type (arg2_type,
6033 cp_type_quals (arg2_type)
6034 | cp_type_quals (arg3_type));
6037 /* [expr.cond]
6039 If the second and third operands are glvalues of the same value
6040 category and have the same type, the result is of that type and
6041 value category. */
6042 if (((lvalue_p (arg2) && lvalue_p (arg3))
6043 || (xvalue_p (arg2) && xvalue_p (arg3)))
6044 && same_type_p (arg2_type, arg3_type))
6046 result_type = arg2_type;
6047 goto valid_operands;
6050 /* [expr.cond]
6052 Otherwise, the result is an rvalue. If the second and third
6053 operand do not have the same type, and either has (possibly
6054 cv-qualified) class type, overload resolution is used to
6055 determine the conversions (if any) to be applied to the operands
6056 (_over.match.oper_, _over.built_). */
6057 is_glvalue = false;
6058 if (!same_type_p (arg2_type, arg3_type)
6059 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6061 releasing_vec args;
6062 conversion *conv;
6063 bool any_viable_p;
6065 /* Rearrange the arguments so that add_builtin_candidate only has
6066 to know about two args. In build_builtin_candidate, the
6067 arguments are unscrambled. */
6068 args->quick_push (arg2);
6069 args->quick_push (arg3);
6070 args->quick_push (arg1);
6071 add_builtin_candidates (&candidates,
6072 COND_EXPR,
6073 NOP_EXPR,
6074 ovl_op_identifier (false, COND_EXPR),
6075 args,
6076 LOOKUP_NORMAL, complain);
6078 /* [expr.cond]
6080 If the overload resolution fails, the program is
6081 ill-formed. */
6082 candidates = splice_viable (candidates, false, &any_viable_p);
6083 if (!any_viable_p)
6085 if (complain & tf_error)
6086 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6087 arg2_type, arg3_type);
6088 return error_mark_node;
6090 cand = tourney (candidates, complain);
6091 if (!cand)
6093 if (complain & tf_error)
6095 auto_diagnostic_group d;
6096 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, false);
6097 print_z_candidates (loc, candidates);
6099 return error_mark_node;
6102 /* [expr.cond]
6104 Otherwise, the conversions thus determined are applied, and
6105 the converted operands are used in place of the original
6106 operands for the remainder of this section. */
6107 conv = cand->convs[0];
6108 arg1 = convert_like (conv, arg1, complain);
6109 conv = cand->convs[1];
6110 arg2 = convert_like (conv, arg2, complain);
6111 arg2_type = TREE_TYPE (arg2);
6112 conv = cand->convs[2];
6113 arg3 = convert_like (conv, arg3, complain);
6114 arg3_type = TREE_TYPE (arg3);
6117 /* [expr.cond]
6119 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6120 and function-to-pointer (_conv.func_) standard conversions are
6121 performed on the second and third operands.
6123 We need to force the lvalue-to-rvalue conversion here for class types,
6124 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6125 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6126 regions. */
6128 arg2 = force_rvalue (arg2, complain);
6129 if (!CLASS_TYPE_P (arg2_type))
6130 arg2_type = TREE_TYPE (arg2);
6132 arg3 = force_rvalue (arg3, complain);
6133 if (!CLASS_TYPE_P (arg3_type))
6134 arg3_type = TREE_TYPE (arg3);
6136 if (arg2 == error_mark_node || arg3 == error_mark_node)
6137 return error_mark_node;
6139 /* [expr.cond]
6141 After those conversions, one of the following shall hold:
6143 --The second and third operands have the same type; the result is of
6144 that type. */
6145 if (same_type_p (arg2_type, arg3_type))
6146 result_type = arg2_type;
6147 /* [expr.cond]
6149 --The second and third operands have arithmetic or enumeration
6150 type; the usual arithmetic conversions are performed to bring
6151 them to a common type, and the result is of that type. */
6152 else if ((ARITHMETIC_TYPE_P (arg2_type)
6153 || UNSCOPED_ENUM_P (arg2_type))
6154 && (ARITHMETIC_TYPE_P (arg3_type)
6155 || UNSCOPED_ENUM_P (arg3_type)))
6157 /* A conditional expression between a floating-point
6158 type and an integer type should convert the integer type to
6159 the evaluation format of the floating-point type, with
6160 possible excess precision. */
6161 tree eptype2 = arg2_type;
6162 tree eptype3 = arg3_type;
6163 tree eptype;
6164 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6165 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6167 eptype3 = eptype;
6168 if (!semantic_result_type)
6169 semantic_result_type
6170 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6172 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6173 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6175 eptype2 = eptype;
6176 if (!semantic_result_type)
6177 semantic_result_type
6178 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6180 result_type = type_after_usual_arithmetic_conversions (eptype2,
6181 eptype3);
6182 if (result_type == error_mark_node)
6184 tree t1 = eptype2;
6185 tree t2 = eptype3;
6186 if (TREE_CODE (t1) == COMPLEX_TYPE)
6187 t1 = TREE_TYPE (t1);
6188 if (TREE_CODE (t2) == COMPLEX_TYPE)
6189 t2 = TREE_TYPE (t2);
6190 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6191 && SCALAR_FLOAT_TYPE_P (t2)
6192 && (extended_float_type_p (t1)
6193 || extended_float_type_p (t2))
6194 && cp_compare_floating_point_conversion_ranks
6195 (t1, t2) == 3);
6196 if (complain & tf_error)
6197 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6198 "have unordered conversion rank",
6199 eptype2, eptype3);
6200 return error_mark_node;
6202 if (semantic_result_type == error_mark_node)
6204 tree t1 = arg2_type;
6205 tree t2 = arg3_type;
6206 if (TREE_CODE (t1) == COMPLEX_TYPE)
6207 t1 = TREE_TYPE (t1);
6208 if (TREE_CODE (t2) == COMPLEX_TYPE)
6209 t2 = TREE_TYPE (t2);
6210 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6211 && SCALAR_FLOAT_TYPE_P (t2)
6212 && (extended_float_type_p (t1)
6213 || extended_float_type_p (t2))
6214 && cp_compare_floating_point_conversion_ranks
6215 (t1, t2) == 3);
6216 if (complain & tf_error)
6217 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6218 "have unordered conversion rank",
6219 arg2_type, arg3_type);
6220 return error_mark_node;
6223 if (complain & tf_warning)
6224 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6225 "implicit conversion from %qH to %qI to "
6226 "match other result of conditional",
6227 loc);
6229 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6230 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6232 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
6233 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
6234 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6235 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6236 && (DECL_CONTEXT (stripped_orig_arg2)
6237 == DECL_CONTEXT (stripped_orig_arg3)))
6238 /* Two enumerators from the same enumeration can have different
6239 types when the enumeration is still being defined. */;
6240 else if (complain & (cxx_dialect >= cxx26
6241 ? tf_warning_or_error : tf_warning))
6242 emit_diagnostic (cxx_dialect >= cxx26 ? DK_PEDWARN : DK_WARNING,
6243 loc, OPT_Wenum_compare, "enumerated mismatch "
6244 "in conditional expression: %qT vs %qT",
6245 arg2_type, arg3_type);
6246 else if (cxx_dialect >= cxx26)
6247 return error_mark_node;
6249 else if ((((complain & (cxx_dialect >= cxx26
6250 ? tf_warning_or_error : tf_warning))
6251 && warn_deprecated_enum_float_conv)
6252 || (cxx_dialect >= cxx26
6253 && (complain & tf_warning_or_error) == 0))
6254 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6255 && SCALAR_FLOAT_TYPE_P (arg3_type))
6256 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6257 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6259 if (cxx_dialect >= cxx26 && (complain & tf_warning_or_error) == 0)
6260 return error_mark_node;
6261 if (cxx_dialect >= cxx26 && TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6262 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6263 "conditional expression between enumeration type "
6264 "%qT and floating-point type %qT", arg2_type, arg3_type);
6265 else if (cxx_dialect >= cxx26)
6266 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6267 "conditional expression between floating-point type "
6268 "%qT and enumeration type %qT", arg2_type, arg3_type);
6269 else if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6270 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6271 "conditional expression between enumeration type "
6272 "%qT and floating-point type %qT is deprecated",
6273 arg2_type, arg3_type);
6274 else
6275 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6276 "conditional expression between floating-point "
6277 "type %qT and enumeration type %qT is deprecated",
6278 arg2_type, arg3_type);
6280 else if ((extra_warnings || warn_enum_conversion)
6281 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6282 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6283 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6284 && !same_type_p (arg2_type,
6285 type_promotes_to (arg3_type)))))
6287 if (complain & tf_warning)
6289 enum opt_code opt = (warn_enum_conversion
6290 ? OPT_Wenum_conversion
6291 : OPT_Wextra);
6292 warning_at (loc, opt, "enumerated and "
6293 "non-enumerated type in conditional expression");
6297 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6298 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6300 /* [expr.cond]
6302 --The second and third operands have pointer type, or one has
6303 pointer type and the other is a null pointer constant; pointer
6304 conversions (_conv.ptr_) and qualification conversions
6305 (_conv.qual_) are performed to bring them to their composite
6306 pointer type (_expr.rel_). The result is of the composite
6307 pointer type.
6309 --The second and third operands have pointer to member type, or
6310 one has pointer to member type and the other is a null pointer
6311 constant; pointer to member conversions (_conv.mem_) and
6312 qualification conversions (_conv.qual_) are performed to bring
6313 them to a common type, whose cv-qualification shall match the
6314 cv-qualification of either the second or the third operand.
6315 The result is of the common type. */
6316 else if ((null_ptr_cst_p (arg2)
6317 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6318 || (null_ptr_cst_p (arg3)
6319 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6320 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6321 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6322 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6324 result_type = composite_pointer_type (loc,
6325 arg2_type, arg3_type, arg2,
6326 arg3, CPO_CONDITIONAL_EXPR,
6327 complain);
6328 if (result_type == error_mark_node)
6329 return error_mark_node;
6330 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6331 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6334 if (!result_type)
6336 if (complain & tf_error)
6337 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6338 arg2_type, arg3_type);
6339 return error_mark_node;
6342 if (arg2 == error_mark_node || arg3 == error_mark_node)
6343 return error_mark_node;
6345 valid_operands:
6346 if (processing_template_decl && is_glvalue)
6348 /* Let lvalue_kind know this was a glvalue. */
6349 tree arg = (result_type == arg2_type ? arg2 : arg3);
6350 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6353 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
6355 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6356 warn here, because the COND_EXPR will be turned into ARG2. */
6357 if (warn_duplicated_branches
6358 && (complain & tf_warning)
6359 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6360 OEP_ADDRESS_OF_SAME_FIELD)))
6361 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6362 "this condition has identical branches");
6364 /* We can't use result_type below, as fold might have returned a
6365 throw_expr. */
6367 if (!is_glvalue)
6369 /* Expand both sides into the same slot, hopefully the target of
6370 the ?: expression. We used to check for TARGET_EXPRs here,
6371 but now we sometimes wrap them in NOP_EXPRs so the test would
6372 fail. */
6373 if (CLASS_TYPE_P (TREE_TYPE (result)))
6375 result = get_target_expr (result, complain);
6376 /* Tell gimplify_modify_expr_rhs not to strip this in
6377 assignment context: we want both arms to initialize
6378 the same temporary. */
6379 TARGET_EXPR_NO_ELIDE (result) = true;
6381 /* If this expression is an rvalue, but might be mistaken for an
6382 lvalue, we must add a NON_LVALUE_EXPR. */
6383 result = rvalue (result);
6384 if (semantic_result_type)
6385 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6386 result);
6388 else
6390 result = force_paren_expr (result);
6391 gcc_assert (semantic_result_type == NULL_TREE);
6394 return result;
6397 /* OPERAND is an operand to an expression. Perform necessary steps
6398 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6399 returned. */
6401 static tree
6402 prep_operand (tree operand)
6404 if (operand)
6406 if (CLASS_TYPE_P (TREE_TYPE (operand))
6407 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6408 /* Make sure the template type is instantiated now. */
6409 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6412 return operand;
6415 /* True iff CONV represents a conversion sequence which no other can be better
6416 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6417 type (including binding to a reference to the same type). This is stronger
6418 than the standard's "identity" category, which also includes reference
6419 bindings that add cv-qualifiers or change rvalueness. */
6421 static bool
6422 perfect_conversion_p (conversion *conv)
6424 if (CONVERSION_RANK (conv) != cr_identity)
6425 return false;
6426 if (conv->kind == ck_ref_bind)
6428 if (!conv->rvaluedness_matches_p)
6429 return false;
6430 if (!same_type_p (TREE_TYPE (conv->type),
6431 next_conversion (conv)->type))
6432 return false;
6434 if (conv->check_narrowing)
6435 /* Brace elision is imperfect. */
6436 return false;
6437 return true;
6440 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6441 other candidate can be a better match. Since the template/non-template
6442 tiebreaker comes immediately after the conversion comparison in
6443 [over.match.best], a perfect non-template candidate is better than all
6444 templates. */
6446 static bool
6447 perfect_candidate_p (z_candidate *cand)
6449 if (cand->viable < 1)
6450 return false;
6451 /* CWG1402 makes an implicitly deleted move op worse than other
6452 candidates. */
6453 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6454 && move_fn_p (cand->fn))
6455 return false;
6456 int len = cand->num_convs;
6457 for (int i = 0; i < len; ++i)
6458 if (!perfect_conversion_p (cand->convs[i]))
6459 return false;
6460 if (conversion *conv = cand->second_conv)
6461 if (!perfect_conversion_p (conv))
6462 return false;
6463 return true;
6466 /* True iff one of CAND's argument conversions is missing. */
6468 static bool
6469 missing_conversion_p (const z_candidate *cand)
6471 for (unsigned i = 0; i < cand->num_convs; ++i)
6473 conversion *conv = cand->convs[i];
6474 if (!conv)
6475 return true;
6476 if (conv->kind == ck_deferred_bad)
6478 /* We don't know whether this conversion is outright invalid or
6479 just bad, so conservatively assume it's missing. */
6480 gcc_checking_assert (conv->bad_p);
6481 return true;
6484 return false;
6487 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6488 OVERLOAD) to the CANDIDATES, returning an updated list of
6489 CANDIDATES. The ARGS are the arguments provided to the call;
6490 if FIRST_ARG is non-null it is the implicit object argument,
6491 otherwise the first element of ARGS is used if needed. The
6492 EXPLICIT_TARGS are explicit template arguments provided.
6493 TEMPLATE_ONLY is true if only template functions should be
6494 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6495 add_function_candidate. */
6497 static void
6498 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6499 tree return_type,
6500 tree explicit_targs, bool template_only,
6501 tree conversion_path, tree access_path,
6502 int flags,
6503 struct z_candidate **candidates,
6504 tsubst_flags_t complain)
6506 tree ctype;
6507 const vec<tree, va_gc> *non_static_args;
6508 bool check_list_ctor = false;
6509 bool check_converting = false;
6510 unification_kind_t strict;
6511 tree ne_fns = NULL_TREE;
6513 if (!fns)
6514 return;
6516 /* Precalculate special handling of constructors and conversion ops. */
6517 tree fn = OVL_FIRST (fns);
6518 if (DECL_CONV_FN_P (fn))
6520 check_list_ctor = false;
6521 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6522 if (flags & LOOKUP_NO_CONVERSION)
6523 /* We're doing return_type(x). */
6524 strict = DEDUCE_CONV;
6525 else
6526 /* We're doing x.operator return_type(). */
6527 strict = DEDUCE_EXACT;
6528 /* [over.match.funcs] For conversion functions, the function
6529 is considered to be a member of the class of the implicit
6530 object argument for the purpose of defining the type of
6531 the implicit object parameter. */
6532 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6534 else
6536 if (DECL_CONSTRUCTOR_P (fn))
6538 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6539 /* For list-initialization we consider explicit constructors
6540 and complain if one is chosen. */
6541 check_converting
6542 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6543 == LOOKUP_ONLYCONVERTING);
6545 strict = DEDUCE_CALL;
6546 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6549 /* P2468: Check if operator== is a rewrite target with first operand
6550 (*args)[0]; for now just do the lookups. */
6551 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6552 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6554 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6555 if (DECL_CLASS_SCOPE_P (fn))
6557 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6558 1, tf_none);
6559 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6560 ne_fns = NULL_TREE;
6561 else
6562 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6564 else
6566 tree context = decl_namespace_context (fn);
6567 ne_fns = lookup_qualified_name (context, ne_name, LOOK_want::NORMAL,
6568 /*complain*/false);
6569 if (ne_fns == error_mark_node
6570 || !is_overloaded_fn (ne_fns))
6571 ne_fns = NULL_TREE;
6575 if (first_arg)
6576 non_static_args = args;
6577 else
6578 /* Delay creating the implicit this parameter until it is needed. */
6579 non_static_args = NULL;
6581 bool seen_strictly_viable = any_strictly_viable (*candidates);
6582 /* If there's a non-template perfect match, we don't need to consider
6583 templates. So check non-templates first. This optimization is only
6584 really needed for the defaulted copy constructor of tuple and the like
6585 (96926), but it seems like we might as well enable it more generally. */
6586 bool seen_perfect = false;
6587 enum { templates, non_templates, either } which = either;
6588 if (template_only)
6589 which = templates;
6590 else /*if (flags & LOOKUP_DEFAULTED)*/
6591 which = non_templates;
6593 /* Template candidates that we'll potentially ignore if the
6594 perfect candidate optimization succeeds. */
6595 z_candidate *ignored_template_cands = nullptr;
6597 /* During overload resolution, we first consider each function under the
6598 assumption that we'll eventually find a strictly viable candidate.
6599 This allows us to circumvent our defacto behavior when checking
6600 argument conversions and shortcut consideration of the candidate
6601 upon encountering the first bad conversion. If this assumption
6602 turns out to be false, and all candidates end up being non-strictly
6603 viable, then we reconsider such candidates under the defacto behavior.
6604 This trick is important for pruning member function overloads according
6605 to their const/ref-qualifiers (since all 'this' conversions are at
6606 worst bad) without breaking -fpermissive. */
6607 z_candidate *bad_cands = nullptr;
6608 bool shortcut_bad_convs = true;
6610 again:
6611 for (tree fn : lkp_range (fns))
6613 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6615 if (template_only)
6616 add_ignored_candidate (candidates, fn);
6617 continue;
6619 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6621 add_ignored_candidate (&ignored_template_cands, fn);
6622 continue;
6624 if ((check_converting && DECL_NONCONVERTING_P (fn))
6625 || (check_list_ctor && !is_list_ctor (fn)))
6627 add_ignored_candidate (candidates, fn);
6628 continue;
6631 tree fn_first_arg = NULL_TREE;
6632 const vec<tree, va_gc> *fn_args = args;
6634 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn))
6636 /* Figure out where the object arg comes from. If this
6637 function is a non-static member and we didn't get an
6638 implicit object argument, move it out of args. */
6639 if (first_arg == NULL_TREE)
6641 unsigned int ix;
6642 tree arg;
6643 vec<tree, va_gc> *tempvec;
6644 vec_alloc (tempvec, args->length () - 1);
6645 for (ix = 1; args->iterate (ix, &arg); ++ix)
6646 tempvec->quick_push (arg);
6647 non_static_args = tempvec;
6648 first_arg = (*args)[0];
6651 fn_first_arg = first_arg;
6652 fn_args = non_static_args;
6655 /* Don't bother reversing an operator with two identical parameters. */
6656 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6658 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6659 if (same_type_p (TREE_VALUE (parmlist),
6660 TREE_VALUE (TREE_CHAIN (parmlist))))
6661 continue;
6664 /* When considering reversed operator==, if there's a corresponding
6665 operator!= in the same scope, it's not a rewrite target. */
6666 if (ne_fns)
6668 bool found = false;
6669 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6670 if (0 && !ne.using_p ()
6671 && DECL_NAMESPACE_SCOPE_P (fn)
6672 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6673 /* ??? This kludge excludes inline namespace members for the H
6674 test in spaceship-eq15.C, but I don't see why we would want
6675 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6676 else if (fns_correspond (fn, *ne))
6678 found = true;
6679 break;
6681 if (found)
6682 continue;
6685 if (TREE_CODE (fn) == TEMPLATE_DECL)
6686 add_template_candidate (candidates,
6688 ctype,
6689 explicit_targs,
6690 fn_first_arg,
6691 fn_args,
6692 return_type,
6693 access_path,
6694 conversion_path,
6695 flags,
6696 strict,
6697 shortcut_bad_convs,
6698 complain);
6699 else
6701 add_function_candidate (candidates,
6703 ctype,
6704 fn_first_arg,
6705 fn_args,
6706 access_path,
6707 conversion_path,
6708 flags,
6709 NULL,
6710 shortcut_bad_convs,
6711 complain);
6712 if (perfect_candidate_p (*candidates))
6713 seen_perfect = true;
6716 z_candidate *cand = *candidates;
6717 if (cand->viable == 1)
6718 seen_strictly_viable = true;
6720 if (cand->viable == -1
6721 && shortcut_bad_convs
6722 && missing_conversion_p (cand))
6724 /* This candidate has been tentatively marked non-strictly viable,
6725 and we didn't compute all argument conversions for it (having
6726 stopped at the first bad conversion). Move it to BAD_CANDS to
6727 to fully reconsider later if we don't find any strictly viable
6728 candidates. */
6729 if (complain & (tf_error | tf_conv))
6731 *candidates = cand->next;
6732 cand->next = bad_cands;
6733 bad_cands = cand;
6735 else
6736 /* But if we're in a SFINAE context, just mark this candidate as
6737 unviable outright and avoid potentially reconsidering it.
6738 This is safe to do because in a SFINAE context, performing a bad
6739 conversion is always an error (even with -fpermissive), so a
6740 non-strictly viable candidate is effectively unviable anyway. */
6741 cand->viable = 0;
6744 if (which == non_templates && !seen_perfect)
6746 which = templates;
6747 ignored_template_cands = nullptr;
6748 goto again;
6750 else if (which == templates
6751 && !seen_strictly_viable
6752 && shortcut_bad_convs
6753 && bad_cands)
6755 /* None of the candidates are strictly viable, so consider again those
6756 functions in BAD_CANDS, this time without shortcutting bad conversions
6757 so that all their argument conversions are computed. */
6758 which = either;
6759 fns = NULL_TREE;
6760 for (z_candidate *cand = bad_cands; cand; cand = cand->next)
6762 tree fn = cand->fn;
6763 if (tree ti = cand->template_decl)
6764 fn = TI_TEMPLATE (ti);
6765 fns = ovl_make (fn, fns);
6767 shortcut_bad_convs = false;
6768 bad_cands = nullptr;
6769 goto again;
6772 if (complain & tf_error)
6774 /* Remember any omitted candidates; we may want to print all candidates
6775 as part of overload resolution failure diagnostics. */
6776 for (z_candidate *omitted_cands : { ignored_template_cands, bad_cands })
6778 z_candidate **omitted_cands_tail = &omitted_cands;
6779 while (*omitted_cands_tail)
6780 omitted_cands_tail = &(*omitted_cands_tail)->next;
6781 *omitted_cands_tail = *candidates;
6782 *candidates = omitted_cands;
6787 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6788 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6790 static int
6791 op_is_ordered (tree_code code)
6793 switch (code)
6795 // 5. b @= a
6796 case MODIFY_EXPR:
6797 return (flag_strong_eval_order > 1 ? -1 : 0);
6799 // 6. a[b]
6800 case ARRAY_REF:
6801 return (flag_strong_eval_order > 1 ? 1 : 0);
6803 // 1. a.b
6804 // Not overloadable (yet).
6805 // 2. a->b
6806 // Only one argument.
6807 // 3. a->*b
6808 case MEMBER_REF:
6809 // 7. a << b
6810 case LSHIFT_EXPR:
6811 // 8. a >> b
6812 case RSHIFT_EXPR:
6813 // a && b
6814 // Predates P0145R3.
6815 case TRUTH_ANDIF_EXPR:
6816 // a || b
6817 // Predates P0145R3.
6818 case TRUTH_ORIF_EXPR:
6819 // a , b
6820 // Predates P0145R3.
6821 case COMPOUND_EXPR:
6822 return (flag_strong_eval_order ? 1 : 0);
6824 default:
6825 return 0;
6829 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6830 operator indicated by CODE/CODE2. This function calls itself recursively to
6831 handle C++20 rewritten comparison operator candidates. Returns NULL_TREE
6832 upon success, and error_mark_node if something went wrong that prevented
6833 us from performing overload resolution (e.g. ambiguous member name lookup).
6835 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6836 overloads to consider. This parameter is used when instantiating a
6837 dependent operator expression and has the same structure as
6838 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6840 static tree
6841 add_operator_candidates (z_candidate **candidates,
6842 tree_code code, tree_code code2,
6843 vec<tree, va_gc> *arglist, tree lookups,
6844 int flags, tsubst_flags_t complain)
6846 z_candidate *start_candidates = *candidates;
6847 bool ismodop = code2 != ERROR_MARK;
6848 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6850 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6851 rewrite from, and also when we're looking for the e.g. < operator to use
6852 on the result of <=>. In the latter case, we don't want the flag set in
6853 the candidate, we just want to suppress looking for rewrites. */
6854 bool rewritten = (flags & LOOKUP_REWRITTEN);
6855 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6856 flags &= ~LOOKUP_REWRITTEN;
6858 bool memonly = false;
6859 switch (code)
6861 /* =, ->, [], () must be non-static member functions. */
6862 case MODIFY_EXPR:
6863 if (code2 != NOP_EXPR)
6864 break;
6865 /* FALLTHRU */
6866 case COMPONENT_REF:
6867 case ARRAY_REF:
6868 memonly = true;
6869 break;
6871 default:
6872 break;
6875 /* Add namespace-scope operators to the list of functions to
6876 consider. */
6877 if (!memonly)
6879 tree fns;
6880 if (!lookups)
6881 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6882 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6883 expression, and LOOKUPS is the result of stage 1 name lookup. */
6884 else if (tree found = purpose_member (fnname, lookups))
6885 fns = TREE_VALUE (found);
6886 else
6887 fns = NULL_TREE;
6888 fns = lookup_arg_dependent (fnname, fns, arglist);
6889 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6890 NULL_TREE, false, NULL_TREE, NULL_TREE,
6891 flags, candidates, complain);
6894 /* Add class-member operators to the candidate set. */
6895 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6896 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6897 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6898 if (CLASS_TYPE_P (arg1_type))
6900 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6901 if (fns == error_mark_node)
6902 return error_mark_node;
6903 if (fns)
6905 if (code == ARRAY_REF)
6907 vec<tree,va_gc> *restlist = make_tree_vector ();
6908 for (unsigned i = 1; i < nargs; ++i)
6909 vec_safe_push (restlist, (*arglist)[i]);
6910 z_candidate *save_cand = *candidates;
6911 add_candidates (BASELINK_FUNCTIONS (fns),
6912 (*arglist)[0], restlist, NULL_TREE,
6913 NULL_TREE, false,
6914 BASELINK_BINFO (fns),
6915 BASELINK_ACCESS_BINFO (fns),
6916 flags, candidates, complain);
6917 /* Release the vec if we didn't add a candidate that uses it. */
6918 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6919 if (c->args == restlist)
6921 restlist = NULL;
6922 break;
6924 release_tree_vector (restlist);
6926 else
6927 add_candidates (BASELINK_FUNCTIONS (fns),
6928 NULL_TREE, arglist, NULL_TREE,
6929 NULL_TREE, false,
6930 BASELINK_BINFO (fns),
6931 BASELINK_ACCESS_BINFO (fns),
6932 flags, candidates, complain);
6935 /* Per [over.match.oper]3.2, if no operand has a class type, then
6936 only non-member functions that have type T1 or reference to
6937 cv-qualified-opt T1 for the first argument, if the first argument
6938 has an enumeration type, or T2 or reference to cv-qualified-opt
6939 T2 for the second argument, if the second argument has an
6940 enumeration type. Filter out those that don't match. */
6941 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6943 struct z_candidate **candp, **next;
6945 for (candp = candidates; *candp != start_candidates; candp = next)
6947 unsigned i;
6948 z_candidate *cand = *candp;
6949 next = &cand->next;
6951 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6953 for (i = 0; i < nargs; ++i)
6955 tree parmtype = TREE_VALUE (parmlist);
6956 tree argtype = unlowered_expr_type ((*arglist)[i]);
6958 if (TYPE_REF_P (parmtype))
6959 parmtype = TREE_TYPE (parmtype);
6960 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6961 && (same_type_ignoring_top_level_qualifiers_p
6962 (argtype, parmtype)))
6963 break;
6965 parmlist = TREE_CHAIN (parmlist);
6968 /* No argument has an appropriate type, so remove this
6969 candidate function from the list. */
6970 if (i == nargs)
6972 *candp = cand->next;
6973 next = candp;
6978 if (!rewritten)
6980 /* The standard says to rewrite built-in candidates, too,
6981 but there's no point. */
6982 add_builtin_candidates (candidates, code, code2, fnname, arglist,
6983 flags, complain);
6985 /* Maybe add C++20 rewritten comparison candidates. */
6986 tree_code rewrite_code = ERROR_MARK;
6987 if (cxx_dialect >= cxx20
6988 && nargs == 2
6989 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6990 switch (code)
6992 case LT_EXPR:
6993 case LE_EXPR:
6994 case GT_EXPR:
6995 case GE_EXPR:
6996 case SPACESHIP_EXPR:
6997 rewrite_code = SPACESHIP_EXPR;
6998 break;
7000 case NE_EXPR:
7001 case EQ_EXPR:
7002 rewrite_code = EQ_EXPR;
7003 break;
7005 default:;
7008 if (rewrite_code)
7010 tree r;
7011 flags |= LOOKUP_REWRITTEN;
7012 if (rewrite_code != code)
7014 /* Add rewritten candidates in same order. */
7015 r = add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7016 arglist, lookups, flags, complain);
7017 if (r == error_mark_node)
7018 return error_mark_node;
7021 z_candidate *save_cand = *candidates;
7023 /* Add rewritten candidates in reverse order. */
7024 flags |= LOOKUP_REVERSED;
7025 vec<tree,va_gc> *revlist = make_tree_vector ();
7026 revlist->quick_push ((*arglist)[1]);
7027 revlist->quick_push ((*arglist)[0]);
7028 r = add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7029 revlist, lookups, flags, complain);
7030 if (r == error_mark_node)
7031 return error_mark_node;
7033 /* Release the vec if we didn't add a candidate that uses it. */
7034 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7035 if (c->args == revlist)
7037 revlist = NULL;
7038 break;
7040 release_tree_vector (revlist);
7044 return NULL_TREE;
7047 tree
7048 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
7049 tree arg1, tree arg2, tree arg3, tree lookups,
7050 tree *overload, tsubst_flags_t complain)
7052 struct z_candidate *candidates = 0, *cand;
7053 releasing_vec arglist;
7054 tree result = NULL_TREE;
7055 bool result_valid_p = false;
7056 enum tree_code code2 = ERROR_MARK;
7057 enum tree_code code_orig_arg1 = ERROR_MARK;
7058 enum tree_code code_orig_arg2 = ERROR_MARK;
7059 bool strict_p;
7060 bool any_viable_p;
7062 auto_cond_timevar tv (TV_OVERLOAD);
7064 if (error_operand_p (arg1)
7065 || error_operand_p (arg2)
7066 || error_operand_p (arg3))
7067 return error_mark_node;
7069 conversion_obstack_sentinel cos;
7071 bool ismodop = code == MODIFY_EXPR;
7072 if (ismodop)
7074 code2 = TREE_CODE (arg3);
7075 arg3 = NULL_TREE;
7078 tree arg1_type = unlowered_expr_type (arg1);
7079 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
7081 arg1 = prep_operand (arg1);
7083 switch (code)
7085 case NEW_EXPR:
7086 case VEC_NEW_EXPR:
7087 case VEC_DELETE_EXPR:
7088 case DELETE_EXPR:
7089 /* Use build_operator_new_call and build_op_delete_call instead. */
7090 gcc_unreachable ();
7092 case CALL_EXPR:
7093 /* Use build_op_call instead. */
7094 gcc_unreachable ();
7096 case TRUTH_ORIF_EXPR:
7097 case TRUTH_ANDIF_EXPR:
7098 case TRUTH_AND_EXPR:
7099 case TRUTH_OR_EXPR:
7100 /* These are saved for the sake of warn_logical_operator. */
7101 code_orig_arg1 = TREE_CODE (arg1);
7102 code_orig_arg2 = TREE_CODE (arg2);
7103 break;
7104 case GT_EXPR:
7105 case LT_EXPR:
7106 case GE_EXPR:
7107 case LE_EXPR:
7108 case EQ_EXPR:
7109 case NE_EXPR:
7110 /* These are saved for the sake of maybe_warn_bool_compare. */
7111 code_orig_arg1 = TREE_CODE (arg1_type);
7112 code_orig_arg2 = TREE_CODE (arg2_type);
7113 break;
7115 default:
7116 break;
7119 arg2 = prep_operand (arg2);
7120 arg3 = prep_operand (arg3);
7122 if (code == COND_EXPR)
7123 /* Use build_conditional_expr instead. */
7124 gcc_unreachable ();
7125 else if (! OVERLOAD_TYPE_P (arg1_type)
7126 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7127 goto builtin;
7129 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7131 arg2 = integer_zero_node;
7132 arg2_type = integer_type_node;
7135 arglist->quick_push (arg1);
7136 if (arg2 != NULL_TREE)
7137 arglist->quick_push (arg2);
7138 if (arg3 != NULL_TREE)
7139 arglist->quick_push (arg3);
7141 result = add_operator_candidates (&candidates, code, code2, arglist,
7142 lookups, flags, complain);
7143 if (result == error_mark_node)
7144 return error_mark_node;
7146 switch (code)
7148 case COMPOUND_EXPR:
7149 case ADDR_EXPR:
7150 /* For these, the built-in candidates set is empty
7151 [over.match.oper]/3. We don't want non-strict matches
7152 because exact matches are always possible with built-in
7153 operators. The built-in candidate set for COMPONENT_REF
7154 would be empty too, but since there are no such built-in
7155 operators, we accept non-strict matches for them. */
7156 strict_p = true;
7157 break;
7159 default:
7160 strict_p = false;
7161 break;
7164 candidates = splice_viable (candidates, strict_p, &any_viable_p);
7165 if (!any_viable_p)
7167 switch (code)
7169 case POSTINCREMENT_EXPR:
7170 case POSTDECREMENT_EXPR:
7171 /* Don't try anything fancy if we're not allowed to produce
7172 errors. */
7173 if (!(complain & tf_error))
7174 return error_mark_node;
7176 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7177 distinguish between prefix and postfix ++ and
7178 operator++() was used for both, so we allow this with
7179 -fpermissive. */
7180 else
7182 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7183 const char *msg = (flag_permissive)
7184 ? G_("no %<%D(int)%> declared for postfix %qs,"
7185 " trying prefix operator instead")
7186 : G_("no %<%D(int)%> declared for postfix %qs");
7187 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7190 if (!flag_permissive)
7191 return error_mark_node;
7193 if (code == POSTINCREMENT_EXPR)
7194 code = PREINCREMENT_EXPR;
7195 else
7196 code = PREDECREMENT_EXPR;
7197 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7198 NULL_TREE, lookups, overload, complain);
7199 break;
7201 /* The caller will deal with these. */
7202 case ADDR_EXPR:
7203 case COMPOUND_EXPR:
7204 case COMPONENT_REF:
7205 case CO_AWAIT_EXPR:
7206 result = NULL_TREE;
7207 result_valid_p = true;
7208 break;
7210 default:
7211 if (complain & tf_error)
7213 /* If one of the arguments of the operator represents
7214 an invalid use of member function pointer, try to report
7215 a meaningful error ... */
7216 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7217 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7218 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7219 /* We displayed the error message. */;
7220 else
7222 /* ... Otherwise, report the more generic
7223 "no matching operator found" error */
7224 auto_diagnostic_group d;
7225 op_error (loc, code, code2, arg1, arg2, arg3, false);
7226 print_z_candidates (loc, candidates);
7229 result = error_mark_node;
7230 break;
7233 else
7235 cand = tourney (candidates, complain);
7236 if (cand == 0)
7238 if (complain & tf_error)
7240 auto_diagnostic_group d;
7241 op_error (loc, code, code2, arg1, arg2, arg3, true);
7242 print_z_candidates (loc, candidates);
7244 result = error_mark_node;
7245 if (overload)
7246 *overload = error_mark_node;
7248 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7250 if (overload)
7251 *overload = cand->fn;
7253 if (resolve_args (arglist, complain) == NULL)
7254 result = error_mark_node;
7255 else
7257 tsubst_flags_t ocomplain = complain;
7258 if (cand->rewritten ())
7259 /* We'll wrap this call in another one. */
7260 ocomplain &= ~tf_decltype;
7261 if (cand->reversed ())
7263 /* We swapped these in add_candidate, swap them back now. */
7264 std::swap (cand->convs[0], cand->convs[1]);
7265 if (cand->fn == current_function_decl)
7266 warning_at (loc, 0, "in C++20 this comparison calls the "
7267 "current function recursively with reversed "
7268 "arguments");
7270 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7273 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7274 /* There won't be a CALL_EXPR. */;
7275 else if (result && result != error_mark_node)
7277 tree call = extract_call_expr (result);
7278 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7280 /* Specify evaluation order as per P0145R2. */
7281 CALL_EXPR_ORDERED_ARGS (call) = false;
7282 switch (op_is_ordered (code))
7284 case -1:
7285 CALL_EXPR_REVERSE_ARGS (call) = true;
7286 break;
7288 case 1:
7289 CALL_EXPR_ORDERED_ARGS (call) = true;
7290 break;
7292 default:
7293 break;
7297 /* If this was a C++20 rewritten comparison, adjust the result. */
7298 if (cand->rewritten ())
7300 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7301 if (overload)
7302 *overload = NULL_TREE;
7303 switch (code)
7305 case EQ_EXPR:
7306 gcc_checking_assert (cand->reversed ());
7307 gcc_fallthrough ();
7308 case NE_EXPR:
7309 if (result == error_mark_node)
7311 /* If a rewritten operator== candidate is selected by
7312 overload resolution for an operator @, its return type
7313 shall be cv bool.... */
7314 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7316 if (complain & tf_error)
7318 auto_diagnostic_group d;
7319 error_at (loc, "return type of %qD is not %qs",
7320 cand->fn, "bool");
7321 inform (loc, "used as rewritten candidate for "
7322 "comparison of %qT and %qT",
7323 arg1_type, arg2_type);
7325 result = error_mark_node;
7327 else if (code == NE_EXPR)
7328 /* !(y == x) or !(x == y) */
7329 result = build1_loc (loc, TRUTH_NOT_EXPR,
7330 boolean_type_node, result);
7331 break;
7333 /* If a rewritten operator<=> candidate is selected by
7334 overload resolution for an operator @, x @ y is
7335 interpreted as 0 @ (y <=> x) if the selected candidate is
7336 a synthesized candidate with reversed order of parameters,
7337 or (x <=> y) @ 0 otherwise, using the selected rewritten
7338 operator<=> candidate. */
7339 case SPACESHIP_EXPR:
7340 if (!cand->reversed ())
7341 /* We're in the build_new_op call below for an outer
7342 reversed call; we don't need to do anything more. */
7343 break;
7344 gcc_fallthrough ();
7345 case LT_EXPR:
7346 case LE_EXPR:
7347 case GT_EXPR:
7348 case GE_EXPR:
7350 tree lhs = result;
7351 tree rhs = integer_zero_node;
7352 if (cand->reversed ())
7353 std::swap (lhs, rhs);
7354 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7355 result = build_new_op (loc, code,
7356 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7357 lhs, rhs, NULL_TREE, lookups,
7358 NULL, complain);
7360 break;
7362 default:
7363 gcc_unreachable ();
7367 /* In an expression of the form `a[]' where cand->fn
7368 which is operator[] turns out to be a static member function,
7369 `a' is none-the-less evaluated. */
7370 if (code == ARRAY_REF)
7371 result = keep_unused_object_arg (result, arg1, cand->fn);
7373 else
7375 /* Give any warnings we noticed during overload resolution. */
7376 if (cand->warnings && (complain & tf_warning))
7378 struct candidate_warning *w;
7379 for (w = cand->warnings; w; w = w->next)
7380 joust (cand, w->loser, 1, complain);
7383 /* Check for comparison of different enum types. */
7384 switch (code)
7386 case GT_EXPR:
7387 case LT_EXPR:
7388 case GE_EXPR:
7389 case LE_EXPR:
7390 case EQ_EXPR:
7391 case NE_EXPR:
7392 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7393 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7394 && (TYPE_MAIN_VARIANT (arg1_type)
7395 != TYPE_MAIN_VARIANT (arg2_type)))
7397 if (cxx_dialect >= cxx26
7398 && (complain & tf_warning_or_error) == 0)
7399 result = error_mark_node;
7400 else if (cxx_dialect >= cxx26 || (complain & tf_warning))
7401 emit_diagnostic (cxx_dialect >= cxx26
7402 ? DK_PEDWARN : DK_WARNING,
7403 loc, OPT_Wenum_compare,
7404 "comparison between %q#T and %q#T",
7405 arg1_type, arg2_type);
7407 break;
7408 default:
7409 break;
7412 /* "If a built-in candidate is selected by overload resolution, the
7413 operands of class type are converted to the types of the
7414 corresponding parameters of the selected operation function,
7415 except that the second standard conversion sequence of a
7416 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7417 conversion *conv = cand->convs[0];
7418 if (conv->user_conv_p)
7420 conv = strip_standard_conversion (conv);
7421 arg1 = convert_like (conv, arg1, complain);
7424 if (arg2)
7426 conv = cand->convs[1];
7427 if (conv->user_conv_p)
7429 conv = strip_standard_conversion (conv);
7430 arg2 = convert_like (conv, arg2, complain);
7434 if (arg3)
7436 conv = cand->convs[2];
7437 if (conv->user_conv_p)
7439 conv = strip_standard_conversion (conv);
7440 arg3 = convert_like (conv, arg3, complain);
7446 if (result || result_valid_p)
7447 return result;
7449 builtin:
7450 switch (code)
7452 case MODIFY_EXPR:
7453 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7455 case INDIRECT_REF:
7456 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7458 case TRUTH_ANDIF_EXPR:
7459 case TRUTH_ORIF_EXPR:
7460 case TRUTH_AND_EXPR:
7461 case TRUTH_OR_EXPR:
7462 if ((complain & tf_warning) && !processing_template_decl)
7463 warn_logical_operator (loc, code, boolean_type_node,
7464 code_orig_arg1, arg1,
7465 code_orig_arg2, arg2);
7466 /* Fall through. */
7467 case GT_EXPR:
7468 case LT_EXPR:
7469 case GE_EXPR:
7470 case LE_EXPR:
7471 case EQ_EXPR:
7472 case NE_EXPR:
7473 if ((complain & tf_warning)
7474 && ((code_orig_arg1 == BOOLEAN_TYPE)
7475 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7476 maybe_warn_bool_compare (loc, code, arg1, arg2);
7477 if (complain & tf_warning && warn_tautological_compare)
7478 warn_tautological_cmp (loc, code, arg1, arg2);
7479 /* Fall through. */
7480 case SPACESHIP_EXPR:
7481 case PLUS_EXPR:
7482 case MINUS_EXPR:
7483 case MULT_EXPR:
7484 case TRUNC_DIV_EXPR:
7485 case MAX_EXPR:
7486 case MIN_EXPR:
7487 case LSHIFT_EXPR:
7488 case RSHIFT_EXPR:
7489 case TRUNC_MOD_EXPR:
7490 case BIT_AND_EXPR:
7491 case BIT_IOR_EXPR:
7492 case BIT_XOR_EXPR:
7493 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7495 case UNARY_PLUS_EXPR:
7496 case NEGATE_EXPR:
7497 case BIT_NOT_EXPR:
7498 case TRUTH_NOT_EXPR:
7499 case PREINCREMENT_EXPR:
7500 case POSTINCREMENT_EXPR:
7501 case PREDECREMENT_EXPR:
7502 case POSTDECREMENT_EXPR:
7503 case REALPART_EXPR:
7504 case IMAGPART_EXPR:
7505 case ABS_EXPR:
7506 case CO_AWAIT_EXPR:
7507 return cp_build_unary_op (code, arg1, false, complain);
7509 case ARRAY_REF:
7510 return cp_build_array_ref (input_location, arg1, arg2, complain);
7512 case MEMBER_REF:
7513 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7514 RO_ARROW_STAR,
7515 complain),
7516 arg2, complain);
7518 /* The caller will deal with these. */
7519 case ADDR_EXPR:
7520 case COMPONENT_REF:
7521 case COMPOUND_EXPR:
7522 return NULL_TREE;
7524 default:
7525 gcc_unreachable ();
7527 return NULL_TREE;
7530 /* Build a new call to operator[]. This may change ARGS. */
7532 tree
7533 build_op_subscript (const op_location_t &loc, tree obj,
7534 vec<tree, va_gc> **args, tree *overload,
7535 tsubst_flags_t complain)
7537 struct z_candidate *candidates = 0, *cand;
7538 tree fns, first_mem_arg = NULL_TREE;
7539 bool any_viable_p;
7540 tree result = NULL_TREE;
7542 auto_cond_timevar tv (TV_OVERLOAD);
7544 obj = mark_lvalue_use (obj);
7546 if (error_operand_p (obj))
7547 return error_mark_node;
7549 tree type = TREE_TYPE (obj);
7551 obj = prep_operand (obj);
7553 if (TYPE_BINFO (type))
7555 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7556 1, complain);
7557 if (fns == error_mark_node)
7558 return error_mark_node;
7560 else
7561 fns = NULL_TREE;
7563 if (args != NULL && *args != NULL)
7565 *args = resolve_args (*args, complain);
7566 if (*args == NULL)
7567 return error_mark_node;
7570 conversion_obstack_sentinel cos;
7572 if (fns)
7574 first_mem_arg = obj;
7576 add_candidates (BASELINK_FUNCTIONS (fns),
7577 first_mem_arg, *args, NULL_TREE,
7578 NULL_TREE, false,
7579 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7580 LOOKUP_NORMAL, &candidates, complain);
7583 /* Be strict here because if we choose a bad conversion candidate, the
7584 errors we get won't mention the call context. */
7585 candidates = splice_viable (candidates, true, &any_viable_p);
7586 if (!any_viable_p)
7588 if (complain & tf_error)
7590 auto_diagnostic_group d;
7591 error ("no match for call to %<%T::operator[] (%A)%>",
7592 TREE_TYPE (obj), build_tree_list_vec (*args));
7593 print_z_candidates (loc, candidates);
7595 result = error_mark_node;
7597 else
7599 cand = tourney (candidates, complain);
7600 if (cand == 0)
7602 if (complain & tf_error)
7604 auto_diagnostic_group d;
7605 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7606 TREE_TYPE (obj), build_tree_list_vec (*args));
7607 print_z_candidates (loc, candidates);
7609 result = error_mark_node;
7611 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7612 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7613 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7615 if (overload)
7616 *overload = cand->fn;
7617 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7618 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7619 /* There won't be a CALL_EXPR. */;
7620 else if (result && result != error_mark_node)
7622 tree call = extract_call_expr (result);
7623 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7625 /* Specify evaluation order as per P0145R2. */
7626 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7629 /* In an expression of the form `a[]' where cand->fn
7630 which is operator[] turns out to be a static member function,
7631 `a' is none-the-less evaluated. */
7632 result = keep_unused_object_arg (result, obj, cand->fn);
7634 else
7635 gcc_unreachable ();
7638 return result;
7641 /* CALL was returned by some call-building function; extract the actual
7642 CALL_EXPR from any bits that have been tacked on, e.g. by
7643 convert_from_reference. */
7645 tree
7646 extract_call_expr (tree call)
7648 while (TREE_CODE (call) == COMPOUND_EXPR)
7649 call = TREE_OPERAND (call, 1);
7650 if (REFERENCE_REF_P (call))
7651 call = TREE_OPERAND (call, 0);
7652 if (TREE_CODE (call) == TARGET_EXPR)
7653 call = TARGET_EXPR_INITIAL (call);
7654 if (cxx_dialect >= cxx20)
7655 switch (TREE_CODE (call))
7657 /* C++20 rewritten comparison operators. */
7658 case TRUTH_NOT_EXPR:
7659 call = TREE_OPERAND (call, 0);
7660 break;
7661 case LT_EXPR:
7662 case LE_EXPR:
7663 case GT_EXPR:
7664 case GE_EXPR:
7665 case SPACESHIP_EXPR:
7667 tree op0 = TREE_OPERAND (call, 0);
7668 if (integer_zerop (op0))
7669 call = TREE_OPERAND (call, 1);
7670 else
7671 call = op0;
7673 break;
7674 default:;
7677 if (TREE_CODE (call) != CALL_EXPR
7678 && TREE_CODE (call) != AGGR_INIT_EXPR
7679 && call != error_mark_node)
7680 return NULL_TREE;
7681 return call;
7684 /* Returns true if FN has two parameters, of which the second has type
7685 size_t. */
7687 static bool
7688 second_parm_is_size_t (tree fn)
7690 tree t = FUNCTION_ARG_CHAIN (fn);
7691 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7692 return false;
7693 t = TREE_CHAIN (t);
7694 if (t == void_list_node)
7695 return true;
7696 return false;
7699 /* True if T, an allocation function, has std::align_val_t as its second
7700 argument. */
7702 bool
7703 aligned_allocation_fn_p (tree t)
7705 if (!aligned_new_threshold)
7706 return false;
7708 tree a = FUNCTION_ARG_CHAIN (t);
7709 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7712 /* True if T is std::destroying_delete_t. */
7714 static bool
7715 std_destroying_delete_t_p (tree t)
7717 return (TYPE_CONTEXT (t) == std_node
7718 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7721 /* A deallocation function with at least two parameters whose second parameter
7722 type is of type std::destroying_delete_t is a destroying operator delete. A
7723 destroying operator delete shall be a class member function named operator
7724 delete. [ Note: Array deletion cannot use a destroying operator
7725 delete. --end note ] */
7727 tree
7728 destroying_delete_p (tree t)
7730 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7731 if (!a || !TREE_CHAIN (a))
7732 return NULL_TREE;
7733 tree type = TREE_VALUE (TREE_CHAIN (a));
7734 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7737 struct dealloc_info
7739 bool sized;
7740 bool aligned;
7741 tree destroying;
7744 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7745 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7746 non-null, also set *DI. */
7748 static bool
7749 usual_deallocation_fn_p (tree t, dealloc_info *di)
7751 if (di) *di = dealloc_info();
7753 /* A template instance is never a usual deallocation function,
7754 regardless of its signature. */
7755 if (TREE_CODE (t) == TEMPLATE_DECL
7756 || primary_template_specialization_p (t))
7757 return false;
7759 /* A usual deallocation function is a deallocation function whose parameters
7760 after the first are
7761 - optionally, a parameter of type std::destroying_delete_t, then
7762 - optionally, a parameter of type std::size_t, then
7763 - optionally, a parameter of type std::align_val_t. */
7764 bool global = DECL_NAMESPACE_SCOPE_P (t);
7765 tree chain = FUNCTION_ARG_CHAIN (t);
7766 if (chain && destroying_delete_p (t))
7768 if (di) di->destroying = TREE_VALUE (chain);
7769 chain = TREE_CHAIN (chain);
7771 if (chain
7772 && (!global || flag_sized_deallocation)
7773 && same_type_p (TREE_VALUE (chain), size_type_node))
7775 if (di) di->sized = true;
7776 chain = TREE_CHAIN (chain);
7778 if (chain && aligned_new_threshold
7779 && same_type_p (TREE_VALUE (chain), align_type_node))
7781 if (di) di->aligned = true;
7782 chain = TREE_CHAIN (chain);
7784 return (chain == void_list_node);
7787 /* Just return whether FN is a usual deallocation function. */
7789 bool
7790 usual_deallocation_fn_p (tree fn)
7792 return usual_deallocation_fn_p (fn, NULL);
7795 /* Build a call to operator delete. This has to be handled very specially,
7796 because the restrictions on what signatures match are different from all
7797 other call instances. For a normal delete, only a delete taking (void *)
7798 or (void *, size_t) is accepted. For a placement delete, only an exact
7799 match with the placement new is accepted.
7801 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7802 ADDR is the pointer to be deleted.
7803 SIZE is the size of the memory block to be deleted.
7804 GLOBAL_P is true if the delete-expression should not consider
7805 class-specific delete operators.
7806 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7808 If this call to "operator delete" is being generated as part to
7809 deallocate memory allocated via a new-expression (as per [expr.new]
7810 which requires that if the initialization throws an exception then
7811 we call a deallocation function), then ALLOC_FN is the allocation
7812 function. */
7814 tree
7815 build_op_delete_call (enum tree_code code, tree addr, tree size,
7816 bool global_p, tree placement,
7817 tree alloc_fn, tsubst_flags_t complain)
7819 tree fn = NULL_TREE;
7820 tree fns, fnname, type, t;
7821 dealloc_info di_fn = { };
7823 if (addr == error_mark_node)
7824 return error_mark_node;
7826 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7828 fnname = ovl_op_identifier (false, code);
7830 if (CLASS_TYPE_P (type)
7831 && COMPLETE_TYPE_P (complete_type (type))
7832 && !global_p)
7833 /* In [class.free]
7835 If the result of the lookup is ambiguous or inaccessible, or if
7836 the lookup selects a placement deallocation function, the
7837 program is ill-formed.
7839 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7841 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7842 if (fns == error_mark_node)
7843 return error_mark_node;
7845 else
7846 fns = NULL_TREE;
7848 if (fns == NULL_TREE)
7849 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7851 /* Strip const and volatile from addr. */
7852 tree oaddr = addr;
7853 addr = cp_convert (ptr_type_node, addr, complain);
7855 tree excluded_destroying = NULL_TREE;
7857 if (placement)
7859 /* "A declaration of a placement deallocation function matches the
7860 declaration of a placement allocation function if it has the same
7861 number of parameters and, after parameter transformations (8.3.5),
7862 all parameter types except the first are identical."
7864 So we build up the function type we want and ask instantiate_type
7865 to get it for us. */
7866 t = FUNCTION_ARG_CHAIN (alloc_fn);
7867 t = tree_cons (NULL_TREE, ptr_type_node, t);
7868 t = build_function_type (void_type_node, t);
7870 fn = instantiate_type (t, fns, tf_none);
7871 if (fn == error_mark_node)
7872 return NULL_TREE;
7874 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7876 /* "If the lookup finds the two-parameter form of a usual deallocation
7877 function (3.7.4.2) and that function, considered as a placement
7878 deallocation function, would have been selected as a match for the
7879 allocation function, the program is ill-formed." */
7880 if (second_parm_is_size_t (fn))
7882 const char *const msg1
7883 = G_("exception cleanup for this placement new selects "
7884 "non-placement %<operator delete%>");
7885 const char *const msg2
7886 = G_("%qD is a usual (non-placement) deallocation "
7887 "function in C++14 (or with %<-fsized-deallocation%>)");
7889 /* But if the class has an operator delete (void *), then that is
7890 the usual deallocation function, so we shouldn't complain
7891 about using the operator delete (void *, size_t). */
7892 if (DECL_CLASS_SCOPE_P (fn))
7893 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7895 if (usual_deallocation_fn_p (elt)
7896 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7897 goto ok;
7899 /* Before C++14 a two-parameter global deallocation function is
7900 always a placement deallocation function, but warn if
7901 -Wc++14-compat. */
7902 else if (!flag_sized_deallocation)
7904 if (complain & tf_warning)
7906 auto_diagnostic_group d;
7907 if (warning (OPT_Wc__14_compat, msg1))
7908 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7910 goto ok;
7913 if (complain & tf_warning_or_error)
7915 auto_diagnostic_group d;
7916 if (permerror (input_location, msg1))
7918 /* Only mention C++14 for namespace-scope delete. */
7919 if (DECL_NAMESPACE_SCOPE_P (fn))
7920 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7921 else
7922 inform (DECL_SOURCE_LOCATION (fn),
7923 "%qD is a usual (non-placement) deallocation "
7924 "function", fn);
7927 else
7928 return error_mark_node;
7929 ok:;
7932 else
7933 /* "Any non-placement deallocation function matches a non-placement
7934 allocation function. If the lookup finds a single matching
7935 deallocation function, that function will be called; otherwise, no
7936 deallocation function will be called." */
7937 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7939 dealloc_info di_elt;
7940 if (usual_deallocation_fn_p (elt, &di_elt))
7942 /* If we're called for an EH cleanup in a new-expression, we can't
7943 use a destroying delete; the exception was thrown before the
7944 object was constructed. */
7945 if (alloc_fn && di_elt.destroying)
7947 excluded_destroying = elt;
7948 continue;
7951 if (!fn)
7953 fn = elt;
7954 di_fn = di_elt;
7955 continue;
7958 /* -- If any of the deallocation functions is a destroying
7959 operator delete, all deallocation functions that are not
7960 destroying operator deletes are eliminated from further
7961 consideration. */
7962 if (di_elt.destroying != di_fn.destroying)
7964 if (di_elt.destroying)
7966 fn = elt;
7967 di_fn = di_elt;
7969 continue;
7972 /* -- If the type has new-extended alignment, a function with a
7973 parameter of type std::align_val_t is preferred; otherwise a
7974 function without such a parameter is preferred. If exactly one
7975 preferred function is found, that function is selected and the
7976 selection process terminates. If more than one preferred
7977 function is found, all non-preferred functions are eliminated
7978 from further consideration. */
7979 if (aligned_new_threshold)
7981 bool want_align = type_has_new_extended_alignment (type);
7982 if (di_elt.aligned != di_fn.aligned)
7984 if (want_align == di_elt.aligned)
7986 fn = elt;
7987 di_fn = di_elt;
7989 continue;
7993 /* -- If the deallocation functions have class scope, the one
7994 without a parameter of type std::size_t is selected. */
7995 bool want_size;
7996 if (DECL_CLASS_SCOPE_P (fn))
7997 want_size = false;
7999 /* -- If the type is complete and if, for the second alternative
8000 (delete array) only, the operand is a pointer to a class type
8001 with a non-trivial destructor or a (possibly multi-dimensional)
8002 array thereof, the function with a parameter of type std::size_t
8003 is selected.
8005 -- Otherwise, it is unspecified whether a deallocation function
8006 with a parameter of type std::size_t is selected. */
8007 else
8009 want_size = COMPLETE_TYPE_P (type);
8010 if (code == VEC_DELETE_EXPR
8011 && !TYPE_VEC_NEW_USES_COOKIE (type))
8012 /* We need a cookie to determine the array size. */
8013 want_size = false;
8015 gcc_assert (di_fn.sized != di_elt.sized);
8016 if (want_size == di_elt.sized)
8018 fn = elt;
8019 di_fn = di_elt;
8024 /* If we have a matching function, call it. */
8025 if (fn)
8027 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8029 /* If the FN is a member function, make sure that it is
8030 accessible. */
8031 if (BASELINK_P (fns))
8032 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
8033 complain);
8035 /* Core issue 901: It's ok to new a type with deleted delete. */
8036 if (DECL_DELETED_FN (fn) && alloc_fn)
8037 return NULL_TREE;
8039 tree ret;
8040 if (placement)
8042 /* The placement args might not be suitable for overload
8043 resolution at this point, so build the call directly. */
8044 int nargs = call_expr_nargs (placement);
8045 tree *argarray = XALLOCAVEC (tree, nargs);
8046 int i;
8047 argarray[0] = addr;
8048 for (i = 1; i < nargs; i++)
8049 argarray[i] = CALL_EXPR_ARG (placement, i);
8050 if (!mark_used (fn, complain) && !(complain & tf_error))
8051 return error_mark_node;
8052 ret = build_cxx_call (fn, nargs, argarray, complain);
8054 else
8056 tree destroying = di_fn.destroying;
8057 if (destroying)
8059 /* Strip const and volatile from addr but retain the type of the
8060 object. */
8061 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
8062 rtype = cv_unqualified (rtype);
8063 rtype = TYPE_POINTER_TO (rtype);
8064 addr = cp_convert (rtype, oaddr, complain);
8065 destroying = build_functional_cast (input_location,
8066 destroying, NULL_TREE,
8067 complain);
8070 releasing_vec args;
8071 args->quick_push (addr);
8072 if (destroying)
8073 args->quick_push (destroying);
8074 if (di_fn.sized)
8075 args->quick_push (size);
8076 if (di_fn.aligned)
8078 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
8079 args->quick_push (al);
8081 ret = cp_build_function_call_vec (fn, &args, complain);
8084 /* Set this flag for all callers of this function. In addition to
8085 delete-expressions, this is called for deallocating coroutine state;
8086 treat that as an implicit delete-expression. This is also called for
8087 the delete if the constructor throws in a new-expression, and for a
8088 deleting destructor (which implements a delete-expression). */
8089 /* But leave this flag off for destroying delete to avoid wrong
8090 assumptions in the optimizers. */
8091 tree call = extract_call_expr (ret);
8092 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
8093 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
8095 return ret;
8098 /* If there's only a destroying delete that we can't use because the
8099 object isn't constructed yet, and we used global new, use global
8100 delete as well. */
8101 if (excluded_destroying
8102 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
8103 return build_op_delete_call (code, addr, size, true, placement,
8104 alloc_fn, complain);
8106 /* [expr.new]
8108 If no unambiguous matching deallocation function can be found,
8109 propagating the exception does not cause the object's memory to
8110 be freed. */
8111 if (alloc_fn)
8113 if ((complain & tf_warning)
8114 && !placement)
8116 bool w = warning (0,
8117 "no corresponding deallocation function for %qD",
8118 alloc_fn);
8119 if (w && excluded_destroying)
8120 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8121 "delete %qD cannot be used to release the allocated memory"
8122 " if the initialization throws because the object is not "
8123 "constructed yet", excluded_destroying);
8125 return NULL_TREE;
8128 if (complain & tf_error)
8129 error ("no suitable %<operator %s%> for %qT",
8130 OVL_OP_INFO (false, code)->name, type);
8131 return error_mark_node;
8134 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8135 in the diagnostics.
8137 If ISSUE_ERROR is true, then issue an error about the access, followed
8138 by a note showing the declaration. Otherwise, just show the note.
8140 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8141 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8142 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8143 would be because DECL was private). If not using NO_ACCESS_REASON,
8144 then it must be ak_none, and the access failure reason will be
8145 figured out by looking at the protection of DECL. */
8147 void
8148 complain_about_access (tree decl, tree diag_decl, tree diag_location,
8149 bool issue_error, access_kind no_access_reason)
8151 /* If we have not already figured out why DECL is inaccessible... */
8152 if (no_access_reason == ak_none)
8154 /* Examine the access of DECL to find out why. */
8155 if (TREE_PRIVATE (decl))
8156 no_access_reason = ak_private;
8157 else if (TREE_PROTECTED (decl))
8158 no_access_reason = ak_protected;
8161 /* Now generate an error message depending on calculated access. */
8162 if (no_access_reason == ak_private)
8164 if (issue_error)
8165 error ("%q#D is private within this context", diag_decl);
8166 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8168 else if (no_access_reason == ak_protected)
8170 if (issue_error)
8171 error ("%q#D is protected within this context", diag_decl);
8172 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8174 /* Couldn't figure out why DECL is inaccesible, so just say it's
8175 inaccessible. */
8176 else
8178 if (issue_error)
8179 error ("%q#D is inaccessible within this context", diag_decl);
8180 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8184 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8185 bitwise or of LOOKUP_* values. If any errors are warnings are
8186 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8187 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8188 to NULL. */
8190 static tree
8191 build_temp (tree expr, tree type, int flags,
8192 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8194 int savew, savee;
8196 *diagnostic_kind = DK_UNSPECIFIED;
8198 /* If the source is a packed field, calling the copy constructor will require
8199 binding the field to the reference parameter to the copy constructor, and
8200 we'll end up with an infinite loop. If we can use a bitwise copy, then
8201 do that now. */
8202 if ((lvalue_kind (expr) & clk_packed)
8203 && CLASS_TYPE_P (TREE_TYPE (expr))
8204 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8205 return get_target_expr (expr, complain);
8207 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8208 But it turns out to be a subexpression, so perform temporary
8209 materialization now. */
8210 if (TREE_CODE (expr) == CALL_EXPR
8211 && CLASS_TYPE_P (type)
8212 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8213 expr = build_cplus_new (type, expr, complain);
8215 savew = warningcount + werrorcount, savee = errorcount;
8216 releasing_vec args (make_tree_vector_single (expr));
8217 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8218 &args, type, flags, complain);
8219 if (warningcount + werrorcount > savew)
8220 *diagnostic_kind = DK_WARNING;
8221 else if (errorcount > savee)
8222 *diagnostic_kind = DK_ERROR;
8223 return expr;
8226 /* Get any location for EXPR, falling back to input_location.
8228 If the result is in a system header and is the virtual location for
8229 a token coming from the expansion of a macro, unwind it to the
8230 location of the expansion point of the macro (e.g. to avoid the
8231 diagnostic being suppressed for expansions of NULL where "NULL" is
8232 in a system header). */
8234 static location_t
8235 get_location_for_expr_unwinding_for_system_header (tree expr)
8237 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8238 loc = expansion_point_location_if_in_system_header (loc);
8239 return loc;
8242 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
8243 Also handle a subset of zero as null warnings.
8244 EXPR is implicitly converted to type TOTYPE.
8245 FN and ARGNUM are used for diagnostics. */
8247 static void
8248 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8250 /* Issue warnings about peculiar, but valid, uses of NULL. */
8251 if (TREE_CODE (totype) != BOOLEAN_TYPE
8252 && ARITHMETIC_TYPE_P (totype)
8253 && null_node_p (expr))
8255 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8256 if (fn)
8258 auto_diagnostic_group d;
8259 if (warning_at (loc, OPT_Wconversion_null,
8260 "passing NULL to non-pointer argument %P of %qD",
8261 argnum, fn))
8262 inform (get_fndecl_argument_location (fn, argnum),
8263 " declared here");
8265 else
8266 warning_at (loc, OPT_Wconversion_null,
8267 "converting to non-pointer type %qT from NULL", totype);
8270 /* Issue warnings if "false" is converted to a NULL pointer */
8271 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8272 && TYPE_PTR_P (totype))
8274 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8275 if (fn)
8277 auto_diagnostic_group d;
8278 if (warning_at (loc, OPT_Wconversion_null,
8279 "converting %<false%> to pointer type for argument "
8280 "%P of %qD", argnum, fn))
8281 inform (get_fndecl_argument_location (fn, argnum),
8282 " declared here");
8284 else
8285 warning_at (loc, OPT_Wconversion_null,
8286 "converting %<false%> to pointer type %qT", totype);
8288 /* Handle zero as null pointer warnings for cases other
8289 than EQ_EXPR and NE_EXPR */
8290 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8291 && null_ptr_cst_p (expr))
8293 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8294 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8298 /* We gave a diagnostic during a conversion. If this was in the second
8299 standard conversion sequence of a user-defined conversion sequence, say
8300 which user-defined conversion. */
8302 static void
8303 maybe_print_user_conv_context (conversion *convs)
8305 if (convs->user_conv_p)
8306 for (conversion *t = convs; t; t = next_conversion (t))
8307 if (t->kind == ck_user)
8309 print_z_candidate (0, N_(" after user-defined conversion:"),
8310 t->cand);
8311 break;
8315 /* Locate the parameter with the given index within FNDECL.
8316 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8317 Return the location of the FNDECL itself if there are problems. */
8319 location_t
8320 get_fndecl_argument_location (tree fndecl, int argnum)
8322 /* The locations of implicitly-declared functions are likely to be
8323 more meaningful than those of their parameters. */
8324 if (DECL_ARTIFICIAL (fndecl))
8325 return DECL_SOURCE_LOCATION (fndecl);
8327 int i;
8328 tree param;
8330 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8331 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8332 i < argnum && param;
8333 i++, param = TREE_CHAIN (param))
8336 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8337 return the location of FNDECL. */
8338 if (param == NULL)
8339 return DECL_SOURCE_LOCATION (fndecl);
8341 return DECL_SOURCE_LOCATION (param);
8344 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8345 within its declaration (or the fndecl itself if something went
8346 wrong). */
8348 void
8349 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
8351 if (fn)
8352 inform (get_fndecl_argument_location (fn, argnum),
8353 " initializing argument %P of %qD", argnum, fn);
8356 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8357 the conversion, EXPR is the expression we're converting. */
8359 static void
8360 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8362 if (cxx_dialect >= cxx20)
8363 return;
8365 tree type = TREE_TYPE (expr);
8366 type = strip_pointer_operator (type);
8368 if (TREE_CODE (type) != ARRAY_TYPE
8369 || TYPE_DOMAIN (type) == NULL_TREE)
8370 return;
8372 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8373 pedwarn (loc, OPT_Wc__20_extensions,
8374 "conversions to arrays of unknown bound "
8375 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8378 /* We call this recursively in convert_like_internal. */
8379 static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8380 tsubst_flags_t);
8382 /* Perform the conversions in CONVS on the expression EXPR. FN and
8383 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8384 indicates the `this' argument of a method. INNER is nonzero when
8385 being called to continue a conversion chain. It is negative when a
8386 reference binding will be applied, positive otherwise. If
8387 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8388 conversions will be emitted if appropriate. If C_CAST_P is true,
8389 this conversion is coming from a C-style cast; in that case,
8390 conversions to inaccessible bases are permitted. */
8392 static tree
8393 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8394 bool issue_conversion_warnings, bool c_cast_p,
8395 bool nested_p, tsubst_flags_t complain)
8397 tree totype = convs->type;
8398 diagnostic_t diag_kind;
8399 int flags;
8400 location_t loc = cp_expr_loc_or_input_loc (expr);
8402 if (convs->bad_p && !(complain & tf_error))
8403 return error_mark_node;
8405 if (convs->bad_p
8406 && convs->kind != ck_user
8407 && convs->kind != ck_list
8408 && convs->kind != ck_ambig
8409 && (convs->kind != ck_ref_bind
8410 || (convs->user_conv_p && next_conversion (convs)->bad_p))
8411 && (convs->kind != ck_rvalue
8412 || SCALAR_TYPE_P (totype))
8413 && convs->kind != ck_base)
8415 int complained = 0;
8416 conversion *t = convs;
8418 /* Give a helpful error if this is bad because of excess braces. */
8419 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8420 && SCALAR_TYPE_P (totype)
8421 && CONSTRUCTOR_NELTS (expr) > 0
8422 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8424 complained = permerror (loc, "too many braces around initializer "
8425 "for %qT", totype);
8426 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8427 && CONSTRUCTOR_NELTS (expr) == 1)
8428 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8431 /* Give a helpful error if this is bad because a conversion to bool
8432 from std::nullptr_t requires direct-initialization. */
8433 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8434 && TREE_CODE (totype) == BOOLEAN_TYPE)
8435 complained = permerror (loc, "converting to %qH from %qI requires "
8436 "direct-initialization",
8437 totype, TREE_TYPE (expr));
8439 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8440 && SCALAR_FLOAT_TYPE_P (totype)
8441 && (extended_float_type_p (TREE_TYPE (expr))
8442 || extended_float_type_p (totype)))
8443 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8444 totype))
8446 case 2:
8447 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8448 "converting to %qH from %qI with greater "
8449 "conversion rank", totype, TREE_TYPE (expr)))
8450 complained = 1;
8451 else if (!complained)
8452 complained = -1;
8453 break;
8454 case 3:
8455 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8456 "converting to %qH from %qI with unordered "
8457 "conversion rank", totype, TREE_TYPE (expr)))
8458 complained = 1;
8459 else if (!complained)
8460 complained = -1;
8461 break;
8462 default:
8463 break;
8466 for (; t ; t = next_conversion (t))
8468 if (t->kind == ck_user && t->cand->reason)
8470 auto_diagnostic_group d;
8471 complained = permerror (loc, "invalid user-defined conversion "
8472 "from %qH to %qI", TREE_TYPE (expr),
8473 totype);
8474 if (complained)
8475 print_z_candidate (loc, N_("candidate is:"), t->cand);
8476 expr = convert_like (t, expr, fn, argnum,
8477 /*issue_conversion_warnings=*/false,
8478 /*c_cast_p=*/false, /*nested_p=*/true,
8479 complain);
8481 else if (t->kind == ck_user || !t->bad_p)
8483 expr = convert_like (t, expr, fn, argnum,
8484 /*issue_conversion_warnings=*/false,
8485 /*c_cast_p=*/false, /*nested_p=*/true,
8486 complain);
8487 if (t->bad_p)
8488 complained = 1;
8489 break;
8491 else if (t->kind == ck_ambig)
8492 return convert_like (t, expr, fn, argnum,
8493 /*issue_conversion_warnings=*/false,
8494 /*c_cast_p=*/false, /*nested_p=*/true,
8495 complain);
8496 else if (t->kind == ck_identity)
8497 break;
8499 if (!complained && expr != error_mark_node)
8501 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8502 gcc_rich_location richloc (loc, &label);
8503 complained = permerror (&richloc,
8504 "invalid conversion from %qH to %qI",
8505 TREE_TYPE (expr), totype);
8507 if (convs->kind == ck_ref_bind)
8508 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8509 LOOKUP_NORMAL, NULL_TREE,
8510 complain);
8511 else
8512 expr = cp_convert (totype, expr, complain);
8513 if (complained == 1)
8514 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8515 return expr;
8518 if (issue_conversion_warnings && (complain & tf_warning))
8519 conversion_null_warnings (totype, expr, fn, argnum);
8521 switch (convs->kind)
8523 case ck_user:
8525 struct z_candidate *cand = convs->cand;
8527 if (cand == NULL)
8528 /* We chose the surrogate function from add_conv_candidate, now we
8529 actually need to build the conversion. */
8530 cand = build_user_type_conversion_1 (totype, expr,
8531 LOOKUP_NO_CONVERSION, complain);
8533 tree convfn = cand->fn;
8535 /* When converting from an init list we consider explicit
8536 constructors, but actually trying to call one is an error. */
8537 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8538 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8539 /* Unless this is for direct-list-initialization. */
8540 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8541 /* And in C++98 a default constructor can't be explicit. */
8542 && cxx_dialect >= cxx11)
8544 if (!(complain & tf_error))
8545 return error_mark_node;
8546 location_t loc = location_of (expr);
8547 if (CONSTRUCTOR_NELTS (expr) == 0
8548 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8550 auto_diagnostic_group d;
8551 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8552 "would use explicit constructor %qD",
8553 totype, convfn))
8555 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8556 convfn);
8557 inform (loc, "in C++11 and above a default constructor "
8558 "can be explicit");
8561 else
8563 auto_diagnostic_group d;
8564 error ("converting to %qT from initializer list would use "
8565 "explicit constructor %qD", totype, convfn);
8566 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8567 convfn);
8571 /* If we're initializing from {}, it's value-initialization. */
8572 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8573 && CONSTRUCTOR_NELTS (expr) == 0
8574 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8575 && !processing_template_decl)
8577 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8578 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8579 return error_mark_node;
8580 expr = build_value_init (totype, complain);
8581 expr = get_target_expr (expr, complain);
8582 if (expr != error_mark_node)
8584 TARGET_EXPR_LIST_INIT_P (expr) = true;
8585 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8587 return expr;
8590 /* We don't know here whether EXPR is being used as an lvalue or
8591 rvalue, but we know it's read. */
8592 mark_exp_read (expr);
8594 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8595 any more UDCs. */
8596 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8597 complain);
8599 /* If this is a constructor or a function returning an aggr type,
8600 we need to build up a TARGET_EXPR. */
8601 if (DECL_CONSTRUCTOR_P (convfn))
8603 expr = build_cplus_new (totype, expr, complain);
8605 /* Remember that this was list-initialization. */
8606 if (convs->check_narrowing && expr != error_mark_node)
8607 TARGET_EXPR_LIST_INIT_P (expr) = true;
8610 return expr;
8612 case ck_identity:
8613 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8615 int nelts = CONSTRUCTOR_NELTS (expr);
8616 if (nelts == 0)
8617 expr = build_value_init (totype, complain);
8618 else if (nelts == 1)
8619 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8620 else
8621 gcc_unreachable ();
8623 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8624 /*read_p=*/true, UNKNOWN_LOCATION,
8625 /*reject_builtin=*/true);
8627 if (type_unknown_p (expr))
8628 expr = instantiate_type (totype, expr, complain);
8629 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8630 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8631 if (expr == null_node
8632 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8633 /* If __null has been converted to an integer type, we do not want to
8634 continue to warn about uses of EXPR as an integer, rather than as a
8635 pointer. */
8636 expr = build_int_cst (totype, 0);
8637 return expr;
8638 case ck_ambig:
8639 /* We leave bad_p off ck_ambig because overload resolution considers
8640 it valid, it just fails when we try to perform it. So we need to
8641 check complain here, too. */
8642 if (complain & tf_error)
8644 /* Call build_user_type_conversion again for the error. */
8645 int flags = (convs->need_temporary_p
8646 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8647 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8648 gcc_assert (seen_error ());
8649 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8651 return error_mark_node;
8653 case ck_list:
8655 /* Conversion to std::initializer_list<T>. */
8656 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8657 unsigned len = CONSTRUCTOR_NELTS (expr);
8658 tree array;
8660 if (tree init = maybe_init_list_as_array (elttype, expr))
8662 elttype = cp_build_qualified_type
8663 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8664 array = build_array_of_n_type (elttype, len);
8665 array = build_vec_init_expr (array, init, complain);
8666 array = get_target_expr (array);
8667 array = cp_build_addr_expr (array, complain);
8669 else if (len)
8671 tree val; unsigned ix;
8673 tree new_ctor = build_constructor (init_list_type_node, NULL);
8675 /* Convert all the elements. */
8676 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8678 tree sub = convert_like (convs->u.list[ix], val, fn,
8679 argnum, false, false,
8680 /*nested_p=*/true, complain);
8681 if (sub == error_mark_node)
8682 return sub;
8683 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8684 && !check_narrowing (TREE_TYPE (sub), val, complain))
8685 return error_mark_node;
8686 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8687 NULL_TREE, sub);
8688 if (!TREE_CONSTANT (sub))
8689 TREE_CONSTANT (new_ctor) = false;
8691 /* Build up the array. */
8692 elttype = cp_build_qualified_type
8693 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8694 array = build_array_of_n_type (elttype, len);
8695 array = finish_compound_literal (array, new_ctor, complain);
8696 /* This is dubious now, should be blessed by P2752. */
8697 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
8698 array = cp_build_addr_expr (array, complain);
8700 else
8701 array = nullptr_node;
8703 array = cp_convert (build_pointer_type (elttype), array, complain);
8704 if (array == error_mark_node)
8705 return error_mark_node;
8707 /* Build up the initializer_list object. Note: fail gracefully
8708 if the object cannot be completed because, for example, no
8709 definition is provided (c++/80956). */
8710 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8711 if (!totype)
8712 return error_mark_node;
8713 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8714 vec<constructor_elt, va_gc> *vec = NULL;
8715 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8716 field = next_aggregate_field (DECL_CHAIN (field));
8717 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8718 tree new_ctor = build_constructor (totype, vec);
8719 return get_target_expr (new_ctor, complain);
8722 case ck_aggr:
8723 if (TREE_CODE (totype) == COMPLEX_TYPE)
8725 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8726 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8727 real = perform_implicit_conversion (TREE_TYPE (totype),
8728 real, complain);
8729 imag = perform_implicit_conversion (TREE_TYPE (totype),
8730 imag, complain);
8731 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8732 return expr;
8734 expr = reshape_init (totype, expr, complain);
8735 expr = get_target_expr (digest_init (totype, expr, complain),
8736 complain);
8737 if (expr != error_mark_node)
8738 TARGET_EXPR_LIST_INIT_P (expr) = true;
8739 return expr;
8741 default:
8742 break;
8745 conversion *nc = next_conversion (convs);
8746 if (convs->kind == ck_ref_bind && nc->kind == ck_qual
8747 && !convs->need_temporary_p)
8748 /* direct_reference_binding might have inserted a ck_qual under
8749 this ck_ref_bind for the benefit of conversion sequence ranking.
8750 Don't actually perform that conversion. */
8751 nc = next_conversion (nc);
8753 expr = convert_like (nc, expr, fn, argnum,
8754 convs->kind == ck_ref_bind
8755 ? issue_conversion_warnings : false,
8756 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8757 if (expr == error_mark_node)
8758 return error_mark_node;
8760 switch (convs->kind)
8762 case ck_rvalue:
8763 expr = decay_conversion (expr, complain);
8764 if (expr == error_mark_node)
8766 if (complain & tf_error)
8768 auto_diagnostic_group d;
8769 maybe_print_user_conv_context (convs);
8770 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8772 return error_mark_node;
8775 if (! MAYBE_CLASS_TYPE_P (totype))
8776 return expr;
8778 /* Don't introduce copies when passing arguments along to the inherited
8779 constructor. */
8780 if (current_function_decl
8781 && flag_new_inheriting_ctors
8782 && DECL_INHERITED_CTOR (current_function_decl))
8783 return expr;
8785 if (TREE_CODE (expr) == TARGET_EXPR
8786 && TARGET_EXPR_LIST_INIT_P (expr))
8787 /* Copy-list-initialization doesn't actually involve a copy. */
8788 return expr;
8790 /* Fall through. */
8791 case ck_base:
8792 if (convs->kind == ck_base && !convs->need_temporary_p)
8794 /* We are going to bind a reference directly to a base-class
8795 subobject of EXPR. */
8796 /* Build an expression for `*((base*) &expr)'. */
8797 expr = convert_to_base (expr, totype,
8798 !c_cast_p, /*nonnull=*/true, complain);
8799 return expr;
8802 /* Copy-initialization where the cv-unqualified version of the source
8803 type is the same class as, or a derived class of, the class of the
8804 destination [is treated as direct-initialization]. [dcl.init] */
8805 flags = LOOKUP_NORMAL;
8806 /* This conversion is being done in the context of a user-defined
8807 conversion (i.e. the second step of copy-initialization), so
8808 don't allow any more. */
8809 if (convs->user_conv_p)
8810 flags |= LOOKUP_NO_CONVERSION;
8811 /* We might be performing a conversion of the argument
8812 to the user-defined conversion, i.e., not a conversion of the
8813 result of the user-defined conversion. In which case we skip
8814 explicit constructors. */
8815 if (convs->copy_init_p)
8816 flags |= LOOKUP_ONLYCONVERTING;
8817 expr = build_temp (expr, totype, flags, &diag_kind, complain);
8818 if (diag_kind && complain)
8820 auto_diagnostic_group d;
8821 maybe_print_user_conv_context (convs);
8822 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8825 return build_cplus_new (totype, expr, complain);
8827 case ck_ref_bind:
8829 tree ref_type = totype;
8831 if (convs->bad_p && !next_conversion (convs)->bad_p)
8833 tree extype = TREE_TYPE (expr);
8834 auto_diagnostic_group d;
8835 if (TYPE_REF_IS_RVALUE (ref_type)
8836 && lvalue_p (expr))
8837 error_at (loc, "cannot bind rvalue reference of type %qH to "
8838 "lvalue of type %qI", totype, extype);
8839 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8840 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8842 conversion *next = next_conversion (convs);
8843 if (next->kind == ck_std)
8845 next = next_conversion (next);
8846 error_at (loc, "cannot bind non-const lvalue reference of "
8847 "type %qH to a value of type %qI",
8848 totype, next->type);
8850 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8851 error_at (loc, "cannot bind non-const lvalue reference of "
8852 "type %qH to an rvalue of type %qI", totype, extype);
8853 else // extype is volatile
8854 error_at (loc, "cannot bind lvalue reference of type "
8855 "%qH to an rvalue of type %qI", totype,
8856 extype);
8858 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8860 /* If we're converting from T[] to T[N], don't talk
8861 about discarding qualifiers. (Converting from T[N] to
8862 T[] is allowed by P0388R4.) */
8863 if (TREE_CODE (extype) == ARRAY_TYPE
8864 && TYPE_DOMAIN (extype) == NULL_TREE
8865 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8866 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8867 error_at (loc, "cannot bind reference of type %qH to %qI "
8868 "due to different array bounds", totype, extype);
8869 else
8870 error_at (loc, "binding reference of type %qH to %qI "
8871 "discards qualifiers", totype, extype);
8873 else
8874 gcc_unreachable ();
8875 maybe_print_user_conv_context (convs);
8876 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8878 return error_mark_node;
8880 else if (complain & tf_warning)
8881 maybe_warn_array_conv (loc, convs, expr);
8883 /* If necessary, create a temporary.
8885 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8886 that need temporaries, even when their types are reference
8887 compatible with the type of reference being bound, so the
8888 upcoming call to cp_build_addr_expr doesn't fail. */
8889 if (convs->need_temporary_p
8890 || TREE_CODE (expr) == CONSTRUCTOR
8891 || TREE_CODE (expr) == VA_ARG_EXPR)
8893 /* Otherwise, a temporary of type "cv1 T1" is created and
8894 initialized from the initializer expression using the rules
8895 for a non-reference copy-initialization (8.5). */
8897 tree type = TREE_TYPE (ref_type);
8898 cp_lvalue_kind lvalue = lvalue_kind (expr);
8900 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8901 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8902 && !TYPE_REF_IS_RVALUE (ref_type))
8904 /* If the reference is volatile or non-const, we
8905 cannot create a temporary. */
8906 if (complain & tf_error)
8908 if (lvalue & clk_bitfield)
8909 error_at (loc, "cannot bind bit-field %qE to %qT",
8910 expr, ref_type);
8911 else if (lvalue & clk_packed)
8912 error_at (loc, "cannot bind packed field %qE to %qT",
8913 expr, ref_type);
8914 else
8915 error_at (loc, "cannot bind rvalue %qE to %qT",
8916 expr, ref_type);
8918 return error_mark_node;
8920 /* If the source is a packed field, and we must use a copy
8921 constructor, then building the target expr will require
8922 binding the field to the reference parameter to the
8923 copy constructor, and we'll end up with an infinite
8924 loop. If we can use a bitwise copy, then we'll be
8925 OK. */
8926 if ((lvalue & clk_packed)
8927 && CLASS_TYPE_P (type)
8928 && type_has_nontrivial_copy_init (type))
8930 error_at (loc, "cannot bind packed field %qE to %qT",
8931 expr, ref_type);
8932 return error_mark_node;
8934 if (lvalue & clk_bitfield)
8936 expr = convert_bitfield_to_declared_type (expr);
8937 expr = fold_convert (type, expr);
8940 /* Creating &TARGET_EXPR<> in a template would break when
8941 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8942 instead. This can happen even when there's no class
8943 involved, e.g., when converting an integer to a reference
8944 type. */
8945 if (processing_template_decl)
8946 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8947 expr = build_target_expr_with_type (expr, type, complain);
8950 /* Take the address of the thing to which we will bind the
8951 reference. */
8952 expr = cp_build_addr_expr (expr, complain);
8953 if (expr == error_mark_node)
8954 return error_mark_node;
8956 /* Convert it to a pointer to the type referred to by the
8957 reference. This will adjust the pointer if a derived to
8958 base conversion is being performed. */
8959 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8960 expr, complain);
8961 /* Convert the pointer to the desired reference type. */
8962 return build_nop (ref_type, expr);
8965 case ck_lvalue:
8966 return decay_conversion (expr, complain);
8968 case ck_fnptr:
8969 /* ??? Should the address of a transaction-safe pointer point to the TM
8970 clone, and this conversion look up the primary function? */
8971 return build_nop (totype, expr);
8973 case ck_qual:
8974 /* Warn about deprecated conversion if appropriate. */
8975 if (complain & tf_warning)
8977 string_conv_p (totype, expr, 1);
8978 maybe_warn_array_conv (loc, convs, expr);
8980 break;
8982 case ck_ptr:
8983 if (convs->base_p)
8984 expr = convert_to_base (expr, totype, !c_cast_p,
8985 /*nonnull=*/false, complain);
8986 return build_nop (totype, expr);
8988 case ck_pmem:
8989 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8990 c_cast_p, complain);
8992 default:
8993 break;
8996 if (convs->check_narrowing
8997 && !check_narrowing (totype, expr, complain,
8998 convs->check_narrowing_const_only))
8999 return error_mark_node;
9001 warning_sentinel w (warn_zero_as_null_pointer_constant);
9002 if (issue_conversion_warnings)
9003 expr = cp_convert_and_check (totype, expr, complain);
9004 else
9006 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
9007 expr = TREE_OPERAND (expr, 0);
9008 expr = cp_convert (totype, expr, complain);
9011 return expr;
9014 /* Return true if converting FROM to TO is unsafe in a template. */
9016 static bool
9017 conv_unsafe_in_template_p (tree to, tree from)
9019 /* Converting classes involves TARGET_EXPR. */
9020 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
9021 return true;
9023 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
9024 doesn't handle. */
9025 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
9026 return true;
9028 /* Converting integer to real isn't a trivial conversion, either. */
9029 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
9030 return true;
9032 return false;
9035 /* Wrapper for convert_like_internal that handles creating
9036 IMPLICIT_CONV_EXPR. */
9038 static tree
9039 convert_like (conversion *convs, tree expr, tree fn, int argnum,
9040 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
9041 tsubst_flags_t complain)
9043 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
9044 and creating a CALL_EXPR in a template breaks in finish_call_expr
9045 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
9046 created such codes e.g. when calling a user-defined conversion
9047 function. */
9048 tree conv_expr = NULL_TREE;
9049 if (processing_template_decl
9050 && convs->kind != ck_identity
9051 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
9053 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
9054 if (convs->kind != ck_ref_bind)
9055 conv_expr = convert_from_reference (conv_expr);
9056 if (!convs->bad_p)
9057 return conv_expr;
9058 /* Do the normal processing to give the bad_p errors. But we still
9059 need to return the IMPLICIT_CONV_EXPR, unless we're returning
9060 error_mark_node. */
9062 expr = convert_like_internal (convs, expr, fn, argnum,
9063 issue_conversion_warnings, c_cast_p,
9064 nested_p, complain);
9065 if (expr == error_mark_node)
9066 return error_mark_node;
9067 return conv_expr ? conv_expr : expr;
9070 /* Convenience wrapper for convert_like. */
9072 static inline tree
9073 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
9075 return convert_like (convs, expr, NULL_TREE, 0,
9076 /*issue_conversion_warnings=*/true,
9077 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9080 /* Convenience wrapper for convert_like. */
9082 static inline tree
9083 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
9084 tsubst_flags_t complain)
9086 return convert_like (convs, expr, fn, argnum,
9087 /*issue_conversion_warnings=*/true,
9088 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9091 /* ARG is being passed to a varargs function. Perform any conversions
9092 required. Return the converted value. */
9094 tree
9095 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
9097 tree arg_type = TREE_TYPE (arg);
9098 location_t loc = cp_expr_loc_or_input_loc (arg);
9100 /* [expr.call]
9102 If the argument has integral or enumeration type that is subject
9103 to the integral promotions (_conv.prom_), or a floating-point
9104 type that is subject to the floating-point promotion
9105 (_conv.fpprom_), the value of the argument is converted to the
9106 promoted type before the call. */
9107 if (SCALAR_FLOAT_TYPE_P (arg_type)
9108 && (TYPE_PRECISION (arg_type)
9109 < TYPE_PRECISION (double_type_node))
9110 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
9111 && !extended_float_type_p (arg_type))
9113 if ((complain & tf_warning)
9114 && warn_double_promotion && !c_inhibit_evaluation_warnings)
9115 warning_at (loc, OPT_Wdouble_promotion,
9116 "implicit conversion from %qH to %qI when passing "
9117 "argument to function",
9118 arg_type, double_type_node);
9119 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
9120 arg = TREE_OPERAND (arg, 0);
9121 arg = mark_rvalue_use (arg);
9122 arg = convert_to_real_nofold (double_type_node, arg);
9124 else if (NULLPTR_TYPE_P (arg_type))
9126 arg = mark_rvalue_use (arg);
9127 if (TREE_SIDE_EFFECTS (arg))
9129 warning_sentinel w(warn_unused_result);
9130 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9132 else
9133 arg = null_pointer_node;
9135 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9137 if (SCOPED_ENUM_P (arg_type))
9139 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9140 complain);
9141 prom = cp_perform_integral_promotions (prom, complain);
9142 if (abi_version_crosses (6)
9143 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9144 && (complain & tf_warning))
9145 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9146 " as %qT before %<-fabi-version=6%>, %qT after",
9147 arg_type,
9148 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9149 if (!abi_version_at_least (6))
9150 arg = prom;
9152 else
9153 arg = cp_perform_integral_promotions (arg, complain);
9155 else
9156 /* [expr.call]
9158 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9159 standard conversions are performed. */
9160 arg = decay_conversion (arg, complain);
9162 arg = require_complete_type (arg, complain);
9163 arg_type = TREE_TYPE (arg);
9165 if (arg != error_mark_node
9166 /* In a template (or ill-formed code), we can have an incomplete type
9167 even after require_complete_type, in which case we don't know
9168 whether it has trivial copy or not. */
9169 && COMPLETE_TYPE_P (arg_type)
9170 && !cp_unevaluated_operand)
9172 /* [expr.call] 5.2.2/7:
9173 Passing a potentially-evaluated argument of class type (Clause 9)
9174 with a non-trivial copy constructor or a non-trivial destructor
9175 with no corresponding parameter is conditionally-supported, with
9176 implementation-defined semantics.
9178 We support it as pass-by-invisible-reference, just like a normal
9179 value parameter.
9181 If the call appears in the context of a sizeof expression,
9182 it is not potentially-evaluated. */
9183 if (type_has_nontrivial_copy_init (arg_type)
9184 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9186 arg = force_rvalue (arg, complain);
9187 if (complain & tf_warning)
9188 warning (OPT_Wconditionally_supported,
9189 "passing objects of non-trivially-copyable "
9190 "type %q#T through %<...%> is conditionally supported",
9191 arg_type);
9192 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9194 /* Build up a real lvalue-to-rvalue conversion in case the
9195 copy constructor is trivial but not callable. */
9196 else if (CLASS_TYPE_P (arg_type))
9197 force_rvalue (arg, complain);
9201 return arg;
9204 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9206 tree
9207 build_x_va_arg (location_t loc, tree expr, tree type)
9209 if (processing_template_decl)
9211 tree r = build_min (VA_ARG_EXPR, type, expr);
9212 SET_EXPR_LOCATION (r, loc);
9213 return r;
9216 type = complete_type_or_else (type, NULL_TREE);
9218 if (expr == error_mark_node || !type)
9219 return error_mark_node;
9221 expr = mark_lvalue_use (expr);
9223 if (TYPE_REF_P (type))
9225 error ("cannot receive reference type %qT through %<...%>", type);
9226 return error_mark_node;
9229 if (type_has_nontrivial_copy_init (type)
9230 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9232 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9233 it as pass by invisible reference. */
9234 warning_at (loc, OPT_Wconditionally_supported,
9235 "receiving objects of non-trivially-copyable type %q#T "
9236 "through %<...%> is conditionally-supported", type);
9238 tree ref = cp_build_reference_type (type, false);
9239 expr = build_va_arg (loc, expr, ref);
9240 return convert_from_reference (expr);
9243 tree ret = build_va_arg (loc, expr, type);
9244 if (CLASS_TYPE_P (type))
9245 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9246 know how to handle it. */
9247 ret = get_target_expr (ret);
9248 return ret;
9251 /* TYPE has been given to va_arg. Apply the default conversions which
9252 would have happened when passed via ellipsis. Return the promoted
9253 type, or the passed type if there is no change. */
9255 tree
9256 cxx_type_promotes_to (tree type)
9258 tree promote;
9260 /* Perform the array-to-pointer and function-to-pointer
9261 conversions. */
9262 type = type_decays_to (type);
9264 promote = type_promotes_to (type);
9265 if (same_type_p (type, promote))
9266 promote = type;
9268 return promote;
9271 /* ARG is a default argument expression being passed to a parameter of
9272 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9273 zero-based argument number. Do any required conversions. Return
9274 the converted value. */
9276 static GTY(()) vec<tree, va_gc> *default_arg_context;
9277 void
9278 push_defarg_context (tree fn)
9279 { vec_safe_push (default_arg_context, fn); }
9281 void
9282 pop_defarg_context (void)
9283 { default_arg_context->pop (); }
9285 tree
9286 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9287 tsubst_flags_t complain)
9289 int i;
9290 tree t;
9292 /* See through clones. */
9293 fn = DECL_ORIGIN (fn);
9294 /* And inheriting ctors. */
9295 if (flag_new_inheriting_ctors)
9296 fn = strip_inheriting_ctors (fn);
9298 /* Detect recursion. */
9299 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9300 if (t == fn)
9302 if (complain & tf_error)
9303 error ("recursive evaluation of default argument for %q#D", fn);
9304 return error_mark_node;
9307 /* If the ARG is an unparsed default argument expression, the
9308 conversion cannot be performed. */
9309 if (TREE_CODE (arg) == DEFERRED_PARSE)
9311 if (complain & tf_error)
9312 error ("call to %qD uses the default argument for parameter %P, which "
9313 "is not yet defined", fn, parmnum);
9314 return error_mark_node;
9317 push_defarg_context (fn);
9319 if (fn && DECL_TEMPLATE_INFO (fn))
9320 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9322 /* Due to:
9324 [dcl.fct.default]
9326 The names in the expression are bound, and the semantic
9327 constraints are checked, at the point where the default
9328 expressions appears.
9330 we must not perform access checks here. */
9331 push_deferring_access_checks (dk_no_check);
9332 /* We must make a copy of ARG, in case subsequent processing
9333 alters any part of it. */
9334 arg = break_out_target_exprs (arg, /*clear location*/true);
9336 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9337 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9338 complain);
9339 arg = convert_for_arg_passing (type, arg, complain);
9340 pop_deferring_access_checks();
9342 pop_defarg_context ();
9344 return arg;
9347 /* Returns the type which will really be used for passing an argument of
9348 type TYPE. */
9350 tree
9351 type_passed_as (tree type)
9353 /* Pass classes with copy ctors by invisible reference. */
9354 if (TREE_ADDRESSABLE (type))
9355 type = build_reference_type (type);
9356 else if (targetm.calls.promote_prototypes (NULL_TREE)
9357 && INTEGRAL_TYPE_P (type)
9358 && COMPLETE_TYPE_P (type)
9359 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9360 type = integer_type_node;
9362 return type;
9365 /* Actually perform the appropriate conversion. */
9367 tree
9368 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9370 tree bitfield_type;
9372 /* If VAL is a bitfield, then -- since it has already been converted
9373 to TYPE -- it cannot have a precision greater than TYPE.
9375 If it has a smaller precision, we must widen it here. For
9376 example, passing "int f:3;" to a function expecting an "int" will
9377 not result in any conversion before this point.
9379 If the precision is the same we must not risk widening. For
9380 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9381 often have type "int", even though the C++ type for the field is
9382 "long long". If the value is being passed to a function
9383 expecting an "int", then no conversions will be required. But,
9384 if we call convert_bitfield_to_declared_type, the bitfield will
9385 be converted to "long long". */
9386 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9387 if (bitfield_type
9388 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9389 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
9391 if (val == error_mark_node)
9393 /* Pass classes with copy ctors by invisible reference. */
9394 else if (TREE_ADDRESSABLE (type))
9395 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9396 else if (targetm.calls.promote_prototypes (NULL_TREE)
9397 && INTEGRAL_TYPE_P (type)
9398 && COMPLETE_TYPE_P (type)
9399 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9400 val = cp_perform_integral_promotions (val, complain);
9401 if (complain & tf_warning)
9403 if (warn_suggest_attribute_format)
9405 tree rhstype = TREE_TYPE (val);
9406 const enum tree_code coder = TREE_CODE (rhstype);
9407 const enum tree_code codel = TREE_CODE (type);
9408 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9409 && coder == codel
9410 && check_missing_format_attribute (type, rhstype))
9411 warning (OPT_Wsuggest_attribute_format,
9412 "argument of function call might be a candidate "
9413 "for a format attribute");
9415 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
9418 if (complain & tf_warning)
9419 warn_for_address_of_packed_member (type, val);
9421 return val;
9424 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9425 which just decay_conversion or no conversions at all should be done.
9426 This is true for some builtins which don't act like normal functions.
9427 Return 2 if just decay_conversion and removal of excess precision should
9428 be done, 1 if just decay_conversion. Return 3 for special treatment of
9429 the 3rd argument for __builtin_*_overflow_p. Return 4 for special
9430 treatment of the 1st argument for
9431 __builtin_{clz,ctz,clrsb,ffs,parity,popcount}g. */
9434 magic_varargs_p (tree fn)
9436 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9437 switch (DECL_FUNCTION_CODE (fn))
9439 case BUILT_IN_CLASSIFY_TYPE:
9440 case BUILT_IN_CONSTANT_P:
9441 case BUILT_IN_NEXT_ARG:
9442 case BUILT_IN_VA_START:
9443 return 1;
9445 case BUILT_IN_ADD_OVERFLOW_P:
9446 case BUILT_IN_SUB_OVERFLOW_P:
9447 case BUILT_IN_MUL_OVERFLOW_P:
9448 return 3;
9450 case BUILT_IN_ISFINITE:
9451 case BUILT_IN_ISINF:
9452 case BUILT_IN_ISINF_SIGN:
9453 case BUILT_IN_ISNAN:
9454 case BUILT_IN_ISNORMAL:
9455 case BUILT_IN_FPCLASSIFY:
9456 return 2;
9458 case BUILT_IN_CLZG:
9459 case BUILT_IN_CTZG:
9460 case BUILT_IN_CLRSBG:
9461 case BUILT_IN_FFSG:
9462 case BUILT_IN_PARITYG:
9463 case BUILT_IN_POPCOUNTG:
9464 return 4;
9466 default:
9467 return lookup_attribute ("type generic",
9468 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9471 return 0;
9474 /* Returns the decl of the dispatcher function if FN is a function version. */
9476 tree
9477 get_function_version_dispatcher (tree fn)
9479 tree dispatcher_decl = NULL;
9481 if (DECL_LOCAL_DECL_P (fn))
9482 fn = DECL_LOCAL_DECL_ALIAS (fn);
9484 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9485 && DECL_FUNCTION_VERSIONED (fn));
9487 gcc_assert (targetm.get_function_versions_dispatcher);
9488 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9490 if (dispatcher_decl == NULL)
9492 error_at (input_location, "use of multiversioned function "
9493 "without a default");
9494 return NULL;
9497 retrofit_lang_decl (dispatcher_decl);
9498 gcc_assert (dispatcher_decl != NULL);
9499 return dispatcher_decl;
9502 /* fn is a function version dispatcher that is marked used. Mark all the
9503 semantically identical function versions it will dispatch as used. */
9505 void
9506 mark_versions_used (tree fn)
9508 struct cgraph_node *node;
9509 struct cgraph_function_version_info *node_v;
9510 struct cgraph_function_version_info *it_v;
9512 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9514 node = cgraph_node::get (fn);
9515 if (node == NULL)
9516 return;
9518 gcc_assert (node->dispatcher_function);
9520 node_v = node->function_version ();
9521 if (node_v == NULL)
9522 return;
9524 /* All semantically identical versions are chained. Traverse and mark each
9525 one of them as used. */
9526 it_v = node_v->next;
9527 while (it_v != NULL)
9529 mark_used (it_v->this_node->decl);
9530 it_v = it_v->next;
9534 /* Build a call to "the copy constructor" for the type of A, even if it
9535 wouldn't be selected by normal overload resolution. Used for
9536 diagnostics. */
9538 static tree
9539 call_copy_ctor (tree a, tsubst_flags_t complain)
9541 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9542 tree binfo = TYPE_BINFO (ctype);
9543 tree copy = get_copy_ctor (ctype, complain);
9544 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9545 tree ob = build_dummy_object (ctype);
9546 releasing_vec args (make_tree_vector_single (a));
9547 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9548 LOOKUP_NORMAL, NULL, complain);
9549 return r;
9552 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9554 static tree
9555 base_ctor_for (tree complete_ctor)
9557 tree clone;
9558 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9559 if (DECL_BASE_CONSTRUCTOR_P (clone))
9560 return clone;
9561 return NULL_TREE;
9564 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9565 and return whether we were successful. EXP must have already been cleared
9566 by unsafe_copy_elision_p{,_opt}. */
9568 static bool
9569 make_base_init_ok (tree exp)
9571 if (TREE_CODE (exp) == TARGET_EXPR)
9572 exp = TARGET_EXPR_INITIAL (exp);
9573 while (TREE_CODE (exp) == COMPOUND_EXPR)
9574 exp = TREE_OPERAND (exp, 1);
9575 if (TREE_CODE (exp) == COND_EXPR)
9577 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9578 if (tree op1 = TREE_OPERAND (exp, 1))
9580 bool r1 = make_base_init_ok (op1);
9581 /* If unsafe_copy_elision_p was false, the arms should match. */
9582 gcc_assert (r1 == ret);
9584 return ret;
9586 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9587 /* A trivial copy is OK. */
9588 return true;
9589 if (!AGGR_INIT_VIA_CTOR_P (exp))
9590 /* unsafe_copy_elision_p_opt must have said this is OK. */
9591 return true;
9592 tree fn = cp_get_callee_fndecl_nofold (exp);
9593 if (DECL_BASE_CONSTRUCTOR_P (fn))
9594 return true;
9595 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9596 fn = base_ctor_for (fn);
9597 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9598 /* The base constructor has more parameters, so we can't just change the
9599 call target. It would be possible to splice in the appropriate
9600 arguments, but probably not worth the complexity. */
9601 return false;
9602 mark_used (fn);
9603 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9604 return true;
9607 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9608 neither of which can be used for return by invisible reference. We avoid
9609 doing C++17 mandatory copy elision for either of these cases.
9611 This returns non-zero even if the type of T has no tail padding that other
9612 data could be allocated into, because that depends on the particular ABI.
9613 unsafe_copy_elision_p_opt does consider whether there is padding. */
9616 unsafe_return_slot_p (tree t)
9618 /* Check empty bases separately, they don't have fields. */
9619 if (is_empty_base_ref (t))
9620 return 2;
9622 /* A delegating constructor might be used to initialize a base. */
9623 if (current_function_decl
9624 && DECL_CONSTRUCTOR_P (current_function_decl)
9625 && (t == current_class_ref
9626 || tree_strip_nop_conversions (t) == current_class_ptr))
9627 return 2;
9629 STRIP_NOPS (t);
9630 if (TREE_CODE (t) == ADDR_EXPR)
9631 t = TREE_OPERAND (t, 0);
9632 if (TREE_CODE (t) == COMPONENT_REF)
9633 t = TREE_OPERAND (t, 1);
9634 if (TREE_CODE (t) != FIELD_DECL)
9635 return false;
9636 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9637 /* The middle-end will do the right thing for scalar types. */
9638 return false;
9639 if (DECL_FIELD_IS_BASE (t))
9640 return 2;
9641 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9642 return 1;
9643 return 0;
9646 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9648 static bool
9649 init_by_return_slot_p (tree exp)
9651 /* Copy elision only happens with a TARGET_EXPR. */
9652 if (TREE_CODE (exp) != TARGET_EXPR)
9653 return false;
9654 tree init = TARGET_EXPR_INITIAL (exp);
9655 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9656 while (TREE_CODE (init) == COMPOUND_EXPR)
9657 init = TREE_OPERAND (init, 1);
9658 if (TREE_CODE (init) == COND_EXPR)
9660 /* We'll end up copying from each of the arms of the COND_EXPR directly
9661 into the target, so look at them. */
9662 if (tree op = TREE_OPERAND (init, 1))
9663 if (init_by_return_slot_p (op))
9664 return true;
9665 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9667 return (TREE_CODE (init) == AGGR_INIT_EXPR
9668 && !AGGR_INIT_VIA_CTOR_P (init));
9671 /* We can't elide a copy from a function returning by value to a
9672 potentially-overlapping subobject, as the callee might clobber tail padding.
9673 Return true iff this could be that case.
9675 Places that use this function (or _opt) to decide to elide a copy should
9676 probably use make_safe_copy_elision instead. */
9678 bool
9679 unsafe_copy_elision_p (tree target, tree exp)
9681 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9684 /* As above, but for optimization allow more cases that are actually safe. */
9686 static bool
9687 unsafe_copy_elision_p_opt (tree target, tree exp)
9689 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9690 /* It's safe to elide the copy for a class with no tail padding. */
9691 if (!is_empty_class (type)
9692 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9693 return false;
9694 return unsafe_copy_elision_p (target, exp);
9697 /* Try to make EXP suitable to be used as the initializer for TARGET,
9698 and return whether we were successful. */
9700 bool
9701 make_safe_copy_elision (tree target, tree exp)
9703 int uns = unsafe_return_slot_p (target);
9704 if (!uns)
9705 return true;
9706 if (init_by_return_slot_p (exp))
9707 return false;
9708 if (uns == 1)
9709 return true;
9710 return make_base_init_ok (exp);
9713 /* True IFF the result of the conversion C is a prvalue. */
9715 static bool
9716 conv_is_prvalue (conversion *c)
9718 if (c->kind == ck_rvalue)
9719 return true;
9720 if (c->kind == ck_base && c->need_temporary_p)
9721 return true;
9722 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9723 return true;
9724 if (c->kind == ck_identity && c->u.expr
9725 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9726 return true;
9728 return false;
9731 /* True iff C is a conversion that binds a reference to a prvalue. */
9733 static bool
9734 conv_binds_ref_to_prvalue (conversion *c)
9736 if (c->kind != ck_ref_bind)
9737 return false;
9738 if (c->need_temporary_p)
9739 return true;
9741 return conv_is_prvalue (next_conversion (c));
9744 /* True iff EXPR represents a (subobject of a) temporary. */
9746 static bool
9747 expr_represents_temporary_p (tree expr)
9749 while (handled_component_p (expr))
9750 expr = TREE_OPERAND (expr, 0);
9751 return TREE_CODE (expr) == TARGET_EXPR;
9754 /* True iff C is a conversion that binds a reference to a temporary.
9755 This is a superset of conv_binds_ref_to_prvalue: here we're also
9756 interested in xvalues. */
9758 static bool
9759 conv_binds_ref_to_temporary (conversion *c)
9761 if (conv_binds_ref_to_prvalue (c))
9762 return true;
9763 if (c->kind != ck_ref_bind)
9764 return false;
9765 c = next_conversion (c);
9766 /* This is the case for
9767 struct Base {};
9768 struct Derived : Base {};
9769 const Base& b(Derived{});
9770 where we bind 'b' to the Base subobject of a temporary object of type
9771 Derived. The subobject is an xvalue; the whole object is a prvalue.
9773 The ck_base doesn't have to be present for cases like X{}.m. */
9774 if (c->kind == ck_base)
9775 c = next_conversion (c);
9776 if (c->kind == ck_identity && c->u.expr
9777 && expr_represents_temporary_p (c->u.expr))
9778 return true;
9779 return false;
9782 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9783 the reference to a temporary. Return tristate::TS_FALSE if converting
9784 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9785 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9786 says whether the conversion should be done in direct- or copy-initialization
9787 context. */
9789 tristate
9790 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9792 gcc_assert (TYPE_REF_P (type));
9794 conversion_obstack_sentinel cos;
9796 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9797 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9798 /*c_cast_p=*/false, flags, tf_none);
9799 tristate ret (tristate::TS_UNKNOWN);
9800 if (conv && !conv->bad_p)
9801 ret = tristate (conv_binds_ref_to_temporary (conv));
9803 return ret;
9806 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9807 class type or a pointer to class type. If NO_PTR_DEREF is true and
9808 INSTANCE has pointer type, clobber the pointer rather than what it points
9809 to. */
9811 tree
9812 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9814 gcc_assert (!is_dummy_object (instance));
9816 if (!flag_lifetime_dse)
9818 no_clobber:
9819 return fold_convert (void_type_node, instance);
9822 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9823 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9825 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9826 goto no_clobber;
9827 instance = cp_build_fold_indirect_ref (instance);
9830 /* A trivial destructor should still clobber the object. */
9831 tree clobber = build_clobber (TREE_TYPE (instance), CLOBBER_OBJECT_END);
9832 return build2 (MODIFY_EXPR, void_type_node,
9833 instance, clobber);
9836 /* Return true if in an immediate function context, or an unevaluated operand,
9837 or a default argument/member initializer, or a subexpression of an immediate
9838 invocation. */
9840 bool
9841 in_immediate_context ()
9843 return (cp_unevaluated_operand != 0
9844 || (current_function_decl != NULL_TREE
9845 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9846 /* DR 2631: default args and DMI aren't immediately evaluated.
9847 Return true here so immediate_invocation_p returns false. */
9848 || current_binding_level->kind == sk_function_parms
9849 || current_binding_level->kind == sk_template_parms
9850 || parsing_nsdmi ()
9851 || in_consteval_if_p);
9854 /* Return true if a call to FN with number of arguments NARGS
9855 is an immediate invocation. */
9857 bool
9858 immediate_invocation_p (tree fn)
9860 return (TREE_CODE (fn) == FUNCTION_DECL
9861 && DECL_IMMEDIATE_FUNCTION_P (fn)
9862 && !in_immediate_context ());
9865 /* Subroutine of the various build_*_call functions. Overload resolution
9866 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9867 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9868 bitmask of various LOOKUP_* flags which apply to the call itself. */
9870 static tree
9871 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9873 tree fn = cand->fn;
9874 const vec<tree, va_gc> *args = cand->args;
9875 tree first_arg = cand->first_arg;
9876 conversion **convs = cand->convs;
9877 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9878 int parmlen;
9879 tree val;
9880 int nargs;
9881 tree *argarray;
9882 bool already_used = false;
9884 /* In a template, there is no need to perform all of the work that
9885 is normally done. We are only interested in the type of the call
9886 expression, i.e., the return type of the function. Any semantic
9887 errors will be deferred until the template is instantiated. */
9888 if (processing_template_decl)
9890 if (undeduced_auto_decl (fn))
9891 mark_used (fn, complain);
9892 else
9893 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9894 See PR80598. */
9895 TREE_USED (fn) = 1;
9897 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9898 tree callee;
9899 if (first_arg == NULL_TREE)
9901 callee = build_addr_func (fn, complain);
9902 if (callee == error_mark_node)
9903 return error_mark_node;
9905 else
9907 callee = build_baselink (cand->conversion_path, cand->access_path,
9908 fn, NULL_TREE);
9909 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9910 first_arg, callee, NULL_TREE);
9913 tree expr = build_call_vec (return_type, callee, args);
9914 SET_EXPR_LOCATION (expr, input_location);
9915 if (TREE_THIS_VOLATILE (fn) && cfun)
9916 current_function_returns_abnormally = 1;
9917 if (immediate_invocation_p (fn))
9919 tree obj_arg = NULL_TREE, exprimm = expr;
9920 if (DECL_CONSTRUCTOR_P (fn))
9921 obj_arg = first_arg;
9922 if (obj_arg
9923 && is_dummy_object (obj_arg)
9924 && !type_dependent_expression_p (obj_arg))
9926 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9927 obj_arg = NULL_TREE;
9929 /* Look through *(const T *)&obj. */
9930 else if (obj_arg && INDIRECT_REF_P (obj_arg))
9932 tree addr = TREE_OPERAND (obj_arg, 0);
9933 STRIP_NOPS (addr);
9934 if (TREE_CODE (addr) == ADDR_EXPR)
9936 tree typeo = TREE_TYPE (obj_arg);
9937 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9938 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9939 obj_arg = TREE_OPERAND (addr, 0);
9942 fold_non_dependent_expr (exprimm, complain,
9943 /*manifestly_const_eval=*/true,
9944 obj_arg);
9946 return convert_from_reference (expr);
9949 /* Give any warnings we noticed during overload resolution. */
9950 if (cand->warnings && (complain & tf_warning))
9952 struct candidate_warning *w;
9953 for (w = cand->warnings; w; w = w->next)
9954 joust (cand, w->loser, 1, complain);
9957 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9958 argument to the copy constructor ends up being a prvalue after
9959 conversion. Let's do the normal processing, but pretend we aren't
9960 actually using the copy constructor. */
9961 bool force_elide = false;
9962 if (cxx_dialect >= cxx17
9963 && cand->num_convs == 1
9964 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9965 && (DECL_COPY_CONSTRUCTOR_P (fn)
9966 || DECL_MOVE_CONSTRUCTOR_P (fn))
9967 && !unsafe_return_slot_p (first_arg)
9968 && conv_binds_ref_to_prvalue (convs[0]))
9970 force_elide = true;
9971 goto not_really_used;
9974 /* OK, we're actually calling this inherited constructor; set its deletedness
9975 appropriately. We can get away with doing this here because calling is
9976 the only way to refer to a constructor. */
9977 if (DECL_INHERITED_CTOR (fn)
9978 && !deduce_inheriting_ctor (fn))
9980 if (complain & tf_error)
9981 mark_used (fn);
9982 return error_mark_node;
9985 /* Make =delete work with SFINAE. */
9986 if (DECL_DELETED_FN (fn))
9988 if (complain & tf_error)
9990 mark_used (fn);
9991 if (cand->next)
9993 if (flag_diagnostics_all_candidates)
9994 print_z_candidates (input_location, cand, /*only_viable_p=*/false);
9995 else
9996 inform (input_location,
9997 "use %<-fdiagnostics-all-candidates%> to display "
9998 "considered candidates");
10001 return error_mark_node;
10004 if (DECL_FUNCTION_MEMBER_P (fn))
10006 tree access_fn;
10007 /* If FN is a template function, two cases must be considered.
10008 For example:
10010 struct A {
10011 protected:
10012 template <class T> void f();
10014 template <class T> struct B {
10015 protected:
10016 void g();
10018 struct C : A, B<int> {
10019 using A::f; // #1
10020 using B<int>::g; // #2
10023 In case #1 where `A::f' is a member template, DECL_ACCESS is
10024 recorded in the primary template but not in its specialization.
10025 We check access of FN using its primary template.
10027 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
10028 because it is a member of class template B, DECL_ACCESS is
10029 recorded in the specialization `B<int>::g'. We cannot use its
10030 primary template because `B<T>::g' and `B<int>::g' may have
10031 different access. */
10032 if (DECL_TEMPLATE_INFO (fn)
10033 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
10034 access_fn = DECL_TI_TEMPLATE (fn);
10035 else
10036 access_fn = fn;
10037 if (!perform_or_defer_access_check (cand->access_path, access_fn,
10038 fn, complain))
10039 return error_mark_node;
10042 /* If we're checking for implicit delete, don't bother with argument
10043 conversions. */
10044 if (flags & LOOKUP_SPECULATIVE)
10046 if (cand->viable == 1)
10047 return fn;
10048 else if (!(complain & tf_error))
10049 /* Reject bad conversions now. */
10050 return error_mark_node;
10051 /* else continue to get conversion error. */
10054 not_really_used:
10056 /* N3276 magic doesn't apply to nested calls. */
10057 tsubst_flags_t decltype_flag = (complain & tf_decltype);
10058 complain &= ~tf_decltype;
10059 /* No-Cleanup doesn't apply to nested calls either. */
10060 tsubst_flags_t no_cleanup_complain = complain;
10061 complain &= ~tf_no_cleanup;
10063 /* Find maximum size of vector to hold converted arguments. */
10064 parmlen = list_length (parm);
10065 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
10066 if (parmlen > nargs)
10067 nargs = parmlen;
10068 argarray = XALLOCAVEC (tree, nargs);
10070 in_consteval_if_p_temp_override icip;
10071 /* If the call is immediate function invocation, make sure
10072 taking address of immediate functions is allowed in its arguments. */
10073 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
10074 in_consteval_if_p = true;
10076 int argarray_size = 0;
10077 unsigned int arg_index = 0;
10078 int conv_index = 0;
10079 int param_index = 0;
10081 auto consume_object_arg = [&arg_index, &first_arg, args]()
10083 if (!first_arg)
10084 return (*args)[arg_index++];
10085 tree object_arg = first_arg;
10086 first_arg = NULL_TREE;
10087 return object_arg;
10090 /* The implicit parameters to a constructor are not considered by overload
10091 resolution, and must be of the proper type. */
10092 if (DECL_CONSTRUCTOR_P (fn))
10094 tree object_arg = consume_object_arg ();
10095 argarray[argarray_size++] = build_this (object_arg);
10096 parm = TREE_CHAIN (parm);
10097 /* We should never try to call the abstract constructor. */
10098 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
10100 if (DECL_HAS_VTT_PARM_P (fn))
10102 argarray[argarray_size++] = (*args)[arg_index];
10103 ++arg_index;
10104 parm = TREE_CHAIN (parm);
10107 /* Bypass access control for 'this' parameter. */
10108 else if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
10110 tree arg = build_this (consume_object_arg ());
10111 tree argtype = TREE_TYPE (arg);
10113 if (arg == error_mark_node)
10114 return error_mark_node;
10115 if (convs[conv_index++]->bad_p)
10117 if (complain & tf_error)
10119 auto_diagnostic_group d;
10120 if (permerror (input_location, "passing %qT as %<this%> "
10121 "argument discards qualifiers",
10122 TREE_TYPE (argtype)))
10123 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
10125 else
10126 return error_mark_node;
10129 /* The class where FN is defined. */
10130 tree ctx = DECL_CONTEXT (fn);
10132 /* See if the function member or the whole class type is declared
10133 final and the call can be devirtualized. */
10134 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
10135 flags |= LOOKUP_NONVIRTUAL;
10137 /* [class.mfct.non-static]: If a non-static member function of a class
10138 X is called for an object that is not of type X, or of a type
10139 derived from X, the behavior is undefined.
10141 So we can assume that anything passed as 'this' is non-null, and
10142 optimize accordingly. */
10143 /* Check that the base class is accessible. */
10144 if (!accessible_base_p (TREE_TYPE (argtype),
10145 BINFO_TYPE (cand->conversion_path), true))
10147 if (complain & tf_error)
10148 error ("%qT is not an accessible base of %qT",
10149 BINFO_TYPE (cand->conversion_path),
10150 TREE_TYPE (argtype));
10151 else
10152 return error_mark_node;
10154 /* If fn was found by a using declaration, the conversion path
10155 will be to the derived class, not the base declaring fn. We
10156 must convert to the base. */
10157 tree base_binfo = cand->conversion_path;
10158 if (BINFO_TYPE (base_binfo) != ctx)
10160 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10161 if (base_binfo == error_mark_node)
10162 return error_mark_node;
10165 /* If we know the dynamic type of the object, look up the final overrider
10166 in the BINFO. */
10167 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10168 && resolves_to_fixed_type_p (arg))
10170 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10172 /* And unwind base_binfo to match. If we don't find the type we're
10173 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10174 inheritance; for now do a normal virtual call in that case. */
10175 tree octx = DECL_CONTEXT (ov);
10176 tree obinfo = base_binfo;
10177 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10178 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10179 if (obinfo)
10181 fn = ov;
10182 base_binfo = obinfo;
10183 flags |= LOOKUP_NONVIRTUAL;
10187 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10188 base_binfo, 1, complain);
10190 argarray[argarray_size++] = converted_arg;
10191 parm = TREE_CHAIN (parm);
10194 auto handle_arg = [fn, flags](tree type,
10195 tree arg,
10196 int const param_index,
10197 conversion *conv,
10198 tsubst_flags_t const arg_complain)
10200 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10201 knows not to allow any more UDCs. This needs to happen after we
10202 process cand->warnings. */
10203 if (flags & LOOKUP_NO_CONVERSION)
10204 conv->user_conv_p = true;
10206 if (arg_complain & tf_warning)
10207 maybe_warn_pessimizing_move (arg, type, /*return_p=*/false);
10209 tree val = convert_like_with_context (conv, arg, fn,
10210 param_index, arg_complain);
10211 val = convert_for_arg_passing (type, val, arg_complain);
10212 return val;
10215 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
10217 gcc_assert (cand->num_convs > 0);
10218 tree object_arg = consume_object_arg ();
10219 val = handle_arg (TREE_VALUE (parm),
10220 object_arg,
10221 param_index++,
10222 convs[conv_index++],
10223 complain);
10225 if (val == error_mark_node)
10226 return error_mark_node;
10227 else
10228 argarray[argarray_size++] = val;
10229 parm = TREE_CHAIN (parm);
10232 gcc_assert (first_arg == NULL_TREE);
10233 for (; arg_index < vec_safe_length (args) && parm;
10234 parm = TREE_CHAIN (parm), ++arg_index, ++param_index, ++conv_index)
10236 tree current_arg = (*args)[arg_index];
10238 /* If the argument is NULL and used to (implicitly) instantiate a
10239 template function (and bind one of the template arguments to
10240 the type of 'long int'), we don't want to warn about passing NULL
10241 to non-pointer argument.
10242 For example, if we have this template function:
10244 template<typename T> void func(T x) {}
10246 we want to warn (when -Wconversion is enabled) in this case:
10248 void foo() {
10249 func<int>(NULL);
10252 but not in this case:
10254 void foo() {
10255 func(NULL);
10258 bool const conversion_warning = !(null_node_p (current_arg)
10259 && DECL_TEMPLATE_INFO (fn)
10260 && cand->template_decl
10261 && !cand->explicit_targs);
10263 tsubst_flags_t const arg_complain
10264 = conversion_warning ? complain : complain & ~tf_warning;
10266 val = handle_arg (TREE_VALUE (parm),
10267 current_arg,
10268 param_index,
10269 convs[conv_index],
10270 arg_complain);
10272 if (val == error_mark_node)
10273 return error_mark_node;
10274 else
10275 argarray[argarray_size++] = val;
10278 /* Default arguments */
10279 for (; parm && parm != void_list_node;
10280 parm = TREE_CHAIN (parm), param_index++)
10282 if (TREE_VALUE (parm) == error_mark_node)
10283 return error_mark_node;
10284 val = convert_default_arg (TREE_VALUE (parm),
10285 TREE_PURPOSE (parm),
10286 fn, param_index,
10287 complain);
10288 if (val == error_mark_node)
10289 return error_mark_node;
10290 argarray[argarray_size++] = val;
10293 /* Ellipsis */
10294 int magic = magic_varargs_p (fn);
10295 for (; arg_index < vec_safe_length (args); ++arg_index)
10297 tree a = (*args)[arg_index];
10298 if ((magic == 3 && arg_index == 2) || (magic == 4 && arg_index == 0))
10300 /* Do no conversions for certain magic varargs. */
10301 a = mark_type_use (a);
10302 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10303 return error_mark_node;
10305 else if (magic != 0)
10307 /* Don't truncate excess precision to the semantic type. */
10308 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10309 a = TREE_OPERAND (a, 0);
10310 /* For other magic varargs only do decay_conversion. */
10311 a = decay_conversion (a, complain);
10313 else if (DECL_CONSTRUCTOR_P (fn)
10314 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10315 TREE_TYPE (a)))
10317 /* Avoid infinite recursion trying to call A(...). */
10318 if (complain & tf_error)
10319 /* Try to call the actual copy constructor for a good error. */
10320 call_copy_ctor (a, complain);
10321 return error_mark_node;
10323 else
10324 a = convert_arg_to_ellipsis (a, complain);
10325 if (a == error_mark_node)
10326 return error_mark_node;
10327 argarray[argarray_size++] = a;
10330 gcc_assert (argarray_size <= nargs);
10331 nargs = argarray_size;
10332 icip.reset ();
10334 /* Avoid performing argument transformation if warnings are disabled.
10335 When tf_warning is set and at least one of the warnings is active
10336 the check_function_arguments function might warn about something. */
10338 bool warned_p = false;
10339 if ((complain & tf_warning)
10340 && (warn_nonnull
10341 || warn_format
10342 || warn_suggest_attribute_format
10343 || warn_restrict))
10345 tree *fargs = (!nargs ? argarray
10346 : (tree *) alloca (nargs * sizeof (tree)));
10347 for (int j = 0; j < nargs; j++)
10349 /* For -Wformat undo the implicit passing by hidden reference
10350 done by convert_arg_to_ellipsis. */
10351 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10352 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10353 fargs[j] = TREE_OPERAND (argarray[j], 0);
10354 else
10355 fargs[j] = argarray[j];
10358 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
10359 nargs, fargs, NULL);
10362 if (DECL_INHERITED_CTOR (fn))
10364 /* Check for passing ellipsis arguments to an inherited constructor. We
10365 could handle this by open-coding the inherited constructor rather than
10366 defining it, but let's not bother now. */
10367 if (!cp_unevaluated_operand
10368 && cand->num_convs
10369 && cand->convs[cand->num_convs-1]->ellipsis_p)
10371 if (complain & tf_error)
10373 sorry ("passing arguments to ellipsis of inherited constructor "
10374 "%qD", cand->fn);
10375 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10377 return error_mark_node;
10380 /* A base constructor inheriting from a virtual base doesn't get the
10381 inherited arguments, just this and __vtt. */
10382 if (ctor_omit_inherited_parms (fn))
10383 nargs = 2;
10386 /* Avoid actually calling copy constructors and copy assignment operators,
10387 if possible. */
10389 if (!force_elide
10390 && (!flag_elide_constructors
10391 /* It's unsafe to elide the operation when handling
10392 a noexcept-expression, it may evaluate to the wrong
10393 value (c++/53025, c++/96090). */
10394 || cp_noexcept_operand != 0))
10395 /* Do things the hard way. */;
10396 else if (cand->num_convs == 1
10397 && (DECL_COPY_CONSTRUCTOR_P (fn)
10398 || DECL_MOVE_CONSTRUCTOR_P (fn)))
10400 tree targ;
10401 tree arg = argarray[num_artificial_parms_for (fn)];
10402 tree fa = argarray[0];
10403 bool trivial = trivial_fn_p (fn);
10405 /* Pull out the real argument, disregarding const-correctness. */
10406 targ = arg;
10407 /* Strip the reference binding for the constructor parameter. */
10408 if (CONVERT_EXPR_P (targ)
10409 && TYPE_REF_P (TREE_TYPE (targ)))
10410 targ = TREE_OPERAND (targ, 0);
10411 /* But don't strip any other reference bindings; binding a temporary to a
10412 reference prevents copy elision. */
10413 while ((CONVERT_EXPR_P (targ)
10414 && !TYPE_REF_P (TREE_TYPE (targ)))
10415 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10416 targ = TREE_OPERAND (targ, 0);
10417 if (TREE_CODE (targ) == ADDR_EXPR)
10419 targ = TREE_OPERAND (targ, 0);
10420 if (!same_type_ignoring_top_level_qualifiers_p
10421 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10422 targ = NULL_TREE;
10424 else
10425 targ = NULL_TREE;
10427 if (targ)
10428 arg = targ;
10429 else
10430 arg = cp_build_fold_indirect_ref (arg);
10432 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10433 potentially-overlapping subobject. */
10434 if (CHECKING_P && cxx_dialect >= cxx17)
10435 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10436 || force_elide
10437 /* It's from binding the ref parm to a packed field. */
10438 || convs[0]->need_temporary_p
10439 || seen_error ()
10440 /* See unsafe_copy_elision_p. */
10441 || unsafe_return_slot_p (fa));
10443 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
10444 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10446 /* [class.copy]: the copy constructor is implicitly defined even if the
10447 implementation elided its use. But don't warn about deprecation when
10448 eliding a temporary, as then no copy is actually performed. */
10449 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10450 if (force_elide)
10451 /* The language says this isn't called. */;
10452 else if (!trivial)
10454 if (!mark_used (fn, complain) && !(complain & tf_error))
10455 return error_mark_node;
10456 already_used = true;
10458 else
10459 cp_handle_deprecated_or_unavailable (fn, complain);
10461 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10462 && !make_base_init_ok (arg))
10463 unsafe = true;
10465 /* If we're creating a temp and we already have one, don't create a
10466 new one. If we're not creating a temp but we get one, use
10467 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10468 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10469 temp or an INIT_EXPR otherwise. */
10470 if (is_dummy_object (fa))
10472 if (TREE_CODE (arg) == TARGET_EXPR)
10473 return arg;
10474 else if (trivial)
10475 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10477 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10478 && !unsafe)
10480 tree to = cp_build_fold_indirect_ref (fa);
10481 val = cp_build_init_expr (to, arg);
10482 return val;
10485 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10486 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10487 && trivial_fn_p (fn))
10489 tree to = cp_build_fold_indirect_ref (argarray[0]);
10490 tree type = TREE_TYPE (to);
10491 tree as_base = CLASSTYPE_AS_BASE (type);
10492 tree arg = argarray[1];
10493 location_t loc = cp_expr_loc_or_input_loc (arg);
10495 if (is_really_empty_class (type, /*ignore_vptr*/true))
10497 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10498 if the object argument isn't one. This isn't needed in other cases
10499 since MODIFY_EXPR is always considered an lvalue. */
10500 to = cp_build_addr_expr (to, tf_none);
10501 to = cp_build_indirect_ref (input_location, to, RO_ARROW, complain);
10502 val = build2 (COMPOUND_EXPR, type, arg, to);
10503 suppress_warning (val, OPT_Wunused);
10505 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10507 if (is_std_init_list (type)
10508 && conv_binds_ref_to_prvalue (convs[1]))
10509 warning_at (loc, OPT_Winit_list_lifetime,
10510 "assignment from temporary %<initializer_list%> does "
10511 "not extend the lifetime of the underlying array");
10512 arg = cp_build_fold_indirect_ref (arg);
10513 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10515 else
10517 /* We must only copy the non-tail padding parts. */
10518 tree arg0, arg2, t;
10519 tree array_type, alias_set;
10521 arg2 = TYPE_SIZE_UNIT (as_base);
10522 to = cp_stabilize_reference (to);
10523 arg0 = cp_build_addr_expr (to, complain);
10525 array_type = build_array_type (unsigned_char_type_node,
10526 build_index_type
10527 (size_binop (MINUS_EXPR,
10528 arg2, size_int (1))));
10529 alias_set = build_int_cst (build_pointer_type (type), 0);
10530 t = build2 (MODIFY_EXPR, void_type_node,
10531 build2 (MEM_REF, array_type, arg0, alias_set),
10532 build2 (MEM_REF, array_type, arg, alias_set));
10533 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10534 suppress_warning (val, OPT_Wunused);
10537 cp_handle_deprecated_or_unavailable (fn, complain);
10539 return val;
10541 else if (trivial_fn_p (fn))
10543 if (DECL_DESTRUCTOR_P (fn))
10544 return build_trivial_dtor_call (argarray[0]);
10545 else if (default_ctor_p (fn))
10547 if (is_dummy_object (argarray[0]))
10548 return force_target_expr (DECL_CONTEXT (fn), void_node,
10549 no_cleanup_complain);
10550 else
10551 return cp_build_fold_indirect_ref (argarray[0]);
10555 gcc_assert (!force_elide);
10557 if (!already_used
10558 && !mark_used (fn, complain))
10559 return error_mark_node;
10561 /* Warn if the built-in writes to an object of a non-trivial type. */
10562 if (warn_class_memaccess
10563 && vec_safe_length (args) >= 2
10564 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10565 maybe_warn_class_memaccess (input_location, fn, args);
10567 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10569 tree t;
10570 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10571 DECL_CONTEXT (fn),
10572 ba_any, NULL, complain);
10573 gcc_assert (binfo && binfo != error_mark_node);
10575 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10576 complain);
10577 if (TREE_SIDE_EFFECTS (argarray[0]))
10578 argarray[0] = save_expr (argarray[0]);
10579 t = build_pointer_type (TREE_TYPE (fn));
10580 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10581 TREE_TYPE (fn) = t;
10583 else
10585 /* If FN is marked deprecated or unavailable, then we've already
10586 issued a diagnostic from mark_used above, so avoid redundantly
10587 issuing another one from build_addr_func. */
10588 auto w = make_temp_override (deprecated_state,
10589 UNAVAILABLE_DEPRECATED_SUPPRESS);
10591 fn = build_addr_func (fn, complain);
10592 if (fn == error_mark_node)
10593 return error_mark_node;
10595 /* We're actually invoking the function. (Immediate functions get an
10596 & when invoking it even though the user didn't use &.) */
10597 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
10600 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10601 if (call == error_mark_node)
10602 return call;
10603 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10605 tree c = extract_call_expr (call);
10606 /* build_new_op will clear this when appropriate. */
10607 CALL_EXPR_ORDERED_ARGS (c) = true;
10609 if (warned_p)
10611 tree c = extract_call_expr (call);
10612 if (TREE_CODE (c) == CALL_EXPR)
10613 suppress_warning (c /* Suppress all warnings. */);
10616 return call;
10619 namespace
10622 /* Return the DECL of the first non-static subobject of class TYPE
10623 that satisfies the predicate PRED or null if none can be found. */
10625 template <class Predicate>
10626 tree
10627 first_non_static_field (tree type, Predicate pred)
10629 if (!type || !CLASS_TYPE_P (type))
10630 return NULL_TREE;
10632 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10634 if (TREE_CODE (field) != FIELD_DECL)
10635 continue;
10636 if (TREE_STATIC (field))
10637 continue;
10638 if (pred (field))
10639 return field;
10642 int i = 0;
10644 for (tree base_binfo, binfo = TYPE_BINFO (type);
10645 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10647 tree base = TREE_TYPE (base_binfo);
10648 if (pred (base))
10649 return base;
10650 if (tree field = first_non_static_field (base, pred))
10651 return field;
10654 return NULL_TREE;
10657 struct NonPublicField
10659 bool operator() (const_tree t) const
10661 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10665 /* Return the DECL of the first non-public subobject of class TYPE
10666 or null if none can be found. */
10668 static inline tree
10669 first_non_public_field (tree type)
10671 return first_non_static_field (type, NonPublicField ());
10674 struct NonTrivialField
10676 bool operator() (const_tree t) const
10678 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10682 /* Return the DECL of the first non-trivial subobject of class TYPE
10683 or null if none can be found. */
10685 static inline tree
10686 first_non_trivial_field (tree type)
10688 return first_non_static_field (type, NonTrivialField ());
10691 } /* unnamed namespace */
10693 /* Return true if all copy and move assignment operator overloads for
10694 class TYPE are trivial and at least one of them is not deleted and,
10695 when ACCESS is set, accessible. Return false otherwise. Set
10696 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10697 copy or move assignment. */
10699 static bool
10700 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10702 tree fns = get_class_binding (type, assign_op_identifier);
10703 bool all_trivial = true;
10705 /* Iterate over overloads of the assignment operator, checking
10706 accessible copy assignments for triviality. */
10708 for (tree f : ovl_range (fns))
10710 /* Skip operators that aren't copy assignments. */
10711 if (!copy_fn_p (f))
10712 continue;
10714 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10715 || accessible_p (TYPE_BINFO (type), f, true));
10717 /* Skip template assignment operators and deleted functions. */
10718 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10719 continue;
10721 if (accessible)
10722 *hasassign = true;
10724 if (!accessible || !trivial_fn_p (f))
10725 all_trivial = false;
10727 /* Break early when both properties have been determined. */
10728 if (*hasassign && !all_trivial)
10729 break;
10732 /* Return true if they're all trivial and one of the expressions
10733 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10734 tree ref = cp_build_reference_type (type, false);
10735 return (all_trivial
10736 && (is_trivially_xible (MODIFY_EXPR, type, type)
10737 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10740 /* Return true if all copy and move ctor overloads for class TYPE are
10741 trivial and at least one of them is not deleted and, when ACCESS is
10742 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10743 to true when the TYPE has a (not necessarily trivial) default and copy
10744 (or move) ctor, respectively. */
10746 static bool
10747 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10749 tree fns = get_class_binding (type, complete_ctor_identifier);
10750 bool all_trivial = true;
10752 for (tree f : ovl_range (fns))
10754 /* Skip template constructors. */
10755 if (TREE_CODE (f) != FUNCTION_DECL)
10756 continue;
10758 bool cpy_or_move_ctor_p = copy_fn_p (f);
10760 /* Skip ctors other than default, copy, and move. */
10761 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10762 continue;
10764 if (DECL_DELETED_FN (f))
10765 continue;
10767 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10768 || accessible_p (TYPE_BINFO (type), f, true));
10770 if (accessible)
10771 hasctor[cpy_or_move_ctor_p] = true;
10773 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10774 all_trivial = false;
10776 /* Break early when both properties have been determined. */
10777 if (hasctor[0] && hasctor[1] && !all_trivial)
10778 break;
10781 return all_trivial;
10784 /* Issue a warning on a call to the built-in function FNDECL if it is
10785 a raw memory write whose destination is not an object of (something
10786 like) trivial or standard layout type with a non-deleted assignment
10787 and copy ctor. Detects const correctness violations, corrupting
10788 references, virtual table pointers, and bypassing non-trivial
10789 assignments. */
10791 static void
10792 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10793 const vec<tree, va_gc> *args)
10795 /* Except for bcopy where it's second, the destination pointer is
10796 the first argument for all functions handled here. Compute
10797 the index of the destination and source arguments. */
10798 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10799 unsigned srcidx = !dstidx;
10801 tree dest = (*args)[dstidx];
10802 if (!TREE_TYPE (dest)
10803 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10804 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10805 return;
10807 tree srctype = NULL_TREE;
10809 /* Determine the type of the pointed-to object and whether it's
10810 a complete class type. */
10811 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10813 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10814 return;
10816 /* Check to see if the raw memory call is made by a non-static member
10817 function with THIS as the destination argument for the destination
10818 type. If so, and if the class has no non-trivial bases or members,
10819 be more permissive. */
10820 if (current_function_decl
10821 && DECL_OBJECT_MEMBER_FUNCTION_P (current_function_decl)
10822 && is_object_parameter (tree_strip_nop_conversions (dest)))
10824 tree ctx = DECL_CONTEXT (current_function_decl);
10825 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10826 tree binfo = TYPE_BINFO (ctx);
10828 if (special
10829 && !BINFO_VTABLE (binfo)
10830 && !first_non_trivial_field (desttype))
10831 return;
10834 /* True if the class is trivial. */
10835 bool trivial = trivial_type_p (desttype);
10837 /* Set to true if DESTYPE has an accessible copy assignment. */
10838 bool hasassign = false;
10839 /* True if all of the class' overloaded copy assignment operators
10840 are all trivial (and not deleted) and at least one of them is
10841 accessible. */
10842 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10844 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10845 respectively. */
10846 bool hasctors[2] = { false, false };
10848 /* True if all of the class' overloaded copy constructors are all
10849 trivial (and not deleted) and at least one of them is accessible. */
10850 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10852 /* Set FLD to the first private/protected member of the class. */
10853 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10855 /* The warning format string. */
10856 const char *warnfmt = NULL;
10857 /* A suggested alternative to offer instead of the raw memory call.
10858 Empty string when none can be come up with. */
10859 const char *suggest = "";
10860 bool warned = false;
10862 switch (DECL_FUNCTION_CODE (fndecl))
10864 case BUILT_IN_MEMSET:
10865 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10867 /* Diagnose setting non-copy-assignable or non-trivial types,
10868 or types with a private member, to (potentially) non-zero
10869 bytes. Since the value of the bytes being written is unknown,
10870 suggest using assignment instead (if one exists). Also warn
10871 for writes into objects for which zero-initialization doesn't
10872 mean all bits clear (pointer-to-member data, where null is all
10873 bits set). Since the value being written is (most likely)
10874 non-zero, simply suggest assignment (but not copy assignment). */
10875 suggest = "; use assignment instead";
10876 if (!trivassign)
10877 warnfmt = G_("%qD writing to an object of type %#qT with "
10878 "no trivial copy-assignment");
10879 else if (!trivial)
10880 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10881 else if (fld)
10883 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10884 warned = warning_at (loc, OPT_Wclass_memaccess,
10885 "%qD writing to an object of type %#qT with "
10886 "%qs member %qD",
10887 fndecl, desttype, access, fld);
10889 else if (!zero_init_p (desttype))
10890 warnfmt = G_("%qD writing to an object of type %#qT containing "
10891 "a pointer to data member%s");
10893 break;
10895 /* Fall through. */
10897 case BUILT_IN_BZERO:
10898 /* Similarly to the above, diagnose clearing non-trivial or non-
10899 standard layout objects, or objects of types with no assignmenmt.
10900 Since the value being written is known to be zero, suggest either
10901 copy assignment, copy ctor, or default ctor as an alternative,
10902 depending on what's available. */
10904 if (hasassign && hasctors[0])
10905 suggest = G_("; use assignment or value-initialization instead");
10906 else if (hasassign)
10907 suggest = G_("; use assignment instead");
10908 else if (hasctors[0])
10909 suggest = G_("; use value-initialization instead");
10911 if (!trivassign)
10912 warnfmt = G_("%qD clearing an object of type %#qT with "
10913 "no trivial copy-assignment%s");
10914 else if (!trivial)
10915 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10916 else if (!zero_init_p (desttype))
10917 warnfmt = G_("%qD clearing an object of type %#qT containing "
10918 "a pointer-to-member%s");
10919 break;
10921 case BUILT_IN_BCOPY:
10922 case BUILT_IN_MEMCPY:
10923 case BUILT_IN_MEMMOVE:
10924 case BUILT_IN_MEMPCPY:
10925 /* Determine the type of the source object. */
10926 srctype = TREE_TYPE ((*args)[srcidx]);
10927 if (!srctype || !INDIRECT_TYPE_P (srctype))
10928 srctype = void_type_node;
10929 else
10930 srctype = TREE_TYPE (srctype);
10932 /* Since it's impossible to determine wheter the byte copy is
10933 being used in place of assignment to an existing object or
10934 as a substitute for initialization, assume it's the former.
10935 Determine the best alternative to use instead depending on
10936 what's not deleted. */
10937 if (hasassign && hasctors[1])
10938 suggest = G_("; use copy-assignment or copy-initialization instead");
10939 else if (hasassign)
10940 suggest = G_("; use copy-assignment instead");
10941 else if (hasctors[1])
10942 suggest = G_("; use copy-initialization instead");
10944 if (!trivassign)
10945 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10946 "copy-assignment%s");
10947 else if (!trivially_copyable_p (desttype))
10948 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10949 "type %#qT%s");
10950 else if (!trivcopy)
10951 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10953 else if (!trivial
10954 && !VOID_TYPE_P (srctype)
10955 && !is_byte_access_type (srctype)
10956 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10957 srctype))
10959 /* Warn when copying into a non-trivial object from an object
10960 of a different type other than void or char. */
10961 warned = warning_at (loc, OPT_Wclass_memaccess,
10962 "%qD copying an object of non-trivial type "
10963 "%#qT from an array of %#qT",
10964 fndecl, desttype, srctype);
10966 else if (fld
10967 && !VOID_TYPE_P (srctype)
10968 && !is_byte_access_type (srctype)
10969 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10970 srctype))
10972 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10973 warned = warning_at (loc, OPT_Wclass_memaccess,
10974 "%qD copying an object of type %#qT with "
10975 "%qs member %qD from an array of %#qT; use "
10976 "assignment or copy-initialization instead",
10977 fndecl, desttype, access, fld, srctype);
10979 else if (!trivial && vec_safe_length (args) > 2)
10981 tree sz = maybe_constant_value ((*args)[2]);
10982 if (!tree_fits_uhwi_p (sz))
10983 break;
10985 /* Finally, warn on partial copies. */
10986 unsigned HOST_WIDE_INT typesize
10987 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10988 if (typesize == 0)
10989 break;
10990 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10991 warned = warning_at (loc, OPT_Wclass_memaccess,
10992 (typesize - partial > 1
10993 ? G_("%qD writing to an object of "
10994 "a non-trivial type %#qT leaves %wu "
10995 "bytes unchanged")
10996 : G_("%qD writing to an object of "
10997 "a non-trivial type %#qT leaves %wu "
10998 "byte unchanged")),
10999 fndecl, desttype, typesize - partial);
11001 break;
11003 case BUILT_IN_REALLOC:
11005 if (!trivially_copyable_p (desttype))
11006 warnfmt = G_("%qD moving an object of non-trivially copyable type "
11007 "%#qT; use %<new%> and %<delete%> instead");
11008 else if (!trivcopy)
11009 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
11010 "constructor; use %<new%> and %<delete%> instead");
11011 else if (!get_dtor (desttype, tf_none))
11012 warnfmt = G_("%qD moving an object of type %#qT with deleted "
11013 "destructor");
11014 else if (!trivial)
11016 tree sz = maybe_constant_value ((*args)[1]);
11017 if (TREE_CODE (sz) == INTEGER_CST
11018 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
11019 /* Finally, warn on reallocation into insufficient space. */
11020 warned = warning_at (loc, OPT_Wclass_memaccess,
11021 "%qD moving an object of non-trivial type "
11022 "%#qT and size %E into a region of size %E",
11023 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
11024 sz);
11026 break;
11028 default:
11029 return;
11032 if (warnfmt)
11034 if (suggest)
11035 warned = warning_at (loc, OPT_Wclass_memaccess,
11036 warnfmt, fndecl, desttype, suggest);
11037 else
11038 warned = warning_at (loc, OPT_Wclass_memaccess,
11039 warnfmt, fndecl, desttype);
11042 if (warned)
11043 inform (location_of (desttype), "%#qT declared here", desttype);
11046 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
11047 If FN is the result of resolving an overloaded target built-in,
11048 ORIG_FNDECL is the original function decl, otherwise it is null.
11049 This function performs no overload resolution, conversion, or other
11050 high-level operations. */
11052 tree
11053 build_cxx_call (tree fn, int nargs, tree *argarray,
11054 tsubst_flags_t complain, tree orig_fndecl)
11056 tree fndecl;
11058 /* Remember roughly where this call is. */
11059 location_t loc = cp_expr_loc_or_input_loc (fn);
11060 fn = build_call_a (fn, nargs, argarray);
11061 SET_EXPR_LOCATION (fn, loc);
11063 fndecl = get_callee_fndecl (fn);
11064 if (!orig_fndecl)
11065 orig_fndecl = fndecl;
11067 /* Check that arguments to builtin functions match the expectations. */
11068 if (fndecl
11069 && !processing_template_decl
11070 && fndecl_built_in_p (fndecl))
11072 int i;
11074 /* We need to take care that values to BUILT_IN_NORMAL
11075 are reduced. */
11076 for (i = 0; i < nargs; i++)
11077 argarray[i] = maybe_constant_value (argarray[i]);
11079 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
11080 orig_fndecl, nargs, argarray))
11081 return error_mark_node;
11082 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
11084 tree arg0 = argarray[0];
11085 STRIP_NOPS (arg0);
11086 if (TREE_CODE (arg0) == ADDR_EXPR
11087 && DECL_P (TREE_OPERAND (arg0, 0))
11088 && same_type_ignoring_top_level_qualifiers_p
11089 (TREE_TYPE (TREE_TYPE (argarray[0])),
11090 TREE_TYPE (TREE_TYPE (arg0))))
11091 /* For __builtin_clear_padding (&var) we know the type
11092 is for a complete object, so there is no risk in clearing
11093 padding that is reused in some derived class member. */;
11094 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
11096 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
11097 "argument %u in call to function %qE "
11098 "has pointer to a non-trivially-copyable type (%qT)",
11099 1, fndecl, TREE_TYPE (argarray[0]));
11100 return error_mark_node;
11105 if (VOID_TYPE_P (TREE_TYPE (fn)))
11106 return fn;
11108 /* 5.2.2/11: If a function call is a prvalue of object type: if the
11109 function call is either the operand of a decltype-specifier or the
11110 right operand of a comma operator that is the operand of a
11111 decltype-specifier, a temporary object is not introduced for the
11112 prvalue. The type of the prvalue may be incomplete. */
11113 if (!(complain & tf_decltype))
11115 fn = require_complete_type (fn, complain);
11116 if (fn == error_mark_node)
11117 return error_mark_node;
11119 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
11121 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
11122 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
11125 return convert_from_reference (fn);
11128 /* Returns the value to use for the in-charge parameter when making a
11129 call to a function with the indicated NAME.
11131 FIXME:Can't we find a neater way to do this mapping? */
11133 tree
11134 in_charge_arg_for_name (tree name)
11136 if (IDENTIFIER_CTOR_P (name))
11138 if (name == complete_ctor_identifier)
11139 return integer_one_node;
11140 gcc_checking_assert (name == base_ctor_identifier);
11142 else
11144 if (name == complete_dtor_identifier)
11145 return integer_two_node;
11146 else if (name == deleting_dtor_identifier)
11147 return integer_three_node;
11148 gcc_checking_assert (name == base_dtor_identifier);
11151 return integer_zero_node;
11154 /* We've built up a constructor call RET. Complain if it delegates to the
11155 constructor we're currently compiling. */
11157 static void
11158 check_self_delegation (tree ret)
11160 if (TREE_CODE (ret) == TARGET_EXPR)
11161 ret = TARGET_EXPR_INITIAL (ret);
11162 tree fn = cp_get_callee_fndecl_nofold (ret);
11163 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11164 error ("constructor delegates to itself");
11167 /* Build a call to a constructor, destructor, or an assignment
11168 operator for INSTANCE, an expression with class type. NAME
11169 indicates the special member function to call; *ARGS are the
11170 arguments. ARGS may be NULL. This may change ARGS. BINFO
11171 indicates the base of INSTANCE that is to be passed as the `this'
11172 parameter to the member function called.
11174 FLAGS are the LOOKUP_* flags to use when processing the call.
11176 If NAME indicates a complete object constructor, INSTANCE may be
11177 NULL_TREE. In this case, the caller will call build_cplus_new to
11178 store the newly constructed object into a VAR_DECL. */
11180 tree
11181 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11182 tree binfo, int flags, tsubst_flags_t complain)
11184 tree fns;
11185 /* The type of the subobject to be constructed or destroyed. */
11186 tree class_type;
11187 vec<tree, va_gc> *allocated = NULL;
11188 tree ret;
11190 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11192 if (error_operand_p (instance))
11193 return error_mark_node;
11195 if (IDENTIFIER_DTOR_P (name))
11197 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11198 if (!type_build_dtor_call (TREE_TYPE (instance)))
11199 /* Shortcut to avoid lazy destructor declaration. */
11200 return build_trivial_dtor_call (instance);
11203 if (TYPE_P (binfo))
11205 /* Resolve the name. */
11206 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11207 return error_mark_node;
11209 binfo = TYPE_BINFO (binfo);
11212 gcc_assert (binfo != NULL_TREE);
11214 class_type = BINFO_TYPE (binfo);
11216 /* Handle the special case where INSTANCE is NULL_TREE. */
11217 if (name == complete_ctor_identifier && !instance)
11218 instance = build_dummy_object (class_type);
11219 else
11221 /* Convert to the base class, if necessary. */
11222 if (!same_type_ignoring_top_level_qualifiers_p
11223 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11225 if (IDENTIFIER_CDTOR_P (name))
11226 /* For constructors and destructors, either the base is
11227 non-virtual, or it is virtual but we are doing the
11228 conversion from a constructor or destructor for the
11229 complete object. In either case, we can convert
11230 statically. */
11231 instance = convert_to_base_statically (instance, binfo);
11232 else
11234 /* However, for assignment operators, we must convert
11235 dynamically if the base is virtual. */
11236 gcc_checking_assert (name == assign_op_identifier);
11237 instance = build_base_path (PLUS_EXPR, instance,
11238 binfo, /*nonnull=*/1, complain);
11243 gcc_assert (instance != NULL_TREE);
11245 /* In C++17, "If the initializer expression is a prvalue and the
11246 cv-unqualified version of the source type is the same class as the class
11247 of the destination, the initializer expression is used to initialize the
11248 destination object." Handle that here to avoid doing overload
11249 resolution. */
11250 if (cxx_dialect >= cxx17
11251 && args && vec_safe_length (*args) == 1
11252 && !unsafe_return_slot_p (instance))
11254 tree arg = (**args)[0];
11256 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11257 && !TYPE_HAS_LIST_CTOR (class_type)
11258 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11259 && CONSTRUCTOR_NELTS (arg) == 1)
11260 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11262 if ((TREE_CODE (arg) == TARGET_EXPR
11263 || TREE_CODE (arg) == CONSTRUCTOR)
11264 && (same_type_ignoring_top_level_qualifiers_p
11265 (class_type, TREE_TYPE (arg))))
11267 if (is_dummy_object (instance))
11268 return arg;
11269 else if (TREE_CODE (arg) == TARGET_EXPR)
11270 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11272 if ((complain & tf_error)
11273 && (flags & LOOKUP_DELEGATING_CONS))
11274 check_self_delegation (arg);
11275 /* Avoid change of behavior on Wunused-var-2.C. */
11276 instance = mark_lvalue_use (instance);
11277 return cp_build_init_expr (instance, arg);
11281 fns = lookup_fnfields (binfo, name, 1, complain);
11283 /* When making a call to a constructor or destructor for a subobject
11284 that uses virtual base classes, pass down a pointer to a VTT for
11285 the subobject. */
11286 if ((name == base_ctor_identifier
11287 || name == base_dtor_identifier)
11288 && CLASSTYPE_VBASECLASSES (class_type))
11290 tree vtt;
11291 tree sub_vtt;
11293 /* If the current function is a complete object constructor
11294 or destructor, then we fetch the VTT directly.
11295 Otherwise, we look it up using the VTT we were given. */
11296 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11297 vtt = decay_conversion (vtt, complain);
11298 if (vtt == error_mark_node)
11299 return error_mark_node;
11300 vtt = build_if_in_charge (vtt, current_vtt_parm);
11301 if (BINFO_SUBVTT_INDEX (binfo))
11302 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11303 else
11304 sub_vtt = vtt;
11306 if (args == NULL)
11308 allocated = make_tree_vector ();
11309 args = &allocated;
11312 vec_safe_insert (*args, 0, sub_vtt);
11315 ret = build_new_method_call (instance, fns, args,
11316 TYPE_BINFO (BINFO_TYPE (binfo)),
11317 flags, /*fn=*/NULL,
11318 complain);
11320 if (allocated != NULL)
11321 release_tree_vector (allocated);
11323 if ((complain & tf_error)
11324 && (flags & LOOKUP_DELEGATING_CONS)
11325 && name == complete_ctor_identifier)
11326 check_self_delegation (ret);
11328 return ret;
11331 /* Return the NAME, as a C string. The NAME indicates a function that
11332 is a member of TYPE. *FREE_P is set to true if the caller must
11333 free the memory returned.
11335 Rather than go through all of this, we should simply set the names
11336 of constructors and destructors appropriately, and dispense with
11337 ctor_identifier, dtor_identifier, etc. */
11339 static char *
11340 name_as_c_string (tree name, tree type, bool *free_p)
11342 const char *pretty_name;
11344 /* Assume that we will not allocate memory. */
11345 *free_p = false;
11346 /* Constructors and destructors are special. */
11347 if (IDENTIFIER_CDTOR_P (name))
11349 pretty_name
11350 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11351 /* For a destructor, add the '~'. */
11352 if (IDENTIFIER_DTOR_P (name))
11354 pretty_name = concat ("~", pretty_name, NULL);
11355 /* Remember that we need to free the memory allocated. */
11356 *free_p = true;
11359 else if (IDENTIFIER_CONV_OP_P (name))
11361 pretty_name = concat ("operator ",
11362 type_as_string_translate (TREE_TYPE (name),
11363 TFF_PLAIN_IDENTIFIER),
11364 NULL);
11365 /* Remember that we need to free the memory allocated. */
11366 *free_p = true;
11368 else
11369 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11371 return CONST_CAST (char *, pretty_name);
11374 /* If CANDIDATES contains exactly one candidate, return it, otherwise
11375 return NULL. */
11377 static z_candidate *
11378 single_z_candidate (z_candidate *candidates)
11380 if (candidates == NULL)
11381 return NULL;
11383 if (candidates->next)
11384 return NULL;
11386 return candidates;
11389 /* If CANDIDATE is invalid due to a bad argument type, return the
11390 pertinent conversion_info.
11392 Otherwise, return NULL. */
11394 static const conversion_info *
11395 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11397 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11398 rejection_reason *r = candidate->reason;
11400 if (r == NULL)
11401 return NULL;
11403 switch (r->code)
11405 default:
11406 return NULL;
11408 case rr_arg_conversion:
11409 return &r->u.conversion;
11411 case rr_bad_arg_conversion:
11412 return &r->u.bad_conversion;
11416 /* Issue an error and note complaining about a bad argument type at a
11417 callsite with a single candidate FNDECL.
11419 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11420 case input_location is used).
11421 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11422 the formal parameter. */
11424 void
11425 complain_about_bad_argument (location_t arg_loc,
11426 tree from_type, tree to_type,
11427 tree fndecl, int parmnum)
11429 auto_diagnostic_group d;
11430 range_label_for_type_mismatch rhs_label (from_type, to_type);
11431 range_label *label = &rhs_label;
11432 if (arg_loc == UNKNOWN_LOCATION)
11434 arg_loc = input_location;
11435 label = NULL;
11437 gcc_rich_location richloc (arg_loc, label);
11438 error_at (&richloc,
11439 "cannot convert %qH to %qI",
11440 from_type, to_type);
11441 maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
11442 parmnum);
11445 /* Subroutine of build_new_method_call_1, for where there are no viable
11446 candidates for the call. */
11448 static void
11449 complain_about_no_candidates_for_method_call (tree instance,
11450 z_candidate *candidates,
11451 tree explicit_targs,
11452 tree basetype,
11453 tree optype, tree name,
11454 bool skip_first_for_error,
11455 vec<tree, va_gc> *user_args)
11457 auto_diagnostic_group d;
11458 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11459 cxx_incomplete_type_error (instance, basetype);
11460 else if (optype)
11461 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11462 basetype, optype, build_tree_list_vec (user_args),
11463 TREE_TYPE (instance));
11464 else
11466 /* Special-case for when there's a single candidate that's failing
11467 due to a bad argument type. */
11468 if (z_candidate *candidate = single_z_candidate (candidates))
11469 if (const conversion_info *conv
11470 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11472 tree from_type = conv->from;
11473 if (!TYPE_P (conv->from))
11474 from_type = lvalue_type (conv->from);
11475 complain_about_bad_argument (conv->loc,
11476 from_type, conv->to_type,
11477 candidate->fn, conv->n_arg);
11478 return;
11481 tree arglist = build_tree_list_vec (user_args);
11482 tree errname = name;
11483 bool twiddle = false;
11484 if (IDENTIFIER_CDTOR_P (errname))
11486 twiddle = IDENTIFIER_DTOR_P (errname);
11487 errname = constructor_name (basetype);
11489 if (explicit_targs)
11490 errname = lookup_template_function (errname, explicit_targs);
11491 if (skip_first_for_error)
11492 arglist = TREE_CHAIN (arglist);
11493 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11494 basetype, &"~"[!twiddle], errname, arglist,
11495 TREE_TYPE (instance));
11497 print_z_candidates (location_of (name), candidates);
11500 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11501 be set, upon return, to the function called. ARGS may be NULL.
11502 This may change ARGS. */
11504 tree
11505 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11506 tree conversion_path, int flags,
11507 tree *fn_p, tsubst_flags_t complain)
11509 struct z_candidate *candidates = 0, *cand;
11510 tree explicit_targs = NULL_TREE;
11511 tree basetype = NULL_TREE;
11512 tree access_binfo;
11513 tree optype;
11514 tree first_mem_arg = NULL_TREE;
11515 tree name;
11516 bool skip_first_for_error;
11517 vec<tree, va_gc> *user_args;
11518 tree call;
11519 tree fn;
11520 int template_only = 0;
11521 bool any_viable_p;
11522 tree orig_instance;
11523 tree orig_fns;
11524 vec<tree, va_gc> *orig_args = NULL;
11526 auto_cond_timevar tv (TV_OVERLOAD);
11528 gcc_assert (instance != NULL_TREE);
11530 /* We don't know what function we're going to call, yet. */
11531 if (fn_p)
11532 *fn_p = NULL_TREE;
11534 if (error_operand_p (instance)
11535 || !fns || error_operand_p (fns))
11536 return error_mark_node;
11538 if (!BASELINK_P (fns))
11540 if (complain & tf_error)
11541 error ("call to non-function %qD", fns);
11542 return error_mark_node;
11545 orig_instance = instance;
11546 orig_fns = fns;
11548 /* Dismantle the baselink to collect all the information we need. */
11549 if (!conversion_path)
11550 conversion_path = BASELINK_BINFO (fns);
11551 access_binfo = BASELINK_ACCESS_BINFO (fns);
11552 optype = BASELINK_OPTYPE (fns);
11553 fns = BASELINK_FUNCTIONS (fns);
11554 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11556 explicit_targs = TREE_OPERAND (fns, 1);
11557 fns = TREE_OPERAND (fns, 0);
11558 template_only = 1;
11560 gcc_assert (OVL_P (fns));
11561 fn = OVL_FIRST (fns);
11562 name = DECL_NAME (fn);
11564 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11565 gcc_assert (CLASS_TYPE_P (basetype));
11567 user_args = args == NULL ? NULL : *args;
11568 /* Under DR 147 A::A() is an invalid constructor call,
11569 not a functional cast. */
11570 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11572 if (! (complain & tf_error))
11573 return error_mark_node;
11575 basetype = DECL_CONTEXT (fn);
11576 name = constructor_name (basetype);
11577 auto_diagnostic_group d;
11578 if (permerror (input_location,
11579 "cannot call constructor %<%T::%D%> directly",
11580 basetype, name))
11581 inform (input_location, "for a function-style cast, remove the "
11582 "redundant %<::%D%>", name);
11583 call = build_functional_cast (input_location, basetype,
11584 build_tree_list_vec (user_args),
11585 complain);
11586 return call;
11589 if (processing_template_decl)
11590 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11592 /* Process the argument list. */
11593 if (args != NULL && *args != NULL)
11595 *args = resolve_args (*args, complain);
11596 if (*args == NULL)
11597 return error_mark_node;
11598 user_args = *args;
11601 /* Consider the object argument to be used even if we end up selecting a
11602 static member function. */
11603 instance = mark_type_use (instance);
11605 /* Figure out whether to skip the first argument for the error
11606 message we will display to users if an error occurs. We don't
11607 want to display any compiler-generated arguments. The "this"
11608 pointer hasn't been added yet. However, we must remove the VTT
11609 pointer if this is a call to a base-class constructor or
11610 destructor. */
11611 skip_first_for_error = false;
11612 if (IDENTIFIER_CDTOR_P (name))
11614 /* Callers should explicitly indicate whether they want to ctor
11615 the complete object or just the part without virtual bases. */
11616 gcc_assert (name != ctor_identifier);
11618 /* Remove the VTT pointer, if present. */
11619 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11620 && CLASSTYPE_VBASECLASSES (basetype))
11621 skip_first_for_error = true;
11623 /* It's OK to call destructors and constructors on cv-qualified
11624 objects. Therefore, convert the INSTANCE to the unqualified
11625 type, if necessary. */
11626 if (!same_type_p (basetype, TREE_TYPE (instance)))
11628 instance = build_this (instance);
11629 instance = build_nop (build_pointer_type (basetype), instance);
11630 instance = build_fold_indirect_ref (instance);
11633 else
11634 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11636 /* For the overload resolution we need to find the actual `this`
11637 that would be captured if the call turns out to be to a
11638 non-static member function. Do not actually capture it at this
11639 point. */
11640 if (DECL_CONSTRUCTOR_P (fn))
11641 /* Constructors don't use the enclosing 'this'. */
11642 first_mem_arg = instance;
11643 else
11644 first_mem_arg = maybe_resolve_dummy (instance, false);
11646 conversion_obstack_sentinel cos;
11648 /* The number of arguments artificial parms in ARGS; we subtract one because
11649 there's no 'this' in ARGS. */
11650 unsigned skip = num_artificial_parms_for (fn) - 1;
11652 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11653 initializer, not T({ }). */
11654 if (DECL_CONSTRUCTOR_P (fn)
11655 && vec_safe_length (user_args) > skip
11656 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11658 tree init_list = (*user_args)[skip];
11659 tree init = NULL_TREE;
11661 gcc_assert (user_args->length () == skip + 1
11662 && !(flags & LOOKUP_ONLYCONVERTING));
11664 /* If the initializer list has no elements and T is a class type with
11665 a default constructor, the object is value-initialized. Handle
11666 this here so we don't need to handle it wherever we use
11667 build_special_member_call. */
11668 if (CONSTRUCTOR_NELTS (init_list) == 0
11669 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11670 /* For a user-provided default constructor, use the normal
11671 mechanisms so that protected access works. */
11672 && type_has_non_user_provided_default_constructor (basetype)
11673 && !processing_template_decl)
11674 init = build_value_init (basetype, complain);
11676 /* If BASETYPE is an aggregate, we need to do aggregate
11677 initialization. */
11678 else if (CP_AGGREGATE_TYPE_P (basetype))
11680 init = reshape_init (basetype, init_list, complain);
11681 init = digest_init (basetype, init, complain);
11684 if (init)
11686 if (is_dummy_object (instance))
11687 return get_target_expr (init, complain);
11688 return cp_build_init_expr (instance, init);
11691 /* Otherwise go ahead with overload resolution. */
11692 add_list_candidates (fns, first_mem_arg, user_args,
11693 basetype, explicit_targs, template_only,
11694 conversion_path, access_binfo, flags,
11695 &candidates, complain);
11697 else
11698 add_candidates (fns, first_mem_arg, user_args, optype,
11699 explicit_targs, template_only, conversion_path,
11700 access_binfo, flags, &candidates, complain);
11702 any_viable_p = false;
11703 candidates = splice_viable (candidates, false, &any_viable_p);
11705 if (!any_viable_p)
11707 /* [dcl.init], 17.6.2.2:
11709 Otherwise, if no constructor is viable, the destination type is
11710 a (possibly cv-qualified) aggregate class A, and the initializer
11711 is a parenthesized expression-list, the object is initialized as
11712 follows...
11714 We achieve this by building up a CONSTRUCTOR, as for list-init,
11715 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11716 the two. */
11717 if (DECL_CONSTRUCTOR_P (fn)
11718 && !(flags & LOOKUP_ONLYCONVERTING)
11719 && cxx_dialect >= cxx20
11720 && CP_AGGREGATE_TYPE_P (basetype)
11721 && !vec_safe_is_empty (user_args))
11723 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11724 tree ctor = build_constructor_from_vec (init_list_type_node,
11725 user_args);
11726 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11727 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11728 if (is_dummy_object (instance))
11729 return ctor;
11730 else
11732 ctor = digest_init (basetype, ctor, complain);
11733 if (ctor == error_mark_node)
11734 return error_mark_node;
11735 return cp_build_init_expr (instance, ctor);
11738 if (complain & tf_error)
11739 complain_about_no_candidates_for_method_call (instance, candidates,
11740 explicit_targs, basetype,
11741 optype, name,
11742 skip_first_for_error,
11743 user_args);
11744 call = error_mark_node;
11746 else
11748 cand = tourney (candidates, complain);
11749 if (cand == 0)
11751 char *pretty_name;
11752 bool free_p;
11753 tree arglist;
11755 if (complain & tf_error)
11757 pretty_name = name_as_c_string (name, basetype, &free_p);
11758 arglist = build_tree_list_vec (user_args);
11759 if (skip_first_for_error)
11760 arglist = TREE_CHAIN (arglist);
11761 auto_diagnostic_group d;
11762 if (!any_strictly_viable (candidates))
11763 error ("no matching function for call to %<%s(%A)%>",
11764 pretty_name, arglist);
11765 else
11766 error ("call of overloaded %<%s(%A)%> is ambiguous",
11767 pretty_name, arglist);
11768 print_z_candidates (location_of (name), candidates);
11769 if (free_p)
11770 free (pretty_name);
11772 call = error_mark_node;
11773 if (fn_p)
11774 *fn_p = error_mark_node;
11776 else
11778 fn = cand->fn;
11779 call = NULL_TREE;
11781 if (!(flags & LOOKUP_NONVIRTUAL)
11782 && DECL_PURE_VIRTUAL_P (fn)
11783 && instance == current_class_ref
11784 && (complain & tf_warning))
11786 /* This is not an error, it is runtime undefined
11787 behavior. */
11788 if (!current_function_decl)
11789 warning (0, "pure virtual %q#D called from "
11790 "non-static data member initializer", fn);
11791 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11792 || DECL_DESTRUCTOR_P (current_function_decl))
11793 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11794 ? G_("pure virtual %q#D called from constructor")
11795 : G_("pure virtual %q#D called from destructor")),
11796 fn);
11799 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11800 && !DECL_CONSTRUCTOR_P (fn)
11801 && is_dummy_object (instance))
11803 instance = maybe_resolve_dummy (instance, true);
11804 if (instance == error_mark_node)
11805 call = error_mark_node;
11806 else if (!is_dummy_object (instance))
11808 /* We captured 'this' in the current lambda now that
11809 we know we really need it. */
11810 cand->first_arg = instance;
11812 else if (current_class_ptr && any_dependent_bases_p ())
11813 /* We can't tell until instantiation time whether we can use
11814 *this as the implicit object argument. */;
11815 else
11817 if (complain & tf_error)
11818 error ("cannot call member function %qD without object",
11819 fn);
11820 call = error_mark_node;
11824 if (call != error_mark_node)
11826 /* Now we know what function is being called. */
11827 if (fn_p)
11828 *fn_p = fn;
11829 /* Build the actual CALL_EXPR. */
11830 call = build_over_call (cand, flags, complain);
11832 /* Suppress warnings for if (my_struct.operator= (x)) where
11833 my_struct is implicitly converted to bool. */
11834 if (TREE_CODE (call) == MODIFY_EXPR)
11835 suppress_warning (call, OPT_Wparentheses);
11837 /* In an expression of the form `a->f()' where `f' turns
11838 out to be a static member function, `a' is
11839 none-the-less evaluated. */
11840 if (!is_dummy_object (instance))
11841 call = keep_unused_object_arg (call, instance, fn);
11842 if (call != error_mark_node
11843 && DECL_DESTRUCTOR_P (cand->fn)
11844 && !VOID_TYPE_P (TREE_TYPE (call)))
11845 /* An explicit call of the form "x->~X()" has type
11846 "void". However, on platforms where destructors
11847 return "this" (i.e., those where
11848 targetm.cxx.cdtor_returns_this is true), such calls
11849 will appear to have a return value of pointer type
11850 to the low-level call machinery. We do not want to
11851 change the low-level machinery, since we want to be
11852 able to optimize "delete f()" on such platforms as
11853 "operator delete(~X(f()))" (rather than generating
11854 "t = f(), ~X(t), operator delete (t)"). */
11855 call = build_nop (void_type_node, call);
11860 if (processing_template_decl && call != error_mark_node)
11862 bool cast_to_void = false;
11864 if (TREE_CODE (call) == COMPOUND_EXPR)
11865 call = TREE_OPERAND (call, 1);
11866 else if (TREE_CODE (call) == NOP_EXPR)
11868 cast_to_void = true;
11869 call = TREE_OPERAND (call, 0);
11871 if (INDIRECT_REF_P (call))
11872 call = TREE_OPERAND (call, 0);
11874 /* Prune all but the selected function from the original overload
11875 set so that we can avoid some duplicate work at instantiation time. */
11876 if (really_overloaded_fn (fns))
11878 if (DECL_TEMPLATE_INFO (fn)
11879 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11881 /* Use the selected template, not the specialization, so that
11882 this looks like an actual lookup result for sake of
11883 filter_memfn_lookup. */
11885 if (OVL_SINGLE_P (fns))
11886 /* If the original overload set consists of a single function
11887 template, this isn't beneficial. */
11888 goto skip_prune;
11890 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11891 if (template_only)
11892 fn = lookup_template_function (fn, explicit_targs);
11894 orig_fns = copy_node (orig_fns);
11895 BASELINK_FUNCTIONS (orig_fns) = fn;
11896 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11899 skip_prune:
11900 call = (build_min_non_dep_call_vec
11901 (call,
11902 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11903 orig_instance, orig_fns, NULL_TREE),
11904 orig_args));
11905 SET_EXPR_LOCATION (call, input_location);
11906 call = convert_from_reference (call);
11907 if (cast_to_void)
11908 call = build_nop (void_type_node, call);
11911 if (orig_args != NULL)
11912 release_tree_vector (orig_args);
11914 return call;
11917 /* Returns true iff standard conversion sequence ICS1 is a proper
11918 subsequence of ICS2. */
11920 static bool
11921 is_subseq (conversion *ics1, conversion *ics2)
11923 /* We can assume that a conversion of the same code
11924 between the same types indicates a subsequence since we only get
11925 here if the types we are converting from are the same. */
11927 while (ics1->kind == ck_rvalue
11928 || ics1->kind == ck_lvalue)
11929 ics1 = next_conversion (ics1);
11931 while (1)
11933 while (ics2->kind == ck_rvalue
11934 || ics2->kind == ck_lvalue)
11935 ics2 = next_conversion (ics2);
11937 if (ics2->kind == ck_user
11938 || !has_next (ics2->kind))
11939 /* At this point, ICS1 cannot be a proper subsequence of
11940 ICS2. We can get a USER_CONV when we are comparing the
11941 second standard conversion sequence of two user conversion
11942 sequences. */
11943 return false;
11945 ics2 = next_conversion (ics2);
11947 while (ics2->kind == ck_rvalue
11948 || ics2->kind == ck_lvalue)
11949 ics2 = next_conversion (ics2);
11951 if (ics2->kind == ics1->kind
11952 && same_type_p (ics2->type, ics1->type)
11953 && (ics1->kind == ck_identity
11954 || same_type_p (next_conversion (ics2)->type,
11955 next_conversion (ics1)->type)))
11956 return true;
11960 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11961 be any _TYPE nodes. */
11963 bool
11964 is_properly_derived_from (tree derived, tree base)
11966 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11967 return false;
11969 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11970 considers every class derived from itself. */
11971 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11972 && DERIVED_FROM_P (base, derived));
11975 /* We build the ICS for an implicit object parameter as a pointer
11976 conversion sequence. However, such a sequence should be compared
11977 as if it were a reference conversion sequence. If ICS is the
11978 implicit conversion sequence for an implicit object parameter,
11979 modify it accordingly. */
11981 static void
11982 maybe_handle_implicit_object (conversion **ics)
11984 if ((*ics)->this_p)
11986 /* [over.match.funcs]
11988 For non-static member functions, the type of the
11989 implicit object parameter is "reference to cv X"
11990 where X is the class of which the function is a
11991 member and cv is the cv-qualification on the member
11992 function declaration. */
11993 conversion *t = *ics;
11994 tree reference_type;
11996 /* The `this' parameter is a pointer to a class type. Make the
11997 implicit conversion talk about a reference to that same class
11998 type. */
11999 reference_type = TREE_TYPE (t->type);
12000 reference_type = build_reference_type (reference_type);
12002 if (t->kind == ck_qual)
12003 t = next_conversion (t);
12004 if (t->kind == ck_ptr)
12005 t = next_conversion (t);
12006 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
12007 t = direct_reference_binding (reference_type, t);
12008 t->this_p = 1;
12009 t->rvaluedness_matches_p = 0;
12010 *ics = t;
12014 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
12015 and return the initial reference binding conversion. Otherwise,
12016 leave *ICS unchanged and return NULL. */
12018 static conversion *
12019 maybe_handle_ref_bind (conversion **ics)
12021 if ((*ics)->kind == ck_ref_bind)
12023 conversion *old_ics = *ics;
12024 *ics = next_conversion (old_ics);
12025 (*ics)->user_conv_p = old_ics->user_conv_p;
12026 return old_ics;
12029 return NULL;
12032 /* Get the expression at the beginning of the conversion chain C. */
12034 static tree
12035 conv_get_original_expr (conversion *c)
12037 for (; c; c = next_conversion (c))
12038 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
12039 return c->u.expr;
12040 return NULL_TREE;
12043 /* Return a tree representing the number of elements initialized by the
12044 list-initialization C. The caller must check that C converts to an
12045 array type. */
12047 static tree
12048 nelts_initialized_by_list_init (conversion *c)
12050 /* If the array we're converting to has a dimension, we'll use that. */
12051 if (TYPE_DOMAIN (c->type))
12052 return array_type_nelts_top (c->type);
12053 else
12055 /* Otherwise, we look at how many elements the constructor we're
12056 initializing from has. */
12057 tree ctor = conv_get_original_expr (c);
12058 return size_int (CONSTRUCTOR_NELTS (ctor));
12062 /* True iff C is a conversion that binds a reference or a pointer to
12063 an array of unknown bound. */
12065 static inline bool
12066 conv_binds_to_array_of_unknown_bound (conversion *c)
12068 /* ck_ref_bind won't have the reference stripped. */
12069 tree type = non_reference (c->type);
12070 /* ck_qual won't have the pointer stripped. */
12071 type = strip_pointer_operator (type);
12072 return (TREE_CODE (type) == ARRAY_TYPE
12073 && TYPE_DOMAIN (type) == NULL_TREE);
12076 /* Compare two implicit conversion sequences according to the rules set out in
12077 [over.ics.rank]. Return values:
12079 1: ics1 is better than ics2
12080 -1: ics2 is better than ics1
12081 0: ics1 and ics2 are indistinguishable */
12083 static int
12084 compare_ics (conversion *ics1, conversion *ics2)
12086 tree from_type1;
12087 tree from_type2;
12088 tree to_type1;
12089 tree to_type2;
12090 tree deref_from_type1 = NULL_TREE;
12091 tree deref_from_type2 = NULL_TREE;
12092 tree deref_to_type1 = NULL_TREE;
12093 tree deref_to_type2 = NULL_TREE;
12094 conversion_rank rank1, rank2;
12096 /* REF_BINDING is nonzero if the result of the conversion sequence
12097 is a reference type. In that case REF_CONV is the reference
12098 binding conversion. */
12099 conversion *ref_conv1;
12100 conversion *ref_conv2;
12102 /* Compare badness before stripping the reference conversion. */
12103 if (ics1->bad_p > ics2->bad_p)
12104 return -1;
12105 else if (ics1->bad_p < ics2->bad_p)
12106 return 1;
12108 /* Handle implicit object parameters. */
12109 maybe_handle_implicit_object (&ics1);
12110 maybe_handle_implicit_object (&ics2);
12112 /* Handle reference parameters. */
12113 ref_conv1 = maybe_handle_ref_bind (&ics1);
12114 ref_conv2 = maybe_handle_ref_bind (&ics2);
12116 /* List-initialization sequence L1 is a better conversion sequence than
12117 list-initialization sequence L2 if L1 converts to
12118 std::initializer_list<X> for some X and L2 does not. */
12119 if (ics1->kind == ck_list && ics2->kind != ck_list)
12120 return 1;
12121 if (ics2->kind == ck_list && ics1->kind != ck_list)
12122 return -1;
12124 /* [over.ics.rank]
12126 When comparing the basic forms of implicit conversion sequences (as
12127 defined in _over.best.ics_)
12129 --a standard conversion sequence (_over.ics.scs_) is a better
12130 conversion sequence than a user-defined conversion sequence
12131 or an ellipsis conversion sequence, and
12133 --a user-defined conversion sequence (_over.ics.user_) is a
12134 better conversion sequence than an ellipsis conversion sequence
12135 (_over.ics.ellipsis_). */
12136 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12137 mismatch. If both ICS are bad, we try to make a decision based on
12138 what would have happened if they'd been good. This is not an
12139 extension, we'll still give an error when we build up the call; this
12140 just helps us give a more helpful error message. */
12141 rank1 = BAD_CONVERSION_RANK (ics1);
12142 rank2 = BAD_CONVERSION_RANK (ics2);
12144 if (rank1 > rank2)
12145 return -1;
12146 else if (rank1 < rank2)
12147 return 1;
12149 if (ics1->ellipsis_p)
12150 /* Both conversions are ellipsis conversions. */
12151 return 0;
12153 /* User-defined conversion sequence U1 is a better conversion sequence
12154 than another user-defined conversion sequence U2 if they contain the
12155 same user-defined conversion operator or constructor and if the sec-
12156 ond standard conversion sequence of U1 is better than the second
12157 standard conversion sequence of U2. */
12159 /* Handle list-conversion with the same code even though it isn't always
12160 ranked as a user-defined conversion and it doesn't have a second
12161 standard conversion sequence; it will still have the desired effect.
12162 Specifically, we need to do the reference binding comparison at the
12163 end of this function. */
12165 if (ics1->user_conv_p || ics1->kind == ck_list
12166 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12168 conversion *t1 = strip_standard_conversion (ics1);
12169 conversion *t2 = strip_standard_conversion (ics2);
12171 if (!t1 || !t2 || t1->kind != t2->kind)
12172 return 0;
12173 else if (t1->kind == ck_user)
12175 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12176 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12177 if (f1 != f2)
12178 return 0;
12180 /* List-initialization sequence L1 is a better conversion sequence than
12181 list-initialization sequence L2 if
12183 -- L1 and L2 convert to arrays of the same element type, and either
12184 the number of elements n1 initialized by L1 is less than the number
12185 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12186 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12187 P0388R4.) */
12188 else if (t1->kind == ck_aggr
12189 && TREE_CODE (t1->type) == ARRAY_TYPE
12190 && TREE_CODE (t2->type) == ARRAY_TYPE
12191 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12193 tree n1 = nelts_initialized_by_list_init (t1);
12194 tree n2 = nelts_initialized_by_list_init (t2);
12195 if (tree_int_cst_lt (n1, n2))
12196 return 1;
12197 else if (tree_int_cst_lt (n2, n1))
12198 return -1;
12199 /* The n1 == n2 case. */
12200 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
12201 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
12202 if (c1 && !c2)
12203 return -1;
12204 else if (!c1 && c2)
12205 return 1;
12206 else
12207 return 0;
12209 else
12211 /* For ambiguous or aggregate conversions, use the target type as
12212 a proxy for the conversion function. */
12213 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12214 return 0;
12217 /* We can just fall through here, after setting up
12218 FROM_TYPE1 and FROM_TYPE2. */
12219 from_type1 = t1->type;
12220 from_type2 = t2->type;
12222 else
12224 conversion *t1;
12225 conversion *t2;
12227 /* We're dealing with two standard conversion sequences.
12229 [over.ics.rank]
12231 Standard conversion sequence S1 is a better conversion
12232 sequence than standard conversion sequence S2 if
12234 --S1 is a proper subsequence of S2 (comparing the conversion
12235 sequences in the canonical form defined by _over.ics.scs_,
12236 excluding any Lvalue Transformation; the identity
12237 conversion sequence is considered to be a subsequence of
12238 any non-identity conversion sequence */
12240 t1 = ics1;
12241 while (t1->kind != ck_identity)
12242 t1 = next_conversion (t1);
12243 from_type1 = t1->type;
12245 t2 = ics2;
12246 while (t2->kind != ck_identity)
12247 t2 = next_conversion (t2);
12248 from_type2 = t2->type;
12251 /* One sequence can only be a subsequence of the other if they start with
12252 the same type. They can start with different types when comparing the
12253 second standard conversion sequence in two user-defined conversion
12254 sequences. */
12255 if (same_type_p (from_type1, from_type2))
12257 if (is_subseq (ics1, ics2))
12258 return 1;
12259 if (is_subseq (ics2, ics1))
12260 return -1;
12263 /* [over.ics.rank]
12265 Or, if not that,
12267 --the rank of S1 is better than the rank of S2 (by the rules
12268 defined below):
12270 Standard conversion sequences are ordered by their ranks: an Exact
12271 Match is a better conversion than a Promotion, which is a better
12272 conversion than a Conversion.
12274 Two conversion sequences with the same rank are indistinguishable
12275 unless one of the following rules applies:
12277 --A conversion that does not a convert a pointer, pointer to member,
12278 or std::nullptr_t to bool is better than one that does.
12280 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12281 so that we do not have to check it explicitly. */
12282 if (ics1->rank < ics2->rank)
12283 return 1;
12284 else if (ics2->rank < ics1->rank)
12285 return -1;
12287 to_type1 = ics1->type;
12288 to_type2 = ics2->type;
12290 /* A conversion from scalar arithmetic type to complex is worse than a
12291 conversion between scalar arithmetic types. */
12292 if (same_type_p (from_type1, from_type2)
12293 && ARITHMETIC_TYPE_P (from_type1)
12294 && ARITHMETIC_TYPE_P (to_type1)
12295 && ARITHMETIC_TYPE_P (to_type2)
12296 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12297 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12299 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12300 return -1;
12301 else
12302 return 1;
12306 /* A conversion in either direction between floating-point type FP1 and
12307 floating-point type FP2 is better than a conversion in the same
12308 direction between FP1 and arithmetic type T3 if
12309 - the floating-point conversion rank of FP1 is equal to the rank of
12310 FP2, and
12311 - T3 is not a floating-point type, or T3 is a floating-point type
12312 whose rank is not equal to the rank of FP1, or the floating-point
12313 conversion subrank of FP2 is greater than the subrank of T3. */
12314 tree fp1 = from_type1;
12315 tree fp2 = to_type1;
12316 tree fp3 = from_type2;
12317 tree t3 = to_type2;
12318 int ret = 1;
12319 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12321 std::swap (fp1, fp2);
12322 std::swap (fp3, t3);
12324 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12325 && SCALAR_FLOAT_TYPE_P (fp1)
12326 /* Only apply this rule if at least one of the 3 types is
12327 extended floating-point type, otherwise keep them as
12328 before for compatibility reasons with types like __float128.
12329 float, double and long double alone have different conversion
12330 ranks and so when just those 3 types are involved, this
12331 rule doesn't trigger. */
12332 && (extended_float_type_p (fp1)
12333 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (fp2))
12334 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (t3))))
12336 if (TREE_CODE (fp2) != REAL_TYPE)
12338 ret = -ret;
12339 std::swap (fp2, t3);
12341 if (SCALAR_FLOAT_TYPE_P (fp2))
12343 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12344 if the conversion rank is equal (-1 or 1 if the subrank is
12345 different). */
12346 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12347 fp2),
12348 -1, 1))
12350 /* Conversion ranks of FP1 and FP2 are equal. */
12351 if (TREE_CODE (t3) != REAL_TYPE
12352 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12353 (fp1, t3),
12354 -1, 1))
12355 /* FP1 <-> FP2 conversion is better. */
12356 return ret;
12357 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12358 gcc_assert (IN_RANGE (c, -1, 1));
12359 if (c == 1)
12360 /* Conversion subrank of FP2 is greater than subrank of T3.
12361 FP1 <-> FP2 conversion is better. */
12362 return ret;
12363 else if (c == -1)
12364 /* Conversion subrank of FP2 is less than subrank of T3.
12365 FP1 <-> T3 conversion is better. */
12366 return -ret;
12368 else if (SCALAR_FLOAT_TYPE_P (t3)
12369 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12370 (fp1, t3),
12371 -1, 1))
12372 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12373 ranks of FP1 and T3 are equal.
12374 FP1 <-> T3 conversion is better. */
12375 return -ret;
12380 if (TYPE_PTR_P (from_type1)
12381 && TYPE_PTR_P (from_type2)
12382 && TYPE_PTR_P (to_type1)
12383 && TYPE_PTR_P (to_type2))
12385 deref_from_type1 = TREE_TYPE (from_type1);
12386 deref_from_type2 = TREE_TYPE (from_type2);
12387 deref_to_type1 = TREE_TYPE (to_type1);
12388 deref_to_type2 = TREE_TYPE (to_type2);
12390 /* The rules for pointers to members A::* are just like the rules
12391 for pointers A*, except opposite: if B is derived from A then
12392 A::* converts to B::*, not vice versa. For that reason, we
12393 switch the from_ and to_ variables here. */
12394 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12395 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12396 || (TYPE_PTRMEMFUNC_P (from_type1)
12397 && TYPE_PTRMEMFUNC_P (from_type2)
12398 && TYPE_PTRMEMFUNC_P (to_type1)
12399 && TYPE_PTRMEMFUNC_P (to_type2)))
12401 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12402 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12403 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12404 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12407 if (deref_from_type1 != NULL_TREE
12408 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12409 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12411 /* This was one of the pointer or pointer-like conversions.
12413 [over.ics.rank]
12415 --If class B is derived directly or indirectly from class A,
12416 conversion of B* to A* is better than conversion of B* to
12417 void*, and conversion of A* to void* is better than
12418 conversion of B* to void*. */
12419 if (VOID_TYPE_P (deref_to_type1)
12420 && VOID_TYPE_P (deref_to_type2))
12422 if (is_properly_derived_from (deref_from_type1,
12423 deref_from_type2))
12424 return -1;
12425 else if (is_properly_derived_from (deref_from_type2,
12426 deref_from_type1))
12427 return 1;
12429 else if (VOID_TYPE_P (deref_to_type1)
12430 || VOID_TYPE_P (deref_to_type2))
12432 if (same_type_p (deref_from_type1, deref_from_type2))
12434 if (VOID_TYPE_P (deref_to_type2))
12436 if (is_properly_derived_from (deref_from_type1,
12437 deref_to_type1))
12438 return 1;
12440 /* We know that DEREF_TO_TYPE1 is `void' here. */
12441 else if (is_properly_derived_from (deref_from_type1,
12442 deref_to_type2))
12443 return -1;
12446 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12447 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12449 /* [over.ics.rank]
12451 --If class B is derived directly or indirectly from class A
12452 and class C is derived directly or indirectly from B,
12454 --conversion of C* to B* is better than conversion of C* to
12457 --conversion of B* to A* is better than conversion of C* to
12458 A* */
12459 if (same_type_p (deref_from_type1, deref_from_type2))
12461 if (is_properly_derived_from (deref_to_type1,
12462 deref_to_type2))
12463 return 1;
12464 else if (is_properly_derived_from (deref_to_type2,
12465 deref_to_type1))
12466 return -1;
12468 else if (same_type_p (deref_to_type1, deref_to_type2))
12470 if (is_properly_derived_from (deref_from_type2,
12471 deref_from_type1))
12472 return 1;
12473 else if (is_properly_derived_from (deref_from_type1,
12474 deref_from_type2))
12475 return -1;
12479 else if (CLASS_TYPE_P (non_reference (from_type1))
12480 && same_type_p (from_type1, from_type2))
12482 tree from = non_reference (from_type1);
12484 /* [over.ics.rank]
12486 --binding of an expression of type C to a reference of type
12487 B& is better than binding an expression of type C to a
12488 reference of type A&
12490 --conversion of C to B is better than conversion of C to A, */
12491 if (is_properly_derived_from (from, to_type1)
12492 && is_properly_derived_from (from, to_type2))
12494 if (is_properly_derived_from (to_type1, to_type2))
12495 return 1;
12496 else if (is_properly_derived_from (to_type2, to_type1))
12497 return -1;
12500 else if (CLASS_TYPE_P (non_reference (to_type1))
12501 && same_type_p (to_type1, to_type2))
12503 tree to = non_reference (to_type1);
12505 /* [over.ics.rank]
12507 --binding of an expression of type B to a reference of type
12508 A& is better than binding an expression of type C to a
12509 reference of type A&,
12511 --conversion of B to A is better than conversion of C to A */
12512 if (is_properly_derived_from (from_type1, to)
12513 && is_properly_derived_from (from_type2, to))
12515 if (is_properly_derived_from (from_type2, from_type1))
12516 return 1;
12517 else if (is_properly_derived_from (from_type1, from_type2))
12518 return -1;
12522 /* [over.ics.rank]
12524 --S1 and S2 differ only in their qualification conversion and yield
12525 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12526 qualification signature of type T1 is a proper subset of the cv-
12527 qualification signature of type T2 */
12528 if (ics1->kind == ck_qual
12529 && ics2->kind == ck_qual
12530 && same_type_p (from_type1, from_type2))
12532 int result = comp_cv_qual_signature (to_type1, to_type2);
12533 if (result != 0)
12534 return result;
12537 /* [over.ics.rank]
12539 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12540 to an implicit object parameter of a non-static member function
12541 declared without a ref-qualifier, and either S1 binds an lvalue
12542 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12543 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12544 draft standard, 13.3.3.2)
12546 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12547 types to which the references refer are the same type except for
12548 top-level cv-qualifiers, and the type to which the reference
12549 initialized by S2 refers is more cv-qualified than the type to
12550 which the reference initialized by S1 refers.
12552 DR 1328 [over.match.best]: the context is an initialization by
12553 conversion function for direct reference binding (13.3.1.6) of a
12554 reference to function type, the return type of F1 is the same kind of
12555 reference (i.e. lvalue or rvalue) as the reference being initialized,
12556 and the return type of F2 is not. */
12558 if (ref_conv1 && ref_conv2)
12560 if (!ref_conv1->this_p && !ref_conv2->this_p
12561 && (ref_conv1->rvaluedness_matches_p
12562 != ref_conv2->rvaluedness_matches_p)
12563 && (same_type_p (ref_conv1->type, ref_conv2->type)
12564 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12565 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12567 if (ref_conv1->bad_p
12568 && !same_type_p (TREE_TYPE (ref_conv1->type),
12569 TREE_TYPE (ref_conv2->type)))
12570 /* Don't prefer a bad conversion that drops cv-quals to a bad
12571 conversion with the wrong rvalueness. */
12572 return 0;
12573 return (ref_conv1->rvaluedness_matches_p
12574 - ref_conv2->rvaluedness_matches_p);
12577 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12579 /* Per P0388R4:
12581 void f (int(&)[]), // (1)
12582 f (int(&)[1]), // (2)
12583 f (int*); // (3)
12585 (2) is better than (1), but (3) should be equal to (1) and to
12586 (2). For that reason we don't use ck_qual for (1) which would
12587 give it the cr_exact rank while (3) remains ck_identity.
12588 Therefore we compare (1) and (2) here. For (1) we'll have
12590 ck_ref_bind <- ck_identity
12591 int[] & int[1]
12593 so to handle this we must look at ref_conv. */
12594 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12595 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12596 if (c1 && !c2)
12597 return -1;
12598 else if (!c1 && c2)
12599 return 1;
12601 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12602 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12603 if (ref_conv1->bad_p)
12605 /* Prefer the one that drops fewer cv-quals. */
12606 tree ftype = next_conversion (ref_conv1)->type;
12607 int fquals = cp_type_quals (ftype);
12608 q1 ^= fquals;
12609 q2 ^= fquals;
12611 return comp_cv_qualification (q2, q1);
12615 /* [over.ics.rank]
12617 Per CWG 1601:
12618 -- A conversion that promotes an enumeration whose underlying type
12619 is fixed to its underlying type is better than one that promotes to
12620 the promoted underlying type, if the two are different. */
12621 if (ics1->rank == cr_promotion
12622 && ics2->rank == cr_promotion
12623 && UNSCOPED_ENUM_P (from_type1)
12624 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12625 && same_type_p (from_type1, from_type2))
12627 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12628 tree prom = type_promotes_to (from_type1);
12629 if (!same_type_p (utype, prom))
12631 if (same_type_p (to_type1, utype)
12632 && same_type_p (to_type2, prom))
12633 return 1;
12634 else if (same_type_p (to_type2, utype)
12635 && same_type_p (to_type1, prom))
12636 return -1;
12640 /* Neither conversion sequence is better than the other. */
12641 return 0;
12644 /* The source type for this standard conversion sequence. */
12646 static tree
12647 source_type (conversion *t)
12649 return strip_standard_conversion (t)->type;
12652 /* Note a warning about preferring WINNER to LOSER. We do this by storing
12653 a pointer to LOSER and re-running joust to produce the warning if WINNER
12654 is actually used. */
12656 static void
12657 add_warning (struct z_candidate *winner, struct z_candidate *loser)
12659 candidate_warning *cw = (candidate_warning *)
12660 conversion_obstack_alloc (sizeof (candidate_warning));
12661 cw->loser = loser;
12662 cw->next = winner->warnings;
12663 winner->warnings = cw;
12666 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12667 prvalue returned from a conversion function, return true. Otherwise, return
12668 false. */
12670 static bool
12671 joust_maybe_elide_copy (z_candidate *cand)
12673 tree fn = cand->fn;
12674 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12675 return false;
12676 conversion *conv = cand->convs[0];
12677 if (conv->kind == ck_ambig)
12678 return false;
12679 gcc_checking_assert (conv->kind == ck_ref_bind);
12680 conv = next_conversion (conv);
12681 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12683 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12684 (conv->type, DECL_CONTEXT (fn)));
12685 z_candidate *uc = conv->cand;
12686 if (DECL_CONV_FN_P (uc->fn))
12687 return true;
12689 return false;
12692 /* Return the class that CAND's implicit object parameter refers to. */
12694 static tree
12695 class_of_implicit_object (z_candidate *cand)
12697 if (!DECL_IOBJ_MEMBER_FUNCTION_P (cand->fn))
12698 return NULL_TREE;
12700 /* "For conversion functions that are implicit object member functions,
12701 the function is considered to be a member of the class of the implied
12702 object argument for the purpose of defining the type of the implicit
12703 object parameter." */
12704 if (DECL_CONV_FN_P (cand->fn))
12705 return TYPE_MAIN_VARIANT (TREE_TYPE (cand->first_arg));
12707 /* "For non-conversion functions that are implicit object member
12708 functions nominated by a using-declaration in a derived class, the
12709 function is considered to be a member of the derived class for the
12710 purpose of defining the type of the implicit object parameter."
12712 That derived class is reflected in the conversion_path binfo. */
12713 return BINFO_TYPE (cand->conversion_path);
12716 /* True if candidates C1 and C2 have corresponding object parameters per
12717 [basic.scope.scope]. */
12719 static bool
12720 object_parms_correspond (z_candidate *c1, tree fn1, z_candidate *c2, tree fn2)
12722 tree context = class_of_implicit_object (c1);
12723 tree ctx2 = class_of_implicit_object (c2);
12724 if (!ctx2)
12725 /* Leave context as is. */;
12726 else if (!context)
12727 context = ctx2;
12728 else if (context != ctx2)
12729 /* This can't happen for normal function calls, since it means finding
12730 functions in multiple bases which would fail with an ambiguous lookup,
12731 but it can occur with reversed operators. */
12732 return false;
12734 return object_parms_correspond (fn1, fn2, context);
12737 /* Return whether the first parameter of C1 matches the second parameter
12738 of C2. */
12740 static bool
12741 reversed_match (z_candidate *c1, z_candidate *c2)
12743 tree fn1 = c1->fn;
12744 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (c2->fn));
12745 tree parm2 = TREE_VALUE (TREE_CHAIN (parms2));
12746 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn1))
12748 tree ctx = class_of_implicit_object (c1);
12749 return iobj_parm_corresponds_to (fn1, parm2, ctx);
12751 else
12753 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12754 tree parm1 = TREE_VALUE (parms1);
12755 return same_type_p (parm1, parm2);
12759 /* True if the defining declarations of the two candidates have equivalent
12760 parameters. MATCH_KIND controls whether we're trying to compare the
12761 original declarations (for a warning) or the actual candidates. */
12763 enum class pmatch { original, current };
12765 static bool
12766 cand_parms_match (z_candidate *c1, z_candidate *c2, pmatch match_kind)
12768 tree fn1 = c1->fn;
12769 tree fn2 = c2->fn;
12770 bool reversed = (match_kind == pmatch::current
12771 && c1->reversed () != c2->reversed ());
12772 if (fn1 == fn2 && !reversed)
12773 return true;
12774 if (identifier_p (fn1) || identifier_p (fn2))
12775 return false;
12776 if (match_kind == pmatch::original)
12778 /* We don't look at c1->template_decl because that's only set for
12779 primary templates, not e.g. non-template member functions of
12780 class templates. */
12781 tree t1 = most_general_template (fn1);
12782 tree t2 = most_general_template (fn2);
12783 if (t1 || t2)
12785 if (!t1 || !t2)
12786 return false;
12787 if (t1 == t2)
12788 return true;
12789 fn1 = DECL_TEMPLATE_RESULT (t1);
12790 fn2 = DECL_TEMPLATE_RESULT (t2);
12794 else if (reversed)
12795 return (reversed_match (c1, c2)
12796 && reversed_match (c2, c1));
12798 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12799 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12801 if (!(DECL_FUNCTION_MEMBER_P (fn1)
12802 && DECL_FUNCTION_MEMBER_P (fn2)))
12803 /* Early escape. */;
12805 /* CWG2789 is not adequate, it should specify corresponding object
12806 parameters, not same typed object parameters. */
12807 else if (!object_parms_correspond (c1, fn1, c2, fn2))
12808 return false;
12809 else
12811 /* We just compared the object parameters, if they don't correspond
12812 we already returned false. */
12813 auto skip_parms = [] (tree fn, tree parms)
12815 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
12816 return TREE_CHAIN (parms);
12817 else
12818 return skip_artificial_parms_for (fn, parms);
12820 parms1 = skip_parms (fn1, parms1);
12821 parms2 = skip_parms (fn2, parms2);
12823 return compparms (parms1, parms2);
12826 /* True iff FN is a copy or move constructor or assignment operator. */
12828 static bool
12829 sfk_copy_or_move (tree fn)
12831 if (TREE_CODE (fn) != FUNCTION_DECL)
12832 return false;
12833 special_function_kind sfk = special_function_p (fn);
12834 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
12837 /* Compare two candidates for overloading as described in
12838 [over.match.best]. Return values:
12840 1: cand1 is better than cand2
12841 -1: cand2 is better than cand1
12842 0: cand1 and cand2 are indistinguishable */
12844 static int
12845 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12846 tsubst_flags_t complain)
12848 int winner = 0;
12849 int off1 = 0, off2 = 0;
12850 size_t i;
12851 size_t len;
12853 /* Candidates that involve bad conversions are always worse than those
12854 that don't. */
12855 if (cand1->viable > cand2->viable)
12856 return 1;
12857 if (cand1->viable < cand2->viable)
12858 return -1;
12860 /* If we have two pseudo-candidates for conversions to the same type,
12861 or two candidates for the same function, arbitrarily pick one. */
12862 if (cand1->fn == cand2->fn
12863 && cand1->reversed () == cand2->reversed ()
12864 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12865 return 1;
12867 /* Prefer a non-deleted function over an implicitly deleted move
12868 constructor or assignment operator. This differs slightly from the
12869 wording for issue 1402 (which says the move op is ignored by overload
12870 resolution), but this way produces better error messages. */
12871 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12872 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12873 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12875 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12876 && move_fn_p (cand1->fn))
12877 return -1;
12878 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12879 && move_fn_p (cand2->fn))
12880 return 1;
12883 /* a viable function F1
12884 is defined to be a better function than another viable function F2 if
12885 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12886 ICSi(F2), and then */
12888 /* for some argument j, ICSj(F1) is a better conversion sequence than
12889 ICSj(F2) */
12891 /* For comparing static and non-static member functions, we ignore
12892 the implicit object parameter of the non-static function. The
12893 standard says to pretend that the static function has an object
12894 parm, but that won't work with operator overloading. */
12895 len = cand1->num_convs;
12896 if (len != cand2->num_convs)
12898 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12899 && DECL_STATIC_FUNCTION_P (cand1->fn));
12900 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12901 && DECL_STATIC_FUNCTION_P (cand2->fn));
12903 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12904 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12905 && DECL_CONSTRUCTOR_P (cand1->fn)
12906 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12907 /* We're comparing a near-match list constructor and a near-match
12908 non-list constructor. Just treat them as unordered. */
12909 return 0;
12911 gcc_assert (static_1 != static_2);
12913 if (static_1)
12915 /* C++23 [over.best.ics.general] says:
12916 When the parameter is the implicit object parameter of a static
12917 member function, the implicit conversion sequence is a standard
12918 conversion sequence that is neither better nor worse than any
12919 other standard conversion sequence. */
12920 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12921 winner = 1;
12922 off2 = 1;
12924 else
12926 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12927 winner = -1;
12928 off1 = 1;
12929 --len;
12933 for (i = 0; i < len; ++i)
12935 conversion *t1 = cand1->convs[i + off1];
12936 conversion *t2 = cand2->convs[i + off2];
12937 int comp = compare_ics (t1, t2);
12939 if (comp != 0)
12941 if ((complain & tf_warning)
12942 && warn_sign_promo
12943 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12944 == cr_std + cr_promotion)
12945 && t1->kind == ck_std
12946 && t2->kind == ck_std
12947 && TREE_CODE (t1->type) == INTEGER_TYPE
12948 && TREE_CODE (t2->type) == INTEGER_TYPE
12949 && (TYPE_PRECISION (t1->type)
12950 == TYPE_PRECISION (t2->type))
12951 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12952 || (TREE_CODE (next_conversion (t1)->type)
12953 == ENUMERAL_TYPE)))
12955 tree type = next_conversion (t1)->type;
12956 tree type1, type2;
12957 struct z_candidate *w, *l;
12958 if (comp > 0)
12959 type1 = t1->type, type2 = t2->type,
12960 w = cand1, l = cand2;
12961 else
12962 type1 = t2->type, type2 = t1->type,
12963 w = cand2, l = cand1;
12965 if (warn)
12967 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12968 type, type1, type2);
12969 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12971 else
12972 add_warning (w, l);
12975 if (winner && comp != winner)
12977 /* Ambiguity between normal and reversed comparison operators
12978 with the same parameter types. P2468 decided not to go with
12979 this approach to resolving the ambiguity, so pedwarn. */
12980 if ((complain & tf_warning_or_error)
12981 && (cand1->reversed () != cand2->reversed ())
12982 && cand_parms_match (cand1, cand2, pmatch::original))
12984 struct z_candidate *w, *l;
12985 if (cand2->reversed ())
12986 winner = 1, w = cand1, l = cand2;
12987 else
12988 winner = -1, w = cand2, l = cand1;
12989 if (warn)
12991 auto_diagnostic_group d;
12992 if (pedwarn (input_location, 0,
12993 "C++20 says that these are ambiguous, "
12994 "even though the second is reversed:"))
12996 print_z_candidate (input_location,
12997 N_("candidate 1:"), w);
12998 print_z_candidate (input_location,
12999 N_("candidate 2:"), l);
13000 if (w->fn == l->fn
13001 && DECL_IOBJ_MEMBER_FUNCTION_P (w->fn)
13002 && (type_memfn_quals (TREE_TYPE (w->fn))
13003 & TYPE_QUAL_CONST) == 0)
13005 /* Suggest adding const to
13006 struct A { bool operator==(const A&); }; */
13007 tree parmtype
13008 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
13009 parmtype = TREE_VALUE (parmtype);
13010 if (TYPE_REF_P (parmtype)
13011 && TYPE_READONLY (TREE_TYPE (parmtype))
13012 && (same_type_ignoring_top_level_qualifiers_p
13013 (TREE_TYPE (parmtype),
13014 DECL_CONTEXT (w->fn))))
13015 inform (DECL_SOURCE_LOCATION (w->fn),
13016 "try making the operator a %<const%> "
13017 "member function");
13021 else
13022 add_warning (w, l);
13023 return winner;
13026 winner = 0;
13027 goto tweak;
13029 winner = comp;
13033 /* warn about confusing overload resolution for user-defined conversions,
13034 either between a constructor and a conversion op, or between two
13035 conversion ops. */
13036 if ((complain & tf_warning)
13037 /* In C++17, the constructor might have been elided, which means that
13038 an originally null ->second_conv could become non-null. */
13039 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
13040 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
13041 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
13043 struct z_candidate *w, *l;
13044 bool give_warning = false;
13046 if (winner == 1)
13047 w = cand1, l = cand2;
13048 else
13049 w = cand2, l = cand1;
13051 /* We don't want to complain about `X::operator T1 ()'
13052 beating `X::operator T2 () const', when T2 is a no less
13053 cv-qualified version of T1. */
13054 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
13055 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
13057 tree t = TREE_TYPE (TREE_TYPE (l->fn));
13058 tree f = TREE_TYPE (TREE_TYPE (w->fn));
13060 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
13062 t = TREE_TYPE (t);
13063 f = TREE_TYPE (f);
13065 if (!comp_ptr_ttypes (t, f))
13066 give_warning = true;
13068 else
13069 give_warning = true;
13071 if (!give_warning)
13072 /*NOP*/;
13073 else if (warn)
13075 tree source = source_type (w->convs[0]);
13076 if (INDIRECT_TYPE_P (source))
13077 source = TREE_TYPE (source);
13078 auto_diagnostic_group d;
13079 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
13080 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
13081 source, w->second_conv->type))
13083 inform (input_location, " because conversion sequence "
13084 "for the argument is better");
13087 else
13088 add_warning (w, l);
13091 if (winner)
13092 return winner;
13094 /* DR 495 moved this tiebreaker above the template ones. */
13095 /* or, if not that,
13096 the context is an initialization by user-defined conversion (see
13097 _dcl.init_ and _over.match.user_) and the standard conversion
13098 sequence from the return type of F1 to the destination type (i.e.,
13099 the type of the entity being initialized) is a better conversion
13100 sequence than the standard conversion sequence from the return type
13101 of F2 to the destination type. */
13103 if (cand1->second_conv)
13105 winner = compare_ics (cand1->second_conv, cand2->second_conv);
13106 if (winner)
13107 return winner;
13110 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
13111 explicit conversion (due to list-initialization) is worse. */
13113 z_candidate *sp = nullptr;
13114 if (sfk_copy_or_move (cand1->fn))
13115 sp = cand1;
13116 if (sfk_copy_or_move (cand2->fn))
13117 sp = sp ? nullptr : cand2;
13118 if (sp)
13120 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
13121 if (conv->user_conv_p)
13122 for (; conv; conv = next_conversion (conv))
13123 if (conv->kind == ck_user
13124 && DECL_P (conv->cand->fn)
13125 && DECL_NONCONVERTING_P (conv->cand->fn))
13126 return (sp == cand1) ? -1 : 1;
13130 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
13131 The standard currently says that only constructors are candidates, but if
13132 one copies a prvalue returned by a conversion function we prefer that.
13134 Clang does something similar, as discussed at
13135 http://lists.isocpp.org/core/2017/10/3166.php
13136 http://lists.isocpp.org/core/2019/03/5721.php */
13137 if (len == 1 && cxx_dialect >= cxx17
13138 && DECL_P (cand1->fn)
13139 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
13140 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
13142 bool elided1 = joust_maybe_elide_copy (cand1);
13143 bool elided2 = joust_maybe_elide_copy (cand2);
13144 winner = elided1 - elided2;
13145 if (winner)
13146 return winner;
13149 /* or, if not that,
13150 F1 is a non-template function and F2 is a template function
13151 specialization. */
13153 if (!cand1->template_decl && cand2->template_decl)
13154 return 1;
13155 else if (cand1->template_decl && !cand2->template_decl)
13156 return -1;
13158 /* or, if not that,
13159 F1 and F2 are template functions and the function template for F1 is
13160 more specialized than the template for F2 according to the partial
13161 ordering rules. */
13163 if (cand1->template_decl && cand2->template_decl)
13165 winner = more_specialized_fn
13166 (TI_TEMPLATE (cand1->template_decl),
13167 TI_TEMPLATE (cand2->template_decl),
13168 /* [temp.func.order]: The presence of unused ellipsis and default
13169 arguments has no effect on the partial ordering of function
13170 templates. add_function_candidate() will not have
13171 counted the "this" argument for constructors. */
13172 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
13173 if (winner)
13174 return winner;
13177 /* Concepts: F1 and F2 are non-template functions with the same
13178 parameter-type-lists, and F1 is more constrained than F2 according to the
13179 partial ordering of constraints described in 13.5.4. */
13181 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
13182 && !cand1->template_decl && !cand2->template_decl
13183 && cand_parms_match (cand1, cand2, pmatch::current))
13185 winner = more_constrained (cand1->fn, cand2->fn);
13186 if (winner)
13187 return winner;
13190 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
13191 rewritten candidates, and F2 is a synthesized candidate with reversed
13192 order of parameters and F1 is not. */
13193 if (cand1->rewritten ())
13195 if (!cand2->rewritten ())
13196 return -1;
13197 if (!cand1->reversed () && cand2->reversed ())
13198 return 1;
13199 if (cand1->reversed () && !cand2->reversed ())
13200 return -1;
13202 else if (cand2->rewritten ())
13203 return 1;
13205 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
13206 if (deduction_guide_p (cand1->fn))
13208 gcc_assert (deduction_guide_p (cand2->fn));
13209 /* We distinguish between candidates from an explicit deduction guide and
13210 candidates built from a constructor based on DECL_ARTIFICIAL. */
13211 int art1 = DECL_ARTIFICIAL (cand1->fn);
13212 int art2 = DECL_ARTIFICIAL (cand2->fn);
13213 if (art1 != art2)
13214 return art2 - art1;
13216 if (art1)
13218 /* Prefer the special copy guide over a declared copy/move
13219 constructor. */
13220 if (copy_guide_p (cand1->fn))
13221 return 1;
13222 if (copy_guide_p (cand2->fn))
13223 return -1;
13225 /* Prefer a candidate generated from a non-template constructor. */
13226 int tg1 = template_guide_p (cand1->fn);
13227 int tg2 = template_guide_p (cand2->fn);
13228 if (tg1 != tg2)
13229 return tg2 - tg1;
13233 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
13234 for all arguments the corresponding parameters of F1 and F2 have the same
13235 type (CWG 2273/2277). */
13236 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
13237 && !DECL_CONV_FN_P (cand1->fn)
13238 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
13239 && !DECL_CONV_FN_P (cand2->fn))
13241 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13242 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13244 bool used1 = false;
13245 bool used2 = false;
13246 if (base1 == base2)
13247 /* No difference. */;
13248 else if (DERIVED_FROM_P (base1, base2))
13249 used1 = true;
13250 else if (DERIVED_FROM_P (base2, base1))
13251 used2 = true;
13253 if (int diff = used2 - used1)
13255 for (i = 0; i < len; ++i)
13257 conversion *t1 = cand1->convs[i + off1];
13258 conversion *t2 = cand2->convs[i + off2];
13259 if (!same_type_p (t1->type, t2->type))
13260 break;
13262 if (i == len)
13263 return diff;
13267 /* Check whether we can discard a builtin candidate, either because we
13268 have two identical ones or matching builtin and non-builtin candidates.
13270 (Pedantically in the latter case the builtin which matched the user
13271 function should not be added to the overload set, but we spot it here.
13273 [over.match.oper]
13274 ... the builtin candidates include ...
13275 - do not have the same parameter type list as any non-template
13276 non-member candidate. */
13278 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
13280 for (i = 0; i < len; ++i)
13281 if (!same_type_p (cand1->convs[i]->type,
13282 cand2->convs[i]->type))
13283 break;
13284 if (i == cand1->num_convs)
13286 if (cand1->fn == cand2->fn)
13287 /* Two built-in candidates; arbitrarily pick one. */
13288 return 1;
13289 else if (identifier_p (cand1->fn))
13290 /* cand1 is built-in; prefer cand2. */
13291 return -1;
13292 else
13293 /* cand2 is built-in; prefer cand1. */
13294 return 1;
13298 /* For candidates of a multi-versioned function, make the version with
13299 the highest priority win. This version will be checked for dispatching
13300 first. If this version can be inlined into the caller, the front-end
13301 will simply make a direct call to this function. */
13303 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13304 && DECL_FUNCTION_VERSIONED (cand1->fn)
13305 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13306 && DECL_FUNCTION_VERSIONED (cand2->fn))
13308 tree f1 = TREE_TYPE (cand1->fn);
13309 tree f2 = TREE_TYPE (cand2->fn);
13310 tree p1 = TYPE_ARG_TYPES (f1);
13311 tree p2 = TYPE_ARG_TYPES (f2);
13313 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13314 is possible that cand1->fn and cand2->fn are function versions but of
13315 different functions. Check types to see if they are versions of the same
13316 function. */
13317 if (compparms (p1, p2)
13318 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13320 /* Always make the version with the higher priority, more
13321 specialized, win. */
13322 gcc_assert (targetm.compare_version_priority);
13323 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13324 return 1;
13325 else
13326 return -1;
13330 /* If the two function declarations represent the same function (this can
13331 happen with declarations in multiple scopes and arg-dependent lookup),
13332 arbitrarily choose one. But first make sure the default args we're
13333 using match. */
13334 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13335 && equal_functions (cand1->fn, cand2->fn))
13337 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13338 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13340 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13342 for (i = 0; i < len; ++i)
13344 /* Don't crash if the fn is variadic. */
13345 if (!parms1)
13346 break;
13347 parms1 = TREE_CHAIN (parms1);
13348 parms2 = TREE_CHAIN (parms2);
13351 if (off1)
13352 parms1 = TREE_CHAIN (parms1);
13353 else if (off2)
13354 parms2 = TREE_CHAIN (parms2);
13356 for (; parms1; ++i)
13358 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13359 TREE_PURPOSE (parms2)))
13361 if (warn)
13363 if (complain & tf_error)
13365 auto_diagnostic_group d;
13366 if (permerror (input_location,
13367 "default argument mismatch in "
13368 "overload resolution"))
13370 inform (DECL_SOURCE_LOCATION (cand1->fn),
13371 " candidate 1: %q#F", cand1->fn);
13372 inform (DECL_SOURCE_LOCATION (cand2->fn),
13373 " candidate 2: %q#F", cand2->fn);
13376 else
13377 return 0;
13379 else
13380 add_warning (cand1, cand2);
13381 break;
13383 parms1 = TREE_CHAIN (parms1);
13384 parms2 = TREE_CHAIN (parms2);
13387 return 1;
13390 tweak:
13392 /* Extension: If the worst conversion for one candidate is better than the
13393 worst conversion for the other, take the first. */
13394 if (!pedantic && (complain & tf_warning_or_error))
13396 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13397 struct z_candidate *w = 0, *l = 0;
13399 for (i = 0; i < len; ++i)
13401 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13402 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13403 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13404 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13406 if (rank1 < rank2)
13407 winner = 1, w = cand1, l = cand2;
13408 if (rank1 > rank2)
13409 winner = -1, w = cand2, l = cand1;
13410 if (winner)
13412 /* Don't choose a deleted function over ambiguity. */
13413 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13414 return 0;
13415 if (warn)
13417 auto_diagnostic_group d;
13418 if (pedwarn (input_location, 0,
13419 "ISO C++ says that these are ambiguous, even "
13420 "though the worst conversion for the first is "
13421 "better than the worst conversion for the second:"))
13423 print_z_candidate (input_location, N_("candidate 1:"), w);
13424 print_z_candidate (input_location, N_("candidate 2:"), l);
13427 else
13428 add_warning (w, l);
13429 return winner;
13433 gcc_assert (!winner);
13434 return 0;
13437 /* Given a list of candidates for overloading, find the best one, if any.
13438 This algorithm has a worst case of O(2n) (winner is last), and a best
13439 case of O(n/2) (totally ambiguous); much better than a sorting
13440 algorithm. The candidates list is assumed to be sorted according
13441 to viability (via splice_viable). */
13443 static struct z_candidate *
13444 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13446 struct z_candidate **champ = &candidates, **challenger;
13447 int fate;
13448 struct z_candidate *previous_worse_champ = nullptr;
13450 /* Walk through the list once, comparing each current champ to the next
13451 candidate, knocking out a candidate or two with each comparison. */
13453 for (challenger = &candidates->next; *challenger && (*challenger)->viable; )
13455 fate = joust (*champ, *challenger, 0, complain);
13456 if (fate == 1)
13457 challenger = &(*challenger)->next;
13458 else if (fate == -1)
13460 previous_worse_champ = *champ;
13461 champ = challenger;
13462 challenger = &(*challenger)->next;
13464 else
13466 previous_worse_champ = nullptr;
13467 champ = &(*challenger)->next;
13468 if (!*champ || !(*champ)->viable)
13470 champ = nullptr;
13471 break;
13473 challenger = &(*champ)->next;
13477 /* Make sure the champ is better than all the candidates it hasn't yet
13478 been compared to. */
13480 if (champ)
13481 for (challenger = &candidates;
13482 challenger != champ;
13483 challenger = &(*challenger)->next)
13485 if (*challenger == previous_worse_champ)
13486 /* We already know this candidate is worse than the champ. */
13487 continue;
13488 fate = joust (*champ, *challenger, 0, complain);
13489 if (fate != 1)
13491 champ = nullptr;
13492 break;
13496 if (!champ)
13497 return nullptr;
13499 /* Move the champ to the front of the candidate list. */
13501 if (champ != &candidates)
13503 z_candidate *saved_champ = *champ;
13504 *champ = saved_champ->next;
13505 saved_champ->next = candidates;
13506 candidates = saved_champ;
13509 return candidates;
13512 /* Returns nonzero if things of type FROM can be converted to TO. */
13514 bool
13515 can_convert (tree to, tree from, tsubst_flags_t complain)
13517 tree arg = NULL_TREE;
13518 /* implicit_conversion only considers user-defined conversions
13519 if it has an expression for the call argument list. */
13520 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13521 arg = build_stub_object (from);
13522 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13525 /* Returns nonzero if things of type FROM can be converted to TO with a
13526 standard conversion. */
13528 bool
13529 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13531 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13534 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13536 bool
13537 can_convert_arg (tree to, tree from, tree arg, int flags,
13538 tsubst_flags_t complain)
13540 conversion *t;
13541 bool ok_p;
13543 conversion_obstack_sentinel cos;
13544 /* We want to discard any access checks done for this test,
13545 as we might not be in the appropriate access context and
13546 we'll do the check again when we actually perform the
13547 conversion. */
13548 push_deferring_access_checks (dk_deferred);
13550 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13551 flags, complain);
13552 ok_p = (t && !t->bad_p);
13554 /* Discard the access checks now. */
13555 pop_deferring_access_checks ();
13557 return ok_p;
13560 /* Like can_convert_arg, but allows dubious conversions as well. */
13562 bool
13563 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13564 tsubst_flags_t complain)
13566 conversion *t;
13568 conversion_obstack_sentinel cos;
13569 /* Try to perform the conversion. */
13570 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13571 flags, complain);
13573 return t != NULL;
13576 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13577 resolution FLAGS. */
13579 tree
13580 build_implicit_conv_flags (tree type, tree expr, int flags)
13582 /* In a template, we are only concerned about determining the
13583 type of non-dependent expressions, so we do not have to
13584 perform the actual conversion. But for initializers, we
13585 need to be able to perform it at instantiation
13586 (or instantiate_non_dependent_expr) time. */
13587 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13588 if (!(flags & LOOKUP_ONLYCONVERTING))
13589 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13590 if (flags & LOOKUP_NO_NARROWING)
13591 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13592 return expr;
13595 /* Convert EXPR to TYPE. Return the converted expression.
13597 Note that we allow bad conversions here because by the time we get to
13598 this point we are committed to doing the conversion. If we end up
13599 doing a bad conversion, convert_like will complain. */
13601 tree
13602 perform_implicit_conversion_flags (tree type, tree expr,
13603 tsubst_flags_t complain, int flags)
13605 conversion *conv;
13606 location_t loc = cp_expr_loc_or_input_loc (expr);
13608 if (TYPE_REF_P (type))
13609 expr = mark_lvalue_use (expr);
13610 else
13611 expr = mark_rvalue_use (expr);
13613 if (error_operand_p (expr))
13614 return error_mark_node;
13616 conversion_obstack_sentinel cos;
13618 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13619 /*c_cast_p=*/false,
13620 flags, complain);
13622 if (!conv)
13624 if (complain & tf_error)
13625 implicit_conversion_error (loc, type, expr);
13626 expr = error_mark_node;
13628 else if (processing_template_decl && conv->kind != ck_identity)
13629 expr = build_implicit_conv_flags (type, expr, flags);
13630 else
13632 /* Give a conversion call the same location as expr. */
13633 iloc_sentinel il (loc);
13634 expr = convert_like (conv, expr, complain);
13637 return expr;
13640 tree
13641 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13643 return perform_implicit_conversion_flags (type, expr, complain,
13644 LOOKUP_IMPLICIT);
13647 /* Convert EXPR to TYPE (as a direct-initialization) if that is
13648 permitted. If the conversion is valid, the converted expression is
13649 returned. Otherwise, NULL_TREE is returned, except in the case
13650 that TYPE is a class type; in that case, an error is issued. If
13651 C_CAST_P is true, then this direct-initialization is taking
13652 place as part of a static_cast being attempted as part of a C-style
13653 cast. */
13655 tree
13656 perform_direct_initialization_if_possible (tree type,
13657 tree expr,
13658 bool c_cast_p,
13659 tsubst_flags_t complain)
13661 conversion *conv;
13663 if (type == error_mark_node || error_operand_p (expr))
13664 return error_mark_node;
13665 /* [dcl.init]
13667 If the destination type is a (possibly cv-qualified) class type:
13669 -- If the initialization is direct-initialization ...,
13670 constructors are considered.
13672 -- If overload resolution is successful, the selected constructor
13673 is called to initialize the object, with the initializer expression
13674 or expression-list as its argument(s).
13676 -- Otherwise, if no constructor is viable, the destination type is
13677 a (possibly cv-qualified) aggregate class A, and the initializer is
13678 a parenthesized expression-list, the object is initialized as
13679 follows... */
13680 if (CLASS_TYPE_P (type))
13682 releasing_vec args (make_tree_vector_single (expr));
13683 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13684 &args, type, LOOKUP_NORMAL, complain);
13685 return build_cplus_new (type, expr, complain);
13688 conversion_obstack_sentinel cos;
13690 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13691 c_cast_p,
13692 LOOKUP_NORMAL, complain);
13693 if (!conv || conv->bad_p)
13694 expr = NULL_TREE;
13695 else if (processing_template_decl && conv->kind != ck_identity)
13697 /* In a template, we are only concerned about determining the
13698 type of non-dependent expressions, so we do not have to
13699 perform the actual conversion. But for initializers, we
13700 need to be able to perform it at instantiation
13701 (or instantiate_non_dependent_expr) time. */
13702 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13703 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13705 else
13706 expr = convert_like (conv, expr, NULL_TREE, 0,
13707 /*issue_conversion_warnings=*/false,
13708 c_cast_p, /*nested_p=*/false, complain);
13710 return expr;
13713 /* When initializing a reference that lasts longer than a full-expression,
13714 this special rule applies:
13716 [class.temporary]
13718 The temporary to which the reference is bound or the temporary
13719 that is the complete object to which the reference is bound
13720 persists for the lifetime of the reference.
13722 The temporaries created during the evaluation of the expression
13723 initializing the reference, except the temporary to which the
13724 reference is bound, are destroyed at the end of the
13725 full-expression in which they are created.
13727 In that case, we store the converted expression into a new
13728 VAR_DECL in a new scope.
13730 However, we want to be careful not to create temporaries when
13731 they are not required. For example, given:
13733 struct B {};
13734 struct D : public B {};
13735 D f();
13736 const B& b = f();
13738 there is no need to copy the return value from "f"; we can just
13739 extend its lifetime. Similarly, given:
13741 struct S {};
13742 struct T { operator S(); };
13743 T t;
13744 const S& s = t;
13746 we can extend the lifetime of the return value of the conversion
13747 operator.
13749 The next several functions are involved in this lifetime extension. */
13751 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13752 reference is being bound to a temporary. Create and return a new
13753 VAR_DECL with the indicated TYPE; this variable will store the value to
13754 which the reference is bound. */
13756 tree
13757 make_temporary_var_for_ref_to_temp (tree decl, tree type)
13759 tree var = create_temporary_var (type);
13761 /* Register the variable. */
13762 if (VAR_P (decl)
13763 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13765 /* Namespace-scope or local static; give it a mangled name. */
13767 /* If an initializer is visible to multiple translation units, those
13768 translation units must agree on the addresses of the
13769 temporaries. Therefore the temporaries must be given a consistent name
13770 and vague linkage. The mangled name of a temporary is the name of the
13771 non-temporary object in whose initializer they appear, prefixed with
13772 GR and suffixed with a sequence number mangled using the usual rules
13773 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13774 left-to-right walk of the complete initializer. */
13775 copy_linkage (var, decl);
13777 tree name = mangle_ref_init_variable (decl);
13778 DECL_NAME (var) = name;
13779 SET_DECL_ASSEMBLER_NAME (var, name);
13781 else
13782 /* Create a new cleanup level if necessary. */
13783 maybe_push_cleanup_level (type);
13785 return pushdecl (var);
13788 /* EXPR is the initializer for a variable DECL of reference or
13789 std::initializer_list type. Create, push and return a new VAR_DECL
13790 for the initializer so that it will live as long as DECL. Any
13791 cleanup for the new variable is returned through CLEANUP, and the
13792 code to initialize the new variable is returned through INITP. */
13794 static tree
13795 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13796 tree *initp, tree *cond_guard)
13798 tree init;
13799 tree type;
13800 tree var;
13802 /* Create the temporary variable. */
13803 type = TREE_TYPE (expr);
13804 var = make_temporary_var_for_ref_to_temp (decl, type);
13805 layout_decl (var, 0);
13806 /* If the rvalue is the result of a function call it will be
13807 a TARGET_EXPR. If it is some other construct (such as a
13808 member access expression where the underlying object is
13809 itself the result of a function call), turn it into a
13810 TARGET_EXPR here. It is important that EXPR be a
13811 TARGET_EXPR below since otherwise the INIT_EXPR will
13812 attempt to make a bitwise copy of EXPR to initialize
13813 VAR. */
13814 if (TREE_CODE (expr) != TARGET_EXPR)
13815 expr = get_target_expr (expr);
13816 else
13818 if (TREE_ADDRESSABLE (expr))
13819 TREE_ADDRESSABLE (var) = 1;
13820 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
13821 DECL_MERGEABLE (var) = true;
13824 if (TREE_CODE (decl) == FIELD_DECL
13825 && extra_warnings && !warning_suppressed_p (decl))
13827 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13828 "until the constructor exits", decl);
13829 suppress_warning (decl);
13832 /* Recursively extend temps in this initializer. */
13833 TARGET_EXPR_INITIAL (expr)
13834 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13835 cond_guard);
13837 /* Any reference temp has a non-trivial initializer. */
13838 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13840 /* If the initializer is constant, put it in DECL_INITIAL so we get
13841 static initialization and use in constant expressions. */
13842 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13843 /* As in store_init_value. */
13844 init = cp_fully_fold (init);
13845 if (TREE_CONSTANT (init))
13847 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13849 /* 5.19 says that a constant expression can include an
13850 lvalue-rvalue conversion applied to "a glvalue of literal type
13851 that refers to a non-volatile temporary object initialized
13852 with a constant expression". Rather than try to communicate
13853 that this VAR_DECL is a temporary, just mark it constexpr. */
13854 DECL_DECLARED_CONSTEXPR_P (var) = true;
13855 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13856 TREE_CONSTANT (var) = true;
13857 TREE_READONLY (var) = true;
13859 DECL_INITIAL (var) = init;
13860 init = NULL_TREE;
13862 else
13863 /* Create the INIT_EXPR that will initialize the temporary
13864 variable. */
13865 init = split_nonconstant_init (var, expr);
13866 if (at_function_scope_p ())
13868 add_decl_expr (var);
13870 if (TREE_STATIC (var))
13871 init = add_stmt_to_compound (init, register_dtor_fn (var));
13872 else
13874 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13875 if (cleanup)
13877 if (cond_guard && cleanup != error_mark_node)
13879 if (*cond_guard == NULL_TREE)
13881 *cond_guard = build_local_temp (boolean_type_node);
13882 add_decl_expr (*cond_guard);
13883 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13884 *cond_guard, NOP_EXPR,
13885 boolean_false_node,
13886 tf_warning_or_error);
13887 finish_expr_stmt (set);
13889 cleanup = build3 (COND_EXPR, void_type_node,
13890 *cond_guard, cleanup, NULL_TREE);
13892 vec_safe_push (*cleanups, cleanup);
13896 /* We must be careful to destroy the temporary only
13897 after its initialization has taken place. If the
13898 initialization throws an exception, then the
13899 destructor should not be run. We cannot simply
13900 transform INIT into something like:
13902 (INIT, ({ CLEANUP_STMT; }))
13904 because emit_local_var always treats the
13905 initializer as a full-expression. Thus, the
13906 destructor would run too early; it would run at the
13907 end of initializing the reference variable, rather
13908 than at the end of the block enclosing the
13909 reference variable.
13911 The solution is to pass back a cleanup expression
13912 which the caller is responsible for attaching to
13913 the statement tree. */
13915 else
13917 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13918 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13920 if (CP_DECL_THREAD_LOCAL_P (var))
13921 tls_aggregates = tree_cons (NULL_TREE, var,
13922 tls_aggregates);
13923 else
13924 static_aggregates = tree_cons (NULL_TREE, var,
13925 static_aggregates);
13927 else
13928 /* Check whether the dtor is callable. */
13929 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13931 /* Avoid -Wunused-variable warning (c++/38958). */
13932 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13933 && VAR_P (decl))
13934 TREE_USED (decl) = DECL_READ_P (decl) = true;
13936 *initp = init;
13937 return var;
13940 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
13941 initializing a variable of that TYPE. */
13943 tree
13944 initialize_reference (tree type, tree expr,
13945 int flags, tsubst_flags_t complain)
13947 conversion *conv;
13948 location_t loc = cp_expr_loc_or_input_loc (expr);
13950 if (type == error_mark_node || error_operand_p (expr))
13951 return error_mark_node;
13953 conversion_obstack_sentinel cos;
13955 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13956 flags, complain);
13957 /* If this conversion failed, we're in C++20, and we have something like
13958 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13959 if ((!conv || conv->bad_p)
13960 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13962 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13963 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13964 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13965 conversion *c = reference_binding (type, TREE_TYPE (e), e,
13966 /*c_cast_p=*/false, flags, complain);
13967 /* If this worked, use it. */
13968 if (c && !c->bad_p)
13969 expr = e, conv = c;
13971 if (!conv || conv->bad_p)
13973 if (complain & tf_error)
13975 if (conv)
13976 convert_like (conv, expr, complain);
13977 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13978 && !TYPE_REF_IS_RVALUE (type)
13979 && !lvalue_p (expr))
13980 error_at (loc, "invalid initialization of non-const reference of "
13981 "type %qH from an rvalue of type %qI",
13982 type, TREE_TYPE (expr));
13983 else
13984 error_at (loc, "invalid initialization of reference of type "
13985 "%qH from expression of type %qI", type,
13986 TREE_TYPE (expr));
13988 return error_mark_node;
13991 if (conv->kind == ck_ref_bind)
13992 /* Perform the conversion. */
13993 expr = convert_like (conv, expr, complain);
13994 else if (conv->kind == ck_ambig)
13995 /* We gave an error in build_user_type_conversion_1. */
13996 expr = error_mark_node;
13997 else
13998 gcc_unreachable ();
14000 return expr;
14003 /* Return true if T is std::pair<const T&, const T&>. */
14005 static bool
14006 std_pair_ref_ref_p (tree t)
14008 /* First, check if we have std::pair. */
14009 if (!NON_UNION_CLASS_TYPE_P (t)
14010 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
14011 return false;
14012 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
14013 if (!decl_in_std_namespace_p (tdecl))
14014 return false;
14015 tree name = DECL_NAME (tdecl);
14016 if (!name || !id_equal (name, "pair"))
14017 return false;
14019 /* Now see if the template arguments are both const T&. */
14020 tree args = CLASSTYPE_TI_ARGS (t);
14021 if (TREE_VEC_LENGTH (args) != 2)
14022 return false;
14023 for (int i = 0; i < 2; i++)
14024 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
14025 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
14026 return false;
14028 return true;
14031 /* Return true if a class T has a reference member. */
14033 static bool
14034 class_has_reference_member_p (tree t)
14036 for (tree fields = TYPE_FIELDS (t);
14037 fields;
14038 fields = DECL_CHAIN (fields))
14039 if (TREE_CODE (fields) == FIELD_DECL
14040 && !DECL_ARTIFICIAL (fields)
14041 && TYPE_REF_P (TREE_TYPE (fields)))
14042 return true;
14043 return false;
14046 /* A wrapper for the above suitable as a callback for dfs_walk_once. */
14048 static tree
14049 class_has_reference_member_p_r (tree binfo, void *)
14051 return (class_has_reference_member_p (BINFO_TYPE (binfo))
14052 ? integer_one_node : NULL_TREE);
14056 /* Return true if T (either a class or a function) has been marked as
14057 not-dangling. */
14059 static bool
14060 no_dangling_p (tree t)
14062 t = lookup_attribute ("no_dangling", TYPE_ATTRIBUTES (t));
14063 if (!t)
14064 return false;
14066 t = TREE_VALUE (t);
14067 if (!t)
14068 return true;
14070 t = build_converted_constant_bool_expr (TREE_VALUE (t), tf_warning_or_error);
14071 t = cxx_constant_value (t);
14072 return t == boolean_true_node;
14075 /* Return true if a class CTYPE is either std::reference_wrapper or
14076 std::ref_view, or a reference wrapper class. We consider a class
14077 a reference wrapper class if it has a reference member. We no
14078 longer check that it has a constructor taking the same reference type
14079 since that approach still generated too many false positives. */
14081 static bool
14082 reference_like_class_p (tree ctype)
14084 if (!CLASS_TYPE_P (ctype))
14085 return false;
14087 if (no_dangling_p (ctype))
14088 return true;
14090 /* Also accept a std::pair<const T&, const T&>. */
14091 if (std_pair_ref_ref_p (ctype))
14092 return true;
14094 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
14095 if (decl_in_std_namespace_p (tdecl))
14097 tree name = DECL_NAME (tdecl);
14098 if (name
14099 && (id_equal (name, "reference_wrapper")
14100 || id_equal (name, "span")
14101 || id_equal (name, "ref_view")))
14102 return true;
14105 /* Avoid warning if CTYPE looks like std::span: it has a T* member and
14106 a trivial destructor. For example,
14108 template<typename T>
14109 struct Span {
14110 T* data_;
14111 std::size len_;
14114 is considered std::span-like. */
14115 if (NON_UNION_CLASS_TYPE_P (ctype) && TYPE_HAS_TRIVIAL_DESTRUCTOR (ctype))
14116 for (tree field = next_aggregate_field (TYPE_FIELDS (ctype));
14117 field; field = next_aggregate_field (DECL_CHAIN (field)))
14118 if (TYPE_PTR_P (TREE_TYPE (field)))
14119 return true;
14121 /* Some classes, such as std::tuple, have the reference member in its
14122 (non-direct) base class. */
14123 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
14124 nullptr, nullptr))
14125 return true;
14127 return false;
14130 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
14131 that initializes the LHS (and at least one of its arguments represents
14132 a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
14133 if none found. For instance:
14135 const S& s = S().self(); // S::self (&TARGET_EXPR <...>)
14136 const int& r = (42, f(1)); // f(1)
14137 const int& t = b ? f(1) : f(2); // f(1)
14138 const int& u = b ? f(1) : f(g); // f(1)
14139 const int& v = b ? f(g) : f(2); // f(2)
14140 const int& w = b ? f(g) : f(g); // NULL_TREE
14141 const int& y = (f(1), 42); // NULL_TREE
14142 const int& z = f(f(1)); // f(f(1))
14144 EXPR is the initializer. If ARG_P is true, we're processing an argument
14145 to a function; the point is to distinguish between, for example,
14147 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
14149 where we shouldn't warn, and
14151 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
14153 where we should warn (Ref is a reference_like_class_p so we see through
14154 it. */
14156 static tree
14157 do_warn_dangling_reference (tree expr, bool arg_p)
14159 STRIP_NOPS (expr);
14161 if (arg_p && expr_represents_temporary_p (expr))
14163 /* An attempt to reduce the number of -Wdangling-reference
14164 false positives concerning reference wrappers (c++/107532).
14165 When we encounter a reference_like_class_p, we don't warn
14166 just yet; instead, we keep recursing to see if there were
14167 any temporaries behind the reference-wrapper class. */
14168 tree e = expr;
14169 while (handled_component_p (e))
14170 e = TREE_OPERAND (e, 0);
14171 tree type = TREE_TYPE (e);
14172 /* If the temporary represents a lambda, we don't really know
14173 what's going on here. */
14174 if (!reference_like_class_p (type) && !LAMBDA_TYPE_P (type))
14175 return expr;
14178 switch (TREE_CODE (expr))
14180 case CALL_EXPR:
14182 tree fndecl = cp_get_callee_fndecl_nofold (expr);
14183 if (!fndecl
14184 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
14185 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
14186 OPT_Wdangling_reference)
14187 /* Don't emit a false positive for:
14188 std::vector<int> v = ...;
14189 std::vector<int>::const_iterator it = v.begin();
14190 const int &r = *it++;
14191 because R refers to one of the int elements of V, not to
14192 a temporary object. Member operator* may return a reference
14193 but probably not to one of its arguments. */
14194 || (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
14195 && DECL_OVERLOADED_OPERATOR_P (fndecl)
14196 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF))
14197 || no_dangling_p (TREE_TYPE (fndecl)))
14198 return NULL_TREE;
14200 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
14201 /* If the function doesn't return a reference, don't warn. This
14202 can be e.g.
14203 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
14204 which doesn't dangle: std::min here returns an int.
14206 If the function returns a std::pair<const T&, const T&>, we
14207 warn, to detect e.g.
14208 std::pair<const int&, const int&> v = std::minmax(1, 2);
14209 which also creates a dangling reference, because std::minmax
14210 returns std::pair<const T&, const T&>(b, a). */
14211 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
14212 return NULL_TREE;
14214 /* Here we're looking to see if any of the arguments is a temporary
14215 initializing a reference parameter. */
14216 for (int i = 0; i < call_expr_nargs (expr); ++i)
14218 tree arg = CALL_EXPR_ARG (expr, i);
14219 /* Check that this argument initializes a reference, except for
14220 the argument initializing the object of a member function. */
14221 if (!DECL_IOBJ_MEMBER_FUNCTION_P (fndecl)
14222 && !TYPE_REF_P (TREE_TYPE (arg)))
14223 continue;
14224 STRIP_NOPS (arg);
14225 if (TREE_CODE (arg) == ADDR_EXPR)
14226 arg = TREE_OPERAND (arg, 0);
14227 /* Recurse to see if the argument is a temporary. It could also
14228 be another call taking a temporary and returning it and
14229 initializing this reference parameter. */
14230 if (do_warn_dangling_reference (arg, /*arg_p=*/true))
14231 return expr;
14232 /* Don't warn about member functions like:
14233 std::any a(...);
14234 S& s = a.emplace<S>({0}, 0);
14235 which construct a new object and return a reference to it, but
14236 we still want to detect:
14237 struct S { const S& self () { return *this; } };
14238 const S& s = S().self();
14239 where 's' dangles. If we've gotten here, the object this function
14240 is invoked on is not a temporary. */
14241 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl))
14242 break;
14244 return NULL_TREE;
14246 case COMPOUND_EXPR:
14247 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
14248 case COND_EXPR:
14249 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
14250 return t;
14251 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
14252 case PAREN_EXPR:
14253 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
14254 case TARGET_EXPR:
14255 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
14256 default:
14257 return NULL_TREE;
14261 /* Implement -Wdangling-reference, to detect cases like
14263 int n = 1;
14264 const int& r = std::max(n - 1, n + 1); // r is dangling
14266 This creates temporaries from the arguments, returns a reference to
14267 one of the temporaries, but both temporaries are destroyed at the end
14268 of the full expression.
14270 This works by checking if a reference is initialized with a function
14271 that returns a reference, and at least one parameter of the function
14272 is a reference that is bound to a temporary. It assumes that such a
14273 function actually returns one of its arguments.
14275 DECL is the reference being initialized, INIT is the initializer. */
14277 static void
14278 maybe_warn_dangling_reference (const_tree decl, tree init)
14280 if (!warn_dangling_reference)
14281 return;
14282 tree type = TREE_TYPE (decl);
14283 /* Only warn if what we're initializing has type T&& or const T&, or
14284 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14285 bind to a temporary.) */
14286 if (!((TYPE_REF_OBJ_P (type)
14287 && (TYPE_REF_IS_RVALUE (type)
14288 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14289 || std_pair_ref_ref_p (type)))
14290 return;
14291 /* Don't suppress the diagnostic just because the call comes from
14292 a system header. If the DECL is not in a system header, or if
14293 -Wsystem-headers was provided, warn. */
14294 auto wsh
14295 = make_temp_override (global_dc->m_warn_system_headers,
14296 (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14297 || global_dc->m_warn_system_headers));
14298 if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
14300 auto_diagnostic_group d;
14301 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14302 "possibly dangling reference to a temporary"))
14303 inform (EXPR_LOCATION (call), "the temporary was destroyed at "
14304 "the end of the full expression %qE", call);
14308 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
14309 gets used to initialize a reference. */
14311 static tree
14312 prevent_lifetime_extension (tree t)
14314 tree *p = &t;
14315 while (TREE_CODE (*p) == COMPOUND_EXPR)
14316 p = &TREE_OPERAND (*p, 1);
14317 while (handled_component_p (*p))
14318 p = &TREE_OPERAND (*p, 0);
14319 /* Change a TARGET_EXPR from prvalue to xvalue. */
14320 if (TREE_CODE (*p) == TARGET_EXPR)
14321 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14322 move (TARGET_EXPR_SLOT (*p)));
14323 return t;
14326 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14327 which is bound either to a reference or a std::initializer_list. */
14329 static tree
14330 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14331 tree *cond_guard)
14333 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14334 the temporary object that is the complete object of a subobject to which
14335 the reference is bound persists for the lifetime of the reference if the
14336 glvalue to which the reference is bound was obtained through one of the
14337 following:
14338 - a temporary materialization conversion ([conv.rval]),
14339 - ( expression ), where expression is one of these expressions,
14340 - subscripting ([expr.sub]) of an array operand, where that operand is one
14341 of these expressions,
14342 - a class member access ([expr.ref]) using the . operator where the left
14343 operand is one of these expressions and the right operand designates a
14344 non-static data member of non-reference type,
14345 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14346 where the left operand is one of these expressions and the right operand
14347 is a pointer to data member of non-reference type,
14348 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14349 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14350 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14351 a glvalue operand that is one of these expressions to a glvalue that
14352 refers to the object designated by the operand, or to its complete
14353 object or a subobject thereof,
14354 - a conditional expression ([expr.cond]) that is a glvalue where the
14355 second or third operand is one of these expressions, or
14356 - a comma expression ([expr.comma]) that is a glvalue where the right
14357 operand is one of these expressions. */
14359 /* FIXME several cases are still handled wrong (101572, 81420). */
14361 tree sub = init;
14362 tree *p;
14363 STRIP_NOPS (sub);
14364 if (TREE_CODE (sub) == COMPOUND_EXPR)
14366 TREE_OPERAND (sub, 1)
14367 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14368 cond_guard);
14369 return init;
14371 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14372 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14373 (TREE_OPERAND (sub, 1)))))
14375 /* A pointer-to-member operation. */
14376 TREE_OPERAND (sub, 0)
14377 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14378 cond_guard);
14379 return init;
14381 if (TREE_CODE (sub) == COND_EXPR)
14383 tree cur_cond_guard = NULL_TREE;
14384 if (TREE_OPERAND (sub, 1))
14385 TREE_OPERAND (sub, 1)
14386 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14387 &cur_cond_guard);
14388 if (cur_cond_guard)
14390 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14391 NOP_EXPR, boolean_true_node,
14392 tf_warning_or_error);
14393 TREE_OPERAND (sub, 1)
14394 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14395 tf_warning_or_error);
14397 cur_cond_guard = NULL_TREE;
14398 if (TREE_OPERAND (sub, 2))
14399 TREE_OPERAND (sub, 2)
14400 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14401 &cur_cond_guard);
14402 if (cur_cond_guard)
14404 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14405 NOP_EXPR, boolean_true_node,
14406 tf_warning_or_error);
14407 TREE_OPERAND (sub, 2)
14408 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14409 tf_warning_or_error);
14411 return init;
14413 if (TREE_CODE (sub) != ADDR_EXPR)
14414 return init;
14415 /* Deal with binding to a subobject. */
14416 for (p = &TREE_OPERAND (sub, 0);
14417 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14418 p = &TREE_OPERAND (*p, 0);
14419 if (TREE_CODE (*p) == TARGET_EXPR)
14421 tree subinit = NULL_TREE;
14422 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
14423 recompute_tree_invariant_for_addr_expr (sub);
14424 if (init != sub)
14425 init = fold_convert (TREE_TYPE (init), sub);
14426 if (subinit)
14427 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14429 return init;
14432 /* INIT is part of the initializer for DECL. If there are any
14433 reference or initializer lists being initialized, extend their
14434 lifetime to match that of DECL. */
14436 tree
14437 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14438 tree *cond_guard)
14440 tree type = TREE_TYPE (init);
14441 if (processing_template_decl)
14442 return init;
14444 maybe_warn_dangling_reference (decl, init);
14446 if (TYPE_REF_P (type))
14447 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14448 else
14450 tree ctor = init;
14451 if (TREE_CODE (ctor) == TARGET_EXPR)
14452 ctor = TARGET_EXPR_INITIAL (ctor);
14453 if (TREE_CODE (ctor) == CONSTRUCTOR)
14455 /* [dcl.init] When initializing an aggregate from a parenthesized list
14456 of values... a temporary object bound to a reference does not have
14457 its lifetime extended. */
14458 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14459 return init;
14461 if (is_std_init_list (type))
14463 /* The temporary array underlying a std::initializer_list
14464 is handled like a reference temporary. */
14465 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14466 array = extend_ref_init_temps_1 (decl, array, cleanups,
14467 cond_guard);
14468 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14470 else
14472 unsigned i;
14473 constructor_elt *p;
14474 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14475 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14476 p->value = extend_ref_init_temps (decl, p->value, cleanups,
14477 cond_guard);
14479 recompute_constructor_flags (ctor);
14480 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14481 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14485 return init;
14488 /* Returns true iff an initializer for TYPE could contain temporaries that
14489 need to be extended because they are bound to references or
14490 std::initializer_list. */
14492 bool
14493 type_has_extended_temps (tree type)
14495 type = strip_array_types (type);
14496 if (TYPE_REF_P (type))
14497 return true;
14498 if (CLASS_TYPE_P (type))
14500 if (is_std_init_list (type))
14501 return true;
14502 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14503 f; f = next_aggregate_field (DECL_CHAIN (f)))
14504 if (type_has_extended_temps (TREE_TYPE (f)))
14505 return true;
14507 return false;
14510 /* Returns true iff TYPE is some variant of std::initializer_list. */
14512 bool
14513 is_std_init_list (tree type)
14515 if (!TYPE_P (type))
14516 return false;
14517 if (cxx_dialect == cxx98)
14518 return false;
14519 /* Look through typedefs. */
14520 type = TYPE_MAIN_VARIANT (type);
14521 return (CLASS_TYPE_P (type)
14522 && CP_TYPE_CONTEXT (type) == std_node
14523 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14526 /* Returns true iff DECL is a list constructor: i.e. a constructor which
14527 will accept an argument list of a single std::initializer_list<T>. */
14529 bool
14530 is_list_ctor (tree decl)
14532 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14533 tree arg;
14535 if (!args || args == void_list_node)
14536 return false;
14538 arg = non_reference (TREE_VALUE (args));
14539 if (!is_std_init_list (arg))
14540 return false;
14542 args = TREE_CHAIN (args);
14544 if (args && args != void_list_node && !TREE_PURPOSE (args))
14545 /* There are more non-defaulted parms. */
14546 return false;
14548 return true;
14551 /* We know that can_convert_arg_bad already said "no" when trying to convert
14552 FROM to TO with ARG and FLAGS. Try to figure out if it was because
14553 an explicit conversion function was skipped when looking for a way to
14554 perform the conversion. At this point we've already printed an error. */
14556 void
14557 maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
14559 if (!(flags & LOOKUP_ONLYCONVERTING))
14560 return;
14562 conversion_obstack_sentinel cos;
14563 conversion *c = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
14564 flags & ~LOOKUP_ONLYCONVERTING, tf_none);
14565 if (c && !c->bad_p && c->user_conv_p)
14566 /* Ay, the conversion would have worked in direct-init context. */
14567 for (; c; c = next_conversion (c))
14568 if (c->kind == ck_user
14569 && DECL_P (c->cand->fn)
14570 && DECL_NONCONVERTING_P (c->cand->fn))
14571 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
14572 "function was not considered");
14575 /* We're converting EXPR to TYPE. If that conversion involves a conversion
14576 function and we're binding EXPR to a reference parameter of that function,
14577 return true. */
14579 bool
14580 conv_binds_to_reference_parm_p (tree type, tree expr)
14582 conversion_obstack_sentinel cos;
14583 conversion *c = implicit_conversion (type, TREE_TYPE (expr), expr,
14584 /*c_cast_p=*/false, LOOKUP_NORMAL,
14585 tf_none);
14586 if (c && !c->bad_p && c->user_conv_p)
14587 for (; c; c = next_conversion (c))
14588 if (c->kind == ck_user)
14589 for (z_candidate *cand = c->cand; cand; cand = cand->next)
14590 if (cand->viable == 1)
14591 for (size_t i = 0; i < cand->num_convs; ++i)
14592 if (cand->convs[i]->kind == ck_ref_bind
14593 && conv_get_original_expr (cand->convs[i]) == expr)
14594 return true;
14596 return false;
14599 #include "gt-cp-call.h"