1/* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2023 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com) and
4 modified by Brendan Kehoe (brendan@cygnus.com).
5
6This file is part of GCC.
7
8GCC is free software; you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation; either version 3, or (at your option)
11any later version.
12
13GCC is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with GCC; see the file COPYING3. If not see
20<http://www.gnu.org/licenses/>. */
21
22
23/* High-level class interface. */
24
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
47/* The various kinds of conversion. */
48
49enum conversion_kind {
50 ck_identity,
51 ck_lvalue,
52 ck_fnptr,
53 ck_qual,
54 ck_std,
55 ck_ptr,
56 ck_pmem,
57 ck_base,
58 ck_ref_bind,
59 ck_user,
60 ck_ambig,
61 ck_list,
62 ck_aggr,
63 ck_rvalue,
64 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
65 this kind whenever we know the true conversion is either bad or outright
66 invalid, but we don't want to attempt to compute the bad conversion (for
67 sake of avoiding unnecessary instantiation). bad_p should always be set
68 for these. */
69 ck_deferred_bad,
70};
71
72/* The rank of the conversion. Order of the enumerals matters; better
73 conversions should come earlier in the list. */
74
75enum conversion_rank {
76 cr_identity,
77 cr_exact,
78 cr_promotion,
79 cr_std,
80 cr_pbool,
81 cr_user,
82 cr_ellipsis,
83 cr_bad
84};
85
86/* An implicit conversion sequence, in the sense of [over.best.ics].
87 The first conversion to be performed is at the end of the chain.
88 That conversion is always a cr_identity conversion. */
89
90struct conversion {
91 /* The kind of conversion represented by this step. */
92 conversion_kind kind;
93 /* The rank of this conversion. */
94 conversion_rank rank;
95 BOOL_BITFIELD user_conv_p : 1;
96 BOOL_BITFIELD ellipsis_p : 1;
97 BOOL_BITFIELD this_p : 1;
98 /* True if this conversion would be permitted with a bending of
99 language standards, e.g. disregarding pointer qualifiers or
100 converting integers to pointers. */
101 BOOL_BITFIELD bad_p : 1;
102 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
103 temporary should be created to hold the result of the
104 conversion. If KIND is ck_ambig or ck_user, true means force
105 copy-initialization. */
106 BOOL_BITFIELD need_temporary_p : 1;
107 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
108 from a pointer-to-derived to pointer-to-base is being performed. */
109 BOOL_BITFIELD base_p : 1;
110 /* If KIND is ck_ref_bind, true when either an lvalue reference is
111 being bound to an lvalue expression or an rvalue reference is
112 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
113 true when we are treating an lvalue as an rvalue (12.8p33). If
114 ck_identity, we will be binding a reference directly or decaying to
115 a pointer. */
116 BOOL_BITFIELD rvaluedness_matches_p: 1;
117 BOOL_BITFIELD check_narrowing: 1;
118 /* Whether check_narrowing should only check TREE_CONSTANTs; used
119 in build_converted_constant_expr. */
120 BOOL_BITFIELD check_narrowing_const_only: 1;
121 /* True if this conversion is taking place in a copy-initialization context
122 and we should only consider converting constructors. Only set in
123 ck_base and ck_rvalue. */
124 BOOL_BITFIELD copy_init_p : 1;
125 /* The type of the expression resulting from the conversion. */
126 tree type;
127 union {
128 /* The next conversion in the chain. Since the conversions are
129 arranged from outermost to innermost, the NEXT conversion will
130 actually be performed before this conversion. This variant is
131 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
132 ck_list. Please use the next_conversion function instead
133 of using this field directly. */
134 conversion *next;
135 /* The expression at the beginning of the conversion chain. This
136 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
137 You can use conv_get_original_expr to get this expression. */
138 tree expr;
139 /* The array of conversions for an initializer_list, so this
140 variant is used only when KIN D is ck_list. */
141 conversion **list;
142 } u;
143 /* The function candidate corresponding to this conversion
144 sequence. This field is only used if KIND is ck_user. */
145 struct z_candidate *cand;
146};
147
148#define CONVERSION_RANK(NODE) \
149 ((NODE)->bad_p ? cr_bad \
150 : (NODE)->ellipsis_p ? cr_ellipsis \
151 : (NODE)->user_conv_p ? cr_user \
152 : (NODE)->rank)
153
154#define BAD_CONVERSION_RANK(NODE) \
155 ((NODE)->ellipsis_p ? cr_ellipsis \
156 : (NODE)->user_conv_p ? cr_user \
157 : (NODE)->rank)
158
159static struct obstack conversion_obstack;
160static bool conversion_obstack_initialized;
161struct rejection_reason;
162
163static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
164static int equal_functions (tree, tree);
165static int joust (struct z_candidate *, struct z_candidate *, bool,
166 tsubst_flags_t);
167static int compare_ics (conversion *, conversion *);
168static void maybe_warn_class_memaccess (location_t, tree,
169 const vec<tree, va_gc> *);
170static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
171static tree convert_like (conversion *, tree, tsubst_flags_t);
172static tree convert_like_with_context (conversion *, tree, tree, int,
173 tsubst_flags_t);
174static void op_error (const op_location_t &, enum tree_code, enum tree_code,
175 tree, tree, tree, bool);
176static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
177 tsubst_flags_t);
178static void print_z_candidate (location_t, const char *, struct z_candidate *);
179static void print_z_candidates (location_t, struct z_candidate *);
180static tree build_this (tree);
181static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
182static bool any_strictly_viable (struct z_candidate *);
183static struct z_candidate *add_template_candidate
184 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
185 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
186static struct z_candidate *add_template_candidate_real
187 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
188 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
189static bool is_complete (tree);
190static struct z_candidate *add_conv_candidate
191 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
192 tree, tsubst_flags_t);
193static struct z_candidate *add_function_candidate
194 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
195 tree, int, conversion**, bool, tsubst_flags_t);
196static conversion *implicit_conversion (tree, tree, tree, bool, int,
197 tsubst_flags_t);
198static conversion *reference_binding (tree, tree, tree, bool, int,
199 tsubst_flags_t);
200static conversion *build_conv (conversion_kind, tree, conversion *);
201static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
202static conversion *next_conversion (conversion *);
203static bool is_subseq (conversion *, conversion *);
204static conversion *maybe_handle_ref_bind (conversion **);
205static void maybe_handle_implicit_object (conversion **);
206static struct z_candidate *add_candidate
207 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
208 conversion **, tree, tree, int, struct rejection_reason *, int);
209static tree source_type (conversion *);
210static void add_warning (struct z_candidate *, struct z_candidate *);
211static conversion *direct_reference_binding (tree, conversion *);
212static bool promoted_arithmetic_type_p (tree);
213static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
214static char *name_as_c_string (tree, tree, bool *);
215static tree prep_operand (tree);
216static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
217 bool, tree, tree, int, struct z_candidate **,
218 tsubst_flags_t);
219static conversion *merge_conversion_sequences (conversion *, conversion *);
220static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
221static conversion *build_identity_conv (tree, tree);
222static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
223static bool conv_is_prvalue (conversion *);
224static tree prevent_lifetime_extension (tree);
225
226/* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
227 NAME can take many forms... */
228
229bool
230check_dtor_name (tree basetype, tree name)
231{
232 /* Just accept something we've already complained about. */
233 if (name == error_mark_node)
234 return true;
235
236 if (TREE_CODE (name) == TYPE_DECL)
237 name = TREE_TYPE (name);
238 else if (TYPE_P (name))
239 /* OK */;
240 else if (identifier_p (t: name))
241 {
242 if ((MAYBE_CLASS_TYPE_P (basetype)
243 || TREE_CODE (basetype) == ENUMERAL_TYPE)
244 && name == constructor_name (basetype))
245 return true;
246
247 /* Otherwise lookup the name, it could be an unrelated typedef
248 of the correct type. */
249 name = lookup_name (name, want: LOOK_want::TYPE);
250 if (!name)
251 return false;
252 name = TREE_TYPE (name);
253 if (name == error_mark_node)
254 return false;
255 }
256 else
257 {
258 /* In the case of:
259
260 template <class T> struct S { ~S(); };
261 int i;
262 i.~S();
263
264 NAME will be a class template. */
265 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
266 return false;
267 }
268
269 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
270}
271
272/* We want the address of a function or method. We avoid creating a
273 pointer-to-member function. */
274
275tree
276build_addr_func (tree function, tsubst_flags_t complain)
277{
278 tree type = TREE_TYPE (function);
279
280 /* We have to do these by hand to avoid real pointer to member
281 functions. */
282 if (TREE_CODE (type) == METHOD_TYPE)
283 {
284 if (TREE_CODE (function) == OFFSET_REF)
285 {
286 tree object = build_address (TREE_OPERAND (function, 0));
287 return get_member_function_from_ptrfunc (&object,
288 TREE_OPERAND (function, 1),
289 complain);
290 }
291 function = build_address (function);
292 }
293 else if (TREE_CODE (function) == FUNCTION_DECL
294 && DECL_IMMEDIATE_FUNCTION_P (function))
295 function = build_address (function);
296 else
297 function = decay_conversion (function, complain, /*reject_builtin=*/false);
298
299 return function;
300}
301
302/* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
303 POINTER_TYPE to those. Note, pointer to member function types
304 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
305 two variants. build_call_a is the primitive taking an array of
306 arguments, while build_call_n is a wrapper that handles varargs. */
307
308tree
309build_call_n (tree function, int n, ...)
310{
311 if (n == 0)
312 return build_call_a (function, 0, NULL);
313 else
314 {
315 tree *argarray = XALLOCAVEC (tree, n);
316 va_list ap;
317 int i;
318
319 va_start (ap, n);
320 for (i = 0; i < n; i++)
321 argarray[i] = va_arg (ap, tree);
322 va_end (ap);
323 return build_call_a (function, n, argarray);
324 }
325}
326
327/* Update various flags in cfun and the call itself based on what is being
328 called. Split out of build_call_a so that bot_manip can use it too. */
329
330void
331set_flags_from_callee (tree call)
332{
333 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
334 tree decl = cp_get_callee_fndecl_nofold (call);
335
336 /* We check both the decl and the type; a function may be known not to
337 throw without being declared throw(). */
338 bool nothrow = decl && TREE_NOTHROW (decl);
339 tree callee = cp_get_callee (call);
340 if (callee)
341 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
342 else if (TREE_CODE (call) == CALL_EXPR
343 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
344 nothrow = true;
345
346 if (cfun && cp_function_chain && !cp_unevaluated_operand)
347 {
348 if (!nothrow && at_function_scope_p ())
349 cp_function_chain->can_throw = 1;
350
351 if (decl && TREE_THIS_VOLATILE (decl))
352 current_function_returns_abnormally = 1;
353 }
354
355 TREE_NOTHROW (call) = nothrow;
356}
357
358tree
359build_call_a (tree function, int n, tree *argarray)
360{
361 tree decl;
362 tree result_type;
363 tree fntype;
364 int i;
365
366 function = build_addr_func (function, complain: tf_warning_or_error);
367
368 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
369 fntype = TREE_TYPE (TREE_TYPE (function));
370 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
371 result_type = TREE_TYPE (fntype);
372 /* An rvalue has no cv-qualifiers. */
373 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
374 result_type = cv_unqualified (result_type);
375
376 function = build_call_array_loc (input_location,
377 result_type, function, n, argarray);
378 set_flags_from_callee (function);
379
380 decl = get_callee_fndecl (function);
381
382 if (decl && !TREE_USED (decl))
383 {
384 /* We invoke build_call directly for several library
385 functions. These may have been declared normally if
386 we're building libgcc, so we can't just check
387 DECL_ARTIFICIAL. */
388 gcc_assert (DECL_ARTIFICIAL (decl)
389 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
390 "__", 2));
391 mark_used (decl);
392 }
393
394 require_complete_eh_spec_types (fntype, decl);
395
396 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
397
398 /* Don't pass empty class objects by value. This is useful
399 for tags in STL, which are used to control overload resolution.
400 We don't need to handle other cases of copying empty classes. */
401 if (!decl || !fndecl_built_in_p (node: decl))
402 for (i = 0; i < n; i++)
403 {
404 tree arg = CALL_EXPR_ARG (function, i);
405 if (is_empty_class (TREE_TYPE (arg))
406 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
407 {
408 while (TREE_CODE (arg) == TARGET_EXPR)
409 /* We're disconnecting the initializer from its target,
410 don't create a temporary. */
411 arg = TARGET_EXPR_INITIAL (arg);
412 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
413 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
414 CALL_EXPR_ARG (function, i) = arg;
415 }
416 }
417
418 return function;
419}
420
421/* New overloading code. */
422
423struct z_candidate;
424
425struct candidate_warning {
426 z_candidate *loser;
427 candidate_warning *next;
428};
429
430/* Information for providing diagnostics about why overloading failed. */
431
432enum rejection_reason_code {
433 rr_none,
434 rr_arity,
435 rr_explicit_conversion,
436 rr_template_conversion,
437 rr_arg_conversion,
438 rr_bad_arg_conversion,
439 rr_template_unification,
440 rr_invalid_copy,
441 rr_inherited_ctor,
442 rr_constraint_failure
443};
444
445struct conversion_info {
446 /* The index of the argument, 0-based. */
447 int n_arg;
448 /* The actual argument or its type. */
449 tree from;
450 /* The type of the parameter. */
451 tree to_type;
452 /* The location of the argument. */
453 location_t loc;
454};
455
456struct rejection_reason {
457 enum rejection_reason_code code;
458 union {
459 /* Information about an arity mismatch. */
460 struct {
461 /* The expected number of arguments. */
462 int expected;
463 /* The actual number of arguments in the call. */
464 int actual;
465 /* Whether EXPECTED should be treated as a lower bound. */
466 bool least_p;
467 } arity;
468 /* Information about an argument conversion mismatch. */
469 struct conversion_info conversion;
470 /* Same, but for bad argument conversions. */
471 struct conversion_info bad_conversion;
472 /* Information about template unification failures. These are the
473 parameters passed to fn_type_unification. */
474 struct {
475 tree tmpl;
476 tree explicit_targs;
477 int num_targs;
478 const tree *args;
479 unsigned int nargs;
480 tree return_type;
481 unification_kind_t strict;
482 int flags;
483 } template_unification;
484 /* Information about template instantiation failures. These are the
485 parameters passed to instantiate_template. */
486 struct {
487 tree tmpl;
488 tree targs;
489 } template_instantiation;
490 } u;
491};
492
493struct z_candidate {
494 /* The FUNCTION_DECL that will be called if this candidate is
495 selected by overload resolution. */
496 tree fn;
497 /* If not NULL_TREE, the first argument to use when calling this
498 function. */
499 tree first_arg;
500 /* The rest of the arguments to use when calling this function. If
501 there are no further arguments this may be NULL or it may be an
502 empty vector. */
503 const vec<tree, va_gc> *args;
504 /* The implicit conversion sequences for each of the arguments to
505 FN. */
506 conversion **convs;
507 /* The number of implicit conversion sequences. */
508 size_t num_convs;
509 /* If FN is a user-defined conversion, the standard conversion
510 sequence from the type returned by FN to the desired destination
511 type. */
512 conversion *second_conv;
513 struct rejection_reason *reason;
514 /* If FN is a member function, the binfo indicating the path used to
515 qualify the name of FN at the call site. This path is used to
516 determine whether or not FN is accessible if it is selected by
517 overload resolution. The DECL_CONTEXT of FN will always be a
518 (possibly improper) base of this binfo. */
519 tree access_path;
520 /* If FN is a non-static member function, the binfo indicating the
521 subobject to which the `this' pointer should be converted if FN
522 is selected by overload resolution. The type pointed to by
523 the `this' pointer must correspond to the most derived class
524 indicated by the CONVERSION_PATH. */
525 tree conversion_path;
526 tree template_decl;
527 tree explicit_targs;
528 candidate_warning *warnings;
529 z_candidate *next;
530 int viable;
531
532 /* The flags active in add_candidate. */
533 int flags;
534
535 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
536 bool reversed () const { return (flags & LOOKUP_REVERSED); }
537};
538
539/* Returns true iff T is a null pointer constant in the sense of
540 [conv.ptr]. */
541
542bool
543null_ptr_cst_p (tree t)
544{
545 tree type = TREE_TYPE (t);
546
547 /* [conv.ptr]
548
549 A null pointer constant is an integer literal ([lex.icon]) with value
550 zero or a prvalue of type std::nullptr_t. */
551 if (NULLPTR_TYPE_P (type))
552 return true;
553
554 if (cxx_dialect >= cxx11)
555 {
556 STRIP_ANY_LOCATION_WRAPPER (t);
557
558 /* Core issue 903 says only literal 0 is a null pointer constant. */
559 if (TREE_CODE (t) == INTEGER_CST
560 && !TREE_OVERFLOW (t)
561 && TREE_CODE (type) == INTEGER_TYPE
562 && integer_zerop (t)
563 && !char_type_p (type))
564 return true;
565 }
566 else if (CP_INTEGRAL_TYPE_P (type))
567 {
568 t = fold_non_dependent_expr (t, tf_none);
569 STRIP_NOPS (t);
570 if (integer_zerop (t) && !TREE_OVERFLOW (t))
571 return true;
572 }
573
574 return false;
575}
576
577/* Returns true iff T is a null member pointer value (4.11). */
578
579bool
580null_member_pointer_value_p (tree t)
581{
582 tree type = TREE_TYPE (t);
583 if (!type)
584 return false;
585 else if (TYPE_PTRMEMFUNC_P (type))
586 return (TREE_CODE (t) == CONSTRUCTOR
587 && CONSTRUCTOR_NELTS (t)
588 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
589 else if (TYPE_PTRDATAMEM_P (type))
590 return integer_all_onesp (t);
591 else
592 return false;
593}
594
595/* Returns nonzero if PARMLIST consists of only default parms,
596 ellipsis, and/or undeduced parameter packs. */
597
598bool
599sufficient_parms_p (const_tree parmlist)
600{
601 for (; parmlist && parmlist != void_list_node;
602 parmlist = TREE_CHAIN (parmlist))
603 if (!TREE_PURPOSE (parmlist)
604 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
605 return false;
606 return true;
607}
608
609/* Allocate N bytes of memory from the conversion obstack. The memory
610 is zeroed before being returned. */
611
612static void *
613conversion_obstack_alloc (size_t n)
614{
615 void *p;
616 if (!conversion_obstack_initialized)
617 {
618 gcc_obstack_init (&conversion_obstack);
619 conversion_obstack_initialized = true;
620 }
621 p = obstack_alloc (&conversion_obstack, n);
622 memset (s: p, c: 0, n: n);
623 return p;
624}
625
626/* RAII class to discard anything added to conversion_obstack. */
627
628struct conversion_obstack_sentinel
629{
630 void *p;
631 conversion_obstack_sentinel (): p (conversion_obstack_alloc (n: 0)) {}
632 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
633};
634
635/* Allocate rejection reasons. */
636
637static struct rejection_reason *
638alloc_rejection (enum rejection_reason_code code)
639{
640 struct rejection_reason *p;
641 p = (struct rejection_reason *) conversion_obstack_alloc (n: sizeof *p);
642 p->code = code;
643 return p;
644}
645
646static struct rejection_reason *
647arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
648{
649 struct rejection_reason *r = alloc_rejection (code: rr_arity);
650 int adjust = first_arg != NULL_TREE;
651 r->u.arity.expected = expected - adjust;
652 r->u.arity.actual = actual - adjust;
653 r->u.arity.least_p = least_p;
654 return r;
655}
656
657static struct rejection_reason *
658arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
659 location_t loc)
660{
661 struct rejection_reason *r = alloc_rejection (code: rr_arg_conversion);
662 int adjust = first_arg != NULL_TREE;
663 r->u.conversion.n_arg = n_arg - adjust;
664 r->u.conversion.from = from;
665 r->u.conversion.to_type = to;
666 r->u.conversion.loc = loc;
667 return r;
668}
669
670static struct rejection_reason *
671bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
672 location_t loc)
673{
674 struct rejection_reason *r = alloc_rejection (code: rr_bad_arg_conversion);
675 int adjust = first_arg != NULL_TREE;
676 r->u.bad_conversion.n_arg = n_arg - adjust;
677 r->u.bad_conversion.from = from;
678 r->u.bad_conversion.to_type = to;
679 r->u.bad_conversion.loc = loc;
680 return r;
681}
682
683static struct rejection_reason *
684explicit_conversion_rejection (tree from, tree to)
685{
686 struct rejection_reason *r = alloc_rejection (code: rr_explicit_conversion);
687 r->u.conversion.n_arg = 0;
688 r->u.conversion.from = from;
689 r->u.conversion.to_type = to;
690 r->u.conversion.loc = UNKNOWN_LOCATION;
691 return r;
692}
693
694static struct rejection_reason *
695template_conversion_rejection (tree from, tree to)
696{
697 struct rejection_reason *r = alloc_rejection (code: rr_template_conversion);
698 r->u.conversion.n_arg = 0;
699 r->u.conversion.from = from;
700 r->u.conversion.to_type = to;
701 r->u.conversion.loc = UNKNOWN_LOCATION;
702 return r;
703}
704
705static struct rejection_reason *
706template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
707 const tree *args, unsigned int nargs,
708 tree return_type, unification_kind_t strict,
709 int flags)
710{
711 size_t args_n_bytes = sizeof (*args) * nargs;
712 tree *args1 = (tree *) conversion_obstack_alloc (n: args_n_bytes);
713 struct rejection_reason *r = alloc_rejection (code: rr_template_unification);
714 r->u.template_unification.tmpl = tmpl;
715 r->u.template_unification.explicit_targs = explicit_targs;
716 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
717 /* Copy args to our own storage. */
718 memcpy (dest: args1, src: args, n: args_n_bytes);
719 r->u.template_unification.args = args1;
720 r->u.template_unification.nargs = nargs;
721 r->u.template_unification.return_type = return_type;
722 r->u.template_unification.strict = strict;
723 r->u.template_unification.flags = flags;
724 return r;
725}
726
727static struct rejection_reason *
728template_unification_error_rejection (void)
729{
730 return alloc_rejection (code: rr_template_unification);
731}
732
733static struct rejection_reason *
734invalid_copy_with_fn_template_rejection (void)
735{
736 struct rejection_reason *r = alloc_rejection (code: rr_invalid_copy);
737 return r;
738}
739
740static struct rejection_reason *
741inherited_ctor_rejection (void)
742{
743 struct rejection_reason *r = alloc_rejection (code: rr_inherited_ctor);
744 return r;
745}
746
747/* Build a constraint failure record. */
748
749static struct rejection_reason *
750constraint_failure (void)
751{
752 struct rejection_reason *r = alloc_rejection (code: rr_constraint_failure);
753 return r;
754}
755
756/* Dynamically allocate a conversion. */
757
758static conversion *
759alloc_conversion (conversion_kind kind)
760{
761 conversion *c;
762 c = (conversion *) conversion_obstack_alloc (n: sizeof (conversion));
763 c->kind = kind;
764 return c;
765}
766
767/* Make sure that all memory on the conversion obstack has been
768 freed. */
769
770void
771validate_conversion_obstack (void)
772{
773 if (conversion_obstack_initialized)
774 gcc_assert ((obstack_next_free (&conversion_obstack)
775 == obstack_base (&conversion_obstack)));
776}
777
778/* Dynamically allocate an array of N conversions. */
779
780static conversion **
781alloc_conversions (size_t n)
782{
783 return (conversion **) conversion_obstack_alloc (n: n * sizeof (conversion *));
784}
785
786/* True iff the active member of conversion::u for code CODE is NEXT. */
787
788static inline bool
789has_next (conversion_kind code)
790{
791 return !(code == ck_identity
792 || code == ck_ambig
793 || code == ck_list
794 || code == ck_aggr
795 || code == ck_deferred_bad);
796}
797
798static conversion *
799build_conv (conversion_kind code, tree type, conversion *from)
800{
801 conversion *t;
802 conversion_rank rank = CONVERSION_RANK (from);
803
804 /* Only call this function for conversions that use u.next. */
805 gcc_assert (from == NULL || has_next (code));
806
807 /* Note that the caller is responsible for filling in t->cand for
808 user-defined conversions. */
809 t = alloc_conversion (kind: code);
810 t->type = type;
811 t->u.next = from;
812
813 switch (code)
814 {
815 case ck_ptr:
816 case ck_pmem:
817 case ck_base:
818 case ck_std:
819 if (rank < cr_std)
820 rank = cr_std;
821 break;
822
823 case ck_qual:
824 case ck_fnptr:
825 if (rank < cr_exact)
826 rank = cr_exact;
827 break;
828
829 default:
830 break;
831 }
832 t->rank = rank;
833 t->user_conv_p = (code == ck_user || from->user_conv_p);
834 t->bad_p = from->bad_p;
835 t->base_p = false;
836 return t;
837}
838
839/* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
840 specialization of std::initializer_list<T>, if such a conversion is
841 possible. */
842
843static conversion *
844build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
845{
846 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
847 unsigned len = CONSTRUCTOR_NELTS (ctor);
848 conversion **subconvs = alloc_conversions (n: len);
849 conversion *t;
850 unsigned i;
851 tree val;
852
853 /* Within a list-initialization we can have more user-defined
854 conversions. */
855 flags &= ~LOOKUP_NO_CONVERSION;
856 /* But no narrowing conversions. */
857 flags |= LOOKUP_NO_NARROWING;
858
859 /* Can't make an array of these types. */
860 if (TYPE_REF_P (elttype)
861 || TREE_CODE (elttype) == FUNCTION_TYPE
862 || VOID_TYPE_P (elttype))
863 return NULL;
864
865 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
866 {
867 conversion *sub
868 = implicit_conversion (elttype, TREE_TYPE (val), val,
869 false, flags, complain);
870 if (sub == NULL)
871 return NULL;
872
873 subconvs[i] = sub;
874 }
875
876 t = alloc_conversion (kind: ck_list);
877 t->type = type;
878 t->u.list = subconvs;
879 t->rank = cr_exact;
880
881 for (i = 0; i < len; ++i)
882 {
883 conversion *sub = subconvs[i];
884 if (sub->rank > t->rank)
885 t->rank = sub->rank;
886 if (sub->user_conv_p)
887 t->user_conv_p = true;
888 if (sub->bad_p)
889 t->bad_p = true;
890 }
891
892 return t;
893}
894
895/* Return the next conversion of the conversion chain (if applicable),
896 or NULL otherwise. Please use this function instead of directly
897 accessing fields of struct conversion. */
898
899static conversion *
900next_conversion (conversion *conv)
901{
902 if (conv == NULL
903 || !has_next (code: conv->kind))
904 return NULL;
905 return conv->u.next;
906}
907
908/* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
909 encountered. */
910
911static conversion *
912strip_standard_conversion (conversion *conv)
913{
914 while (conv
915 && conv->kind != ck_user
916 && has_next (code: conv->kind))
917 conv = next_conversion (conv);
918 return conv;
919}
920
921/* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
922 initializer for array type ATYPE. */
923
924static bool
925can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
926{
927 tree elttype = TREE_TYPE (atype);
928 unsigned i;
929
930 if (TREE_CODE (from) == CONSTRUCTOR)
931 {
932 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
933 {
934 tree val = CONSTRUCTOR_ELT (from, i)->value;
935 bool ok;
936 if (TREE_CODE (elttype) == ARRAY_TYPE)
937 ok = can_convert_array (atype: elttype, from: val, flags, complain);
938 else
939 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
940 complain);
941 if (!ok)
942 return false;
943 }
944 return true;
945 }
946
947 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
948 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
949 return array_string_literal_compatible_p (atype, from);
950
951 /* No other valid way to aggregate initialize an array. */
952 return false;
953}
954
955/* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
956 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
957 is in PSET. */
958
959static bool
960field_in_pset (hash_set<tree, true> &pset, tree field)
961{
962 if (pset.contains (k: field))
963 return true;
964 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
965 for (field = TYPE_FIELDS (TREE_TYPE (field));
966 field; field = DECL_CHAIN (field))
967 {
968 field = next_aggregate_field (field);
969 if (field == NULL_TREE)
970 break;
971 if (field_in_pset (pset, field))
972 return true;
973 }
974 return false;
975}
976
977/* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
978 aggregate class, if such a conversion is possible. */
979
980static conversion *
981build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
982{
983 unsigned HOST_WIDE_INT i = 0;
984 conversion *c;
985 tree field = next_aggregate_field (TYPE_FIELDS (type));
986 tree empty_ctor = NULL_TREE;
987 hash_set<tree, true> pset;
988
989 /* We already called reshape_init in implicit_conversion, but it might not
990 have done anything in the case of parenthesized aggr init. */
991
992 /* The conversions within the init-list aren't affected by the enclosing
993 context; they're always simple copy-initialization. */
994 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
995
996 /* For designated initializers, verify that each initializer is convertible
997 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
998 visited. In the following loop then ignore already visited
999 FIELD_DECLs. */
1000 tree idx, val;
1001 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1002 {
1003 if (!idx)
1004 break;
1005
1006 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1007
1008 tree ftype = TREE_TYPE (idx);
1009 bool ok;
1010
1011 if (TREE_CODE (ftype) == ARRAY_TYPE)
1012 ok = can_convert_array (atype: ftype, from: val, flags, complain);
1013 else
1014 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1015 complain);
1016
1017 if (!ok)
1018 return NULL;
1019
1020 /* For unions, there should be just one initializer. */
1021 if (TREE_CODE (type) == UNION_TYPE)
1022 {
1023 field = NULL_TREE;
1024 i = 1;
1025 break;
1026 }
1027 pset.add (k: idx);
1028 }
1029
1030 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1031 {
1032 tree ftype = TREE_TYPE (field);
1033 bool ok;
1034
1035 if (!pset.is_empty () && field_in_pset (pset, field))
1036 continue;
1037 if (i < CONSTRUCTOR_NELTS (ctor))
1038 {
1039 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1040 gcc_checking_assert (!ce->index);
1041 val = ce->value;
1042 ++i;
1043 }
1044 else if (DECL_INITIAL (field))
1045 val = get_nsdmi (field, /*ctor*/false, complain);
1046 else if (TYPE_REF_P (ftype))
1047 /* Value-initialization of reference is ill-formed. */
1048 return NULL;
1049 else
1050 {
1051 if (empty_ctor == NULL_TREE)
1052 empty_ctor = build_constructor (init_list_type_node, NULL);
1053 val = empty_ctor;
1054 }
1055
1056 if (TREE_CODE (ftype) == ARRAY_TYPE)
1057 ok = can_convert_array (atype: ftype, from: val, flags, complain);
1058 else
1059 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1060 complain);
1061
1062 if (!ok)
1063 return NULL;
1064
1065 if (TREE_CODE (type) == UNION_TYPE)
1066 break;
1067 }
1068
1069 if (i < CONSTRUCTOR_NELTS (ctor))
1070 return NULL;
1071
1072 c = alloc_conversion (kind: ck_aggr);
1073 c->type = type;
1074 c->rank = cr_exact;
1075 c->user_conv_p = true;
1076 c->check_narrowing = true;
1077 c->u.expr = ctor;
1078 return c;
1079}
1080
1081/* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1082 array type, if such a conversion is possible. */
1083
1084static conversion *
1085build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1086{
1087 conversion *c;
1088 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1089 tree elttype = TREE_TYPE (type);
1090 bool bad = false;
1091 bool user = false;
1092 enum conversion_rank rank = cr_exact;
1093
1094 /* We might need to propagate the size from the element to the array. */
1095 complete_type (type);
1096
1097 if (TYPE_DOMAIN (type)
1098 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1099 {
1100 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1101 if (alen < len)
1102 return NULL;
1103 }
1104
1105 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1106
1107 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1108 {
1109 conversion *sub
1110 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1111 false, flags, complain);
1112 if (sub == NULL)
1113 return NULL;
1114
1115 if (sub->rank > rank)
1116 rank = sub->rank;
1117 if (sub->user_conv_p)
1118 user = true;
1119 if (sub->bad_p)
1120 bad = true;
1121 }
1122
1123 c = alloc_conversion (kind: ck_aggr);
1124 c->type = type;
1125 c->rank = rank;
1126 c->user_conv_p = user;
1127 c->bad_p = bad;
1128 c->u.expr = ctor;
1129 return c;
1130}
1131
1132/* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1133 complex type, if such a conversion is possible. */
1134
1135static conversion *
1136build_complex_conv (tree type, tree ctor, int flags,
1137 tsubst_flags_t complain)
1138{
1139 conversion *c;
1140 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1141 tree elttype = TREE_TYPE (type);
1142 bool bad = false;
1143 bool user = false;
1144 enum conversion_rank rank = cr_exact;
1145
1146 if (len != 2)
1147 return NULL;
1148
1149 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1150
1151 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1152 {
1153 conversion *sub
1154 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1155 false, flags, complain);
1156 if (sub == NULL)
1157 return NULL;
1158
1159 if (sub->rank > rank)
1160 rank = sub->rank;
1161 if (sub->user_conv_p)
1162 user = true;
1163 if (sub->bad_p)
1164 bad = true;
1165 }
1166
1167 c = alloc_conversion (kind: ck_aggr);
1168 c->type = type;
1169 c->rank = rank;
1170 c->user_conv_p = user;
1171 c->bad_p = bad;
1172 c->u.expr = ctor;
1173 return c;
1174}
1175
1176/* Build a representation of the identity conversion from EXPR to
1177 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1178
1179static conversion *
1180build_identity_conv (tree type, tree expr)
1181{
1182 conversion *c;
1183
1184 c = alloc_conversion (kind: ck_identity);
1185 c->type = type;
1186 c->u.expr = expr;
1187
1188 return c;
1189}
1190
1191/* Converting from EXPR to TYPE was ambiguous in the sense that there
1192 were multiple user-defined conversions to accomplish the job.
1193 Build a conversion that indicates that ambiguity. */
1194
1195static conversion *
1196build_ambiguous_conv (tree type, tree expr)
1197{
1198 conversion *c;
1199
1200 c = alloc_conversion (kind: ck_ambig);
1201 c->type = type;
1202 c->u.expr = expr;
1203
1204 return c;
1205}
1206
1207tree
1208strip_top_quals (tree t)
1209{
1210 if (TREE_CODE (t) == ARRAY_TYPE)
1211 return t;
1212 return cp_build_qualified_type (t, 0);
1213}
1214
1215/* Returns the standard conversion path (see [conv]) from type FROM to type
1216 TO, if any. For proper handling of null pointer constants, you must
1217 also pass the expression EXPR to convert from. If C_CAST_P is true,
1218 this conversion is coming from a C-style cast. */
1219
1220static conversion *
1221standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1222 int flags, tsubst_flags_t complain)
1223{
1224 enum tree_code fcode, tcode;
1225 conversion *conv;
1226 bool fromref = false;
1227 tree qualified_to;
1228
1229 to = non_reference (to);
1230 if (TYPE_REF_P (from))
1231 {
1232 fromref = true;
1233 from = TREE_TYPE (from);
1234 }
1235 qualified_to = to;
1236 to = strip_top_quals (t: to);
1237 from = strip_top_quals (t: from);
1238
1239 if (expr && type_unknown_p (expr))
1240 {
1241 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1242 {
1243 tsubst_flags_t tflags = tf_conv;
1244 expr = instantiate_type (to, expr, tflags);
1245 if (expr == error_mark_node)
1246 return NULL;
1247 from = TREE_TYPE (expr);
1248 }
1249 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1250 {
1251 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1252 expr = resolve_nondeduced_context (expr, complain);
1253 from = TREE_TYPE (expr);
1254 }
1255 }
1256
1257 fcode = TREE_CODE (from);
1258 tcode = TREE_CODE (to);
1259
1260 conv = build_identity_conv (type: from, expr);
1261 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1262 {
1263 from = type_decays_to (from);
1264 fcode = TREE_CODE (from);
1265 /* Tell convert_like that we're using the address. */
1266 conv->rvaluedness_matches_p = true;
1267 conv = build_conv (code: ck_lvalue, type: from, from: conv);
1268 }
1269 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1270 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1271 express the copy constructor call required by copy-initialization. */
1272 else if (fromref || (expr && obvalue_p (expr)))
1273 {
1274 if (expr)
1275 {
1276 tree bitfield_type;
1277 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1278 if (bitfield_type)
1279 {
1280 from = strip_top_quals (t: bitfield_type);
1281 fcode = TREE_CODE (from);
1282 }
1283 }
1284 conv = build_conv (code: ck_rvalue, type: from, from: conv);
1285 /* If we're performing copy-initialization, remember to skip
1286 explicit constructors. */
1287 if (flags & LOOKUP_ONLYCONVERTING)
1288 conv->copy_init_p = true;
1289 }
1290
1291 /* Allow conversion between `__complex__' data types. */
1292 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1293 {
1294 /* The standard conversion sequence to convert FROM to TO is
1295 the standard conversion sequence to perform componentwise
1296 conversion. */
1297 conversion *part_conv = standard_conversion
1298 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1299 complain);
1300
1301 if (!part_conv)
1302 conv = NULL;
1303 else if (part_conv->kind == ck_identity)
1304 /* Leave conv alone. */;
1305 else
1306 {
1307 conv = build_conv (code: part_conv->kind, type: to, from: conv);
1308 conv->rank = part_conv->rank;
1309 }
1310
1311 return conv;
1312 }
1313
1314 if (same_type_p (from, to))
1315 {
1316 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1317 conv->type = qualified_to;
1318 return conv;
1319 }
1320
1321 /* [conv.ptr]
1322 A null pointer constant can be converted to a pointer type; ... A
1323 null pointer constant of integral type can be converted to an
1324 rvalue of type std::nullptr_t. */
1325 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1326 || NULLPTR_TYPE_P (to))
1327 && ((expr && null_ptr_cst_p (t: expr))
1328 || NULLPTR_TYPE_P (from)))
1329 conv = build_conv (code: ck_std, type: to, from: conv);
1330 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1331 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1332 {
1333 /* For backwards brain damage compatibility, allow interconversion of
1334 pointers and integers with a pedwarn. */
1335 conv = build_conv (code: ck_std, type: to, from: conv);
1336 conv->bad_p = true;
1337 }
1338 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1339 {
1340 /* For backwards brain damage compatibility, allow interconversion of
1341 enums and integers with a pedwarn. */
1342 conv = build_conv (code: ck_std, type: to, from: conv);
1343 conv->bad_p = true;
1344 }
1345 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1346 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1347 {
1348 tree to_pointee;
1349 tree from_pointee;
1350
1351 if (tcode == POINTER_TYPE)
1352 {
1353 to_pointee = TREE_TYPE (to);
1354 from_pointee = TREE_TYPE (from);
1355
1356 /* Since this is the target of a pointer, it can't have function
1357 qualifiers, so any TYPE_QUALS must be for attributes const or
1358 noreturn. Strip them. */
1359 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1360 && TYPE_QUALS (to_pointee))
1361 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1362 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1363 && TYPE_QUALS (from_pointee))
1364 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1365 }
1366 else
1367 {
1368 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1369 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1370 }
1371
1372 if (tcode == POINTER_TYPE
1373 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1374 to_pointee))
1375 ;
1376 else if (VOID_TYPE_P (to_pointee)
1377 && !TYPE_PTRDATAMEM_P (from)
1378 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1379 {
1380 tree nfrom = TREE_TYPE (from);
1381 /* Don't try to apply restrict to void. */
1382 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1383 from_pointee = cp_build_qualified_type (void_type_node, quals);
1384 from = build_pointer_type (from_pointee);
1385 conv = build_conv (code: ck_ptr, type: from, from: conv);
1386 }
1387 else if (TYPE_PTRDATAMEM_P (from))
1388 {
1389 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1390 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1391
1392 if (same_type_p (fbase, tbase))
1393 /* No base conversion needed. */;
1394 else if (DERIVED_FROM_P (fbase, tbase)
1395 && (same_type_ignoring_top_level_qualifiers_p
1396 (from_pointee, to_pointee)))
1397 {
1398 from = build_ptrmem_type (tbase, from_pointee);
1399 conv = build_conv (code: ck_pmem, type: from, from: conv);
1400 }
1401 else
1402 return NULL;
1403 }
1404 else if (CLASS_TYPE_P (from_pointee)
1405 && CLASS_TYPE_P (to_pointee)
1406 /* [conv.ptr]
1407
1408 An rvalue of type "pointer to cv D," where D is a
1409 class type, can be converted to an rvalue of type
1410 "pointer to cv B," where B is a base class (clause
1411 _class.derived_) of D. If B is an inaccessible
1412 (clause _class.access_) or ambiguous
1413 (_class.member.lookup_) base class of D, a program
1414 that necessitates this conversion is ill-formed.
1415 Therefore, we use DERIVED_FROM_P, and do not check
1416 access or uniqueness. */
1417 && DERIVED_FROM_P (to_pointee, from_pointee))
1418 {
1419 from_pointee
1420 = cp_build_qualified_type (to_pointee,
1421 cp_type_quals (from_pointee));
1422 from = build_pointer_type (from_pointee);
1423 conv = build_conv (code: ck_ptr, type: from, from: conv);
1424 conv->base_p = true;
1425 }
1426
1427 if (same_type_p (from, to))
1428 /* OK */;
1429 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1430 /* In a C-style cast, we ignore CV-qualification because we
1431 are allowed to perform a static_cast followed by a
1432 const_cast. */
1433 conv = build_conv (code: ck_qual, type: to, from: conv);
1434 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1435 conv = build_conv (code: ck_qual, type: to, from: conv);
1436 else if (expr && string_conv_p (to, expr, 0))
1437 /* converting from string constant to char *. */
1438 conv = build_conv (code: ck_qual, type: to, from: conv);
1439 else if (fnptr_conv_p (to, from))
1440 conv = build_conv (code: ck_fnptr, type: to, from: conv);
1441 /* Allow conversions among compatible ObjC pointer types (base
1442 conversions have been already handled above). */
1443 else if (c_dialect_objc ()
1444 && objc_compare_types (to, from, -4, NULL_TREE))
1445 conv = build_conv (code: ck_ptr, type: to, from: conv);
1446 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1447 {
1448 conv = build_conv (code: ck_ptr, type: to, from: conv);
1449 conv->bad_p = true;
1450 }
1451 else
1452 return NULL;
1453
1454 from = to;
1455 }
1456 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1457 {
1458 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1459 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1460 tree fbase = class_of_this_parm (fntype: fromfn);
1461 tree tbase = class_of_this_parm (fntype: tofn);
1462
1463 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1464 yields false. But a pointer to member of incomplete class is OK. */
1465 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1466 return NULL;
1467
1468 tree fstat = static_fn_type (fromfn);
1469 tree tstat = static_fn_type (tofn);
1470 if (same_type_p (tstat, fstat)
1471 || fnptr_conv_p (tstat, fstat))
1472 /* OK */;
1473 else
1474 return NULL;
1475
1476 if (!same_type_p (fbase, tbase))
1477 {
1478 from = build_memfn_type (fstat,
1479 tbase,
1480 cp_type_quals (tbase),
1481 type_memfn_rqual (tofn));
1482 from = build_ptrmemfunc_type (build_pointer_type (from));
1483 conv = build_conv (code: ck_pmem, type: from, from: conv);
1484 conv->base_p = true;
1485 }
1486 if (fnptr_conv_p (tstat, fstat))
1487 conv = build_conv (code: ck_fnptr, type: to, from: conv);
1488 }
1489 else if (tcode == BOOLEAN_TYPE)
1490 {
1491 /* [conv.bool]
1492
1493 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1494 to member type can be converted to a prvalue of type bool. ...
1495 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1496 std::nullptr_t can be converted to a prvalue of type bool; */
1497 if (ARITHMETIC_TYPE_P (from)
1498 || UNSCOPED_ENUM_P (from)
1499 || fcode == POINTER_TYPE
1500 || TYPE_PTRMEM_P (from)
1501 || NULLPTR_TYPE_P (from))
1502 {
1503 conv = build_conv (code: ck_std, type: to, from: conv);
1504 if (fcode == POINTER_TYPE
1505 || TYPE_PTRDATAMEM_P (from)
1506 || (TYPE_PTRMEMFUNC_P (from)
1507 && conv->rank < cr_pbool)
1508 || NULLPTR_TYPE_P (from))
1509 conv->rank = cr_pbool;
1510 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1511 conv->bad_p = true;
1512 if (flags & LOOKUP_NO_NARROWING)
1513 conv->check_narrowing = true;
1514 return conv;
1515 }
1516
1517 return NULL;
1518 }
1519 /* We don't check for ENUMERAL_TYPE here because there are no standard
1520 conversions to enum type. */
1521 /* As an extension, allow conversion to complex type. */
1522 else if (ARITHMETIC_TYPE_P (to))
1523 {
1524 if (! (INTEGRAL_CODE_P (fcode)
1525 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1526 || SCOPED_ENUM_P (from))
1527 return NULL;
1528
1529 /* If we're parsing an enum with no fixed underlying type, we're
1530 dealing with an incomplete type, which renders the conversion
1531 ill-formed. */
1532 if (!COMPLETE_TYPE_P (from))
1533 return NULL;
1534
1535 conv = build_conv (code: ck_std, type: to, from: conv);
1536
1537 tree underlying_type = NULL_TREE;
1538 if (TREE_CODE (from) == ENUMERAL_TYPE
1539 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1540 underlying_type = ENUM_UNDERLYING_TYPE (from);
1541
1542 /* Give this a better rank if it's a promotion.
1543
1544 To handle CWG 1601, also bump the rank if we are converting
1545 an enumeration with a fixed underlying type to the underlying
1546 type. */
1547 if ((same_type_p (to, type_promotes_to (from))
1548 || (underlying_type && same_type_p (to, underlying_type)))
1549 && next_conversion (conv)->rank <= cr_promotion)
1550 conv->rank = cr_promotion;
1551
1552 /* A prvalue of floating-point type can be converted to a prvalue of
1553 another floating-point type with a greater or equal conversion
1554 rank ([conv.rank]). A prvalue of standard floating-point type can
1555 be converted to a prvalue of another standard floating-point type.
1556 For backwards compatibility with handling __float128 and other
1557 non-standard floating point types, allow all implicit floating
1558 point conversions if neither type is extended floating-point
1559 type and if at least one of them is, fail if they have unordered
1560 conversion rank or from has higher conversion rank. */
1561 if (fcode == REAL_TYPE
1562 && tcode == REAL_TYPE
1563 && (extended_float_type_p (type: from)
1564 || extended_float_type_p (type: to))
1565 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1566 conv->bad_p = true;
1567 }
1568 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1569 && vector_types_convertible_p (t1: from, t2: to, emit_lax_note: false))
1570 return build_conv (code: ck_std, type: to, from: conv);
1571 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1572 && is_properly_derived_from (from, to))
1573 {
1574 if (conv->kind == ck_rvalue)
1575 conv = next_conversion (conv);
1576 conv = build_conv (code: ck_base, type: to, from: conv);
1577 /* The derived-to-base conversion indicates the initialization
1578 of a parameter with base type from an object of a derived
1579 type. A temporary object is created to hold the result of
1580 the conversion unless we're binding directly to a reference. */
1581 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1582 /* If we're performing copy-initialization, remember to skip
1583 explicit constructors. */
1584 if (flags & LOOKUP_ONLYCONVERTING)
1585 conv->copy_init_p = true;
1586 }
1587 else
1588 return NULL;
1589
1590 if (flags & LOOKUP_NO_NARROWING)
1591 conv->check_narrowing = true;
1592
1593 return conv;
1594}
1595
1596/* Returns nonzero if T1 is reference-related to T2. */
1597
1598bool
1599reference_related_p (tree t1, tree t2)
1600{
1601 if (t1 == error_mark_node || t2 == error_mark_node)
1602 return false;
1603
1604 t1 = TYPE_MAIN_VARIANT (t1);
1605 t2 = TYPE_MAIN_VARIANT (t2);
1606
1607 /* [dcl.init.ref]
1608
1609 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1610 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1611 return (similar_type_p (t1, t2)
1612 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1613 && DERIVED_FROM_P (t1, t2)));
1614}
1615
1616/* Returns nonzero if T1 is reference-compatible with T2. */
1617
1618bool
1619reference_compatible_p (tree t1, tree t2)
1620{
1621 /* [dcl.init.ref]
1622
1623 "cv1 T1" is reference compatible with "cv2 T2" if
1624 a prvalue of type "pointer to cv2 T2" can be converted to the type
1625 "pointer to cv1 T1" via a standard conversion sequence. */
1626 tree ptype1 = build_pointer_type (t1);
1627 tree ptype2 = build_pointer_type (t2);
1628 conversion *conv = standard_conversion (to: ptype1, from: ptype2, NULL_TREE,
1629 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1630 if (!conv || conv->bad_p)
1631 return false;
1632 return true;
1633}
1634
1635/* Return true if converting FROM to TO would involve a qualification
1636 conversion. */
1637
1638static bool
1639involves_qualification_conversion_p (tree to, tree from)
1640{
1641 /* If we're not convering a pointer to another one, we won't get
1642 a qualification conversion. */
1643 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1644 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1645 return false;
1646
1647 conversion *conv = standard_conversion (to, from, NULL_TREE,
1648 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1649 for (conversion *t = conv; t; t = next_conversion (conv: t))
1650 if (t->kind == ck_qual)
1651 return true;
1652
1653 return false;
1654}
1655
1656/* A reference of the indicated TYPE is being bound directly to the
1657 expression represented by the implicit conversion sequence CONV.
1658 Return a conversion sequence for this binding. */
1659
1660static conversion *
1661direct_reference_binding (tree type, conversion *conv)
1662{
1663 tree t;
1664
1665 gcc_assert (TYPE_REF_P (type));
1666 gcc_assert (!TYPE_REF_P (conv->type));
1667
1668 t = TREE_TYPE (type);
1669
1670 if (conv->kind == ck_identity)
1671 /* Mark the identity conv as to not decay to rvalue. */
1672 conv->rvaluedness_matches_p = true;
1673
1674 /* [over.ics.rank]
1675
1676 When a parameter of reference type binds directly
1677 (_dcl.init.ref_) to an argument expression, the implicit
1678 conversion sequence is the identity conversion, unless the
1679 argument expression has a type that is a derived class of the
1680 parameter type, in which case the implicit conversion sequence is
1681 a derived-to-base Conversion.
1682
1683 If the parameter binds directly to the result of applying a
1684 conversion function to the argument expression, the implicit
1685 conversion sequence is a user-defined conversion sequence
1686 (_over.ics.user_), with the second standard conversion sequence
1687 either an identity conversion or, if the conversion function
1688 returns an entity of a type that is a derived class of the
1689 parameter type, a derived-to-base conversion. */
1690 if (is_properly_derived_from (conv->type, t))
1691 {
1692 /* Represent the derived-to-base conversion. */
1693 conv = build_conv (code: ck_base, type: t, from: conv);
1694 /* We will actually be binding to the base-class subobject in
1695 the derived class, so we mark this conversion appropriately.
1696 That way, convert_like knows not to generate a temporary. */
1697 conv->need_temporary_p = false;
1698 }
1699 else if (involves_qualification_conversion_p (to: t, from: conv->type))
1700 /* Represent the qualification conversion. After DR 2352
1701 #1 and #2 were indistinguishable conversion sequences:
1702
1703 void f(int*); // #1
1704 void f(const int* const &); // #2
1705 void g(int* p) { f(p); }
1706
1707 because the types "int *" and "const int *const" are
1708 reference-related and we were binding both directly and they
1709 had the same rank. To break it up, we add a ck_qual under the
1710 ck_ref_bind so that conversion sequence ranking chooses #1.
1711
1712 We strip_top_quals here which is also what standard_conversion
1713 does. Failure to do so would confuse comp_cv_qual_signature
1714 into thinking that in
1715
1716 void f(const int * const &); // #1
1717 void f(const int *); // #2
1718 int *x;
1719 f(x);
1720
1721 #2 is a better match than #1 even though they're ambiguous (97296). */
1722 conv = build_conv (code: ck_qual, type: strip_top_quals (t), from: conv);
1723
1724 return build_conv (code: ck_ref_bind, type, from: conv);
1725}
1726
1727/* Returns the conversion path from type FROM to reference type TO for
1728 purposes of reference binding. For lvalue binding, either pass a
1729 reference type to FROM or an lvalue expression to EXPR. If the
1730 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1731 the conversion returned. If C_CAST_P is true, this
1732 conversion is coming from a C-style cast. */
1733
1734static conversion *
1735reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1736 tsubst_flags_t complain)
1737{
1738 conversion *conv = NULL;
1739 tree to = TREE_TYPE (rto);
1740 tree from = rfrom;
1741 tree tfrom;
1742 bool related_p;
1743 bool compatible_p;
1744 cp_lvalue_kind gl_kind;
1745 bool is_lvalue;
1746
1747 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1748 {
1749 expr = instantiate_type (to, expr, tf_none);
1750 if (expr == error_mark_node)
1751 return NULL;
1752 from = TREE_TYPE (expr);
1753 }
1754
1755 bool copy_list_init = false;
1756 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1757 {
1758 maybe_warn_cpp0x (str: CPP0X_INITIALIZER_LISTS);
1759 /* DR 1288: Otherwise, if the initializer list has a single element
1760 of type E and ... [T's] referenced type is reference-related to E,
1761 the object or reference is initialized from that element...
1762
1763 ??? With P0388R4, we should bind 't' directly to U{}:
1764 using U = A[2];
1765 A (&&t)[] = {U{}};
1766 because A[] and A[2] are reference-related. But we don't do it
1767 because grok_reference_init has deduced the array size (to 1), and
1768 A[1] and A[2] aren't reference-related. */
1769 if (CONSTRUCTOR_NELTS (expr) == 1
1770 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1771 {
1772 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1773 if (error_operand_p (t: elt))
1774 return NULL;
1775 tree etype = TREE_TYPE (elt);
1776 if (reference_related_p (t1: to, t2: etype))
1777 {
1778 expr = elt;
1779 from = etype;
1780 goto skip;
1781 }
1782 }
1783 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1784 referenced by T is copy-list-initialized, and the reference is bound
1785 to that temporary. */
1786 copy_list_init = true;
1787 skip:;
1788 }
1789
1790 if (TYPE_REF_P (from))
1791 {
1792 from = TREE_TYPE (from);
1793 if (!TYPE_REF_IS_RVALUE (rfrom)
1794 || TREE_CODE (from) == FUNCTION_TYPE)
1795 gl_kind = clk_ordinary;
1796 else
1797 gl_kind = clk_rvalueref;
1798 }
1799 else if (expr)
1800 gl_kind = lvalue_kind (expr);
1801 else if (CLASS_TYPE_P (from)
1802 || TREE_CODE (from) == ARRAY_TYPE)
1803 gl_kind = clk_class;
1804 else
1805 gl_kind = clk_none;
1806
1807 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1808 if ((flags & LOOKUP_NO_TEMP_BIND)
1809 && (gl_kind & clk_class))
1810 gl_kind = clk_none;
1811
1812 /* Same mask as real_lvalue_p. */
1813 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1814
1815 tfrom = from;
1816 if ((gl_kind & clk_bitfield) != 0)
1817 tfrom = unlowered_expr_type (expr);
1818
1819 /* Figure out whether or not the types are reference-related and
1820 reference compatible. We have to do this after stripping
1821 references from FROM. */
1822 related_p = reference_related_p (t1: to, t2: tfrom);
1823 /* If this is a C cast, first convert to an appropriately qualified
1824 type, so that we can later do a const_cast to the desired type. */
1825 if (related_p && c_cast_p
1826 && !at_least_as_qualified_p (to, tfrom))
1827 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1828 compatible_p = reference_compatible_p (t1: to, t2: tfrom);
1829
1830 /* Directly bind reference when target expression's type is compatible with
1831 the reference and expression is an lvalue. In DR391, the wording in
1832 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1833 const and rvalue references to rvalues of compatible class type.
1834 We should also do direct bindings for non-class xvalues. */
1835 if ((related_p || compatible_p) && gl_kind)
1836 {
1837 /* [dcl.init.ref]
1838
1839 If the initializer expression
1840
1841 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1842 is reference-compatible with "cv2 T2,"
1843
1844 the reference is bound directly to the initializer expression
1845 lvalue.
1846
1847 [...]
1848 If the initializer expression is an rvalue, with T2 a class type,
1849 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1850 is bound to the object represented by the rvalue or to a sub-object
1851 within that object. */
1852
1853 conv = build_identity_conv (type: tfrom, expr);
1854 conv = direct_reference_binding (type: rto, conv);
1855
1856 if (TYPE_REF_P (rfrom))
1857 /* Handle rvalue reference to function properly. */
1858 conv->rvaluedness_matches_p
1859 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1860 else
1861 conv->rvaluedness_matches_p
1862 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1863
1864 if ((gl_kind & clk_bitfield) != 0
1865 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1866 /* For the purposes of overload resolution, we ignore the fact
1867 this expression is a bitfield or packed field. (In particular,
1868 [over.ics.ref] says specifically that a function with a
1869 non-const reference parameter is viable even if the
1870 argument is a bitfield.)
1871
1872 However, when we actually call the function we must create
1873 a temporary to which to bind the reference. If the
1874 reference is volatile, or isn't const, then we cannot make
1875 a temporary, so we just issue an error when the conversion
1876 actually occurs. */
1877 conv->need_temporary_p = true;
1878
1879 /* Don't allow binding of lvalues (other than function lvalues) to
1880 rvalue references. */
1881 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1882 && TREE_CODE (to) != FUNCTION_TYPE)
1883 conv->bad_p = true;
1884
1885 /* Nor the reverse. */
1886 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1887 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1888 But in C++23, such an expression is just an xvalue, not a special
1889 lvalue, so the binding is once again ill-formed. */
1890 && !(cxx_dialect <= cxx20
1891 && (gl_kind & clk_implicit_rval))
1892 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1893 || (flags & LOOKUP_NO_RVAL_BIND))
1894 && TREE_CODE (to) != FUNCTION_TYPE)
1895 conv->bad_p = true;
1896
1897 if (!compatible_p)
1898 conv->bad_p = true;
1899
1900 return conv;
1901 }
1902 /* [class.conv.fct] A conversion function is never used to convert a
1903 (possibly cv-qualified) object to the (possibly cv-qualified) same
1904 object type (or a reference to it), to a (possibly cv-qualified) base
1905 class of that type (or a reference to it).... */
1906 else if (CLASS_TYPE_P (from) && !related_p
1907 && !(flags & LOOKUP_NO_CONVERSION))
1908 {
1909 /* [dcl.init.ref]
1910
1911 If the initializer expression
1912
1913 -- has a class type (i.e., T2 is a class type) can be
1914 implicitly converted to an lvalue of type "cv3 T3," where
1915 "cv1 T1" is reference-compatible with "cv3 T3". (this
1916 conversion is selected by enumerating the applicable
1917 conversion functions (_over.match.ref_) and choosing the
1918 best one through overload resolution. (_over.match_).
1919
1920 the reference is bound to the lvalue result of the conversion
1921 in the second case. */
1922 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1923 complain);
1924 if (cand)
1925 return cand->second_conv;
1926 }
1927
1928 /* From this point on, we conceptually need temporaries, even if we
1929 elide them. Only the cases above are "direct bindings". */
1930 if (flags & LOOKUP_NO_TEMP_BIND)
1931 return NULL;
1932
1933 /* [over.ics.rank]
1934
1935 When a parameter of reference type is not bound directly to an
1936 argument expression, the conversion sequence is the one required
1937 to convert the argument expression to the underlying type of the
1938 reference according to _over.best.ics_. Conceptually, this
1939 conversion sequence corresponds to copy-initializing a temporary
1940 of the underlying type with the argument expression. Any
1941 difference in top-level cv-qualification is subsumed by the
1942 initialization itself and does not constitute a conversion. */
1943
1944 bool maybe_valid_p = true;
1945
1946 /* [dcl.init.ref]
1947
1948 Otherwise, the reference shall be an lvalue reference to a
1949 non-volatile const type, or the reference shall be an rvalue
1950 reference. */
1951 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1952 maybe_valid_p = false;
1953
1954 /* [dcl.init.ref]
1955
1956 Otherwise, a temporary of type "cv1 T1" is created and
1957 initialized from the initializer expression using the rules for a
1958 non-reference copy initialization. If T1 is reference-related to
1959 T2, cv1 must be the same cv-qualification as, or greater
1960 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1961 if (related_p && !at_least_as_qualified_p (to, from))
1962 maybe_valid_p = false;
1963
1964 /* We try below to treat an invalid reference binding as a bad conversion
1965 to improve diagnostics, but doing so may cause otherwise unnecessary
1966 instantiations that can lead to a hard error. So during the first pass
1967 of overload resolution wherein we shortcut bad conversions, instead just
1968 produce a special conversion indicating a second pass is necessary if
1969 there's no strictly viable candidate. */
1970 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1971 {
1972 conv = alloc_conversion (kind: ck_deferred_bad);
1973 conv->bad_p = true;
1974 return conv;
1975 }
1976
1977 /* We're generating a temporary now, but don't bind any more in the
1978 conversion (specifically, don't slice the temporary returned by a
1979 conversion operator). */
1980 flags |= LOOKUP_NO_TEMP_BIND;
1981
1982 /* Core issue 899: When [copy-]initializing a temporary to be bound
1983 to the first parameter of a copy constructor (12.8) called with
1984 a single argument in the context of direct-initialization,
1985 explicit conversion functions are also considered.
1986
1987 So don't set LOOKUP_ONLYCONVERTING in that case. */
1988 if (!(flags & LOOKUP_COPY_PARM))
1989 flags |= LOOKUP_ONLYCONVERTING;
1990
1991 if (!conv)
1992 conv = implicit_conversion (to, from, expr, c_cast_p,
1993 flags, complain);
1994 if (!conv)
1995 return NULL;
1996
1997 if (conv->user_conv_p)
1998 {
1999 if (copy_list_init)
2000 /* Remember this was copy-list-initialization. */
2001 conv->need_temporary_p = true;
2002
2003 /* If initializing the temporary used a conversion function,
2004 recalculate the second conversion sequence. */
2005 for (conversion *t = conv; t; t = next_conversion (conv: t))
2006 if (t->kind == ck_user
2007 && DECL_CONV_FN_P (t->cand->fn))
2008 {
2009 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2010 /* A prvalue of non-class type is cv-unqualified. */
2011 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2012 ftype = cv_unqualified (ftype);
2013 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2014 conversion *new_second
2015 = reference_binding (rto, rfrom: ftype, NULL_TREE, c_cast_p,
2016 flags: sflags, complain);
2017 if (!new_second)
2018 return NULL;
2019 conv = merge_conversion_sequences (t, new_second);
2020 gcc_assert (maybe_valid_p || conv->bad_p);
2021 return conv;
2022 }
2023 }
2024
2025 conv = build_conv (code: ck_ref_bind, type: rto, from: conv);
2026 /* This reference binding, unlike those above, requires the
2027 creation of a temporary. */
2028 conv->need_temporary_p = true;
2029 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2030 conv->bad_p |= !maybe_valid_p;
2031
2032 return conv;
2033}
2034
2035/* Returns the implicit conversion sequence (see [over.ics]) from type
2036 FROM to type TO. The optional expression EXPR may affect the
2037 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2038 true, this conversion is coming from a C-style cast. */
2039
2040static conversion *
2041implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2042 int flags, tsubst_flags_t complain)
2043{
2044 conversion *conv;
2045
2046 if (from == error_mark_node || to == error_mark_node
2047 || expr == error_mark_node)
2048 return NULL;
2049
2050 /* Other flags only apply to the primary function in overload
2051 resolution, or after we've chosen one. */
2052 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2053 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2054 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2055
2056 /* FIXME: actually we don't want warnings either, but we can't just
2057 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2058 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2059 We really ought not to issue that warning until we've committed
2060 to that conversion. */
2061 complain &= ~tf_error;
2062
2063 /* Call reshape_init early to remove redundant braces. */
2064 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2065 {
2066 to = complete_type (to);
2067 if (!COMPLETE_TYPE_P (to))
2068 return nullptr;
2069 if (!CLASSTYPE_NON_AGGREGATE (to))
2070 {
2071 expr = reshape_init (to, expr, complain);
2072 if (expr == error_mark_node)
2073 return nullptr;
2074 from = TREE_TYPE (expr);
2075 }
2076 }
2077
2078 if (TYPE_REF_P (to))
2079 conv = reference_binding (rto: to, rfrom: from, expr, c_cast_p, flags, complain);
2080 else
2081 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2082
2083 if (conv)
2084 return conv;
2085
2086 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2087 {
2088 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2089 return build_list_conv (type: to, ctor: expr, flags, complain);
2090
2091 /* As an extension, allow list-initialization of _Complex. */
2092 if (TREE_CODE (to) == COMPLEX_TYPE
2093 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2094 {
2095 conv = build_complex_conv (type: to, ctor: expr, flags, complain);
2096 if (conv)
2097 return conv;
2098 }
2099
2100 /* Allow conversion from an initializer-list with one element to a
2101 scalar type. */
2102 if (SCALAR_TYPE_P (to))
2103 {
2104 int nelts = CONSTRUCTOR_NELTS (expr);
2105 tree elt;
2106
2107 if (nelts == 0)
2108 elt = build_value_init (to, tf_none);
2109 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2110 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2111 else
2112 elt = error_mark_node;
2113
2114 conv = implicit_conversion (to, TREE_TYPE (elt), expr: elt,
2115 c_cast_p, flags, complain);
2116 if (conv)
2117 {
2118 conv->check_narrowing = true;
2119 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2120 /* Too many levels of braces, i.e. '{{1}}'. */
2121 conv->bad_p = true;
2122 return conv;
2123 }
2124 }
2125 else if (TREE_CODE (to) == ARRAY_TYPE)
2126 return build_array_conv (type: to, ctor: expr, flags, complain);
2127 }
2128
2129 if (expr != NULL_TREE
2130 && (MAYBE_CLASS_TYPE_P (from)
2131 || MAYBE_CLASS_TYPE_P (to))
2132 && (flags & LOOKUP_NO_CONVERSION) == 0)
2133 {
2134 struct z_candidate *cand;
2135
2136 if (CLASS_TYPE_P (to)
2137 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2138 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2139 return build_aggr_conv (type: to, ctor: expr, flags, complain);
2140
2141 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2142 if (cand)
2143 {
2144 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2145 && CONSTRUCTOR_NELTS (expr) == 1
2146 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2147 && !is_list_ctor (cand->fn))
2148 {
2149 /* "If C is not an initializer-list constructor and the
2150 initializer list has a single element of type cv U, where U is
2151 X or a class derived from X, the implicit conversion sequence
2152 has Exact Match rank if U is X, or Conversion rank if U is
2153 derived from X." */
2154 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2155 tree elttype = TREE_TYPE (elt);
2156 if (reference_related_p (t1: to, t2: elttype))
2157 return implicit_conversion (to, from: elttype, expr: elt,
2158 c_cast_p, flags, complain);
2159 }
2160 conv = cand->second_conv;
2161 }
2162
2163 /* We used to try to bind a reference to a temporary here, but that
2164 is now handled after the recursive call to this function at the end
2165 of reference_binding. */
2166 return conv;
2167 }
2168
2169 return NULL;
2170}
2171
2172/* Like implicit_conversion, but return NULL if the conversion is bad.
2173
2174 This is not static so that check_non_deducible_conversion can call it within
2175 add_template_candidate_real as part of overload resolution; it should not be
2176 called outside of overload resolution. */
2177
2178conversion *
2179good_conversion (tree to, tree from, tree expr,
2180 int flags, tsubst_flags_t complain)
2181{
2182 conversion *c = implicit_conversion (to, from, expr, /*cast*/c_cast_p: false,
2183 flags, complain);
2184 if (c && c->bad_p)
2185 c = NULL;
2186 return c;
2187}
2188
2189/* Add a new entry to the list of candidates. Used by the add_*_candidate
2190 functions. ARGS will not be changed until a single candidate is
2191 selected. */
2192
2193static struct z_candidate *
2194add_candidate (struct z_candidate **candidates,
2195 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2196 size_t num_convs, conversion **convs,
2197 tree access_path, tree conversion_path,
2198 int viable, struct rejection_reason *reason,
2199 int flags)
2200{
2201 struct z_candidate *cand = (struct z_candidate *)
2202 conversion_obstack_alloc (n: sizeof (struct z_candidate));
2203
2204 cand->fn = fn;
2205 cand->first_arg = first_arg;
2206 cand->args = args;
2207 cand->convs = convs;
2208 cand->num_convs = num_convs;
2209 cand->access_path = access_path;
2210 cand->conversion_path = conversion_path;
2211 cand->viable = viable;
2212 cand->reason = reason;
2213 cand->next = *candidates;
2214 cand->flags = flags;
2215 *candidates = cand;
2216
2217 if (convs && cand->reversed ())
2218 /* Swap the conversions for comparison in joust; we'll swap them back
2219 before build_over_call. */
2220 std::swap (a&: convs[0], b&: convs[1]);
2221
2222 return cand;
2223}
2224
2225/* Return the number of remaining arguments in the parameter list
2226 beginning with ARG. */
2227
2228int
2229remaining_arguments (tree arg)
2230{
2231 int n;
2232
2233 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2234 arg = TREE_CHAIN (arg))
2235 n++;
2236
2237 return n;
2238}
2239
2240/* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2241 to the first parameter of a constructor where the parameter is of type
2242 "reference to possibly cv-qualified T" and the constructor is called with a
2243 single argument in the context of direct-initialization of an object of type
2244 "cv2 T", explicit conversion functions are also considered.
2245
2246 So set LOOKUP_COPY_PARM to let reference_binding know that
2247 it's being called in that context. */
2248
2249int
2250conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2251{
2252 int lflags = flags;
2253 tree t;
2254 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2255 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2256 && (same_type_ignoring_top_level_qualifiers_p
2257 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2258 {
2259 if (!(flags & LOOKUP_ONLYCONVERTING))
2260 lflags |= LOOKUP_COPY_PARM;
2261 if ((flags & LOOKUP_LIST_INIT_CTOR)
2262 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2263 lflags |= LOOKUP_NO_CONVERSION;
2264 }
2265 else
2266 lflags |= LOOKUP_ONLYCONVERTING;
2267
2268 return lflags;
2269}
2270
2271/* Build an appropriate 'this' conversion for the method FN and class
2272 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2273 This function modifies PARMTYPE, ARGTYPE and ARG. */
2274
2275static conversion *
2276build_this_conversion (tree fn, tree ctype,
2277 tree& parmtype, tree& argtype, tree& arg,
2278 int flags, tsubst_flags_t complain)
2279{
2280 gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2281 && !DECL_CONSTRUCTOR_P (fn));
2282
2283 /* The type of the implicit object parameter ('this') for
2284 overload resolution is not always the same as for the
2285 function itself; conversion functions are considered to
2286 be members of the class being converted, and functions
2287 introduced by a using-declaration are considered to be
2288 members of the class that uses them.
2289
2290 Since build_over_call ignores the ICS for the `this'
2291 parameter, we can just change the parm type. */
2292 parmtype = cp_build_qualified_type (ctype,
2293 cp_type_quals (TREE_TYPE (parmtype)));
2294 bool this_p = true;
2295 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2296 {
2297 /* If the function has a ref-qualifier, the implicit
2298 object parameter has reference type. */
2299 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2300 parmtype = cp_build_reference_type (parmtype, rv);
2301 /* The special handling of 'this' conversions in compare_ics
2302 does not apply if there is a ref-qualifier. */
2303 this_p = false;
2304 }
2305 else
2306 {
2307 parmtype = build_pointer_type (parmtype);
2308 /* We don't use build_this here because we don't want to
2309 capture the object argument until we've chosen a
2310 non-static member function. */
2311 arg = build_address (arg);
2312 argtype = lvalue_type (arg);
2313 }
2314 flags |= LOOKUP_ONLYCONVERTING;
2315 conversion *t = implicit_conversion (to: parmtype, from: argtype, expr: arg,
2316 /*c_cast_p=*/false, flags, complain);
2317 t->this_p = this_p;
2318 return t;
2319}
2320
2321/* Create an overload candidate for the function or method FN called
2322 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2323 FLAGS is passed on to implicit_conversion.
2324
2325 This does not change ARGS.
2326
2327 CTYPE, if non-NULL, is the type we want to pretend this function
2328 comes from for purposes of overload resolution.
2329
2330 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2331 If true, we stop computing conversions upon seeing the first bad
2332 conversion. This is used by add_candidates to avoid computing
2333 more conversions than necessary in the presence of a strictly viable
2334 candidate, while preserving the defacto behavior of overload resolution
2335 when it turns out there are only non-strictly viable candidates. */
2336
2337static struct z_candidate *
2338add_function_candidate (struct z_candidate **candidates,
2339 tree fn, tree ctype, tree first_arg,
2340 const vec<tree, va_gc> *args, tree access_path,
2341 tree conversion_path, int flags,
2342 conversion **convs,
2343 bool shortcut_bad_convs,
2344 tsubst_flags_t complain)
2345{
2346 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2347 int i, len;
2348 tree parmnode;
2349 tree orig_first_arg = first_arg;
2350 int skip;
2351 int viable = 1;
2352 struct rejection_reason *reason = NULL;
2353
2354 /* The `this', `in_chrg' and VTT arguments to constructors are not
2355 considered in overload resolution. */
2356 if (DECL_CONSTRUCTOR_P (fn))
2357 {
2358 if (ctor_omit_inherited_parms (fn))
2359 /* Bring back parameters omitted from an inherited ctor. */
2360 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2361 else
2362 parmlist = skip_artificial_parms_for (fn, parmlist);
2363 skip = num_artificial_parms_for (fn);
2364 if (skip > 0 && first_arg != NULL_TREE)
2365 {
2366 --skip;
2367 first_arg = NULL_TREE;
2368 }
2369 }
2370 else
2371 skip = 0;
2372
2373 len = vec_safe_length (v: args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2374 if (!convs)
2375 convs = alloc_conversions (n: len);
2376
2377 /* 13.3.2 - Viable functions [over.match.viable]
2378 First, to be a viable function, a candidate function shall have enough
2379 parameters to agree in number with the arguments in the list.
2380
2381 We need to check this first; otherwise, checking the ICSes might cause
2382 us to produce an ill-formed template instantiation. */
2383
2384 parmnode = parmlist;
2385 for (i = 0; i < len; ++i)
2386 {
2387 if (parmnode == NULL_TREE || parmnode == void_list_node)
2388 break;
2389 parmnode = TREE_CHAIN (parmnode);
2390 }
2391
2392 if ((i < len && parmnode)
2393 || !sufficient_parms_p (parmlist: parmnode))
2394 {
2395 int remaining = remaining_arguments (arg: parmnode);
2396 viable = 0;
2397 reason = arity_rejection (first_arg, expected: i + remaining, actual: len);
2398 }
2399
2400 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2401 parameter of type "reference to cv C" (including such a constructor
2402 instantiated from a template) is excluded from the set of candidate
2403 functions when used to construct an object of type D with an argument list
2404 containing a single argument if C is reference-related to D. */
2405 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2406 && flag_new_inheriting_ctors
2407 && DECL_INHERITED_CTOR (fn))
2408 {
2409 tree ptype = non_reference (TREE_VALUE (parmlist));
2410 tree dtype = DECL_CONTEXT (fn);
2411 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2412 if (reference_related_p (t1: ptype, t2: dtype)
2413 && reference_related_p (t1: btype, t2: ptype))
2414 {
2415 viable = false;
2416 reason = inherited_ctor_rejection ();
2417 }
2418 }
2419
2420 /* Second, for a function to be viable, its constraints must be
2421 satisfied. */
2422 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2423 {
2424 reason = constraint_failure ();
2425 viable = false;
2426 }
2427
2428 /* When looking for a function from a subobject from an implicit
2429 copy/move constructor/operator=, don't consider anything that takes (a
2430 reference to) an unrelated type. See c++/44909 and core 1092. */
2431 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2432 {
2433 if (DECL_CONSTRUCTOR_P (fn))
2434 i = 1;
2435 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2436 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2437 i = 2;
2438 else
2439 i = 0;
2440 if (i && len == i)
2441 {
2442 parmnode = chain_index (i-1, parmlist);
2443 if (!reference_related_p (t1: non_reference (TREE_VALUE (parmnode)),
2444 t2: ctype))
2445 viable = 0;
2446 }
2447
2448 /* This only applies at the top level. */
2449 flags &= ~LOOKUP_DEFAULTED;
2450 }
2451
2452 if (! viable)
2453 goto out;
2454
2455 if (shortcut_bad_convs)
2456 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2457 else
2458 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2459
2460 /* Third, for F to be a viable function, there shall exist for each
2461 argument an implicit conversion sequence that converts that argument
2462 to the corresponding parameter of F. */
2463
2464 parmnode = parmlist;
2465
2466 for (i = 0; i < len; ++i)
2467 {
2468 tree argtype, to_type;
2469 tree arg;
2470
2471 if (parmnode == void_list_node)
2472 break;
2473
2474 if (convs[i])
2475 {
2476 /* Already set during deduction. */
2477 parmnode = TREE_CHAIN (parmnode);
2478 continue;
2479 }
2480
2481 if (i == 0 && first_arg != NULL_TREE)
2482 arg = first_arg;
2483 else
2484 arg = CONST_CAST_TREE (
2485 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2486 argtype = lvalue_type (arg);
2487
2488 conversion *t;
2489 if (parmnode)
2490 {
2491 tree parmtype = TREE_VALUE (parmnode);
2492 if (i == 0
2493 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2494 && !DECL_CONSTRUCTOR_P (fn))
2495 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2496 flags, complain);
2497 else
2498 {
2499 int lflags = conv_flags (i, nargs: len-skip, fn, arg, flags);
2500 t = implicit_conversion (to: parmtype, from: argtype, expr: arg,
2501 /*c_cast_p=*/false, flags: lflags, complain);
2502 }
2503 to_type = parmtype;
2504 parmnode = TREE_CHAIN (parmnode);
2505 }
2506 else
2507 {
2508 t = build_identity_conv (type: argtype, expr: arg);
2509 t->ellipsis_p = true;
2510 to_type = argtype;
2511 }
2512
2513 convs[i] = t;
2514 if (! t)
2515 {
2516 viable = 0;
2517 reason = arg_conversion_rejection (first_arg, n_arg: i, from: argtype, to: to_type,
2518 EXPR_LOCATION (arg));
2519 break;
2520 }
2521
2522 if (t->bad_p)
2523 {
2524 viable = -1;
2525 reason = bad_arg_conversion_rejection (first_arg, n_arg: i, from: arg, to: to_type,
2526 EXPR_LOCATION (arg));
2527 if (shortcut_bad_convs)
2528 break;
2529 }
2530 }
2531
2532 out:
2533 return add_candidate (candidates, fn, first_arg: orig_first_arg, args, num_convs: len, convs,
2534 access_path, conversion_path, viable, reason, flags);
2535}
2536
2537/* Create an overload candidate for the conversion function FN which will
2538 be invoked for expression OBJ, producing a pointer-to-function which
2539 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2540 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2541 passed on to implicit_conversion.
2542
2543 Actually, we don't really care about FN; we care about the type it
2544 converts to. There may be multiple conversion functions that will
2545 convert to that type, and we rely on build_user_type_conversion_1 to
2546 choose the best one; so when we create our candidate, we record the type
2547 instead of the function. */
2548
2549static struct z_candidate *
2550add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2551 const vec<tree, va_gc> *arglist,
2552 tree access_path, tree conversion_path,
2553 tsubst_flags_t complain)
2554{
2555 tree totype = TREE_TYPE (TREE_TYPE (fn));
2556 int i, len, viable, flags;
2557 tree parmlist, parmnode;
2558 conversion **convs;
2559 struct rejection_reason *reason;
2560
2561 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2562 parmlist = TREE_TYPE (parmlist);
2563 parmlist = TYPE_ARG_TYPES (parmlist);
2564
2565 len = vec_safe_length (v: arglist) + 1;
2566 convs = alloc_conversions (n: len);
2567 parmnode = parmlist;
2568 viable = 1;
2569 flags = LOOKUP_IMPLICIT;
2570 reason = NULL;
2571
2572 /* Don't bother looking up the same type twice. */
2573 if (*candidates && (*candidates)->fn == totype)
2574 return NULL;
2575
2576 if (!constraints_satisfied_p (fn))
2577 {
2578 reason = constraint_failure ();
2579 viable = 0;
2580 return add_candidate (candidates, fn, first_arg: obj, args: arglist, num_convs: len, convs,
2581 access_path, conversion_path, viable, reason, flags);
2582 }
2583
2584 for (i = 0; i < len; ++i)
2585 {
2586 tree arg, argtype, convert_type = NULL_TREE;
2587 conversion *t;
2588
2589 if (i == 0)
2590 arg = obj;
2591 else
2592 arg = (*arglist)[i - 1];
2593 argtype = lvalue_type (arg);
2594
2595 if (i == 0)
2596 {
2597 t = build_identity_conv (type: argtype, NULL_TREE);
2598 t = build_conv (code: ck_user, type: totype, from: t);
2599 /* Leave the 'cand' field null; we'll figure out the conversion in
2600 convert_like if this candidate is chosen. */
2601 convert_type = totype;
2602 }
2603 else if (parmnode == void_list_node)
2604 break;
2605 else if (parmnode)
2606 {
2607 t = implicit_conversion (TREE_VALUE (parmnode), from: argtype, expr: arg,
2608 /*c_cast_p=*/false, flags, complain);
2609 convert_type = TREE_VALUE (parmnode);
2610 }
2611 else
2612 {
2613 t = build_identity_conv (type: argtype, expr: arg);
2614 t->ellipsis_p = true;
2615 convert_type = argtype;
2616 }
2617
2618 convs[i] = t;
2619 if (! t)
2620 break;
2621
2622 if (t->bad_p)
2623 {
2624 viable = -1;
2625 reason = bad_arg_conversion_rejection (NULL_TREE, n_arg: i, from: arg, to: convert_type,
2626 EXPR_LOCATION (arg));
2627 }
2628
2629 if (i == 0)
2630 continue;
2631
2632 if (parmnode)
2633 parmnode = TREE_CHAIN (parmnode);
2634 }
2635
2636 if (i < len
2637 || ! sufficient_parms_p (parmlist: parmnode))
2638 {
2639 int remaining = remaining_arguments (arg: parmnode);
2640 viable = 0;
2641 reason = arity_rejection (NULL_TREE, expected: i + remaining, actual: len);
2642 }
2643
2644 return add_candidate (candidates, fn: totype, first_arg: obj, args: arglist, num_convs: len, convs,
2645 access_path, conversion_path, viable, reason, flags);
2646}
2647
2648static void
2649build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2650 tree type1, tree type2, const vec<tree,va_gc> &args,
2651 tree *argtypes, int flags, tsubst_flags_t complain)
2652{
2653 conversion *t;
2654 conversion **convs;
2655 size_t num_convs;
2656 int viable = 1;
2657 tree types[2];
2658 struct rejection_reason *reason = NULL;
2659
2660 types[0] = type1;
2661 types[1] = type2;
2662
2663 num_convs = args.length ();
2664 convs = alloc_conversions (n: num_convs);
2665
2666 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2667 conversion ops are allowed. We handle that here by just checking for
2668 boolean_type_node because other operators don't ask for it. COND_EXPR
2669 also does contextual conversion to bool for the first operand, but we
2670 handle that in build_conditional_expr, and type1 here is operand 2. */
2671 if (type1 != boolean_type_node)
2672 flags |= LOOKUP_ONLYCONVERTING;
2673
2674 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2675 {
2676 t = implicit_conversion (to: types[i], from: argtypes[i], expr: args[i],
2677 /*c_cast_p=*/false, flags, complain);
2678 if (! t)
2679 {
2680 viable = 0;
2681 /* We need something for printing the candidate. */
2682 t = build_identity_conv (type: types[i], NULL_TREE);
2683 reason = arg_conversion_rejection (NULL_TREE, n_arg: i, from: argtypes[i],
2684 to: types[i], EXPR_LOCATION (args[i]));
2685 }
2686 else if (t->bad_p)
2687 {
2688 viable = 0;
2689 reason = bad_arg_conversion_rejection (NULL_TREE, n_arg: i, from: args[i],
2690 to: types[i],
2691 EXPR_LOCATION (args[i]));
2692 }
2693 convs[i] = t;
2694 }
2695
2696 /* For COND_EXPR we rearranged the arguments; undo that now. */
2697 if (num_convs == 3)
2698 {
2699 convs[2] = convs[1];
2700 convs[1] = convs[0];
2701 t = implicit_conversion (boolean_type_node, from: argtypes[2], expr: args[2],
2702 /*c_cast_p=*/false, flags,
2703 complain);
2704 if (t)
2705 convs[0] = t;
2706 else
2707 {
2708 viable = 0;
2709 reason = arg_conversion_rejection (NULL_TREE, n_arg: 0, from: argtypes[2],
2710 boolean_type_node,
2711 EXPR_LOCATION (args[2]));
2712 }
2713 }
2714
2715 add_candidate (candidates, fn: fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2716 num_convs, convs,
2717 /*access_path=*/NULL_TREE,
2718 /*conversion_path=*/NULL_TREE,
2719 viable, reason, flags);
2720}
2721
2722static bool
2723is_complete (tree t)
2724{
2725 return COMPLETE_TYPE_P (complete_type (t));
2726}
2727
2728/* Returns nonzero if TYPE is a promoted arithmetic type. */
2729
2730static bool
2731promoted_arithmetic_type_p (tree type)
2732{
2733 /* [over.built]
2734
2735 In this section, the term promoted integral type is used to refer
2736 to those integral types which are preserved by integral promotion
2737 (including e.g. int and long but excluding e.g. char).
2738 Similarly, the term promoted arithmetic type refers to promoted
2739 integral types plus floating types. */
2740 return ((CP_INTEGRAL_TYPE_P (type)
2741 && same_type_p (type_promotes_to (type), type))
2742 || SCALAR_FLOAT_TYPE_P (type));
2743}
2744
2745/* Create any builtin operator overload candidates for the operator in
2746 question given the converted operand types TYPE1 and TYPE2. The other
2747 args are passed through from add_builtin_candidates to
2748 build_builtin_candidate.
2749
2750 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2751 If CODE is requires candidates operands of the same type of the kind
2752 of which TYPE1 and TYPE2 are, we add both candidates
2753 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2754
2755static void
2756add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2757 enum tree_code code2, tree fnname, tree type1,
2758 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2759 int flags, tsubst_flags_t complain)
2760{
2761 switch (code)
2762 {
2763 case POSTINCREMENT_EXPR:
2764 case POSTDECREMENT_EXPR:
2765 args[1] = integer_zero_node;
2766 type2 = integer_type_node;
2767 break;
2768 default:
2769 break;
2770 }
2771
2772 switch (code)
2773 {
2774
2775/* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2776 and VQ is either volatile or empty, there exist candidate operator
2777 functions of the form
2778 VQ T& operator++(VQ T&);
2779 T operator++(VQ T&, int);
2780 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2781 and VQ is either volatile or empty, there exist candidate operator
2782 functions of the form
2783 VQ T& operator--(VQ T&);
2784 T operator--(VQ T&, int);
2785 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2786 type, and VQ is either volatile or empty, there exist candidate operator
2787 functions of the form
2788 T*VQ& operator++(T*VQ&);
2789 T*VQ& operator--(T*VQ&);
2790 T* operator++(T*VQ&, int);
2791 T* operator--(T*VQ&, int); */
2792
2793 case POSTDECREMENT_EXPR:
2794 case PREDECREMENT_EXPR:
2795 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2796 return;
2797 /* FALLTHRU */
2798 case POSTINCREMENT_EXPR:
2799 case PREINCREMENT_EXPR:
2800 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2801 to p4. */
2802 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2803 return;
2804 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2805 {
2806 type1 = build_reference_type (type1);
2807 break;
2808 }
2809 return;
2810
2811/* 7 For every cv-qualified or cv-unqualified object type T, there
2812 exist candidate operator functions of the form
2813
2814 T& operator*(T*);
2815
2816
2817 8 For every function type T that does not have cv-qualifiers or
2818 a ref-qualifier, there exist candidate operator functions of the form
2819 T& operator*(T*); */
2820
2821 case INDIRECT_REF:
2822 if (TYPE_PTR_P (type1)
2823 && (TYPE_PTROB_P (type1)
2824 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2825 break;
2826 return;
2827
2828/* 9 For every type T, there exist candidate operator functions of the form
2829 T* operator+(T*);
2830
2831 10 For every floating-point or promoted integral type T, there exist
2832 candidate operator functions of the form
2833 T operator+(T);
2834 T operator-(T); */
2835
2836 case UNARY_PLUS_EXPR: /* unary + */
2837 if (TYPE_PTR_P (type1))
2838 break;
2839 /* FALLTHRU */
2840 case NEGATE_EXPR:
2841 if (ARITHMETIC_TYPE_P (type1))
2842 break;
2843 return;
2844
2845/* 11 For every promoted integral type T, there exist candidate operator
2846 functions of the form
2847 T operator~(T); */
2848
2849 case BIT_NOT_EXPR:
2850 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2851 break;
2852 return;
2853
2854/* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2855 is the same type as C2 or is a derived class of C2, and T is an object
2856 type or a function type there exist candidate operator functions of the
2857 form
2858 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2859 where CV12 is the union of CV1 and CV2. */
2860
2861 case MEMBER_REF:
2862 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2863 {
2864 tree c1 = TREE_TYPE (type1);
2865 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2866
2867 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2868 && (TYPE_PTRMEMFUNC_P (type2)
2869 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2870 break;
2871 }
2872 return;
2873
2874/* 13 For every pair of types L and R, where each of L and R is a floating-point
2875 or promoted integral type, there exist candidate operator functions of the
2876 form
2877 LR operator*(L, R);
2878 LR operator/(L, R);
2879 LR operator+(L, R);
2880 LR operator-(L, R);
2881 bool operator<(L, R);
2882 bool operator>(L, R);
2883 bool operator<=(L, R);
2884 bool operator>=(L, R);
2885 bool operator==(L, R);
2886 bool operator!=(L, R);
2887 where LR is the result of the usual arithmetic conversions between
2888 types L and R.
2889
2890 14 For every integral type T there exists a candidate operator function of
2891 the form
2892
2893 std::strong_ordering operator<=>(T, T);
2894
2895 15 For every pair of floating-point types L and R, there exists a candidate
2896 operator function of the form
2897
2898 std::partial_ordering operator<=>(L, R);
2899
2900 16 For every cv-qualified or cv-unqualified object type T there exist
2901 candidate operator functions of the form
2902 T* operator+(T*, std::ptrdiff_t);
2903 T& operator[](T*, std::ptrdiff_t);
2904 T* operator-(T*, std::ptrdiff_t);
2905 T* operator+(std::ptrdiff_t, T*);
2906 T& operator[](std::ptrdiff_t, T*);
2907
2908 17 For every T, where T is a pointer to object type, there exist candidate
2909 operator functions of the form
2910 std::ptrdiff_t operator-(T, T);
2911
2912 18 For every T, where T is an enumeration type or a pointer type, there
2913 exist candidate operator functions of the form
2914 bool operator<(T, T);
2915 bool operator>(T, T);
2916 bool operator<=(T, T);
2917 bool operator>=(T, T);
2918 bool operator==(T, T);
2919 bool operator!=(T, T);
2920 R operator<=>(T, T);
2921
2922 where R is the result type specified in [expr.spaceship].
2923
2924 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2925 there exist candidate operator functions of the form
2926 bool operator==(T, T);
2927 bool operator!=(T, T); */
2928
2929 case MINUS_EXPR:
2930 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2931 break;
2932 if (TYPE_PTROB_P (type1)
2933 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2934 {
2935 type2 = ptrdiff_type_node;
2936 break;
2937 }
2938 /* FALLTHRU */
2939 case MULT_EXPR:
2940 case TRUNC_DIV_EXPR:
2941 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2942 break;
2943 return;
2944
2945 /* This isn't exactly what's specified above for operator<=>, but it's
2946 close enough. In particular, we don't care about the return type
2947 specified above; it doesn't participate in overload resolution and it
2948 doesn't affect the semantics of the built-in operator. */
2949 case SPACESHIP_EXPR:
2950 case EQ_EXPR:
2951 case NE_EXPR:
2952 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2953 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2954 break;
2955 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2956 break;
2957 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (t: args[1]))
2958 {
2959 type2 = type1;
2960 break;
2961 }
2962 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (t: args[0]))
2963 {
2964 type1 = type2;
2965 break;
2966 }
2967 /* Fall through. */
2968 case LT_EXPR:
2969 case GT_EXPR:
2970 case LE_EXPR:
2971 case GE_EXPR:
2972 case MAX_EXPR:
2973 case MIN_EXPR:
2974 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2975 break;
2976 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2977 break;
2978 if (TREE_CODE (type1) == ENUMERAL_TYPE
2979 && TREE_CODE (type2) == ENUMERAL_TYPE)
2980 break;
2981 if (TYPE_PTR_P (type1)
2982 && null_ptr_cst_p (t: args[1]))
2983 {
2984 type2 = type1;
2985 break;
2986 }
2987 if (null_ptr_cst_p (t: args[0])
2988 && TYPE_PTR_P (type2))
2989 {
2990 type1 = type2;
2991 break;
2992 }
2993 return;
2994
2995 case PLUS_EXPR:
2996 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2997 break;
2998 /* FALLTHRU */
2999 case ARRAY_REF:
3000 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3001 {
3002 type1 = ptrdiff_type_node;
3003 break;
3004 }
3005 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3006 {
3007 type2 = ptrdiff_type_node;
3008 break;
3009 }
3010 return;
3011
3012/* 18For every pair of promoted integral types L and R, there exist candi-
3013 date operator functions of the form
3014 LR operator%(L, R);
3015 LR operator&(L, R);
3016 LR operator^(L, R);
3017 LR operator|(L, R);
3018 L operator<<(L, R);
3019 L operator>>(L, R);
3020 where LR is the result of the usual arithmetic conversions between
3021 types L and R. */
3022
3023 case TRUNC_MOD_EXPR:
3024 case BIT_AND_EXPR:
3025 case BIT_IOR_EXPR:
3026 case BIT_XOR_EXPR:
3027 case LSHIFT_EXPR:
3028 case RSHIFT_EXPR:
3029 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3030 break;
3031 return;
3032
3033/* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3034 type, VQ is either volatile or empty, and R is a promoted arithmetic
3035 type, there exist candidate operator functions of the form
3036 VQ L& operator=(VQ L&, R);
3037 VQ L& operator*=(VQ L&, R);
3038 VQ L& operator/=(VQ L&, R);
3039 VQ L& operator+=(VQ L&, R);
3040 VQ L& operator-=(VQ L&, R);
3041
3042 20For every pair T, VQ), where T is any type and VQ is either volatile
3043 or empty, there exist candidate operator functions of the form
3044 T*VQ& operator=(T*VQ&, T*);
3045
3046 21For every pair T, VQ), where T is a pointer to member type and VQ is
3047 either volatile or empty, there exist candidate operator functions of
3048 the form
3049 VQ T& operator=(VQ T&, T);
3050
3051 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3052 unqualified complete object type, VQ is either volatile or empty, and
3053 I is a promoted integral type, there exist candidate operator func-
3054 tions of the form
3055 T*VQ& operator+=(T*VQ&, I);
3056 T*VQ& operator-=(T*VQ&, I);
3057
3058 23For every triple L, VQ, R), where L is an integral or enumeration
3059 type, VQ is either volatile or empty, and R is a promoted integral
3060 type, there exist candidate operator functions of the form
3061
3062 VQ L& operator%=(VQ L&, R);
3063 VQ L& operator<<=(VQ L&, R);
3064 VQ L& operator>>=(VQ L&, R);
3065 VQ L& operator&=(VQ L&, R);
3066 VQ L& operator^=(VQ L&, R);
3067 VQ L& operator|=(VQ L&, R); */
3068
3069 case MODIFY_EXPR:
3070 switch (code2)
3071 {
3072 case PLUS_EXPR:
3073 case MINUS_EXPR:
3074 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3075 {
3076 type2 = ptrdiff_type_node;
3077 break;
3078 }
3079 /* FALLTHRU */
3080 case MULT_EXPR:
3081 case TRUNC_DIV_EXPR:
3082 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3083 break;
3084 return;
3085
3086 case TRUNC_MOD_EXPR:
3087 case BIT_AND_EXPR:
3088 case BIT_IOR_EXPR:
3089 case BIT_XOR_EXPR:
3090 case LSHIFT_EXPR:
3091 case RSHIFT_EXPR:
3092 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3093 break;
3094 return;
3095
3096 case NOP_EXPR:
3097 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3098 break;
3099 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3100 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3101 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3102 || ((TYPE_PTRMEMFUNC_P (type1)
3103 || TYPE_PTR_P (type1))
3104 && null_ptr_cst_p (t: args[1])))
3105 {
3106 type2 = type1;
3107 break;
3108 }
3109 return;
3110
3111 default:
3112 gcc_unreachable ();
3113 }
3114 type1 = build_reference_type (type1);
3115 break;
3116
3117 case COND_EXPR:
3118 /* [over.built]
3119
3120 For every pair of promoted arithmetic types L and R, there
3121 exist candidate operator functions of the form
3122
3123 LR operator?(bool, L, R);
3124
3125 where LR is the result of the usual arithmetic conversions
3126 between types L and R.
3127
3128 For every type T, where T is a pointer or pointer-to-member
3129 type, there exist candidate operator functions of the form T
3130 operator?(bool, T, T); */
3131
3132 if (promoted_arithmetic_type_p (type: type1)
3133 && promoted_arithmetic_type_p (type: type2))
3134 /* That's OK. */
3135 break;
3136
3137 /* Otherwise, the types should be pointers. */
3138 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3139 return;
3140
3141 /* We don't check that the two types are the same; the logic
3142 below will actually create two candidates; one in which both
3143 parameter types are TYPE1, and one in which both parameter
3144 types are TYPE2. */
3145 break;
3146
3147 case REALPART_EXPR:
3148 case IMAGPART_EXPR:
3149 if (ARITHMETIC_TYPE_P (type1))
3150 break;
3151 return;
3152
3153 default:
3154 gcc_unreachable ();
3155 }
3156
3157 /* Make sure we don't create builtin candidates with dependent types. */
3158 bool u1 = uses_template_parms (type1);
3159 bool u2 = type2 ? uses_template_parms (type2) : false;
3160 if (u1 || u2)
3161 {
3162 /* Try to recover if one of the types is non-dependent. But if
3163 there's only one type, there's nothing we can do. */
3164 if (!type2)
3165 return;
3166 /* And we lose if both are dependent. */
3167 if (u1 && u2)
3168 return;
3169 /* Or if they have different forms. */
3170 if (TREE_CODE (type1) != TREE_CODE (type2))
3171 return;
3172
3173 if (u1 && !u2)
3174 type1 = type2;
3175 else if (u2 && !u1)
3176 type2 = type1;
3177 }
3178
3179 /* If we're dealing with two pointer types or two enumeral types,
3180 we need candidates for both of them. */
3181 if (type2 && !same_type_p (type1, type2)
3182 && TREE_CODE (type1) == TREE_CODE (type2)
3183 && (TYPE_REF_P (type1)
3184 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3185 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3186 || TYPE_PTRMEMFUNC_P (type1)
3187 || MAYBE_CLASS_TYPE_P (type1)
3188 || TREE_CODE (type1) == ENUMERAL_TYPE))
3189 {
3190 if (TYPE_PTR_OR_PTRMEM_P (type1))
3191 {
3192 tree cptype = composite_pointer_type (input_location,
3193 type1, type2,
3194 error_mark_node,
3195 error_mark_node,
3196 CPO_CONVERSION,
3197 tf_none);
3198 if (cptype != error_mark_node)
3199 {
3200 build_builtin_candidate
3201 (candidates, fnname, type1: cptype, type2: cptype, args, argtypes,
3202 flags, complain);
3203 return;
3204 }
3205 }
3206
3207 build_builtin_candidate
3208 (candidates, fnname, type1, type2: type1, args, argtypes, flags, complain);
3209 build_builtin_candidate
3210 (candidates, fnname, type1: type2, type2, args, argtypes, flags, complain);
3211 return;
3212 }
3213
3214 build_builtin_candidate
3215 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3216}
3217
3218tree
3219type_decays_to (tree type)
3220{
3221 if (TREE_CODE (type) == ARRAY_TYPE)
3222 return build_pointer_type (TREE_TYPE (type));
3223 if (TREE_CODE (type) == FUNCTION_TYPE)
3224 return build_pointer_type (type);
3225 return type;
3226}
3227
3228/* There are three conditions of builtin candidates:
3229
3230 1) bool-taking candidates. These are the same regardless of the input.
3231 2) pointer-pair taking candidates. These are generated for each type
3232 one of the input types converts to.
3233 3) arithmetic candidates. According to the standard, we should generate
3234 all of these, but I'm trying not to...
3235
3236 Here we generate a superset of the possible candidates for this particular
3237 case. That is a subset of the full set the standard defines, plus some
3238 other cases which the standard disallows. add_builtin_candidate will
3239 filter out the invalid set. */
3240
3241static void
3242add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3243 enum tree_code code2, tree fnname,
3244 vec<tree, va_gc> *argv,
3245 int flags, tsubst_flags_t complain)
3246{
3247 int ref1;
3248 int enum_p = 0;
3249 tree type, argtypes[3], t;
3250 /* TYPES[i] is the set of possible builtin-operator parameter types
3251 we will consider for the Ith argument. */
3252 vec<tree, va_gc> *types[2];
3253 unsigned ix;
3254 vec<tree, va_gc> &args = *argv;
3255 unsigned len = args.length ();
3256
3257 for (unsigned i = 0; i < len; ++i)
3258 {
3259 if (args[i])
3260 argtypes[i] = unlowered_expr_type (args[i]);
3261 else
3262 argtypes[i] = NULL_TREE;
3263 }
3264
3265 switch (code)
3266 {
3267/* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3268 and VQ is either volatile or empty, there exist candidate operator
3269 functions of the form
3270 VQ T& operator++(VQ T&); */
3271
3272 case POSTINCREMENT_EXPR:
3273 case PREINCREMENT_EXPR:
3274 case POSTDECREMENT_EXPR:
3275 case PREDECREMENT_EXPR:
3276 case MODIFY_EXPR:
3277 ref1 = 1;
3278 break;
3279
3280/* 24There also exist candidate operator functions of the form
3281 bool operator!(bool);
3282 bool operator&&(bool, bool);
3283 bool operator||(bool, bool); */
3284
3285 case TRUTH_NOT_EXPR:
3286 build_builtin_candidate
3287 (candidates, fnname, boolean_type_node,
3288 NULL_TREE, args, argtypes, flags, complain);
3289 return;
3290
3291 case TRUTH_ORIF_EXPR:
3292 case TRUTH_ANDIF_EXPR:
3293 build_builtin_candidate
3294 (candidates, fnname, boolean_type_node,
3295 boolean_type_node, args, argtypes, flags, complain);
3296 return;
3297
3298 case ADDR_EXPR:
3299 case COMPOUND_EXPR:
3300 case COMPONENT_REF:
3301 case CO_AWAIT_EXPR:
3302 return;
3303
3304 case COND_EXPR:
3305 case EQ_EXPR:
3306 case NE_EXPR:
3307 case LT_EXPR:
3308 case LE_EXPR:
3309 case GT_EXPR:
3310 case GE_EXPR:
3311 case SPACESHIP_EXPR:
3312 enum_p = 1;
3313 /* Fall through. */
3314
3315 default:
3316 ref1 = 0;
3317 }
3318
3319 types[0] = make_tree_vector ();
3320 types[1] = make_tree_vector ();
3321
3322 if (len == 3)
3323 len = 2;
3324 for (unsigned i = 0; i < len; ++i)
3325 {
3326 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3327 {
3328 tree convs;
3329
3330 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3331 return;
3332
3333 convs = lookup_conversions (argtypes[i]);
3334
3335 if (code == COND_EXPR)
3336 {
3337 if (lvalue_p (args[i]))
3338 vec_safe_push (v&: types[i], obj: build_reference_type (argtypes[i]));
3339
3340 vec_safe_push (v&: types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3341 }
3342
3343 else if (! convs)
3344 return;
3345
3346 for (; convs; convs = TREE_CHAIN (convs))
3347 {
3348 type = TREE_TYPE (convs);
3349
3350 if (i == 0 && ref1
3351 && (!TYPE_REF_P (type)
3352 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3353 continue;
3354
3355 if (code == COND_EXPR && TYPE_REF_P (type))
3356 vec_safe_push (v&: types[i], obj: type);
3357
3358 type = non_reference (type);
3359 if (i != 0 || ! ref1)
3360 {
3361 type = cv_unqualified (type_decays_to (type));
3362 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3363 vec_safe_push (v&: types[i], obj: type);
3364 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3365 type = type_promotes_to (type);
3366 }
3367
3368 if (! vec_member (type, types[i]))
3369 vec_safe_push (v&: types[i], obj: type);
3370 }
3371 }
3372 else
3373 {
3374 if (code == COND_EXPR && lvalue_p (args[i]))
3375 vec_safe_push (v&: types[i], obj: build_reference_type (argtypes[i]));
3376 type = non_reference (argtypes[i]);
3377 if (i != 0 || ! ref1)
3378 {
3379 type = cv_unqualified (type_decays_to (type));
3380 if (enum_p && UNSCOPED_ENUM_P (type))
3381 vec_safe_push (v&: types[i], obj: type);
3382 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3383 type = type_promotes_to (type);
3384 }
3385 vec_safe_push (v&: types[i], obj: type);
3386 }
3387 }
3388
3389 /* Run through the possible parameter types of both arguments,
3390 creating candidates with those parameter types. */
3391 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3392 {
3393 unsigned jx;
3394 tree u;
3395
3396 if (!types[1]->is_empty ())
3397 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3398 add_builtin_candidate
3399 (candidates, code, code2, fnname, type1: t,
3400 type2: u, args, argtypes, flags, complain);
3401 else
3402 add_builtin_candidate
3403 (candidates, code, code2, fnname, type1: t,
3404 NULL_TREE, args, argtypes, flags, complain);
3405 }
3406
3407 release_tree_vector (types[0]);
3408 release_tree_vector (types[1]);
3409}
3410
3411
3412/* If TMPL can be successfully instantiated as indicated by
3413 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3414
3415 TMPL is the template. EXPLICIT_TARGS are any explicit template
3416 arguments. ARGLIST is the arguments provided at the call-site.
3417 This does not change ARGLIST. The RETURN_TYPE is the desired type
3418 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3419 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3420 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3421
3422 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3423
3424static struct z_candidate*
3425add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3426 tree ctype, tree explicit_targs, tree first_arg,
3427 const vec<tree, va_gc> *arglist, tree return_type,
3428 tree access_path, tree conversion_path,
3429 int flags, tree obj, unification_kind_t strict,
3430 bool shortcut_bad_convs, tsubst_flags_t complain)
3431{
3432 int ntparms = DECL_NTPARMS (tmpl);
3433 tree targs = make_tree_vec (ntparms);
3434 unsigned int len = vec_safe_length (v: arglist);
3435 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3436 unsigned int skip_without_in_chrg = 0;
3437 tree first_arg_without_in_chrg = first_arg;
3438 tree *args_without_in_chrg;
3439 unsigned int nargs_without_in_chrg;
3440 unsigned int ia, ix;
3441 tree arg;
3442 struct z_candidate *cand;
3443 tree fn;
3444 struct rejection_reason *reason = NULL;
3445 int errs;
3446 conversion **convs = NULL;
3447
3448 /* We don't do deduction on the in-charge parameter, the VTT
3449 parameter or 'this'. */
3450 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3451 {
3452 if (first_arg_without_in_chrg != NULL_TREE)
3453 first_arg_without_in_chrg = NULL_TREE;
3454 else if (return_type && strict == DEDUCE_CALL)
3455 /* We're deducing for a call to the result of a template conversion
3456 function, so the args don't contain 'this'; leave them alone. */;
3457 else
3458 ++skip_without_in_chrg;
3459 }
3460
3461 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3462 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3463 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3464 {
3465 if (first_arg_without_in_chrg != NULL_TREE)
3466 first_arg_without_in_chrg = NULL_TREE;
3467 else
3468 ++skip_without_in_chrg;
3469 }
3470
3471 if (len < skip_without_in_chrg)
3472 return NULL;
3473
3474 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3475 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3476 TREE_TYPE ((*arglist)[0])))
3477 {
3478 /* 12.8/6 says, "A declaration of a constructor for a class X is
3479 ill-formed if its first parameter is of type (optionally cv-qualified)
3480 X and either there are no other parameters or else all other
3481 parameters have default arguments. A member function template is never
3482 instantiated to produce such a constructor signature."
3483
3484 So if we're trying to copy an object of the containing class, don't
3485 consider a template constructor that has a first parameter type that
3486 is just a template parameter, as we would deduce a signature that we
3487 would then reject in the code below. */
3488 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3489 {
3490 firstparm = TREE_VALUE (firstparm);
3491 if (PACK_EXPANSION_P (firstparm))
3492 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3493 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3494 {
3495 gcc_assert (!explicit_targs);
3496 reason = invalid_copy_with_fn_template_rejection ();
3497 goto fail;
3498 }
3499 }
3500 }
3501
3502 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3503 + (len - skip_without_in_chrg));
3504 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3505 ia = 0;
3506 if (first_arg_without_in_chrg != NULL_TREE)
3507 {
3508 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3509 ++ia;
3510 }
3511 for (ix = skip_without_in_chrg;
3512 vec_safe_iterate (v: arglist, ix, ptr: &arg);
3513 ++ix)
3514 {
3515 args_without_in_chrg[ia] = arg;
3516 ++ia;
3517 }
3518 gcc_assert (ia == nargs_without_in_chrg);
3519
3520 if (!obj)
3521 {
3522 /* Check that there's no obvious arity mismatch before proceeding with
3523 deduction. This avoids substituting explicit template arguments
3524 into the template or e.g. derived-to-base parm/arg unification
3525 (which could result in an error outside the immediate context) when
3526 the resulting candidate would be unviable anyway. */
3527 int min_arity = 0, max_arity = 0;
3528 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3529 parms = skip_artificial_parms_for (tmpl, parms);
3530 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3531 {
3532 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3533 {
3534 max_arity = -1;
3535 break;
3536 }
3537 if (TREE_PURPOSE (parms))
3538 /* A parameter with a default argument. */
3539 ++max_arity;
3540 else
3541 ++min_arity, ++max_arity;
3542 }
3543 if (ia < (unsigned)min_arity)
3544 {
3545 /* Too few arguments. */
3546 reason = arity_rejection (NULL_TREE, expected: min_arity, actual: ia,
3547 /*least_p=*/(max_arity == -1));
3548 goto fail;
3549 }
3550 else if (max_arity != -1 && ia > (unsigned)max_arity)
3551 {
3552 /* Too many arguments. */
3553 reason = arity_rejection (NULL_TREE, expected: max_arity, actual: ia);
3554 goto fail;
3555 }
3556
3557 convs = alloc_conversions (n: nargs);
3558
3559 if (shortcut_bad_convs
3560 && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3561 && !DECL_CONSTRUCTOR_P (tmpl))
3562 {
3563 /* Check the 'this' conversion before proceeding with deduction.
3564 This is effectively an extension of the DR 1391 resolution
3565 that we perform in check_non_deducible_conversions, though it's
3566 convenient to do this extra check here instead of there. */
3567 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3568 tree argtype = lvalue_type (first_arg);
3569 tree arg = first_arg;
3570 conversion *t = build_this_conversion (fn: tmpl, ctype,
3571 parmtype, argtype, arg,
3572 flags, complain);
3573 convs[0] = t;
3574 if (t->bad_p)
3575 {
3576 reason = bad_arg_conversion_rejection (first_arg, n_arg: 0,
3577 from: arg, to: parmtype,
3578 EXPR_LOCATION (arg));
3579 goto fail;
3580 }
3581 }
3582 }
3583
3584 errs = errorcount+sorrycount;
3585 fn = fn_type_unification (tmpl, explicit_targs, targs,
3586 args_without_in_chrg,
3587 nargs_without_in_chrg,
3588 return_type, strict, flags, convs,
3589 false, complain & tf_decltype);
3590
3591 if (fn == error_mark_node)
3592 {
3593 /* Don't repeat unification later if it already resulted in errors. */
3594 if (errorcount+sorrycount == errs)
3595 reason = template_unification_rejection (tmpl, explicit_targs,
3596 targs, args: args_without_in_chrg,
3597 nargs: nargs_without_in_chrg,
3598 return_type, strict, flags);
3599 else
3600 reason = template_unification_error_rejection ();
3601 goto fail;
3602 }
3603
3604 /* Now the explicit specifier might have been deduced; check if this
3605 declaration is explicit. If it is and we're ignoring non-converting
3606 constructors, don't add this function to the set of candidates. */
3607 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3608 == LOOKUP_ONLYCONVERTING)
3609 && DECL_NONCONVERTING_P (fn))
3610 return NULL;
3611
3612 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3613 {
3614 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3615 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3616 ctype))
3617 {
3618 /* We're trying to produce a constructor with a prohibited signature,
3619 as discussed above; handle here any cases we didn't catch then,
3620 such as X(X<T>). */
3621 reason = invalid_copy_with_fn_template_rejection ();
3622 goto fail;
3623 }
3624 }
3625
3626 if (obj != NULL_TREE)
3627 /* Aha, this is a conversion function. */
3628 cand = add_conv_candidate (candidates, fn, obj, arglist,
3629 access_path, conversion_path, complain);
3630 else
3631 cand = add_function_candidate (candidates, fn, ctype,
3632 first_arg, args: arglist, access_path,
3633 conversion_path, flags, convs,
3634 shortcut_bad_convs, complain);
3635 if (DECL_TI_TEMPLATE (fn) != tmpl)
3636 /* This situation can occur if a member template of a template
3637 class is specialized. Then, instantiate_template might return
3638 an instantiation of the specialization, in which case the
3639 DECL_TI_TEMPLATE field will point at the original
3640 specialization. For example:
3641
3642 template <class T> struct S { template <class U> void f(U);
3643 template <> void f(int) {}; };
3644 S<double> sd;
3645 sd.f(3);
3646
3647 Here, TMPL will be template <class U> S<double>::f(U).
3648 And, instantiate template will give us the specialization
3649 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3650 for this will point at template <class T> template <> S<T>::f(int),
3651 so that we can find the definition. For the purposes of
3652 overload resolution, however, we want the original TMPL. */
3653 cand->template_decl = build_template_info (tmpl, targs);
3654 else
3655 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3656 cand->explicit_targs = explicit_targs;
3657
3658 return cand;
3659 fail:
3660 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3661 return add_candidate (candidates, fn: tmpl, first_arg, args: arglist, num_convs: nargs, convs,
3662 access_path, conversion_path, viable, reason, flags);
3663}
3664
3665
3666static struct z_candidate *
3667add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3668 tree explicit_targs, tree first_arg,
3669 const vec<tree, va_gc> *arglist, tree return_type,
3670 tree access_path, tree conversion_path, int flags,
3671 unification_kind_t strict, bool shortcut_bad_convs,
3672 tsubst_flags_t complain)
3673{
3674 return
3675 add_template_candidate_real (candidates, tmpl, ctype,
3676 explicit_targs, first_arg, arglist,
3677 return_type, access_path, conversion_path,
3678 flags, NULL_TREE, strict, shortcut_bad_convs,
3679 complain);
3680}
3681
3682/* Create an overload candidate for the conversion function template TMPL,
3683 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3684 pointer-to-function which will in turn be called with the argument list
3685 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3686 passed on to implicit_conversion. */
3687
3688static struct z_candidate *
3689add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3690 tree obj,
3691 const vec<tree, va_gc> *arglist,
3692 tree return_type, tree access_path,
3693 tree conversion_path, tsubst_flags_t complain)
3694{
3695 return
3696 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3697 NULL_TREE, arglist, return_type, access_path,
3698 conversion_path, flags: 0, obj, strict: DEDUCE_CALL,
3699 /*shortcut_bad_convs=*/false, complain);
3700}
3701
3702/* The CANDS are the set of candidates that were considered for
3703 overload resolution. Return the set of viable candidates, or CANDS
3704 if none are viable. If any of the candidates were viable, set
3705 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3706 considered viable only if it is strictly viable. */
3707
3708static struct z_candidate*
3709splice_viable (struct z_candidate *cands,
3710 bool strict_p,
3711 bool *any_viable_p)
3712{
3713 struct z_candidate *viable;
3714 struct z_candidate **last_viable;
3715 struct z_candidate **cand;
3716 bool found_strictly_viable = false;
3717
3718 /* Be strict inside templates, since build_over_call won't actually
3719 do the conversions to get pedwarns. */
3720 if (processing_template_decl)
3721 strict_p = true;
3722
3723 viable = NULL;
3724 last_viable = &viable;
3725 *any_viable_p = false;
3726
3727 cand = &cands;
3728 while (*cand)
3729 {
3730 struct z_candidate *c = *cand;
3731 if (!strict_p
3732 && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3733 {
3734 /* Be strict in the presence of a viable candidate. Also if
3735 there are template candidates, so that we get deduction errors
3736 for them instead of silently preferring a bad conversion. */
3737 strict_p = true;
3738 if (viable && !found_strictly_viable)
3739 {
3740 /* Put any spliced near matches back onto the main list so
3741 that we see them if there is no strict match. */
3742 *any_viable_p = false;
3743 *last_viable = cands;
3744 cands = viable;
3745 viable = NULL;
3746 last_viable = &viable;
3747 }
3748 }
3749
3750 if (strict_p ? c->viable == 1 : c->viable)
3751 {
3752 *last_viable = c;
3753 *cand = c->next;
3754 c->next = NULL;
3755 last_viable = &c->next;
3756 *any_viable_p = true;
3757 if (c->viable == 1)
3758 found_strictly_viable = true;
3759 }
3760 else
3761 cand = &c->next;
3762 }
3763
3764 return viable ? viable : cands;
3765}
3766
3767static bool
3768any_strictly_viable (struct z_candidate *cands)
3769{
3770 for (; cands; cands = cands->next)
3771 if (cands->viable == 1)
3772 return true;
3773 return false;
3774}
3775
3776/* OBJ is being used in an expression like "OBJ.f (...)". In other
3777 words, it is about to become the "this" pointer for a member
3778 function call. Take the address of the object. */
3779
3780static tree
3781build_this (tree obj)
3782{
3783 /* In a template, we are only concerned about the type of the
3784 expression, so we can take a shortcut. */
3785 if (processing_template_decl)
3786 return build_address (obj);
3787
3788 return cp_build_addr_expr (obj, tf_warning_or_error);
3789}
3790
3791/* Returns true iff functions are equivalent. Equivalent functions are
3792 not '==' only if one is a function-local extern function or if
3793 both are extern "C". */
3794
3795static inline int
3796equal_functions (tree fn1, tree fn2)
3797{
3798 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3799 return 0;
3800 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3801 return fn1 == fn2;
3802 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3803 || DECL_EXTERN_C_FUNCTION_P (fn1))
3804 return decls_match (fn1, fn2);
3805 return fn1 == fn2;
3806}
3807
3808/* Print information about a candidate FN being rejected due to INFO. */
3809
3810static void
3811print_conversion_rejection (location_t loc, struct conversion_info *info,
3812 tree fn)
3813{
3814 tree from = info->from;
3815 if (!TYPE_P (from))
3816 from = lvalue_type (from);
3817 if (info->n_arg == -1)
3818 {
3819 /* Conversion of implicit `this' argument failed. */
3820 if (!TYPE_P (info->from))
3821 /* A bad conversion for 'this' must be discarding cv-quals. */
3822 inform (loc, " passing %qT as %<this%> "
3823 "argument discards qualifiers",
3824 from);
3825 else
3826 inform (loc, " no known conversion for implicit "
3827 "%<this%> parameter from %qH to %qI",
3828 from, info->to_type);
3829 }
3830 else if (!TYPE_P (info->from))
3831 {
3832 if (info->n_arg >= 0)
3833 inform (loc, " conversion of argument %d would be ill-formed:",
3834 info->n_arg + 1);
3835 iloc_sentinel ils = loc;
3836 perform_implicit_conversion (info->to_type, info->from,
3837 tf_warning_or_error);
3838 }
3839 else if (info->n_arg == -2)
3840 /* Conversion of conversion function return value failed. */
3841 inform (loc, " no known conversion from %qH to %qI",
3842 from, info->to_type);
3843 else
3844 {
3845 if (TREE_CODE (fn) == FUNCTION_DECL)
3846 loc = get_fndecl_argument_location (fn, info->n_arg);
3847 inform (loc, " no known conversion for argument %d from %qH to %qI",
3848 info->n_arg + 1, from, info->to_type);
3849 }
3850}
3851
3852/* Print information about a candidate with WANT parameters and we found
3853 HAVE. */
3854
3855static void
3856print_arity_information (location_t loc, unsigned int have, unsigned int want,
3857 bool least_p)
3858{
3859 if (least_p)
3860 inform_n (loc, want,
3861 " candidate expects at least %d argument, %d provided",
3862 " candidate expects at least %d arguments, %d provided",
3863 want, have);
3864 else
3865 inform_n (loc, want,
3866 " candidate expects %d argument, %d provided",
3867 " candidate expects %d arguments, %d provided",
3868 want, have);
3869}
3870
3871/* Print information about one overload candidate CANDIDATE. MSGSTR
3872 is the text to print before the candidate itself.
3873
3874 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3875 to have been run through gettext by the caller. This wart makes
3876 life simpler in print_z_candidates and for the translators. */
3877
3878static void
3879print_z_candidate (location_t loc, const char *msgstr,
3880 struct z_candidate *candidate)
3881{
3882 const char *msg = (msgstr == NULL
3883 ? ""
3884 : ACONCAT ((_(msgstr), " ", NULL)));
3885 tree fn = candidate->fn;
3886 if (flag_new_inheriting_ctors)
3887 fn = strip_inheriting_ctors (fn);
3888 location_t cloc = location_of (fn);
3889
3890 if (identifier_p (t: fn))
3891 {
3892 cloc = loc;
3893 if (candidate->num_convs == 3)
3894 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3895 candidate->convs[0]->type,
3896 candidate->convs[1]->type,
3897 candidate->convs[2]->type);
3898 else if (candidate->num_convs == 2)
3899 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3900 candidate->convs[0]->type,
3901 candidate->convs[1]->type);
3902 else
3903 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3904 candidate->convs[0]->type);
3905 }
3906 else if (TYPE_P (fn))
3907 inform (cloc, "%s%qT (conversion)", msg, fn);
3908 else if (candidate->viable == -1)
3909 inform (cloc, "%s%#qD (near match)", msg, fn);
3910 else if (DECL_DELETED_FN (fn))
3911 inform (cloc, "%s%#qD (deleted)", msg, fn);
3912 else if (candidate->reversed ())
3913 inform (cloc, "%s%#qD (reversed)", msg, fn);
3914 else if (candidate->rewritten ())
3915 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3916 else
3917 inform (cloc, "%s%#qD", msg, fn);
3918 if (fn != candidate->fn)
3919 {
3920 cloc = location_of (candidate->fn);
3921 inform (cloc, " inherited here");
3922 }
3923 /* Give the user some information about why this candidate failed. */
3924 if (candidate->reason != NULL)
3925 {
3926 struct rejection_reason *r = candidate->reason;
3927
3928 switch (r->code)
3929 {
3930 case rr_arity:
3931 print_arity_information (loc: cloc, have: r->u.arity.actual,
3932 want: r->u.arity.expected,
3933 least_p: r->u.arity.least_p);
3934 break;
3935 case rr_arg_conversion:
3936 print_conversion_rejection (loc: cloc, info: &r->u.conversion, fn);
3937 break;
3938 case rr_bad_arg_conversion:
3939 print_conversion_rejection (loc: cloc, info: &r->u.bad_conversion, fn);
3940 break;
3941 case rr_explicit_conversion:
3942 inform (cloc, " return type %qT of explicit conversion function "
3943 "cannot be converted to %qT with a qualification "
3944 "conversion", r->u.conversion.from,
3945 r->u.conversion.to_type);
3946 break;
3947 case rr_template_conversion:
3948 inform (cloc, " conversion from return type %qT of template "
3949 "conversion function specialization to %qT is not an "
3950 "exact match", r->u.conversion.from,
3951 r->u.conversion.to_type);
3952 break;
3953 case rr_template_unification:
3954 /* We use template_unification_error_rejection if unification caused
3955 actual non-SFINAE errors, in which case we don't need to repeat
3956 them here. */
3957 if (r->u.template_unification.tmpl == NULL_TREE)
3958 {
3959 inform (cloc, " substitution of deduced template arguments "
3960 "resulted in errors seen above");
3961 break;
3962 }
3963 /* Re-run template unification with diagnostics. */
3964 inform (cloc, " template argument deduction/substitution failed:");
3965 fn_type_unification (r->u.template_unification.tmpl,
3966 r->u.template_unification.explicit_targs,
3967 (make_tree_vec
3968 (r->u.template_unification.num_targs)),
3969 r->u.template_unification.args,
3970 r->u.template_unification.nargs,
3971 r->u.template_unification.return_type,
3972 r->u.template_unification.strict,
3973 r->u.template_unification.flags,
3974 NULL, true, false);
3975 break;
3976 case rr_invalid_copy:
3977 inform (cloc,
3978 " a constructor taking a single argument of its own "
3979 "class type is invalid");
3980 break;
3981 case rr_constraint_failure:
3982 diagnose_constraints (cloc, fn, NULL_TREE);
3983 break;
3984 case rr_inherited_ctor:
3985 inform (cloc, " an inherited constructor is not a candidate for "
3986 "initialization from an expression of the same or derived "
3987 "type");
3988 break;
3989 case rr_none:
3990 default:
3991 /* This candidate didn't have any issues or we failed to
3992 handle a particular code. Either way... */
3993 gcc_unreachable ();
3994 }
3995 }
3996}
3997
3998static void
3999print_z_candidates (location_t loc, struct z_candidate *candidates)
4000{
4001 struct z_candidate *cand1;
4002 struct z_candidate **cand2;
4003
4004 if (!candidates)
4005 return;
4006
4007 /* Remove non-viable deleted candidates. */
4008 cand1 = candidates;
4009 for (cand2 = &cand1; *cand2; )
4010 {
4011 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4012 && !(*cand2)->viable
4013 && DECL_DELETED_FN ((*cand2)->fn))
4014 *cand2 = (*cand2)->next;
4015 else
4016 cand2 = &(*cand2)->next;
4017 }
4018 /* ...if there are any non-deleted ones. */
4019 if (cand1)
4020 candidates = cand1;
4021
4022 /* There may be duplicates in the set of candidates. We put off
4023 checking this condition as long as possible, since we have no way
4024 to eliminate duplicates from a set of functions in less than n^2
4025 time. Now we are about to emit an error message, so it is more
4026 permissible to go slowly. */
4027 for (cand1 = candidates; cand1; cand1 = cand1->next)
4028 {
4029 tree fn = cand1->fn;
4030 /* Skip builtin candidates and conversion functions. */
4031 if (!DECL_P (fn))
4032 continue;
4033 cand2 = &cand1->next;
4034 while (*cand2)
4035 {
4036 if (DECL_P ((*cand2)->fn)
4037 && equal_functions (fn1: fn, fn2: (*cand2)->fn))
4038 *cand2 = (*cand2)->next;
4039 else
4040 cand2 = &(*cand2)->next;
4041 }
4042 }
4043
4044 for (; candidates; candidates = candidates->next)
4045 print_z_candidate (loc, N_("candidate:"), candidate: candidates);
4046}
4047
4048/* USER_SEQ is a user-defined conversion sequence, beginning with a
4049 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4050 the result of the conversion function to convert it to the final
4051 desired type. Merge the two sequences into a single sequence,
4052 and return the merged sequence. */
4053
4054static conversion *
4055merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4056{
4057 conversion **t;
4058 bool bad = user_seq->bad_p;
4059
4060 gcc_assert (user_seq->kind == ck_user);
4061
4062 /* Find the end of the second conversion sequence. */
4063 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4064 {
4065 /* The entire sequence is a user-conversion sequence. */
4066 (*t)->user_conv_p = true;
4067 if (bad)
4068 (*t)->bad_p = true;
4069 }
4070
4071 if ((*t)->rvaluedness_matches_p)
4072 /* We're binding a reference directly to the result of the conversion.
4073 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4074 type, but we want it back. */
4075 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4076
4077 /* Replace the identity conversion with the user conversion
4078 sequence. */
4079 *t = user_seq;
4080
4081 return std_seq;
4082}
4083
4084/* Handle overload resolution for initializing an object of class type from
4085 an initializer list. First we look for a suitable constructor that
4086 takes a std::initializer_list; if we don't find one, we then look for a
4087 non-list constructor.
4088
4089 Parameters are as for add_candidates, except that the arguments are in
4090 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4091 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4092
4093static void
4094add_list_candidates (tree fns, tree first_arg,
4095 const vec<tree, va_gc> *args, tree totype,
4096 tree explicit_targs, bool template_only,
4097 tree conversion_path, tree access_path,
4098 int flags,
4099 struct z_candidate **candidates,
4100 tsubst_flags_t complain)
4101{
4102 gcc_assert (*candidates == NULL);
4103
4104 /* We're looking for a ctor for list-initialization. */
4105 flags |= LOOKUP_LIST_INIT_CTOR;
4106 /* And we don't allow narrowing conversions. We also use this flag to
4107 avoid the copy constructor call for copy-list-initialization. */
4108 flags |= LOOKUP_NO_NARROWING;
4109
4110 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4111 tree init_list = (*args)[nart];
4112
4113 /* Always use the default constructor if the list is empty (DR 990). */
4114 if (CONSTRUCTOR_NELTS (init_list) == 0
4115 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4116 ;
4117 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4118 && !CP_AGGREGATE_TYPE_P (totype))
4119 {
4120 if (complain & tf_error)
4121 error ("designated initializers cannot be used with a "
4122 "non-aggregate type %qT", totype);
4123 return;
4124 }
4125 /* If the class has a list ctor, try passing the list as a single
4126 argument first, but only consider list ctors. */
4127 else if (TYPE_HAS_LIST_CTOR (totype))
4128 {
4129 flags |= LOOKUP_LIST_ONLY;
4130 add_candidates (fns, first_arg, args, NULL_TREE,
4131 explicit_targs, template_only, conversion_path,
4132 access_path, flags, candidates, complain);
4133 if (any_strictly_viable (cands: *candidates))
4134 return;
4135 }
4136
4137 /* Expand the CONSTRUCTOR into a new argument vec. */
4138 vec<tree, va_gc> *new_args;
4139 vec_alloc (v&: new_args, nelems: nart + CONSTRUCTOR_NELTS (init_list));
4140 for (unsigned i = 0; i < nart; ++i)
4141 new_args->quick_push (obj: (*args)[i]);
4142 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4143 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4144
4145 /* We aren't looking for list-ctors anymore. */
4146 flags &= ~LOOKUP_LIST_ONLY;
4147 /* We allow more user-defined conversions within an init-list. */
4148 flags &= ~LOOKUP_NO_CONVERSION;
4149
4150 add_candidates (fns, first_arg, new_args, NULL_TREE,
4151 explicit_targs, template_only, conversion_path,
4152 access_path, flags, candidates, complain);
4153}
4154
4155/* Given C(std::initializer_list<A>), return A. */
4156
4157static tree
4158list_ctor_element_type (tree fn)
4159{
4160 gcc_checking_assert (is_list_ctor (fn));
4161
4162 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4163 parm = non_reference (TREE_VALUE (parm));
4164 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4165}
4166
4167/* If EXPR is a braced-init-list where the elements all decay to the same type,
4168 return that type. */
4169
4170static tree
4171braced_init_element_type (tree expr)
4172{
4173 if (TREE_CODE (expr) == CONSTRUCTOR
4174 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4175 return TREE_TYPE (TREE_TYPE (expr));
4176 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4177 return NULL_TREE;
4178
4179 tree elttype = NULL_TREE;
4180 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4181 {
4182 tree type = TREE_TYPE (e.value);
4183 type = type_decays_to (type);
4184 if (!elttype)
4185 elttype = type;
4186 else if (!same_type_p (type, elttype))
4187 return NULL_TREE;
4188 }
4189 return elttype;
4190}
4191
4192/* True iff EXPR contains any temporaries with non-trivial destruction.
4193
4194 ??? Also ignore classes with non-trivial but no-op destruction other than
4195 std::allocator? */
4196
4197static bool
4198has_non_trivial_temporaries (tree expr)
4199{
4200 auto_vec<tree*> temps;
4201 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4202 for (tree *p : temps)
4203 {
4204 tree t = TREE_TYPE (*p);
4205 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4206 && !is_std_allocator (t))
4207 return true;
4208 }
4209 return false;
4210}
4211
4212/* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4213 return INIT as an array (of its own type) so the caller can initialize the
4214 target array in a loop. */
4215
4216static tree
4217maybe_init_list_as_array (tree elttype, tree init)
4218{
4219 /* Only do this if the array can go in rodata but not once converted. */
4220 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4221 return NULL_TREE;
4222 tree init_elttype = braced_init_element_type (expr: init);
4223 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4224 return NULL_TREE;
4225
4226 /* Check with a stub expression to weed out special cases, and check whether
4227 we call the same function for direct-init as copy-list-init. */
4228 conversion_obstack_sentinel cos;
4229 tree arg = build_stub_object (init_elttype);
4230 conversion *c = implicit_conversion (to: elttype, from: init_elttype, expr: arg, c_cast_p: false,
4231 LOOKUP_NORMAL, complain: tf_none);
4232 if (c && c->kind == ck_rvalue)
4233 c = next_conversion (conv: c);
4234 if (!c || c->kind != ck_user)
4235 return NULL_TREE;
4236
4237 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4238 conversion *fc = implicit_conversion (to: elttype, from: init_elttype, expr: first, c_cast_p: false,
4239 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4240 complain: tf_none);
4241 if (fc && fc->kind == ck_rvalue)
4242 fc = next_conversion (conv: fc);
4243 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4244 return NULL_TREE;
4245 first = convert_like (fc, first, tf_none);
4246 if (first == error_mark_node)
4247 /* Let the normal code give the error. */
4248 return NULL_TREE;
4249
4250 /* Don't do this if the conversion would be constant. */
4251 first = maybe_constant_init (first);
4252 if (TREE_CONSTANT (first))
4253 return NULL_TREE;
4254
4255 /* We can't do this if the conversion creates temporaries that need
4256 to live until the whole array is initialized. */
4257 if (has_non_trivial_temporaries (expr: first))
4258 return NULL_TREE;
4259
4260 /* We can't do this if copying from the initializer_list would be
4261 ill-formed. */
4262 tree copy_argtypes = make_tree_vec (1);
4263 TREE_VEC_ELT (copy_argtypes, 0)
4264 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4265 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4266 return NULL_TREE;
4267
4268 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4269 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4270 arr = finish_compound_literal (arr, init, tf_none);
4271 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4272 return arr;
4273}
4274
4275/* If we were going to call e.g. vector(initializer_list<string>) starting
4276 with a list of string-literals (which is inefficient, see PR105838),
4277 instead build an array of const char* and pass it to the range constructor.
4278 But only do this for standard library types, where we can assume the
4279 transformation makes sense.
4280
4281 Really the container classes should have initializer_list<U> constructors to
4282 get the same effect more simply; this is working around that lack. */
4283
4284static tree
4285maybe_init_list_as_range (tree fn, tree expr)
4286{
4287 if (!processing_template_decl
4288 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4289 && is_list_ctor (fn)
4290 && decl_in_std_namespace_p (fn))
4291 {
4292 tree to = list_ctor_element_type (fn);
4293 if (tree init = maybe_init_list_as_array (elttype: to, init: expr))
4294 {
4295 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4296 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4297 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4298 nelts, tf_none);
4299 begin = cp_build_compound_expr (init, begin, tf_none);
4300 return build_constructor_va (init_list_type_node, 2,
4301 NULL_TREE, begin, NULL_TREE, end);
4302 }
4303 }
4304
4305 return NULL_TREE;
4306}
4307
4308/* Returns the best overload candidate to perform the requested
4309 conversion. This function is used for three the overloading situations
4310 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4311 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4312 per [dcl.init.ref], so we ignore temporary bindings. */
4313
4314static struct z_candidate *
4315build_user_type_conversion_1 (tree totype, tree expr, int flags,
4316 tsubst_flags_t complain)
4317{
4318 struct z_candidate *candidates, *cand;
4319 tree fromtype;
4320 tree ctors = NULL_TREE;
4321 tree conv_fns = NULL_TREE;
4322 conversion *conv = NULL;
4323 tree first_arg = NULL_TREE;
4324 vec<tree, va_gc> *args = NULL;
4325 bool any_viable_p;
4326 int convflags;
4327
4328 if (!expr)
4329 return NULL;
4330
4331 fromtype = TREE_TYPE (expr);
4332
4333 /* We represent conversion within a hierarchy using RVALUE_CONV and
4334 BASE_CONV, as specified by [over.best.ics]; these become plain
4335 constructor calls, as specified in [dcl.init]. */
4336 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4337 || !DERIVED_FROM_P (totype, fromtype));
4338
4339 if (CLASS_TYPE_P (totype))
4340 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4341 creating a garbage BASELINK; constructors can't be inherited. */
4342 ctors = get_class_binding (totype, complete_ctor_identifier);
4343
4344 tree to_nonref = non_reference (totype);
4345 if (MAYBE_CLASS_TYPE_P (fromtype))
4346 {
4347 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4348 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4349 && DERIVED_FROM_P (to_nonref, fromtype)))
4350 {
4351 /* [class.conv.fct] A conversion function is never used to
4352 convert a (possibly cv-qualified) object to the (possibly
4353 cv-qualified) same object type (or a reference to it), to a
4354 (possibly cv-qualified) base class of that type (or a
4355 reference to it)... */
4356 }
4357 else
4358 conv_fns = lookup_conversions (fromtype);
4359 }
4360
4361 candidates = 0;
4362 flags |= LOOKUP_NO_CONVERSION;
4363 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4364 flags |= LOOKUP_NO_NARROWING;
4365 /* Prevent add_candidates from treating a non-strictly viable candidate
4366 as unviable. */
4367 complain |= tf_conv;
4368
4369 /* It's OK to bind a temporary for converting constructor arguments, but
4370 not in converting the return value of a conversion operator. */
4371 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4372 | (flags & LOOKUP_NO_NARROWING));
4373 flags &= ~LOOKUP_NO_TEMP_BIND;
4374
4375 if (ctors)
4376 {
4377 int ctorflags = flags;
4378
4379 first_arg = build_dummy_object (totype);
4380
4381 /* We should never try to call the abstract or base constructor
4382 from here. */
4383 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4384 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4385
4386 args = make_tree_vector_single (expr);
4387 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4388 {
4389 /* List-initialization. */
4390 add_list_candidates (fns: ctors, first_arg, args, totype, NULL_TREE,
4391 template_only: false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4392 flags: ctorflags, candidates: &candidates, complain);
4393 }
4394 else
4395 {
4396 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4397 TYPE_BINFO (totype), TYPE_BINFO (totype),
4398 ctorflags, &candidates, complain);
4399 }
4400
4401 for (cand = candidates; cand; cand = cand->next)
4402 {
4403 cand->second_conv = build_identity_conv (type: totype, NULL_TREE);
4404
4405 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4406 set, then this is copy-initialization. In that case, "The
4407 result of the call is then used to direct-initialize the
4408 object that is the destination of the copy-initialization."
4409 [dcl.init]
4410
4411 We represent this in the conversion sequence with an
4412 rvalue conversion, which means a constructor call. */
4413 if (!TYPE_REF_P (totype)
4414 && cxx_dialect < cxx17
4415 && (flags & LOOKUP_ONLYCONVERTING)
4416 && !(convflags & LOOKUP_NO_TEMP_BIND))
4417 cand->second_conv
4418 = build_conv (code: ck_rvalue, type: totype, from: cand->second_conv);
4419 }
4420 }
4421
4422 if (conv_fns)
4423 {
4424 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4425 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4426 else
4427 first_arg = expr;
4428 }
4429
4430 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4431 {
4432 tree conversion_path = TREE_PURPOSE (conv_fns);
4433 struct z_candidate *old_candidates;
4434
4435 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4436 would need an addional user-defined conversion, i.e. if the return
4437 type differs in class-ness from the desired type. So we avoid
4438 considering operator bool when calling a copy constructor.
4439
4440 This optimization avoids the failure in PR97600, and is allowed by
4441 [temp.inst]/9: "If the function selected by overload resolution can be
4442 determined without instantiating a class template definition, it is
4443 unspecified whether that instantiation actually takes place." */
4444 tree convtype = non_reference (TREE_TYPE (conv_fns));
4445 if ((flags & LOOKUP_NO_CONVERSION)
4446 && !WILDCARD_TYPE_P (convtype)
4447 && (CLASS_TYPE_P (to_nonref)
4448 != CLASS_TYPE_P (convtype)))
4449 continue;
4450
4451 /* If we are called to convert to a reference type, we are trying to
4452 find a direct binding, so don't even consider temporaries. If
4453 we don't find a direct binding, the caller will try again to
4454 look for a temporary binding. */
4455 if (TYPE_REF_P (totype))
4456 convflags |= LOOKUP_NO_TEMP_BIND;
4457
4458 old_candidates = candidates;
4459 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4460 NULL_TREE, false,
4461 conversion_path, TYPE_BINFO (fromtype),
4462 flags, &candidates, complain);
4463
4464 for (cand = candidates; cand != old_candidates; cand = cand->next)
4465 {
4466 if (cand->viable == 0)
4467 /* Already rejected, don't change to -1. */
4468 continue;
4469
4470 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4471 conversion *ics
4472 = implicit_conversion (to: totype,
4473 from: rettype,
4474 expr: 0,
4475 /*c_cast_p=*/false, flags: convflags,
4476 complain);
4477
4478 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4479 copy-initialization. In that case, "The result of the
4480 call is then used to direct-initialize the object that is
4481 the destination of the copy-initialization." [dcl.init]
4482
4483 We represent this in the conversion sequence with an
4484 rvalue conversion, which means a constructor call. But
4485 don't add a second rvalue conversion if there's already
4486 one there. Which there really shouldn't be, but it's
4487 harmless since we'd add it here anyway. */
4488 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4489 && !(convflags & LOOKUP_NO_TEMP_BIND))
4490 ics = build_conv (code: ck_rvalue, type: totype, from: ics);
4491
4492 cand->second_conv = ics;
4493
4494 if (!ics)
4495 {
4496 cand->viable = 0;
4497 cand->reason = arg_conversion_rejection (NULL_TREE, n_arg: -2,
4498 from: rettype, to: totype,
4499 EXPR_LOCATION (expr));
4500 }
4501 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4502 /* Limit this to non-templates for now (PR90546). */
4503 && !cand->template_decl
4504 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4505 {
4506 /* If we are called to convert to a reference type, we are trying
4507 to find a direct binding per [over.match.ref], so rvaluedness
4508 must match for non-functions. */
4509 cand->viable = 0;
4510 }
4511 else if (DECL_NONCONVERTING_P (cand->fn)
4512 && ics->rank > cr_exact)
4513 {
4514 /* 13.3.1.5: For direct-initialization, those explicit
4515 conversion functions that are not hidden within S and
4516 yield type T or a type that can be converted to type T
4517 with a qualification conversion (4.4) are also candidate
4518 functions. */
4519 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4520 I've raised this issue with the committee. --jason 9/2011 */
4521 cand->viable = -1;
4522 cand->reason = explicit_conversion_rejection (from: rettype, to: totype);
4523 }
4524 else if (cand->viable == 1 && ics->bad_p)
4525 {
4526 cand->viable = -1;
4527 cand->reason
4528 = bad_arg_conversion_rejection (NULL_TREE, n_arg: -2,
4529 from: rettype, to: totype,
4530 EXPR_LOCATION (expr));
4531 }
4532 else if (primary_template_specialization_p (cand->fn)
4533 && ics->rank > cr_exact)
4534 {
4535 /* 13.3.3.1.2: If the user-defined conversion is specified by
4536 a specialization of a conversion function template, the
4537 second standard conversion sequence shall have exact match
4538 rank. */
4539 cand->viable = -1;
4540 cand->reason = template_conversion_rejection (from: rettype, to: totype);
4541 }
4542 }
4543 }
4544
4545 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
4546 if (!any_viable_p)
4547 {
4548 if (args)
4549 release_tree_vector (args);
4550 return NULL;
4551 }
4552
4553 cand = tourney (candidates, complain);
4554 if (cand == NULL)
4555 {
4556 if (complain & tf_error)
4557 {
4558 auto_diagnostic_group d;
4559 error_at (cp_expr_loc_or_input_loc (t: expr),
4560 "conversion from %qH to %qI is ambiguous",
4561 fromtype, totype);
4562 print_z_candidates (loc: location_of (expr), candidates);
4563 }
4564
4565 cand = candidates; /* any one will do */
4566 cand->second_conv = build_ambiguous_conv (type: totype, expr);
4567 cand->second_conv->user_conv_p = true;
4568 if (!any_strictly_viable (cands: candidates))
4569 cand->second_conv->bad_p = true;
4570 if (flags & LOOKUP_ONLYCONVERTING)
4571 cand->second_conv->need_temporary_p = true;
4572 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4573 ambiguous conversion is no worse than another user-defined
4574 conversion. */
4575
4576 return cand;
4577 }
4578
4579 /* Maybe pass { } as iterators instead of an initializer_list. */
4580 if (tree iters = maybe_init_list_as_range (fn: cand->fn, expr))
4581 if (z_candidate *cand2
4582 = build_user_type_conversion_1 (totype, expr: iters, flags, complain: tf_none))
4583 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4584 {
4585 cand = cand2;
4586 expr = iters;
4587 }
4588
4589 tree convtype;
4590 if (!DECL_CONSTRUCTOR_P (cand->fn))
4591 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4592 else if (cand->second_conv->kind == ck_rvalue)
4593 /* DR 5: [in the first step of copy-initialization]...if the function
4594 is a constructor, the call initializes a temporary of the
4595 cv-unqualified version of the destination type. */
4596 convtype = cv_unqualified (totype);
4597 else
4598 convtype = totype;
4599 /* Build the user conversion sequence. */
4600 conv = build_conv
4601 (code: ck_user,
4602 type: convtype,
4603 from: build_identity_conv (TREE_TYPE (expr), expr));
4604 conv->cand = cand;
4605 if (cand->viable == -1)
4606 conv->bad_p = true;
4607
4608 /* Remember that this was a list-initialization. */
4609 if (flags & LOOKUP_NO_NARROWING)
4610 conv->check_narrowing = true;
4611
4612 /* Combine it with the second conversion sequence. */
4613 cand->second_conv = merge_conversion_sequences (user_seq: conv,
4614 std_seq: cand->second_conv);
4615
4616 return cand;
4617}
4618
4619/* Wrapper for above. */
4620
4621tree
4622build_user_type_conversion (tree totype, tree expr, int flags,
4623 tsubst_flags_t complain)
4624{
4625 struct z_candidate *cand;
4626 tree ret;
4627
4628 auto_cond_timevar tv (TV_OVERLOAD);
4629
4630 conversion_obstack_sentinel cos;
4631
4632 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4633
4634 if (cand)
4635 {
4636 if (cand->second_conv->kind == ck_ambig)
4637 ret = error_mark_node;
4638 else
4639 {
4640 expr = convert_like (cand->second_conv, expr, complain);
4641 ret = convert_from_reference (expr);
4642 }
4643 }
4644 else
4645 ret = NULL_TREE;
4646
4647 return ret;
4648}
4649
4650/* Give a helpful diagnostic when implicit_conversion fails. */
4651
4652static void
4653implicit_conversion_error (location_t loc, tree type, tree expr)
4654{
4655 tsubst_flags_t complain = tf_warning_or_error;
4656
4657 /* If expr has unknown type, then it is an overloaded function.
4658 Call instantiate_type to get good error messages. */
4659 if (TREE_TYPE (expr) == unknown_type_node)
4660 instantiate_type (type, expr, complain);
4661 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4662 /* We gave an error. */;
4663 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4664 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4665 && !CP_AGGREGATE_TYPE_P (type))
4666 error_at (loc, "designated initializers cannot be used with a "
4667 "non-aggregate type %qT", type);
4668 else
4669 {
4670 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4671 gcc_rich_location rich_loc (loc, &label);
4672 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4673 expr, TREE_TYPE (expr), type);
4674 }
4675}
4676
4677/* Worker for build_converted_constant_expr. */
4678
4679static tree
4680build_converted_constant_expr_internal (tree type, tree expr,
4681 int flags, tsubst_flags_t complain)
4682{
4683 conversion *conv;
4684 tree t;
4685 location_t loc = cp_expr_loc_or_input_loc (t: expr);
4686
4687 if (error_operand_p (t: expr))
4688 return error_mark_node;
4689
4690 conversion_obstack_sentinel cos;
4691
4692 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
4693 /*c_cast_p=*/false, flags, complain);
4694
4695 /* A converted constant expression of type T is an expression, implicitly
4696 converted to type T, where the converted expression is a constant
4697 expression and the implicit conversion sequence contains only
4698
4699 * user-defined conversions,
4700 * lvalue-to-rvalue conversions (7.1),
4701 * array-to-pointer conversions (7.2),
4702 * function-to-pointer conversions (7.3),
4703 * qualification conversions (7.5),
4704 * integral promotions (7.6),
4705 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4706 * null pointer conversions (7.11) from std::nullptr_t,
4707 * null member pointer conversions (7.12) from std::nullptr_t, and
4708 * function pointer conversions (7.13),
4709
4710 and where the reference binding (if any) binds directly. */
4711
4712 for (conversion *c = conv;
4713 c && c->kind != ck_identity;
4714 c = next_conversion (conv: c))
4715 {
4716 switch (c->kind)
4717 {
4718 /* A conversion function is OK. If it isn't constexpr, we'll
4719 complain later that the argument isn't constant. */
4720 case ck_user:
4721 /* List-initialization is OK. */
4722 case ck_aggr:
4723 /* The lvalue-to-rvalue conversion is OK. */
4724 case ck_rvalue:
4725 /* Array-to-pointer and function-to-pointer. */
4726 case ck_lvalue:
4727 /* Function pointer conversions. */
4728 case ck_fnptr:
4729 /* Qualification conversions. */
4730 case ck_qual:
4731 break;
4732
4733 case ck_ref_bind:
4734 if (c->need_temporary_p)
4735 {
4736 if (complain & tf_error)
4737 error_at (loc, "initializing %qH with %qI in converted "
4738 "constant expression does not bind directly",
4739 type, next_conversion (conv: c)->type);
4740 conv = NULL;
4741 }
4742 break;
4743
4744 case ck_base:
4745 case ck_pmem:
4746 case ck_ptr:
4747 case ck_std:
4748 t = next_conversion (conv: c)->type;
4749 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4750 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4751 /* Integral promotion or conversion. */
4752 break;
4753 if (NULLPTR_TYPE_P (t))
4754 /* Conversion from nullptr to pointer or pointer-to-member. */
4755 break;
4756
4757 if (complain & tf_error)
4758 error_at (loc, "conversion from %qH to %qI in a "
4759 "converted constant expression", t, type);
4760 /* fall through. */
4761
4762 default:
4763 conv = NULL;
4764 break;
4765 }
4766 }
4767
4768 /* Avoid confusing convert_nontype_argument by introducing
4769 a redundant conversion to the same reference type. */
4770 if (conv && conv->kind == ck_ref_bind
4771 && REFERENCE_REF_P (expr))
4772 {
4773 tree ref = TREE_OPERAND (expr, 0);
4774 if (same_type_p (type, TREE_TYPE (ref)))
4775 return ref;
4776 }
4777
4778 if (conv)
4779 {
4780 /* Don't copy a class in a template. */
4781 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4782 && processing_template_decl)
4783 conv = next_conversion (conv);
4784
4785 /* Issuing conversion warnings for value-dependent expressions is
4786 likely too noisy. */
4787 warning_sentinel w (warn_conversion);
4788 conv->check_narrowing = true;
4789 conv->check_narrowing_const_only = true;
4790 expr = convert_like (conv, expr, complain);
4791 }
4792 else
4793 {
4794 if (complain & tf_error)
4795 implicit_conversion_error (loc, type, expr);
4796 expr = error_mark_node;
4797 }
4798
4799 return expr;
4800}
4801
4802/* Subroutine of convert_nontype_argument.
4803
4804 EXPR is an expression used in a context that requires a converted
4805 constant-expression, such as a template non-type parameter. Do any
4806 necessary conversions (that are permitted for converted
4807 constant-expressions) to convert it to the desired type.
4808
4809 This function doesn't consider explicit conversion functions. If
4810 you mean to use "a contextually converted constant expression of type
4811 bool", use build_converted_constant_bool_expr.
4812
4813 If conversion is successful, returns the converted expression;
4814 otherwise, returns error_mark_node. */
4815
4816tree
4817build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4818{
4819 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4820 complain);
4821}
4822
4823/* Used to create "a contextually converted constant expression of type
4824 bool". This differs from build_converted_constant_expr in that it
4825 also considers explicit conversion functions. */
4826
4827tree
4828build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4829{
4830 return build_converted_constant_expr_internal (boolean_type_node, expr,
4831 LOOKUP_NORMAL, complain);
4832}
4833
4834/* Do any initial processing on the arguments to a function call. */
4835
4836vec<tree, va_gc> *
4837resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4838{
4839 unsigned int ix;
4840 tree arg;
4841
4842 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4843 {
4844 if (error_operand_p (t: arg))
4845 return NULL;
4846 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4847 {
4848 if (complain & tf_error)
4849 error_at (cp_expr_loc_or_input_loc (t: arg),
4850 "invalid use of void expression");
4851 return NULL;
4852 }
4853 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4854 return NULL;
4855
4856 /* Force auto deduction now. Omit tf_warning to avoid redundant
4857 deprecated warning on deprecated-14.C. */
4858 if (!mark_single_function (arg, complain & ~tf_warning))
4859 return NULL;
4860 }
4861 return args;
4862}
4863
4864/* Perform overload resolution on FN, which is called with the ARGS.
4865
4866 Return the candidate function selected by overload resolution, or
4867 NULL if the event that overload resolution failed. In the case
4868 that overload resolution fails, *CANDIDATES will be the set of
4869 candidates considered, and ANY_VIABLE_P will be set to true or
4870 false to indicate whether or not any of the candidates were
4871 viable.
4872
4873 The ARGS should already have gone through RESOLVE_ARGS before this
4874 function is called. */
4875
4876static struct z_candidate *
4877perform_overload_resolution (tree fn,
4878 const vec<tree, va_gc> *args,
4879 struct z_candidate **candidates,
4880 bool *any_viable_p, tsubst_flags_t complain)
4881{
4882 struct z_candidate *cand;
4883 tree explicit_targs;
4884 int template_only;
4885
4886 auto_cond_timevar tv (TV_OVERLOAD);
4887
4888 explicit_targs = NULL_TREE;
4889 template_only = 0;
4890
4891 *candidates = NULL;
4892 *any_viable_p = true;
4893
4894 /* Check FN. */
4895 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4896
4897 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4898 {
4899 explicit_targs = TREE_OPERAND (fn, 1);
4900 fn = TREE_OPERAND (fn, 0);
4901 template_only = 1;
4902 }
4903
4904 /* Add the various candidate functions. */
4905 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4906 explicit_targs, template_only,
4907 /*conversion_path=*/NULL_TREE,
4908 /*access_path=*/NULL_TREE,
4909 LOOKUP_NORMAL,
4910 candidates, complain);
4911
4912 *candidates = splice_viable (cands: *candidates, strict_p: false, any_viable_p);
4913 if (*any_viable_p)
4914 cand = tourney (*candidates, complain);
4915 else
4916 cand = NULL;
4917
4918 return cand;
4919}
4920
4921/* Print an error message about being unable to build a call to FN with
4922 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4923 be located; CANDIDATES is a possibly empty list of such
4924 functions. */
4925
4926static void
4927print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4928 struct z_candidate *candidates)
4929{
4930 tree targs = NULL_TREE;
4931 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4932 {
4933 targs = TREE_OPERAND (fn, 1);
4934 fn = TREE_OPERAND (fn, 0);
4935 }
4936 tree name = OVL_NAME (fn);
4937 location_t loc = location_of (name);
4938 if (targs)
4939 name = lookup_template_function (name, targs);
4940
4941 auto_diagnostic_group d;
4942 if (!any_strictly_viable (cands: candidates))
4943 error_at (loc, "no matching function for call to %<%D(%A)%>",
4944 name, build_tree_list_vec (args));
4945 else
4946 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4947 name, build_tree_list_vec (args));
4948 if (candidates)
4949 print_z_candidates (loc, candidates);
4950}
4951
4952/* Perform overload resolution on the set of deduction guides DGUIDES
4953 using ARGS. Returns the selected deduction guide, or error_mark_node
4954 if overload resolution fails. */
4955
4956tree
4957perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4958 tsubst_flags_t complain)
4959{
4960 z_candidate *candidates;
4961 bool any_viable_p;
4962 tree result;
4963
4964 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4965
4966 conversion_obstack_sentinel cos;
4967
4968 z_candidate *cand = perform_overload_resolution (fn: dguides, args, candidates: &candidates,
4969 any_viable_p: &any_viable_p, complain);
4970 if (!cand)
4971 {
4972 if (complain & tf_error)
4973 print_error_for_call_failure (fn: dguides, args, candidates);
4974 result = error_mark_node;
4975 }
4976 else
4977 result = cand->fn;
4978
4979 return result;
4980}
4981
4982/* Return an expression for a call to FN (a namespace-scope function,
4983 or a static member function) with the ARGS. This may change
4984 ARGS. */
4985
4986tree
4987build_new_function_call (tree fn, vec<tree, va_gc> **args,
4988 tsubst_flags_t complain)
4989{
4990 struct z_candidate *candidates, *cand;
4991 bool any_viable_p;
4992 tree result;
4993
4994 if (args != NULL && *args != NULL)
4995 {
4996 *args = resolve_args (args: *args, complain);
4997 if (*args == NULL)
4998 return error_mark_node;
4999 }
5000
5001 if (flag_tm)
5002 tm_malloc_replacement (fn);
5003
5004 conversion_obstack_sentinel cos;
5005
5006 cand = perform_overload_resolution (fn, args: *args, candidates: &candidates, any_viable_p: &any_viable_p,
5007 complain);
5008
5009 if (!cand)
5010 {
5011 if (complain & tf_error)
5012 {
5013 // If there is a single (non-viable) function candidate,
5014 // let the error be diagnosed by cp_build_function_call_vec.
5015 if (!any_viable_p && candidates && ! candidates->next
5016 && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
5017 return cp_build_function_call_vec (candidates->fn, args, complain);
5018
5019 // Otherwise, emit notes for non-viable candidates.
5020 print_error_for_call_failure (fn, args: *args, candidates);
5021 }
5022 result = error_mark_node;
5023 }
5024 else
5025 {
5026 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5027 }
5028
5029 if (flag_coroutines
5030 && result
5031 && TREE_CODE (result) == CALL_EXPR
5032 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5033 == BUILT_IN_NORMAL)
5034 result = coro_validate_builtin_call (result);
5035
5036 return result;
5037}
5038
5039/* Build a call to a global operator new. FNNAME is the name of the
5040 operator (either "operator new" or "operator new[]") and ARGS are
5041 the arguments provided. This may change ARGS. *SIZE points to the
5042 total number of bytes required by the allocation, and is updated if
5043 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5044 be used. If this function determines that no cookie should be
5045 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5046 is not NULL_TREE, it is evaluated before calculating the final
5047 array size, and if it fails, the array size is replaced with
5048 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5049 is non-NULL, it will be set, upon return, to the allocation
5050 function called. */
5051
5052tree
5053build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5054 tree *size, tree *cookie_size,
5055 tree align_arg, tree size_check,
5056 tree *fn, tsubst_flags_t complain)
5057{
5058 tree original_size = *size;
5059 tree fns;
5060 struct z_candidate *candidates;
5061 struct z_candidate *cand = NULL;
5062 bool any_viable_p;
5063
5064 if (fn)
5065 *fn = NULL_TREE;
5066 /* Set to (size_t)-1 if the size check fails. */
5067 if (size_check != NULL_TREE)
5068 {
5069 tree errval = TYPE_MAX_VALUE (sizetype);
5070 if (cxx_dialect >= cxx11 && flag_exceptions)
5071 errval = throw_bad_array_new_length ();
5072 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5073 original_size, errval);
5074 }
5075 vec_safe_insert (v&: *args, ix: 0, obj: *size);
5076 *args = resolve_args (args: *args, complain);
5077 if (*args == NULL)
5078 return error_mark_node;
5079
5080 conversion_obstack_sentinel cos;
5081
5082 /* Based on:
5083
5084 [expr.new]
5085
5086 If this lookup fails to find the name, or if the allocated type
5087 is not a class type, the allocation function's name is looked
5088 up in the global scope.
5089
5090 we disregard block-scope declarations of "operator new". */
5091 fns = lookup_qualified_name (global_namespace, name: fnname);
5092
5093 if (align_arg)
5094 {
5095 vec<tree, va_gc>* align_args
5096 = vec_copy_and_insert (*args, align_arg, 1);
5097 cand = perform_overload_resolution (fn: fns, args: align_args, candidates: &candidates,
5098 any_viable_p: &any_viable_p, complain: tf_none);
5099 if (cand)
5100 *args = align_args;
5101 /* If no aligned allocation function matches, try again without the
5102 alignment. */
5103 }
5104
5105 /* Figure out what function is being called. */
5106 if (!cand)
5107 cand = perform_overload_resolution (fn: fns, args: *args, candidates: &candidates, any_viable_p: &any_viable_p,
5108 complain);
5109
5110 /* If no suitable function could be found, issue an error message
5111 and give up. */
5112 if (!cand)
5113 {
5114 if (complain & tf_error)
5115 print_error_for_call_failure (fn: fns, args: *args, candidates);
5116 return error_mark_node;
5117 }
5118
5119 /* If a cookie is required, add some extra space. Whether
5120 or not a cookie is required cannot be determined until
5121 after we know which function was called. */
5122 if (*cookie_size)
5123 {
5124 bool use_cookie = true;
5125 tree arg_types;
5126
5127 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5128 /* Skip the size_t parameter. */
5129 arg_types = TREE_CHAIN (arg_types);
5130 /* Check the remaining parameters (if any). */
5131 if (arg_types
5132 && TREE_CHAIN (arg_types) == void_list_node
5133 && same_type_p (TREE_VALUE (arg_types),
5134 ptr_type_node))
5135 use_cookie = false;
5136 /* If we need a cookie, adjust the number of bytes allocated. */
5137 if (use_cookie)
5138 {
5139 /* Update the total size. */
5140 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5141 if (size_check)
5142 {
5143 /* Set to (size_t)-1 if the size check fails. */
5144 gcc_assert (size_check != NULL_TREE);
5145 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5146 *size, TYPE_MAX_VALUE (sizetype));
5147 }
5148 /* Update the argument list to reflect the adjusted size. */
5149 (**args)[0] = *size;
5150 }
5151 else
5152 *cookie_size = NULL_TREE;
5153 }
5154
5155 /* Tell our caller which function we decided to call. */
5156 if (fn)
5157 *fn = cand->fn;
5158
5159 /* Build the CALL_EXPR. */
5160 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5161
5162 /* Set this flag for all callers of this function. In addition to
5163 new-expressions, this is called for allocating coroutine state; treat
5164 that as an implicit new-expression. */
5165 tree call = extract_call_expr (ret);
5166 if (TREE_CODE (call) == CALL_EXPR)
5167 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5168
5169 return ret;
5170}
5171
5172/* Evaluate side-effects from OBJ before evaluating call
5173 to FN in RESULT expression.
5174 This is for expressions of the form `obj->fn(...)'
5175 where `fn' turns out to be a static member function and
5176 `obj' needs to be evaluated. `fn' could be also static operator[]
5177 or static operator(), in which cases the source expression
5178 would be `obj[...]' or `obj(...)'. */
5179
5180tree
5181keep_unused_object_arg (tree result, tree obj, tree fn)
5182{
5183 if (result == NULL_TREE
5184 || result == error_mark_node
5185 || TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
5186 || !TREE_SIDE_EFFECTS (obj))
5187 return result;
5188
5189 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5190 volatile. */
5191 tree a = obj;
5192 if (TREE_THIS_VOLATILE (a))
5193 a = build_this (obj: a);
5194 if (TREE_SIDE_EFFECTS (a))
5195 return cp_build_compound_expr (a, result, tf_error);
5196 return result;
5197}
5198
5199/* Build a new call to operator(). This may change ARGS. */
5200
5201tree
5202build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5203{
5204 struct z_candidate *candidates = 0, *cand;
5205 tree fns, convs, first_mem_arg = NULL_TREE;
5206 bool any_viable_p;
5207 tree result = NULL_TREE;
5208
5209 auto_cond_timevar tv (TV_OVERLOAD);
5210
5211 obj = mark_lvalue_use (obj);
5212
5213 if (error_operand_p (t: obj))
5214 return error_mark_node;
5215
5216 tree type = TREE_TYPE (obj);
5217
5218 obj = prep_operand (obj);
5219
5220 if (TYPE_PTRMEMFUNC_P (type))
5221 {
5222 if (complain & tf_error)
5223 /* It's no good looking for an overloaded operator() on a
5224 pointer-to-member-function. */
5225 error ("pointer-to-member function %qE cannot be called without "
5226 "an object; consider using %<.*%> or %<->*%>", obj);
5227 return error_mark_node;
5228 }
5229
5230 if (TYPE_BINFO (type))
5231 {
5232 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5233 if (fns == error_mark_node)
5234 return error_mark_node;
5235 }
5236 else
5237 fns = NULL_TREE;
5238
5239 if (args != NULL && *args != NULL)
5240 {
5241 *args = resolve_args (args: *args, complain);
5242 if (*args == NULL)
5243 return error_mark_node;
5244 }
5245
5246 conversion_obstack_sentinel cos;
5247
5248 if (fns)
5249 {
5250 first_mem_arg = obj;
5251
5252 add_candidates (BASELINK_FUNCTIONS (fns),
5253 first_mem_arg, *args, NULL_TREE,
5254 NULL_TREE, false,
5255 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5256 LOOKUP_NORMAL, &candidates, complain);
5257 }
5258
5259 bool any_call_ops = candidates != nullptr;
5260
5261 convs = lookup_conversions (type);
5262
5263 for (; convs; convs = TREE_CHAIN (convs))
5264 {
5265 tree totype = TREE_TYPE (convs);
5266
5267 if (TYPE_PTRFN_P (totype)
5268 || TYPE_REFFN_P (totype)
5269 || (TYPE_REF_P (totype)
5270 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5271 for (tree fn : ovl_range (TREE_VALUE (convs)))
5272 {
5273 if (DECL_NONCONVERTING_P (fn))
5274 continue;
5275
5276 if (TREE_CODE (fn) == TEMPLATE_DECL)
5277 {
5278 /* Making this work broke PR 71117 and 85118, so until the
5279 committee resolves core issue 2189, let's disable this
5280 candidate if there are any call operators. */
5281 if (any_call_ops)
5282 continue;
5283
5284 add_template_conv_candidate
5285 (candidates: &candidates, tmpl: fn, obj, arglist: *args, return_type: totype,
5286 /*access_path=*/NULL_TREE,
5287 /*conversion_path=*/NULL_TREE, complain);
5288 }
5289 else
5290 add_conv_candidate (candidates: &candidates, fn, obj,
5291 arglist: *args, /*conversion_path=*/NULL_TREE,
5292 /*access_path=*/NULL_TREE, complain);
5293 }
5294 }
5295
5296 /* Be strict here because if we choose a bad conversion candidate, the
5297 errors we get won't mention the call context. */
5298 candidates = splice_viable (cands: candidates, strict_p: true, any_viable_p: &any_viable_p);
5299 if (!any_viable_p)
5300 {
5301 if (complain & tf_error)
5302 {
5303 auto_diagnostic_group d;
5304 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5305 build_tree_list_vec (*args));
5306 print_z_candidates (loc: location_of (TREE_TYPE (obj)), candidates);
5307 }
5308 result = error_mark_node;
5309 }
5310 else
5311 {
5312 cand = tourney (candidates, complain);
5313 if (cand == 0)
5314 {
5315 if (complain & tf_error)
5316 {
5317 auto_diagnostic_group d;
5318 error ("call of %<(%T) (%A)%> is ambiguous",
5319 TREE_TYPE (obj), build_tree_list_vec (*args));
5320 print_z_candidates (loc: location_of (TREE_TYPE (obj)), candidates);
5321 }
5322 result = error_mark_node;
5323 }
5324 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5325 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5326 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5327 {
5328 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5329 /* In an expression of the form `a()' where cand->fn
5330 which is operator() turns out to be a static member function,
5331 `a' is none-the-less evaluated. */
5332 result = keep_unused_object_arg (result, obj, fn: cand->fn);
5333 }
5334 else
5335 {
5336 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5337 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5338 -1, complain);
5339 else
5340 {
5341 gcc_checking_assert (TYPE_P (cand->fn));
5342 obj = convert_like (cand->convs[0], obj, complain);
5343 }
5344 obj = convert_from_reference (obj);
5345 result = cp_build_function_call_vec (obj, args, complain);
5346 }
5347 }
5348
5349 return result;
5350}
5351
5352/* Called by op_error to prepare format strings suitable for the error
5353 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5354 and a suffix (controlled by NTYPES). */
5355
5356static const char *
5357op_error_string (const char *errmsg, int ntypes, bool match)
5358{
5359 const char *msg;
5360
5361 const char *msgp = concat (match ? G_("ambiguous overload for ")
5362 : G_("no match for "), errmsg, NULL);
5363
5364 if (ntypes == 3)
5365 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5366 else if (ntypes == 2)
5367 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5368 else
5369 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5370
5371 return msg;
5372}
5373
5374static void
5375op_error (const op_location_t &loc,
5376 enum tree_code code, enum tree_code code2,
5377 tree arg1, tree arg2, tree arg3, bool match)
5378{
5379 bool assop = code == MODIFY_EXPR;
5380 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5381
5382 switch (code)
5383 {
5384 case COND_EXPR:
5385 if (flag_diagnostics_show_caret)
5386 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5387 ntypes: 3, match),
5388 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5389 else
5390 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5391 "in %<%E ? %E : %E%>"), ntypes: 3, match),
5392 arg1, arg2, arg3,
5393 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5394 break;
5395
5396 case POSTINCREMENT_EXPR:
5397 case POSTDECREMENT_EXPR:
5398 if (flag_diagnostics_show_caret)
5399 error_at (loc, op_error_string (G_("%<operator%s%>"), ntypes: 1, match),
5400 opname, TREE_TYPE (arg1));
5401 else
5402 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5403 ntypes: 1, match),
5404 opname, arg1, opname, TREE_TYPE (arg1));
5405 break;
5406
5407 case ARRAY_REF:
5408 if (flag_diagnostics_show_caret)
5409 error_at (loc, op_error_string (G_("%<operator[]%>"), ntypes: 2, match),
5410 TREE_TYPE (arg1), TREE_TYPE (arg2));
5411 else
5412 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5413 ntypes: 2, match),
5414 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5415 break;
5416
5417 case REALPART_EXPR:
5418 case IMAGPART_EXPR:
5419 if (flag_diagnostics_show_caret)
5420 error_at (loc, op_error_string (G_("%qs"), ntypes: 1, match),
5421 opname, TREE_TYPE (arg1));
5422 else
5423 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), ntypes: 1, match),
5424 opname, opname, arg1, TREE_TYPE (arg1));
5425 break;
5426
5427 case CO_AWAIT_EXPR:
5428 if (flag_diagnostics_show_caret)
5429 error_at (loc, op_error_string (G_("%<operator %s%>"), ntypes: 1, match),
5430 opname, TREE_TYPE (arg1));
5431 else
5432 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5433 ntypes: 1, match),
5434 opname, opname, arg1, TREE_TYPE (arg1));
5435 break;
5436
5437 default:
5438 if (arg2)
5439 if (flag_diagnostics_show_caret)
5440 {
5441 binary_op_rich_location richloc (loc, arg1, arg2, true);
5442 error_at (&richloc,
5443 op_error_string (G_("%<operator%s%>"), ntypes: 2, match),
5444 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5445 }
5446 else
5447 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5448 ntypes: 2, match),
5449 opname, arg1, opname, arg2,
5450 TREE_TYPE (arg1), TREE_TYPE (arg2));
5451 else
5452 if (flag_diagnostics_show_caret)
5453 error_at (loc, op_error_string (G_("%<operator%s%>"), ntypes: 1, match),
5454 opname, TREE_TYPE (arg1));
5455 else
5456 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5457 ntypes: 1, match),
5458 opname, opname, arg1, TREE_TYPE (arg1));
5459 break;
5460 }
5461}
5462
5463/* Return the implicit conversion sequence that could be used to
5464 convert E1 to E2 in [expr.cond]. */
5465
5466static conversion *
5467conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5468{
5469 tree t1 = non_reference (TREE_TYPE (e1));
5470 tree t2 = non_reference (TREE_TYPE (e2));
5471 conversion *conv;
5472 bool good_base;
5473
5474 /* [expr.cond]
5475
5476 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5477 implicitly converted (clause _conv_) to the type "lvalue reference to
5478 T2", subject to the constraint that in the conversion the
5479 reference must bind directly (_dcl.init.ref_) to an lvalue.
5480
5481 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5482 implicitly converted to the type "rvalue reference to T2", subject to
5483 the constraint that the reference must bind directly. */
5484 if (glvalue_p (e2))
5485 {
5486 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5487 conv = implicit_conversion (to: rtype,
5488 from: t1,
5489 expr: e1,
5490 /*c_cast_p=*/false,
5491 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5492 |LOOKUP_ONLYCONVERTING,
5493 complain);
5494 if (conv && !conv->bad_p)
5495 return conv;
5496 }
5497
5498 /* If E2 is a prvalue or if neither of the conversions above can be done
5499 and at least one of the operands has (possibly cv-qualified) class
5500 type: */
5501 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5502 return NULL;
5503
5504 /* [expr.cond]
5505
5506 If E1 and E2 have class type, and the underlying class types are
5507 the same or one is a base class of the other: E1 can be converted
5508 to match E2 if the class of T2 is the same type as, or a base
5509 class of, the class of T1, and the cv-qualification of T2 is the
5510 same cv-qualification as, or a greater cv-qualification than, the
5511 cv-qualification of T1. If the conversion is applied, E1 is
5512 changed to an rvalue of type T2 that still refers to the original
5513 source class object (or the appropriate subobject thereof). */
5514 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5515 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5516 {
5517 if (good_base && at_least_as_qualified_p (t2, t1))
5518 {
5519 conv = build_identity_conv (type: t1, expr: e1);
5520 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5521 TYPE_MAIN_VARIANT (t2)))
5522 conv = build_conv (code: ck_base, type: t2, from: conv);
5523 else
5524 conv = build_conv (code: ck_rvalue, type: t2, from: conv);
5525 return conv;
5526 }
5527 else
5528 return NULL;
5529 }
5530 else
5531 /* [expr.cond]
5532
5533 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5534 converted to the type that expression E2 would have if E2 were
5535 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5536 return implicit_conversion (to: t2, from: t1, expr: e1, /*c_cast_p=*/false,
5537 LOOKUP_IMPLICIT, complain);
5538}
5539
5540/* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5541 arguments to the conditional expression. */
5542
5543tree
5544build_conditional_expr (const op_location_t &loc,
5545 tree arg1, tree arg2, tree arg3,
5546 tsubst_flags_t complain)
5547{
5548 tree arg2_type;
5549 tree arg3_type;
5550 tree result = NULL_TREE;
5551 tree result_type = NULL_TREE;
5552 tree semantic_result_type = NULL_TREE;
5553 bool is_glvalue = true;
5554 struct z_candidate *candidates = 0;
5555 struct z_candidate *cand;
5556 tree orig_arg2, orig_arg3;
5557
5558 auto_cond_timevar tv (TV_OVERLOAD);
5559
5560 /* As a G++ extension, the second argument to the conditional can be
5561 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5562 c'.) If the second operand is omitted, make sure it is
5563 calculated only once. */
5564 if (!arg2)
5565 {
5566 if (complain & tf_error)
5567 pedwarn (loc, OPT_Wpedantic,
5568 "ISO C++ forbids omitting the middle term of "
5569 "a %<?:%> expression");
5570
5571 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5572 warn_for_omitted_condop (loc, arg1);
5573
5574 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5575 if (glvalue_p (arg1))
5576 {
5577 arg1 = cp_stabilize_reference (arg1);
5578 arg2 = arg1 = prevent_lifetime_extension (arg1);
5579 }
5580 else if (TREE_CODE (arg1) == TARGET_EXPR)
5581 /* arg1 can't be a prvalue result of the conditional
5582 expression, since it needs to be materialized for the
5583 conversion to bool, so treat it as an xvalue in arg2. */
5584 arg2 = move (TARGET_EXPR_SLOT (arg1));
5585 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5586 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5587 cp_save_expr (TREE_OPERAND (arg1, 0)));
5588 else
5589 arg2 = arg1 = cp_save_expr (arg1);
5590 }
5591
5592 /* If something has already gone wrong, just pass that fact up the
5593 tree. */
5594 if (error_operand_p (t: arg1)
5595 || error_operand_p (t: arg2)
5596 || error_operand_p (t: arg3))
5597 return error_mark_node;
5598
5599 conversion_obstack_sentinel cos;
5600
5601 orig_arg2 = arg2;
5602 orig_arg3 = arg3;
5603
5604 if (gnu_vector_type_p (TREE_TYPE (arg1))
5605 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5606 {
5607 tree arg1_type = TREE_TYPE (arg1);
5608
5609 /* If arg1 is another cond_expr choosing between -1 and 0,
5610 then we can use its comparison. It may help to avoid
5611 additional comparison, produce more accurate diagnostics
5612 and enables folding. */
5613 if (TREE_CODE (arg1) == VEC_COND_EXPR
5614 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5615 && integer_zerop (TREE_OPERAND (arg1, 2)))
5616 arg1 = TREE_OPERAND (arg1, 0);
5617
5618 arg1 = force_rvalue (arg1, complain);
5619 arg2 = force_rvalue (arg2, complain);
5620 arg3 = force_rvalue (arg3, complain);
5621
5622 /* force_rvalue can return error_mark on valid arguments. */
5623 if (error_operand_p (t: arg1)
5624 || error_operand_p (t: arg2)
5625 || error_operand_p (t: arg3))
5626 return error_mark_node;
5627
5628 arg2_type = TREE_TYPE (arg2);
5629 arg3_type = TREE_TYPE (arg3);
5630
5631 if (!VECTOR_TYPE_P (arg2_type)
5632 && !VECTOR_TYPE_P (arg3_type))
5633 {
5634 /* Rely on the error messages of the scalar version. */
5635 tree scal = build_conditional_expr (loc, integer_one_node,
5636 arg2: orig_arg2, arg3: orig_arg3, complain);
5637 if (scal == error_mark_node)
5638 return error_mark_node;
5639 tree stype = TREE_TYPE (scal);
5640 tree ctype = TREE_TYPE (arg1_type);
5641 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5642 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5643 {
5644 if (complain & tf_error)
5645 error_at (loc, "inferred scalar type %qT is not an integer or "
5646 "floating-point type of the same size as %qT", stype,
5647 COMPARISON_CLASS_P (arg1)
5648 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5649 : ctype);
5650 return error_mark_node;
5651 }
5652
5653 tree vtype = build_opaque_vector_type (stype,
5654 TYPE_VECTOR_SUBPARTS (node: arg1_type));
5655 /* We could pass complain & tf_warning to unsafe_conversion_p,
5656 but the warnings (like Wsign-conversion) have already been
5657 given by the scalar build_conditional_expr_1. We still check
5658 unsafe_conversion_p to forbid truncating long long -> float. */
5659 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5660 {
5661 if (complain & tf_error)
5662 error_at (loc, "conversion of scalar %qH to vector %qI "
5663 "involves truncation", arg2_type, vtype);
5664 return error_mark_node;
5665 }
5666 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5667 {
5668 if (complain & tf_error)
5669 error_at (loc, "conversion of scalar %qH to vector %qI "
5670 "involves truncation", arg3_type, vtype);
5671 return error_mark_node;
5672 }
5673
5674 arg2 = cp_convert (stype, arg2, complain);
5675 arg2 = save_expr (arg2);
5676 arg2 = build_vector_from_val (vtype, arg2);
5677 arg2_type = vtype;
5678 arg3 = cp_convert (stype, arg3, complain);
5679 arg3 = save_expr (arg3);
5680 arg3 = build_vector_from_val (vtype, arg3);
5681 arg3_type = vtype;
5682 }
5683
5684 if ((gnu_vector_type_p (type: arg2_type) && !VECTOR_TYPE_P (arg3_type))
5685 || (gnu_vector_type_p (type: arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5686 {
5687 enum stv_conv convert_flag =
5688 scalar_to_vector (loc, code: VEC_COND_EXPR, op0: arg2, op1: arg3,
5689 complain & tf_error);
5690
5691 switch (convert_flag)
5692 {
5693 case stv_error:
5694 return error_mark_node;
5695 case stv_firstarg:
5696 {
5697 arg2 = save_expr (arg2);
5698 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5699 arg2 = build_vector_from_val (arg3_type, arg2);
5700 arg2_type = TREE_TYPE (arg2);
5701 break;
5702 }
5703 case stv_secondarg:
5704 {
5705 arg3 = save_expr (arg3);
5706 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5707 arg3 = build_vector_from_val (arg2_type, arg3);
5708 arg3_type = TREE_TYPE (arg3);
5709 break;
5710 }
5711 default:
5712 break;
5713 }
5714 }
5715
5716 if (!gnu_vector_type_p (type: arg2_type)
5717 || !gnu_vector_type_p (type: arg3_type)
5718 || !same_type_p (arg2_type, arg3_type)
5719 || maybe_ne (a: TYPE_VECTOR_SUBPARTS (node: arg1_type),
5720 b: TYPE_VECTOR_SUBPARTS (node: arg2_type))
5721 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5722 {
5723 if (complain & tf_error)
5724 error_at (loc,
5725 "incompatible vector types in conditional expression: "
5726 "%qT, %qT and %qT", TREE_TYPE (arg1),
5727 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5728 return error_mark_node;
5729 }
5730
5731 if (!COMPARISON_CLASS_P (arg1))
5732 {
5733 tree cmp_type = truth_type_for (arg1_type);
5734 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5735 }
5736 return build3_loc (loc, code: VEC_COND_EXPR, type: arg2_type, arg0: arg1, arg1: arg2, arg2: arg3);
5737 }
5738
5739 /* [expr.cond]
5740
5741 The first expression is implicitly converted to bool (clause
5742 _conv_). */
5743 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5744 LOOKUP_NORMAL);
5745 if (error_operand_p (t: arg1))
5746 return error_mark_node;
5747
5748 arg2_type = unlowered_expr_type (arg2);
5749 arg3_type = unlowered_expr_type (arg3);
5750
5751 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5752 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5753 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5754 || SCALAR_FLOAT_TYPE_P (arg2_type)
5755 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5756 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5757 || SCALAR_FLOAT_TYPE_P (arg3_type)
5758 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5759 {
5760 semantic_result_type
5761 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5762 if (semantic_result_type == error_mark_node)
5763 {
5764 tree t1 = arg2_type;
5765 tree t2 = arg3_type;
5766 if (TREE_CODE (t1) == COMPLEX_TYPE)
5767 t1 = TREE_TYPE (t1);
5768 if (TREE_CODE (t2) == COMPLEX_TYPE)
5769 t2 = TREE_TYPE (t2);
5770 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
5771 && SCALAR_FLOAT_TYPE_P (t2)
5772 && (extended_float_type_p (t1)
5773 || extended_float_type_p (t2))
5774 && cp_compare_floating_point_conversion_ranks
5775 (t1, t2) == 3);
5776 if (complain & tf_error)
5777 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5778 "have unordered conversion rank",
5779 arg2_type, arg3_type);
5780 return error_mark_node;
5781 }
5782 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5783 {
5784 arg2 = TREE_OPERAND (arg2, 0);
5785 arg2_type = TREE_TYPE (arg2);
5786 }
5787 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5788 {
5789 arg3 = TREE_OPERAND (arg3, 0);
5790 arg3_type = TREE_TYPE (arg3);
5791 }
5792 }
5793
5794 /* [expr.cond]
5795
5796 If either the second or the third operand has type (possibly
5797 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5798 array-to-pointer (_conv.array_), and function-to-pointer
5799 (_conv.func_) standard conversions are performed on the second
5800 and third operands. */
5801 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5802 {
5803 /* 'void' won't help in resolving an overloaded expression on the
5804 other side, so require it to resolve by itself. */
5805 if (arg2_type == unknown_type_node)
5806 {
5807 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5808 arg2_type = TREE_TYPE (arg2);
5809 }
5810 if (arg3_type == unknown_type_node)
5811 {
5812 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5813 arg3_type = TREE_TYPE (arg3);
5814 }
5815
5816 /* [expr.cond]
5817
5818 One of the following shall hold:
5819
5820 --The second or the third operand (but not both) is a
5821 throw-expression (_except.throw_); the result is of the type
5822 and value category of the other.
5823
5824 --Both the second and the third operands have type void; the
5825 result is of type void and is a prvalue. */
5826 if (TREE_CODE (arg2) == THROW_EXPR
5827 && TREE_CODE (arg3) != THROW_EXPR)
5828 {
5829 result_type = arg3_type;
5830 is_glvalue = glvalue_p (arg3);
5831 }
5832 else if (TREE_CODE (arg2) != THROW_EXPR
5833 && TREE_CODE (arg3) == THROW_EXPR)
5834 {
5835 result_type = arg2_type;
5836 is_glvalue = glvalue_p (arg2);
5837 }
5838 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5839 {
5840 result_type = void_type_node;
5841 is_glvalue = false;
5842 }
5843 else
5844 {
5845 if (complain & tf_error)
5846 {
5847 if (VOID_TYPE_P (arg2_type))
5848 error_at (cp_expr_loc_or_loc (t: arg3, or_loc: loc),
5849 "second operand to the conditional operator "
5850 "is of type %<void%>, but the third operand is "
5851 "neither a throw-expression nor of type %<void%>");
5852 else
5853 error_at (cp_expr_loc_or_loc (t: arg2, or_loc: loc),
5854 "third operand to the conditional operator "
5855 "is of type %<void%>, but the second operand is "
5856 "neither a throw-expression nor of type %<void%>");
5857 }
5858 return error_mark_node;
5859 }
5860
5861 goto valid_operands;
5862 }
5863 /* [expr.cond]
5864
5865 Otherwise, if the second and third operand have different types,
5866 and either has (possibly cv-qualified) class type, or if both are
5867 glvalues of the same value category and the same type except for
5868 cv-qualification, an attempt is made to convert each of those operands
5869 to the type of the other. */
5870 else if (!same_type_p (arg2_type, arg3_type)
5871 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5872 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5873 arg3_type)
5874 && glvalue_p (arg2) && glvalue_p (arg3)
5875 && lvalue_p (arg2) == lvalue_p (arg3))))
5876 {
5877 conversion *conv2;
5878 conversion *conv3;
5879 bool converted = false;
5880
5881 conv2 = conditional_conversion (e1: arg2, e2: arg3, complain);
5882 conv3 = conditional_conversion (e1: arg3, e2: arg2, complain);
5883
5884 /* [expr.cond]
5885
5886 If both can be converted, or one can be converted but the
5887 conversion is ambiguous, the program is ill-formed. If
5888 neither can be converted, the operands are left unchanged and
5889 further checking is performed as described below. If exactly
5890 one conversion is possible, that conversion is applied to the
5891 chosen operand and the converted operand is used in place of
5892 the original operand for the remainder of this section. */
5893 if ((conv2 && !conv2->bad_p
5894 && conv3 && !conv3->bad_p)
5895 || (conv2 && conv2->kind == ck_ambig)
5896 || (conv3 && conv3->kind == ck_ambig))
5897 {
5898 if (complain & tf_error)
5899 {
5900 error_at (loc, "operands to %<?:%> have different types "
5901 "%qT and %qT",
5902 arg2_type, arg3_type);
5903 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5904 inform (loc, " and each type can be converted to the other");
5905 else if (conv2 && conv2->kind == ck_ambig)
5906 convert_like (conv2, arg2, complain);
5907 else
5908 convert_like (conv3, arg3, complain);
5909 }
5910 result = error_mark_node;
5911 }
5912 else if (conv2 && !conv2->bad_p)
5913 {
5914 arg2 = convert_like (conv2, arg2, complain);
5915 arg2 = convert_from_reference (arg2);
5916 arg2_type = TREE_TYPE (arg2);
5917 /* Even if CONV2 is a valid conversion, the result of the
5918 conversion may be invalid. For example, if ARG3 has type
5919 "volatile X", and X does not have a copy constructor
5920 accepting a "volatile X&", then even if ARG2 can be
5921 converted to X, the conversion will fail. */
5922 if (error_operand_p (t: arg2))
5923 result = error_mark_node;
5924 converted = true;
5925 }
5926 else if (conv3 && !conv3->bad_p)
5927 {
5928 arg3 = convert_like (conv3, arg3, complain);
5929 arg3 = convert_from_reference (arg3);
5930 arg3_type = TREE_TYPE (arg3);
5931 if (error_operand_p (t: arg3))
5932 result = error_mark_node;
5933 converted = true;
5934 }
5935
5936 if (result)
5937 return result;
5938
5939 /* If, after the conversion, both operands have class type,
5940 treat the cv-qualification of both operands as if it were the
5941 union of the cv-qualification of the operands.
5942
5943 The standard is not clear about what to do in this
5944 circumstance. For example, if the first operand has type
5945 "const X" and the second operand has a user-defined
5946 conversion to "volatile X", what is the type of the second
5947 operand after this step? Making it be "const X" (matching
5948 the first operand) seems wrong, as that discards the
5949 qualification without actually performing a copy. Leaving it
5950 as "volatile X" seems wrong as that will result in the
5951 conditional expression failing altogether, even though,
5952 according to this step, the one operand could be converted to
5953 the type of the other. */
5954 if (converted
5955 && CLASS_TYPE_P (arg2_type)
5956 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5957 arg2_type = arg3_type =
5958 cp_build_qualified_type (arg2_type,
5959 cp_type_quals (arg2_type)
5960 | cp_type_quals (arg3_type));
5961 }
5962
5963 /* [expr.cond]
5964
5965 If the second and third operands are glvalues of the same value
5966 category and have the same type, the result is of that type and
5967 value category. */
5968 if (((lvalue_p (arg2) && lvalue_p (arg3))
5969 || (xvalue_p (arg2) && xvalue_p (arg3)))
5970 && same_type_p (arg2_type, arg3_type))
5971 {
5972 result_type = arg2_type;
5973 goto valid_operands;
5974 }
5975
5976 /* [expr.cond]
5977
5978 Otherwise, the result is an rvalue. If the second and third
5979 operand do not have the same type, and either has (possibly
5980 cv-qualified) class type, overload resolution is used to
5981 determine the conversions (if any) to be applied to the operands
5982 (_over.match.oper_, _over.built_). */
5983 is_glvalue = false;
5984 if (!same_type_p (arg2_type, arg3_type)
5985 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
5986 {
5987 releasing_vec args;
5988 conversion *conv;
5989 bool any_viable_p;
5990
5991 /* Rearrange the arguments so that add_builtin_candidate only has
5992 to know about two args. In build_builtin_candidate, the
5993 arguments are unscrambled. */
5994 args->quick_push (obj: arg2);
5995 args->quick_push (obj: arg3);
5996 args->quick_push (obj: arg1);
5997 add_builtin_candidates (candidates: &candidates,
5998 code: COND_EXPR,
5999 code2: NOP_EXPR,
6000 fnname: ovl_op_identifier (isass: false, code: COND_EXPR),
6001 argv: args,
6002 LOOKUP_NORMAL, complain);
6003
6004 /* [expr.cond]
6005
6006 If the overload resolution fails, the program is
6007 ill-formed. */
6008 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
6009 if (!any_viable_p)
6010 {
6011 if (complain & tf_error)
6012 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6013 arg2_type, arg3_type);
6014 return error_mark_node;
6015 }
6016 cand = tourney (candidates, complain);
6017 if (!cand)
6018 {
6019 if (complain & tf_error)
6020 {
6021 auto_diagnostic_group d;
6022 op_error (loc, code: COND_EXPR, code2: NOP_EXPR, arg1, arg2, arg3, match: false);
6023 print_z_candidates (loc, candidates);
6024 }
6025 return error_mark_node;
6026 }
6027
6028 /* [expr.cond]
6029
6030 Otherwise, the conversions thus determined are applied, and
6031 the converted operands are used in place of the original
6032 operands for the remainder of this section. */
6033 conv = cand->convs[0];
6034 arg1 = convert_like (conv, arg1, complain);
6035 conv = cand->convs[1];
6036 arg2 = convert_like (conv, arg2, complain);
6037 arg2_type = TREE_TYPE (arg2);
6038 conv = cand->convs[2];
6039 arg3 = convert_like (conv, arg3, complain);
6040 arg3_type = TREE_TYPE (arg3);
6041 }
6042
6043 /* [expr.cond]
6044
6045 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6046 and function-to-pointer (_conv.func_) standard conversions are
6047 performed on the second and third operands.
6048
6049 We need to force the lvalue-to-rvalue conversion here for class types,
6050 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6051 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6052 regions. */
6053
6054 arg2 = force_rvalue (arg2, complain);
6055 if (!CLASS_TYPE_P (arg2_type))
6056 arg2_type = TREE_TYPE (arg2);
6057
6058 arg3 = force_rvalue (arg3, complain);
6059 if (!CLASS_TYPE_P (arg3_type))
6060 arg3_type = TREE_TYPE (arg3);
6061
6062 if (arg2 == error_mark_node || arg3 == error_mark_node)
6063 return error_mark_node;
6064
6065 /* [expr.cond]
6066
6067 After those conversions, one of the following shall hold:
6068
6069 --The second and third operands have the same type; the result is of
6070 that type. */
6071 if (same_type_p (arg2_type, arg3_type))
6072 result_type = arg2_type;
6073 /* [expr.cond]
6074
6075 --The second and third operands have arithmetic or enumeration
6076 type; the usual arithmetic conversions are performed to bring
6077 them to a common type, and the result is of that type. */
6078 else if ((ARITHMETIC_TYPE_P (arg2_type)
6079 || UNSCOPED_ENUM_P (arg2_type))
6080 && (ARITHMETIC_TYPE_P (arg3_type)
6081 || UNSCOPED_ENUM_P (arg3_type)))
6082 {
6083 /* A conditional expression between a floating-point
6084 type and an integer type should convert the integer type to
6085 the evaluation format of the floating-point type, with
6086 possible excess precision. */
6087 tree eptype2 = arg2_type;
6088 tree eptype3 = arg3_type;
6089 tree eptype;
6090 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6091 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6092 {
6093 eptype3 = eptype;
6094 if (!semantic_result_type)
6095 semantic_result_type
6096 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6097 }
6098 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6099 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6100 {
6101 eptype2 = eptype;
6102 if (!semantic_result_type)
6103 semantic_result_type
6104 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6105 }
6106 result_type = type_after_usual_arithmetic_conversions (eptype2,
6107 eptype3);
6108 if (result_type == error_mark_node)
6109 {
6110 tree t1 = eptype2;
6111 tree t2 = eptype3;
6112 if (TREE_CODE (t1) == COMPLEX_TYPE)
6113 t1 = TREE_TYPE (t1);
6114 if (TREE_CODE (t2) == COMPLEX_TYPE)
6115 t2 = TREE_TYPE (t2);
6116 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6117 && SCALAR_FLOAT_TYPE_P (t2)
6118 && (extended_float_type_p (t1)
6119 || extended_float_type_p (t2))
6120 && cp_compare_floating_point_conversion_ranks
6121 (t1, t2) == 3);
6122 if (complain & tf_error)
6123 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6124 "have unordered conversion rank",
6125 eptype2, eptype3);
6126 return error_mark_node;
6127 }
6128 if (semantic_result_type == error_mark_node)
6129 {
6130 tree t1 = arg2_type;
6131 tree t2 = arg3_type;
6132 if (TREE_CODE (t1) == COMPLEX_TYPE)
6133 t1 = TREE_TYPE (t1);
6134 if (TREE_CODE (t2) == COMPLEX_TYPE)
6135 t2 = TREE_TYPE (t2);
6136 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6137 && SCALAR_FLOAT_TYPE_P (t2)
6138 && (extended_float_type_p (t1)
6139 || extended_float_type_p (t2))
6140 && cp_compare_floating_point_conversion_ranks
6141 (t1, t2) == 3);
6142 if (complain & tf_error)
6143 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6144 "have unordered conversion rank",
6145 arg2_type, arg3_type);
6146 return error_mark_node;
6147 }
6148
6149 if (complain & tf_warning)
6150 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6151 "implicit conversion from %qH to %qI to "
6152 "match other result of conditional",
6153 loc);
6154
6155 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6156 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6157 {
6158 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (exp: orig_arg2);
6159 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (exp: orig_arg3);
6160 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6161 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6162 && (DECL_CONTEXT (stripped_orig_arg2)
6163 == DECL_CONTEXT (stripped_orig_arg3)))
6164 /* Two enumerators from the same enumeration can have different
6165 types when the enumeration is still being defined. */;
6166 else if (complain & tf_warning)
6167 warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
6168 "in conditional expression: %qT vs %qT",
6169 arg2_type, arg3_type);
6170 }
6171 else if ((complain & tf_warning)
6172 && warn_deprecated_enum_float_conv
6173 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6174 && SCALAR_FLOAT_TYPE_P (arg3_type))
6175 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6176 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6177 {
6178 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6179 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6180 "conditional expression between enumeration type "
6181 "%qT and floating-point type %qT is deprecated",
6182 arg2_type, arg3_type);
6183 else
6184 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6185 "conditional expression between floating-point "
6186 "type %qT and enumeration type %qT is deprecated",
6187 arg2_type, arg3_type);
6188 }
6189 else if ((extra_warnings || warn_enum_conversion)
6190 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6191 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6192 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6193 && !same_type_p (arg2_type,
6194 type_promotes_to (arg3_type)))))
6195 {
6196 if (complain & tf_warning)
6197 {
6198 enum opt_code opt = (warn_enum_conversion
6199 ? OPT_Wenum_conversion
6200 : OPT_Wextra);
6201 warning_at (loc, opt, "enumerated and "
6202 "non-enumerated type in conditional expression");
6203 }
6204 }
6205
6206 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6207 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6208 }
6209 /* [expr.cond]
6210
6211 --The second and third operands have pointer type, or one has
6212 pointer type and the other is a null pointer constant; pointer
6213 conversions (_conv.ptr_) and qualification conversions
6214 (_conv.qual_) are performed to bring them to their composite
6215 pointer type (_expr.rel_). The result is of the composite
6216 pointer type.
6217
6218 --The second and third operands have pointer to member type, or
6219 one has pointer to member type and the other is a null pointer
6220 constant; pointer to member conversions (_conv.mem_) and
6221 qualification conversions (_conv.qual_) are performed to bring
6222 them to a common type, whose cv-qualification shall match the
6223 cv-qualification of either the second or the third operand.
6224 The result is of the common type. */
6225 else if ((null_ptr_cst_p (t: arg2)
6226 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6227 || (null_ptr_cst_p (t: arg3)
6228 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6229 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6230 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6231 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6232 {
6233 result_type = composite_pointer_type (loc,
6234 arg2_type, arg3_type, arg2,
6235 arg3, CPO_CONDITIONAL_EXPR,
6236 complain);
6237 if (result_type == error_mark_node)
6238 return error_mark_node;
6239 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6240 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6241 }
6242
6243 if (!result_type)
6244 {
6245 if (complain & tf_error)
6246 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6247 arg2_type, arg3_type);
6248 return error_mark_node;
6249 }
6250
6251 if (arg2 == error_mark_node || arg3 == error_mark_node)
6252 return error_mark_node;
6253
6254 valid_operands:
6255 if (processing_template_decl && is_glvalue)
6256 {
6257 /* Let lvalue_kind know this was a glvalue. */
6258 tree arg = (result_type == arg2_type ? arg2 : arg3);
6259 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6260 }
6261
6262 result = build3_loc (loc, code: COND_EXPR, type: result_type, arg0: arg1, arg1: arg2, arg2: arg3);
6263
6264 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6265 warn here, because the COND_EXPR will be turned into ARG2. */
6266 if (warn_duplicated_branches
6267 && (complain & tf_warning)
6268 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6269 flags: OEP_ADDRESS_OF_SAME_FIELD)))
6270 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6271 "this condition has identical branches");
6272
6273 /* We can't use result_type below, as fold might have returned a
6274 throw_expr. */
6275
6276 if (!is_glvalue)
6277 {
6278 /* Expand both sides into the same slot, hopefully the target of
6279 the ?: expression. We used to check for TARGET_EXPRs here,
6280 but now we sometimes wrap them in NOP_EXPRs so the test would
6281 fail. */
6282 if (CLASS_TYPE_P (TREE_TYPE (result)))
6283 {
6284 result = get_target_expr (result, complain);
6285 /* Tell gimplify_modify_expr_rhs not to strip this in
6286 assignment context: we want both arms to initialize
6287 the same temporary. */
6288 TARGET_EXPR_NO_ELIDE (result) = true;
6289 }
6290 /* If this expression is an rvalue, but might be mistaken for an
6291 lvalue, we must add a NON_LVALUE_EXPR. */
6292 result = rvalue (result);
6293 if (semantic_result_type)
6294 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6295 result);
6296 }
6297 else
6298 {
6299 result = force_paren_expr (result);
6300 gcc_assert (semantic_result_type == NULL_TREE);
6301 }
6302
6303 return result;
6304}
6305
6306/* OPERAND is an operand to an expression. Perform necessary steps
6307 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6308 returned. */
6309
6310static tree
6311prep_operand (tree operand)
6312{
6313 if (operand)
6314 {
6315 if (CLASS_TYPE_P (TREE_TYPE (operand))
6316 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6317 /* Make sure the template type is instantiated now. */
6318 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6319 }
6320
6321 return operand;
6322}
6323
6324/* True iff CONV represents a conversion sequence which no other can be better
6325 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6326 type (including binding to a reference to the same type). This is stronger
6327 than the standard's "identity" category, which also includes reference
6328 bindings that add cv-qualifiers or change rvalueness. */
6329
6330static bool
6331perfect_conversion_p (conversion *conv)
6332{
6333 if (CONVERSION_RANK (conv) != cr_identity)
6334 return false;
6335 if (conv->kind == ck_ref_bind)
6336 {
6337 if (!conv->rvaluedness_matches_p)
6338 return false;
6339 if (!same_type_p (TREE_TYPE (conv->type),
6340 next_conversion (conv)->type))
6341 return false;
6342 }
6343 if (conv->check_narrowing)
6344 /* Brace elision is imperfect. */
6345 return false;
6346 return true;
6347}
6348
6349/* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6350 other candidate can be a better match. Since the template/non-template
6351 tiebreaker comes immediately after the conversion comparison in
6352 [over.match.best], a perfect non-template candidate is better than all
6353 templates. */
6354
6355static bool
6356perfect_candidate_p (z_candidate *cand)
6357{
6358 if (cand->viable < 1)
6359 return false;
6360 /* CWG1402 makes an implicitly deleted move op worse than other
6361 candidates. */
6362 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6363 && move_fn_p (cand->fn))
6364 return false;
6365 int len = cand->num_convs;
6366 for (int i = 0; i < len; ++i)
6367 if (!perfect_conversion_p (conv: cand->convs[i]))
6368 return false;
6369 if (conversion *conv = cand->second_conv)
6370 if (!perfect_conversion_p (conv))
6371 return false;
6372 return true;
6373}
6374
6375/* True iff one of CAND's argument conversions is missing. */
6376
6377static bool
6378missing_conversion_p (const z_candidate *cand)
6379{
6380 for (unsigned i = 0; i < cand->num_convs; ++i)
6381 {
6382 conversion *conv = cand->convs[i];
6383 if (!conv)
6384 return true;
6385 if (conv->kind == ck_deferred_bad)
6386 {
6387 /* We don't know whether this conversion is outright invalid or
6388 just bad, so conservatively assume it's missing. */
6389 gcc_checking_assert (conv->bad_p);
6390 return true;
6391 }
6392 }
6393 return false;
6394}
6395
6396/* Add each of the viable functions in FNS (a FUNCTION_DECL or
6397 OVERLOAD) to the CANDIDATES, returning an updated list of
6398 CANDIDATES. The ARGS are the arguments provided to the call;
6399 if FIRST_ARG is non-null it is the implicit object argument,
6400 otherwise the first element of ARGS is used if needed. The
6401 EXPLICIT_TARGS are explicit template arguments provided.
6402 TEMPLATE_ONLY is true if only template functions should be
6403 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6404 add_function_candidate. */
6405
6406static void
6407add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6408 tree return_type,
6409 tree explicit_targs, bool template_only,
6410 tree conversion_path, tree access_path,
6411 int flags,
6412 struct z_candidate **candidates,
6413 tsubst_flags_t complain)
6414{
6415 tree ctype;
6416 const vec<tree, va_gc> *non_static_args;
6417 bool check_list_ctor = false;
6418 bool check_converting = false;
6419 unification_kind_t strict;
6420 tree ne_fns = NULL_TREE;
6421
6422 if (!fns)
6423 return;
6424
6425 /* Precalculate special handling of constructors and conversion ops. */
6426 tree fn = OVL_FIRST (fns);
6427 if (DECL_CONV_FN_P (fn))
6428 {
6429 check_list_ctor = false;
6430 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6431 if (flags & LOOKUP_NO_CONVERSION)
6432 /* We're doing return_type(x). */
6433 strict = DEDUCE_CONV;
6434 else
6435 /* We're doing x.operator return_type(). */
6436 strict = DEDUCE_EXACT;
6437 /* [over.match.funcs] For conversion functions, the function
6438 is considered to be a member of the class of the implicit
6439 object argument for the purpose of defining the type of
6440 the implicit object parameter. */
6441 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6442 }
6443 else
6444 {
6445 if (DECL_CONSTRUCTOR_P (fn))
6446 {
6447 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6448 /* For list-initialization we consider explicit constructors
6449 and complain if one is chosen. */
6450 check_converting
6451 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6452 == LOOKUP_ONLYCONVERTING);
6453 }
6454 strict = DEDUCE_CALL;
6455 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6456 }
6457
6458 /* P2468: Check if operator== is a rewrite target with first operand
6459 (*args)[0]; for now just do the lookups. */
6460 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6461 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6462 {
6463 tree ne_name = ovl_op_identifier (isass: false, code: NE_EXPR);
6464 if (DECL_CLASS_SCOPE_P (fn))
6465 {
6466 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6467 1, tf_none);
6468 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6469 ne_fns = NULL_TREE;
6470 else
6471 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6472 }
6473 else
6474 {
6475 tree context = decl_namespace_context (fn);
6476 ne_fns = lookup_qualified_name (scope: context, name: ne_name, LOOK_want::NORMAL,
6477 /*complain*/false);
6478 if (ne_fns == error_mark_node
6479 || !is_overloaded_fn (ne_fns))
6480 ne_fns = NULL_TREE;
6481 }
6482 }
6483
6484 if (first_arg)
6485 non_static_args = args;
6486 else
6487 /* Delay creating the implicit this parameter until it is needed. */
6488 non_static_args = NULL;
6489
6490 bool seen_strictly_viable = any_strictly_viable (cands: *candidates);
6491 /* If there's a non-template perfect match, we don't need to consider
6492 templates. So check non-templates first. This optimization is only
6493 really needed for the defaulted copy constructor of tuple and the like
6494 (96926), but it seems like we might as well enable it more generally. */
6495 bool seen_perfect = false;
6496 enum { templates, non_templates, either } which = either;
6497 if (template_only)
6498 which = templates;
6499 else /*if (flags & LOOKUP_DEFAULTED)*/
6500 which = non_templates;
6501
6502 /* During overload resolution, we first consider each function under the
6503 assumption that we'll eventually find a strictly viable candidate.
6504 This allows us to circumvent our defacto behavior when checking
6505 argument conversions and shortcut consideration of the candidate
6506 upon encountering the first bad conversion. If this assumption
6507 turns out to be false, and all candidates end up being non-strictly
6508 viable, then we reconsider such candidates under the defacto behavior.
6509 This trick is important for pruning member function overloads according
6510 to their const/ref-qualifiers (since all 'this' conversions are at
6511 worst bad) without breaking -fpermissive. */
6512 tree bad_fns = NULL_TREE;
6513 bool shortcut_bad_convs = true;
6514
6515 again:
6516 for (tree fn : lkp_range (fns))
6517 {
6518 if (check_converting && DECL_NONCONVERTING_P (fn))
6519 continue;
6520 if (check_list_ctor && !is_list_ctor (fn))
6521 continue;
6522 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6523 continue;
6524 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6525 continue;
6526
6527 tree fn_first_arg = NULL_TREE;
6528 const vec<tree, va_gc> *fn_args = args;
6529
6530 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6531 {
6532 /* Figure out where the object arg comes from. If this
6533 function is a non-static member and we didn't get an
6534 implicit object argument, move it out of args. */
6535 if (first_arg == NULL_TREE)
6536 {
6537 unsigned int ix;
6538 tree arg;
6539 vec<tree, va_gc> *tempvec;
6540 vec_alloc (v&: tempvec, nelems: args->length () - 1);
6541 for (ix = 1; args->iterate (ix, ptr: &arg); ++ix)
6542 tempvec->quick_push (obj: arg);
6543 non_static_args = tempvec;
6544 first_arg = (*args)[0];
6545 }
6546
6547 fn_first_arg = first_arg;
6548 fn_args = non_static_args;
6549 }
6550
6551 /* Don't bother reversing an operator with two identical parameters. */
6552 else if (vec_safe_length (v: args) == 2 && (flags & LOOKUP_REVERSED))
6553 {
6554 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6555 if (same_type_p (TREE_VALUE (parmlist),
6556 TREE_VALUE (TREE_CHAIN (parmlist))))
6557 continue;
6558 }
6559
6560 /* When considering reversed operator==, if there's a corresponding
6561 operator!= in the same scope, it's not a rewrite target. */
6562 if (ne_fns)
6563 {
6564 bool found = false;
6565 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6566 if (0 && !ne.using_p ()
6567 && DECL_NAMESPACE_SCOPE_P (fn)
6568 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6569 /* ??? This kludge excludes inline namespace members for the H
6570 test in spaceship-eq15.C, but I don't see why we would want
6571 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6572 else if (fns_correspond (fn, *ne))
6573 {
6574 found = true;
6575 break;
6576 }
6577 if (found)
6578 continue;
6579 }
6580
6581 if (TREE_CODE (fn) == TEMPLATE_DECL)
6582 {
6583 if (!add_template_candidate (candidates,
6584 tmpl: fn,
6585 ctype,
6586 explicit_targs,
6587 first_arg: fn_first_arg,
6588 arglist: fn_args,
6589 return_type,
6590 access_path,
6591 conversion_path,
6592 flags,
6593 strict,
6594 shortcut_bad_convs,
6595 complain))
6596 continue;
6597 }
6598 else
6599 {
6600 add_function_candidate (candidates,
6601 fn,
6602 ctype,
6603 first_arg: fn_first_arg,
6604 args: fn_args,
6605 access_path,
6606 conversion_path,
6607 flags,
6608 NULL,
6609 shortcut_bad_convs,
6610 complain);
6611 if (perfect_candidate_p (cand: *candidates))
6612 seen_perfect = true;
6613 }
6614
6615 z_candidate *cand = *candidates;
6616 if (cand->viable == 1)
6617 seen_strictly_viable = true;
6618
6619 if (cand->viable == -1
6620 && shortcut_bad_convs
6621 && missing_conversion_p (cand))
6622 {
6623 /* This candidate has been tentatively marked non-strictly viable,
6624 and we didn't compute all argument conversions for it (having
6625 stopped at the first bad conversion). Add the function to BAD_FNS
6626 to fully reconsider later if we don't find any strictly viable
6627 candidates. */
6628 if (complain & (tf_error | tf_conv))
6629 {
6630 bad_fns = lookup_add (fns: fn, lookup: bad_fns);
6631 *candidates = (*candidates)->next;
6632 }
6633 else
6634 /* But if we're in a SFINAE context, just mark this candidate as
6635 unviable outright and avoid potentially reconsidering it.
6636 This is safe to do because in a SFINAE context, performing a bad
6637 conversion is always an error (even with -fpermissive), so a
6638 non-strictly viable candidate is effectively unviable anyway. */
6639 cand->viable = 0;
6640 }
6641 }
6642 if (which == non_templates && !seen_perfect)
6643 {
6644 which = templates;
6645 goto again;
6646 }
6647 else if (which == templates
6648 && !seen_strictly_viable
6649 && shortcut_bad_convs
6650 && bad_fns)
6651 {
6652 /* None of the candidates are strictly viable, so consider again those
6653 functions in BAD_FNS, this time without shortcutting bad conversions
6654 so that all their argument conversions are computed. */
6655 which = either;
6656 fns = bad_fns;
6657 shortcut_bad_convs = false;
6658 goto again;
6659 }
6660}
6661
6662/* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6663 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6664
6665static int
6666op_is_ordered (tree_code code)
6667{
6668 switch (code)
6669 {
6670 // 5. b @= a
6671 case MODIFY_EXPR:
6672 return (flag_strong_eval_order > 1 ? -1 : 0);
6673
6674 // 6. a[b]
6675 case ARRAY_REF:
6676 return (flag_strong_eval_order > 1 ? 1 : 0);
6677
6678 // 1. a.b
6679 // Not overloadable (yet).
6680 // 2. a->b
6681 // Only one argument.
6682 // 3. a->*b
6683 case MEMBER_REF:
6684 // 7. a << b
6685 case LSHIFT_EXPR:
6686 // 8. a >> b
6687 case RSHIFT_EXPR:
6688 // a && b
6689 // Predates P0145R3.
6690 case TRUTH_ANDIF_EXPR:
6691 // a || b
6692 // Predates P0145R3.
6693 case TRUTH_ORIF_EXPR:
6694 // a , b
6695 // Predates P0145R3.
6696 case COMPOUND_EXPR:
6697 return (flag_strong_eval_order ? 1 : 0);
6698
6699 default:
6700 return 0;
6701 }
6702}
6703
6704/* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6705 operator indicated by CODE/CODE2. This function calls itself recursively to
6706 handle C++20 rewritten comparison operator candidates.
6707
6708 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6709 overloads to consider. This parameter is used when instantiating a
6710 dependent operator expression and has the same structure as
6711 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6712
6713static tree
6714add_operator_candidates (z_candidate **candidates,
6715 tree_code code, tree_code code2,
6716 vec<tree, va_gc> *arglist, tree lookups,
6717 int flags, tsubst_flags_t complain)
6718{
6719 z_candidate *start_candidates = *candidates;
6720 bool ismodop = code2 != ERROR_MARK;
6721 tree fnname = ovl_op_identifier (isass: ismodop, code: ismodop ? code2 : code);
6722
6723 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6724 rewrite from, and also when we're looking for the e.g. < operator to use
6725 on the result of <=>. In the latter case, we don't want the flag set in
6726 the candidate, we just want to suppress looking for rewrites. */
6727 bool rewritten = (flags & LOOKUP_REWRITTEN);
6728 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6729 flags &= ~LOOKUP_REWRITTEN;
6730
6731 bool memonly = false;
6732 switch (code)
6733 {
6734 /* =, ->, [], () must be non-static member functions. */
6735 case MODIFY_EXPR:
6736 if (code2 != NOP_EXPR)
6737 break;
6738 /* FALLTHRU */
6739 case COMPONENT_REF:
6740 case ARRAY_REF:
6741 memonly = true;
6742 break;
6743
6744 default:
6745 break;
6746 }
6747
6748 /* Add namespace-scope operators to the list of functions to
6749 consider. */
6750 if (!memonly)
6751 {
6752 tree fns;
6753 if (!lookups)
6754 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6755 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6756 expression, and LOOKUPS is the result of stage 1 name lookup. */
6757 else if (tree found = purpose_member (fnname, lookups))
6758 fns = TREE_VALUE (found);
6759 else
6760 fns = NULL_TREE;
6761 fns = lookup_arg_dependent (fnname, fns, arglist);
6762 add_candidates (fns, NULL_TREE, args: arglist, NULL_TREE,
6763 NULL_TREE, template_only: false, NULL_TREE, NULL_TREE,
6764 flags, candidates, complain);
6765 }
6766
6767 /* Add class-member operators to the candidate set. */
6768 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6769 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6770 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6771 if (CLASS_TYPE_P (arg1_type))
6772 {
6773 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6774 if (fns == error_mark_node)
6775 return error_mark_node;
6776 if (fns)
6777 {
6778 if (code == ARRAY_REF)
6779 {
6780 vec<tree,va_gc> *restlist = make_tree_vector ();
6781 for (unsigned i = 1; i < nargs; ++i)
6782 vec_safe_push (v&: restlist, obj: (*arglist)[i]);
6783 z_candidate *save_cand = *candidates;
6784 add_candidates (BASELINK_FUNCTIONS (fns),
6785 first_arg: (*arglist)[0], args: restlist, NULL_TREE,
6786 NULL_TREE, template_only: false,
6787 BASELINK_BINFO (fns),
6788 BASELINK_ACCESS_BINFO (fns),
6789 flags, candidates, complain);
6790 /* Release the vec if we didn't add a candidate that uses it. */
6791 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6792 if (c->args == restlist)
6793 {
6794 restlist = NULL;
6795 break;
6796 }
6797 release_tree_vector (restlist);
6798 }
6799 else
6800 add_candidates (BASELINK_FUNCTIONS (fns),
6801 NULL_TREE, args: arglist, NULL_TREE,
6802 NULL_TREE, template_only: false,
6803 BASELINK_BINFO (fns),
6804 BASELINK_ACCESS_BINFO (fns),
6805 flags, candidates, complain);
6806 }
6807 }
6808 /* Per [over.match.oper]3.2, if no operand has a class type, then
6809 only non-member functions that have type T1 or reference to
6810 cv-qualified-opt T1 for the first argument, if the first argument
6811 has an enumeration type, or T2 or reference to cv-qualified-opt
6812 T2 for the second argument, if the second argument has an
6813 enumeration type. Filter out those that don't match. */
6814 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6815 {
6816 struct z_candidate **candp, **next;
6817
6818 for (candp = candidates; *candp != start_candidates; candp = next)
6819 {
6820 unsigned i;
6821 z_candidate *cand = *candp;
6822 next = &cand->next;
6823
6824 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6825
6826 for (i = 0; i < nargs; ++i)
6827 {
6828 tree parmtype = TREE_VALUE (parmlist);
6829 tree argtype = unlowered_expr_type ((*arglist)[i]);
6830
6831 if (TYPE_REF_P (parmtype))
6832 parmtype = TREE_TYPE (parmtype);
6833 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6834 && (same_type_ignoring_top_level_qualifiers_p
6835 (argtype, parmtype)))
6836 break;
6837
6838 parmlist = TREE_CHAIN (parmlist);
6839 }
6840
6841 /* No argument has an appropriate type, so remove this
6842 candidate function from the list. */
6843 if (i == nargs)
6844 {
6845 *candp = cand->next;
6846 next = candp;
6847 }
6848 }
6849 }
6850
6851 if (!rewritten)
6852 {
6853 /* The standard says to rewrite built-in candidates, too,
6854 but there's no point. */
6855 add_builtin_candidates (candidates, code, code2, fnname, argv: arglist,
6856 flags, complain);
6857
6858 /* Maybe add C++20 rewritten comparison candidates. */
6859 tree_code rewrite_code = ERROR_MARK;
6860 if (cxx_dialect >= cxx20
6861 && nargs == 2
6862 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6863 switch (code)
6864 {
6865 case LT_EXPR:
6866 case LE_EXPR:
6867 case GT_EXPR:
6868 case GE_EXPR:
6869 case SPACESHIP_EXPR:
6870 rewrite_code = SPACESHIP_EXPR;
6871 break;
6872
6873 case NE_EXPR:
6874 case EQ_EXPR:
6875 rewrite_code = EQ_EXPR;
6876 break;
6877
6878 default:;
6879 }
6880
6881 if (rewrite_code)
6882 {
6883 flags |= LOOKUP_REWRITTEN;
6884 if (rewrite_code != code)
6885 /* Add rewritten candidates in same order. */
6886 add_operator_candidates (candidates, code: rewrite_code, code2: ERROR_MARK,
6887 arglist, lookups, flags, complain);
6888
6889 z_candidate *save_cand = *candidates;
6890
6891 /* Add rewritten candidates in reverse order. */
6892 flags |= LOOKUP_REVERSED;
6893 vec<tree,va_gc> *revlist = make_tree_vector ();
6894 revlist->quick_push (obj: (*arglist)[1]);
6895 revlist->quick_push (obj: (*arglist)[0]);
6896 add_operator_candidates (candidates, code: rewrite_code, code2: ERROR_MARK,
6897 arglist: revlist, lookups, flags, complain);
6898
6899 /* Release the vec if we didn't add a candidate that uses it. */
6900 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6901 if (c->args == revlist)
6902 {
6903 revlist = NULL;
6904 break;
6905 }
6906 release_tree_vector (revlist);
6907 }
6908 }
6909
6910 return NULL_TREE;
6911}
6912
6913tree
6914build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6915 tree arg1, tree arg2, tree arg3, tree lookups,
6916 tree *overload, tsubst_flags_t complain)
6917{
6918 struct z_candidate *candidates = 0, *cand;
6919 releasing_vec arglist;
6920 tree result = NULL_TREE;
6921 bool result_valid_p = false;
6922 enum tree_code code2 = ERROR_MARK;
6923 enum tree_code code_orig_arg1 = ERROR_MARK;
6924 enum tree_code code_orig_arg2 = ERROR_MARK;
6925 bool strict_p;
6926 bool any_viable_p;
6927
6928 auto_cond_timevar tv (TV_OVERLOAD);
6929
6930 if (error_operand_p (t: arg1)
6931 || error_operand_p (t: arg2)
6932 || error_operand_p (t: arg3))
6933 return error_mark_node;
6934
6935 conversion_obstack_sentinel cos;
6936
6937 bool ismodop = code == MODIFY_EXPR;
6938 if (ismodop)
6939 {
6940 code2 = TREE_CODE (arg3);
6941 arg3 = NULL_TREE;
6942 }
6943
6944 tree arg1_type = unlowered_expr_type (arg1);
6945 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6946
6947 arg1 = prep_operand (operand: arg1);
6948
6949 switch (code)
6950 {
6951 case NEW_EXPR:
6952 case VEC_NEW_EXPR:
6953 case VEC_DELETE_EXPR:
6954 case DELETE_EXPR:
6955 /* Use build_operator_new_call and build_op_delete_call instead. */
6956 gcc_unreachable ();
6957
6958 case CALL_EXPR:
6959 /* Use build_op_call instead. */
6960 gcc_unreachable ();
6961
6962 case TRUTH_ORIF_EXPR:
6963 case TRUTH_ANDIF_EXPR:
6964 case TRUTH_AND_EXPR:
6965 case TRUTH_OR_EXPR:
6966 /* These are saved for the sake of warn_logical_operator. */
6967 code_orig_arg1 = TREE_CODE (arg1);
6968 code_orig_arg2 = TREE_CODE (arg2);
6969 break;
6970 case GT_EXPR:
6971 case LT_EXPR:
6972 case GE_EXPR:
6973 case LE_EXPR:
6974 case EQ_EXPR:
6975 case NE_EXPR:
6976 /* These are saved for the sake of maybe_warn_bool_compare. */
6977 code_orig_arg1 = TREE_CODE (arg1_type);
6978 code_orig_arg2 = TREE_CODE (arg2_type);
6979 break;
6980
6981 default:
6982 break;
6983 }
6984
6985 arg2 = prep_operand (operand: arg2);
6986 arg3 = prep_operand (operand: arg3);
6987
6988 if (code == COND_EXPR)
6989 /* Use build_conditional_expr instead. */
6990 gcc_unreachable ();
6991 else if (! OVERLOAD_TYPE_P (arg1_type)
6992 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
6993 goto builtin;
6994
6995 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
6996 {
6997 arg2 = integer_zero_node;
6998 arg2_type = integer_type_node;
6999 }
7000
7001 arglist->quick_push (obj: arg1);
7002 if (arg2 != NULL_TREE)
7003 arglist->quick_push (obj: arg2);
7004 if (arg3 != NULL_TREE)
7005 arglist->quick_push (obj: arg3);
7006
7007 result = add_operator_candidates (candidates: &candidates, code, code2, arglist,
7008 lookups, flags, complain);
7009 if (result == error_mark_node)
7010 return error_mark_node;
7011
7012 switch (code)
7013 {
7014 case COMPOUND_EXPR:
7015 case ADDR_EXPR:
7016 /* For these, the built-in candidates set is empty
7017 [over.match.oper]/3. We don't want non-strict matches
7018 because exact matches are always possible with built-in
7019 operators. The built-in candidate set for COMPONENT_REF
7020 would be empty too, but since there are no such built-in
7021 operators, we accept non-strict matches for them. */
7022 strict_p = true;
7023 break;
7024
7025 default:
7026 strict_p = false;
7027 break;
7028 }
7029
7030 candidates = splice_viable (cands: candidates, strict_p, any_viable_p: &any_viable_p);
7031 if (!any_viable_p)
7032 {
7033 switch (code)
7034 {
7035 case POSTINCREMENT_EXPR:
7036 case POSTDECREMENT_EXPR:
7037 /* Don't try anything fancy if we're not allowed to produce
7038 errors. */
7039 if (!(complain & tf_error))
7040 return error_mark_node;
7041
7042 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7043 distinguish between prefix and postfix ++ and
7044 operator++() was used for both, so we allow this with
7045 -fpermissive. */
7046 else
7047 {
7048 tree fnname = ovl_op_identifier (isass: ismodop, code: ismodop ? code2 : code);
7049 const char *msg = (flag_permissive)
7050 ? G_("no %<%D(int)%> declared for postfix %qs,"
7051 " trying prefix operator instead")
7052 : G_("no %<%D(int)%> declared for postfix %qs");
7053 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7054 }
7055
7056 if (!flag_permissive)
7057 return error_mark_node;
7058
7059 if (code == POSTINCREMENT_EXPR)
7060 code = PREINCREMENT_EXPR;
7061 else
7062 code = PREDECREMENT_EXPR;
7063 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7064 NULL_TREE, lookups, overload, complain);
7065 break;
7066
7067 /* The caller will deal with these. */
7068 case ADDR_EXPR:
7069 case COMPOUND_EXPR:
7070 case COMPONENT_REF:
7071 case CO_AWAIT_EXPR:
7072 result = NULL_TREE;
7073 result_valid_p = true;
7074 break;
7075
7076 default:
7077 if (complain & tf_error)
7078 {
7079 /* If one of the arguments of the operator represents
7080 an invalid use of member function pointer, try to report
7081 a meaningful error ... */
7082 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7083 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7084 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7085 /* We displayed the error message. */;
7086 else
7087 {
7088 /* ... Otherwise, report the more generic
7089 "no matching operator found" error */
7090 auto_diagnostic_group d;
7091 op_error (loc, code, code2, arg1, arg2, arg3, match: false);
7092 print_z_candidates (loc, candidates);
7093 }
7094 }
7095 result = error_mark_node;
7096 break;
7097 }
7098 }
7099 else
7100 {
7101 cand = tourney (candidates, complain);
7102 if (cand == 0)
7103 {
7104 if (complain & tf_error)
7105 {
7106 auto_diagnostic_group d;
7107 op_error (loc, code, code2, arg1, arg2, arg3, match: true);
7108 print_z_candidates (loc, candidates);
7109 }
7110 result = error_mark_node;
7111 if (overload)
7112 *overload = error_mark_node;
7113 }
7114 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7115 {
7116 if (overload)
7117 *overload = cand->fn;
7118
7119 if (resolve_args (args: arglist, complain) == NULL)
7120 result = error_mark_node;
7121 else
7122 {
7123 tsubst_flags_t ocomplain = complain;
7124 if (cand->rewritten ())
7125 /* We'll wrap this call in another one. */
7126 ocomplain &= ~tf_decltype;
7127 if (cand->reversed ())
7128 {
7129 /* We swapped these in add_candidate, swap them back now. */
7130 std::swap (a&: cand->convs[0], b&: cand->convs[1]);
7131 if (cand->fn == current_function_decl)
7132 warning_at (loc, 0, "in C++20 this comparison calls the "
7133 "current function recursively with reversed "
7134 "arguments");
7135 }
7136 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7137 }
7138
7139 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7140 /* There won't be a CALL_EXPR. */;
7141 else if (result && result != error_mark_node)
7142 {
7143 tree call = extract_call_expr (result);
7144 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7145
7146 /* Specify evaluation order as per P0145R2. */
7147 CALL_EXPR_ORDERED_ARGS (call) = false;
7148 switch (op_is_ordered (code))
7149 {
7150 case -1:
7151 CALL_EXPR_REVERSE_ARGS (call) = true;
7152 break;
7153
7154 case 1:
7155 CALL_EXPR_ORDERED_ARGS (call) = true;
7156 break;
7157
7158 default:
7159 break;
7160 }
7161 }
7162
7163 /* If this was a C++20 rewritten comparison, adjust the result. */
7164 if (cand->rewritten ())
7165 {
7166 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7167 if (overload)
7168 *overload = NULL_TREE;
7169 switch (code)
7170 {
7171 case EQ_EXPR:
7172 gcc_checking_assert (cand->reversed ());
7173 gcc_fallthrough ();
7174 case NE_EXPR:
7175 if (result == error_mark_node)
7176 ;
7177 /* If a rewritten operator== candidate is selected by
7178 overload resolution for an operator @, its return type
7179 shall be cv bool.... */
7180 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7181 {
7182 if (complain & tf_error)
7183 {
7184 auto_diagnostic_group d;
7185 error_at (loc, "return type of %qD is not %qs",
7186 cand->fn, "bool");
7187 inform (loc, "used as rewritten candidate for "
7188 "comparison of %qT and %qT",
7189 arg1_type, arg2_type);
7190 }
7191 result = error_mark_node;
7192 }
7193 else if (code == NE_EXPR)
7194 /* !(y == x) or !(x == y) */
7195 result = build1_loc (loc, code: TRUTH_NOT_EXPR,
7196 boolean_type_node, arg1: result);
7197 break;
7198
7199 /* If a rewritten operator<=> candidate is selected by
7200 overload resolution for an operator @, x @ y is
7201 interpreted as 0 @ (y <=> x) if the selected candidate is
7202 a synthesized candidate with reversed order of parameters,
7203 or (x <=> y) @ 0 otherwise, using the selected rewritten
7204 operator<=> candidate. */
7205 case SPACESHIP_EXPR:
7206 if (!cand->reversed ())
7207 /* We're in the build_new_op call below for an outer
7208 reversed call; we don't need to do anything more. */
7209 break;
7210 gcc_fallthrough ();
7211 case LT_EXPR:
7212 case LE_EXPR:
7213 case GT_EXPR:
7214 case GE_EXPR:
7215 {
7216 tree lhs = result;
7217 tree rhs = integer_zero_node;
7218 if (cand->reversed ())
7219 std::swap (a&: lhs, b&: rhs);
7220 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7221 result = build_new_op (loc, code,
7222 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7223 arg1: lhs, arg2: rhs, NULL_TREE, lookups,
7224 NULL, complain);
7225 }
7226 break;
7227
7228 default:
7229 gcc_unreachable ();
7230 }
7231 }
7232
7233 /* In an expression of the form `a[]' where cand->fn
7234 which is operator[] turns out to be a static member function,
7235 `a' is none-the-less evaluated. */
7236 if (code == ARRAY_REF)
7237 result = keep_unused_object_arg (result, obj: arg1, fn: cand->fn);
7238 }
7239 else
7240 {
7241 /* Give any warnings we noticed during overload resolution. */
7242 if (cand->warnings && (complain & tf_warning))
7243 {
7244 struct candidate_warning *w;
7245 for (w = cand->warnings; w; w = w->next)
7246 joust (cand, w->loser, 1, complain);
7247 }
7248
7249 /* Check for comparison of different enum types. */
7250 switch (code)
7251 {
7252 case GT_EXPR:
7253 case LT_EXPR:
7254 case GE_EXPR:
7255 case LE_EXPR:
7256 case EQ_EXPR:
7257 case NE_EXPR:
7258 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7259 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7260 && (TYPE_MAIN_VARIANT (arg1_type)
7261 != TYPE_MAIN_VARIANT (arg2_type))
7262 && (complain & tf_warning))
7263 warning_at (loc, OPT_Wenum_compare,
7264 "comparison between %q#T and %q#T",
7265 arg1_type, arg2_type);
7266 break;
7267 default:
7268 break;
7269 }
7270
7271 /* "If a built-in candidate is selected by overload resolution, the
7272 operands of class type are converted to the types of the
7273 corresponding parameters of the selected operation function,
7274 except that the second standard conversion sequence of a
7275 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7276 conversion *conv = cand->convs[0];
7277 if (conv->user_conv_p)
7278 {
7279 conv = strip_standard_conversion (conv);
7280 arg1 = convert_like (conv, arg1, complain);
7281 }
7282
7283 if (arg2)
7284 {
7285 conv = cand->convs[1];
7286 if (conv->user_conv_p)
7287 {
7288 conv = strip_standard_conversion (conv);
7289 arg2 = convert_like (conv, arg2, complain);
7290 }
7291 }
7292
7293 if (arg3)
7294 {
7295 conv = cand->convs[2];
7296 if (conv->user_conv_p)
7297 {
7298 conv = strip_standard_conversion (conv);
7299 arg3 = convert_like (conv, arg3, complain);
7300 }
7301 }
7302 }
7303 }
7304
7305 if (result || result_valid_p)
7306 return result;
7307
7308 builtin:
7309 switch (code)
7310 {
7311 case MODIFY_EXPR:
7312 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7313
7314 case INDIRECT_REF:
7315 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7316
7317 case TRUTH_ANDIF_EXPR:
7318 case TRUTH_ORIF_EXPR:
7319 case TRUTH_AND_EXPR:
7320 case TRUTH_OR_EXPR:
7321 if ((complain & tf_warning) && !processing_template_decl)
7322 warn_logical_operator (loc, code, boolean_type_node,
7323 code_orig_arg1, arg1,
7324 code_orig_arg2, arg2);
7325 /* Fall through. */
7326 case GT_EXPR:
7327 case LT_EXPR:
7328 case GE_EXPR:
7329 case LE_EXPR:
7330 case EQ_EXPR:
7331 case NE_EXPR:
7332 if ((complain & tf_warning)
7333 && ((code_orig_arg1 == BOOLEAN_TYPE)
7334 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7335 maybe_warn_bool_compare (loc, code, arg1, arg2);
7336 if (complain & tf_warning && warn_tautological_compare)
7337 warn_tautological_cmp (loc, code, arg1, arg2);
7338 /* Fall through. */
7339 case SPACESHIP_EXPR:
7340 case PLUS_EXPR:
7341 case MINUS_EXPR:
7342 case MULT_EXPR:
7343 case TRUNC_DIV_EXPR:
7344 case MAX_EXPR:
7345 case MIN_EXPR:
7346 case LSHIFT_EXPR:
7347 case RSHIFT_EXPR:
7348 case TRUNC_MOD_EXPR:
7349 case BIT_AND_EXPR:
7350 case BIT_IOR_EXPR:
7351 case BIT_XOR_EXPR:
7352 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7353
7354 case UNARY_PLUS_EXPR:
7355 case NEGATE_EXPR:
7356 case BIT_NOT_EXPR:
7357 case TRUTH_NOT_EXPR:
7358 case PREINCREMENT_EXPR:
7359 case POSTINCREMENT_EXPR:
7360 case PREDECREMENT_EXPR:
7361 case POSTDECREMENT_EXPR:
7362 case REALPART_EXPR:
7363 case IMAGPART_EXPR:
7364 case ABS_EXPR:
7365 case CO_AWAIT_EXPR:
7366 return cp_build_unary_op (code, arg1, false, complain);
7367
7368 case ARRAY_REF:
7369 return cp_build_array_ref (input_location, arg1, arg2, complain);
7370
7371 case MEMBER_REF:
7372 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7373 RO_ARROW_STAR,
7374 complain),
7375 arg2, complain);
7376
7377 /* The caller will deal with these. */
7378 case ADDR_EXPR:
7379 case COMPONENT_REF:
7380 case COMPOUND_EXPR:
7381 return NULL_TREE;
7382
7383 default:
7384 gcc_unreachable ();
7385 }
7386 return NULL_TREE;
7387}
7388
7389/* Build a new call to operator[]. This may change ARGS. */
7390
7391tree
7392build_op_subscript (const op_location_t &loc, tree obj,
7393 vec<tree, va_gc> **args, tree *overload,
7394 tsubst_flags_t complain)
7395{
7396 struct z_candidate *candidates = 0, *cand;
7397 tree fns, first_mem_arg = NULL_TREE;
7398 bool any_viable_p;
7399 tree result = NULL_TREE;
7400
7401 auto_cond_timevar tv (TV_OVERLOAD);
7402
7403 obj = mark_lvalue_use (obj);
7404
7405 if (error_operand_p (t: obj))
7406 return error_mark_node;
7407
7408 tree type = TREE_TYPE (obj);
7409
7410 obj = prep_operand (operand: obj);
7411
7412 if (TYPE_BINFO (type))
7413 {
7414 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (code: ARRAY_REF),
7415 1, complain);
7416 if (fns == error_mark_node)
7417 return error_mark_node;
7418 }
7419 else
7420 fns = NULL_TREE;
7421
7422 if (args != NULL && *args != NULL)
7423 {
7424 *args = resolve_args (args: *args, complain);
7425 if (*args == NULL)
7426 return error_mark_node;
7427 }
7428
7429 conversion_obstack_sentinel cos;
7430
7431 if (fns)
7432 {
7433 first_mem_arg = obj;
7434
7435 add_candidates (BASELINK_FUNCTIONS (fns),
7436 first_arg: first_mem_arg, args: *args, NULL_TREE,
7437 NULL_TREE, template_only: false,
7438 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7439 LOOKUP_NORMAL, candidates: &candidates, complain);
7440 }
7441
7442 /* Be strict here because if we choose a bad conversion candidate, the
7443 errors we get won't mention the call context. */
7444 candidates = splice_viable (cands: candidates, strict_p: true, any_viable_p: &any_viable_p);
7445 if (!any_viable_p)
7446 {
7447 if (complain & tf_error)
7448 {
7449 auto_diagnostic_group d;
7450 error ("no match for call to %<%T::operator[] (%A)%>",
7451 TREE_TYPE (obj), build_tree_list_vec (*args));
7452 print_z_candidates (loc, candidates);
7453 }
7454 result = error_mark_node;
7455 }
7456 else
7457 {
7458 cand = tourney (candidates, complain);
7459 if (cand == 0)
7460 {
7461 if (complain & tf_error)
7462 {
7463 auto_diagnostic_group d;
7464 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7465 TREE_TYPE (obj), build_tree_list_vec (*args));
7466 print_z_candidates (loc, candidates);
7467 }
7468 result = error_mark_node;
7469 }
7470 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7471 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7472 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7473 {
7474 if (overload)
7475 *overload = cand->fn;
7476 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7477 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7478 /* There won't be a CALL_EXPR. */;
7479 else if (result && result != error_mark_node)
7480 {
7481 tree call = extract_call_expr (result);
7482 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7483
7484 /* Specify evaluation order as per P0145R2. */
7485 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (code: ARRAY_REF) == 1;
7486 }
7487
7488 /* In an expression of the form `a[]' where cand->fn
7489 which is operator[] turns out to be a static member function,
7490 `a' is none-the-less evaluated. */
7491 result = keep_unused_object_arg (result, obj, fn: cand->fn);
7492 }
7493 else
7494 gcc_unreachable ();
7495 }
7496
7497 return result;
7498}
7499
7500/* CALL was returned by some call-building function; extract the actual
7501 CALL_EXPR from any bits that have been tacked on, e.g. by
7502 convert_from_reference. */
7503
7504tree
7505extract_call_expr (tree call)
7506{
7507 while (TREE_CODE (call) == COMPOUND_EXPR)
7508 call = TREE_OPERAND (call, 1);
7509 if (REFERENCE_REF_P (call))
7510 call = TREE_OPERAND (call, 0);
7511 if (TREE_CODE (call) == TARGET_EXPR)
7512 call = TARGET_EXPR_INITIAL (call);
7513 if (cxx_dialect >= cxx20)
7514 switch (TREE_CODE (call))
7515 {
7516 /* C++20 rewritten comparison operators. */
7517 case TRUTH_NOT_EXPR:
7518 call = TREE_OPERAND (call, 0);
7519 break;
7520 case LT_EXPR:
7521 case LE_EXPR:
7522 case GT_EXPR:
7523 case GE_EXPR:
7524 case SPACESHIP_EXPR:
7525 {
7526 tree op0 = TREE_OPERAND (call, 0);
7527 if (integer_zerop (op0))
7528 call = TREE_OPERAND (call, 1);
7529 else
7530 call = op0;
7531 }
7532 break;
7533 default:;
7534 }
7535
7536 if (TREE_CODE (call) != CALL_EXPR
7537 && TREE_CODE (call) != AGGR_INIT_EXPR
7538 && call != error_mark_node)
7539 return NULL_TREE;
7540 return call;
7541}
7542
7543/* Returns true if FN has two parameters, of which the second has type
7544 size_t. */
7545
7546static bool
7547second_parm_is_size_t (tree fn)
7548{
7549 tree t = FUNCTION_ARG_CHAIN (fn);
7550 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7551 return false;
7552 t = TREE_CHAIN (t);
7553 if (t == void_list_node)
7554 return true;
7555 return false;
7556}
7557
7558/* True if T, an allocation function, has std::align_val_t as its second
7559 argument. */
7560
7561bool
7562aligned_allocation_fn_p (tree t)
7563{
7564 if (!aligned_new_threshold)
7565 return false;
7566
7567 tree a = FUNCTION_ARG_CHAIN (t);
7568 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7569}
7570
7571/* True if T is std::destroying_delete_t. */
7572
7573static bool
7574std_destroying_delete_t_p (tree t)
7575{
7576 return (TYPE_CONTEXT (t) == std_node
7577 && id_equal (TYPE_IDENTIFIER (t), str: "destroying_delete_t"));
7578}
7579
7580/* A deallocation function with at least two parameters whose second parameter
7581 type is of type std::destroying_delete_t is a destroying operator delete. A
7582 destroying operator delete shall be a class member function named operator
7583 delete. [ Note: Array deletion cannot use a destroying operator
7584 delete. --end note ] */
7585
7586tree
7587destroying_delete_p (tree t)
7588{
7589 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7590 if (!a || !TREE_CHAIN (a))
7591 return NULL_TREE;
7592 tree type = TREE_VALUE (TREE_CHAIN (a));
7593 return std_destroying_delete_t_p (t: type) ? type : NULL_TREE;
7594}
7595
7596struct dealloc_info
7597{
7598 bool sized;
7599 bool aligned;
7600 tree destroying;
7601};
7602
7603/* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7604 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7605 non-null, also set *DI. */
7606
7607static bool
7608usual_deallocation_fn_p (tree t, dealloc_info *di)
7609{
7610 if (di) *di = dealloc_info();
7611
7612 /* A template instance is never a usual deallocation function,
7613 regardless of its signature. */
7614 if (TREE_CODE (t) == TEMPLATE_DECL
7615 || primary_template_specialization_p (t))
7616 return false;
7617
7618 /* A usual deallocation function is a deallocation function whose parameters
7619 after the first are
7620 - optionally, a parameter of type std::destroying_delete_t, then
7621 - optionally, a parameter of type std::size_t, then
7622 - optionally, a parameter of type std::align_val_t. */
7623 bool global = DECL_NAMESPACE_SCOPE_P (t);
7624 tree chain = FUNCTION_ARG_CHAIN (t);
7625 if (chain && destroying_delete_p (t))
7626 {
7627 if (di) di->destroying = TREE_VALUE (chain);
7628 chain = TREE_CHAIN (chain);
7629 }
7630 if (chain
7631 && (!global || flag_sized_deallocation)
7632 && same_type_p (TREE_VALUE (chain), size_type_node))
7633 {
7634 if (di) di->sized = true;
7635 chain = TREE_CHAIN (chain);
7636 }
7637 if (chain && aligned_new_threshold
7638 && same_type_p (TREE_VALUE (chain), align_type_node))
7639 {
7640 if (di) di->aligned = true;
7641 chain = TREE_CHAIN (chain);
7642 }
7643 return (chain == void_list_node);
7644}
7645
7646/* Just return whether FN is a usual deallocation function. */
7647
7648bool
7649usual_deallocation_fn_p (tree fn)
7650{
7651 return usual_deallocation_fn_p (t: fn, NULL);
7652}
7653
7654/* Build a call to operator delete. This has to be handled very specially,
7655 because the restrictions on what signatures match are different from all
7656 other call instances. For a normal delete, only a delete taking (void *)
7657 or (void *, size_t) is accepted. For a placement delete, only an exact
7658 match with the placement new is accepted.
7659
7660 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7661 ADDR is the pointer to be deleted.
7662 SIZE is the size of the memory block to be deleted.
7663 GLOBAL_P is true if the delete-expression should not consider
7664 class-specific delete operators.
7665 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7666
7667 If this call to "operator delete" is being generated as part to
7668 deallocate memory allocated via a new-expression (as per [expr.new]
7669 which requires that if the initialization throws an exception then
7670 we call a deallocation function), then ALLOC_FN is the allocation
7671 function. */
7672
7673tree
7674build_op_delete_call (enum tree_code code, tree addr, tree size,
7675 bool global_p, tree placement,
7676 tree alloc_fn, tsubst_flags_t complain)
7677{
7678 tree fn = NULL_TREE;
7679 tree fns, fnname, type, t;
7680 dealloc_info di_fn = { };
7681
7682 if (addr == error_mark_node)
7683 return error_mark_node;
7684
7685 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7686
7687 fnname = ovl_op_identifier (isass: false, code);
7688
7689 if (CLASS_TYPE_P (type)
7690 && COMPLETE_TYPE_P (complete_type (type))
7691 && !global_p)
7692 /* In [class.free]
7693
7694 If the result of the lookup is ambiguous or inaccessible, or if
7695 the lookup selects a placement deallocation function, the
7696 program is ill-formed.
7697
7698 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7699 {
7700 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7701 if (fns == error_mark_node)
7702 return error_mark_node;
7703 }
7704 else
7705 fns = NULL_TREE;
7706
7707 if (fns == NULL_TREE)
7708 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7709
7710 /* Strip const and volatile from addr. */
7711 tree oaddr = addr;
7712 addr = cp_convert (ptr_type_node, addr, complain);
7713
7714 tree excluded_destroying = NULL_TREE;
7715
7716 if (placement)
7717 {
7718 /* "A declaration of a placement deallocation function matches the
7719 declaration of a placement allocation function if it has the same
7720 number of parameters and, after parameter transformations (8.3.5),
7721 all parameter types except the first are identical."
7722
7723 So we build up the function type we want and ask instantiate_type
7724 to get it for us. */
7725 t = FUNCTION_ARG_CHAIN (alloc_fn);
7726 t = tree_cons (NULL_TREE, ptr_type_node, t);
7727 t = build_function_type (void_type_node, t);
7728
7729 fn = instantiate_type (t, fns, tf_none);
7730 if (fn == error_mark_node)
7731 return NULL_TREE;
7732
7733 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7734
7735 /* "If the lookup finds the two-parameter form of a usual deallocation
7736 function (3.7.4.2) and that function, considered as a placement
7737 deallocation function, would have been selected as a match for the
7738 allocation function, the program is ill-formed." */
7739 if (second_parm_is_size_t (fn))
7740 {
7741 const char *const msg1
7742 = G_("exception cleanup for this placement new selects "
7743 "non-placement %<operator delete%>");
7744 const char *const msg2
7745 = G_("%qD is a usual (non-placement) deallocation "
7746 "function in C++14 (or with %<-fsized-deallocation%>)");
7747
7748 /* But if the class has an operator delete (void *), then that is
7749 the usual deallocation function, so we shouldn't complain
7750 about using the operator delete (void *, size_t). */
7751 if (DECL_CLASS_SCOPE_P (fn))
7752 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7753 {
7754 if (usual_deallocation_fn_p (fn: elt)
7755 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7756 goto ok;
7757 }
7758 /* Before C++14 a two-parameter global deallocation function is
7759 always a placement deallocation function, but warn if
7760 -Wc++14-compat. */
7761 else if (!flag_sized_deallocation)
7762 {
7763 if (complain & tf_warning)
7764 {
7765 auto_diagnostic_group d;
7766 if (warning (OPT_Wc__14_compat, msg1))
7767 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7768 }
7769 goto ok;
7770 }
7771
7772 if (complain & tf_warning_or_error)
7773 {
7774 auto_diagnostic_group d;
7775 if (permerror (input_location, msg1))
7776 {
7777 /* Only mention C++14 for namespace-scope delete. */
7778 if (DECL_NAMESPACE_SCOPE_P (fn))
7779 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7780 else
7781 inform (DECL_SOURCE_LOCATION (fn),
7782 "%qD is a usual (non-placement) deallocation "
7783 "function", fn);
7784 }
7785 }
7786 else
7787 return error_mark_node;
7788 ok:;
7789 }
7790 }
7791 else
7792 /* "Any non-placement deallocation function matches a non-placement
7793 allocation function. If the lookup finds a single matching
7794 deallocation function, that function will be called; otherwise, no
7795 deallocation function will be called." */
7796 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7797 {
7798 dealloc_info di_elt;
7799 if (usual_deallocation_fn_p (t: elt, di: &di_elt))
7800 {
7801 /* If we're called for an EH cleanup in a new-expression, we can't
7802 use a destroying delete; the exception was thrown before the
7803 object was constructed. */
7804 if (alloc_fn && di_elt.destroying)
7805 {
7806 excluded_destroying = elt;
7807 continue;
7808 }
7809
7810 if (!fn)
7811 {
7812 fn = elt;
7813 di_fn = di_elt;
7814 continue;
7815 }
7816
7817 /* -- If any of the deallocation functions is a destroying
7818 operator delete, all deallocation functions that are not
7819 destroying operator deletes are eliminated from further
7820 consideration. */
7821 if (di_elt.destroying != di_fn.destroying)
7822 {
7823 if (di_elt.destroying)
7824 {
7825 fn = elt;
7826 di_fn = di_elt;
7827 }
7828 continue;
7829 }
7830
7831 /* -- If the type has new-extended alignment, a function with a
7832 parameter of type std::align_val_t is preferred; otherwise a
7833 function without such a parameter is preferred. If exactly one
7834 preferred function is found, that function is selected and the
7835 selection process terminates. If more than one preferred
7836 function is found, all non-preferred functions are eliminated
7837 from further consideration. */
7838 if (aligned_new_threshold)
7839 {
7840 bool want_align = type_has_new_extended_alignment (type);
7841 if (di_elt.aligned != di_fn.aligned)
7842 {
7843 if (want_align == di_elt.aligned)
7844 {
7845 fn = elt;
7846 di_fn = di_elt;
7847 }
7848 continue;
7849 }
7850 }
7851
7852 /* -- If the deallocation functions have class scope, the one
7853 without a parameter of type std::size_t is selected. */
7854 bool want_size;
7855 if (DECL_CLASS_SCOPE_P (fn))
7856 want_size = false;
7857
7858 /* -- If the type is complete and if, for the second alternative
7859 (delete array) only, the operand is a pointer to a class type
7860 with a non-trivial destructor or a (possibly multi-dimensional)
7861 array thereof, the function with a parameter of type std::size_t
7862 is selected.
7863
7864 -- Otherwise, it is unspecified whether a deallocation function
7865 with a parameter of type std::size_t is selected. */
7866 else
7867 {
7868 want_size = COMPLETE_TYPE_P (type);
7869 if (code == VEC_DELETE_EXPR
7870 && !TYPE_VEC_NEW_USES_COOKIE (type))
7871 /* We need a cookie to determine the array size. */
7872 want_size = false;
7873 }
7874 gcc_assert (di_fn.sized != di_elt.sized);
7875 if (want_size == di_elt.sized)
7876 {
7877 fn = elt;
7878 di_fn = di_elt;
7879 }
7880 }
7881 }
7882
7883 /* If we have a matching function, call it. */
7884 if (fn)
7885 {
7886 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7887
7888 /* If the FN is a member function, make sure that it is
7889 accessible. */
7890 if (BASELINK_P (fns))
7891 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7892 complain);
7893
7894 /* Core issue 901: It's ok to new a type with deleted delete. */
7895 if (DECL_DELETED_FN (fn) && alloc_fn)
7896 return NULL_TREE;
7897
7898 tree ret;
7899 if (placement)
7900 {
7901 /* The placement args might not be suitable for overload
7902 resolution at this point, so build the call directly. */
7903 int nargs = call_expr_nargs (placement);
7904 tree *argarray = XALLOCAVEC (tree, nargs);
7905 int i;
7906 argarray[0] = addr;
7907 for (i = 1; i < nargs; i++)
7908 argarray[i] = CALL_EXPR_ARG (placement, i);
7909 if (!mark_used (fn, complain) && !(complain & tf_error))
7910 return error_mark_node;
7911 ret = build_cxx_call (fn, nargs, argarray, complain);
7912 }
7913 else
7914 {
7915 tree destroying = di_fn.destroying;
7916 if (destroying)
7917 {
7918 /* Strip const and volatile from addr but retain the type of the
7919 object. */
7920 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7921 rtype = cv_unqualified (rtype);
7922 rtype = TYPE_POINTER_TO (rtype);
7923 addr = cp_convert (rtype, oaddr, complain);
7924 destroying = build_functional_cast (input_location,
7925 destroying, NULL_TREE,
7926 complain);
7927 }
7928
7929 releasing_vec args;
7930 args->quick_push (obj: addr);
7931 if (destroying)
7932 args->quick_push (obj: destroying);
7933 if (di_fn.sized)
7934 args->quick_push (obj: size);
7935 if (di_fn.aligned)
7936 {
7937 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7938 args->quick_push (obj: al);
7939 }
7940 ret = cp_build_function_call_vec (fn, &args, complain);
7941 }
7942
7943 /* Set this flag for all callers of this function. In addition to
7944 delete-expressions, this is called for deallocating coroutine state;
7945 treat that as an implicit delete-expression. This is also called for
7946 the delete if the constructor throws in a new-expression, and for a
7947 deleting destructor (which implements a delete-expression). */
7948 /* But leave this flag off for destroying delete to avoid wrong
7949 assumptions in the optimizers. */
7950 tree call = extract_call_expr (call: ret);
7951 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (t: fn))
7952 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7953
7954 return ret;
7955 }
7956
7957 /* If there's only a destroying delete that we can't use because the
7958 object isn't constructed yet, and we used global new, use global
7959 delete as well. */
7960 if (excluded_destroying
7961 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
7962 return build_op_delete_call (code, addr, size, global_p: true, placement,
7963 alloc_fn, complain);
7964
7965 /* [expr.new]
7966
7967 If no unambiguous matching deallocation function can be found,
7968 propagating the exception does not cause the object's memory to
7969 be freed. */
7970 if (alloc_fn)
7971 {
7972 if ((complain & tf_warning)
7973 && !placement)
7974 {
7975 bool w = warning (0,
7976 "no corresponding deallocation function for %qD",
7977 alloc_fn);
7978 if (w && excluded_destroying)
7979 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
7980 "delete %qD cannot be used to release the allocated memory"
7981 " if the initialization throws because the object is not "
7982 "constructed yet", excluded_destroying);
7983 }
7984 return NULL_TREE;
7985 }
7986
7987 if (complain & tf_error)
7988 error ("no suitable %<operator %s%> for %qT",
7989 OVL_OP_INFO (false, code)->name, type);
7990 return error_mark_node;
7991}
7992
7993/* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
7994 in the diagnostics.
7995
7996 If ISSUE_ERROR is true, then issue an error about the access, followed
7997 by a note showing the declaration. Otherwise, just show the note.
7998
7999 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8000 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8001 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8002 would be because DECL was private). If not using NO_ACCESS_REASON,
8003 then it must be ak_none, and the access failure reason will be
8004 figured out by looking at the protection of DECL. */
8005
8006void
8007complain_about_access (tree decl, tree diag_decl, tree diag_location,
8008 bool issue_error, access_kind no_access_reason)
8009{
8010 /* If we have not already figured out why DECL is inaccessible... */
8011 if (no_access_reason == ak_none)
8012 {
8013 /* Examine the access of DECL to find out why. */
8014 if (TREE_PRIVATE (decl))
8015 no_access_reason = ak_private;
8016 else if (TREE_PROTECTED (decl))
8017 no_access_reason = ak_protected;
8018 }
8019
8020 /* Now generate an error message depending on calculated access. */
8021 if (no_access_reason == ak_private)
8022 {
8023 if (issue_error)
8024 error ("%q#D is private within this context", diag_decl);
8025 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8026 }
8027 else if (no_access_reason == ak_protected)
8028 {
8029 if (issue_error)
8030 error ("%q#D is protected within this context", diag_decl);
8031 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8032 }
8033 /* Couldn't figure out why DECL is inaccesible, so just say it's
8034 inaccessible. */
8035 else
8036 {
8037 if (issue_error)
8038 error ("%q#D is inaccessible within this context", diag_decl);
8039 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8040 }
8041}
8042
8043/* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8044 bitwise or of LOOKUP_* values. If any errors are warnings are
8045 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8046 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8047 to NULL. */
8048
8049static tree
8050build_temp (tree expr, tree type, int flags,
8051 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8052{
8053 int savew, savee;
8054
8055 *diagnostic_kind = DK_UNSPECIFIED;
8056
8057 /* If the source is a packed field, calling the copy constructor will require
8058 binding the field to the reference parameter to the copy constructor, and
8059 we'll end up with an infinite loop. If we can use a bitwise copy, then
8060 do that now. */
8061 if ((lvalue_kind (expr) & clk_packed)
8062 && CLASS_TYPE_P (TREE_TYPE (expr))
8063 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8064 return get_target_expr (expr, complain);
8065
8066 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8067 But it turns out to be a subexpression, so perform temporary
8068 materialization now. */
8069 if (TREE_CODE (expr) == CALL_EXPR
8070 && CLASS_TYPE_P (type)
8071 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8072 expr = build_cplus_new (type, expr, complain);
8073
8074 savew = warningcount + werrorcount, savee = errorcount;
8075 releasing_vec args (make_tree_vector_single (expr));
8076 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8077 &args, type, flags, complain);
8078 if (warningcount + werrorcount > savew)
8079 *diagnostic_kind = DK_WARNING;
8080 else if (errorcount > savee)
8081 *diagnostic_kind = DK_ERROR;
8082 return expr;
8083}
8084
8085/* Get any location for EXPR, falling back to input_location.
8086
8087 If the result is in a system header and is the virtual location for
8088 a token coming from the expansion of a macro, unwind it to the
8089 location of the expansion point of the macro (e.g. to avoid the
8090 diagnostic being suppressed for expansions of NULL where "NULL" is
8091 in a system header). */
8092
8093static location_t
8094get_location_for_expr_unwinding_for_system_header (tree expr)
8095{
8096 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8097 loc = expansion_point_location_if_in_system_header (loc);
8098 return loc;
8099}
8100
8101/* Perform warnings about peculiar, but valid, conversions from/to NULL.
8102 Also handle a subset of zero as null warnings.
8103 EXPR is implicitly converted to type TOTYPE.
8104 FN and ARGNUM are used for diagnostics. */
8105
8106static void
8107conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8108{
8109 /* Issue warnings about peculiar, but valid, uses of NULL. */
8110 if (TREE_CODE (totype) != BOOLEAN_TYPE
8111 && ARITHMETIC_TYPE_P (totype)
8112 && null_node_p (expr))
8113 {
8114 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8115 if (fn)
8116 {
8117 auto_diagnostic_group d;
8118 if (warning_at (loc, OPT_Wconversion_null,
8119 "passing NULL to non-pointer argument %P of %qD",
8120 argnum, fn))
8121 inform (get_fndecl_argument_location (fn, argnum),
8122 " declared here");
8123 }
8124 else
8125 warning_at (loc, OPT_Wconversion_null,
8126 "converting to non-pointer type %qT from NULL", totype);
8127 }
8128
8129 /* Issue warnings if "false" is converted to a NULL pointer */
8130 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8131 && TYPE_PTR_P (totype))
8132 {
8133 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8134 if (fn)
8135 {
8136 auto_diagnostic_group d;
8137 if (warning_at (loc, OPT_Wconversion_null,
8138 "converting %<false%> to pointer type for argument "
8139 "%P of %qD", argnum, fn))
8140 inform (get_fndecl_argument_location (fn, argnum),
8141 " declared here");
8142 }
8143 else
8144 warning_at (loc, OPT_Wconversion_null,
8145 "converting %<false%> to pointer type %qT", totype);
8146 }
8147 /* Handle zero as null pointer warnings for cases other
8148 than EQ_EXPR and NE_EXPR */
8149 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8150 && null_ptr_cst_p (t: expr))
8151 {
8152 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8153 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8154 }
8155}
8156
8157/* We gave a diagnostic during a conversion. If this was in the second
8158 standard conversion sequence of a user-defined conversion sequence, say
8159 which user-defined conversion. */
8160
8161static void
8162maybe_print_user_conv_context (conversion *convs)
8163{
8164 if (convs->user_conv_p)
8165 for (conversion *t = convs; t; t = next_conversion (conv: t))
8166 if (t->kind == ck_user)
8167 {
8168 print_z_candidate (loc: 0, N_(" after user-defined conversion:"),
8169 candidate: t->cand);
8170 break;
8171 }
8172}
8173
8174/* Locate the parameter with the given index within FNDECL.
8175 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8176 Return the location of the FNDECL itself if there are problems. */
8177
8178location_t
8179get_fndecl_argument_location (tree fndecl, int argnum)
8180{
8181 /* The locations of implicitly-declared functions are likely to be
8182 more meaningful than those of their parameters. */
8183 if (DECL_ARTIFICIAL (fndecl))
8184 return DECL_SOURCE_LOCATION (fndecl);
8185
8186 int i;
8187 tree param;
8188
8189 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8190 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8191 i < argnum && param;
8192 i++, param = TREE_CHAIN (param))
8193 ;
8194
8195 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8196 return the location of FNDECL. */
8197 if (param == NULL)
8198 return DECL_SOURCE_LOCATION (fndecl);
8199
8200 return DECL_SOURCE_LOCATION (param);
8201}
8202
8203/* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8204 within its declaration (or the fndecl itself if something went
8205 wrong). */
8206
8207void
8208maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
8209{
8210 if (fn)
8211 inform (get_fndecl_argument_location (fndecl: fn, argnum),
8212 " initializing argument %P of %qD", argnum, fn);
8213}
8214
8215/* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8216 the conversion, EXPR is the expression we're converting. */
8217
8218static void
8219maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8220{
8221 if (cxx_dialect >= cxx20)
8222 return;
8223
8224 tree type = TREE_TYPE (expr);
8225 type = strip_pointer_operator (type);
8226
8227 if (TREE_CODE (type) != ARRAY_TYPE
8228 || TYPE_DOMAIN (type) == NULL_TREE)
8229 return;
8230
8231 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8232 pedwarn (loc, OPT_Wc__20_extensions,
8233 "conversions to arrays of unknown bound "
8234 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8235}
8236
8237/* We call this recursively in convert_like_internal. */
8238static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8239 tsubst_flags_t);
8240
8241/* Perform the conversions in CONVS on the expression EXPR. FN and
8242 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8243 indicates the `this' argument of a method. INNER is nonzero when
8244 being called to continue a conversion chain. It is negative when a
8245 reference binding will be applied, positive otherwise. If
8246 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8247 conversions will be emitted if appropriate. If C_CAST_P is true,
8248 this conversion is coming from a C-style cast; in that case,
8249 conversions to inaccessible bases are permitted. */
8250
8251static tree
8252convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8253 bool issue_conversion_warnings, bool c_cast_p,
8254 bool nested_p, tsubst_flags_t complain)
8255{
8256 tree totype = convs->type;
8257 diagnostic_t diag_kind;
8258 int flags;
8259 location_t loc = cp_expr_loc_or_input_loc (t: expr);
8260
8261 if (convs->bad_p && !(complain & tf_error))
8262 return error_mark_node;
8263
8264 if (convs->bad_p
8265 && convs->kind != ck_user
8266 && convs->kind != ck_list
8267 && convs->kind != ck_ambig
8268 && (convs->kind != ck_ref_bind
8269 || (convs->user_conv_p && next_conversion (conv: convs)->bad_p))
8270 && (convs->kind != ck_rvalue
8271 || SCALAR_TYPE_P (totype))
8272 && convs->kind != ck_base)
8273 {
8274 int complained = 0;
8275 conversion *t = convs;
8276
8277 /* Give a helpful error if this is bad because of excess braces. */
8278 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8279 && SCALAR_TYPE_P (totype)
8280 && CONSTRUCTOR_NELTS (expr) > 0
8281 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8282 {
8283 complained = permerror (loc, "too many braces around initializer "
8284 "for %qT", totype);
8285 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8286 && CONSTRUCTOR_NELTS (expr) == 1)
8287 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8288 }
8289
8290 /* Give a helpful error if this is bad because a conversion to bool
8291 from std::nullptr_t requires direct-initialization. */
8292 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8293 && TREE_CODE (totype) == BOOLEAN_TYPE)
8294 complained = permerror (loc, "converting to %qH from %qI requires "
8295 "direct-initialization",
8296 totype, TREE_TYPE (expr));
8297
8298 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8299 && SCALAR_FLOAT_TYPE_P (totype)
8300 && (extended_float_type_p (TREE_TYPE (expr))
8301 || extended_float_type_p (type: totype)))
8302 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8303 totype))
8304 {
8305 case 2:
8306 if (pedwarn (loc, 0, "converting to %qH from %qI with greater "
8307 "conversion rank", totype, TREE_TYPE (expr)))
8308 complained = 1;
8309 else if (!complained)
8310 complained = -1;
8311 break;
8312 case 3:
8313 if (pedwarn (loc, 0, "converting to %qH from %qI with unordered "
8314 "conversion ranks", totype, TREE_TYPE (expr)))
8315 complained = 1;
8316 else if (!complained)
8317 complained = -1;
8318 break;
8319 default:
8320 break;
8321 }
8322
8323 for (; t ; t = next_conversion (conv: t))
8324 {
8325 if (t->kind == ck_user && t->cand->reason)
8326 {
8327 auto_diagnostic_group d;
8328 complained = permerror (loc, "invalid user-defined conversion "
8329 "from %qH to %qI", TREE_TYPE (expr),
8330 totype);
8331 if (complained)
8332 print_z_candidate (loc, N_("candidate is:"), candidate: t->cand);
8333 expr = convert_like (t, expr, fn, argnum,
8334 /*issue_conversion_warnings=*/false,
8335 /*c_cast_p=*/false, /*nested_p=*/true,
8336 complain);
8337 }
8338 else if (t->kind == ck_user || !t->bad_p)
8339 {
8340 expr = convert_like (t, expr, fn, argnum,
8341 /*issue_conversion_warnings=*/false,
8342 /*c_cast_p=*/false, /*nested_p=*/true,
8343 complain);
8344 if (t->bad_p)
8345 complained = 1;
8346 break;
8347 }
8348 else if (t->kind == ck_ambig)
8349 return convert_like (t, expr, fn, argnum,
8350 /*issue_conversion_warnings=*/false,
8351 /*c_cast_p=*/false, /*nested_p=*/true,
8352 complain);
8353 else if (t->kind == ck_identity)
8354 break;
8355 }
8356 if (!complained && expr != error_mark_node)
8357 {
8358 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8359 gcc_rich_location richloc (loc, &label);
8360 complained = permerror (&richloc,
8361 "invalid conversion from %qH to %qI",
8362 TREE_TYPE (expr), totype);
8363 }
8364 if (convs->kind == ck_ref_bind)
8365 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8366 LOOKUP_NORMAL, NULL_TREE,
8367 complain);
8368 else
8369 expr = cp_convert (totype, expr, complain);
8370 if (complained == 1)
8371 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8372 return expr;
8373 }
8374
8375 if (issue_conversion_warnings && (complain & tf_warning))
8376 conversion_null_warnings (totype, expr, fn, argnum);
8377
8378 switch (convs->kind)
8379 {
8380 case ck_user:
8381 {
8382 struct z_candidate *cand = convs->cand;
8383
8384 if (cand == NULL)
8385 /* We chose the surrogate function from add_conv_candidate, now we
8386 actually need to build the conversion. */
8387 cand = build_user_type_conversion_1 (totype, expr,
8388 LOOKUP_NO_CONVERSION, complain);
8389
8390 tree convfn = cand->fn;
8391
8392 /* When converting from an init list we consider explicit
8393 constructors, but actually trying to call one is an error. */
8394 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8395 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8396 /* Unless this is for direct-list-initialization. */
8397 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8398 /* And in C++98 a default constructor can't be explicit. */
8399 && cxx_dialect >= cxx11)
8400 {
8401 if (!(complain & tf_error))
8402 return error_mark_node;
8403 location_t loc = location_of (expr);
8404 if (CONSTRUCTOR_NELTS (expr) == 0
8405 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8406 {
8407 auto_diagnostic_group d;
8408 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8409 "would use explicit constructor %qD",
8410 totype, convfn))
8411 {
8412 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8413 convfn);
8414 inform (loc, "in C++11 and above a default constructor "
8415 "can be explicit");
8416 }
8417 }
8418 else
8419 {
8420 auto_diagnostic_group d;
8421 error ("converting to %qT from initializer list would use "
8422 "explicit constructor %qD", totype, convfn);
8423 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8424 convfn);
8425 }
8426 }
8427
8428 /* If we're initializing from {}, it's value-initialization. */
8429 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8430 && CONSTRUCTOR_NELTS (expr) == 0
8431 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8432 && !processing_template_decl)
8433 {
8434 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8435 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8436 return error_mark_node;
8437 expr = build_value_init (totype, complain);
8438 expr = get_target_expr (expr, complain);
8439 if (expr != error_mark_node)
8440 {
8441 TARGET_EXPR_LIST_INIT_P (expr) = true;
8442 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8443 }
8444 return expr;
8445 }
8446
8447 /* We don't know here whether EXPR is being used as an lvalue or
8448 rvalue, but we know it's read. */
8449 mark_exp_read (expr);
8450
8451 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8452 any more UDCs. */
8453 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8454 complain);
8455
8456 /* If this is a constructor or a function returning an aggr type,
8457 we need to build up a TARGET_EXPR. */
8458 if (DECL_CONSTRUCTOR_P (convfn))
8459 {
8460 expr = build_cplus_new (totype, expr, complain);
8461
8462 /* Remember that this was list-initialization. */
8463 if (convs->check_narrowing && expr != error_mark_node)
8464 TARGET_EXPR_LIST_INIT_P (expr) = true;
8465 }
8466
8467 return expr;
8468 }
8469 case ck_identity:
8470 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8471 {
8472 int nelts = CONSTRUCTOR_NELTS (expr);
8473 if (nelts == 0)
8474 expr = build_value_init (totype, complain);
8475 else if (nelts == 1)
8476 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8477 else
8478 gcc_unreachable ();
8479 }
8480 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8481 /*read_p=*/true, UNKNOWN_LOCATION,
8482 /*reject_builtin=*/true);
8483
8484 if (type_unknown_p (expr))
8485 expr = instantiate_type (totype, expr, complain);
8486 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8487 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8488 if (expr == null_node
8489 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8490 /* If __null has been converted to an integer type, we do not want to
8491 continue to warn about uses of EXPR as an integer, rather than as a
8492 pointer. */
8493 expr = build_int_cst (totype, 0);
8494 return expr;
8495 case ck_ambig:
8496 /* We leave bad_p off ck_ambig because overload resolution considers
8497 it valid, it just fails when we try to perform it. So we need to
8498 check complain here, too. */
8499 if (complain & tf_error)
8500 {
8501 /* Call build_user_type_conversion again for the error. */
8502 int flags = (convs->need_temporary_p
8503 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8504 build_user_type_conversion (totype, expr: convs->u.expr, flags, complain);
8505 gcc_assert (seen_error ());
8506 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8507 }
8508 return error_mark_node;
8509
8510 case ck_list:
8511 {
8512 /* Conversion to std::initializer_list<T>. */
8513 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8514 unsigned len = CONSTRUCTOR_NELTS (expr);
8515 tree array;
8516
8517 if (tree init = maybe_init_list_as_array (elttype, init: expr))
8518 {
8519 elttype = cp_build_qualified_type
8520 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8521 array = build_array_of_n_type (elttype, len);
8522 array = build_vec_init_expr (array, init, complain);
8523 array = get_target_expr (array);
8524 array = cp_build_addr_expr (array, complain);
8525 }
8526 else if (len)
8527 {
8528 tree val; unsigned ix;
8529
8530 tree new_ctor = build_constructor (init_list_type_node, NULL);
8531
8532 /* Convert all the elements. */
8533 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8534 {
8535 tree sub = convert_like (convs->u.list[ix], val, fn,
8536 argnum, false, false,
8537 /*nested_p=*/true, complain);
8538 if (sub == error_mark_node)
8539 return sub;
8540 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8541 && !check_narrowing (TREE_TYPE (sub), val, complain))
8542 return error_mark_node;
8543 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8544 NULL_TREE, sub);
8545 if (!TREE_CONSTANT (sub))
8546 TREE_CONSTANT (new_ctor) = false;
8547 }
8548 /* Build up the array. */
8549 elttype = cp_build_qualified_type
8550 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8551 array = build_array_of_n_type (elttype, len);
8552 array = finish_compound_literal (array, new_ctor, complain);
8553 /* This is dubious now, should be blessed by P2752. */
8554 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
8555 /* Take the address explicitly rather than via decay_conversion
8556 to avoid the error about taking the address of a temporary. */
8557 array = cp_build_addr_expr (array, complain);
8558 }
8559 else
8560 array = nullptr_node;
8561
8562 array = cp_convert (build_pointer_type (elttype), array, complain);
8563 if (array == error_mark_node)
8564 return error_mark_node;
8565
8566 /* Build up the initializer_list object. Note: fail gracefully
8567 if the object cannot be completed because, for example, no
8568 definition is provided (c++/80956). */
8569 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8570 if (!totype)
8571 return error_mark_node;
8572 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8573 vec<constructor_elt, va_gc> *vec = NULL;
8574 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8575 field = next_aggregate_field (DECL_CHAIN (field));
8576 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8577 tree new_ctor = build_constructor (totype, vec);
8578 return get_target_expr (new_ctor, complain);
8579 }
8580
8581 case ck_aggr:
8582 if (TREE_CODE (totype) == COMPLEX_TYPE)
8583 {
8584 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8585 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8586 real = perform_implicit_conversion (TREE_TYPE (totype),
8587 real, complain);
8588 imag = perform_implicit_conversion (TREE_TYPE (totype),
8589 imag, complain);
8590 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8591 return expr;
8592 }
8593 expr = reshape_init (totype, expr, complain);
8594 expr = get_target_expr (digest_init (totype, expr, complain),
8595 complain);
8596 if (expr != error_mark_node)
8597 TARGET_EXPR_LIST_INIT_P (expr) = true;
8598 return expr;
8599
8600 default:
8601 break;
8602 };
8603
8604 expr = convert_like (next_conversion (conv: convs), expr, fn, argnum,
8605 convs->kind == ck_ref_bind
8606 ? issue_conversion_warnings : false,
8607 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8608 if (expr == error_mark_node)
8609 return error_mark_node;
8610
8611 switch (convs->kind)
8612 {
8613 case ck_rvalue:
8614 expr = decay_conversion (expr, complain);
8615 if (expr == error_mark_node)
8616 {
8617 if (complain & tf_error)
8618 {
8619 auto_diagnostic_group d;
8620 maybe_print_user_conv_context (convs);
8621 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8622 }
8623 return error_mark_node;
8624 }
8625
8626 if (! MAYBE_CLASS_TYPE_P (totype))
8627 return expr;
8628
8629 /* Don't introduce copies when passing arguments along to the inherited
8630 constructor. */
8631 if (current_function_decl
8632 && flag_new_inheriting_ctors
8633 && DECL_INHERITED_CTOR (current_function_decl))
8634 return expr;
8635
8636 if (TREE_CODE (expr) == TARGET_EXPR
8637 && TARGET_EXPR_LIST_INIT_P (expr))
8638 /* Copy-list-initialization doesn't actually involve a copy. */
8639 return expr;
8640
8641 /* Fall through. */
8642 case ck_base:
8643 if (convs->kind == ck_base && !convs->need_temporary_p)
8644 {
8645 /* We are going to bind a reference directly to a base-class
8646 subobject of EXPR. */
8647 /* Build an expression for `*((base*) &expr)'. */
8648 expr = convert_to_base (expr, totype,
8649 !c_cast_p, /*nonnull=*/true, complain);
8650 return expr;
8651 }
8652
8653 /* Copy-initialization where the cv-unqualified version of the source
8654 type is the same class as, or a derived class of, the class of the
8655 destination [is treated as direct-initialization]. [dcl.init] */
8656 flags = LOOKUP_NORMAL;
8657 /* This conversion is being done in the context of a user-defined
8658 conversion (i.e. the second step of copy-initialization), so
8659 don't allow any more. */
8660 if (convs->user_conv_p)
8661 flags |= LOOKUP_NO_CONVERSION;
8662 /* We might be performing a conversion of the argument
8663 to the user-defined conversion, i.e., not a conversion of the
8664 result of the user-defined conversion. In which case we skip
8665 explicit constructors. */
8666 if (convs->copy_init_p)
8667 flags |= LOOKUP_ONLYCONVERTING;
8668 expr = build_temp (expr, type: totype, flags, diagnostic_kind: &diag_kind, complain);
8669 if (diag_kind && complain)
8670 {
8671 auto_diagnostic_group d;
8672 maybe_print_user_conv_context (convs);
8673 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8674 }
8675
8676 return build_cplus_new (totype, expr, complain);
8677
8678 case ck_ref_bind:
8679 {
8680 tree ref_type = totype;
8681
8682 /* direct_reference_binding might have inserted a ck_qual under
8683 this ck_ref_bind for the benefit of conversion sequence ranking.
8684 Ignore the conversion; we'll create our own below. */
8685 if (next_conversion (conv: convs)->kind == ck_qual
8686 && !convs->need_temporary_p)
8687 {
8688 gcc_assert (same_type_p (TREE_TYPE (expr),
8689 next_conversion (convs)->type));
8690 /* Strip the cast created by the ck_qual; cp_build_addr_expr
8691 below expects an lvalue. */
8692 STRIP_NOPS (expr);
8693 }
8694
8695 if (convs->bad_p && !next_conversion (conv: convs)->bad_p)
8696 {
8697 tree extype = TREE_TYPE (expr);
8698 auto_diagnostic_group d;
8699 if (TYPE_REF_IS_RVALUE (ref_type)
8700 && lvalue_p (expr))
8701 error_at (loc, "cannot bind rvalue reference of type %qH to "
8702 "lvalue of type %qI", totype, extype);
8703 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8704 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8705 {
8706 conversion *next = next_conversion (conv: convs);
8707 if (next->kind == ck_std)
8708 {
8709 next = next_conversion (conv: next);
8710 error_at (loc, "cannot bind non-const lvalue reference of "
8711 "type %qH to a value of type %qI",
8712 totype, next->type);
8713 }
8714 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8715 error_at (loc, "cannot bind non-const lvalue reference of "
8716 "type %qH to an rvalue of type %qI", totype, extype);
8717 else // extype is volatile
8718 error_at (loc, "cannot bind lvalue reference of type "
8719 "%qH to an rvalue of type %qI", totype,
8720 extype);
8721 }
8722 else if (!reference_compatible_p (TREE_TYPE (totype), t2: extype))
8723 {
8724 /* If we're converting from T[] to T[N], don't talk
8725 about discarding qualifiers. (Converting from T[N] to
8726 T[] is allowed by P0388R4.) */
8727 if (TREE_CODE (extype) == ARRAY_TYPE
8728 && TYPE_DOMAIN (extype) == NULL_TREE
8729 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8730 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8731 error_at (loc, "cannot bind reference of type %qH to %qI "
8732 "due to different array bounds", totype, extype);
8733 else
8734 error_at (loc, "binding reference of type %qH to %qI "
8735 "discards qualifiers", totype, extype);
8736 }
8737 else
8738 gcc_unreachable ();
8739 maybe_print_user_conv_context (convs);
8740 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8741
8742 return error_mark_node;
8743 }
8744 else if (complain & tf_warning)
8745 maybe_warn_array_conv (loc, c: convs, expr);
8746
8747 /* If necessary, create a temporary.
8748
8749 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8750 that need temporaries, even when their types are reference
8751 compatible with the type of reference being bound, so the
8752 upcoming call to cp_build_addr_expr doesn't fail. */
8753 if (convs->need_temporary_p
8754 || TREE_CODE (expr) == CONSTRUCTOR
8755 || TREE_CODE (expr) == VA_ARG_EXPR)
8756 {
8757 /* Otherwise, a temporary of type "cv1 T1" is created and
8758 initialized from the initializer expression using the rules
8759 for a non-reference copy-initialization (8.5). */
8760
8761 tree type = TREE_TYPE (ref_type);
8762 cp_lvalue_kind lvalue = lvalue_kind (expr);
8763
8764 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8765 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8766 && !TYPE_REF_IS_RVALUE (ref_type))
8767 {
8768 /* If the reference is volatile or non-const, we
8769 cannot create a temporary. */
8770 if (complain & tf_error)
8771 {
8772 if (lvalue & clk_bitfield)
8773 error_at (loc, "cannot bind bit-field %qE to %qT",
8774 expr, ref_type);
8775 else if (lvalue & clk_packed)
8776 error_at (loc, "cannot bind packed field %qE to %qT",
8777 expr, ref_type);
8778 else
8779 error_at (loc, "cannot bind rvalue %qE to %qT",
8780 expr, ref_type);
8781 }
8782 return error_mark_node;
8783 }
8784 /* If the source is a packed field, and we must use a copy
8785 constructor, then building the target expr will require
8786 binding the field to the reference parameter to the
8787 copy constructor, and we'll end up with an infinite
8788 loop. If we can use a bitwise copy, then we'll be
8789 OK. */
8790 if ((lvalue & clk_packed)
8791 && CLASS_TYPE_P (type)
8792 && type_has_nontrivial_copy_init (type))
8793 {
8794 error_at (loc, "cannot bind packed field %qE to %qT",
8795 expr, ref_type);
8796 return error_mark_node;
8797 }
8798 if (lvalue & clk_bitfield)
8799 {
8800 expr = convert_bitfield_to_declared_type (expr);
8801 expr = fold_convert (type, expr);
8802 }
8803
8804 /* Creating &TARGET_EXPR<> in a template would break when
8805 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8806 instead. This can happen even when there's no class
8807 involved, e.g., when converting an integer to a reference
8808 type. */
8809 if (processing_template_decl)
8810 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8811 expr = build_target_expr_with_type (expr, type, complain);
8812 }
8813
8814 /* Take the address of the thing to which we will bind the
8815 reference. */
8816 expr = cp_build_addr_expr (expr, complain);
8817 if (expr == error_mark_node)
8818 return error_mark_node;
8819
8820 /* Convert it to a pointer to the type referred to by the
8821 reference. This will adjust the pointer if a derived to
8822 base conversion is being performed. */
8823 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8824 expr, complain);
8825 /* Convert the pointer to the desired reference type. */
8826 return build_nop (ref_type, expr);
8827 }
8828
8829 case ck_lvalue:
8830 return decay_conversion (expr, complain);
8831
8832 case ck_fnptr:
8833 /* ??? Should the address of a transaction-safe pointer point to the TM
8834 clone, and this conversion look up the primary function? */
8835 return build_nop (totype, expr);
8836
8837 case ck_qual:
8838 /* Warn about deprecated conversion if appropriate. */
8839 if (complain & tf_warning)
8840 {
8841 string_conv_p (totype, expr, 1);
8842 maybe_warn_array_conv (loc, c: convs, expr);
8843 }
8844 break;
8845
8846 case ck_ptr:
8847 if (convs->base_p)
8848 expr = convert_to_base (expr, totype, !c_cast_p,
8849 /*nonnull=*/false, complain);
8850 return build_nop (totype, expr);
8851
8852 case ck_pmem:
8853 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8854 c_cast_p, complain);
8855
8856 default:
8857 break;
8858 }
8859
8860 if (convs->check_narrowing
8861 && !check_narrowing (totype, expr, complain,
8862 convs->check_narrowing_const_only))
8863 return error_mark_node;
8864
8865 warning_sentinel w (warn_zero_as_null_pointer_constant);
8866 if (issue_conversion_warnings)
8867 expr = cp_convert_and_check (totype, expr, complain);
8868 else
8869 {
8870 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8871 expr = TREE_OPERAND (expr, 0);
8872 expr = cp_convert (totype, expr, complain);
8873 }
8874
8875 return expr;
8876}
8877
8878/* Return true if converting FROM to TO is unsafe in a template. */
8879
8880static bool
8881conv_unsafe_in_template_p (tree to, tree from)
8882{
8883 /* Converting classes involves TARGET_EXPR. */
8884 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8885 return true;
8886
8887 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8888 doesn't handle. */
8889 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8890 return true;
8891
8892 /* Converting integer to real isn't a trivial conversion, either. */
8893 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8894 return true;
8895
8896 return false;
8897}
8898
8899/* Wrapper for convert_like_internal that handles creating
8900 IMPLICIT_CONV_EXPR. */
8901
8902static tree
8903convert_like (conversion *convs, tree expr, tree fn, int argnum,
8904 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
8905 tsubst_flags_t complain)
8906{
8907 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8908 and creating a CALL_EXPR in a template breaks in finish_call_expr
8909 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
8910 created such codes e.g. when calling a user-defined conversion
8911 function. */
8912 tree conv_expr = NULL_TREE;
8913 if (processing_template_decl
8914 && convs->kind != ck_identity
8915 && conv_unsafe_in_template_p (to: convs->type, TREE_TYPE (expr)))
8916 {
8917 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8918 if (convs->kind != ck_ref_bind)
8919 conv_expr = convert_from_reference (conv_expr);
8920 if (!convs->bad_p)
8921 return conv_expr;
8922 /* Do the normal processing to give the bad_p errors. But we still
8923 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8924 error_mark_node. */
8925 }
8926 expr = convert_like_internal (convs, expr, fn, argnum,
8927 issue_conversion_warnings, c_cast_p,
8928 nested_p, complain);
8929 if (expr == error_mark_node)
8930 return error_mark_node;
8931 return conv_expr ? conv_expr : expr;
8932}
8933
8934/* Convenience wrapper for convert_like. */
8935
8936static inline tree
8937convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8938{
8939 return convert_like (convs, expr, NULL_TREE, argnum: 0,
8940 /*issue_conversion_warnings=*/true,
8941 /*c_cast_p=*/false, /*nested_p=*/false, complain);
8942}
8943
8944/* Convenience wrapper for convert_like. */
8945
8946static inline tree
8947convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8948 tsubst_flags_t complain)
8949{
8950 return convert_like (convs, expr, fn, argnum,
8951 /*issue_conversion_warnings=*/true,
8952 /*c_cast_p=*/false, /*nested_p=*/false, complain);
8953}
8954
8955/* ARG is being passed to a varargs function. Perform any conversions
8956 required. Return the converted value. */
8957
8958tree
8959convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8960{
8961 tree arg_type = TREE_TYPE (arg);
8962 location_t loc = cp_expr_loc_or_input_loc (t: arg);
8963
8964 /* [expr.call]
8965
8966 If the argument has integral or enumeration type that is subject
8967 to the integral promotions (_conv.prom_), or a floating-point
8968 type that is subject to the floating-point promotion
8969 (_conv.fpprom_), the value of the argument is converted to the
8970 promoted type before the call. */
8971 if (SCALAR_FLOAT_TYPE_P (arg_type)
8972 && (TYPE_PRECISION (arg_type)
8973 < TYPE_PRECISION (double_type_node))
8974 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
8975 && !extended_float_type_p (type: arg_type))
8976 {
8977 if ((complain & tf_warning)
8978 && warn_double_promotion && !c_inhibit_evaluation_warnings)
8979 warning_at (loc, OPT_Wdouble_promotion,
8980 "implicit conversion from %qH to %qI when passing "
8981 "argument to function",
8982 arg_type, double_type_node);
8983 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
8984 arg = TREE_OPERAND (arg, 0);
8985 arg = mark_rvalue_use (arg);
8986 arg = convert_to_real_nofold (double_type_node, x: arg);
8987 }
8988 else if (NULLPTR_TYPE_P (arg_type))
8989 {
8990 arg = mark_rvalue_use (arg);
8991 if (TREE_SIDE_EFFECTS (arg))
8992 {
8993 warning_sentinel w(warn_unused_result);
8994 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
8995 }
8996 else
8997 arg = null_pointer_node;
8998 }
8999 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9000 {
9001 if (SCOPED_ENUM_P (arg_type))
9002 {
9003 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9004 complain);
9005 prom = cp_perform_integral_promotions (prom, complain);
9006 if (abi_version_crosses (6)
9007 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9008 && (complain & tf_warning))
9009 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9010 " as %qT before %<-fabi-version=6%>, %qT after",
9011 arg_type,
9012 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9013 if (!abi_version_at_least (6))
9014 arg = prom;
9015 }
9016 else
9017 arg = cp_perform_integral_promotions (arg, complain);
9018 }
9019 else
9020 /* [expr.call]
9021
9022 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9023 standard conversions are performed. */
9024 arg = decay_conversion (arg, complain);
9025
9026 arg = require_complete_type (arg, complain);
9027 arg_type = TREE_TYPE (arg);
9028
9029 if (arg != error_mark_node
9030 /* In a template (or ill-formed code), we can have an incomplete type
9031 even after require_complete_type, in which case we don't know
9032 whether it has trivial copy or not. */
9033 && COMPLETE_TYPE_P (arg_type)
9034 && !cp_unevaluated_operand)
9035 {
9036 /* [expr.call] 5.2.2/7:
9037 Passing a potentially-evaluated argument of class type (Clause 9)
9038 with a non-trivial copy constructor or a non-trivial destructor
9039 with no corresponding parameter is conditionally-supported, with
9040 implementation-defined semantics.
9041
9042 We support it as pass-by-invisible-reference, just like a normal
9043 value parameter.
9044
9045 If the call appears in the context of a sizeof expression,
9046 it is not potentially-evaluated. */
9047 if (type_has_nontrivial_copy_init (arg_type)
9048 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9049 {
9050 arg = force_rvalue (arg, complain);
9051 if (complain & tf_warning)
9052 warning (OPT_Wconditionally_supported,
9053 "passing objects of non-trivially-copyable "
9054 "type %q#T through %<...%> is conditionally supported",
9055 arg_type);
9056 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9057 }
9058 /* Build up a real lvalue-to-rvalue conversion in case the
9059 copy constructor is trivial but not callable. */
9060 else if (CLASS_TYPE_P (arg_type))
9061 force_rvalue (arg, complain);
9062
9063 }
9064
9065 return arg;
9066}
9067
9068/* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9069
9070tree
9071build_x_va_arg (location_t loc, tree expr, tree type)
9072{
9073 if (processing_template_decl)
9074 {
9075 tree r = build_min (VA_ARG_EXPR, type, expr);
9076 SET_EXPR_LOCATION (r, loc);
9077 return r;
9078 }
9079
9080 type = complete_type_or_else (type, NULL_TREE);
9081
9082 if (expr == error_mark_node || !type)
9083 return error_mark_node;
9084
9085 expr = mark_lvalue_use (expr);
9086
9087 if (TYPE_REF_P (type))
9088 {
9089 error ("cannot receive reference type %qT through %<...%>", type);
9090 return error_mark_node;
9091 }
9092
9093 if (type_has_nontrivial_copy_init (type)
9094 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9095 {
9096 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9097 it as pass by invisible reference. */
9098 warning_at (loc, OPT_Wconditionally_supported,
9099 "receiving objects of non-trivially-copyable type %q#T "
9100 "through %<...%> is conditionally-supported", type);
9101
9102 tree ref = cp_build_reference_type (type, false);
9103 expr = build_va_arg (loc, expr, ref);
9104 return convert_from_reference (expr);
9105 }
9106
9107 tree ret = build_va_arg (loc, expr, type);
9108 if (CLASS_TYPE_P (type))
9109 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9110 know how to handle it. */
9111 ret = get_target_expr (ret);
9112 return ret;
9113}
9114
9115/* TYPE has been given to va_arg. Apply the default conversions which
9116 would have happened when passed via ellipsis. Return the promoted
9117 type, or the passed type if there is no change. */
9118
9119tree
9120cxx_type_promotes_to (tree type)
9121{
9122 tree promote;
9123
9124 /* Perform the array-to-pointer and function-to-pointer
9125 conversions. */
9126 type = type_decays_to (type);
9127
9128 promote = type_promotes_to (type);
9129 if (same_type_p (type, promote))
9130 promote = type;
9131
9132 return promote;
9133}
9134
9135/* ARG is a default argument expression being passed to a parameter of
9136 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9137 zero-based argument number. Do any required conversions. Return
9138 the converted value. */
9139
9140static GTY(()) vec<tree, va_gc> *default_arg_context;
9141void
9142push_defarg_context (tree fn)
9143{ vec_safe_push (v&: default_arg_context, obj: fn); }
9144
9145void
9146pop_defarg_context (void)
9147{ default_arg_context->pop (); }
9148
9149tree
9150convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9151 tsubst_flags_t complain)
9152{
9153 int i;
9154 tree t;
9155
9156 /* See through clones. */
9157 fn = DECL_ORIGIN (fn);
9158 /* And inheriting ctors. */
9159 if (flag_new_inheriting_ctors)
9160 fn = strip_inheriting_ctors (fn);
9161
9162 /* Detect recursion. */
9163 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9164 if (t == fn)
9165 {
9166 if (complain & tf_error)
9167 error ("recursive evaluation of default argument for %q#D", fn);
9168 return error_mark_node;
9169 }
9170
9171 /* If the ARG is an unparsed default argument expression, the
9172 conversion cannot be performed. */
9173 if (TREE_CODE (arg) == DEFERRED_PARSE)
9174 {
9175 if (complain & tf_error)
9176 error ("call to %qD uses the default argument for parameter %P, which "
9177 "is not yet defined", fn, parmnum);
9178 return error_mark_node;
9179 }
9180
9181 push_defarg_context (fn);
9182
9183 if (fn && DECL_TEMPLATE_INFO (fn))
9184 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9185
9186 /* Due to:
9187
9188 [dcl.fct.default]
9189
9190 The names in the expression are bound, and the semantic
9191 constraints are checked, at the point where the default
9192 expressions appears.
9193
9194 we must not perform access checks here. */
9195 push_deferring_access_checks (dk_no_check);
9196 /* We must make a copy of ARG, in case subsequent processing
9197 alters any part of it. */
9198 arg = break_out_target_exprs (arg, /*clear location*/true);
9199
9200 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9201 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9202 complain);
9203 arg = convert_for_arg_passing (type, arg, complain);
9204 pop_deferring_access_checks();
9205
9206 pop_defarg_context ();
9207
9208 return arg;
9209}
9210
9211/* Returns the type which will really be used for passing an argument of
9212 type TYPE. */
9213
9214tree
9215type_passed_as (tree type)
9216{
9217 /* Pass classes with copy ctors by invisible reference. */
9218 if (TREE_ADDRESSABLE (type))
9219 type = build_reference_type (type);
9220 else if (targetm.calls.promote_prototypes (NULL_TREE)
9221 && INTEGRAL_TYPE_P (type)
9222 && COMPLETE_TYPE_P (type)
9223 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9224 type = integer_type_node;
9225
9226 return type;
9227}
9228
9229/* Actually perform the appropriate conversion. */
9230
9231tree
9232convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9233{
9234 tree bitfield_type;
9235
9236 /* If VAL is a bitfield, then -- since it has already been converted
9237 to TYPE -- it cannot have a precision greater than TYPE.
9238
9239 If it has a smaller precision, we must widen it here. For
9240 example, passing "int f:3;" to a function expecting an "int" will
9241 not result in any conversion before this point.
9242
9243 If the precision is the same we must not risk widening. For
9244 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9245 often have type "int", even though the C++ type for the field is
9246 "long long". If the value is being passed to a function
9247 expecting an "int", then no conversions will be required. But,
9248 if we call convert_bitfield_to_declared_type, the bitfield will
9249 be converted to "long long". */
9250 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9251 if (bitfield_type
9252 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9253 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), x: val);
9254
9255 if (val == error_mark_node)
9256 ;
9257 /* Pass classes with copy ctors by invisible reference. */
9258 else if (TREE_ADDRESSABLE (type))
9259 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9260 else if (targetm.calls.promote_prototypes (NULL_TREE)
9261 && INTEGRAL_TYPE_P (type)
9262 && COMPLETE_TYPE_P (type)
9263 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9264 val = cp_perform_integral_promotions (val, complain);
9265 if (complain & tf_warning)
9266 {
9267 if (warn_suggest_attribute_format)
9268 {
9269 tree rhstype = TREE_TYPE (val);
9270 const enum tree_code coder = TREE_CODE (rhstype);
9271 const enum tree_code codel = TREE_CODE (type);
9272 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9273 && coder == codel
9274 && check_missing_format_attribute (type, rhstype))
9275 warning (OPT_Wsuggest_attribute_format,
9276 "argument of function call might be a candidate "
9277 "for a format attribute");
9278 }
9279 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (t: val));
9280 }
9281
9282 if (complain & tf_warning)
9283 warn_for_address_or_pointer_of_packed_member (type, val);
9284
9285 return val;
9286}
9287
9288/* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9289 which just decay_conversion or no conversions at all should be done.
9290 This is true for some builtins which don't act like normal functions.
9291 Return 2 if just decay_conversion and removal of excess precision should
9292 be done, 1 if just decay_conversion. Return 3 for special treatment of
9293 the 3rd argument for __builtin_*_overflow_p. */
9294
9295int
9296magic_varargs_p (tree fn)
9297{
9298 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9299 switch (DECL_FUNCTION_CODE (decl: fn))
9300 {
9301 case BUILT_IN_CLASSIFY_TYPE:
9302 case BUILT_IN_CONSTANT_P:
9303 case BUILT_IN_NEXT_ARG:
9304 case BUILT_IN_VA_START:
9305 return 1;
9306
9307 case BUILT_IN_ADD_OVERFLOW_P:
9308 case BUILT_IN_SUB_OVERFLOW_P:
9309 case BUILT_IN_MUL_OVERFLOW_P:
9310 return 3;
9311
9312 case BUILT_IN_ISFINITE:
9313 case BUILT_IN_ISINF:
9314 case BUILT_IN_ISINF_SIGN:
9315 case BUILT_IN_ISNAN:
9316 case BUILT_IN_ISNORMAL:
9317 case BUILT_IN_FPCLASSIFY:
9318 return 2;
9319
9320 default:
9321 return lookup_attribute (attr_name: "type generic",
9322 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9323 }
9324
9325 return 0;
9326}
9327
9328/* Returns the decl of the dispatcher function if FN is a function version. */
9329
9330tree
9331get_function_version_dispatcher (tree fn)
9332{
9333 tree dispatcher_decl = NULL;
9334
9335 if (DECL_LOCAL_DECL_P (fn))
9336 fn = DECL_LOCAL_DECL_ALIAS (fn);
9337
9338 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9339 && DECL_FUNCTION_VERSIONED (fn));
9340
9341 gcc_assert (targetm.get_function_versions_dispatcher);
9342 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9343
9344 if (dispatcher_decl == NULL)
9345 {
9346 error_at (input_location, "use of multiversioned function "
9347 "without a default");
9348 return NULL;
9349 }
9350
9351 retrofit_lang_decl (dispatcher_decl);
9352 gcc_assert (dispatcher_decl != NULL);
9353 return dispatcher_decl;
9354}
9355
9356/* fn is a function version dispatcher that is marked used. Mark all the
9357 semantically identical function versions it will dispatch as used. */
9358
9359void
9360mark_versions_used (tree fn)
9361{
9362 struct cgraph_node *node;
9363 struct cgraph_function_version_info *node_v;
9364 struct cgraph_function_version_info *it_v;
9365
9366 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9367
9368 node = cgraph_node::get (decl: fn);
9369 if (node == NULL)
9370 return;
9371
9372 gcc_assert (node->dispatcher_function);
9373
9374 node_v = node->function_version ();
9375 if (node_v == NULL)
9376 return;
9377
9378 /* All semantically identical versions are chained. Traverse and mark each
9379 one of them as used. */
9380 it_v = node_v->next;
9381 while (it_v != NULL)
9382 {
9383 mark_used (it_v->this_node->decl);
9384 it_v = it_v->next;
9385 }
9386}
9387
9388/* Build a call to "the copy constructor" for the type of A, even if it
9389 wouldn't be selected by normal overload resolution. Used for
9390 diagnostics. */
9391
9392static tree
9393call_copy_ctor (tree a, tsubst_flags_t complain)
9394{
9395 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9396 tree binfo = TYPE_BINFO (ctype);
9397 tree copy = get_copy_ctor (ctype, complain);
9398 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9399 tree ob = build_dummy_object (ctype);
9400 releasing_vec args (make_tree_vector_single (a));
9401 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9402 LOOKUP_NORMAL, NULL, complain);
9403 return r;
9404}
9405
9406/* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9407
9408static tree
9409base_ctor_for (tree complete_ctor)
9410{
9411 tree clone;
9412 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9413 if (DECL_BASE_CONSTRUCTOR_P (clone))
9414 return clone;
9415 return NULL_TREE;
9416}
9417
9418/* Try to make EXP suitable to be used as the initializer for a base subobject,
9419 and return whether we were successful. EXP must have already been cleared
9420 by unsafe_copy_elision_p{,_opt}. */
9421
9422static bool
9423make_base_init_ok (tree exp)
9424{
9425 if (TREE_CODE (exp) == TARGET_EXPR)
9426 exp = TARGET_EXPR_INITIAL (exp);
9427 while (TREE_CODE (exp) == COMPOUND_EXPR)
9428 exp = TREE_OPERAND (exp, 1);
9429 if (TREE_CODE (exp) == COND_EXPR)
9430 {
9431 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9432 if (tree op1 = TREE_OPERAND (exp, 1))
9433 {
9434 bool r1 = make_base_init_ok (exp: op1);
9435 /* If unsafe_copy_elision_p was false, the arms should match. */
9436 gcc_assert (r1 == ret);
9437 }
9438 return ret;
9439 }
9440 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9441 /* A trivial copy is OK. */
9442 return true;
9443 if (!AGGR_INIT_VIA_CTOR_P (exp))
9444 /* unsafe_copy_elision_p_opt must have said this is OK. */
9445 return true;
9446 tree fn = cp_get_callee_fndecl_nofold (exp);
9447 if (DECL_BASE_CONSTRUCTOR_P (fn))
9448 return true;
9449 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9450 fn = base_ctor_for (complete_ctor: fn);
9451 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9452 /* The base constructor has more parameters, so we can't just change the
9453 call target. It would be possible to splice in the appropriate
9454 arguments, but probably not worth the complexity. */
9455 return false;
9456 mark_used (fn);
9457 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9458 return true;
9459}
9460
9461/* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9462 neither of which can be used for return by invisible reference. We avoid
9463 doing C++17 mandatory copy elision for either of these cases.
9464
9465 This returns non-zero even if the type of T has no tail padding that other
9466 data could be allocated into, because that depends on the particular ABI.
9467 unsafe_copy_elision_p_opt does consider whether there is padding. */
9468
9469int
9470unsafe_return_slot_p (tree t)
9471{
9472 /* Check empty bases separately, they don't have fields. */
9473 if (is_empty_base_ref (t))
9474 return 2;
9475
9476 /* A delegating constructor might be used to initialize a base. */
9477 if (current_function_decl
9478 && DECL_CONSTRUCTOR_P (current_function_decl)
9479 && (t == current_class_ref
9480 || tree_strip_nop_conversions (t) == current_class_ptr))
9481 return 2;
9482
9483 STRIP_NOPS (t);
9484 if (TREE_CODE (t) == ADDR_EXPR)
9485 t = TREE_OPERAND (t, 0);
9486 if (TREE_CODE (t) == COMPONENT_REF)
9487 t = TREE_OPERAND (t, 1);
9488 if (TREE_CODE (t) != FIELD_DECL)
9489 return false;
9490 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9491 /* The middle-end will do the right thing for scalar types. */
9492 return false;
9493 if (DECL_FIELD_IS_BASE (t))
9494 return 2;
9495 if (lookup_attribute (attr_name: "no_unique_address", DECL_ATTRIBUTES (t)))
9496 return 1;
9497 return 0;
9498}
9499
9500/* True IFF EXP is a prvalue that represents return by invisible reference. */
9501
9502static bool
9503init_by_return_slot_p (tree exp)
9504{
9505 /* Copy elision only happens with a TARGET_EXPR. */
9506 if (TREE_CODE (exp) != TARGET_EXPR)
9507 return false;
9508 tree init = TARGET_EXPR_INITIAL (exp);
9509 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9510 while (TREE_CODE (init) == COMPOUND_EXPR)
9511 init = TREE_OPERAND (init, 1);
9512 if (TREE_CODE (init) == COND_EXPR)
9513 {
9514 /* We'll end up copying from each of the arms of the COND_EXPR directly
9515 into the target, so look at them. */
9516 if (tree op = TREE_OPERAND (init, 1))
9517 if (init_by_return_slot_p (exp: op))
9518 return true;
9519 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9520 }
9521 return (TREE_CODE (init) == AGGR_INIT_EXPR
9522 && !AGGR_INIT_VIA_CTOR_P (init));
9523}
9524
9525/* We can't elide a copy from a function returning by value to a
9526 potentially-overlapping subobject, as the callee might clobber tail padding.
9527 Return true iff this could be that case.
9528
9529 Places that use this function (or _opt) to decide to elide a copy should
9530 probably use make_safe_copy_elision instead. */
9531
9532bool
9533unsafe_copy_elision_p (tree target, tree exp)
9534{
9535 return unsafe_return_slot_p (t: target) && init_by_return_slot_p (exp);
9536}
9537
9538/* As above, but for optimization allow more cases that are actually safe. */
9539
9540static bool
9541unsafe_copy_elision_p_opt (tree target, tree exp)
9542{
9543 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9544 /* It's safe to elide the copy for a class with no tail padding. */
9545 if (!is_empty_class (type)
9546 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9547 return false;
9548 return unsafe_copy_elision_p (target, exp);
9549}
9550
9551/* Try to make EXP suitable to be used as the initializer for TARGET,
9552 and return whether we were successful. */
9553
9554bool
9555make_safe_copy_elision (tree target, tree exp)
9556{
9557 int uns = unsafe_return_slot_p (t: target);
9558 if (!uns)
9559 return true;
9560 if (init_by_return_slot_p (exp))
9561 return false;
9562 if (uns == 1)
9563 return true;
9564 return make_base_init_ok (exp);
9565}
9566
9567/* True IFF the result of the conversion C is a prvalue. */
9568
9569static bool
9570conv_is_prvalue (conversion *c)
9571{
9572 if (c->kind == ck_rvalue)
9573 return true;
9574 if (c->kind == ck_base && c->need_temporary_p)
9575 return true;
9576 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9577 return true;
9578 if (c->kind == ck_identity && c->u.expr
9579 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9580 return true;
9581
9582 return false;
9583}
9584
9585/* True iff C is a conversion that binds a reference to a prvalue. */
9586
9587static bool
9588conv_binds_ref_to_prvalue (conversion *c)
9589{
9590 if (c->kind != ck_ref_bind)
9591 return false;
9592 if (c->need_temporary_p)
9593 return true;
9594
9595 return conv_is_prvalue (c: next_conversion (conv: c));
9596}
9597
9598/* True iff EXPR represents a (subobject of a) temporary. */
9599
9600static bool
9601expr_represents_temporary_p (tree expr)
9602{
9603 while (handled_component_p (t: expr))
9604 expr = TREE_OPERAND (expr, 0);
9605 return TREE_CODE (expr) == TARGET_EXPR;
9606}
9607
9608/* True iff C is a conversion that binds a reference to a temporary.
9609 This is a superset of conv_binds_ref_to_prvalue: here we're also
9610 interested in xvalues. */
9611
9612static bool
9613conv_binds_ref_to_temporary (conversion *c)
9614{
9615 if (conv_binds_ref_to_prvalue (c))
9616 return true;
9617 if (c->kind != ck_ref_bind)
9618 return false;
9619 c = next_conversion (conv: c);
9620 /* This is the case for
9621 struct Base {};
9622 struct Derived : Base {};
9623 const Base& b(Derived{});
9624 where we bind 'b' to the Base subobject of a temporary object of type
9625 Derived. The subobject is an xvalue; the whole object is a prvalue.
9626
9627 The ck_base doesn't have to be present for cases like X{}.m. */
9628 if (c->kind == ck_base)
9629 c = next_conversion (conv: c);
9630 if (c->kind == ck_identity && c->u.expr
9631 && expr_represents_temporary_p (expr: c->u.expr))
9632 return true;
9633 return false;
9634}
9635
9636/* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9637 the reference to a temporary. Return tristate::TS_FALSE if converting
9638 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9639 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9640 says whether the conversion should be done in direct- or copy-initialization
9641 context. */
9642
9643tristate
9644ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9645{
9646 gcc_assert (TYPE_REF_P (type));
9647
9648 conversion_obstack_sentinel cos;
9649
9650 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9651 conversion *conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
9652 /*c_cast_p=*/false, flags, complain: tf_none);
9653 tristate ret (tristate::TS_UNKNOWN);
9654 if (conv && !conv->bad_p)
9655 ret = tristate (conv_binds_ref_to_temporary (c: conv));
9656
9657 return ret;
9658}
9659
9660/* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9661 class type or a pointer to class type. If NO_PTR_DEREF is true and
9662 INSTANCE has pointer type, clobber the pointer rather than what it points
9663 to. */
9664
9665tree
9666build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9667{
9668 gcc_assert (!is_dummy_object (instance));
9669
9670 if (!flag_lifetime_dse)
9671 {
9672 no_clobber:
9673 return fold_convert (void_type_node, instance);
9674 }
9675
9676 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9677 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9678 {
9679 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9680 goto no_clobber;
9681 instance = cp_build_fold_indirect_ref (instance);
9682 }
9683
9684 /* A trivial destructor should still clobber the object. */
9685 tree clobber = build_clobber (TREE_TYPE (instance));
9686 return build2 (MODIFY_EXPR, void_type_node,
9687 instance, clobber);
9688}
9689
9690/* Return true if in an immediate function context, or an unevaluated operand,
9691 or a default argument/member initializer, or a subexpression of an immediate
9692 invocation. */
9693
9694bool
9695in_immediate_context ()
9696{
9697 return (cp_unevaluated_operand != 0
9698 || (current_function_decl != NULL_TREE
9699 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9700 /* DR 2631: default args and DMI aren't immediately evaluated.
9701 Return true here so immediate_invocation_p returns false. */
9702 || current_binding_level->kind == sk_function_parms
9703 || current_binding_level->kind == sk_template_parms
9704 || parsing_nsdmi ()
9705 || in_consteval_if_p);
9706}
9707
9708/* Return true if a call to FN with number of arguments NARGS
9709 is an immediate invocation. */
9710
9711static bool
9712immediate_invocation_p (tree fn)
9713{
9714 return (TREE_CODE (fn) == FUNCTION_DECL
9715 && DECL_IMMEDIATE_FUNCTION_P (fn)
9716 && !in_immediate_context ());
9717}
9718
9719/* Subroutine of the various build_*_call functions. Overload resolution
9720 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9721 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9722 bitmask of various LOOKUP_* flags which apply to the call itself. */
9723
9724static tree
9725build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9726{
9727 tree fn = cand->fn;
9728 const vec<tree, va_gc> *args = cand->args;
9729 tree first_arg = cand->first_arg;
9730 conversion **convs = cand->convs;
9731 conversion *conv;
9732 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9733 int parmlen;
9734 tree val;
9735 int i = 0;
9736 int j = 0;
9737 unsigned int arg_index = 0;
9738 int is_method = 0;
9739 int nargs;
9740 tree *argarray;
9741 bool already_used = false;
9742
9743 /* In a template, there is no need to perform all of the work that
9744 is normally done. We are only interested in the type of the call
9745 expression, i.e., the return type of the function. Any semantic
9746 errors will be deferred until the template is instantiated. */
9747 if (processing_template_decl)
9748 {
9749 if (undeduced_auto_decl (fn))
9750 mark_used (fn, complain);
9751 else
9752 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9753 See PR80598. */
9754 TREE_USED (fn) = 1;
9755
9756 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9757 tree callee;
9758 if (first_arg == NULL_TREE)
9759 {
9760 callee = build_addr_func (function: fn, complain);
9761 if (callee == error_mark_node)
9762 return error_mark_node;
9763 }
9764 else
9765 {
9766 callee = build_baselink (cand->conversion_path, cand->access_path,
9767 fn, NULL_TREE);
9768 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9769 first_arg, callee, NULL_TREE);
9770 }
9771
9772 tree expr = build_call_vec (return_type, callee, args);
9773 SET_EXPR_LOCATION (expr, input_location);
9774 if (TREE_THIS_VOLATILE (fn) && cfun)
9775 current_function_returns_abnormally = 1;
9776 if (immediate_invocation_p (fn))
9777 {
9778 tree obj_arg = NULL_TREE, exprimm = expr;
9779 if (DECL_CONSTRUCTOR_P (fn))
9780 obj_arg = first_arg;
9781 if (obj_arg
9782 && is_dummy_object (obj_arg)
9783 && !type_dependent_expression_p (obj_arg))
9784 {
9785 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9786 obj_arg = NULL_TREE;
9787 }
9788 /* Look through *(const T *)&obj. */
9789 else if (obj_arg && INDIRECT_REF_P (obj_arg))
9790 {
9791 tree addr = TREE_OPERAND (obj_arg, 0);
9792 STRIP_NOPS (addr);
9793 if (TREE_CODE (addr) == ADDR_EXPR)
9794 {
9795 tree typeo = TREE_TYPE (obj_arg);
9796 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9797 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9798 obj_arg = TREE_OPERAND (addr, 0);
9799 }
9800 }
9801 fold_non_dependent_expr (exprimm, complain,
9802 /*manifestly_const_eval=*/true,
9803 obj_arg);
9804 }
9805 return convert_from_reference (expr);
9806 }
9807
9808 /* Give any warnings we noticed during overload resolution. */
9809 if (cand->warnings && (complain & tf_warning))
9810 {
9811 struct candidate_warning *w;
9812 for (w = cand->warnings; w; w = w->next)
9813 joust (cand, w->loser, 1, complain);
9814 }
9815
9816 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9817 argument to the copy constructor ends up being a prvalue after
9818 conversion. Let's do the normal processing, but pretend we aren't
9819 actually using the copy constructor. */
9820 bool force_elide = false;
9821 if (cxx_dialect >= cxx17
9822 && cand->num_convs == 1
9823 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9824 && (DECL_COPY_CONSTRUCTOR_P (fn)
9825 || DECL_MOVE_CONSTRUCTOR_P (fn))
9826 && !unsafe_return_slot_p (t: first_arg)
9827 && conv_binds_ref_to_prvalue (c: convs[0]))
9828 {
9829 force_elide = true;
9830 goto not_really_used;
9831 }
9832
9833 /* OK, we're actually calling this inherited constructor; set its deletedness
9834 appropriately. We can get away with doing this here because calling is
9835 the only way to refer to a constructor. */
9836 if (DECL_INHERITED_CTOR (fn)
9837 && !deduce_inheriting_ctor (fn))
9838 {
9839 if (complain & tf_error)
9840 mark_used (fn);
9841 return error_mark_node;
9842 }
9843
9844 /* Make =delete work with SFINAE. */
9845 if (DECL_DELETED_FN (fn))
9846 {
9847 if (complain & tf_error)
9848 mark_used (fn);
9849 return error_mark_node;
9850 }
9851
9852 if (DECL_FUNCTION_MEMBER_P (fn))
9853 {
9854 tree access_fn;
9855 /* If FN is a template function, two cases must be considered.
9856 For example:
9857
9858 struct A {
9859 protected:
9860 template <class T> void f();
9861 };
9862 template <class T> struct B {
9863 protected:
9864 void g();
9865 };
9866 struct C : A, B<int> {
9867 using A::f; // #1
9868 using B<int>::g; // #2
9869 };
9870
9871 In case #1 where `A::f' is a member template, DECL_ACCESS is
9872 recorded in the primary template but not in its specialization.
9873 We check access of FN using its primary template.
9874
9875 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9876 because it is a member of class template B, DECL_ACCESS is
9877 recorded in the specialization `B<int>::g'. We cannot use its
9878 primary template because `B<T>::g' and `B<int>::g' may have
9879 different access. */
9880 if (DECL_TEMPLATE_INFO (fn)
9881 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9882 access_fn = DECL_TI_TEMPLATE (fn);
9883 else
9884 access_fn = fn;
9885 if (!perform_or_defer_access_check (cand->access_path, access_fn,
9886 fn, complain))
9887 return error_mark_node;
9888 }
9889
9890 /* If we're checking for implicit delete, don't bother with argument
9891 conversions. */
9892 if (flags & LOOKUP_SPECULATIVE)
9893 {
9894 if (cand->viable == 1)
9895 return fn;
9896 else if (!(complain & tf_error))
9897 /* Reject bad conversions now. */
9898 return error_mark_node;
9899 /* else continue to get conversion error. */
9900 }
9901
9902 not_really_used:
9903
9904 /* N3276 magic doesn't apply to nested calls. */
9905 tsubst_flags_t decltype_flag = (complain & tf_decltype);
9906 complain &= ~tf_decltype;
9907 /* No-Cleanup doesn't apply to nested calls either. */
9908 tsubst_flags_t no_cleanup_complain = complain;
9909 complain &= ~tf_no_cleanup;
9910
9911 /* Find maximum size of vector to hold converted arguments. */
9912 parmlen = list_length (parm);
9913 nargs = vec_safe_length (v: args) + (first_arg != NULL_TREE ? 1 : 0);
9914 if (parmlen > nargs)
9915 nargs = parmlen;
9916 argarray = XALLOCAVEC (tree, nargs);
9917
9918 in_consteval_if_p_temp_override icip;
9919 /* If the call is immediate function invocation, make sure
9920 taking address of immediate functions is allowed in its arguments. */
9921 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
9922 in_consteval_if_p = true;
9923
9924 /* The implicit parameters to a constructor are not considered by overload
9925 resolution, and must be of the proper type. */
9926 if (DECL_CONSTRUCTOR_P (fn))
9927 {
9928 tree object_arg;
9929 if (first_arg != NULL_TREE)
9930 {
9931 object_arg = first_arg;
9932 first_arg = NULL_TREE;
9933 }
9934 else
9935 {
9936 object_arg = (*args)[arg_index];
9937 ++arg_index;
9938 }
9939 argarray[j++] = build_this (obj: object_arg);
9940 parm = TREE_CHAIN (parm);
9941 /* We should never try to call the abstract constructor. */
9942 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9943
9944 if (DECL_HAS_VTT_PARM_P (fn))
9945 {
9946 argarray[j++] = (*args)[arg_index];
9947 ++arg_index;
9948 parm = TREE_CHAIN (parm);
9949 }
9950 }
9951 /* Bypass access control for 'this' parameter. */
9952 else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9953 {
9954 tree arg = build_this (obj: first_arg != NULL_TREE
9955 ? first_arg
9956 : (*args)[arg_index]);
9957 tree argtype = TREE_TYPE (arg);
9958
9959 if (arg == error_mark_node)
9960 return error_mark_node;
9961
9962 if (convs[i]->bad_p)
9963 {
9964 if (complain & tf_error)
9965 {
9966 auto_diagnostic_group d;
9967 if (permerror (input_location, "passing %qT as %<this%> "
9968 "argument discards qualifiers",
9969 TREE_TYPE (argtype)))
9970 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
9971 }
9972 else
9973 return error_mark_node;
9974 }
9975
9976 /* The class where FN is defined. */
9977 tree ctx = DECL_CONTEXT (fn);
9978
9979 /* See if the function member or the whole class type is declared
9980 final and the call can be devirtualized. */
9981 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9982 flags |= LOOKUP_NONVIRTUAL;
9983
9984 /* [class.mfct.non-static]: If a non-static member function of a class
9985 X is called for an object that is not of type X, or of a type
9986 derived from X, the behavior is undefined.
9987
9988 So we can assume that anything passed as 'this' is non-null, and
9989 optimize accordingly. */
9990 /* Check that the base class is accessible. */
9991 if (!accessible_base_p (TREE_TYPE (argtype),
9992 BINFO_TYPE (cand->conversion_path), true))
9993 {
9994 if (complain & tf_error)
9995 error ("%qT is not an accessible base of %qT",
9996 BINFO_TYPE (cand->conversion_path),
9997 TREE_TYPE (argtype));
9998 else
9999 return error_mark_node;
10000 }
10001 /* If fn was found by a using declaration, the conversion path
10002 will be to the derived class, not the base declaring fn. We
10003 must convert to the base. */
10004 tree base_binfo = cand->conversion_path;
10005 if (BINFO_TYPE (base_binfo) != ctx)
10006 {
10007 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10008 if (base_binfo == error_mark_node)
10009 return error_mark_node;
10010 }
10011
10012 /* If we know the dynamic type of the object, look up the final overrider
10013 in the BINFO. */
10014 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10015 && resolves_to_fixed_type_p (arg))
10016 {
10017 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10018
10019 /* And unwind base_binfo to match. If we don't find the type we're
10020 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10021 inheritance; for now do a normal virtual call in that case. */
10022 tree octx = DECL_CONTEXT (ov);
10023 tree obinfo = base_binfo;
10024 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10025 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10026 if (obinfo)
10027 {
10028 fn = ov;
10029 base_binfo = obinfo;
10030 flags |= LOOKUP_NONVIRTUAL;
10031 }
10032 }
10033
10034 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10035 base_binfo, 1, complain);
10036
10037 argarray[j++] = converted_arg;
10038 parm = TREE_CHAIN (parm);
10039 if (first_arg != NULL_TREE)
10040 first_arg = NULL_TREE;
10041 else
10042 ++arg_index;
10043 ++i;
10044 is_method = 1;
10045 }
10046
10047 gcc_assert (first_arg == NULL_TREE);
10048 for (; arg_index < vec_safe_length (v: args) && parm;
10049 parm = TREE_CHAIN (parm), ++arg_index, ++i)
10050 {
10051 tree type = TREE_VALUE (parm);
10052 tree arg = (*args)[arg_index];
10053 bool conversion_warning = true;
10054
10055 conv = convs[i];
10056
10057 /* If the argument is NULL and used to (implicitly) instantiate a
10058 template function (and bind one of the template arguments to
10059 the type of 'long int'), we don't want to warn about passing NULL
10060 to non-pointer argument.
10061 For example, if we have this template function:
10062
10063 template<typename T> void func(T x) {}
10064
10065 we want to warn (when -Wconversion is enabled) in this case:
10066
10067 void foo() {
10068 func<int>(NULL);
10069 }
10070
10071 but not in this case:
10072
10073 void foo() {
10074 func(NULL);
10075 }
10076 */
10077 if (null_node_p (expr: arg)
10078 && DECL_TEMPLATE_INFO (fn)
10079 && cand->template_decl
10080 && !cand->explicit_targs)
10081 conversion_warning = false;
10082
10083 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10084 knows not to allow any more UDCs. This needs to happen after we
10085 process cand->warnings. */
10086 if (flags & LOOKUP_NO_CONVERSION)
10087 conv->user_conv_p = true;
10088
10089 tsubst_flags_t arg_complain = complain;
10090 if (!conversion_warning)
10091 arg_complain &= ~tf_warning;
10092
10093 if (arg_complain & tf_warning)
10094 maybe_warn_pessimizing_move (arg, type, /*return_p*/false);
10095
10096 val = convert_like_with_context (convs: conv, expr: arg, fn, argnum: i - is_method,
10097 complain: arg_complain);
10098 val = convert_for_arg_passing (type, val, complain: arg_complain);
10099
10100 if (val == error_mark_node)
10101 return error_mark_node;
10102 else
10103 argarray[j++] = val;
10104 }
10105
10106 /* Default arguments */
10107 for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
10108 {
10109 if (TREE_VALUE (parm) == error_mark_node)
10110 return error_mark_node;
10111 val = convert_default_arg (TREE_VALUE (parm),
10112 TREE_PURPOSE (parm),
10113 fn, parmnum: i - is_method,
10114 complain);
10115 if (val == error_mark_node)
10116 return error_mark_node;
10117 argarray[j++] = val;
10118 }
10119
10120 /* Ellipsis */
10121 int magic = magic_varargs_p (fn);
10122 for (; arg_index < vec_safe_length (v: args); ++arg_index)
10123 {
10124 tree a = (*args)[arg_index];
10125 if (magic == 3 && arg_index == 2)
10126 {
10127 /* Do no conversions for certain magic varargs. */
10128 a = mark_type_use (a);
10129 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10130 return error_mark_node;
10131 }
10132 else if (magic != 0)
10133 {
10134 /* Don't truncate excess precision to the semantic type. */
10135 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10136 a = TREE_OPERAND (a, 0);
10137 /* For other magic varargs only do decay_conversion. */
10138 a = decay_conversion (a, complain);
10139 }
10140 else if (DECL_CONSTRUCTOR_P (fn)
10141 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10142 TREE_TYPE (a)))
10143 {
10144 /* Avoid infinite recursion trying to call A(...). */
10145 if (complain & tf_error)
10146 /* Try to call the actual copy constructor for a good error. */
10147 call_copy_ctor (a, complain);
10148 return error_mark_node;
10149 }
10150 else
10151 a = convert_arg_to_ellipsis (arg: a, complain);
10152 if (a == error_mark_node)
10153 return error_mark_node;
10154 argarray[j++] = a;
10155 }
10156
10157 gcc_assert (j <= nargs);
10158 nargs = j;
10159 icip.reset ();
10160
10161 /* Avoid performing argument transformation if warnings are disabled.
10162 When tf_warning is set and at least one of the warnings is active
10163 the check_function_arguments function might warn about something. */
10164
10165 bool warned_p = false;
10166 if ((complain & tf_warning)
10167 && (warn_nonnull
10168 || warn_format
10169 || warn_suggest_attribute_format
10170 || warn_restrict))
10171 {
10172 tree *fargs = (!nargs ? argarray
10173 : (tree *) alloca (nargs * sizeof (tree)));
10174 for (j = 0; j < nargs; j++)
10175 {
10176 /* For -Wformat undo the implicit passing by hidden reference
10177 done by convert_arg_to_ellipsis. */
10178 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10179 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10180 fargs[j] = TREE_OPERAND (argarray[j], 0);
10181 else
10182 fargs[j] = argarray[j];
10183 }
10184
10185 warned_p = check_function_arguments (loc: input_location, fn, TREE_TYPE (fn),
10186 nargs, fargs, NULL);
10187 }
10188
10189 if (DECL_INHERITED_CTOR (fn))
10190 {
10191 /* Check for passing ellipsis arguments to an inherited constructor. We
10192 could handle this by open-coding the inherited constructor rather than
10193 defining it, but let's not bother now. */
10194 if (!cp_unevaluated_operand
10195 && cand->num_convs
10196 && cand->convs[cand->num_convs-1]->ellipsis_p)
10197 {
10198 if (complain & tf_error)
10199 {
10200 sorry ("passing arguments to ellipsis of inherited constructor "
10201 "%qD", cand->fn);
10202 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10203 }
10204 return error_mark_node;
10205 }
10206
10207 /* A base constructor inheriting from a virtual base doesn't get the
10208 inherited arguments, just this and __vtt. */
10209 if (ctor_omit_inherited_parms (fn))
10210 nargs = 2;
10211 }
10212
10213 /* Avoid actually calling copy constructors and copy assignment operators,
10214 if possible. */
10215
10216 if (! flag_elide_constructors && !force_elide)
10217 /* Do things the hard way. */;
10218 else if (cand->num_convs == 1
10219 && (DECL_COPY_CONSTRUCTOR_P (fn)
10220 || DECL_MOVE_CONSTRUCTOR_P (fn))
10221 /* It's unsafe to elide the constructor when handling
10222 a noexcept-expression, it may evaluate to the wrong
10223 value (c++/53025). */
10224 && (force_elide || cp_noexcept_operand == 0))
10225 {
10226 tree targ;
10227 tree arg = argarray[num_artificial_parms_for (fn)];
10228 tree fa = argarray[0];
10229 bool trivial = trivial_fn_p (fn);
10230
10231 /* Pull out the real argument, disregarding const-correctness. */
10232 targ = arg;
10233 /* Strip the reference binding for the constructor parameter. */
10234 if (CONVERT_EXPR_P (targ)
10235 && TYPE_REF_P (TREE_TYPE (targ)))
10236 targ = TREE_OPERAND (targ, 0);
10237 /* But don't strip any other reference bindings; binding a temporary to a
10238 reference prevents copy elision. */
10239 while ((CONVERT_EXPR_P (targ)
10240 && !TYPE_REF_P (TREE_TYPE (targ)))
10241 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10242 targ = TREE_OPERAND (targ, 0);
10243 if (TREE_CODE (targ) == ADDR_EXPR)
10244 {
10245 targ = TREE_OPERAND (targ, 0);
10246 if (!same_type_ignoring_top_level_qualifiers_p
10247 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10248 targ = NULL_TREE;
10249 }
10250 else
10251 targ = NULL_TREE;
10252
10253 if (targ)
10254 arg = targ;
10255 else
10256 arg = cp_build_fold_indirect_ref (arg);
10257
10258 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10259 potentially-overlapping subobject. */
10260 if (CHECKING_P && cxx_dialect >= cxx17)
10261 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10262 || force_elide
10263 /* It's from binding the ref parm to a packed field. */
10264 || convs[0]->need_temporary_p
10265 || seen_error ()
10266 /* See unsafe_copy_elision_p. */
10267 || unsafe_return_slot_p (fa));
10268
10269 bool unsafe = unsafe_copy_elision_p_opt (target: fa, exp: arg);
10270 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10271
10272 /* [class.copy]: the copy constructor is implicitly defined even if the
10273 implementation elided its use. But don't warn about deprecation when
10274 eliding a temporary, as then no copy is actually performed. */
10275 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10276 if (force_elide)
10277 /* The language says this isn't called. */;
10278 else if (!trivial)
10279 {
10280 if (!mark_used (fn, complain) && !(complain & tf_error))
10281 return error_mark_node;
10282 already_used = true;
10283 }
10284 else
10285 cp_handle_deprecated_or_unavailable (fn, complain);
10286
10287 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10288 && !make_base_init_ok (exp: arg))
10289 unsafe = true;
10290
10291 /* If we're creating a temp and we already have one, don't create a
10292 new one. If we're not creating a temp but we get one, use
10293 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10294 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10295 temp or an INIT_EXPR otherwise. */
10296 if (is_dummy_object (fa))
10297 {
10298 if (TREE_CODE (arg) == TARGET_EXPR)
10299 return arg;
10300 else if (trivial)
10301 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10302 }
10303 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10304 && !unsafe)
10305 {
10306 tree to = cp_build_fold_indirect_ref (fa);
10307 val = cp_build_init_expr (t: to, i: arg);
10308 return val;
10309 }
10310 }
10311 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10312 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10313 && trivial_fn_p (fn))
10314 {
10315 tree to = cp_build_fold_indirect_ref (argarray[0]);
10316 tree type = TREE_TYPE (to);
10317 tree as_base = CLASSTYPE_AS_BASE (type);
10318 tree arg = argarray[1];
10319 location_t loc = cp_expr_loc_or_input_loc (t: arg);
10320
10321 if (is_really_empty_class (type, /*ignore_vptr*/true))
10322 {
10323 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10324 if the object argument isn't one. This isn't needed in other cases
10325 since MODIFY_EXPR is always considered an lvalue. */
10326 to = cp_build_addr_expr (to, tf_none);
10327 to = cp_build_indirect_ref (input_location, to, RO_ARROW, complain);
10328 val = build2 (COMPOUND_EXPR, type, arg, to);
10329 suppress_warning (val, OPT_Wunused);
10330 }
10331 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10332 {
10333 if (is_std_init_list (type)
10334 && conv_binds_ref_to_prvalue (c: convs[1]))
10335 warning_at (loc, OPT_Winit_list_lifetime,
10336 "assignment from temporary %<initializer_list%> does "
10337 "not extend the lifetime of the underlying array");
10338 arg = cp_build_fold_indirect_ref (arg);
10339 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10340 }
10341 else
10342 {
10343 /* We must only copy the non-tail padding parts. */
10344 tree arg0, arg2, t;
10345 tree array_type, alias_set;
10346
10347 arg2 = TYPE_SIZE_UNIT (as_base);
10348 to = cp_stabilize_reference (to);
10349 arg0 = cp_build_addr_expr (to, complain);
10350
10351 array_type = build_array_type (unsigned_char_type_node,
10352 build_index_type
10353 (size_binop (MINUS_EXPR,
10354 arg2, size_int (1))));
10355 alias_set = build_int_cst (build_pointer_type (type), 0);
10356 t = build2 (MODIFY_EXPR, void_type_node,
10357 build2 (MEM_REF, array_type, arg0, alias_set),
10358 build2 (MEM_REF, array_type, arg, alias_set));
10359 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10360 suppress_warning (val, OPT_Wunused);
10361 }
10362
10363 cp_handle_deprecated_or_unavailable (fn, complain);
10364
10365 return val;
10366 }
10367 else if (trivial_fn_p (fn))
10368 {
10369 if (DECL_DESTRUCTOR_P (fn))
10370 return build_trivial_dtor_call (instance: argarray[0]);
10371 else if (default_ctor_p (fn))
10372 {
10373 if (is_dummy_object (argarray[0]))
10374 return force_target_expr (DECL_CONTEXT (fn), void_node,
10375 no_cleanup_complain);
10376 else
10377 return cp_build_fold_indirect_ref (argarray[0]);
10378 }
10379 }
10380
10381 gcc_assert (!force_elide);
10382
10383 if (!already_used
10384 && !mark_used (fn, complain))
10385 return error_mark_node;
10386
10387 /* Warn if the built-in writes to an object of a non-trivial type. */
10388 if (warn_class_memaccess
10389 && vec_safe_length (v: args) >= 2
10390 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10391 maybe_warn_class_memaccess (input_location, fn, args);
10392
10393 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10394 {
10395 tree t;
10396 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10397 DECL_CONTEXT (fn),
10398 ba_any, NULL, complain);
10399 gcc_assert (binfo && binfo != error_mark_node);
10400
10401 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10402 complain);
10403 if (TREE_SIDE_EFFECTS (argarray[0]))
10404 argarray[0] = save_expr (argarray[0]);
10405 t = build_pointer_type (TREE_TYPE (fn));
10406 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10407 TREE_TYPE (fn) = t;
10408 }
10409 else
10410 {
10411 /* If FN is marked deprecated or unavailable, then we've already
10412 issued a diagnostic from mark_used above, so avoid redundantly
10413 issuing another one from build_addr_func. */
10414 auto w = make_temp_override (var&: deprecated_state,
10415 overrider: UNAVAILABLE_DEPRECATED_SUPPRESS);
10416
10417 fn = build_addr_func (function: fn, complain);
10418 if (fn == error_mark_node)
10419 return error_mark_node;
10420
10421 /* We're actually invoking the function. (Immediate functions get an
10422 & when invoking it even though the user didn't use &.) */
10423 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
10424 }
10425
10426 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10427 if (call == error_mark_node)
10428 return call;
10429 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10430 {
10431 tree c = extract_call_expr (call);
10432 /* build_new_op will clear this when appropriate. */
10433 CALL_EXPR_ORDERED_ARGS (c) = true;
10434 }
10435 if (warned_p)
10436 {
10437 tree c = extract_call_expr (call);
10438 if (TREE_CODE (c) == CALL_EXPR)
10439 suppress_warning (c /* Suppress all warnings. */);
10440 }
10441
10442 return call;
10443}
10444
10445namespace
10446{
10447
10448/* Return the DECL of the first non-static subobject of class TYPE
10449 that satisfies the predicate PRED or null if none can be found. */
10450
10451template <class Predicate>
10452tree
10453first_non_static_field (tree type, Predicate pred)
10454{
10455 if (!type || !CLASS_TYPE_P (type))
10456 return NULL_TREE;
10457
10458 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10459 {
10460 if (TREE_CODE (field) != FIELD_DECL)
10461 continue;
10462 if (TREE_STATIC (field))
10463 continue;
10464 if (pred (field))
10465 return field;
10466 }
10467
10468 int i = 0;
10469
10470 for (tree base_binfo, binfo = TYPE_BINFO (type);
10471 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10472 {
10473 tree base = TREE_TYPE (base_binfo);
10474 if (pred (base))
10475 return base;
10476 if (tree field = first_non_static_field (base, pred))
10477 return field;
10478 }
10479
10480 return NULL_TREE;
10481}
10482
10483struct NonPublicField
10484{
10485 bool operator() (const_tree t) const
10486 {
10487 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10488 }
10489};
10490
10491/* Return the DECL of the first non-public subobject of class TYPE
10492 or null if none can be found. */
10493
10494static inline tree
10495first_non_public_field (tree type)
10496{
10497 return first_non_static_field (type, pred: NonPublicField ());
10498}
10499
10500struct NonTrivialField
10501{
10502 bool operator() (const_tree t) const
10503 {
10504 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10505 }
10506};
10507
10508/* Return the DECL of the first non-trivial subobject of class TYPE
10509 or null if none can be found. */
10510
10511static inline tree
10512first_non_trivial_field (tree type)
10513{
10514 return first_non_static_field (type, pred: NonTrivialField ());
10515}
10516
10517} /* unnamed namespace */
10518
10519/* Return true if all copy and move assignment operator overloads for
10520 class TYPE are trivial and at least one of them is not deleted and,
10521 when ACCESS is set, accessible. Return false otherwise. Set
10522 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10523 copy or move assignment. */
10524
10525static bool
10526has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10527{
10528 tree fns = get_class_binding (type, assign_op_identifier);
10529 bool all_trivial = true;
10530
10531 /* Iterate over overloads of the assignment operator, checking
10532 accessible copy assignments for triviality. */
10533
10534 for (tree f : ovl_range (fns))
10535 {
10536 /* Skip operators that aren't copy assignments. */
10537 if (!copy_fn_p (f))
10538 continue;
10539
10540 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10541 || accessible_p (TYPE_BINFO (type), f, true));
10542
10543 /* Skip template assignment operators and deleted functions. */
10544 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10545 continue;
10546
10547 if (accessible)
10548 *hasassign = true;
10549
10550 if (!accessible || !trivial_fn_p (f))
10551 all_trivial = false;
10552
10553 /* Break early when both properties have been determined. */
10554 if (*hasassign && !all_trivial)
10555 break;
10556 }
10557
10558 /* Return true if they're all trivial and one of the expressions
10559 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10560 tree ref = cp_build_reference_type (type, false);
10561 return (all_trivial
10562 && (is_trivially_xible (MODIFY_EXPR, type, type)
10563 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10564}
10565
10566/* Return true if all copy and move ctor overloads for class TYPE are
10567 trivial and at least one of them is not deleted and, when ACCESS is
10568 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10569 to true when the TYPE has a (not necessarily trivial) default and copy
10570 (or move) ctor, respectively. */
10571
10572static bool
10573has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10574{
10575 tree fns = get_class_binding (type, complete_ctor_identifier);
10576 bool all_trivial = true;
10577
10578 for (tree f : ovl_range (fns))
10579 {
10580 /* Skip template constructors. */
10581 if (TREE_CODE (f) != FUNCTION_DECL)
10582 continue;
10583
10584 bool cpy_or_move_ctor_p = copy_fn_p (f);
10585
10586 /* Skip ctors other than default, copy, and move. */
10587 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10588 continue;
10589
10590 if (DECL_DELETED_FN (f))
10591 continue;
10592
10593 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10594 || accessible_p (TYPE_BINFO (type), f, true));
10595
10596 if (accessible)
10597 hasctor[cpy_or_move_ctor_p] = true;
10598
10599 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10600 all_trivial = false;
10601
10602 /* Break early when both properties have been determined. */
10603 if (hasctor[0] && hasctor[1] && !all_trivial)
10604 break;
10605 }
10606
10607 return all_trivial;
10608}
10609
10610/* Issue a warning on a call to the built-in function FNDECL if it is
10611 a raw memory write whose destination is not an object of (something
10612 like) trivial or standard layout type with a non-deleted assignment
10613 and copy ctor. Detects const correctness violations, corrupting
10614 references, virtual table pointers, and bypassing non-trivial
10615 assignments. */
10616
10617static void
10618maybe_warn_class_memaccess (location_t loc, tree fndecl,
10619 const vec<tree, va_gc> *args)
10620{
10621 /* Except for bcopy where it's second, the destination pointer is
10622 the first argument for all functions handled here. Compute
10623 the index of the destination and source arguments. */
10624 unsigned dstidx = DECL_FUNCTION_CODE (decl: fndecl) == BUILT_IN_BCOPY;
10625 unsigned srcidx = !dstidx;
10626
10627 tree dest = (*args)[dstidx];
10628 if (!TREE_TYPE (dest)
10629 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10630 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10631 return;
10632
10633 tree srctype = NULL_TREE;
10634
10635 /* Determine the type of the pointed-to object and whether it's
10636 a complete class type. */
10637 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10638
10639 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10640 return;
10641
10642 /* Check to see if the raw memory call is made by a non-static member
10643 function with THIS as the destination argument for the destination
10644 type. If so, and if the class has no non-trivial bases or members,
10645 be more permissive. */
10646 if (current_function_decl
10647 && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10648 && is_this_parameter (tree_strip_nop_conversions (dest)))
10649 {
10650 tree ctx = DECL_CONTEXT (current_function_decl);
10651 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10652 tree binfo = TYPE_BINFO (ctx);
10653
10654 if (special
10655 && !BINFO_VTABLE (binfo)
10656 && !first_non_trivial_field (type: desttype))
10657 return;
10658 }
10659
10660 /* True if the class is trivial. */
10661 bool trivial = trivial_type_p (desttype);
10662
10663 /* Set to true if DESTYPE has an accessible copy assignment. */
10664 bool hasassign = false;
10665 /* True if all of the class' overloaded copy assignment operators
10666 are all trivial (and not deleted) and at least one of them is
10667 accessible. */
10668 bool trivassign = has_trivial_copy_assign_p (type: desttype, access: true, hasassign: &hasassign);
10669
10670 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10671 respectively. */
10672 bool hasctors[2] = { false, false };
10673
10674 /* True if all of the class' overloaded copy constructors are all
10675 trivial (and not deleted) and at least one of them is accessible. */
10676 bool trivcopy = has_trivial_copy_p (type: desttype, access: true, hasctor: hasctors);
10677
10678 /* Set FLD to the first private/protected member of the class. */
10679 tree fld = trivial ? first_non_public_field (type: desttype) : NULL_TREE;
10680
10681 /* The warning format string. */
10682 const char *warnfmt = NULL;
10683 /* A suggested alternative to offer instead of the raw memory call.
10684 Empty string when none can be come up with. */
10685 const char *suggest = "";
10686 bool warned = false;
10687
10688 switch (DECL_FUNCTION_CODE (decl: fndecl))
10689 {
10690 case BUILT_IN_MEMSET:
10691 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10692 {
10693 /* Diagnose setting non-copy-assignable or non-trivial types,
10694 or types with a private member, to (potentially) non-zero
10695 bytes. Since the value of the bytes being written is unknown,
10696 suggest using assignment instead (if one exists). Also warn
10697 for writes into objects for which zero-initialization doesn't
10698 mean all bits clear (pointer-to-member data, where null is all
10699 bits set). Since the value being written is (most likely)
10700 non-zero, simply suggest assignment (but not copy assignment). */
10701 suggest = "; use assignment instead";
10702 if (!trivassign)
10703 warnfmt = G_("%qD writing to an object of type %#qT with "
10704 "no trivial copy-assignment");
10705 else if (!trivial)
10706 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10707 else if (fld)
10708 {
10709 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10710 warned = warning_at (loc, OPT_Wclass_memaccess,
10711 "%qD writing to an object of type %#qT with "
10712 "%qs member %qD",
10713 fndecl, desttype, access, fld);
10714 }
10715 else if (!zero_init_p (desttype))
10716 warnfmt = G_("%qD writing to an object of type %#qT containing "
10717 "a pointer to data member%s");
10718
10719 break;
10720 }
10721 /* Fall through. */
10722
10723 case BUILT_IN_BZERO:
10724 /* Similarly to the above, diagnose clearing non-trivial or non-
10725 standard layout objects, or objects of types with no assignmenmt.
10726 Since the value being written is known to be zero, suggest either
10727 copy assignment, copy ctor, or default ctor as an alternative,
10728 depending on what's available. */
10729
10730 if (hasassign && hasctors[0])
10731 suggest = G_("; use assignment or value-initialization instead");
10732 else if (hasassign)
10733 suggest = G_("; use assignment instead");
10734 else if (hasctors[0])
10735 suggest = G_("; use value-initialization instead");
10736
10737 if (!trivassign)
10738 warnfmt = G_("%qD clearing an object of type %#qT with "
10739 "no trivial copy-assignment%s");
10740 else if (!trivial)
10741 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10742 else if (!zero_init_p (desttype))
10743 warnfmt = G_("%qD clearing an object of type %#qT containing "
10744 "a pointer-to-member%s");
10745 break;
10746
10747 case BUILT_IN_BCOPY:
10748 case BUILT_IN_MEMCPY:
10749 case BUILT_IN_MEMMOVE:
10750 case BUILT_IN_MEMPCPY:
10751 /* Determine the type of the source object. */
10752 srctype = TREE_TYPE ((*args)[srcidx]);
10753 if (!srctype || !INDIRECT_TYPE_P (srctype))
10754 srctype = void_type_node;
10755 else
10756 srctype = TREE_TYPE (srctype);
10757
10758 /* Since it's impossible to determine wheter the byte copy is
10759 being used in place of assignment to an existing object or
10760 as a substitute for initialization, assume it's the former.
10761 Determine the best alternative to use instead depending on
10762 what's not deleted. */
10763 if (hasassign && hasctors[1])
10764 suggest = G_("; use copy-assignment or copy-initialization instead");
10765 else if (hasassign)
10766 suggest = G_("; use copy-assignment instead");
10767 else if (hasctors[1])
10768 suggest = G_("; use copy-initialization instead");
10769
10770 if (!trivassign)
10771 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10772 "copy-assignment%s");
10773 else if (!trivially_copyable_p (desttype))
10774 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10775 "type %#qT%s");
10776 else if (!trivcopy)
10777 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10778
10779 else if (!trivial
10780 && !VOID_TYPE_P (srctype)
10781 && !is_byte_access_type (srctype)
10782 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10783 srctype))
10784 {
10785 /* Warn when copying into a non-trivial object from an object
10786 of a different type other than void or char. */
10787 warned = warning_at (loc, OPT_Wclass_memaccess,
10788 "%qD copying an object of non-trivial type "
10789 "%#qT from an array of %#qT",
10790 fndecl, desttype, srctype);
10791 }
10792 else if (fld
10793 && !VOID_TYPE_P (srctype)
10794 && !is_byte_access_type (srctype)
10795 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10796 srctype))
10797 {
10798 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10799 warned = warning_at (loc, OPT_Wclass_memaccess,
10800 "%qD copying an object of type %#qT with "
10801 "%qs member %qD from an array of %#qT; use "
10802 "assignment or copy-initialization instead",
10803 fndecl, desttype, access, fld, srctype);
10804 }
10805 else if (!trivial && vec_safe_length (v: args) > 2)
10806 {
10807 tree sz = maybe_constant_value ((*args)[2]);
10808 if (!tree_fits_uhwi_p (sz))
10809 break;
10810
10811 /* Finally, warn on partial copies. */
10812 unsigned HOST_WIDE_INT typesize
10813 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10814 if (typesize == 0)
10815 break;
10816 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10817 warned = warning_at (loc, OPT_Wclass_memaccess,
10818 (typesize - partial > 1
10819 ? G_("%qD writing to an object of "
10820 "a non-trivial type %#qT leaves %wu "
10821 "bytes unchanged")
10822 : G_("%qD writing to an object of "
10823 "a non-trivial type %#qT leaves %wu "
10824 "byte unchanged")),
10825 fndecl, desttype, typesize - partial);
10826 }
10827 break;
10828
10829 case BUILT_IN_REALLOC:
10830
10831 if (!trivially_copyable_p (desttype))
10832 warnfmt = G_("%qD moving an object of non-trivially copyable type "
10833 "%#qT; use %<new%> and %<delete%> instead");
10834 else if (!trivcopy)
10835 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10836 "constructor; use %<new%> and %<delete%> instead");
10837 else if (!get_dtor (desttype, tf_none))
10838 warnfmt = G_("%qD moving an object of type %#qT with deleted "
10839 "destructor");
10840 else if (!trivial)
10841 {
10842 tree sz = maybe_constant_value ((*args)[1]);
10843 if (TREE_CODE (sz) == INTEGER_CST
10844 && tree_int_cst_lt (t1: sz, TYPE_SIZE_UNIT (desttype)))
10845 /* Finally, warn on reallocation into insufficient space. */
10846 warned = warning_at (loc, OPT_Wclass_memaccess,
10847 "%qD moving an object of non-trivial type "
10848 "%#qT and size %E into a region of size %E",
10849 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10850 sz);
10851 }
10852 break;
10853
10854 default:
10855 return;
10856 }
10857
10858 if (warnfmt)
10859 {
10860 if (suggest)
10861 warned = warning_at (loc, OPT_Wclass_memaccess,
10862 warnfmt, fndecl, desttype, suggest);
10863 else
10864 warned = warning_at (loc, OPT_Wclass_memaccess,
10865 warnfmt, fndecl, desttype);
10866 }
10867
10868 if (warned)
10869 inform (location_of (desttype), "%#qT declared here", desttype);
10870}
10871
10872/* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10873 If FN is the result of resolving an overloaded target built-in,
10874 ORIG_FNDECL is the original function decl, otherwise it is null.
10875 This function performs no overload resolution, conversion, or other
10876 high-level operations. */
10877
10878tree
10879build_cxx_call (tree fn, int nargs, tree *argarray,
10880 tsubst_flags_t complain, tree orig_fndecl)
10881{
10882 tree fndecl;
10883
10884 /* Remember roughly where this call is. */
10885 location_t loc = cp_expr_loc_or_input_loc (t: fn);
10886 fn = build_call_a (function: fn, n: nargs, argarray);
10887 SET_EXPR_LOCATION (fn, loc);
10888
10889 fndecl = get_callee_fndecl (fn);
10890 if (!orig_fndecl)
10891 orig_fndecl = fndecl;
10892
10893 /* Check that arguments to builtin functions match the expectations. */
10894 if (fndecl
10895 && !processing_template_decl
10896 && fndecl_built_in_p (node: fndecl))
10897 {
10898 int i;
10899
10900 /* We need to take care that values to BUILT_IN_NORMAL
10901 are reduced. */
10902 for (i = 0; i < nargs; i++)
10903 argarray[i] = maybe_constant_value (argarray[i]);
10904
10905 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10906 orig_fndecl, nargs, argarray))
10907 return error_mark_node;
10908 else if (fndecl_built_in_p (node: fndecl, name1: BUILT_IN_CLEAR_PADDING))
10909 {
10910 tree arg0 = argarray[0];
10911 STRIP_NOPS (arg0);
10912 if (TREE_CODE (arg0) == ADDR_EXPR
10913 && DECL_P (TREE_OPERAND (arg0, 0))
10914 && same_type_ignoring_top_level_qualifiers_p
10915 (TREE_TYPE (TREE_TYPE (argarray[0])),
10916 TREE_TYPE (TREE_TYPE (arg0))))
10917 /* For __builtin_clear_padding (&var) we know the type
10918 is for a complete object, so there is no risk in clearing
10919 padding that is reused in some derived class member. */;
10920 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
10921 {
10922 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
10923 "argument %u in call to function %qE "
10924 "has pointer to a non-trivially-copyable type (%qT)",
10925 1, fndecl, TREE_TYPE (argarray[0]));
10926 return error_mark_node;
10927 }
10928 }
10929 }
10930
10931 if (VOID_TYPE_P (TREE_TYPE (fn)))
10932 return fn;
10933
10934 /* 5.2.2/11: If a function call is a prvalue of object type: if the
10935 function call is either the operand of a decltype-specifier or the
10936 right operand of a comma operator that is the operand of a
10937 decltype-specifier, a temporary object is not introduced for the
10938 prvalue. The type of the prvalue may be incomplete. */
10939 if (!(complain & tf_decltype))
10940 {
10941 fn = require_complete_type (fn, complain);
10942 if (fn == error_mark_node)
10943 return error_mark_node;
10944
10945 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10946 {
10947 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10948 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10949 }
10950 }
10951 return convert_from_reference (fn);
10952}
10953
10954/* Returns the value to use for the in-charge parameter when making a
10955 call to a function with the indicated NAME.
10956
10957 FIXME:Can't we find a neater way to do this mapping? */
10958
10959tree
10960in_charge_arg_for_name (tree name)
10961{
10962 if (IDENTIFIER_CTOR_P (name))
10963 {
10964 if (name == complete_ctor_identifier)
10965 return integer_one_node;
10966 gcc_checking_assert (name == base_ctor_identifier);
10967 }
10968 else
10969 {
10970 if (name == complete_dtor_identifier)
10971 return integer_two_node;
10972 else if (name == deleting_dtor_identifier)
10973 return integer_three_node;
10974 gcc_checking_assert (name == base_dtor_identifier);
10975 }
10976
10977 return integer_zero_node;
10978}
10979
10980/* We've built up a constructor call RET. Complain if it delegates to the
10981 constructor we're currently compiling. */
10982
10983static void
10984check_self_delegation (tree ret)
10985{
10986 if (TREE_CODE (ret) == TARGET_EXPR)
10987 ret = TARGET_EXPR_INITIAL (ret);
10988 tree fn = cp_get_callee_fndecl_nofold (ret);
10989 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
10990 error ("constructor delegates to itself");
10991}
10992
10993/* Build a call to a constructor, destructor, or an assignment
10994 operator for INSTANCE, an expression with class type. NAME
10995 indicates the special member function to call; *ARGS are the
10996 arguments. ARGS may be NULL. This may change ARGS. BINFO
10997 indicates the base of INSTANCE that is to be passed as the `this'
10998 parameter to the member function called.
10999
11000 FLAGS are the LOOKUP_* flags to use when processing the call.
11001
11002 If NAME indicates a complete object constructor, INSTANCE may be
11003 NULL_TREE. In this case, the caller will call build_cplus_new to
11004 store the newly constructed object into a VAR_DECL. */
11005
11006tree
11007build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11008 tree binfo, int flags, tsubst_flags_t complain)
11009{
11010 tree fns;
11011 /* The type of the subobject to be constructed or destroyed. */
11012 tree class_type;
11013 vec<tree, va_gc> *allocated = NULL;
11014 tree ret;
11015
11016 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11017
11018 if (error_operand_p (t: instance))
11019 return error_mark_node;
11020
11021 if (IDENTIFIER_DTOR_P (name))
11022 {
11023 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11024 if (!type_build_dtor_call (TREE_TYPE (instance)))
11025 /* Shortcut to avoid lazy destructor declaration. */
11026 return build_trivial_dtor_call (instance);
11027 }
11028
11029 if (TYPE_P (binfo))
11030 {
11031 /* Resolve the name. */
11032 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11033 return error_mark_node;
11034
11035 binfo = TYPE_BINFO (binfo);
11036 }
11037
11038 gcc_assert (binfo != NULL_TREE);
11039
11040 class_type = BINFO_TYPE (binfo);
11041
11042 /* Handle the special case where INSTANCE is NULL_TREE. */
11043 if (name == complete_ctor_identifier && !instance)
11044 instance = build_dummy_object (class_type);
11045 else
11046 {
11047 /* Convert to the base class, if necessary. */
11048 if (!same_type_ignoring_top_level_qualifiers_p
11049 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11050 {
11051 if (IDENTIFIER_CDTOR_P (name))
11052 /* For constructors and destructors, either the base is
11053 non-virtual, or it is virtual but we are doing the
11054 conversion from a constructor or destructor for the
11055 complete object. In either case, we can convert
11056 statically. */
11057 instance = convert_to_base_statically (instance, binfo);
11058 else
11059 {
11060 /* However, for assignment operators, we must convert
11061 dynamically if the base is virtual. */
11062 gcc_checking_assert (name == assign_op_identifier);
11063 instance = build_base_path (PLUS_EXPR, instance,
11064 binfo, /*nonnull=*/1, complain);
11065 }
11066 }
11067 }
11068
11069 gcc_assert (instance != NULL_TREE);
11070
11071 /* In C++17, "If the initializer expression is a prvalue and the
11072 cv-unqualified version of the source type is the same class as the class
11073 of the destination, the initializer expression is used to initialize the
11074 destination object." Handle that here to avoid doing overload
11075 resolution. */
11076 if (cxx_dialect >= cxx17
11077 && args && vec_safe_length (v: *args) == 1
11078 && !unsafe_return_slot_p (t: instance))
11079 {
11080 tree arg = (**args)[0];
11081
11082 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11083 && !TYPE_HAS_LIST_CTOR (class_type)
11084 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11085 && CONSTRUCTOR_NELTS (arg) == 1)
11086 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11087
11088 if ((TREE_CODE (arg) == TARGET_EXPR
11089 || TREE_CODE (arg) == CONSTRUCTOR)
11090 && (same_type_ignoring_top_level_qualifiers_p
11091 (class_type, TREE_TYPE (arg))))
11092 {
11093 if (is_dummy_object (instance))
11094 return arg;
11095 else if (TREE_CODE (arg) == TARGET_EXPR)
11096 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11097
11098 if ((complain & tf_error)
11099 && (flags & LOOKUP_DELEGATING_CONS))
11100 check_self_delegation (ret: arg);
11101 /* Avoid change of behavior on Wunused-var-2.C. */
11102 instance = mark_lvalue_use (instance);
11103 return cp_build_init_expr (t: instance, i: arg);
11104 }
11105 }
11106
11107 fns = lookup_fnfields (binfo, name, 1, complain);
11108
11109 /* When making a call to a constructor or destructor for a subobject
11110 that uses virtual base classes, pass down a pointer to a VTT for
11111 the subobject. */
11112 if ((name == base_ctor_identifier
11113 || name == base_dtor_identifier)
11114 && CLASSTYPE_VBASECLASSES (class_type))
11115 {
11116 tree vtt;
11117 tree sub_vtt;
11118
11119 /* If the current function is a complete object constructor
11120 or destructor, then we fetch the VTT directly.
11121 Otherwise, we look it up using the VTT we were given. */
11122 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11123 vtt = decay_conversion (vtt, complain);
11124 if (vtt == error_mark_node)
11125 return error_mark_node;
11126 vtt = build_if_in_charge (true_stmt: vtt, current_vtt_parm);
11127 if (BINFO_SUBVTT_INDEX (binfo))
11128 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11129 else
11130 sub_vtt = vtt;
11131
11132 if (args == NULL)
11133 {
11134 allocated = make_tree_vector ();
11135 args = &allocated;
11136 }
11137
11138 vec_safe_insert (v&: *args, ix: 0, obj: sub_vtt);
11139 }
11140
11141 ret = build_new_method_call (instance, fns, args,
11142 TYPE_BINFO (BINFO_TYPE (binfo)),
11143 flags, /*fn=*/NULL,
11144 complain);
11145
11146 if (allocated != NULL)
11147 release_tree_vector (allocated);
11148
11149 if ((complain & tf_error)
11150 && (flags & LOOKUP_DELEGATING_CONS)
11151 && name == complete_ctor_identifier)
11152 check_self_delegation (ret);
11153
11154 return ret;
11155}
11156
11157/* Return the NAME, as a C string. The NAME indicates a function that
11158 is a member of TYPE. *FREE_P is set to true if the caller must
11159 free the memory returned.
11160
11161 Rather than go through all of this, we should simply set the names
11162 of constructors and destructors appropriately, and dispense with
11163 ctor_identifier, dtor_identifier, etc. */
11164
11165static char *
11166name_as_c_string (tree name, tree type, bool *free_p)
11167{
11168 const char *pretty_name;
11169
11170 /* Assume that we will not allocate memory. */
11171 *free_p = false;
11172 /* Constructors and destructors are special. */
11173 if (IDENTIFIER_CDTOR_P (name))
11174 {
11175 pretty_name
11176 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11177 /* For a destructor, add the '~'. */
11178 if (IDENTIFIER_DTOR_P (name))
11179 {
11180 pretty_name = concat ("~", pretty_name, NULL);
11181 /* Remember that we need to free the memory allocated. */
11182 *free_p = true;
11183 }
11184 }
11185 else if (IDENTIFIER_CONV_OP_P (name))
11186 {
11187 pretty_name = concat ("operator ",
11188 type_as_string_translate (TREE_TYPE (name),
11189 TFF_PLAIN_IDENTIFIER),
11190 NULL);
11191 /* Remember that we need to free the memory allocated. */
11192 *free_p = true;
11193 }
11194 else
11195 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11196
11197 return CONST_CAST (char *, pretty_name);
11198}
11199
11200/* If CANDIDATES contains exactly one candidate, return it, otherwise
11201 return NULL. */
11202
11203static z_candidate *
11204single_z_candidate (z_candidate *candidates)
11205{
11206 if (candidates == NULL)
11207 return NULL;
11208
11209 if (candidates->next)
11210 return NULL;
11211
11212 return candidates;
11213}
11214
11215/* If CANDIDATE is invalid due to a bad argument type, return the
11216 pertinent conversion_info.
11217
11218 Otherwise, return NULL. */
11219
11220static const conversion_info *
11221maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11222{
11223 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11224 rejection_reason *r = candidate->reason;
11225
11226 if (r == NULL)
11227 return NULL;
11228
11229 switch (r->code)
11230 {
11231 default:
11232 return NULL;
11233
11234 case rr_arg_conversion:
11235 return &r->u.conversion;
11236
11237 case rr_bad_arg_conversion:
11238 return &r->u.bad_conversion;
11239 }
11240}
11241
11242/* Issue an error and note complaining about a bad argument type at a
11243 callsite with a single candidate FNDECL.
11244
11245 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11246 case input_location is used).
11247 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11248 the formal parameter. */
11249
11250void
11251complain_about_bad_argument (location_t arg_loc,
11252 tree from_type, tree to_type,
11253 tree fndecl, int parmnum)
11254{
11255 auto_diagnostic_group d;
11256 range_label_for_type_mismatch rhs_label (from_type, to_type);
11257 range_label *label = &rhs_label;
11258 if (arg_loc == UNKNOWN_LOCATION)
11259 {
11260 arg_loc = input_location;
11261 label = NULL;
11262 }
11263 gcc_rich_location richloc (arg_loc, label);
11264 error_at (&richloc,
11265 "cannot convert %qH to %qI",
11266 from_type, to_type);
11267 maybe_inform_about_fndecl_for_bogus_argument_init (fn: fndecl,
11268 argnum: parmnum);
11269}
11270
11271/* Subroutine of build_new_method_call_1, for where there are no viable
11272 candidates for the call. */
11273
11274static void
11275complain_about_no_candidates_for_method_call (tree instance,
11276 z_candidate *candidates,
11277 tree explicit_targs,
11278 tree basetype,
11279 tree optype, tree name,
11280 bool skip_first_for_error,
11281 vec<tree, va_gc> *user_args)
11282{
11283 auto_diagnostic_group d;
11284 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11285 cxx_incomplete_type_error (value: instance, type: basetype);
11286 else if (optype)
11287 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11288 basetype, optype, build_tree_list_vec (user_args),
11289 TREE_TYPE (instance));
11290 else
11291 {
11292 /* Special-case for when there's a single candidate that's failing
11293 due to a bad argument type. */
11294 if (z_candidate *candidate = single_z_candidate (candidates))
11295 if (const conversion_info *conv
11296 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11297 {
11298 tree from_type = conv->from;
11299 if (!TYPE_P (conv->from))
11300 from_type = lvalue_type (conv->from);
11301 complain_about_bad_argument (arg_loc: conv->loc,
11302 from_type, to_type: conv->to_type,
11303 fndecl: candidate->fn, parmnum: conv->n_arg);
11304 return;
11305 }
11306
11307 tree arglist = build_tree_list_vec (user_args);
11308 tree errname = name;
11309 bool twiddle = false;
11310 if (IDENTIFIER_CDTOR_P (errname))
11311 {
11312 twiddle = IDENTIFIER_DTOR_P (errname);
11313 errname = constructor_name (basetype);
11314 }
11315 if (explicit_targs)
11316 errname = lookup_template_function (errname, explicit_targs);
11317 if (skip_first_for_error)
11318 arglist = TREE_CHAIN (arglist);
11319 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11320 basetype, &"~"[!twiddle], errname, arglist,
11321 TREE_TYPE (instance));
11322 }
11323 print_z_candidates (loc: location_of (name), candidates);
11324}
11325
11326/* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11327 be set, upon return, to the function called. ARGS may be NULL.
11328 This may change ARGS. */
11329
11330tree
11331build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11332 tree conversion_path, int flags,
11333 tree *fn_p, tsubst_flags_t complain)
11334{
11335 struct z_candidate *candidates = 0, *cand;
11336 tree explicit_targs = NULL_TREE;
11337 tree basetype = NULL_TREE;
11338 tree access_binfo;
11339 tree optype;
11340 tree first_mem_arg = NULL_TREE;
11341 tree name;
11342 bool skip_first_for_error;
11343 vec<tree, va_gc> *user_args;
11344 tree call;
11345 tree fn;
11346 int template_only = 0;
11347 bool any_viable_p;
11348 tree orig_instance;
11349 tree orig_fns;
11350 vec<tree, va_gc> *orig_args = NULL;
11351
11352 auto_cond_timevar tv (TV_OVERLOAD);
11353
11354 gcc_assert (instance != NULL_TREE);
11355
11356 /* We don't know what function we're going to call, yet. */
11357 if (fn_p)
11358 *fn_p = NULL_TREE;
11359
11360 if (error_operand_p (t: instance)
11361 || !fns || error_operand_p (t: fns))
11362 return error_mark_node;
11363
11364 if (!BASELINK_P (fns))
11365 {
11366 if (complain & tf_error)
11367 error ("call to non-function %qD", fns);
11368 return error_mark_node;
11369 }
11370
11371 orig_instance = instance;
11372 orig_fns = fns;
11373
11374 /* Dismantle the baselink to collect all the information we need. */
11375 if (!conversion_path)
11376 conversion_path = BASELINK_BINFO (fns);
11377 access_binfo = BASELINK_ACCESS_BINFO (fns);
11378 optype = BASELINK_OPTYPE (fns);
11379 fns = BASELINK_FUNCTIONS (fns);
11380 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11381 {
11382 explicit_targs = TREE_OPERAND (fns, 1);
11383 fns = TREE_OPERAND (fns, 0);
11384 template_only = 1;
11385 }
11386 gcc_assert (OVL_P (fns));
11387 fn = OVL_FIRST (fns);
11388 name = DECL_NAME (fn);
11389
11390 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11391 gcc_assert (CLASS_TYPE_P (basetype));
11392
11393 user_args = args == NULL ? NULL : *args;
11394 /* Under DR 147 A::A() is an invalid constructor call,
11395 not a functional cast. */
11396 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11397 {
11398 if (! (complain & tf_error))
11399 return error_mark_node;
11400
11401 basetype = DECL_CONTEXT (fn);
11402 name = constructor_name (basetype);
11403 auto_diagnostic_group d;
11404 if (permerror (input_location,
11405 "cannot call constructor %<%T::%D%> directly",
11406 basetype, name))
11407 inform (input_location, "for a function-style cast, remove the "
11408 "redundant %<::%D%>", name);
11409 call = build_functional_cast (input_location, basetype,
11410 build_tree_list_vec (user_args),
11411 complain);
11412 return call;
11413 }
11414
11415 if (processing_template_decl)
11416 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11417
11418 /* Process the argument list. */
11419 if (args != NULL && *args != NULL)
11420 {
11421 *args = resolve_args (args: *args, complain);
11422 if (*args == NULL)
11423 return error_mark_node;
11424 user_args = *args;
11425 }
11426
11427 /* Consider the object argument to be used even if we end up selecting a
11428 static member function. */
11429 instance = mark_type_use (instance);
11430
11431 /* Figure out whether to skip the first argument for the error
11432 message we will display to users if an error occurs. We don't
11433 want to display any compiler-generated arguments. The "this"
11434 pointer hasn't been added yet. However, we must remove the VTT
11435 pointer if this is a call to a base-class constructor or
11436 destructor. */
11437 skip_first_for_error = false;
11438 if (IDENTIFIER_CDTOR_P (name))
11439 {
11440 /* Callers should explicitly indicate whether they want to ctor
11441 the complete object or just the part without virtual bases. */
11442 gcc_assert (name != ctor_identifier);
11443
11444 /* Remove the VTT pointer, if present. */
11445 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11446 && CLASSTYPE_VBASECLASSES (basetype))
11447 skip_first_for_error = true;
11448
11449 /* It's OK to call destructors and constructors on cv-qualified
11450 objects. Therefore, convert the INSTANCE to the unqualified
11451 type, if necessary. */
11452 if (!same_type_p (basetype, TREE_TYPE (instance)))
11453 {
11454 instance = build_this (obj: instance);
11455 instance = build_nop (build_pointer_type (basetype), instance);
11456 instance = build_fold_indirect_ref (instance);
11457 }
11458 }
11459 else
11460 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11461
11462 /* For the overload resolution we need to find the actual `this`
11463 that would be captured if the call turns out to be to a
11464 non-static member function. Do not actually capture it at this
11465 point. */
11466 if (DECL_CONSTRUCTOR_P (fn))
11467 /* Constructors don't use the enclosing 'this'. */
11468 first_mem_arg = instance;
11469 else
11470 first_mem_arg = maybe_resolve_dummy (instance, false);
11471
11472 conversion_obstack_sentinel cos;
11473
11474 /* The number of arguments artificial parms in ARGS; we subtract one because
11475 there's no 'this' in ARGS. */
11476 unsigned skip = num_artificial_parms_for (fn) - 1;
11477
11478 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11479 initializer, not T({ }). */
11480 if (DECL_CONSTRUCTOR_P (fn)
11481 && vec_safe_length (v: user_args) > skip
11482 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11483 {
11484 tree init_list = (*user_args)[skip];
11485 tree init = NULL_TREE;
11486
11487 gcc_assert (user_args->length () == skip + 1
11488 && !(flags & LOOKUP_ONLYCONVERTING));
11489
11490 /* If the initializer list has no elements and T is a class type with
11491 a default constructor, the object is value-initialized. Handle
11492 this here so we don't need to handle it wherever we use
11493 build_special_member_call. */
11494 if (CONSTRUCTOR_NELTS (init_list) == 0
11495 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11496 /* For a user-provided default constructor, use the normal
11497 mechanisms so that protected access works. */
11498 && type_has_non_user_provided_default_constructor (basetype)
11499 && !processing_template_decl)
11500 init = build_value_init (basetype, complain);
11501
11502 /* If BASETYPE is an aggregate, we need to do aggregate
11503 initialization. */
11504 else if (CP_AGGREGATE_TYPE_P (basetype))
11505 {
11506 init = reshape_init (basetype, init_list, complain);
11507 init = digest_init (basetype, init, complain);
11508 }
11509
11510 if (init)
11511 {
11512 if (is_dummy_object (instance))
11513 return get_target_expr (init, complain);
11514 return cp_build_init_expr (t: instance, i: init);
11515 }
11516
11517 /* Otherwise go ahead with overload resolution. */
11518 add_list_candidates (fns, first_arg: first_mem_arg, args: user_args,
11519 totype: basetype, explicit_targs, template_only,
11520 conversion_path, access_path: access_binfo, flags,
11521 candidates: &candidates, complain);
11522 }
11523 else
11524 add_candidates (fns, first_arg: first_mem_arg, args: user_args, return_type: optype,
11525 explicit_targs, template_only, conversion_path,
11526 access_path: access_binfo, flags, candidates: &candidates, complain);
11527
11528 any_viable_p = false;
11529 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
11530
11531 if (!any_viable_p)
11532 {
11533 /* [dcl.init], 17.6.2.2:
11534
11535 Otherwise, if no constructor is viable, the destination type is
11536 a (possibly cv-qualified) aggregate class A, and the initializer
11537 is a parenthesized expression-list, the object is initialized as
11538 follows...
11539
11540 We achieve this by building up a CONSTRUCTOR, as for list-init,
11541 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11542 the two. */
11543 if (DECL_CONSTRUCTOR_P (fn)
11544 && !(flags & LOOKUP_ONLYCONVERTING)
11545 && cxx_dialect >= cxx20
11546 && CP_AGGREGATE_TYPE_P (basetype)
11547 && !vec_safe_is_empty (v: user_args))
11548 {
11549 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11550 tree ctor = build_constructor_from_vec (init_list_type_node,
11551 user_args);
11552 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11553 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11554 if (is_dummy_object (instance))
11555 return ctor;
11556 else
11557 {
11558 ctor = digest_init (basetype, ctor, complain);
11559 if (ctor == error_mark_node)
11560 return error_mark_node;
11561 return cp_build_init_expr (t: instance, i: ctor);
11562 }
11563 }
11564 if (complain & tf_error)
11565 complain_about_no_candidates_for_method_call (instance, candidates,
11566 explicit_targs, basetype,
11567 optype, name,
11568 skip_first_for_error,
11569 user_args);
11570 call = error_mark_node;
11571 }
11572 else
11573 {
11574 cand = tourney (candidates, complain);
11575 if (cand == 0)
11576 {
11577 char *pretty_name;
11578 bool free_p;
11579 tree arglist;
11580
11581 if (complain & tf_error)
11582 {
11583 pretty_name = name_as_c_string (name, type: basetype, free_p: &free_p);
11584 arglist = build_tree_list_vec (user_args);
11585 if (skip_first_for_error)
11586 arglist = TREE_CHAIN (arglist);
11587 auto_diagnostic_group d;
11588 if (!any_strictly_viable (cands: candidates))
11589 error ("no matching function for call to %<%s(%A)%>",
11590 pretty_name, arglist);
11591 else
11592 error ("call of overloaded %<%s(%A)%> is ambiguous",
11593 pretty_name, arglist);
11594 print_z_candidates (loc: location_of (name), candidates);
11595 if (free_p)
11596 free (ptr: pretty_name);
11597 }
11598 call = error_mark_node;
11599 if (fn_p)
11600 *fn_p = error_mark_node;
11601 }
11602 else
11603 {
11604 fn = cand->fn;
11605 call = NULL_TREE;
11606
11607 if (!(flags & LOOKUP_NONVIRTUAL)
11608 && DECL_PURE_VIRTUAL_P (fn)
11609 && instance == current_class_ref
11610 && (complain & tf_warning))
11611 {
11612 /* This is not an error, it is runtime undefined
11613 behavior. */
11614 if (!current_function_decl)
11615 warning (0, "pure virtual %q#D called from "
11616 "non-static data member initializer", fn);
11617 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11618 || DECL_DESTRUCTOR_P (current_function_decl))
11619 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11620 ? G_("pure virtual %q#D called from constructor")
11621 : G_("pure virtual %q#D called from destructor")),
11622 fn);
11623 }
11624
11625 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11626 && !DECL_CONSTRUCTOR_P (fn)
11627 && is_dummy_object (instance))
11628 {
11629 instance = maybe_resolve_dummy (instance, true);
11630 if (instance == error_mark_node)
11631 call = error_mark_node;
11632 else if (!is_dummy_object (instance))
11633 {
11634 /* We captured 'this' in the current lambda now that
11635 we know we really need it. */
11636 cand->first_arg = instance;
11637 }
11638 else if (current_class_ptr && any_dependent_bases_p ())
11639 /* We can't tell until instantiation time whether we can use
11640 *this as the implicit object argument. */;
11641 else
11642 {
11643 if (complain & tf_error)
11644 error ("cannot call member function %qD without object",
11645 fn);
11646 call = error_mark_node;
11647 }
11648 }
11649
11650 if (call != error_mark_node)
11651 {
11652 /* Now we know what function is being called. */
11653 if (fn_p)
11654 *fn_p = fn;
11655 /* Build the actual CALL_EXPR. */
11656 call = build_over_call (cand, flags, complain);
11657
11658 /* Suppress warnings for if (my_struct.operator= (x)) where
11659 my_struct is implicitly converted to bool. */
11660 if (TREE_CODE (call) == MODIFY_EXPR)
11661 suppress_warning (call, OPT_Wparentheses);
11662
11663 /* In an expression of the form `a->f()' where `f' turns
11664 out to be a static member function, `a' is
11665 none-the-less evaluated. */
11666 if (!is_dummy_object (instance))
11667 call = keep_unused_object_arg (result: call, obj: instance, fn);
11668 if (call != error_mark_node
11669 && DECL_DESTRUCTOR_P (cand->fn)
11670 && !VOID_TYPE_P (TREE_TYPE (call)))
11671 /* An explicit call of the form "x->~X()" has type
11672 "void". However, on platforms where destructors
11673 return "this" (i.e., those where
11674 targetm.cxx.cdtor_returns_this is true), such calls
11675 will appear to have a return value of pointer type
11676 to the low-level call machinery. We do not want to
11677 change the low-level machinery, since we want to be
11678 able to optimize "delete f()" on such platforms as
11679 "operator delete(~X(f()))" (rather than generating
11680 "t = f(), ~X(t), operator delete (t)"). */
11681 call = build_nop (void_type_node, call);
11682 }
11683 }
11684 }
11685
11686 if (processing_template_decl && call != error_mark_node)
11687 {
11688 bool cast_to_void = false;
11689
11690 if (TREE_CODE (call) == COMPOUND_EXPR)
11691 call = TREE_OPERAND (call, 1);
11692 else if (TREE_CODE (call) == NOP_EXPR)
11693 {
11694 cast_to_void = true;
11695 call = TREE_OPERAND (call, 0);
11696 }
11697 if (INDIRECT_REF_P (call))
11698 call = TREE_OPERAND (call, 0);
11699
11700 /* Prune all but the selected function from the original overload
11701 set so that we can avoid some duplicate work at instantiation time. */
11702 if (really_overloaded_fn (fns))
11703 {
11704 if (DECL_TEMPLATE_INFO (fn)
11705 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11706 {
11707 /* Use the selected template, not the specialization, so that
11708 this looks like an actual lookup result for sake of
11709 filter_memfn_lookup. */
11710
11711 if (OVL_SINGLE_P (fns))
11712 /* If the original overload set consists of a single function
11713 template, this isn't beneficial. */
11714 goto skip_prune;
11715
11716 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11717 if (template_only)
11718 fn = lookup_template_function (fn, explicit_targs);
11719 }
11720 orig_fns = copy_node (orig_fns);
11721 BASELINK_FUNCTIONS (orig_fns) = fn;
11722 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11723 }
11724
11725skip_prune:
11726 call = (build_min_non_dep_call_vec
11727 (call,
11728 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11729 orig_instance, orig_fns, NULL_TREE),
11730 orig_args));
11731 SET_EXPR_LOCATION (call, input_location);
11732 call = convert_from_reference (call);
11733 if (cast_to_void)
11734 call = build_nop (void_type_node, call);
11735 }
11736
11737 if (orig_args != NULL)
11738 release_tree_vector (orig_args);
11739
11740 return call;
11741}
11742
11743/* Returns true iff standard conversion sequence ICS1 is a proper
11744 subsequence of ICS2. */
11745
11746static bool
11747is_subseq (conversion *ics1, conversion *ics2)
11748{
11749 /* We can assume that a conversion of the same code
11750 between the same types indicates a subsequence since we only get
11751 here if the types we are converting from are the same. */
11752
11753 while (ics1->kind == ck_rvalue
11754 || ics1->kind == ck_lvalue)
11755 ics1 = next_conversion (conv: ics1);
11756
11757 while (1)
11758 {
11759 while (ics2->kind == ck_rvalue
11760 || ics2->kind == ck_lvalue)
11761 ics2 = next_conversion (conv: ics2);
11762
11763 if (ics2->kind == ck_user
11764 || !has_next (code: ics2->kind))
11765 /* At this point, ICS1 cannot be a proper subsequence of
11766 ICS2. We can get a USER_CONV when we are comparing the
11767 second standard conversion sequence of two user conversion
11768 sequences. */
11769 return false;
11770
11771 ics2 = next_conversion (conv: ics2);
11772
11773 while (ics2->kind == ck_rvalue
11774 || ics2->kind == ck_lvalue)
11775 ics2 = next_conversion (conv: ics2);
11776
11777 if (ics2->kind == ics1->kind
11778 && same_type_p (ics2->type, ics1->type)
11779 && (ics1->kind == ck_identity
11780 || same_type_p (next_conversion (ics2)->type,
11781 next_conversion (ics1)->type)))
11782 return true;
11783 }
11784}
11785
11786/* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11787 be any _TYPE nodes. */
11788
11789bool
11790is_properly_derived_from (tree derived, tree base)
11791{
11792 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11793 return false;
11794
11795 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11796 considers every class derived from itself. */
11797 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11798 && DERIVED_FROM_P (base, derived));
11799}
11800
11801/* We build the ICS for an implicit object parameter as a pointer
11802 conversion sequence. However, such a sequence should be compared
11803 as if it were a reference conversion sequence. If ICS is the
11804 implicit conversion sequence for an implicit object parameter,
11805 modify it accordingly. */
11806
11807static void
11808maybe_handle_implicit_object (conversion **ics)
11809{
11810 if ((*ics)->this_p)
11811 {
11812 /* [over.match.funcs]
11813
11814 For non-static member functions, the type of the
11815 implicit object parameter is "reference to cv X"
11816 where X is the class of which the function is a
11817 member and cv is the cv-qualification on the member
11818 function declaration. */
11819 conversion *t = *ics;
11820 tree reference_type;
11821
11822 /* The `this' parameter is a pointer to a class type. Make the
11823 implicit conversion talk about a reference to that same class
11824 type. */
11825 reference_type = TREE_TYPE (t->type);
11826 reference_type = build_reference_type (reference_type);
11827
11828 if (t->kind == ck_qual)
11829 t = next_conversion (conv: t);
11830 if (t->kind == ck_ptr)
11831 t = next_conversion (conv: t);
11832 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11833 t = direct_reference_binding (type: reference_type, conv: t);
11834 t->this_p = 1;
11835 t->rvaluedness_matches_p = 0;
11836 *ics = t;
11837 }
11838}
11839
11840/* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11841 and return the initial reference binding conversion. Otherwise,
11842 leave *ICS unchanged and return NULL. */
11843
11844static conversion *
11845maybe_handle_ref_bind (conversion **ics)
11846{
11847 if ((*ics)->kind == ck_ref_bind)
11848 {
11849 conversion *old_ics = *ics;
11850 *ics = next_conversion (conv: old_ics);
11851 (*ics)->user_conv_p = old_ics->user_conv_p;
11852 return old_ics;
11853 }
11854
11855 return NULL;
11856}
11857
11858/* Get the expression at the beginning of the conversion chain C. */
11859
11860static tree
11861conv_get_original_expr (conversion *c)
11862{
11863 for (; c; c = next_conversion (conv: c))
11864 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11865 return c->u.expr;
11866 return NULL_TREE;
11867}
11868
11869/* Return a tree representing the number of elements initialized by the
11870 list-initialization C. The caller must check that C converts to an
11871 array type. */
11872
11873static tree
11874nelts_initialized_by_list_init (conversion *c)
11875{
11876 /* If the array we're converting to has a dimension, we'll use that. */
11877 if (TYPE_DOMAIN (c->type))
11878 return array_type_nelts_top (c->type);
11879 else
11880 {
11881 /* Otherwise, we look at how many elements the constructor we're
11882 initializing from has. */
11883 tree ctor = conv_get_original_expr (c);
11884 return size_int (CONSTRUCTOR_NELTS (ctor));
11885 }
11886}
11887
11888/* True iff C is a conversion that binds a reference or a pointer to
11889 an array of unknown bound. */
11890
11891static inline bool
11892conv_binds_to_array_of_unknown_bound (conversion *c)
11893{
11894 /* ck_ref_bind won't have the reference stripped. */
11895 tree type = non_reference (c->type);
11896 /* ck_qual won't have the pointer stripped. */
11897 type = strip_pointer_operator (type);
11898 return (TREE_CODE (type) == ARRAY_TYPE
11899 && TYPE_DOMAIN (type) == NULL_TREE);
11900}
11901
11902/* Compare two implicit conversion sequences according to the rules set out in
11903 [over.ics.rank]. Return values:
11904
11905 1: ics1 is better than ics2
11906 -1: ics2 is better than ics1
11907 0: ics1 and ics2 are indistinguishable */
11908
11909static int
11910compare_ics (conversion *ics1, conversion *ics2)
11911{
11912 tree from_type1;
11913 tree from_type2;
11914 tree to_type1;
11915 tree to_type2;
11916 tree deref_from_type1 = NULL_TREE;
11917 tree deref_from_type2 = NULL_TREE;
11918 tree deref_to_type1 = NULL_TREE;
11919 tree deref_to_type2 = NULL_TREE;
11920 conversion_rank rank1, rank2;
11921
11922 /* REF_BINDING is nonzero if the result of the conversion sequence
11923 is a reference type. In that case REF_CONV is the reference
11924 binding conversion. */
11925 conversion *ref_conv1;
11926 conversion *ref_conv2;
11927
11928 /* Compare badness before stripping the reference conversion. */
11929 if (ics1->bad_p > ics2->bad_p)
11930 return -1;
11931 else if (ics1->bad_p < ics2->bad_p)
11932 return 1;
11933
11934 /* Handle implicit object parameters. */
11935 maybe_handle_implicit_object (ics: &ics1);
11936 maybe_handle_implicit_object (ics: &ics2);
11937
11938 /* Handle reference parameters. */
11939 ref_conv1 = maybe_handle_ref_bind (ics: &ics1);
11940 ref_conv2 = maybe_handle_ref_bind (ics: &ics2);
11941
11942 /* List-initialization sequence L1 is a better conversion sequence than
11943 list-initialization sequence L2 if L1 converts to
11944 std::initializer_list<X> for some X and L2 does not. */
11945 if (ics1->kind == ck_list && ics2->kind != ck_list)
11946 return 1;
11947 if (ics2->kind == ck_list && ics1->kind != ck_list)
11948 return -1;
11949
11950 /* [over.ics.rank]
11951
11952 When comparing the basic forms of implicit conversion sequences (as
11953 defined in _over.best.ics_)
11954
11955 --a standard conversion sequence (_over.ics.scs_) is a better
11956 conversion sequence than a user-defined conversion sequence
11957 or an ellipsis conversion sequence, and
11958
11959 --a user-defined conversion sequence (_over.ics.user_) is a
11960 better conversion sequence than an ellipsis conversion sequence
11961 (_over.ics.ellipsis_). */
11962 /* Use BAD_CONVERSION_RANK because we already checked for a badness
11963 mismatch. If both ICS are bad, we try to make a decision based on
11964 what would have happened if they'd been good. This is not an
11965 extension, we'll still give an error when we build up the call; this
11966 just helps us give a more helpful error message. */
11967 rank1 = BAD_CONVERSION_RANK (ics1);
11968 rank2 = BAD_CONVERSION_RANK (ics2);
11969
11970 if (rank1 > rank2)
11971 return -1;
11972 else if (rank1 < rank2)
11973 return 1;
11974
11975 if (ics1->ellipsis_p)
11976 /* Both conversions are ellipsis conversions. */
11977 return 0;
11978
11979 /* User-defined conversion sequence U1 is a better conversion sequence
11980 than another user-defined conversion sequence U2 if they contain the
11981 same user-defined conversion operator or constructor and if the sec-
11982 ond standard conversion sequence of U1 is better than the second
11983 standard conversion sequence of U2. */
11984
11985 /* Handle list-conversion with the same code even though it isn't always
11986 ranked as a user-defined conversion and it doesn't have a second
11987 standard conversion sequence; it will still have the desired effect.
11988 Specifically, we need to do the reference binding comparison at the
11989 end of this function. */
11990
11991 if (ics1->user_conv_p || ics1->kind == ck_list
11992 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
11993 {
11994 conversion *t1 = strip_standard_conversion (conv: ics1);
11995 conversion *t2 = strip_standard_conversion (conv: ics2);
11996
11997 if (!t1 || !t2 || t1->kind != t2->kind)
11998 return 0;
11999 else if (t1->kind == ck_user)
12000 {
12001 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12002 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12003 if (f1 != f2)
12004 return 0;
12005 }
12006 /* List-initialization sequence L1 is a better conversion sequence than
12007 list-initialization sequence L2 if
12008
12009 -- L1 and L2 convert to arrays of the same element type, and either
12010 the number of elements n1 initialized by L1 is less than the number
12011 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12012 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12013 P0388R4.) */
12014 else if (t1->kind == ck_aggr
12015 && TREE_CODE (t1->type) == ARRAY_TYPE
12016 && TREE_CODE (t2->type) == ARRAY_TYPE
12017 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12018 {
12019 tree n1 = nelts_initialized_by_list_init (c: t1);
12020 tree n2 = nelts_initialized_by_list_init (c: t2);
12021 if (tree_int_cst_lt (t1: n1, t2: n2))
12022 return 1;
12023 else if (tree_int_cst_lt (t1: n2, t2: n1))
12024 return -1;
12025 /* The n1 == n2 case. */
12026 bool c1 = conv_binds_to_array_of_unknown_bound (c: t1);
12027 bool c2 = conv_binds_to_array_of_unknown_bound (c: t2);
12028 if (c1 && !c2)
12029 return -1;
12030 else if (!c1 && c2)
12031 return 1;
12032 else
12033 return 0;
12034 }
12035 else
12036 {
12037 /* For ambiguous or aggregate conversions, use the target type as
12038 a proxy for the conversion function. */
12039 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12040 return 0;
12041 }
12042
12043 /* We can just fall through here, after setting up
12044 FROM_TYPE1 and FROM_TYPE2. */
12045 from_type1 = t1->type;
12046 from_type2 = t2->type;
12047 }
12048 else
12049 {
12050 conversion *t1;
12051 conversion *t2;
12052
12053 /* We're dealing with two standard conversion sequences.
12054
12055 [over.ics.rank]
12056
12057 Standard conversion sequence S1 is a better conversion
12058 sequence than standard conversion sequence S2 if
12059
12060 --S1 is a proper subsequence of S2 (comparing the conversion
12061 sequences in the canonical form defined by _over.ics.scs_,
12062 excluding any Lvalue Transformation; the identity
12063 conversion sequence is considered to be a subsequence of
12064 any non-identity conversion sequence */
12065
12066 t1 = ics1;
12067 while (t1->kind != ck_identity)
12068 t1 = next_conversion (conv: t1);
12069 from_type1 = t1->type;
12070
12071 t2 = ics2;
12072 while (t2->kind != ck_identity)
12073 t2 = next_conversion (conv: t2);
12074 from_type2 = t2->type;
12075 }
12076
12077 /* One sequence can only be a subsequence of the other if they start with
12078 the same type. They can start with different types when comparing the
12079 second standard conversion sequence in two user-defined conversion
12080 sequences. */
12081 if (same_type_p (from_type1, from_type2))
12082 {
12083 if (is_subseq (ics1, ics2))
12084 return 1;
12085 if (is_subseq (ics1: ics2, ics2: ics1))
12086 return -1;
12087 }
12088
12089 /* [over.ics.rank]
12090
12091 Or, if not that,
12092
12093 --the rank of S1 is better than the rank of S2 (by the rules
12094 defined below):
12095
12096 Standard conversion sequences are ordered by their ranks: an Exact
12097 Match is a better conversion than a Promotion, which is a better
12098 conversion than a Conversion.
12099
12100 Two conversion sequences with the same rank are indistinguishable
12101 unless one of the following rules applies:
12102
12103 --A conversion that does not a convert a pointer, pointer to member,
12104 or std::nullptr_t to bool is better than one that does.
12105
12106 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12107 so that we do not have to check it explicitly. */
12108 if (ics1->rank < ics2->rank)
12109 return 1;
12110 else if (ics2->rank < ics1->rank)
12111 return -1;
12112
12113 to_type1 = ics1->type;
12114 to_type2 = ics2->type;
12115
12116 /* A conversion from scalar arithmetic type to complex is worse than a
12117 conversion between scalar arithmetic types. */
12118 if (same_type_p (from_type1, from_type2)
12119 && ARITHMETIC_TYPE_P (from_type1)
12120 && ARITHMETIC_TYPE_P (to_type1)
12121 && ARITHMETIC_TYPE_P (to_type2)
12122 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12123 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12124 {
12125 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12126 return -1;
12127 else
12128 return 1;
12129 }
12130
12131 {
12132 /* A conversion in either direction between floating-point type FP1 and
12133 floating-point type FP2 is better than a conversion in the same
12134 direction between FP1 and arithmetic type T3 if
12135 - the floating-point conversion rank of FP1 is equal to the rank of
12136 FP2, and
12137 - T3 is not a floating-point type, or T3 is a floating-point type
12138 whose rank is not equal to the rank of FP1, or the floating-point
12139 conversion subrank of FP2 is greater than the subrank of T3. */
12140 tree fp1 = from_type1;
12141 tree fp2 = to_type1;
12142 tree fp3 = from_type2;
12143 tree t3 = to_type2;
12144 int ret = 1;
12145 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12146 {
12147 std::swap (a&: fp1, b&: fp2);
12148 std::swap (a&: fp3, b&: t3);
12149 }
12150 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12151 && SCALAR_FLOAT_TYPE_P (fp1)
12152 /* Only apply this rule if at least one of the 3 types is
12153 extended floating-point type, otherwise keep them as
12154 before for compatibility reasons with types like __float128.
12155 float, double and long double alone have different conversion
12156 ranks and so when just those 3 types are involved, this
12157 rule doesn't trigger. */
12158 && (extended_float_type_p (type: fp1)
12159 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (type: fp2))
12160 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (type: t3))))
12161 {
12162 if (TREE_CODE (fp2) != REAL_TYPE)
12163 {
12164 ret = -ret;
12165 std::swap (a&: fp2, b&: t3);
12166 }
12167 if (SCALAR_FLOAT_TYPE_P (fp2))
12168 {
12169 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12170 if the conversion rank is equal (-1 or 1 if the subrank is
12171 different). */
12172 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12173 fp2),
12174 -1, 1))
12175 {
12176 /* Conversion ranks of FP1 and FP2 are equal. */
12177 if (TREE_CODE (t3) != REAL_TYPE
12178 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12179 (fp1, t3),
12180 -1, 1))
12181 /* FP1 <-> FP2 conversion is better. */
12182 return ret;
12183 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12184 gcc_assert (IN_RANGE (c, -1, 1));
12185 if (c == 1)
12186 /* Conversion subrank of FP2 is greater than subrank of T3.
12187 FP1 <-> FP2 conversion is better. */
12188 return ret;
12189 else if (c == -1)
12190 /* Conversion subrank of FP2 is less than subrank of T3.
12191 FP1 <-> T3 conversion is better. */
12192 return -ret;
12193 }
12194 else if (SCALAR_FLOAT_TYPE_P (t3)
12195 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12196 (fp1, t3),
12197 -1, 1))
12198 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12199 ranks of FP1 and T3 are equal.
12200 FP1 <-> T3 conversion is better. */
12201 return -ret;
12202 }
12203 }
12204 }
12205
12206 if (TYPE_PTR_P (from_type1)
12207 && TYPE_PTR_P (from_type2)
12208 && TYPE_PTR_P (to_type1)
12209 && TYPE_PTR_P (to_type2))
12210 {
12211 deref_from_type1 = TREE_TYPE (from_type1);
12212 deref_from_type2 = TREE_TYPE (from_type2);
12213 deref_to_type1 = TREE_TYPE (to_type1);
12214 deref_to_type2 = TREE_TYPE (to_type2);
12215 }
12216 /* The rules for pointers to members A::* are just like the rules
12217 for pointers A*, except opposite: if B is derived from A then
12218 A::* converts to B::*, not vice versa. For that reason, we
12219 switch the from_ and to_ variables here. */
12220 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12221 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12222 || (TYPE_PTRMEMFUNC_P (from_type1)
12223 && TYPE_PTRMEMFUNC_P (from_type2)
12224 && TYPE_PTRMEMFUNC_P (to_type1)
12225 && TYPE_PTRMEMFUNC_P (to_type2)))
12226 {
12227 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12228 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12229 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12230 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12231 }
12232
12233 if (deref_from_type1 != NULL_TREE
12234 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12235 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12236 {
12237 /* This was one of the pointer or pointer-like conversions.
12238
12239 [over.ics.rank]
12240
12241 --If class B is derived directly or indirectly from class A,
12242 conversion of B* to A* is better than conversion of B* to
12243 void*, and conversion of A* to void* is better than
12244 conversion of B* to void*. */
12245 if (VOID_TYPE_P (deref_to_type1)
12246 && VOID_TYPE_P (deref_to_type2))
12247 {
12248 if (is_properly_derived_from (derived: deref_from_type1,
12249 base: deref_from_type2))
12250 return -1;
12251 else if (is_properly_derived_from (derived: deref_from_type2,
12252 base: deref_from_type1))
12253 return 1;
12254 }
12255 else if (VOID_TYPE_P (deref_to_type1)
12256 || VOID_TYPE_P (deref_to_type2))
12257 {
12258 if (same_type_p (deref_from_type1, deref_from_type2))
12259 {
12260 if (VOID_TYPE_P (deref_to_type2))
12261 {
12262 if (is_properly_derived_from (derived: deref_from_type1,
12263 base: deref_to_type1))
12264 return 1;
12265 }
12266 /* We know that DEREF_TO_TYPE1 is `void' here. */
12267 else if (is_properly_derived_from (derived: deref_from_type1,
12268 base: deref_to_type2))
12269 return -1;
12270 }
12271 }
12272 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12273 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12274 {
12275 /* [over.ics.rank]
12276
12277 --If class B is derived directly or indirectly from class A
12278 and class C is derived directly or indirectly from B,
12279
12280 --conversion of C* to B* is better than conversion of C* to
12281 A*,
12282
12283 --conversion of B* to A* is better than conversion of C* to
12284 A* */
12285 if (same_type_p (deref_from_type1, deref_from_type2))
12286 {
12287 if (is_properly_derived_from (derived: deref_to_type1,
12288 base: deref_to_type2))
12289 return 1;
12290 else if (is_properly_derived_from (derived: deref_to_type2,
12291 base: deref_to_type1))
12292 return -1;
12293 }
12294 else if (same_type_p (deref_to_type1, deref_to_type2))
12295 {
12296 if (is_properly_derived_from (derived: deref_from_type2,
12297 base: deref_from_type1))
12298 return 1;
12299 else if (is_properly_derived_from (derived: deref_from_type1,
12300 base: deref_from_type2))
12301 return -1;
12302 }
12303 }
12304 }
12305 else if (CLASS_TYPE_P (non_reference (from_type1))
12306 && same_type_p (from_type1, from_type2))
12307 {
12308 tree from = non_reference (from_type1);
12309
12310 /* [over.ics.rank]
12311
12312 --binding of an expression of type C to a reference of type
12313 B& is better than binding an expression of type C to a
12314 reference of type A&
12315
12316 --conversion of C to B is better than conversion of C to A, */
12317 if (is_properly_derived_from (derived: from, base: to_type1)
12318 && is_properly_derived_from (derived: from, base: to_type2))
12319 {
12320 if (is_properly_derived_from (derived: to_type1, base: to_type2))
12321 return 1;
12322 else if (is_properly_derived_from (derived: to_type2, base: to_type1))
12323 return -1;
12324 }
12325 }
12326 else if (CLASS_TYPE_P (non_reference (to_type1))
12327 && same_type_p (to_type1, to_type2))
12328 {
12329 tree to = non_reference (to_type1);
12330
12331 /* [over.ics.rank]
12332
12333 --binding of an expression of type B to a reference of type
12334 A& is better than binding an expression of type C to a
12335 reference of type A&,
12336
12337 --conversion of B to A is better than conversion of C to A */
12338 if (is_properly_derived_from (derived: from_type1, base: to)
12339 && is_properly_derived_from (derived: from_type2, base: to))
12340 {
12341 if (is_properly_derived_from (derived: from_type2, base: from_type1))
12342 return 1;
12343 else if (is_properly_derived_from (derived: from_type1, base: from_type2))
12344 return -1;
12345 }
12346 }
12347
12348 /* [over.ics.rank]
12349
12350 --S1 and S2 differ only in their qualification conversion and yield
12351 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12352 qualification signature of type T1 is a proper subset of the cv-
12353 qualification signature of type T2 */
12354 if (ics1->kind == ck_qual
12355 && ics2->kind == ck_qual
12356 && same_type_p (from_type1, from_type2))
12357 {
12358 int result = comp_cv_qual_signature (to_type1, to_type2);
12359 if (result != 0)
12360 return result;
12361 }
12362
12363 /* [over.ics.rank]
12364
12365 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12366 to an implicit object parameter of a non-static member function
12367 declared without a ref-qualifier, and either S1 binds an lvalue
12368 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12369 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12370 draft standard, 13.3.3.2)
12371
12372 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12373 types to which the references refer are the same type except for
12374 top-level cv-qualifiers, and the type to which the reference
12375 initialized by S2 refers is more cv-qualified than the type to
12376 which the reference initialized by S1 refers.
12377
12378 DR 1328 [over.match.best]: the context is an initialization by
12379 conversion function for direct reference binding (13.3.1.6) of a
12380 reference to function type, the return type of F1 is the same kind of
12381 reference (i.e. lvalue or rvalue) as the reference being initialized,
12382 and the return type of F2 is not. */
12383
12384 if (ref_conv1 && ref_conv2)
12385 {
12386 if (!ref_conv1->this_p && !ref_conv2->this_p
12387 && (ref_conv1->rvaluedness_matches_p
12388 != ref_conv2->rvaluedness_matches_p)
12389 && (same_type_p (ref_conv1->type, ref_conv2->type)
12390 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12391 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12392 {
12393 if (ref_conv1->bad_p
12394 && !same_type_p (TREE_TYPE (ref_conv1->type),
12395 TREE_TYPE (ref_conv2->type)))
12396 /* Don't prefer a bad conversion that drops cv-quals to a bad
12397 conversion with the wrong rvalueness. */
12398 return 0;
12399 return (ref_conv1->rvaluedness_matches_p
12400 - ref_conv2->rvaluedness_matches_p);
12401 }
12402
12403 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12404 {
12405 /* Per P0388R4:
12406
12407 void f (int(&)[]), // (1)
12408 f (int(&)[1]), // (2)
12409 f (int*); // (3)
12410
12411 (2) is better than (1), but (3) should be equal to (1) and to
12412 (2). For that reason we don't use ck_qual for (1) which would
12413 give it the cr_exact rank while (3) remains ck_identity.
12414 Therefore we compare (1) and (2) here. For (1) we'll have
12415
12416 ck_ref_bind <- ck_identity
12417 int[] & int[1]
12418
12419 so to handle this we must look at ref_conv. */
12420 bool c1 = conv_binds_to_array_of_unknown_bound (c: ref_conv1);
12421 bool c2 = conv_binds_to_array_of_unknown_bound (c: ref_conv2);
12422 if (c1 && !c2)
12423 return -1;
12424 else if (!c1 && c2)
12425 return 1;
12426
12427 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12428 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12429 if (ref_conv1->bad_p)
12430 {
12431 /* Prefer the one that drops fewer cv-quals. */
12432 tree ftype = next_conversion (conv: ref_conv1)->type;
12433 int fquals = cp_type_quals (ftype);
12434 q1 ^= fquals;
12435 q2 ^= fquals;
12436 }
12437 return comp_cv_qualification (q2, q1);
12438 }
12439 }
12440
12441 /* [over.ics.rank]
12442
12443 Per CWG 1601:
12444 -- A conversion that promotes an enumeration whose underlying type
12445 is fixed to its underlying type is better than one that promotes to
12446 the promoted underlying type, if the two are different. */
12447 if (ics1->rank == cr_promotion
12448 && ics2->rank == cr_promotion
12449 && UNSCOPED_ENUM_P (from_type1)
12450 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12451 && same_type_p (from_type1, from_type2))
12452 {
12453 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12454 tree prom = type_promotes_to (from_type1);
12455 if (!same_type_p (utype, prom))
12456 {
12457 if (same_type_p (to_type1, utype)
12458 && same_type_p (to_type2, prom))
12459 return 1;
12460 else if (same_type_p (to_type2, utype)
12461 && same_type_p (to_type1, prom))
12462 return -1;
12463 }
12464 }
12465
12466 /* Neither conversion sequence is better than the other. */
12467 return 0;
12468}
12469
12470/* The source type for this standard conversion sequence. */
12471
12472static tree
12473source_type (conversion *t)
12474{
12475 return strip_standard_conversion (conv: t)->type;
12476}
12477
12478/* Note a warning about preferring WINNER to LOSER. We do this by storing
12479 a pointer to LOSER and re-running joust to produce the warning if WINNER
12480 is actually used. */
12481
12482static void
12483add_warning (struct z_candidate *winner, struct z_candidate *loser)
12484{
12485 candidate_warning *cw = (candidate_warning *)
12486 conversion_obstack_alloc (n: sizeof (candidate_warning));
12487 cw->loser = loser;
12488 cw->next = winner->warnings;
12489 winner->warnings = cw;
12490}
12491
12492/* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12493 prvalue returned from a conversion function, return true. Otherwise, return
12494 false. */
12495
12496static bool
12497joust_maybe_elide_copy (z_candidate *cand)
12498{
12499 tree fn = cand->fn;
12500 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12501 return false;
12502 conversion *conv = cand->convs[0];
12503 if (conv->kind == ck_ambig)
12504 return false;
12505 gcc_checking_assert (conv->kind == ck_ref_bind);
12506 conv = next_conversion (conv);
12507 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12508 {
12509 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12510 (conv->type, DECL_CONTEXT (fn)));
12511 z_candidate *uc = conv->cand;
12512 if (DECL_CONV_FN_P (uc->fn))
12513 return true;
12514 }
12515 return false;
12516}
12517
12518/* True if the defining declarations of the two candidates have equivalent
12519 parameters. */
12520
12521static bool
12522cand_parms_match (z_candidate *c1, z_candidate *c2)
12523{
12524 tree fn1 = c1->fn;
12525 tree fn2 = c2->fn;
12526 if (fn1 == fn2)
12527 return true;
12528 if (identifier_p (t: fn1) || identifier_p (t: fn2))
12529 return false;
12530 /* We don't look at c1->template_decl because that's only set for primary
12531 templates, not e.g. non-template member functions of class templates. */
12532 tree t1 = most_general_template (fn1);
12533 tree t2 = most_general_template (fn2);
12534 if (t1 || t2)
12535 {
12536 if (!t1 || !t2)
12537 return false;
12538 if (t1 == t2)
12539 return true;
12540 fn1 = DECL_TEMPLATE_RESULT (t1);
12541 fn2 = DECL_TEMPLATE_RESULT (t2);
12542 }
12543 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12544 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12545 if (DECL_FUNCTION_MEMBER_P (fn1)
12546 && DECL_FUNCTION_MEMBER_P (fn2)
12547 && (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn1)
12548 != DECL_NONSTATIC_MEMBER_FUNCTION_P (fn2)))
12549 {
12550 /* Ignore 'this' when comparing the parameters of a static member
12551 function with those of a non-static one. */
12552 parms1 = skip_artificial_parms_for (fn1, parms1);
12553 parms2 = skip_artificial_parms_for (fn2, parms2);
12554 }
12555 return compparms (parms1, parms2);
12556}
12557
12558/* True iff FN is a copy or move constructor or assignment operator. */
12559
12560static bool
12561sfk_copy_or_move (tree fn)
12562{
12563 if (TREE_CODE (fn) != FUNCTION_DECL)
12564 return false;
12565 special_function_kind sfk = special_function_p (fn);
12566 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
12567}
12568
12569/* Compare two candidates for overloading as described in
12570 [over.match.best]. Return values:
12571
12572 1: cand1 is better than cand2
12573 -1: cand2 is better than cand1
12574 0: cand1 and cand2 are indistinguishable */
12575
12576static int
12577joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12578 tsubst_flags_t complain)
12579{
12580 int winner = 0;
12581 int off1 = 0, off2 = 0;
12582 size_t i;
12583 size_t len;
12584
12585 /* Candidates that involve bad conversions are always worse than those
12586 that don't. */
12587 if (cand1->viable > cand2->viable)
12588 return 1;
12589 if (cand1->viable < cand2->viable)
12590 return -1;
12591
12592 /* If we have two pseudo-candidates for conversions to the same type,
12593 or two candidates for the same function, arbitrarily pick one. */
12594 if (cand1->fn == cand2->fn
12595 && cand1->reversed () == cand2->reversed ()
12596 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12597 return 1;
12598
12599 /* Prefer a non-deleted function over an implicitly deleted move
12600 constructor or assignment operator. This differs slightly from the
12601 wording for issue 1402 (which says the move op is ignored by overload
12602 resolution), but this way produces better error messages. */
12603 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12604 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12605 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12606 {
12607 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12608 && move_fn_p (cand1->fn))
12609 return -1;
12610 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12611 && move_fn_p (cand2->fn))
12612 return 1;
12613 }
12614
12615 /* a viable function F1
12616 is defined to be a better function than another viable function F2 if
12617 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12618 ICSi(F2), and then */
12619
12620 /* for some argument j, ICSj(F1) is a better conversion sequence than
12621 ICSj(F2) */
12622
12623 /* For comparing static and non-static member functions, we ignore
12624 the implicit object parameter of the non-static function. The
12625 standard says to pretend that the static function has an object
12626 parm, but that won't work with operator overloading. */
12627 len = cand1->num_convs;
12628 if (len != cand2->num_convs)
12629 {
12630 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12631 && DECL_STATIC_FUNCTION_P (cand1->fn));
12632 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12633 && DECL_STATIC_FUNCTION_P (cand2->fn));
12634
12635 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12636 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12637 && DECL_CONSTRUCTOR_P (cand1->fn)
12638 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12639 /* We're comparing a near-match list constructor and a near-match
12640 non-list constructor. Just treat them as unordered. */
12641 return 0;
12642
12643 gcc_assert (static_1 != static_2);
12644
12645 if (static_1)
12646 {
12647 /* C++23 [over.best.ics.general] says:
12648 When the parameter is the implicit object parameter of a static
12649 member function, the implicit conversion sequence is a standard
12650 conversion sequence that is neither better nor worse than any
12651 other standard conversion sequence. */
12652 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12653 winner = 1;
12654 off2 = 1;
12655 }
12656 else
12657 {
12658 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12659 winner = -1;
12660 off1 = 1;
12661 --len;
12662 }
12663 }
12664
12665 for (i = 0; i < len; ++i)
12666 {
12667 conversion *t1 = cand1->convs[i + off1];
12668 conversion *t2 = cand2->convs[i + off2];
12669 int comp = compare_ics (ics1: t1, ics2: t2);
12670
12671 if (comp != 0)
12672 {
12673 if ((complain & tf_warning)
12674 && warn_sign_promo
12675 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12676 == cr_std + cr_promotion)
12677 && t1->kind == ck_std
12678 && t2->kind == ck_std
12679 && TREE_CODE (t1->type) == INTEGER_TYPE
12680 && TREE_CODE (t2->type) == INTEGER_TYPE
12681 && (TYPE_PRECISION (t1->type)
12682 == TYPE_PRECISION (t2->type))
12683 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12684 || (TREE_CODE (next_conversion (t1)->type)
12685 == ENUMERAL_TYPE)))
12686 {
12687 tree type = next_conversion (conv: t1)->type;
12688 tree type1, type2;
12689 struct z_candidate *w, *l;
12690 if (comp > 0)
12691 type1 = t1->type, type2 = t2->type,
12692 w = cand1, l = cand2;
12693 else
12694 type1 = t2->type, type2 = t1->type,
12695 w = cand2, l = cand1;
12696
12697 if (warn)
12698 {
12699 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12700 type, type1, type2);
12701 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12702 }
12703 else
12704 add_warning (winner: w, loser: l);
12705 }
12706
12707 if (winner && comp != winner)
12708 {
12709 /* Ambiguity between normal and reversed comparison operators
12710 with the same parameter types. P2468 decided not to go with
12711 this approach to resolving the ambiguity, so pedwarn. */
12712 if ((complain & tf_warning_or_error)
12713 && (cand1->reversed () != cand2->reversed ())
12714 && cand_parms_match (c1: cand1, c2: cand2))
12715 {
12716 struct z_candidate *w, *l;
12717 if (cand2->reversed ())
12718 winner = 1, w = cand1, l = cand2;
12719 else
12720 winner = -1, w = cand2, l = cand1;
12721 if (warn)
12722 {
12723 auto_diagnostic_group d;
12724 if (pedwarn (input_location, 0,
12725 "C++20 says that these are ambiguous, "
12726 "even though the second is reversed:"))
12727 {
12728 print_z_candidate (loc: input_location,
12729 N_("candidate 1:"), candidate: w);
12730 print_z_candidate (loc: input_location,
12731 N_("candidate 2:"), candidate: l);
12732 if (w->fn == l->fn
12733 && DECL_NONSTATIC_MEMBER_FUNCTION_P (w->fn)
12734 && (type_memfn_quals (TREE_TYPE (w->fn))
12735 & TYPE_QUAL_CONST) == 0)
12736 {
12737 /* Suggest adding const to
12738 struct A { bool operator==(const A&); }; */
12739 tree parmtype
12740 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
12741 parmtype = TREE_VALUE (parmtype);
12742 if (TYPE_REF_P (parmtype)
12743 && TYPE_READONLY (TREE_TYPE (parmtype))
12744 && (same_type_ignoring_top_level_qualifiers_p
12745 (TREE_TYPE (parmtype),
12746 DECL_CONTEXT (w->fn))))
12747 inform (DECL_SOURCE_LOCATION (w->fn),
12748 "try making the operator a %<const%> "
12749 "member function");
12750 }
12751 }
12752 }
12753 else
12754 add_warning (winner: w, loser: l);
12755 return winner;
12756 }
12757
12758 winner = 0;
12759 goto tweak;
12760 }
12761 winner = comp;
12762 }
12763 }
12764
12765 /* warn about confusing overload resolution for user-defined conversions,
12766 either between a constructor and a conversion op, or between two
12767 conversion ops. */
12768 if ((complain & tf_warning)
12769 /* In C++17, the constructor might have been elided, which means that
12770 an originally null ->second_conv could become non-null. */
12771 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12772 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12773 && winner != compare_ics (ics1: cand1->second_conv, ics2: cand2->second_conv))
12774 {
12775 struct z_candidate *w, *l;
12776 bool give_warning = false;
12777
12778 if (winner == 1)
12779 w = cand1, l = cand2;
12780 else
12781 w = cand2, l = cand1;
12782
12783 /* We don't want to complain about `X::operator T1 ()'
12784 beating `X::operator T2 () const', when T2 is a no less
12785 cv-qualified version of T1. */
12786 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12787 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12788 {
12789 tree t = TREE_TYPE (TREE_TYPE (l->fn));
12790 tree f = TREE_TYPE (TREE_TYPE (w->fn));
12791
12792 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12793 {
12794 t = TREE_TYPE (t);
12795 f = TREE_TYPE (f);
12796 }
12797 if (!comp_ptr_ttypes (t, f))
12798 give_warning = true;
12799 }
12800 else
12801 give_warning = true;
12802
12803 if (!give_warning)
12804 /*NOP*/;
12805 else if (warn)
12806 {
12807 tree source = source_type (t: w->convs[0]);
12808 if (INDIRECT_TYPE_P (source))
12809 source = TREE_TYPE (source);
12810 auto_diagnostic_group d;
12811 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12812 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
12813 source, w->second_conv->type))
12814 {
12815 inform (input_location, " because conversion sequence "
12816 "for the argument is better");
12817 }
12818 }
12819 else
12820 add_warning (winner: w, loser: l);
12821 }
12822
12823 if (winner)
12824 return winner;
12825
12826 /* DR 495 moved this tiebreaker above the template ones. */
12827 /* or, if not that,
12828 the context is an initialization by user-defined conversion (see
12829 _dcl.init_ and _over.match.user_) and the standard conversion
12830 sequence from the return type of F1 to the destination type (i.e.,
12831 the type of the entity being initialized) is a better conversion
12832 sequence than the standard conversion sequence from the return type
12833 of F2 to the destination type. */
12834
12835 if (cand1->second_conv)
12836 {
12837 winner = compare_ics (ics1: cand1->second_conv, ics2: cand2->second_conv);
12838 if (winner)
12839 return winner;
12840 }
12841
12842 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
12843 explicit conversion (due to list-initialization) is worse. */
12844 {
12845 z_candidate *sp = nullptr;
12846 if (sfk_copy_or_move (fn: cand1->fn))
12847 sp = cand1;
12848 if (sfk_copy_or_move (fn: cand2->fn))
12849 sp = sp ? nullptr : cand2;
12850 if (sp)
12851 {
12852 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
12853 if (conv->user_conv_p)
12854 for (; conv; conv = next_conversion (conv))
12855 if (conv->kind == ck_user
12856 && DECL_P (conv->cand->fn)
12857 && DECL_NONCONVERTING_P (conv->cand->fn))
12858 return (sp == cand1) ? -1 : 1;
12859 }
12860 }
12861
12862 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
12863 The standard currently says that only constructors are candidates, but if
12864 one copies a prvalue returned by a conversion function we prefer that.
12865
12866 Clang does something similar, as discussed at
12867 http://lists.isocpp.org/core/2017/10/3166.php
12868 http://lists.isocpp.org/core/2019/03/5721.php */
12869 if (len == 1 && cxx_dialect >= cxx17
12870 && DECL_P (cand1->fn)
12871 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
12872 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
12873 {
12874 bool elided1 = joust_maybe_elide_copy (cand: cand1);
12875 bool elided2 = joust_maybe_elide_copy (cand: cand2);
12876 winner = elided1 - elided2;
12877 if (winner)
12878 return winner;
12879 }
12880
12881 /* or, if not that,
12882 F1 is a non-template function and F2 is a template function
12883 specialization. */
12884
12885 if (!cand1->template_decl && cand2->template_decl)
12886 return 1;
12887 else if (cand1->template_decl && !cand2->template_decl)
12888 return -1;
12889
12890 /* or, if not that,
12891 F1 and F2 are template functions and the function template for F1 is
12892 more specialized than the template for F2 according to the partial
12893 ordering rules. */
12894
12895 if (cand1->template_decl && cand2->template_decl)
12896 {
12897 winner = more_specialized_fn
12898 (TI_TEMPLATE (cand1->template_decl),
12899 TI_TEMPLATE (cand2->template_decl),
12900 /* [temp.func.order]: The presence of unused ellipsis and default
12901 arguments has no effect on the partial ordering of function
12902 templates. add_function_candidate() will not have
12903 counted the "this" argument for constructors. */
12904 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
12905 if (winner)
12906 return winner;
12907 }
12908
12909 /* Concepts: F1 and F2 are non-template functions with the same
12910 parameter-type-lists, and F1 is more constrained than F2 according to the
12911 partial ordering of constraints described in 13.5.4. */
12912
12913 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
12914 && !cand1->template_decl && !cand2->template_decl
12915 && cand_parms_match (c1: cand1, c2: cand2))
12916 {
12917 winner = more_constrained (cand1->fn, cand2->fn);
12918 if (winner)
12919 return winner;
12920 }
12921
12922 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
12923 rewritten candidates, and F2 is a synthesized candidate with reversed
12924 order of parameters and F1 is not. */
12925 if (cand1->rewritten ())
12926 {
12927 if (!cand2->rewritten ())
12928 return -1;
12929 if (!cand1->reversed () && cand2->reversed ())
12930 return 1;
12931 if (cand1->reversed () && !cand2->reversed ())
12932 return -1;
12933 }
12934 else if (cand2->rewritten ())
12935 return 1;
12936
12937 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
12938 if (deduction_guide_p (cand1->fn))
12939 {
12940 gcc_assert (deduction_guide_p (cand2->fn));
12941 /* We distinguish between candidates from an explicit deduction guide and
12942 candidates built from a constructor based on DECL_ARTIFICIAL. */
12943 int art1 = DECL_ARTIFICIAL (cand1->fn);
12944 int art2 = DECL_ARTIFICIAL (cand2->fn);
12945 if (art1 != art2)
12946 return art2 - art1;
12947
12948 if (art1)
12949 {
12950 /* Prefer the special copy guide over a declared copy/move
12951 constructor. */
12952 if (copy_guide_p (cand1->fn))
12953 return 1;
12954 if (copy_guide_p (cand2->fn))
12955 return -1;
12956
12957 /* Prefer a candidate generated from a non-template constructor. */
12958 int tg1 = template_guide_p (cand1->fn);
12959 int tg2 = template_guide_p (cand2->fn);
12960 if (tg1 != tg2)
12961 return tg2 - tg1;
12962 }
12963 }
12964
12965 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
12966 for all arguments the corresponding parameters of F1 and F2 have the same
12967 type (CWG 2273/2277). */
12968 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
12969 && !DECL_CONV_FN_P (cand1->fn)
12970 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
12971 && !DECL_CONV_FN_P (cand2->fn))
12972 {
12973 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
12974 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
12975
12976 bool used1 = false;
12977 bool used2 = false;
12978 if (base1 == base2)
12979 /* No difference. */;
12980 else if (DERIVED_FROM_P (base1, base2))
12981 used1 = true;
12982 else if (DERIVED_FROM_P (base2, base1))
12983 used2 = true;
12984
12985 if (int diff = used2 - used1)
12986 {
12987 for (i = 0; i < len; ++i)
12988 {
12989 conversion *t1 = cand1->convs[i + off1];
12990 conversion *t2 = cand2->convs[i + off2];
12991 if (!same_type_p (t1->type, t2->type))
12992 break;
12993 }
12994 if (i == len)
12995 return diff;
12996 }
12997 }
12998
12999 /* Check whether we can discard a builtin candidate, either because we
13000 have two identical ones or matching builtin and non-builtin candidates.
13001
13002 (Pedantically in the latter case the builtin which matched the user
13003 function should not be added to the overload set, but we spot it here.
13004
13005 [over.match.oper]
13006 ... the builtin candidates include ...
13007 - do not have the same parameter type list as any non-template
13008 non-member candidate. */
13009
13010 if (identifier_p (t: cand1->fn) || identifier_p (t: cand2->fn))
13011 {
13012 for (i = 0; i < len; ++i)
13013 if (!same_type_p (cand1->convs[i]->type,
13014 cand2->convs[i]->type))
13015 break;
13016 if (i == cand1->num_convs)
13017 {
13018 if (cand1->fn == cand2->fn)
13019 /* Two built-in candidates; arbitrarily pick one. */
13020 return 1;
13021 else if (identifier_p (t: cand1->fn))
13022 /* cand1 is built-in; prefer cand2. */
13023 return -1;
13024 else
13025 /* cand2 is built-in; prefer cand1. */
13026 return 1;
13027 }
13028 }
13029
13030 /* For candidates of a multi-versioned function, make the version with
13031 the highest priority win. This version will be checked for dispatching
13032 first. If this version can be inlined into the caller, the front-end
13033 will simply make a direct call to this function. */
13034
13035 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13036 && DECL_FUNCTION_VERSIONED (cand1->fn)
13037 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13038 && DECL_FUNCTION_VERSIONED (cand2->fn))
13039 {
13040 tree f1 = TREE_TYPE (cand1->fn);
13041 tree f2 = TREE_TYPE (cand2->fn);
13042 tree p1 = TYPE_ARG_TYPES (f1);
13043 tree p2 = TYPE_ARG_TYPES (f2);
13044
13045 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13046 is possible that cand1->fn and cand2->fn are function versions but of
13047 different functions. Check types to see if they are versions of the same
13048 function. */
13049 if (compparms (p1, p2)
13050 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13051 {
13052 /* Always make the version with the higher priority, more
13053 specialized, win. */
13054 gcc_assert (targetm.compare_version_priority);
13055 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13056 return 1;
13057 else
13058 return -1;
13059 }
13060 }
13061
13062 /* If the two function declarations represent the same function (this can
13063 happen with declarations in multiple scopes and arg-dependent lookup),
13064 arbitrarily choose one. But first make sure the default args we're
13065 using match. */
13066 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13067 && equal_functions (fn1: cand1->fn, fn2: cand2->fn))
13068 {
13069 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13070 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13071
13072 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13073
13074 for (i = 0; i < len; ++i)
13075 {
13076 /* Don't crash if the fn is variadic. */
13077 if (!parms1)
13078 break;
13079 parms1 = TREE_CHAIN (parms1);
13080 parms2 = TREE_CHAIN (parms2);
13081 }
13082
13083 if (off1)
13084 parms1 = TREE_CHAIN (parms1);
13085 else if (off2)
13086 parms2 = TREE_CHAIN (parms2);
13087
13088 for (; parms1; ++i)
13089 {
13090 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13091 TREE_PURPOSE (parms2)))
13092 {
13093 if (warn)
13094 {
13095 if (complain & tf_error)
13096 {
13097 auto_diagnostic_group d;
13098 if (permerror (input_location,
13099 "default argument mismatch in "
13100 "overload resolution"))
13101 {
13102 inform (DECL_SOURCE_LOCATION (cand1->fn),
13103 " candidate 1: %q#F", cand1->fn);
13104 inform (DECL_SOURCE_LOCATION (cand2->fn),
13105 " candidate 2: %q#F", cand2->fn);
13106 }
13107 }
13108 else
13109 return 0;
13110 }
13111 else
13112 add_warning (winner: cand1, loser: cand2);
13113 break;
13114 }
13115 parms1 = TREE_CHAIN (parms1);
13116 parms2 = TREE_CHAIN (parms2);
13117 }
13118
13119 return 1;
13120 }
13121
13122tweak:
13123
13124 /* Extension: If the worst conversion for one candidate is better than the
13125 worst conversion for the other, take the first. */
13126 if (!pedantic && (complain & tf_warning_or_error))
13127 {
13128 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13129 struct z_candidate *w = 0, *l = 0;
13130
13131 for (i = 0; i < len; ++i)
13132 {
13133 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13134 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13135 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13136 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13137 }
13138 if (rank1 < rank2)
13139 winner = 1, w = cand1, l = cand2;
13140 if (rank1 > rank2)
13141 winner = -1, w = cand2, l = cand1;
13142 if (winner)
13143 {
13144 /* Don't choose a deleted function over ambiguity. */
13145 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13146 return 0;
13147 if (warn)
13148 {
13149 auto_diagnostic_group d;
13150 if (pedwarn (input_location, 0,
13151 "ISO C++ says that these are ambiguous, even "
13152 "though the worst conversion for the first is "
13153 "better than the worst conversion for the second:"))
13154 {
13155 print_z_candidate (loc: input_location, N_("candidate 1:"), candidate: w);
13156 print_z_candidate (loc: input_location, N_("candidate 2:"), candidate: l);
13157 }
13158 }
13159 else
13160 add_warning (winner: w, loser: l);
13161 return winner;
13162 }
13163 }
13164
13165 gcc_assert (!winner);
13166 return 0;
13167}
13168
13169/* Given a list of candidates for overloading, find the best one, if any.
13170 This algorithm has a worst case of O(2n) (winner is last), and a best
13171 case of O(n/2) (totally ambiguous); much better than a sorting
13172 algorithm. */
13173
13174static struct z_candidate *
13175tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13176{
13177 struct z_candidate *champ = candidates, *challenger;
13178 int fate;
13179 struct z_candidate *champ_compared_to_predecessor = nullptr;
13180
13181 /* Walk through the list once, comparing each current champ to the next
13182 candidate, knocking out a candidate or two with each comparison. */
13183
13184 for (challenger = champ->next; challenger; )
13185 {
13186 fate = joust (cand1: champ, cand2: challenger, warn: 0, complain);
13187 if (fate == 1)
13188 challenger = challenger->next;
13189 else
13190 {
13191 if (fate == 0)
13192 {
13193 champ = challenger->next;
13194 if (champ == 0)
13195 return NULL;
13196 champ_compared_to_predecessor = nullptr;
13197 }
13198 else
13199 {
13200 champ_compared_to_predecessor = champ;
13201 champ = challenger;
13202 }
13203
13204 challenger = champ->next;
13205 }
13206 }
13207
13208 /* Make sure the champ is better than all the candidates it hasn't yet
13209 been compared to. */
13210
13211 for (challenger = candidates;
13212 challenger != champ;
13213 challenger = challenger->next)
13214 {
13215 if (challenger == champ_compared_to_predecessor)
13216 continue;
13217 fate = joust (cand1: champ, cand2: challenger, warn: 0, complain);
13218 if (fate != 1)
13219 return NULL;
13220 }
13221
13222 return champ;
13223}
13224
13225/* Returns nonzero if things of type FROM can be converted to TO. */
13226
13227bool
13228can_convert (tree to, tree from, tsubst_flags_t complain)
13229{
13230 tree arg = NULL_TREE;
13231 /* implicit_conversion only considers user-defined conversions
13232 if it has an expression for the call argument list. */
13233 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13234 arg = build_stub_object (from);
13235 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13236}
13237
13238/* Returns nonzero if things of type FROM can be converted to TO with a
13239 standard conversion. */
13240
13241bool
13242can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13243{
13244 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13245}
13246
13247/* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13248
13249bool
13250can_convert_arg (tree to, tree from, tree arg, int flags,
13251 tsubst_flags_t complain)
13252{
13253 conversion *t;
13254 bool ok_p;
13255
13256 conversion_obstack_sentinel cos;
13257 /* We want to discard any access checks done for this test,
13258 as we might not be in the appropriate access context and
13259 we'll do the check again when we actually perform the
13260 conversion. */
13261 push_deferring_access_checks (dk_deferred);
13262
13263 t = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
13264 flags, complain);
13265 ok_p = (t && !t->bad_p);
13266
13267 /* Discard the access checks now. */
13268 pop_deferring_access_checks ();
13269
13270 return ok_p;
13271}
13272
13273/* Like can_convert_arg, but allows dubious conversions as well. */
13274
13275bool
13276can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13277 tsubst_flags_t complain)
13278{
13279 conversion *t;
13280
13281 conversion_obstack_sentinel cos;
13282 /* Try to perform the conversion. */
13283 t = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
13284 flags, complain);
13285
13286 return t != NULL;
13287}
13288
13289/* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13290 resolution FLAGS. */
13291
13292tree
13293build_implicit_conv_flags (tree type, tree expr, int flags)
13294{
13295 /* In a template, we are only concerned about determining the
13296 type of non-dependent expressions, so we do not have to
13297 perform the actual conversion. But for initializers, we
13298 need to be able to perform it at instantiation
13299 (or instantiate_non_dependent_expr) time. */
13300 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13301 if (!(flags & LOOKUP_ONLYCONVERTING))
13302 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13303 if (flags & LOOKUP_NO_NARROWING)
13304 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13305 return expr;
13306}
13307
13308/* Convert EXPR to TYPE. Return the converted expression.
13309
13310 Note that we allow bad conversions here because by the time we get to
13311 this point we are committed to doing the conversion. If we end up
13312 doing a bad conversion, convert_like will complain. */
13313
13314tree
13315perform_implicit_conversion_flags (tree type, tree expr,
13316 tsubst_flags_t complain, int flags)
13317{
13318 conversion *conv;
13319 location_t loc = cp_expr_loc_or_input_loc (t: expr);
13320
13321 if (TYPE_REF_P (type))
13322 expr = mark_lvalue_use (expr);
13323 else
13324 expr = mark_rvalue_use (expr);
13325
13326 if (error_operand_p (t: expr))
13327 return error_mark_node;
13328
13329 conversion_obstack_sentinel cos;
13330
13331 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
13332 /*c_cast_p=*/false,
13333 flags, complain);
13334
13335 if (!conv)
13336 {
13337 if (complain & tf_error)
13338 implicit_conversion_error (loc, type, expr);
13339 expr = error_mark_node;
13340 }
13341 else if (processing_template_decl && conv->kind != ck_identity)
13342 expr = build_implicit_conv_flags (type, expr, flags);
13343 else
13344 {
13345 /* Give a conversion call the same location as expr. */
13346 iloc_sentinel il (loc);
13347 expr = convert_like (convs: conv, expr, complain);
13348 }
13349
13350 return expr;
13351}
13352
13353tree
13354perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13355{
13356 return perform_implicit_conversion_flags (type, expr, complain,
13357 LOOKUP_IMPLICIT);
13358}
13359
13360/* Convert EXPR to TYPE (as a direct-initialization) if that is
13361 permitted. If the conversion is valid, the converted expression is
13362 returned. Otherwise, NULL_TREE is returned, except in the case
13363 that TYPE is a class type; in that case, an error is issued. If
13364 C_CAST_P is true, then this direct-initialization is taking
13365 place as part of a static_cast being attempted as part of a C-style
13366 cast. */
13367
13368tree
13369perform_direct_initialization_if_possible (tree type,
13370 tree expr,
13371 bool c_cast_p,
13372 tsubst_flags_t complain)
13373{
13374 conversion *conv;
13375
13376 if (type == error_mark_node || error_operand_p (t: expr))
13377 return error_mark_node;
13378 /* [dcl.init]
13379
13380 If the destination type is a (possibly cv-qualified) class type:
13381
13382 -- If the initialization is direct-initialization ...,
13383 constructors are considered.
13384
13385 -- If overload resolution is successful, the selected constructor
13386 is called to initialize the object, with the initializer expression
13387 or expression-list as its argument(s).
13388
13389 -- Otherwise, if no constructor is viable, the destination type is
13390 a (possibly cv-qualified) aggregate class A, and the initializer is
13391 a parenthesized expression-list, the object is initialized as
13392 follows... */
13393 if (CLASS_TYPE_P (type))
13394 {
13395 releasing_vec args (make_tree_vector_single (expr));
13396 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13397 args: &args, binfo: type, LOOKUP_NORMAL, complain);
13398 return build_cplus_new (type, expr, complain);
13399 }
13400
13401 conversion_obstack_sentinel cos;
13402
13403 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
13404 c_cast_p,
13405 LOOKUP_NORMAL, complain);
13406 if (!conv || conv->bad_p)
13407 expr = NULL_TREE;
13408 else if (processing_template_decl && conv->kind != ck_identity)
13409 {
13410 /* In a template, we are only concerned about determining the
13411 type of non-dependent expressions, so we do not have to
13412 perform the actual conversion. But for initializers, we
13413 need to be able to perform it at instantiation
13414 (or instantiate_non_dependent_expr) time. */
13415 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13416 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13417 }
13418 else
13419 expr = convert_like (convs: conv, expr, NULL_TREE, argnum: 0,
13420 /*issue_conversion_warnings=*/false,
13421 c_cast_p, /*nested_p=*/false, complain);
13422
13423 return expr;
13424}
13425
13426/* When initializing a reference that lasts longer than a full-expression,
13427 this special rule applies:
13428
13429 [class.temporary]
13430
13431 The temporary to which the reference is bound or the temporary
13432 that is the complete object to which the reference is bound
13433 persists for the lifetime of the reference.
13434
13435 The temporaries created during the evaluation of the expression
13436 initializing the reference, except the temporary to which the
13437 reference is bound, are destroyed at the end of the
13438 full-expression in which they are created.
13439
13440 In that case, we store the converted expression into a new
13441 VAR_DECL in a new scope.
13442
13443 However, we want to be careful not to create temporaries when
13444 they are not required. For example, given:
13445
13446 struct B {};
13447 struct D : public B {};
13448 D f();
13449 const B& b = f();
13450
13451 there is no need to copy the return value from "f"; we can just
13452 extend its lifetime. Similarly, given:
13453
13454 struct S {};
13455 struct T { operator S(); };
13456 T t;
13457 const S& s = t;
13458
13459 we can extend the lifetime of the return value of the conversion
13460 operator.
13461
13462 The next several functions are involved in this lifetime extension. */
13463
13464/* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13465 reference is being bound to a temporary. Create and return a new
13466 VAR_DECL with the indicated TYPE; this variable will store the value to
13467 which the reference is bound. */
13468
13469tree
13470make_temporary_var_for_ref_to_temp (tree decl, tree type)
13471{
13472 tree var = create_temporary_var (type);
13473
13474 /* Register the variable. */
13475 if (VAR_P (decl)
13476 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13477 {
13478 /* Namespace-scope or local static; give it a mangled name. */
13479
13480 /* If an initializer is visible to multiple translation units, those
13481 translation units must agree on the addresses of the
13482 temporaries. Therefore the temporaries must be given a consistent name
13483 and vague linkage. The mangled name of a temporary is the name of the
13484 non-temporary object in whose initializer they appear, prefixed with
13485 GR and suffixed with a sequence number mangled using the usual rules
13486 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13487 left-to-right walk of the complete initializer. */
13488 copy_linkage (var, decl);
13489
13490 tree name = mangle_ref_init_variable (decl);
13491 DECL_NAME (var) = name;
13492 SET_DECL_ASSEMBLER_NAME (var, name);
13493 }
13494 else
13495 /* Create a new cleanup level if necessary. */
13496 maybe_push_cleanup_level (type);
13497
13498 return pushdecl (var);
13499}
13500
13501/* EXPR is the initializer for a variable DECL of reference or
13502 std::initializer_list type. Create, push and return a new VAR_DECL
13503 for the initializer so that it will live as long as DECL. Any
13504 cleanup for the new variable is returned through CLEANUP, and the
13505 code to initialize the new variable is returned through INITP. */
13506
13507static tree
13508set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13509 tree *initp, tree *cond_guard)
13510{
13511 tree init;
13512 tree type;
13513 tree var;
13514
13515 /* Create the temporary variable. */
13516 type = TREE_TYPE (expr);
13517 var = make_temporary_var_for_ref_to_temp (decl, type);
13518 layout_decl (var, 0);
13519 /* If the rvalue is the result of a function call it will be
13520 a TARGET_EXPR. If it is some other construct (such as a
13521 member access expression where the underlying object is
13522 itself the result of a function call), turn it into a
13523 TARGET_EXPR here. It is important that EXPR be a
13524 TARGET_EXPR below since otherwise the INIT_EXPR will
13525 attempt to make a bitwise copy of EXPR to initialize
13526 VAR. */
13527 if (TREE_CODE (expr) != TARGET_EXPR)
13528 expr = get_target_expr (expr);
13529 else
13530 {
13531 if (TREE_ADDRESSABLE (expr))
13532 TREE_ADDRESSABLE (var) = 1;
13533 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
13534 DECL_MERGEABLE (var) = true;
13535 }
13536
13537 if (TREE_CODE (decl) == FIELD_DECL
13538 && extra_warnings && !warning_suppressed_p (decl))
13539 {
13540 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13541 "until the constructor exits", decl);
13542 suppress_warning (decl);
13543 }
13544
13545 /* Recursively extend temps in this initializer. */
13546 TARGET_EXPR_INITIAL (expr)
13547 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13548 cond_guard);
13549
13550 /* Any reference temp has a non-trivial initializer. */
13551 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13552
13553 /* If the initializer is constant, put it in DECL_INITIAL so we get
13554 static initialization and use in constant expressions. */
13555 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13556 /* As in store_init_value. */
13557 init = cp_fully_fold (init);
13558 if (TREE_CONSTANT (init))
13559 {
13560 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13561 {
13562 /* 5.19 says that a constant expression can include an
13563 lvalue-rvalue conversion applied to "a glvalue of literal type
13564 that refers to a non-volatile temporary object initialized
13565 with a constant expression". Rather than try to communicate
13566 that this VAR_DECL is a temporary, just mark it constexpr. */
13567 DECL_DECLARED_CONSTEXPR_P (var) = true;
13568 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13569 TREE_CONSTANT (var) = true;
13570 TREE_READONLY (var) = true;
13571 }
13572 DECL_INITIAL (var) = init;
13573 init = NULL_TREE;
13574 }
13575 else
13576 /* Create the INIT_EXPR that will initialize the temporary
13577 variable. */
13578 init = split_nonconstant_init (var, expr);
13579 if (at_function_scope_p ())
13580 {
13581 add_decl_expr (var);
13582
13583 if (TREE_STATIC (var))
13584 init = add_stmt_to_compound (init, register_dtor_fn (var));
13585 else
13586 {
13587 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13588 if (cleanup)
13589 {
13590 if (cond_guard && cleanup != error_mark_node)
13591 {
13592 if (*cond_guard == NULL_TREE)
13593 {
13594 *cond_guard = build_local_temp (boolean_type_node);
13595 add_decl_expr (*cond_guard);
13596 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13597 *cond_guard, NOP_EXPR,
13598 boolean_false_node,
13599 tf_warning_or_error);
13600 finish_expr_stmt (set);
13601 }
13602 cleanup = build3 (COND_EXPR, void_type_node,
13603 *cond_guard, cleanup, NULL_TREE);
13604 }
13605 vec_safe_push (v&: *cleanups, obj: cleanup);
13606 }
13607 }
13608
13609 /* We must be careful to destroy the temporary only
13610 after its initialization has taken place. If the
13611 initialization throws an exception, then the
13612 destructor should not be run. We cannot simply
13613 transform INIT into something like:
13614
13615 (INIT, ({ CLEANUP_STMT; }))
13616
13617 because emit_local_var always treats the
13618 initializer as a full-expression. Thus, the
13619 destructor would run too early; it would run at the
13620 end of initializing the reference variable, rather
13621 than at the end of the block enclosing the
13622 reference variable.
13623
13624 The solution is to pass back a cleanup expression
13625 which the caller is responsible for attaching to
13626 the statement tree. */
13627 }
13628 else
13629 {
13630 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13631 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13632 {
13633 if (CP_DECL_THREAD_LOCAL_P (var))
13634 tls_aggregates = tree_cons (NULL_TREE, var,
13635 tls_aggregates);
13636 else
13637 static_aggregates = tree_cons (NULL_TREE, var,
13638 static_aggregates);
13639 }
13640 else
13641 /* Check whether the dtor is callable. */
13642 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13643 }
13644 /* Avoid -Wunused-variable warning (c++/38958). */
13645 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13646 && VAR_P (decl))
13647 TREE_USED (decl) = DECL_READ_P (decl) = true;
13648
13649 *initp = init;
13650 return var;
13651}
13652
13653/* Convert EXPR to the indicated reference TYPE, in a way suitable for
13654 initializing a variable of that TYPE. */
13655
13656tree
13657initialize_reference (tree type, tree expr,
13658 int flags, tsubst_flags_t complain)
13659{
13660 conversion *conv;
13661 location_t loc = cp_expr_loc_or_input_loc (t: expr);
13662
13663 if (type == error_mark_node || error_operand_p (t: expr))
13664 return error_mark_node;
13665
13666 conversion_obstack_sentinel cos;
13667
13668 conv = reference_binding (rto: type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13669 flags, complain);
13670 /* If this conversion failed, we're in C++20, and we have something like
13671 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13672 if ((!conv || conv->bad_p)
13673 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13674 {
13675 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13676 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13677 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13678 conversion *c = reference_binding (rto: type, TREE_TYPE (e), expr: e,
13679 /*c_cast_p=*/false, flags, complain);
13680 /* If this worked, use it. */
13681 if (c && !c->bad_p)
13682 expr = e, conv = c;
13683 }
13684 if (!conv || conv->bad_p)
13685 {
13686 if (complain & tf_error)
13687 {
13688 if (conv)
13689 convert_like (convs: conv, expr, complain);
13690 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13691 && !TYPE_REF_IS_RVALUE (type)
13692 && !lvalue_p (expr))
13693 error_at (loc, "invalid initialization of non-const reference of "
13694 "type %qH from an rvalue of type %qI",
13695 type, TREE_TYPE (expr));
13696 else
13697 error_at (loc, "invalid initialization of reference of type "
13698 "%qH from expression of type %qI", type,
13699 TREE_TYPE (expr));
13700 }
13701 return error_mark_node;
13702 }
13703
13704 if (conv->kind == ck_ref_bind)
13705 /* Perform the conversion. */
13706 expr = convert_like (convs: conv, expr, complain);
13707 else if (conv->kind == ck_ambig)
13708 /* We gave an error in build_user_type_conversion_1. */
13709 expr = error_mark_node;
13710 else
13711 gcc_unreachable ();
13712
13713 return expr;
13714}
13715
13716/* Return true if T is std::pair<const T&, const T&>. */
13717
13718static bool
13719std_pair_ref_ref_p (tree t)
13720{
13721 /* First, check if we have std::pair. */
13722 if (!NON_UNION_CLASS_TYPE_P (t)
13723 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
13724 return false;
13725 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
13726 if (!decl_in_std_namespace_p (tdecl))
13727 return false;
13728 tree name = DECL_NAME (tdecl);
13729 if (!name || !id_equal (id: name, str: "pair"))
13730 return false;
13731
13732 /* Now see if the template arguments are both const T&. */
13733 tree args = CLASSTYPE_TI_ARGS (t);
13734 if (TREE_VEC_LENGTH (args) != 2)
13735 return false;
13736 for (int i = 0; i < 2; i++)
13737 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
13738 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
13739 return false;
13740
13741 return true;
13742}
13743
13744/* Return true if a class CTYPE is either std::reference_wrapper or
13745 std::ref_view, or a reference wrapper class. We consider a class
13746 a reference wrapper class if it has a reference member. We no
13747 longer check that it has a constructor taking the same reference type
13748 since that approach still generated too many false positives. */
13749
13750static bool
13751class_has_reference_member_p (tree t)
13752{
13753 for (tree fields = TYPE_FIELDS (t);
13754 fields;
13755 fields = DECL_CHAIN (fields))
13756 if (TREE_CODE (fields) == FIELD_DECL
13757 && !DECL_ARTIFICIAL (fields)
13758 && TYPE_REF_P (TREE_TYPE (fields)))
13759 return true;
13760 return false;
13761}
13762
13763/* A wrapper for the above suitable as a callback for dfs_walk_once. */
13764
13765static tree
13766class_has_reference_member_p_r (tree binfo, void *)
13767{
13768 return (class_has_reference_member_p (BINFO_TYPE (binfo))
13769 ? integer_one_node : NULL_TREE);
13770}
13771
13772static bool
13773reference_like_class_p (tree ctype)
13774{
13775 if (!CLASS_TYPE_P (ctype))
13776 return false;
13777
13778 /* Also accept a std::pair<const T&, const T&>. */
13779 if (std_pair_ref_ref_p (t: ctype))
13780 return true;
13781
13782 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
13783 if (decl_in_std_namespace_p (tdecl))
13784 {
13785 tree name = DECL_NAME (tdecl);
13786 if (name
13787 && (id_equal (id: name, str: "reference_wrapper")
13788 || id_equal (id: name, str: "span")
13789 || id_equal (id: name, str: "ref_view")))
13790 return true;
13791 }
13792
13793 /* Some classes, such as std::tuple, have the reference member in its
13794 (non-direct) base class. */
13795 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
13796 nullptr, nullptr))
13797 return true;
13798
13799 return false;
13800}
13801
13802/* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
13803 that initializes the LHS (and at least one of its arguments represents
13804 a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
13805 if none found. For instance:
13806
13807 const S& s = S().self(); // S::self (&TARGET_EXPR <...>)
13808 const int& r = (42, f(1)); // f(1)
13809 const int& t = b ? f(1) : f(2); // f(1)
13810 const int& u = b ? f(1) : f(g); // f(1)
13811 const int& v = b ? f(g) : f(2); // f(2)
13812 const int& w = b ? f(g) : f(g); // NULL_TREE
13813 const int& y = (f(1), 42); // NULL_TREE
13814 const int& z = f(f(1)); // f(f(1))
13815
13816 EXPR is the initializer. If ARG_P is true, we're processing an argument
13817 to a function; the point is to distinguish between, for example,
13818
13819 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
13820
13821 where we shouldn't warn, and
13822
13823 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
13824
13825 where we should warn (Ref is a reference_like_class_p so we see through
13826 it. */
13827
13828static tree
13829do_warn_dangling_reference (tree expr, bool arg_p)
13830{
13831 STRIP_NOPS (expr);
13832
13833 if (arg_p && expr_represents_temporary_p (expr))
13834 {
13835 /* An attempt to reduce the number of -Wdangling-reference
13836 false positives concerning reference wrappers (c++/107532).
13837 When we encounter a reference_like_class_p, we don't warn
13838 just yet; instead, we keep recursing to see if there were
13839 any temporaries behind the reference-wrapper class. */
13840 tree e = expr;
13841 while (handled_component_p (t: e))
13842 e = TREE_OPERAND (e, 0);
13843 if (!reference_like_class_p (TREE_TYPE (e)))
13844 return expr;
13845 }
13846
13847 switch (TREE_CODE (expr))
13848 {
13849 case CALL_EXPR:
13850 {
13851 tree fndecl = cp_get_callee_fndecl_nofold (expr);
13852 if (!fndecl
13853 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
13854 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
13855 opt: OPT_Wdangling_reference)
13856 /* Don't emit a false positive for:
13857 std::vector<int> v = ...;
13858 std::vector<int>::const_iterator it = v.begin();
13859 const int &r = *it++;
13860 because R refers to one of the int elements of V, not to
13861 a temporary object. Member operator* may return a reference
13862 but probably not to one of its arguments. */
13863 || (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13864 && DECL_OVERLOADED_OPERATOR_P (fndecl)
13865 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF)))
13866 return NULL_TREE;
13867
13868 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
13869 /* If the function doesn't return a reference, don't warn. This
13870 can be e.g.
13871 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
13872 which doesn't dangle: std::min here returns an int.
13873
13874 If the function returns a std::pair<const T&, const T&>, we
13875 warn, to detect e.g.
13876 std::pair<const int&, const int&> v = std::minmax(1, 2);
13877 which also creates a dangling reference, because std::minmax
13878 returns std::pair<const T&, const T&>(b, a). */
13879 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (ctype: rettype)))
13880 return NULL_TREE;
13881
13882 /* Here we're looking to see if any of the arguments is a temporary
13883 initializing a reference parameter. */
13884 for (int i = 0; i < call_expr_nargs (expr); ++i)
13885 {
13886 tree arg = CALL_EXPR_ARG (expr, i);
13887 /* Check that this argument initializes a reference, except for
13888 the argument initializing the object of a member function. */
13889 if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13890 && !TYPE_REF_P (TREE_TYPE (arg)))
13891 continue;
13892 STRIP_NOPS (arg);
13893 if (TREE_CODE (arg) == ADDR_EXPR)
13894 arg = TREE_OPERAND (arg, 0);
13895 /* Recurse to see if the argument is a temporary. It could also
13896 be another call taking a temporary and returning it and
13897 initializing this reference parameter. */
13898 if (do_warn_dangling_reference (expr: arg, /*arg_p=*/true))
13899 return expr;
13900 /* Don't warn about member function like:
13901 std::any a(...);
13902 S& s = a.emplace<S>({0}, 0);
13903 which constructs a new object and returns a reference to it, but
13904 we still want to detect:
13905 struct S { const S& self () { return *this; } };
13906 const S& s = S().self();
13907 where 's' dangles. If we've gotten here, the object this function
13908 is invoked on is not a temporary. */
13909 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl))
13910 break;
13911 }
13912 return NULL_TREE;
13913 }
13914 case COMPOUND_EXPR:
13915 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
13916 case COND_EXPR:
13917 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
13918 return t;
13919 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
13920 case PAREN_EXPR:
13921 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
13922 case TARGET_EXPR:
13923 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
13924 default:
13925 return NULL_TREE;
13926 }
13927}
13928
13929/* Implement -Wdangling-reference, to detect cases like
13930
13931 int n = 1;
13932 const int& r = std::max(n - 1, n + 1); // r is dangling
13933
13934 This creates temporaries from the arguments, returns a reference to
13935 one of the temporaries, but both temporaries are destroyed at the end
13936 of the full expression.
13937
13938 This works by checking if a reference is initialized with a function
13939 that returns a reference, and at least one parameter of the function
13940 is a reference that is bound to a temporary. It assumes that such a
13941 function actually returns one of its arguments.
13942
13943 DECL is the reference being initialized, INIT is the initializer. */
13944
13945static void
13946maybe_warn_dangling_reference (const_tree decl, tree init)
13947{
13948 if (!warn_dangling_reference)
13949 return;
13950 tree type = TREE_TYPE (decl);
13951 /* Only warn if what we're initializing has type T&& or const T&, or
13952 std::pair<const T&, const T&>. (A non-const lvalue reference can't
13953 bind to a temporary.) */
13954 if (!((TYPE_REF_OBJ_P (type)
13955 && (TYPE_REF_IS_RVALUE (type)
13956 || CP_TYPE_CONST_P (TREE_TYPE (type))))
13957 || std_pair_ref_ref_p (t: type)))
13958 return;
13959 /* Don't suppress the diagnostic just because the call comes from
13960 a system header. If the DECL is not in a system header, or if
13961 -Wsystem-headers was provided, warn. */
13962 auto wsh
13963 = make_temp_override (var&: global_dc->m_warn_system_headers,
13964 overrider: (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
13965 || global_dc->m_warn_system_headers));
13966 if (tree call = do_warn_dangling_reference (expr: init, /*arg_p=*/false))
13967 {
13968 auto_diagnostic_group d;
13969 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
13970 "possibly dangling reference to a temporary"))
13971 inform (EXPR_LOCATION (call), "the temporary was destroyed at "
13972 "the end of the full expression %qE", call);
13973 }
13974}
13975
13976/* If *P is an xvalue expression, prevent temporary lifetime extension if it
13977 gets used to initialize a reference. */
13978
13979static tree
13980prevent_lifetime_extension (tree t)
13981{
13982 tree *p = &t;
13983 while (TREE_CODE (*p) == COMPOUND_EXPR)
13984 p = &TREE_OPERAND (*p, 1);
13985 while (handled_component_p (t: *p))
13986 p = &TREE_OPERAND (*p, 0);
13987 /* Change a TARGET_EXPR from prvalue to xvalue. */
13988 if (TREE_CODE (*p) == TARGET_EXPR)
13989 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
13990 move (TARGET_EXPR_SLOT (*p)));
13991 return t;
13992}
13993
13994/* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
13995 which is bound either to a reference or a std::initializer_list. */
13996
13997static tree
13998extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
13999 tree *cond_guard)
14000{
14001 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14002 the temporary object that is the complete object of a subobject to which
14003 the reference is bound persists for the lifetime of the reference if the
14004 glvalue to which the reference is bound was obtained through one of the
14005 following:
14006 - a temporary materialization conversion ([conv.rval]),
14007 - ( expression ), where expression is one of these expressions,
14008 - subscripting ([expr.sub]) of an array operand, where that operand is one
14009 of these expressions,
14010 - a class member access ([expr.ref]) using the . operator where the left
14011 operand is one of these expressions and the right operand designates a
14012 non-static data member of non-reference type,
14013 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14014 where the left operand is one of these expressions and the right operand
14015 is a pointer to data member of non-reference type,
14016 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14017 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14018 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14019 a glvalue operand that is one of these expressions to a glvalue that
14020 refers to the object designated by the operand, or to its complete
14021 object or a subobject thereof,
14022 - a conditional expression ([expr.cond]) that is a glvalue where the
14023 second or third operand is one of these expressions, or
14024 - a comma expression ([expr.comma]) that is a glvalue where the right
14025 operand is one of these expressions. */
14026
14027 /* FIXME several cases are still handled wrong (101572, 81420). */
14028
14029 tree sub = init;
14030 tree *p;
14031 STRIP_NOPS (sub);
14032 if (TREE_CODE (sub) == COMPOUND_EXPR)
14033 {
14034 TREE_OPERAND (sub, 1)
14035 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14036 cond_guard);
14037 return init;
14038 }
14039 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14040 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14041 (TREE_OPERAND (sub, 1)))))
14042 {
14043 /* A pointer-to-member operation. */
14044 TREE_OPERAND (sub, 0)
14045 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14046 cond_guard);
14047 return init;
14048 }
14049 if (TREE_CODE (sub) == COND_EXPR)
14050 {
14051 tree cur_cond_guard = NULL_TREE;
14052 if (TREE_OPERAND (sub, 1))
14053 TREE_OPERAND (sub, 1)
14054 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14055 cond_guard: &cur_cond_guard);
14056 if (cur_cond_guard)
14057 {
14058 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14059 NOP_EXPR, boolean_true_node,
14060 tf_warning_or_error);
14061 TREE_OPERAND (sub, 1)
14062 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14063 tf_warning_or_error);
14064 }
14065 cur_cond_guard = NULL_TREE;
14066 if (TREE_OPERAND (sub, 2))
14067 TREE_OPERAND (sub, 2)
14068 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14069 cond_guard: &cur_cond_guard);
14070 if (cur_cond_guard)
14071 {
14072 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14073 NOP_EXPR, boolean_true_node,
14074 tf_warning_or_error);
14075 TREE_OPERAND (sub, 2)
14076 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14077 tf_warning_or_error);
14078 }
14079 return init;
14080 }
14081 if (TREE_CODE (sub) != ADDR_EXPR)
14082 return init;
14083 /* Deal with binding to a subobject. */
14084 for (p = &TREE_OPERAND (sub, 0);
14085 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14086 p = &TREE_OPERAND (*p, 0);
14087 if (TREE_CODE (*p) == TARGET_EXPR)
14088 {
14089 tree subinit = NULL_TREE;
14090 *p = set_up_extended_ref_temp (decl, expr: *p, cleanups, initp: &subinit, cond_guard);
14091 recompute_tree_invariant_for_addr_expr (sub);
14092 if (init != sub)
14093 init = fold_convert (TREE_TYPE (init), sub);
14094 if (subinit)
14095 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14096 }
14097 return init;
14098}
14099
14100/* INIT is part of the initializer for DECL. If there are any
14101 reference or initializer lists being initialized, extend their
14102 lifetime to match that of DECL. */
14103
14104tree
14105extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14106 tree *cond_guard)
14107{
14108 tree type = TREE_TYPE (init);
14109 if (processing_template_decl)
14110 return init;
14111
14112 maybe_warn_dangling_reference (decl, init);
14113
14114 if (TYPE_REF_P (type))
14115 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14116 else
14117 {
14118 tree ctor = init;
14119 if (TREE_CODE (ctor) == TARGET_EXPR)
14120 ctor = TARGET_EXPR_INITIAL (ctor);
14121 if (TREE_CODE (ctor) == CONSTRUCTOR)
14122 {
14123 /* [dcl.init] When initializing an aggregate from a parenthesized list
14124 of values... a temporary object bound to a reference does not have
14125 its lifetime extended. */
14126 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14127 return init;
14128
14129 if (is_std_init_list (type))
14130 {
14131 /* The temporary array underlying a std::initializer_list
14132 is handled like a reference temporary. */
14133 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14134 array = extend_ref_init_temps_1 (decl, init: array, cleanups,
14135 cond_guard);
14136 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14137 }
14138 else
14139 {
14140 unsigned i;
14141 constructor_elt *p;
14142 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14143 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14144 p->value = extend_ref_init_temps (decl, init: p->value, cleanups,
14145 cond_guard);
14146 }
14147 recompute_constructor_flags (ctor);
14148 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14149 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14150 }
14151 }
14152
14153 return init;
14154}
14155
14156/* Returns true iff an initializer for TYPE could contain temporaries that
14157 need to be extended because they are bound to references or
14158 std::initializer_list. */
14159
14160bool
14161type_has_extended_temps (tree type)
14162{
14163 type = strip_array_types (type);
14164 if (TYPE_REF_P (type))
14165 return true;
14166 if (CLASS_TYPE_P (type))
14167 {
14168 if (is_std_init_list (type))
14169 return true;
14170 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14171 f; f = next_aggregate_field (DECL_CHAIN (f)))
14172 if (type_has_extended_temps (TREE_TYPE (f)))
14173 return true;
14174 }
14175 return false;
14176}
14177
14178/* Returns true iff TYPE is some variant of std::initializer_list. */
14179
14180bool
14181is_std_init_list (tree type)
14182{
14183 if (!TYPE_P (type))
14184 return false;
14185 if (cxx_dialect == cxx98)
14186 return false;
14187 /* Look through typedefs. */
14188 type = TYPE_MAIN_VARIANT (type);
14189 return (CLASS_TYPE_P (type)
14190 && CP_TYPE_CONTEXT (type) == std_node
14191 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14192}
14193
14194/* Returns true iff DECL is a list constructor: i.e. a constructor which
14195 will accept an argument list of a single std::initializer_list<T>. */
14196
14197bool
14198is_list_ctor (tree decl)
14199{
14200 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14201 tree arg;
14202
14203 if (!args || args == void_list_node)
14204 return false;
14205
14206 arg = non_reference (TREE_VALUE (args));
14207 if (!is_std_init_list (type: arg))
14208 return false;
14209
14210 args = TREE_CHAIN (args);
14211
14212 if (args && args != void_list_node && !TREE_PURPOSE (args))
14213 /* There are more non-defaulted parms. */
14214 return false;
14215
14216 return true;
14217}
14218
14219/* We know that can_convert_arg_bad already said "no" when trying to convert
14220 FROM to TO with ARG and FLAGS. Try to figure out if it was because
14221 an explicit conversion function was skipped when looking for a way to
14222 perform the conversion. At this point we've already printed an error. */
14223
14224void
14225maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
14226{
14227 if (!(flags & LOOKUP_ONLYCONVERTING))
14228 return;
14229
14230 conversion_obstack_sentinel cos;
14231 conversion *c = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
14232 flags: flags & ~LOOKUP_ONLYCONVERTING, complain: tf_none);
14233 if (c && !c->bad_p && c->user_conv_p)
14234 /* Ay, the conversion would have worked in direct-init context. */
14235 for (; c; c = next_conversion (conv: c))
14236 if (c->kind == ck_user
14237 && DECL_P (c->cand->fn)
14238 && DECL_NONCONVERTING_P (c->cand->fn))
14239 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
14240 "function was not considered");
14241}
14242
14243#include "gt-cp-call.h"
14244

source code of gcc/cp/call.cc