1/* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2026 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 "c-family/c-type-mismatch.h"
46#include "tristate.h"
47#include "tree-pretty-print-markup.h"
48#include "contracts.h" // maybe_contract_wrap_call
49
50/* The various kinds of conversion. */
51
52enum conversion_kind {
53 ck_identity,
54 ck_lvalue,
55 ck_fnptr,
56 ck_qual,
57 ck_std,
58 ck_ptr,
59 ck_pmem,
60 ck_base,
61 ck_ref_bind,
62 ck_user,
63 ck_ambig,
64 ck_list,
65 ck_aggr,
66 ck_rvalue,
67 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
68 this kind whenever we know the true conversion is either bad or outright
69 invalid, but we don't want to attempt to compute the bad conversion (for
70 sake of avoiding unnecessary instantiation). bad_p should always be set
71 for these. */
72 ck_deferred_bad,
73};
74
75/* The rank of the conversion. Order of the enumerals matters; better
76 conversions should come earlier in the list. */
77
78enum conversion_rank {
79 cr_identity,
80 cr_exact,
81 cr_promotion,
82 cr_std,
83 cr_pbool,
84 cr_user,
85 cr_ellipsis,
86 cr_bad
87};
88
89/* An implicit conversion sequence, in the sense of [over.best.ics].
90 The first conversion to be performed is at the end of the chain.
91 That conversion is always a cr_identity conversion. */
92
93struct conversion {
94 /* The kind of conversion represented by this step. */
95 conversion_kind kind;
96 /* The rank of this conversion. */
97 conversion_rank rank;
98 BOOL_BITFIELD user_conv_p : 1;
99 BOOL_BITFIELD ellipsis_p : 1;
100 BOOL_BITFIELD this_p : 1;
101 /* True if this conversion would be permitted with a bending of
102 language standards, e.g. disregarding pointer qualifiers or
103 converting integers to pointers. */
104 BOOL_BITFIELD bad_p : 1;
105 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
106 temporary should be created to hold the result of the
107 conversion. If KIND is ck_ambig or ck_user, true means force
108 copy-initialization. */
109 BOOL_BITFIELD need_temporary_p : 1;
110 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
111 from a pointer-to-derived to pointer-to-base is being performed. */
112 BOOL_BITFIELD base_p : 1;
113 /* If KIND is ck_ref_bind, true when either an lvalue reference is
114 being bound to an lvalue expression or an rvalue reference is
115 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
116 true when we are treating an lvalue as an rvalue (12.8p33). If
117 ck_identity, we will be binding a reference directly or decaying to
118 a pointer. */
119 BOOL_BITFIELD rvaluedness_matches_p: 1;
120 BOOL_BITFIELD check_narrowing: 1;
121 /* Whether check_narrowing should only check TREE_CONSTANTs; used
122 in build_converted_constant_expr. */
123 BOOL_BITFIELD check_narrowing_const_only: 1;
124 /* True if this conversion is taking place in a copy-initialization context
125 and we should only consider converting constructors. Only set in
126 ck_base and ck_rvalue. */
127 BOOL_BITFIELD copy_init_p : 1;
128 /* The type of the expression resulting from the conversion. */
129 tree type;
130 union {
131 /* The next conversion in the chain. Since the conversions are
132 arranged from outermost to innermost, the NEXT conversion will
133 actually be performed before this conversion. This variant is
134 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
135 ck_list. Please use the next_conversion function instead
136 of using this field directly. */
137 conversion *next;
138 /* The expression at the beginning of the conversion chain. This
139 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
140 You can use conv_get_original_expr to get this expression. */
141 tree expr;
142 /* The array of conversions for an initializer_list, so this
143 variant is used only when KIN D is ck_list. */
144 conversion **list;
145 } u;
146 /* The function candidate corresponding to this conversion
147 sequence. This field is only used if KIND is ck_user. */
148 struct z_candidate *cand;
149};
150
151#define CONVERSION_RANK(NODE) \
152 ((NODE)->bad_p ? cr_bad \
153 : (NODE)->ellipsis_p ? cr_ellipsis \
154 : (NODE)->user_conv_p ? cr_user \
155 : (NODE)->rank)
156
157#define BAD_CONVERSION_RANK(NODE) \
158 ((NODE)->ellipsis_p ? cr_ellipsis \
159 : (NODE)->user_conv_p ? cr_user \
160 : (NODE)->rank)
161
162static struct obstack conversion_obstack;
163static bool conversion_obstack_initialized;
164struct rejection_reason;
165
166static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
167static int equal_functions (tree, tree);
168static int joust (struct z_candidate *, struct z_candidate *, bool,
169 tsubst_flags_t);
170static int compare_ics (conversion *, conversion *);
171static void maybe_warn_class_memaccess (location_t, tree,
172 const vec<tree, va_gc> *);
173static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
174static tree convert_like (conversion *, tree, tsubst_flags_t);
175static tree convert_like_with_context (conversion *, tree, tree, int,
176 tsubst_flags_t);
177static void op_error (const op_location_t &, enum tree_code, enum tree_code,
178 tree, tree, tree, bool);
179static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
180 tsubst_flags_t);
181static void print_z_candidate (location_t, const char *, struct z_candidate *);
182static void print_z_candidates (location_t, struct z_candidate *,
183 tristate = tristate::unknown ());
184static tree build_this (tree);
185static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
186static bool any_strictly_viable (struct z_candidate *);
187static struct z_candidate *add_template_candidate
188 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
189 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
190static struct z_candidate *add_template_candidate_real
191 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
192 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
193static bool is_complete (tree);
194static struct z_candidate *add_conv_candidate
195 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
196 tree, tsubst_flags_t);
197static struct z_candidate *add_function_candidate
198 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
199 tree, int, conversion**, bool, tsubst_flags_t);
200static conversion *implicit_conversion (tree, tree, tree, bool, int,
201 tsubst_flags_t);
202static conversion *reference_binding (tree, tree, tree, bool, int,
203 tsubst_flags_t);
204static conversion *build_conv (conversion_kind, tree, conversion *);
205static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
206static conversion *next_conversion (conversion *);
207static bool is_subseq (conversion *, conversion *);
208static conversion *maybe_handle_ref_bind (conversion **);
209static void maybe_handle_implicit_object (conversion **);
210static struct z_candidate *add_candidate
211 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
212 conversion **, tree, tree, int, struct rejection_reason *, int);
213static tree source_type (conversion *);
214static void add_warning (struct z_candidate *, struct z_candidate *);
215static conversion *direct_reference_binding (tree, conversion *);
216static bool promoted_arithmetic_type_p (tree);
217static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
218static char *name_as_c_string (tree, tree, bool *);
219static tree prep_operand (tree);
220static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
221 bool, tree, tree, int, struct z_candidate **,
222 tsubst_flags_t);
223static conversion *merge_conversion_sequences (conversion *, conversion *);
224static tree build_temp (tree, tree, int, enum diagnostics::kind *,
225 tsubst_flags_t);
226static conversion *build_identity_conv (tree, tree);
227static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
228static bool conv_is_prvalue (conversion *);
229static tree prevent_lifetime_extension (tree);
230
231/* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
232 NAME can take many forms... */
233
234bool
235check_dtor_name (tree basetype, tree name)
236{
237 /* Just accept something we've already complained about. */
238 if (name == error_mark_node)
239 return true;
240
241 if (TREE_CODE (name) == TYPE_DECL)
242 name = TREE_TYPE (name);
243 else if (TYPE_P (name))
244 /* OK */;
245 else if (identifier_p (t: name))
246 {
247 if ((MAYBE_CLASS_TYPE_P (basetype)
248 || TREE_CODE (basetype) == ENUMERAL_TYPE)
249 && name == constructor_name (basetype))
250 return true;
251
252 /* Otherwise lookup the name, it could be an unrelated typedef
253 of the correct type. */
254 name = lookup_name (name, want: LOOK_want::TYPE);
255 if (!name)
256 return false;
257 name = TREE_TYPE (name);
258 if (name == error_mark_node)
259 return false;
260 }
261 else
262 {
263 /* In the case of:
264
265 template <class T> struct S { ~S(); };
266 int i;
267 i.~S();
268
269 NAME will be a class template. */
270 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
271 return false;
272 }
273
274 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
275}
276
277/* We want the address of a function or method. We avoid creating a
278 pointer-to-member function. */
279
280tree
281build_addr_func (tree function, tsubst_flags_t complain)
282{
283 tree type = TREE_TYPE (function);
284
285 /* We have to do these by hand to avoid real pointer to member
286 functions. */
287 if (TREE_CODE (type) == METHOD_TYPE)
288 {
289 if (TREE_CODE (function) == OFFSET_REF)
290 {
291 tree object = build_address (TREE_OPERAND (function, 0));
292 return get_member_function_from_ptrfunc (&object,
293 TREE_OPERAND (function, 1),
294 complain);
295 }
296 function = build_address (function);
297 }
298 else if (TREE_CODE (function) == FUNCTION_DECL
299 && DECL_IMMEDIATE_FUNCTION_P (function))
300 function = build_address (function);
301 else
302 function = decay_conversion (function, complain, /*reject_builtin=*/false);
303
304 return function;
305}
306
307/* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
308 POINTER_TYPE to those. Note, pointer to member function types
309 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
310 two variants. build_call_a is the primitive taking an array of
311 arguments, while build_call_n is a wrapper that handles varargs. */
312
313tree
314build_call_n (tree function, int n, ...)
315{
316 if (n == 0)
317 return build_call_a (function, 0, NULL);
318 else
319 {
320 tree *argarray = XALLOCAVEC (tree, n);
321 va_list ap;
322 int i;
323
324 va_start (ap, n);
325 for (i = 0; i < n; i++)
326 argarray[i] = va_arg (ap, tree);
327 va_end (ap);
328 return build_call_a (function, n, argarray);
329 }
330}
331
332/* Update various flags in cfun and the call itself based on what is being
333 called. Split out of build_call_a so that bot_manip can use it too. */
334
335void
336set_flags_from_callee (tree call)
337{
338 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
339 tree decl = cp_get_callee_fndecl_nofold (call);
340
341 /* We check both the decl and the type; a function may be known not to
342 throw without being declared throw(). */
343 bool nothrow = decl && TREE_NOTHROW (decl);
344 tree callee = cp_get_callee (call);
345 if (callee)
346 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
347 else if (TREE_CODE (call) == CALL_EXPR
348 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
349 nothrow = true;
350
351 if (cfun && cp_function_chain && !cp_unevaluated_operand)
352 {
353 if (!nothrow && at_function_scope_p ())
354 cp_function_chain->can_throw = 1;
355
356 if (decl && TREE_THIS_VOLATILE (decl))
357 current_function_returns_abnormally = 1;
358 }
359
360 TREE_NOTHROW (call) = nothrow;
361}
362
363tree
364build_call_a (tree function, int n, tree *argarray)
365{
366 tree decl;
367 tree result_type;
368 tree fntype;
369 int i;
370
371 function = build_addr_func (function, complain: tf_warning_or_error);
372
373 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
374 fntype = TREE_TYPE (TREE_TYPE (function));
375 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
376 result_type = TREE_TYPE (fntype);
377 /* An rvalue has no cv-qualifiers. */
378 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
379 result_type = cv_unqualified (result_type);
380
381 function = build_call_array_loc (input_location,
382 result_type, function, n, argarray);
383 set_flags_from_callee (function);
384
385 decl = get_callee_fndecl (function);
386
387 if (decl && !TREE_USED (decl))
388 {
389 /* We invoke build_call directly for several library
390 functions. These may have been declared normally if
391 we're building libgcc, so we can't just check
392 DECL_ARTIFICIAL. */
393 gcc_assert (DECL_ARTIFICIAL (decl)
394 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
395 "__", 2));
396 mark_used (decl);
397 }
398
399 require_complete_eh_spec_types (fntype, decl);
400
401 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
402
403 /* Don't pass empty class objects by value. This is useful
404 for tags in STL, which are used to control overload resolution.
405 We don't need to handle other cases of copying empty classes. */
406 if (!decl || !fndecl_built_in_p (node: decl))
407 for (i = 0; i < n; i++)
408 {
409 tree arg = CALL_EXPR_ARG (function, i);
410 if (is_empty_class (TREE_TYPE (arg))
411 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
412 {
413 while (TREE_CODE (arg) == TARGET_EXPR)
414 /* We're disconnecting the initializer from its target,
415 don't create a temporary. */
416 arg = TARGET_EXPR_INITIAL (arg);
417 suppress_warning (arg, OPT_Wunused_result);
418 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
419 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
420 CALL_EXPR_ARG (function, i) = arg;
421 }
422 }
423
424 return function;
425}
426
427/* New overloading code. */
428
429struct z_candidate;
430
431struct candidate_warning {
432 z_candidate *loser;
433 candidate_warning *next;
434};
435
436/* Information for providing diagnostics about why overloading failed. */
437
438enum rejection_reason_code {
439 rr_none,
440 rr_arity,
441 rr_explicit_conversion,
442 rr_template_conversion,
443 rr_arg_conversion,
444 rr_bad_arg_conversion,
445 rr_template_unification,
446 rr_invalid_copy,
447 rr_inherited_ctor,
448 rr_constraint_failure,
449 rr_ignored,
450};
451
452struct conversion_info {
453 /* The index of the argument, 0-based. */
454 int n_arg;
455 /* The actual argument or its type. */
456 tree from;
457 /* The type of the parameter. */
458 tree to_type;
459 /* The location of the argument. */
460 location_t loc;
461};
462
463struct rejection_reason {
464 enum rejection_reason_code code;
465 union {
466 /* Information about an arity mismatch. */
467 struct {
468 /* The expected number of arguments. */
469 int expected;
470 /* The actual number of arguments in the call. */
471 int actual;
472 /* Whether EXPECTED should be treated as a lower bound. */
473 bool least_p;
474 } arity;
475 /* Information about an argument conversion mismatch. */
476 struct conversion_info conversion;
477 /* Same, but for bad argument conversions. */
478 struct conversion_info bad_conversion;
479 /* Information about template unification failures. These are the
480 parameters passed to fn_type_unification. */
481 struct {
482 tree tmpl;
483 tree explicit_targs;
484 int num_targs;
485 const tree *args;
486 unsigned int nargs;
487 tree return_type;
488 unification_kind_t strict;
489 int flags;
490 } template_unification;
491 /* Information about template instantiation failures. These are the
492 parameters passed to instantiate_template. */
493 struct {
494 tree tmpl;
495 tree targs;
496 } template_instantiation;
497 } u;
498};
499
500struct z_candidate {
501 /* The FUNCTION_DECL that will be called if this candidate is
502 selected by overload resolution. */
503 tree fn;
504 /* If not NULL_TREE, the first argument to use when calling this
505 function. */
506 tree first_arg;
507 /* The rest of the arguments to use when calling this function. If
508 there are no further arguments this may be NULL or it may be an
509 empty vector. */
510 const vec<tree, va_gc> *args;
511 /* The implicit conversion sequences for each of the arguments to
512 FN. */
513 conversion **convs;
514 /* The number of implicit conversion sequences. */
515 size_t num_convs;
516 /* If FN is a user-defined conversion, the standard conversion
517 sequence from the type returned by FN to the desired destination
518 type. */
519 conversion *second_conv;
520 struct rejection_reason *reason;
521 /* If FN is a member function, the binfo indicating the path used to
522 qualify the name of FN at the call site. This path is used to
523 determine whether or not FN is accessible if it is selected by
524 overload resolution. The DECL_CONTEXT of FN will always be a
525 (possibly improper) base of this binfo. */
526 tree access_path;
527 /* If FN is a non-static member function, the binfo indicating the
528 subobject to which the `this' pointer should be converted if FN
529 is selected by overload resolution. The type pointed to by
530 the `this' pointer must correspond to the most derived class
531 indicated by the CONVERSION_PATH. */
532 tree conversion_path;
533 tree template_decl;
534 tree explicit_targs;
535 candidate_warning *warnings;
536 z_candidate *next;
537 int viable;
538
539 /* The flags active in add_candidate. */
540 int flags;
541
542 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
543 bool reversed () const { return (flags & LOOKUP_REVERSED); }
544};
545
546/* Returns true iff T is a null pointer constant in the sense of
547 [conv.ptr]. */
548
549bool
550null_ptr_cst_p (tree t)
551{
552 tree type = TREE_TYPE (t);
553
554 /* [conv.ptr]
555
556 A null pointer constant is an integer literal ([lex.icon]) with value
557 zero or a prvalue of type std::nullptr_t. */
558 if (NULLPTR_TYPE_P (type))
559 return true;
560
561 if (cxx_dialect >= cxx11)
562 {
563 STRIP_ANY_LOCATION_WRAPPER (t);
564
565 /* Core issue 903 says only literal 0 is a null pointer constant. */
566 if (TREE_CODE (t) == INTEGER_CST
567 && !TREE_OVERFLOW (t)
568 && TREE_CODE (type) == INTEGER_TYPE
569 && integer_zerop (t)
570 && !char_type_p (type))
571 return true;
572 }
573 else if (CP_INTEGRAL_TYPE_P (type))
574 {
575 t = fold_non_dependent_expr (t, tf_none);
576 STRIP_NOPS (t);
577 if (integer_zerop (t) && !TREE_OVERFLOW (t))
578 return true;
579 }
580
581 return false;
582}
583
584/* Returns true iff T is a null member pointer value (4.11). */
585
586bool
587null_member_pointer_value_p (tree t)
588{
589 tree type = TREE_TYPE (t);
590 if (!type)
591 return false;
592 else if (TYPE_PTRMEMFUNC_P (type))
593 return (TREE_CODE (t) == CONSTRUCTOR
594 && CONSTRUCTOR_NELTS (t)
595 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
596 else if (TYPE_PTRDATAMEM_P (type))
597 return integer_all_onesp (t);
598 else
599 return false;
600}
601
602/* Returns nonzero if PARMLIST consists of only default parms,
603 ellipsis, and/or undeduced parameter packs. */
604
605bool
606sufficient_parms_p (const_tree parmlist)
607{
608 for (; parmlist && parmlist != void_list_node;
609 parmlist = TREE_CHAIN (parmlist))
610 if (!TREE_PURPOSE (parmlist)
611 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
612 return false;
613 return true;
614}
615
616/* Allocate N bytes of memory from the conversion obstack. The memory
617 is zeroed before being returned. */
618
619static void *
620conversion_obstack_alloc (size_t n)
621{
622 void *p;
623 if (!conversion_obstack_initialized)
624 {
625 gcc_obstack_init (&conversion_obstack);
626 conversion_obstack_initialized = true;
627 }
628 p = obstack_alloc (&conversion_obstack, n);
629 memset (s: p, c: 0, n: n);
630 return p;
631}
632
633/* RAII class to discard anything added to conversion_obstack. */
634
635struct conversion_obstack_sentinel
636{
637 void *p;
638 conversion_obstack_sentinel (): p (conversion_obstack_alloc (n: 0)) {}
639 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
640};
641
642/* Allocate rejection reasons. */
643
644static struct rejection_reason *
645alloc_rejection (enum rejection_reason_code code)
646{
647 struct rejection_reason *p;
648 p = (struct rejection_reason *) conversion_obstack_alloc (n: sizeof *p);
649 p->code = code;
650 return p;
651}
652
653static struct rejection_reason *
654arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
655{
656 struct rejection_reason *r = alloc_rejection (code: rr_arity);
657 int adjust = first_arg != NULL_TREE;
658 r->u.arity.expected = expected - adjust;
659 r->u.arity.actual = actual - adjust;
660 r->u.arity.least_p = least_p;
661 return r;
662}
663
664static struct rejection_reason *
665arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
666 location_t loc)
667{
668 struct rejection_reason *r = alloc_rejection (code: rr_arg_conversion);
669 int adjust = first_arg != NULL_TREE;
670 r->u.conversion.n_arg = n_arg - adjust;
671 r->u.conversion.from = from;
672 r->u.conversion.to_type = to;
673 r->u.conversion.loc = loc;
674 return r;
675}
676
677static struct rejection_reason *
678bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
679 location_t loc)
680{
681 struct rejection_reason *r = alloc_rejection (code: rr_bad_arg_conversion);
682 int adjust = first_arg != NULL_TREE;
683 r->u.bad_conversion.n_arg = n_arg - adjust;
684 r->u.bad_conversion.from = from;
685 r->u.bad_conversion.to_type = to;
686 r->u.bad_conversion.loc = loc;
687 return r;
688}
689
690static struct rejection_reason *
691explicit_conversion_rejection (tree from, tree to)
692{
693 struct rejection_reason *r = alloc_rejection (code: rr_explicit_conversion);
694 r->u.conversion.n_arg = 0;
695 r->u.conversion.from = from;
696 r->u.conversion.to_type = to;
697 r->u.conversion.loc = UNKNOWN_LOCATION;
698 return r;
699}
700
701static struct rejection_reason *
702template_conversion_rejection (tree from, tree to)
703{
704 struct rejection_reason *r = alloc_rejection (code: rr_template_conversion);
705 r->u.conversion.n_arg = 0;
706 r->u.conversion.from = from;
707 r->u.conversion.to_type = to;
708 r->u.conversion.loc = UNKNOWN_LOCATION;
709 return r;
710}
711
712static struct rejection_reason *
713template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
714 const tree *args, unsigned int nargs,
715 tree return_type, unification_kind_t strict,
716 int flags)
717{
718 size_t args_n_bytes = sizeof (*args) * nargs;
719 tree *args1 = (tree *) conversion_obstack_alloc (n: args_n_bytes);
720 struct rejection_reason *r = alloc_rejection (code: rr_template_unification);
721 r->u.template_unification.tmpl = tmpl;
722 r->u.template_unification.explicit_targs = explicit_targs;
723 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
724 /* Copy args to our own storage. */
725 memcpy (dest: args1, src: args, n: args_n_bytes);
726 r->u.template_unification.args = args1;
727 r->u.template_unification.nargs = nargs;
728 r->u.template_unification.return_type = return_type;
729 r->u.template_unification.strict = strict;
730 r->u.template_unification.flags = flags;
731 return r;
732}
733
734static struct rejection_reason *
735template_unification_error_rejection (void)
736{
737 return alloc_rejection (code: rr_template_unification);
738}
739
740static struct rejection_reason *
741invalid_copy_with_fn_template_rejection (void)
742{
743 struct rejection_reason *r = alloc_rejection (code: rr_invalid_copy);
744 return r;
745}
746
747static struct rejection_reason *
748inherited_ctor_rejection (void)
749{
750 struct rejection_reason *r = alloc_rejection (code: rr_inherited_ctor);
751 return r;
752}
753
754/* Build a constraint failure record. */
755
756static struct rejection_reason *
757constraint_failure (void)
758{
759 struct rejection_reason *r = alloc_rejection (code: rr_constraint_failure);
760 return r;
761}
762
763/* Dynamically allocate a conversion. */
764
765static conversion *
766alloc_conversion (conversion_kind kind)
767{
768 conversion *c;
769 c = (conversion *) conversion_obstack_alloc (n: sizeof (conversion));
770 c->kind = kind;
771 return c;
772}
773
774/* Make sure that all memory on the conversion obstack has been
775 freed. */
776
777void
778validate_conversion_obstack (void)
779{
780 if (conversion_obstack_initialized)
781 gcc_assert ((obstack_next_free (&conversion_obstack)
782 == obstack_base (&conversion_obstack)));
783}
784
785/* Dynamically allocate an array of N conversions. */
786
787static conversion **
788alloc_conversions (size_t n)
789{
790 return (conversion **) conversion_obstack_alloc (n: n * sizeof (conversion *));
791}
792
793/* True iff the active member of conversion::u for code CODE is NEXT. */
794
795static inline bool
796has_next (conversion_kind code)
797{
798 return !(code == ck_identity
799 || code == ck_ambig
800 || code == ck_list
801 || code == ck_aggr
802 || code == ck_deferred_bad);
803}
804
805static conversion *
806build_conv (conversion_kind code, tree type, conversion *from)
807{
808 conversion *t;
809 conversion_rank rank = CONVERSION_RANK (from);
810
811 /* Only call this function for conversions that use u.next. */
812 gcc_assert (from == NULL || has_next (code));
813
814 /* Note that the caller is responsible for filling in t->cand for
815 user-defined conversions. */
816 t = alloc_conversion (kind: code);
817 t->type = type;
818 t->u.next = from;
819
820 switch (code)
821 {
822 case ck_ptr:
823 case ck_pmem:
824 case ck_base:
825 case ck_std:
826 if (rank < cr_std)
827 rank = cr_std;
828 break;
829
830 case ck_qual:
831 case ck_fnptr:
832 if (rank < cr_exact)
833 rank = cr_exact;
834 break;
835
836 default:
837 break;
838 }
839 t->rank = rank;
840 t->user_conv_p = (code == ck_user || from->user_conv_p);
841 t->bad_p = from->bad_p;
842 t->base_p = false;
843 return t;
844}
845
846/* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
847 specialization of std::initializer_list<T>, if such a conversion is
848 possible. */
849
850static conversion *
851build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
852{
853 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
854 unsigned len = CONSTRUCTOR_NELTS (ctor);
855 conversion **subconvs = alloc_conversions (n: len);
856 conversion *t;
857 unsigned i;
858 tree val;
859
860 /* Within a list-initialization we can have more user-defined
861 conversions. */
862 flags &= ~LOOKUP_NO_CONVERSION;
863 /* But no narrowing conversions. */
864 flags |= LOOKUP_NO_NARROWING;
865
866 /* Can't make an array of these types. */
867 if (TYPE_REF_P (elttype)
868 || TREE_CODE (elttype) == FUNCTION_TYPE
869 || VOID_TYPE_P (elttype))
870 return NULL;
871
872 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
873 {
874 if (TREE_CODE (val) == RAW_DATA_CST)
875 {
876 tree elt
877 = build_int_cst (TREE_TYPE (val), RAW_DATA_UCHAR_ELT (val, 0));
878 conversion *sub
879 = implicit_conversion (elttype, TREE_TYPE (val), elt,
880 false, flags, complain);
881 conversion *next;
882 if (sub == NULL)
883 return NULL;
884 /* For conversion to initializer_list<unsigned char> or
885 initializer_list<char> or initializer_list<signed char>
886 we can optimize and keep RAW_DATA_CST with adjusted
887 type if we report narrowing errors if needed.
888 Use just one subconversion for that case. */
889 if (sub->kind == ck_std
890 && sub->type
891 && (TREE_CODE (sub->type) == INTEGER_TYPE
892 || is_byte_access_type (sub->type))
893 && TYPE_PRECISION (sub->type) == CHAR_BIT
894 && (next = next_conversion (sub))
895 && next->kind == ck_identity)
896 {
897 subconvs[i] = sub;
898 continue;
899 }
900 /* Otherwise. build separate subconv for each RAW_DATA_CST
901 byte. Wrap those into an artificial ck_list which convert_like
902 will then handle. */
903 conversion **subsubconvs = alloc_conversions (RAW_DATA_LENGTH (val));
904 unsigned int j;
905 subsubconvs[0] = sub;
906 for (j = 1; j < (unsigned) RAW_DATA_LENGTH (val); ++j)
907 {
908 elt = build_int_cst (TREE_TYPE (val),
909 RAW_DATA_UCHAR_ELT (val, j));
910 sub = implicit_conversion (elttype, TREE_TYPE (val), elt,
911 false, flags, complain);
912 if (sub == NULL)
913 return NULL;
914 subsubconvs[j] = sub;
915 }
916
917 t = alloc_conversion (kind: ck_list);
918 t->type = type;
919 t->u.list = subsubconvs;
920 t->rank = cr_exact;
921 for (j = 0; j < (unsigned) RAW_DATA_LENGTH (val); ++j)
922 {
923 sub = subsubconvs[j];
924 if (sub->rank > t->rank)
925 t->rank = sub->rank;
926 if (sub->user_conv_p)
927 t->user_conv_p = true;
928 if (sub->bad_p)
929 t->bad_p = true;
930 }
931 subconvs[i] = t;
932 continue;
933 }
934
935 conversion *sub
936 = implicit_conversion (elttype, TREE_TYPE (val), val,
937 false, flags, complain);
938 if (sub == NULL)
939 return NULL;
940
941 subconvs[i] = sub;
942 }
943
944 t = alloc_conversion (kind: ck_list);
945 t->type = type;
946 t->u.list = subconvs;
947 t->rank = cr_exact;
948
949 for (i = 0; i < len; ++i)
950 {
951 conversion *sub = subconvs[i];
952 if (sub->rank > t->rank)
953 t->rank = sub->rank;
954 if (sub->user_conv_p)
955 t->user_conv_p = true;
956 if (sub->bad_p)
957 t->bad_p = true;
958 }
959
960 return t;
961}
962
963/* Return the next conversion of the conversion chain (if applicable),
964 or NULL otherwise. Please use this function instead of directly
965 accessing fields of struct conversion. */
966
967static conversion *
968next_conversion (conversion *conv)
969{
970 if (conv == NULL
971 || !has_next (code: conv->kind))
972 return NULL;
973 return conv->u.next;
974}
975
976/* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
977 encountered. */
978
979static conversion *
980strip_standard_conversion (conversion *conv)
981{
982 while (conv
983 && conv->kind != ck_user
984 && has_next (code: conv->kind))
985 conv = next_conversion (conv);
986 return conv;
987}
988
989/* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
990 initializer for array type ATYPE. */
991
992static bool
993can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
994{
995 tree elttype = TREE_TYPE (atype);
996 unsigned i;
997
998 if (TREE_CODE (from) == CONSTRUCTOR)
999 {
1000 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
1001 {
1002 tree val = CONSTRUCTOR_ELT (from, i)->value;
1003 bool ok;
1004 if (TREE_CODE (elttype) == ARRAY_TYPE)
1005 ok = can_convert_array (atype: elttype, from: val, flags, complain);
1006 else
1007 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
1008 complain);
1009 if (!ok)
1010 return false;
1011 }
1012 return true;
1013 }
1014
1015 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
1016 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
1017 return array_string_literal_compatible_p (atype, from);
1018
1019 /* No other valid way to aggregate initialize an array. */
1020 return false;
1021}
1022
1023/* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
1024 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
1025 is in PSET. */
1026
1027static bool
1028field_in_pset (hash_set<tree, true> &pset, tree field)
1029{
1030 if (pset.contains (k: field))
1031 return true;
1032 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1033 for (field = TYPE_FIELDS (TREE_TYPE (field));
1034 field; field = DECL_CHAIN (field))
1035 {
1036 field = next_aggregate_field (field);
1037 if (field == NULL_TREE)
1038 break;
1039 if (field_in_pset (pset, field))
1040 return true;
1041 }
1042 return false;
1043}
1044
1045/* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1046 aggregate class, if such a conversion is possible. */
1047
1048static conversion *
1049build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1050{
1051 unsigned HOST_WIDE_INT i = 0;
1052 conversion *c;
1053 tree field = next_aggregate_field (TYPE_FIELDS (type));
1054 tree empty_ctor = NULL_TREE;
1055 hash_set<tree, true> pset;
1056
1057 /* We already called reshape_init in implicit_conversion, but it might not
1058 have done anything in the case of parenthesized aggr init. */
1059
1060 /* The conversions within the init-list aren't affected by the enclosing
1061 context; they're always simple copy-initialization. */
1062 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1063
1064 /* For designated initializers, verify that each initializer is convertible
1065 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
1066 visited. In the following loop then ignore already visited
1067 FIELD_DECLs. */
1068 tree idx, val;
1069 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1070 {
1071 if (!idx)
1072 break;
1073
1074 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1075
1076 tree ftype = TREE_TYPE (idx);
1077 bool ok;
1078
1079 if (TREE_CODE (ftype) == ARRAY_TYPE)
1080 ok = can_convert_array (atype: ftype, from: val, flags, complain);
1081 else
1082 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1083 complain);
1084
1085 if (!ok)
1086 return NULL;
1087
1088 /* For unions, there should be just one initializer. */
1089 if (TREE_CODE (type) == UNION_TYPE)
1090 {
1091 field = NULL_TREE;
1092 i = 1;
1093 break;
1094 }
1095 pset.add (k: idx);
1096 }
1097
1098 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1099 {
1100 tree ftype = TREE_TYPE (field);
1101 bool ok;
1102
1103 if (!pset.is_empty () && field_in_pset (pset, field))
1104 continue;
1105 if (i < CONSTRUCTOR_NELTS (ctor))
1106 {
1107 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1108 gcc_checking_assert (!ce->index);
1109 val = ce->value;
1110 ++i;
1111 }
1112 else if (DECL_INITIAL (field))
1113 val = get_nsdmi (field, /*ctor*/false, complain);
1114 else if (TYPE_REF_P (ftype))
1115 /* Value-initialization of reference is ill-formed. */
1116 return NULL;
1117 else
1118 {
1119 if (empty_ctor == NULL_TREE)
1120 empty_ctor = build_constructor (init_list_type_node, NULL);
1121 val = empty_ctor;
1122 }
1123
1124 if (TREE_CODE (ftype) == ARRAY_TYPE)
1125 ok = can_convert_array (atype: ftype, from: val, flags, complain);
1126 else
1127 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1128 complain);
1129
1130 if (!ok)
1131 return NULL;
1132
1133 if (TREE_CODE (type) == UNION_TYPE)
1134 break;
1135 }
1136
1137 if (i < CONSTRUCTOR_NELTS (ctor))
1138 return NULL;
1139
1140 c = alloc_conversion (kind: ck_aggr);
1141 c->type = type;
1142 c->rank = cr_exact;
1143 c->user_conv_p = true;
1144 c->check_narrowing = true;
1145 c->u.expr = ctor;
1146 return c;
1147}
1148
1149/* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1150 array type, if such a conversion is possible. */
1151
1152static conversion *
1153build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1154{
1155 conversion *c;
1156 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1157 tree elttype = TREE_TYPE (type);
1158 bool bad = false;
1159 bool user = false;
1160 enum conversion_rank rank = cr_exact;
1161
1162 /* We might need to propagate the size from the element to the array. */
1163 complete_type (type);
1164
1165 if (TYPE_DOMAIN (type)
1166 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1167 {
1168 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1169 if (alen < len)
1170 return NULL;
1171 }
1172
1173 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1174
1175 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1176 {
1177 conversion *sub
1178 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1179 false, flags, complain);
1180 if (sub == NULL)
1181 return NULL;
1182
1183 if (sub->rank > rank)
1184 rank = sub->rank;
1185 if (sub->user_conv_p)
1186 user = true;
1187 if (sub->bad_p)
1188 bad = true;
1189 }
1190
1191 c = alloc_conversion (kind: ck_aggr);
1192 c->type = type;
1193 c->rank = rank;
1194 c->user_conv_p = user;
1195 c->bad_p = bad;
1196 c->u.expr = ctor;
1197 return c;
1198}
1199
1200/* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1201 complex type, if such a conversion is possible. */
1202
1203static conversion *
1204build_complex_conv (tree type, tree ctor, int flags,
1205 tsubst_flags_t complain)
1206{
1207 conversion *c;
1208 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1209 tree elttype = TREE_TYPE (type);
1210 bool bad = false;
1211 bool user = false;
1212 enum conversion_rank rank = cr_exact;
1213
1214 if (len != 2)
1215 return NULL;
1216
1217 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1218
1219 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1220 {
1221 conversion *sub
1222 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1223 false, flags, complain);
1224 if (sub == NULL)
1225 return NULL;
1226
1227 if (sub->rank > rank)
1228 rank = sub->rank;
1229 if (sub->user_conv_p)
1230 user = true;
1231 if (sub->bad_p)
1232 bad = true;
1233 }
1234
1235 c = alloc_conversion (kind: ck_aggr);
1236 c->type = type;
1237 c->rank = rank;
1238 c->user_conv_p = user;
1239 c->bad_p = bad;
1240 c->u.expr = ctor;
1241 return c;
1242}
1243
1244/* Build a representation of the identity conversion from EXPR to
1245 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1246
1247static conversion *
1248build_identity_conv (tree type, tree expr)
1249{
1250 conversion *c;
1251
1252 c = alloc_conversion (kind: ck_identity);
1253 c->type = type;
1254 c->u.expr = expr;
1255
1256 return c;
1257}
1258
1259/* Converting from EXPR to TYPE was ambiguous in the sense that there
1260 were multiple user-defined conversions to accomplish the job.
1261 Build a conversion that indicates that ambiguity. */
1262
1263static conversion *
1264build_ambiguous_conv (tree type, tree expr)
1265{
1266 conversion *c;
1267
1268 c = alloc_conversion (kind: ck_ambig);
1269 c->type = type;
1270 c->u.expr = expr;
1271
1272 return c;
1273}
1274
1275tree
1276strip_top_quals (tree t)
1277{
1278 if (TREE_CODE (t) == ARRAY_TYPE)
1279 return t;
1280 return cp_build_qualified_type (t, 0);
1281}
1282
1283/* Returns the standard conversion path (see [conv]) from type FROM to type
1284 TO, if any. For proper handling of null pointer constants, you must
1285 also pass the expression EXPR to convert from. If C_CAST_P is true,
1286 this conversion is coming from a C-style cast. */
1287
1288static conversion *
1289standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1290 int flags, tsubst_flags_t complain)
1291{
1292 enum tree_code fcode, tcode;
1293 conversion *conv;
1294 bool fromref = false;
1295 tree qualified_to;
1296
1297 to = non_reference (to);
1298 if (TYPE_REF_P (from))
1299 {
1300 fromref = true;
1301 from = TREE_TYPE (from);
1302 }
1303 qualified_to = to;
1304 to = strip_top_quals (t: to);
1305 from = strip_top_quals (t: from);
1306
1307 if (expr && type_unknown_p (expr))
1308 {
1309 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1310 {
1311 tsubst_flags_t tflags = tf_conv;
1312 expr = instantiate_type (to, expr, tflags);
1313 if (expr == error_mark_node)
1314 return NULL;
1315 from = TREE_TYPE (expr);
1316 }
1317 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1318 {
1319 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1320 expr = resolve_nondeduced_context (expr, complain);
1321 from = TREE_TYPE (expr);
1322 }
1323 }
1324
1325 fcode = TREE_CODE (from);
1326 tcode = TREE_CODE (to);
1327
1328 conv = build_identity_conv (type: from, expr);
1329 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1330 {
1331 from = type_decays_to (from);
1332 fcode = TREE_CODE (from);
1333 /* Tell convert_like that we're using the address. */
1334 conv->rvaluedness_matches_p = true;
1335 conv = build_conv (code: ck_lvalue, type: from, from: conv);
1336 }
1337 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1338 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1339 express the copy constructor call required by copy-initialization. */
1340 else if (fromref || (expr && obvalue_p (expr)))
1341 {
1342 if (expr)
1343 {
1344 tree bitfield_type;
1345 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1346 if (bitfield_type)
1347 {
1348 from = strip_top_quals (t: bitfield_type);
1349 fcode = TREE_CODE (from);
1350 }
1351 }
1352 conv = build_conv (code: ck_rvalue, type: from, from: conv);
1353 /* If we're performing copy-initialization, remember to skip
1354 explicit constructors. */
1355 if (flags & LOOKUP_ONLYCONVERTING)
1356 conv->copy_init_p = true;
1357 }
1358
1359 /* Allow conversion between `__complex__' data types. */
1360 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1361 {
1362 /* The standard conversion sequence to convert FROM to TO is
1363 the standard conversion sequence to perform componentwise
1364 conversion. */
1365 conversion *part_conv = standard_conversion
1366 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1367 complain);
1368
1369 if (!part_conv)
1370 conv = NULL;
1371 else if (part_conv->kind == ck_identity)
1372 /* Leave conv alone. */;
1373 else
1374 {
1375 conv = build_conv (code: part_conv->kind, type: to, from: conv);
1376 conv->rank = part_conv->rank;
1377 }
1378
1379 return conv;
1380 }
1381
1382 if (same_type_p (from, to))
1383 {
1384 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1385 conv->type = qualified_to;
1386 else if (from != to)
1387 /* Use TO in order to not lose TO in diagnostics. */
1388 conv->type = to;
1389 return conv;
1390 }
1391
1392 /* [conv.ptr]
1393 A null pointer constant can be converted to a pointer type; ... A
1394 null pointer constant of integral type can be converted to an
1395 rvalue of type std::nullptr_t. */
1396 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1397 || NULLPTR_TYPE_P (to))
1398 && ((expr && null_ptr_cst_p (t: expr))
1399 || NULLPTR_TYPE_P (from)))
1400 conv = build_conv (code: ck_std, type: to, from: conv);
1401 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1402 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1403 {
1404 /* For backwards brain damage compatibility, allow interconversion of
1405 pointers and integers with a pedwarn. */
1406 conv = build_conv (code: ck_std, type: to, from: conv);
1407 conv->bad_p = true;
1408 }
1409 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1410 {
1411 /* For backwards brain damage compatibility, allow interconversion of
1412 enums and integers with a pedwarn. */
1413 conv = build_conv (code: ck_std, type: to, from: conv);
1414 conv->bad_p = true;
1415 }
1416 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1417 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1418 {
1419 tree to_pointee;
1420 tree from_pointee;
1421
1422 if (tcode == POINTER_TYPE)
1423 {
1424 to_pointee = TREE_TYPE (to);
1425 from_pointee = TREE_TYPE (from);
1426
1427 /* Since this is the target of a pointer, it can't have function
1428 qualifiers, so any TYPE_QUALS must be for attributes const or
1429 noreturn. Strip them. */
1430 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1431 && TYPE_QUALS (to_pointee))
1432 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1433 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1434 && TYPE_QUALS (from_pointee))
1435 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1436 }
1437 else
1438 {
1439 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1440 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1441 }
1442
1443 if (tcode == POINTER_TYPE
1444 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1445 to_pointee))
1446 ;
1447 else if (VOID_TYPE_P (to_pointee)
1448 && !TYPE_PTRDATAMEM_P (from)
1449 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1450 {
1451 tree nfrom = TREE_TYPE (from);
1452 /* Don't try to apply restrict to void. */
1453 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1454 from_pointee = cp_build_qualified_type (void_type_node, quals);
1455 from = build_pointer_type (from_pointee);
1456 conv = build_conv (code: ck_ptr, type: from, from: conv);
1457 }
1458 else if (TYPE_PTRDATAMEM_P (from))
1459 {
1460 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1461 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1462
1463 if (same_type_p (fbase, tbase))
1464 /* No base conversion needed. */;
1465 else if (DERIVED_FROM_P (fbase, tbase)
1466 && (same_type_ignoring_top_level_qualifiers_p
1467 (from_pointee, to_pointee)))
1468 {
1469 from = build_ptrmem_type (tbase, from_pointee);
1470 conv = build_conv (code: ck_pmem, type: from, from: conv);
1471 }
1472 else
1473 return NULL;
1474 }
1475 else if (CLASS_TYPE_P (from_pointee)
1476 && CLASS_TYPE_P (to_pointee)
1477 /* [conv.ptr]
1478
1479 An rvalue of type "pointer to cv D," where D is a
1480 class type, can be converted to an rvalue of type
1481 "pointer to cv B," where B is a base class (clause
1482 _class.derived_) of D. If B is an inaccessible
1483 (clause _class.access_) or ambiguous
1484 (_class.member.lookup_) base class of D, a program
1485 that necessitates this conversion is ill-formed.
1486 Therefore, we use DERIVED_FROM_P, and do not check
1487 access or uniqueness. */
1488 && DERIVED_FROM_P (to_pointee, from_pointee))
1489 {
1490 from_pointee
1491 = cp_build_qualified_type (to_pointee,
1492 cp_type_quals (from_pointee));
1493 from = build_pointer_type (from_pointee);
1494 conv = build_conv (code: ck_ptr, type: from, from: conv);
1495 conv->base_p = true;
1496 }
1497
1498 if (same_type_p (from, to))
1499 /* OK */;
1500 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1501 /* In a C-style cast, we ignore CV-qualification because we
1502 are allowed to perform a static_cast followed by a
1503 const_cast. */
1504 conv = build_conv (code: ck_qual, type: to, from: conv);
1505 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1506 conv = build_conv (code: ck_qual, type: to, from: conv);
1507 else if (expr && string_conv_p (to, expr, 0))
1508 /* converting from string constant to char *. */
1509 conv = build_conv (code: ck_qual, type: to, from: conv);
1510 else if (fnptr_conv_p (to, from))
1511 conv = build_conv (code: ck_fnptr, type: to, from: conv);
1512 /* Allow conversions among compatible ObjC pointer types (base
1513 conversions have been already handled above). */
1514 else if (c_dialect_objc ()
1515 && objc_compare_types (to, from, -4, NULL_TREE))
1516 conv = build_conv (code: ck_ptr, type: to, from: conv);
1517 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1518 {
1519 conv = build_conv (code: ck_ptr, type: to, from: conv);
1520 conv->bad_p = true;
1521 }
1522 else
1523 return NULL;
1524
1525 from = to;
1526 }
1527 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1528 {
1529 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1530 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1531 tree fbase = class_of_this_parm (fntype: fromfn);
1532 tree tbase = class_of_this_parm (fntype: tofn);
1533
1534 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1535 yields false. But a pointer to member of incomplete class is OK. */
1536 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1537 return NULL;
1538
1539 tree fstat = static_fn_type (fromfn);
1540 tree tstat = static_fn_type (tofn);
1541 if (same_type_p (tstat, fstat)
1542 || fnptr_conv_p (tstat, fstat))
1543 /* OK */;
1544 else
1545 return NULL;
1546
1547 if (!same_type_p (fbase, tbase))
1548 {
1549 from = build_memfn_type (fstat,
1550 tbase,
1551 cp_type_quals (tbase),
1552 type_memfn_rqual (tofn));
1553 from = build_ptrmemfunc_type (build_pointer_type (from));
1554 conv = build_conv (code: ck_pmem, type: from, from: conv);
1555 conv->base_p = true;
1556 }
1557 if (fnptr_conv_p (tstat, fstat))
1558 conv = build_conv (code: ck_fnptr, type: to, from: conv);
1559 }
1560 else if (tcode == BOOLEAN_TYPE)
1561 {
1562 /* [conv.bool]
1563
1564 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1565 to member type can be converted to a prvalue of type bool. ...
1566 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1567 std::nullptr_t can be converted to a prvalue of type bool; */
1568 if (ARITHMETIC_TYPE_P (from)
1569 || UNSCOPED_ENUM_P (from)
1570 || fcode == POINTER_TYPE
1571 || TYPE_PTRMEM_P (from)
1572 || NULLPTR_TYPE_P (from))
1573 {
1574 conv = build_conv (code: ck_std, type: to, from: conv);
1575 if (fcode == POINTER_TYPE
1576 || TYPE_PTRDATAMEM_P (from)
1577 || (TYPE_PTRMEMFUNC_P (from)
1578 && conv->rank < cr_pbool)
1579 || NULLPTR_TYPE_P (from))
1580 conv->rank = cr_pbool;
1581 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1582 conv->bad_p = true;
1583 if (flags & LOOKUP_NO_NARROWING)
1584 conv->check_narrowing = true;
1585 return conv;
1586 }
1587
1588 return NULL;
1589 }
1590 /* We don't check for ENUMERAL_TYPE here because there are no standard
1591 conversions to enum type. */
1592 /* As an extension, allow conversion to complex type. */
1593 else if (ARITHMETIC_TYPE_P (to))
1594 {
1595 if (! (INTEGRAL_CODE_P (fcode)
1596 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1597 || SCOPED_ENUM_P (from))
1598 return NULL;
1599
1600 /* If we're parsing an enum with no fixed underlying type, we're
1601 dealing with an incomplete type, which renders the conversion
1602 ill-formed. */
1603 if (!COMPLETE_TYPE_P (from))
1604 return NULL;
1605
1606 conv = build_conv (code: ck_std, type: to, from: conv);
1607
1608 tree underlying_type = NULL_TREE;
1609 if (TREE_CODE (from) == ENUMERAL_TYPE
1610 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1611 underlying_type = ENUM_UNDERLYING_TYPE (from);
1612
1613 /* Give this a better rank if it's a promotion.
1614
1615 To handle CWG 1601, also bump the rank if we are converting
1616 an enumeration with a fixed underlying type to the underlying
1617 type. */
1618 if ((same_type_p (to, type_promotes_to (from))
1619 || (underlying_type && same_type_p (to, underlying_type)))
1620 && next_conversion (conv)->rank <= cr_promotion)
1621 conv->rank = cr_promotion;
1622
1623 /* A prvalue of floating-point type can be converted to a prvalue of
1624 another floating-point type with a greater or equal conversion
1625 rank ([conv.rank]). A prvalue of standard floating-point type can
1626 be converted to a prvalue of another standard floating-point type.
1627 For backwards compatibility with handling __float128 and other
1628 non-standard floating point types, allow all implicit floating
1629 point conversions if neither type is extended floating-point
1630 type and if at least one of them is, fail if they have unordered
1631 conversion rank or from has higher conversion rank. */
1632 if (fcode == REAL_TYPE
1633 && tcode == REAL_TYPE
1634 && (extended_float_type_p (type: from)
1635 || extended_float_type_p (type: to))
1636 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1637 conv->bad_p = true;
1638 }
1639 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1640 && vector_types_convertible_p (t1: from, t2: to, emit_lax_note: false))
1641 return build_conv (code: ck_std, type: to, from: conv);
1642 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1643 && is_properly_derived_from (from, to))
1644 {
1645 if (conv->kind == ck_rvalue)
1646 conv = next_conversion (conv);
1647 conv = build_conv (code: ck_base, type: to, from: conv);
1648 /* The derived-to-base conversion indicates the initialization
1649 of a parameter with base type from an object of a derived
1650 type. A temporary object is created to hold the result of
1651 the conversion unless we're binding directly to a reference. */
1652 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1653 /* If we're performing copy-initialization, remember to skip
1654 explicit constructors. */
1655 if (flags & LOOKUP_ONLYCONVERTING)
1656 conv->copy_init_p = true;
1657 }
1658 else
1659 return NULL;
1660
1661 if (flags & LOOKUP_NO_NARROWING)
1662 conv->check_narrowing = true;
1663
1664 return conv;
1665}
1666
1667/* Returns nonzero if T1 is reference-related to T2.
1668
1669 This is considered when a reference to T1 is initialized by a T2. */
1670
1671bool
1672reference_related_p (tree t1, tree t2)
1673{
1674 if (t1 == error_mark_node || t2 == error_mark_node)
1675 return false;
1676
1677 t1 = TYPE_MAIN_VARIANT (t1);
1678 t2 = TYPE_MAIN_VARIANT (t2);
1679
1680 /* [dcl.init.ref]
1681
1682 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1683 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1684 return (similar_type_p (t1, t2)
1685 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1686 && DERIVED_FROM_P (t1, t2)));
1687}
1688
1689/* Returns nonzero if T1 is reference-compatible with T2. */
1690
1691bool
1692reference_compatible_p (tree t1, tree t2)
1693{
1694 /* [dcl.init.ref]
1695
1696 "cv1 T1" is reference compatible with "cv2 T2" if
1697 a prvalue of type "pointer to cv2 T2" can be converted to the type
1698 "pointer to cv1 T1" via a standard conversion sequence. */
1699 tree ptype1 = build_pointer_type (t1);
1700 tree ptype2 = build_pointer_type (t2);
1701 conversion *conv = standard_conversion (to: ptype1, from: ptype2, NULL_TREE,
1702 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1703 if (!conv || conv->bad_p)
1704 return false;
1705 return true;
1706}
1707
1708/* Return true if converting FROM to TO would involve a qualification
1709 conversion. */
1710
1711static bool
1712involves_qualification_conversion_p (tree to, tree from)
1713{
1714 /* If we're not convering a pointer to another one, we won't get
1715 a qualification conversion. */
1716 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1717 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1718 return false;
1719
1720 conversion *conv = standard_conversion (to, from, NULL_TREE,
1721 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1722 for (conversion *t = conv; t; t = next_conversion (conv: t))
1723 if (t->kind == ck_qual)
1724 return true;
1725
1726 return false;
1727}
1728
1729/* Return true if HANDLER is a match for exception object with EXCEPT_TYPE as
1730 per [except.handle]/3. */
1731
1732bool
1733handler_match_for_exception_type (tree handler, tree except_type)
1734{
1735 tree handler_type = HANDLER_TYPE (handler);
1736 if (handler_type == NULL_TREE)
1737 return true; /* ... */
1738 if (same_type_ignoring_top_level_qualifiers_p (handler_type, except_type))
1739 return true;
1740 if (CLASS_TYPE_P (except_type) && CLASS_TYPE_P (handler_type))
1741 {
1742 base_kind b_kind;
1743 tree binfo = lookup_base (except_type, handler_type, ba_check, &b_kind,
1744 tf_none);
1745 if (binfo && binfo != error_mark_node)
1746 return true;
1747 }
1748 if (TYPE_PTR_P (handler_type) || TYPE_PTRDATAMEM_P (handler_type))
1749 {
1750 if (TREE_CODE (except_type) == NULLPTR_TYPE)
1751 return true;
1752 if ((TYPE_PTR_P (handler_type) && TYPE_PTR_P (except_type))
1753 || (TYPE_PTRDATAMEM_P (handler_type)
1754 && TYPE_PTRDATAMEM_P (except_type)))
1755 {
1756 conversion *conv
1757 = standard_conversion (to: handler_type, from: except_type, NULL_TREE,
1758 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1759 if (conv && !conv->bad_p)
1760 {
1761 for (conversion *t = conv; t; t = next_conversion (conv: t))
1762 switch (t->kind)
1763 {
1764 case ck_ptr:
1765 case ck_fnptr:
1766 case ck_qual:
1767 case ck_identity:
1768 break;
1769 default:
1770 return false;
1771 }
1772 return true;
1773 }
1774 }
1775 }
1776 return false;
1777}
1778
1779/* A reference of the indicated TYPE is being bound directly to the
1780 expression represented by the implicit conversion sequence CONV.
1781 Return a conversion sequence for this binding. */
1782
1783static conversion *
1784direct_reference_binding (tree type, conversion *conv)
1785{
1786 tree t;
1787
1788 gcc_assert (TYPE_REF_P (type));
1789 gcc_assert (!TYPE_REF_P (conv->type));
1790
1791 t = TREE_TYPE (type);
1792
1793 if (conv->kind == ck_identity)
1794 /* Mark the identity conv as to not decay to rvalue. */
1795 conv->rvaluedness_matches_p = true;
1796
1797 /* [over.ics.rank]
1798
1799 When a parameter of reference type binds directly
1800 (_dcl.init.ref_) to an argument expression, the implicit
1801 conversion sequence is the identity conversion, unless the
1802 argument expression has a type that is a derived class of the
1803 parameter type, in which case the implicit conversion sequence is
1804 a derived-to-base Conversion.
1805
1806 If the parameter binds directly to the result of applying a
1807 conversion function to the argument expression, the implicit
1808 conversion sequence is a user-defined conversion sequence
1809 (_over.ics.user_), with the second standard conversion sequence
1810 either an identity conversion or, if the conversion function
1811 returns an entity of a type that is a derived class of the
1812 parameter type, a derived-to-base conversion. */
1813 if (is_properly_derived_from (conv->type, t))
1814 {
1815 /* Represent the derived-to-base conversion. */
1816 conv = build_conv (code: ck_base, type: t, from: conv);
1817 /* We will actually be binding to the base-class subobject in
1818 the derived class, so we mark this conversion appropriately.
1819 That way, convert_like knows not to generate a temporary. */
1820 conv->need_temporary_p = false;
1821 }
1822 else if (involves_qualification_conversion_p (to: t, from: conv->type))
1823 /* Represent the qualification conversion. After DR 2352
1824 #1 and #2 were indistinguishable conversion sequences:
1825
1826 void f(int*); // #1
1827 void f(const int* const &); // #2
1828 void g(int* p) { f(p); }
1829
1830 because the types "int *" and "const int *const" are
1831 reference-related and we were binding both directly and they
1832 had the same rank. To break it up, we add a ck_qual under the
1833 ck_ref_bind so that conversion sequence ranking chooses #1.
1834
1835 We strip_top_quals here which is also what standard_conversion
1836 does. Failure to do so would confuse comp_cv_qual_signature
1837 into thinking that in
1838
1839 void f(const int * const &); // #1
1840 void f(const int *); // #2
1841 int *x;
1842 f(x);
1843
1844 #2 is a better match than #1 even though they're ambiguous (97296). */
1845 conv = build_conv (code: ck_qual, type: strip_top_quals (t), from: conv);
1846
1847 return build_conv (code: ck_ref_bind, type, from: conv);
1848}
1849
1850/* Returns the conversion path from type FROM to reference type TO for
1851 purposes of reference binding. For lvalue binding, either pass a
1852 reference type to FROM or an lvalue expression to EXPR. If the
1853 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1854 the conversion returned. If C_CAST_P is true, this
1855 conversion is coming from a C-style cast. */
1856
1857static conversion *
1858reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1859 tsubst_flags_t complain)
1860{
1861 conversion *conv = NULL;
1862 conversion *bad_direct_conv = nullptr;
1863 tree to = TREE_TYPE (rto);
1864 tree from = rfrom;
1865 tree tfrom;
1866 bool related_p;
1867 bool compatible_p;
1868 cp_lvalue_kind gl_kind;
1869 bool is_lvalue;
1870
1871 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1872 {
1873 expr = instantiate_type (to, expr, tf_none);
1874 if (expr == error_mark_node)
1875 return NULL;
1876 from = TREE_TYPE (expr);
1877 }
1878
1879 bool copy_list_init = false;
1880 bool single_list_conv = false;
1881 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1882 {
1883 maybe_warn_cpp0x (str: CPP0X_INITIALIZER_LISTS);
1884 /* DR 1288: Otherwise, if the initializer list has a single element
1885 of type E and ... [T's] referenced type is reference-related to E,
1886 the object or reference is initialized from that element...
1887
1888 ??? With P0388R4, we should bind 't' directly to U{}:
1889 using U = A[2];
1890 A (&&t)[] = {U{}};
1891 because A[] and A[2] are reference-related. But we don't do it
1892 because grok_reference_init has deduced the array size (to 1), and
1893 A[1] and A[2] aren't reference-related. */
1894 if (CONSTRUCTOR_NELTS (expr) == 1
1895 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1896 {
1897 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1898 if (error_operand_p (t: elt))
1899 return NULL;
1900 tree etype = TREE_TYPE (elt);
1901 if (reference_related_p (t1: to, t2: etype))
1902 {
1903 expr = elt;
1904 from = etype;
1905 goto skip;
1906 }
1907 else if (CLASS_TYPE_P (etype) && TYPE_HAS_CONVERSION (etype))
1908 /* CWG1996: jason's proposed drafting adds "or initializing T from E
1909 would bind directly". We check that in the direct binding with
1910 conversion code below. */
1911 single_list_conv = true;
1912 }
1913 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1914 referenced by T is copy-list-initialized, and the reference is bound
1915 to that temporary. */
1916 copy_list_init = true;
1917 skip:;
1918 }
1919
1920 if (TYPE_REF_P (from))
1921 {
1922 from = TREE_TYPE (from);
1923 if (!TYPE_REF_IS_RVALUE (rfrom)
1924 || TREE_CODE (from) == FUNCTION_TYPE)
1925 gl_kind = clk_ordinary;
1926 else
1927 gl_kind = clk_rvalueref;
1928 }
1929 else if (expr)
1930 gl_kind = lvalue_kind (expr);
1931 else if (CLASS_TYPE_P (from)
1932 || TREE_CODE (from) == ARRAY_TYPE)
1933 gl_kind = clk_class;
1934 else
1935 gl_kind = clk_none;
1936
1937 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1938 if ((flags & LOOKUP_NO_TEMP_BIND)
1939 && (gl_kind & clk_class))
1940 gl_kind = clk_none;
1941
1942 /* Same mask as real_lvalue_p. */
1943 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1944
1945 tfrom = from;
1946 if ((gl_kind & clk_bitfield) != 0)
1947 tfrom = unlowered_expr_type (expr);
1948
1949 /* Figure out whether or not the types are reference-related and
1950 reference compatible. We have to do this after stripping
1951 references from FROM. */
1952 related_p = reference_related_p (t1: to, t2: tfrom);
1953 /* If this is a C cast, first convert to an appropriately qualified
1954 type, so that we can later do a const_cast to the desired type. */
1955 if (related_p && c_cast_p
1956 && !at_least_as_qualified_p (to, tfrom))
1957 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1958 compatible_p = reference_compatible_p (t1: to, t2: tfrom);
1959
1960 /* Directly bind reference when target expression's type is compatible with
1961 the reference and expression is an lvalue. In DR391, the wording in
1962 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1963 const and rvalue references to rvalues of compatible class type.
1964 We should also do direct bindings for non-class xvalues. */
1965 if ((related_p || compatible_p) && gl_kind)
1966 {
1967 /* [dcl.init.ref]
1968
1969 If the initializer expression
1970
1971 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1972 is reference-compatible with "cv2 T2,"
1973
1974 the reference is bound directly to the initializer expression
1975 lvalue.
1976
1977 [...]
1978 If the initializer expression is an rvalue, with T2 a class type,
1979 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1980 is bound to the object represented by the rvalue or to a sub-object
1981 within that object. */
1982
1983 conv = build_identity_conv (type: tfrom, expr);
1984 conv = direct_reference_binding (type: rto, conv);
1985
1986 if (TYPE_REF_P (rfrom))
1987 /* Handle rvalue reference to function properly. */
1988 conv->rvaluedness_matches_p
1989 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1990 else
1991 conv->rvaluedness_matches_p
1992 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1993
1994 if ((gl_kind & clk_bitfield) != 0
1995 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1996 /* For the purposes of overload resolution, we ignore the fact
1997 this expression is a bitfield or packed field. (In particular,
1998 [over.ics.ref] says specifically that a function with a
1999 non-const reference parameter is viable even if the
2000 argument is a bitfield.)
2001
2002 However, when we actually call the function we must create
2003 a temporary to which to bind the reference. If the
2004 reference is volatile, or isn't const, then we cannot make
2005 a temporary, so we just issue an error when the conversion
2006 actually occurs. */
2007 conv->need_temporary_p = true;
2008
2009 /* Don't allow binding of lvalues (other than function lvalues) to
2010 rvalue references. */
2011 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
2012 && TREE_CODE (to) != FUNCTION_TYPE)
2013 conv->bad_p = true;
2014
2015 /* Nor the reverse. */
2016 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
2017 /* Unless it's really a C++20 lvalue being treated as an xvalue.
2018 But in C++23, such an expression is just an xvalue, not a special
2019 lvalue, so the binding is once again ill-formed. */
2020 && !(cxx_dialect <= cxx20
2021 && (gl_kind & clk_implicit_rval))
2022 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
2023 || (flags & LOOKUP_NO_RVAL_BIND))
2024 && TREE_CODE (to) != FUNCTION_TYPE)
2025 conv->bad_p = true;
2026
2027 if (!compatible_p)
2028 conv->bad_p = true;
2029
2030 return conv;
2031 }
2032 /* [class.conv.fct] A conversion function is never used to convert a
2033 (possibly cv-qualified) object to the (possibly cv-qualified) same
2034 object type (or a reference to it), to a (possibly cv-qualified) base
2035 class of that type (or a reference to it).... */
2036 else if (!related_p
2037 && !(flags & LOOKUP_NO_CONVERSION)
2038 && (CLASS_TYPE_P (from) || single_list_conv))
2039 {
2040 tree rexpr = expr;
2041 if (single_list_conv)
2042 rexpr = CONSTRUCTOR_ELT (expr, 0)->value;
2043
2044 /* [dcl.init.ref]
2045
2046 If the initializer expression
2047
2048 -- has a class type (i.e., T2 is a class type) can be
2049 implicitly converted to an lvalue of type "cv3 T3," where
2050 "cv1 T1" is reference-compatible with "cv3 T3". (this
2051 conversion is selected by enumerating the applicable
2052 conversion functions (_over.match.ref_) and choosing the
2053 best one through overload resolution. (_over.match_).
2054
2055 the reference is bound to the lvalue result of the conversion
2056 in the second case. */
2057 z_candidate *cand = build_user_type_conversion_1 (rto, rexpr, flags,
2058 complain);
2059 if (cand)
2060 {
2061 if (!cand->second_conv->bad_p)
2062 return cand->second_conv;
2063
2064 /* Direct reference binding wasn't successful and yielded a bad
2065 conversion. Proceed with trying to go through a temporary
2066 instead, and if that also fails then we'll return this bad
2067 conversion rather than no conversion for sake of better
2068 diagnostics. */
2069 bad_direct_conv = cand->second_conv;
2070 }
2071 }
2072
2073 /* From this point on, we conceptually need temporaries, even if we
2074 elide them. Only the cases above are "direct bindings". */
2075 if (flags & LOOKUP_NO_TEMP_BIND)
2076 return bad_direct_conv ? bad_direct_conv : nullptr;
2077
2078 /* [over.ics.rank]
2079
2080 When a parameter of reference type is not bound directly to an
2081 argument expression, the conversion sequence is the one required
2082 to convert the argument expression to the underlying type of the
2083 reference according to _over.best.ics_. Conceptually, this
2084 conversion sequence corresponds to copy-initializing a temporary
2085 of the underlying type with the argument expression. Any
2086 difference in top-level cv-qualification is subsumed by the
2087 initialization itself and does not constitute a conversion. */
2088
2089 bool maybe_valid_p = true;
2090
2091 /* [dcl.init.ref]
2092
2093 Otherwise, the reference shall be an lvalue reference to a
2094 non-volatile const type, or the reference shall be an rvalue
2095 reference. */
2096 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
2097 maybe_valid_p = false;
2098
2099 /* [dcl.init.ref]
2100
2101 Otherwise, a temporary of type "cv1 T1" is created and
2102 initialized from the initializer expression using the rules for a
2103 non-reference copy initialization. If T1 is reference-related to
2104 T2, cv1 must be the same cv-qualification as, or greater
2105 cv-qualification than, cv2; otherwise, the program is ill-formed. */
2106 if (related_p && !at_least_as_qualified_p (to, from))
2107 maybe_valid_p = false;
2108
2109 /* We try below to treat an invalid reference binding as a bad conversion
2110 to improve diagnostics, but doing so may cause otherwise unnecessary
2111 instantiations that can lead to a hard error. So during the first pass
2112 of overload resolution wherein we shortcut bad conversions, instead just
2113 produce a special conversion indicating a second pass is necessary if
2114 there's no strictly viable candidate. */
2115 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
2116 {
2117 if (bad_direct_conv)
2118 return bad_direct_conv;
2119
2120 conv = alloc_conversion (kind: ck_deferred_bad);
2121 conv->bad_p = true;
2122 return conv;
2123 }
2124
2125 /* We're generating a temporary now, but don't bind any more in the
2126 conversion (specifically, don't slice the temporary returned by a
2127 conversion operator). */
2128 flags |= LOOKUP_NO_TEMP_BIND;
2129
2130 /* Core issue 899: When [copy-]initializing a temporary to be bound
2131 to the first parameter of a copy constructor (12.8) called with
2132 a single argument in the context of direct-initialization,
2133 explicit conversion functions are also considered.
2134
2135 So don't set LOOKUP_ONLYCONVERTING in that case. */
2136 if (!(flags & LOOKUP_COPY_PARM))
2137 flags |= LOOKUP_ONLYCONVERTING;
2138
2139 if (!conv)
2140 conv = implicit_conversion (to, from, expr, c_cast_p,
2141 flags, complain);
2142 if (!conv)
2143 return bad_direct_conv ? bad_direct_conv : nullptr;
2144
2145 if (conv->user_conv_p)
2146 {
2147 if (copy_list_init)
2148 /* Remember this was copy-list-initialization. */
2149 conv->need_temporary_p = true;
2150
2151 /* If initializing the temporary used a conversion function,
2152 recalculate the second conversion sequence. */
2153 for (conversion *t = conv; t; t = next_conversion (conv: t))
2154 if (t->kind == ck_user
2155 && c_cast_p && !maybe_valid_p)
2156 {
2157 if (complain & tf_warning)
2158 warning (OPT_Wcast_user_defined,
2159 "casting %qT to %qT does not use %qD",
2160 from, rto, t->cand->fn);
2161 /* Don't let recalculation try to make this valid. */
2162 break;
2163 }
2164 else if (t->kind == ck_user
2165 && DECL_CONV_FN_P (t->cand->fn))
2166 {
2167 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2168 /* A prvalue of non-class type is cv-unqualified. */
2169 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2170 ftype = cv_unqualified (ftype);
2171 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2172 conversion *new_second
2173 = reference_binding (rto, rfrom: ftype, NULL_TREE, c_cast_p,
2174 flags: sflags, complain);
2175 if (!new_second)
2176 return bad_direct_conv ? bad_direct_conv : nullptr;
2177 conv = merge_conversion_sequences (t, new_second);
2178 gcc_assert (maybe_valid_p || conv->bad_p);
2179 return conv;
2180 }
2181 }
2182
2183 conv = build_conv (code: ck_ref_bind, type: rto, from: conv);
2184 /* This reference binding, unlike those above, requires the
2185 creation of a temporary. */
2186 conv->need_temporary_p = true;
2187 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2188 conv->bad_p |= !maybe_valid_p;
2189
2190 return conv;
2191}
2192
2193/* Returns the implicit conversion sequence (see [over.ics]) from type
2194 FROM to type TO. The optional expression EXPR may affect the
2195 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2196 true, this conversion is coming from a C-style cast. */
2197
2198static conversion *
2199implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2200 int flags, tsubst_flags_t complain)
2201{
2202 conversion *conv;
2203
2204 if (from == error_mark_node || to == error_mark_node
2205 || expr == error_mark_node)
2206 return NULL;
2207
2208 /* Other flags only apply to the primary function in overload
2209 resolution, or after we've chosen one. */
2210 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2211 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2212 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2213
2214 /* FIXME: actually we don't want warnings either, but we can't just
2215 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2216 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2217 We really ought not to issue that warning until we've committed
2218 to that conversion. */
2219 complain &= ~tf_error;
2220
2221 /* Call reshape_init early to remove redundant braces. */
2222 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2223 {
2224 to = complete_type (to);
2225 if (!COMPLETE_TYPE_P (to))
2226 return nullptr;
2227 if (!CLASSTYPE_NON_AGGREGATE (to))
2228 {
2229 expr = reshape_init (to, expr, complain);
2230 if (expr == error_mark_node)
2231 return nullptr;
2232 from = TREE_TYPE (expr);
2233 }
2234 }
2235
2236 /* An argument should have gone through convert_from_reference. */
2237 gcc_checking_assert (!expr || !TYPE_REF_P (from));
2238
2239 if (TYPE_REF_P (to))
2240 conv = reference_binding (rto: to, rfrom: from, expr, c_cast_p, flags, complain);
2241 else
2242 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2243
2244 if (conv)
2245 return conv;
2246
2247 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2248 {
2249 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2250 return build_list_conv (type: to, ctor: expr, flags, complain);
2251
2252 /* As an extension, allow list-initialization of _Complex. */
2253 if (TREE_CODE (to) == COMPLEX_TYPE
2254 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2255 {
2256 conv = build_complex_conv (type: to, ctor: expr, flags, complain);
2257 if (conv)
2258 return conv;
2259 }
2260
2261 /* Allow conversion from an initializer-list with one element to a
2262 scalar type. */
2263 if (SCALAR_TYPE_P (to))
2264 {
2265 int nelts = CONSTRUCTOR_NELTS (expr);
2266 tree elt;
2267
2268 if (nelts == 0)
2269 elt = build_value_init (to, tf_none);
2270 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2271 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2272 else
2273 elt = error_mark_node;
2274
2275 conv = implicit_conversion (to, TREE_TYPE (elt), expr: elt,
2276 c_cast_p, flags, complain);
2277 if (conv)
2278 {
2279 conv->check_narrowing = true;
2280 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2281 /* Too many levels of braces, i.e. '{{1}}'. */
2282 conv->bad_p = true;
2283 return conv;
2284 }
2285 }
2286 else if (TREE_CODE (to) == ARRAY_TYPE)
2287 return build_array_conv (type: to, ctor: expr, flags, complain);
2288 }
2289
2290 if (expr != NULL_TREE
2291 && (MAYBE_CLASS_TYPE_P (from)
2292 || MAYBE_CLASS_TYPE_P (to))
2293 && (flags & LOOKUP_NO_CONVERSION) == 0)
2294 {
2295 struct z_candidate *cand;
2296
2297 if (CLASS_TYPE_P (to)
2298 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2299 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2300 return build_aggr_conv (type: to, ctor: expr, flags, complain);
2301
2302 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2303 if (cand)
2304 {
2305 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2306 && CONSTRUCTOR_NELTS (expr) == 1
2307 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2308 && !is_list_ctor (cand->fn))
2309 {
2310 /* "If C is not an initializer-list constructor and the
2311 initializer list has a single element of type cv U, where U is
2312 X or a class derived from X, the implicit conversion sequence
2313 has Exact Match rank if U is X, or Conversion rank if U is
2314 derived from X." */
2315 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2316 tree elttype = TREE_TYPE (elt);
2317 if (reference_related_p (t1: to, t2: elttype))
2318 return implicit_conversion (to, from: elttype, expr: elt,
2319 c_cast_p, flags, complain);
2320 }
2321 conv = cand->second_conv;
2322 }
2323
2324 /* We used to try to bind a reference to a temporary here, but that
2325 is now handled after the recursive call to this function at the end
2326 of reference_binding. */
2327 return conv;
2328 }
2329
2330 return NULL;
2331}
2332
2333/* Like implicit_conversion, but return NULL if the conversion is bad.
2334
2335 This is not static so that check_non_deducible_conversion can call it within
2336 add_template_candidate_real as part of overload resolution; it should not be
2337 called outside of overload resolution. */
2338
2339conversion *
2340good_conversion (tree to, tree from, tree expr,
2341 int flags, tsubst_flags_t complain)
2342{
2343 conversion *c = implicit_conversion (to, from, expr, /*cast*/c_cast_p: false,
2344 flags, complain);
2345 if (c && c->bad_p)
2346 c = NULL;
2347 return c;
2348}
2349
2350/* Add a new entry to the list of candidates. Used by the add_*_candidate
2351 functions. ARGS will not be changed until a single candidate is
2352 selected. */
2353
2354static struct z_candidate *
2355add_candidate (struct z_candidate **candidates,
2356 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2357 size_t num_convs, conversion **convs,
2358 tree access_path, tree conversion_path,
2359 int viable, struct rejection_reason *reason,
2360 int flags)
2361{
2362 struct z_candidate *cand = (struct z_candidate *)
2363 conversion_obstack_alloc (n: sizeof (struct z_candidate));
2364
2365 cand->fn = fn;
2366 cand->first_arg = first_arg;
2367 cand->args = args;
2368 cand->convs = convs;
2369 cand->num_convs = num_convs;
2370 cand->access_path = access_path;
2371 cand->conversion_path = conversion_path;
2372 cand->viable = viable;
2373 cand->reason = reason;
2374 cand->next = *candidates;
2375 cand->flags = flags;
2376 *candidates = cand;
2377
2378 if (convs && cand->reversed ())
2379 /* Swap the conversions for comparison in joust; we'll swap them back
2380 before build_over_call. */
2381 std::swap (a&: convs[0], b&: convs[1]);
2382
2383 return cand;
2384}
2385
2386/* FN is a function from the overload set that we outright didn't even
2387 consider (for some reason); add it to the list as an non-viable "ignored"
2388 candidate. */
2389
2390static z_candidate *
2391add_ignored_candidate (z_candidate **candidates, tree fn)
2392{
2393 /* No need to dynamically allocate these. */
2394 static const rejection_reason reason_ignored = { .code: rr_ignored, .u: {} };
2395
2396 struct z_candidate *cand = (struct z_candidate *)
2397 conversion_obstack_alloc (n: sizeof (struct z_candidate));
2398
2399 cand->fn = fn;
2400 cand->reason = const_cast<rejection_reason *> (&reason_ignored);
2401 cand->next = *candidates;
2402 *candidates = cand;
2403
2404 return cand;
2405}
2406
2407/* True iff CAND is a candidate added by add_ignored_candidate. */
2408
2409static bool
2410ignored_candidate_p (const z_candidate *cand)
2411{
2412 return cand->reason && cand->reason->code == rr_ignored;
2413}
2414
2415/* Return the number of remaining arguments in the parameter list
2416 beginning with ARG. */
2417
2418int
2419remaining_arguments (tree arg)
2420{
2421 int n;
2422
2423 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2424 arg = TREE_CHAIN (arg))
2425 n++;
2426
2427 return n;
2428}
2429
2430/* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2431 to the first parameter of a constructor where the parameter is of type
2432 "reference to possibly cv-qualified T" and the constructor is called with a
2433 single argument in the context of direct-initialization of an object of type
2434 "cv2 T", explicit conversion functions are also considered.
2435
2436 So set LOOKUP_COPY_PARM to let reference_binding know that
2437 it's being called in that context. */
2438
2439int
2440conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2441{
2442 int lflags = flags;
2443 tree t;
2444 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2445 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2446 && (same_type_ignoring_top_level_qualifiers_p
2447 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2448 {
2449 if (!(flags & LOOKUP_ONLYCONVERTING))
2450 lflags |= LOOKUP_COPY_PARM;
2451 if ((flags & LOOKUP_LIST_INIT_CTOR)
2452 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2453 lflags |= LOOKUP_NO_CONVERSION;
2454 }
2455 else
2456 lflags |= LOOKUP_ONLYCONVERTING;
2457
2458 return lflags;
2459}
2460
2461/* Build an appropriate 'this' conversion for the method FN and class
2462 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2463 This function modifies PARMTYPE, ARGTYPE and ARG. */
2464
2465static conversion *
2466build_this_conversion (tree fn, tree ctype,
2467 tree& parmtype, tree& argtype, tree& arg,
2468 int flags, tsubst_flags_t complain)
2469{
2470 gcc_assert (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2471 && !DECL_CONSTRUCTOR_P (fn));
2472
2473 /* The type of the implicit object parameter ('this') for
2474 overload resolution is not always the same as for the
2475 function itself; conversion functions are considered to
2476 be members of the class being converted, and functions
2477 introduced by a using-declaration are considered to be
2478 members of the class that uses them.
2479
2480 Since build_over_call ignores the ICS for the `this'
2481 parameter, we can just change the parm type. */
2482 parmtype = cp_build_qualified_type (ctype,
2483 cp_type_quals (TREE_TYPE (parmtype)));
2484 bool this_p = true;
2485 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2486 {
2487 /* If the function has a ref-qualifier, the implicit
2488 object parameter has reference type. */
2489 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2490 parmtype = cp_build_reference_type (parmtype, rv);
2491 /* The special handling of 'this' conversions in compare_ics
2492 does not apply if there is a ref-qualifier. */
2493 this_p = false;
2494 }
2495 else
2496 {
2497 parmtype = build_pointer_type (parmtype);
2498 /* We don't use build_this here because we don't want to
2499 capture the object argument until we've chosen a
2500 non-static member function. */
2501 arg = build_address (arg);
2502 argtype = lvalue_type (arg);
2503 }
2504 flags |= LOOKUP_ONLYCONVERTING;
2505 conversion *t = implicit_conversion (to: parmtype, from: argtype, expr: arg,
2506 /*c_cast_p=*/false, flags, complain);
2507 t->this_p = this_p;
2508 return t;
2509}
2510
2511/* Create an overload candidate for the function or method FN called
2512 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2513 FLAGS is passed on to implicit_conversion.
2514
2515 This does not change ARGS.
2516
2517 CTYPE, if non-NULL, is the type we want to pretend this function
2518 comes from for purposes of overload resolution.
2519
2520 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2521 If true, we stop computing conversions upon seeing the first bad
2522 conversion. This is used by add_candidates to avoid computing
2523 more conversions than necessary in the presence of a strictly viable
2524 candidate, while preserving the defacto behavior of overload resolution
2525 when it turns out there are only non-strictly viable candidates. */
2526
2527static struct z_candidate *
2528add_function_candidate (struct z_candidate **candidates,
2529 tree fn, tree ctype, tree first_arg,
2530 const vec<tree, va_gc> *args, tree access_path,
2531 tree conversion_path, int flags,
2532 conversion **convs,
2533 bool shortcut_bad_convs,
2534 tsubst_flags_t complain)
2535{
2536 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2537 int i, len;
2538 tree parmnode;
2539 tree orig_first_arg = first_arg;
2540 int skip;
2541 int viable = 1;
2542 struct rejection_reason *reason = NULL;
2543
2544 /* The `this', `in_chrg' and VTT arguments to constructors are not
2545 considered in overload resolution. */
2546 if (DECL_CONSTRUCTOR_P (fn))
2547 {
2548 if (ctor_omit_inherited_parms (fn))
2549 /* Bring back parameters omitted from an inherited ctor. */
2550 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2551 else
2552 parmlist = skip_artificial_parms_for (fn, parmlist);
2553 skip = num_artificial_parms_for (fn);
2554 if (skip > 0 && first_arg != NULL_TREE)
2555 {
2556 --skip;
2557 first_arg = NULL_TREE;
2558 }
2559 }
2560 else
2561 skip = 0;
2562
2563 len = vec_safe_length (v: args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2564 if (!convs)
2565 convs = alloc_conversions (n: len);
2566
2567 /* 13.3.2 - Viable functions [over.match.viable]
2568 First, to be a viable function, a candidate function shall have enough
2569 parameters to agree in number with the arguments in the list.
2570
2571 We need to check this first; otherwise, checking the ICSes might cause
2572 us to produce an ill-formed template instantiation. */
2573
2574 parmnode = parmlist;
2575 for (i = 0; i < len; ++i)
2576 {
2577 if (parmnode == NULL_TREE || parmnode == void_list_node)
2578 break;
2579 parmnode = TREE_CHAIN (parmnode);
2580 }
2581
2582 if ((i < len && parmnode)
2583 || !sufficient_parms_p (parmlist: parmnode))
2584 {
2585 int remaining = remaining_arguments (arg: parmnode);
2586 viable = 0;
2587 reason = arity_rejection (first_arg, expected: i + remaining, actual: len);
2588 }
2589
2590 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2591 parameter of type "reference to cv C" (including such a constructor
2592 instantiated from a template) is excluded from the set of candidate
2593 functions when used to construct an object of type D with an argument list
2594 containing a single argument if C is reference-related to D. */
2595 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2596 && flag_new_inheriting_ctors
2597 && DECL_INHERITED_CTOR (fn))
2598 {
2599 tree ptype = non_reference (TREE_VALUE (parmlist));
2600 tree dtype = DECL_CONTEXT (fn);
2601 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2602 if (reference_related_p (t1: ptype, t2: dtype)
2603 && reference_related_p (t1: btype, t2: ptype))
2604 {
2605 viable = false;
2606 reason = inherited_ctor_rejection ();
2607 }
2608 }
2609
2610 /* Second, for a function to be viable, its constraints must be
2611 satisfied. */
2612 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2613 {
2614 reason = constraint_failure ();
2615 viable = false;
2616 }
2617
2618 /* When looking for a function from a subobject from an implicit
2619 copy/move constructor/operator=, don't consider anything that takes (a
2620 reference to) an unrelated type. See c++/44909 and core 1092. */
2621 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2622 {
2623 if (DECL_CONSTRUCTOR_P (fn))
2624 i = 1;
2625 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2626 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2627 i = 2;
2628 else
2629 i = 0;
2630 if (i && len == i)
2631 {
2632 parmnode = chain_index (i-1, parmlist);
2633 if (!reference_related_p (t1: non_reference (TREE_VALUE (parmnode)),
2634 t2: ctype))
2635 viable = 0;
2636 }
2637
2638 /* This only applies at the top level. */
2639 flags &= ~LOOKUP_DEFAULTED;
2640 }
2641
2642 if (! viable)
2643 goto out;
2644
2645 if (shortcut_bad_convs)
2646 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2647 else
2648 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2649
2650 /* Third, for F to be a viable function, there shall exist for each
2651 argument an implicit conversion sequence that converts that argument
2652 to the corresponding parameter of F. */
2653
2654 parmnode = parmlist;
2655
2656 for (i = 0; i < len; ++i)
2657 {
2658 tree argtype, to_type;
2659 tree arg;
2660
2661 if (parmnode == void_list_node)
2662 break;
2663
2664 if (convs[i])
2665 {
2666 /* Already set during deduction. */
2667 parmnode = TREE_CHAIN (parmnode);
2668 continue;
2669 }
2670
2671 if (i == 0 && first_arg != NULL_TREE)
2672 arg = first_arg;
2673 else
2674 arg = const_cast<tree> (
2675 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2676 argtype = lvalue_type (arg);
2677
2678 conversion *t;
2679 if (parmnode)
2680 {
2681 tree parmtype = TREE_VALUE (parmnode);
2682 if (i == 0
2683 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2684 && !DECL_CONSTRUCTOR_P (fn))
2685 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2686 flags, complain);
2687 else
2688 {
2689 int lflags = conv_flags (i, nargs: len-skip, fn, arg, flags);
2690 t = implicit_conversion (to: parmtype, from: argtype, expr: arg,
2691 /*c_cast_p=*/false, flags: lflags, complain);
2692 }
2693 to_type = parmtype;
2694 parmnode = TREE_CHAIN (parmnode);
2695 }
2696 else
2697 {
2698 t = build_identity_conv (type: argtype, expr: arg);
2699 t->ellipsis_p = true;
2700 to_type = argtype;
2701 }
2702
2703 convs[i] = t;
2704 if (! t)
2705 {
2706 viable = 0;
2707 reason = arg_conversion_rejection (first_arg, n_arg: i, from: argtype, to: to_type,
2708 EXPR_LOCATION (arg));
2709 break;
2710 }
2711
2712 if (t->bad_p)
2713 {
2714 viable = -1;
2715 reason = bad_arg_conversion_rejection (first_arg, n_arg: i, from: arg, to: to_type,
2716 EXPR_LOCATION (arg));
2717 if (shortcut_bad_convs)
2718 break;
2719 }
2720 }
2721
2722 out:
2723 return add_candidate (candidates, fn, first_arg: orig_first_arg, args, num_convs: len, convs,
2724 access_path, conversion_path, viable, reason, flags);
2725}
2726
2727/* Create an overload candidate for the conversion function FN which will
2728 be invoked for expression OBJ, producing a pointer-to-function which
2729 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2730 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2731 passed on to implicit_conversion.
2732
2733 Actually, we don't really care about FN; we care about the type it
2734 converts to. There may be multiple conversion functions that will
2735 convert to that type, and we rely on build_user_type_conversion_1 to
2736 choose the best one; so when we create our candidate, we record the type
2737 instead of the function. */
2738
2739static struct z_candidate *
2740add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2741 const vec<tree, va_gc> *arglist,
2742 tree access_path, tree conversion_path,
2743 tsubst_flags_t complain)
2744{
2745 tree totype = TREE_TYPE (TREE_TYPE (fn));
2746 int i, len, viable, flags;
2747 tree parmlist, parmnode;
2748 conversion **convs;
2749 struct rejection_reason *reason;
2750
2751 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2752 parmlist = TREE_TYPE (parmlist);
2753 parmlist = TYPE_ARG_TYPES (parmlist);
2754
2755 len = vec_safe_length (v: arglist) + 1;
2756 convs = alloc_conversions (n: len);
2757 parmnode = parmlist;
2758 viable = 1;
2759 flags = LOOKUP_IMPLICIT;
2760 reason = NULL;
2761
2762 /* Don't bother looking up the same type twice. */
2763 if (*candidates && (*candidates)->fn == totype)
2764 return NULL;
2765
2766 if (!constraints_satisfied_p (fn))
2767 {
2768 reason = constraint_failure ();
2769 viable = 0;
2770 return add_candidate (candidates, fn, first_arg: obj, args: arglist, num_convs: len, convs,
2771 access_path, conversion_path, viable, reason, flags);
2772 }
2773
2774 for (i = 0; i < len; ++i)
2775 {
2776 tree arg, argtype, convert_type = NULL_TREE;
2777 conversion *t;
2778
2779 if (i == 0)
2780 arg = obj;
2781 else
2782 arg = (*arglist)[i - 1];
2783 argtype = lvalue_type (arg);
2784
2785 if (i == 0)
2786 {
2787 t = build_identity_conv (type: argtype, NULL_TREE);
2788 t = build_conv (code: ck_user, type: totype, from: t);
2789 /* Leave the 'cand' field null; we'll figure out the conversion in
2790 convert_like if this candidate is chosen. */
2791 convert_type = totype;
2792 }
2793 else if (parmnode == void_list_node)
2794 break;
2795 else if (parmnode)
2796 {
2797 t = implicit_conversion (TREE_VALUE (parmnode), from: argtype, expr: arg,
2798 /*c_cast_p=*/false, flags, complain);
2799 convert_type = TREE_VALUE (parmnode);
2800 }
2801 else
2802 {
2803 t = build_identity_conv (type: argtype, expr: arg);
2804 t->ellipsis_p = true;
2805 convert_type = argtype;
2806 }
2807
2808 convs[i] = t;
2809 if (! t)
2810 break;
2811
2812 if (t->bad_p)
2813 {
2814 viable = -1;
2815 reason = bad_arg_conversion_rejection (NULL_TREE, n_arg: i, from: arg, to: convert_type,
2816 EXPR_LOCATION (arg));
2817 }
2818
2819 if (i == 0)
2820 continue;
2821
2822 if (parmnode)
2823 parmnode = TREE_CHAIN (parmnode);
2824 }
2825
2826 if (i < len
2827 || ! sufficient_parms_p (parmlist: parmnode))
2828 {
2829 int remaining = remaining_arguments (arg: parmnode);
2830 viable = 0;
2831 reason = arity_rejection (NULL_TREE, expected: i + remaining, actual: len);
2832 }
2833
2834 return add_candidate (candidates, fn: totype, first_arg: obj, args: arglist, num_convs: len, convs,
2835 access_path, conversion_path, viable, reason, flags);
2836}
2837
2838static void
2839build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2840 tree type1, tree type2, const vec<tree,va_gc> &args,
2841 tree *argtypes, int flags, tsubst_flags_t complain)
2842{
2843 conversion *t;
2844 conversion **convs;
2845 size_t num_convs;
2846 int viable = 1;
2847 tree types[2];
2848 struct rejection_reason *reason = NULL;
2849
2850 types[0] = type1;
2851 types[1] = type2;
2852
2853 num_convs = args.length ();
2854 convs = alloc_conversions (n: num_convs);
2855
2856 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2857 conversion ops are allowed. We handle that here by just checking for
2858 boolean_type_node because other operators don't ask for it. COND_EXPR
2859 also does contextual conversion to bool for the first operand, but we
2860 handle that in build_conditional_expr, and type1 here is operand 2. */
2861 if (type1 != boolean_type_node)
2862 flags |= LOOKUP_ONLYCONVERTING;
2863
2864 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2865 {
2866 t = implicit_conversion (to: types[i], from: argtypes[i], expr: args[i],
2867 /*c_cast_p=*/false, flags, complain);
2868 if (! t)
2869 {
2870 viable = 0;
2871 /* We need something for printing the candidate. */
2872 t = build_identity_conv (type: types[i], NULL_TREE);
2873 reason = arg_conversion_rejection (NULL_TREE, n_arg: i, from: argtypes[i],
2874 to: types[i], EXPR_LOCATION (args[i]));
2875 }
2876 else if (t->bad_p)
2877 {
2878 viable = 0;
2879 reason = bad_arg_conversion_rejection (NULL_TREE, n_arg: i, from: args[i],
2880 to: types[i],
2881 EXPR_LOCATION (args[i]));
2882 }
2883 convs[i] = t;
2884 }
2885
2886 /* For COND_EXPR we rearranged the arguments; undo that now. */
2887 if (num_convs == 3)
2888 {
2889 convs[2] = convs[1];
2890 convs[1] = convs[0];
2891 t = implicit_conversion (boolean_type_node, from: argtypes[2], expr: args[2],
2892 /*c_cast_p=*/false, flags,
2893 complain);
2894 if (t)
2895 convs[0] = t;
2896 else
2897 {
2898 viable = 0;
2899 reason = arg_conversion_rejection (NULL_TREE, n_arg: 0, from: argtypes[2],
2900 boolean_type_node,
2901 EXPR_LOCATION (args[2]));
2902 }
2903 }
2904
2905 add_candidate (candidates, fn: fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2906 num_convs, convs,
2907 /*access_path=*/NULL_TREE,
2908 /*conversion_path=*/NULL_TREE,
2909 viable, reason, flags);
2910}
2911
2912static bool
2913is_complete (tree t)
2914{
2915 return COMPLETE_TYPE_P (complete_type (t));
2916}
2917
2918/* Returns nonzero if TYPE is a promoted arithmetic type. */
2919
2920static bool
2921promoted_arithmetic_type_p (tree type)
2922{
2923 /* [over.built]
2924
2925 In this section, the term promoted integral type is used to refer
2926 to those integral types which are preserved by integral promotion
2927 (including e.g. int and long but excluding e.g. char).
2928 Similarly, the term promoted arithmetic type refers to promoted
2929 integral types plus floating types. */
2930 return ((CP_INTEGRAL_TYPE_P (type)
2931 && same_type_p (type_promotes_to (type), type))
2932 || SCALAR_FLOAT_TYPE_P (type));
2933}
2934
2935/* Create any builtin operator overload candidates for the operator in
2936 question given the converted operand types TYPE1 and TYPE2. The other
2937 args are passed through from add_builtin_candidates to
2938 build_builtin_candidate.
2939
2940 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2941 If CODE is requires candidates operands of the same type of the kind
2942 of which TYPE1 and TYPE2 are, we add both candidates
2943 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2944
2945static void
2946add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2947 enum tree_code code2, tree fnname, tree type1,
2948 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2949 int flags, tsubst_flags_t complain)
2950{
2951 switch (code)
2952 {
2953 case POSTINCREMENT_EXPR:
2954 case POSTDECREMENT_EXPR:
2955 args[1] = integer_zero_node;
2956 type2 = integer_type_node;
2957 break;
2958 default:
2959 break;
2960 }
2961
2962 switch (code)
2963 {
2964
2965/* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2966 and VQ is either volatile or empty, there exist candidate operator
2967 functions of the form
2968 VQ T& operator++(VQ T&);
2969 T operator++(VQ T&, int);
2970 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2971 and VQ is either volatile or empty, there exist candidate operator
2972 functions of the form
2973 VQ T& operator--(VQ T&);
2974 T operator--(VQ T&, int);
2975 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2976 type, and VQ is either volatile or empty, there exist candidate operator
2977 functions of the form
2978 T*VQ& operator++(T*VQ&);
2979 T*VQ& operator--(T*VQ&);
2980 T* operator++(T*VQ&, int);
2981 T* operator--(T*VQ&, int); */
2982
2983 case POSTDECREMENT_EXPR:
2984 case PREDECREMENT_EXPR:
2985 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2986 return;
2987 /* FALLTHRU */
2988 case POSTINCREMENT_EXPR:
2989 case PREINCREMENT_EXPR:
2990 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2991 to p4. */
2992 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2993 return;
2994 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2995 {
2996 type1 = build_reference_type (type1);
2997 break;
2998 }
2999 return;
3000
3001/* 7 For every cv-qualified or cv-unqualified object type T, there
3002 exist candidate operator functions of the form
3003
3004 T& operator*(T*);
3005
3006
3007 8 For every function type T that does not have cv-qualifiers or
3008 a ref-qualifier, there exist candidate operator functions of the form
3009 T& operator*(T*); */
3010
3011 case INDIRECT_REF:
3012 if (TYPE_PTR_P (type1)
3013 && (TYPE_PTROB_P (type1)
3014 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
3015 break;
3016 return;
3017
3018/* 9 For every type T, there exist candidate operator functions of the form
3019 T* operator+(T*);
3020
3021 10 For every floating-point or promoted integral type T, there exist
3022 candidate operator functions of the form
3023 T operator+(T);
3024 T operator-(T); */
3025
3026 case UNARY_PLUS_EXPR: /* unary + */
3027 if (TYPE_PTR_P (type1))
3028 break;
3029 /* FALLTHRU */
3030 case NEGATE_EXPR:
3031 if (ARITHMETIC_TYPE_P (type1))
3032 break;
3033 return;
3034
3035/* 11 For every promoted integral type T, there exist candidate operator
3036 functions of the form
3037 T operator~(T); */
3038
3039 case BIT_NOT_EXPR:
3040 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
3041 break;
3042 return;
3043
3044/* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
3045 is the same type as C2 or is a derived class of C2, and T is an object
3046 type or a function type there exist candidate operator functions of the
3047 form
3048 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3049 where CV12 is the union of CV1 and CV2. */
3050
3051 case MEMBER_REF:
3052 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
3053 {
3054 tree c1 = TREE_TYPE (type1);
3055 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
3056
3057 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
3058 && (TYPE_PTRMEMFUNC_P (type2)
3059 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
3060 break;
3061 }
3062 return;
3063
3064/* 13 For every pair of types L and R, where each of L and R is a floating-point
3065 or promoted integral type, there exist candidate operator functions of the
3066 form
3067 LR operator*(L, R);
3068 LR operator/(L, R);
3069 LR operator+(L, R);
3070 LR operator-(L, R);
3071 bool operator<(L, R);
3072 bool operator>(L, R);
3073 bool operator<=(L, R);
3074 bool operator>=(L, R);
3075 bool operator==(L, R);
3076 bool operator!=(L, R);
3077 where LR is the result of the usual arithmetic conversions between
3078 types L and R.
3079
3080 14 For every integral type T there exists a candidate operator function of
3081 the form
3082
3083 std::strong_ordering operator<=>(T, T);
3084
3085 15 For every pair of floating-point types L and R, there exists a candidate
3086 operator function of the form
3087
3088 std::partial_ordering operator<=>(L, R);
3089
3090 16 For every cv-qualified or cv-unqualified object type T there exist
3091 candidate operator functions of the form
3092 T* operator+(T*, std::ptrdiff_t);
3093 T& operator[](T*, std::ptrdiff_t);
3094 T* operator-(T*, std::ptrdiff_t);
3095 T* operator+(std::ptrdiff_t, T*);
3096 T& operator[](std::ptrdiff_t, T*);
3097
3098 17 For every T, where T is a pointer to object type, there exist candidate
3099 operator functions of the form
3100 std::ptrdiff_t operator-(T, T);
3101
3102 18 For every T, where T is an enumeration type or a pointer type, there
3103 exist candidate operator functions of the form
3104 bool operator<(T, T);
3105 bool operator>(T, T);
3106 bool operator<=(T, T);
3107 bool operator>=(T, T);
3108 bool operator==(T, T);
3109 bool operator!=(T, T);
3110 R operator<=>(T, T);
3111
3112 where R is the result type specified in [expr.spaceship].
3113
3114 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
3115 there exist candidate operator functions of the form
3116 bool operator==(T, T);
3117 bool operator!=(T, T); */
3118
3119 case MINUS_EXPR:
3120 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
3121 break;
3122 if (TYPE_PTROB_P (type1)
3123 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3124 {
3125 type2 = ptrdiff_type_node;
3126 break;
3127 }
3128 /* FALLTHRU */
3129 case MULT_EXPR:
3130 case TRUNC_DIV_EXPR:
3131 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3132 break;
3133 return;
3134
3135 /* This isn't exactly what's specified above for operator<=>, but it's
3136 close enough. In particular, we don't care about the return type
3137 specified above; it doesn't participate in overload resolution and it
3138 doesn't affect the semantics of the built-in operator. */
3139 case SPACESHIP_EXPR:
3140 case EQ_EXPR:
3141 case NE_EXPR:
3142 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3143 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
3144 break;
3145 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
3146 break;
3147 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (t: args[1]))
3148 {
3149 type2 = type1;
3150 break;
3151 }
3152 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (t: args[0]))
3153 {
3154 type1 = type2;
3155 break;
3156 }
3157 /* Fall through. */
3158 case LT_EXPR:
3159 case GT_EXPR:
3160 case LE_EXPR:
3161 case GE_EXPR:
3162 case MAX_EXPR:
3163 case MIN_EXPR:
3164 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3165 break;
3166 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3167 break;
3168 if (TREE_CODE (type1) == ENUMERAL_TYPE
3169 && TREE_CODE (type2) == ENUMERAL_TYPE)
3170 break;
3171 if (TYPE_PTR_P (type1)
3172 && null_ptr_cst_p (t: args[1]))
3173 {
3174 type2 = type1;
3175 break;
3176 }
3177 if (null_ptr_cst_p (t: args[0])
3178 && TYPE_PTR_P (type2))
3179 {
3180 type1 = type2;
3181 break;
3182 }
3183 return;
3184
3185 case PLUS_EXPR:
3186 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3187 break;
3188 /* FALLTHRU */
3189 case ARRAY_REF:
3190 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3191 {
3192 type1 = ptrdiff_type_node;
3193 break;
3194 }
3195 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3196 {
3197 type2 = ptrdiff_type_node;
3198 break;
3199 }
3200 return;
3201
3202/* 18For every pair of promoted integral types L and R, there exist candi-
3203 date operator functions of the form
3204 LR operator%(L, R);
3205 LR operator&(L, R);
3206 LR operator^(L, R);
3207 LR operator|(L, R);
3208 L operator<<(L, R);
3209 L operator>>(L, R);
3210 where LR is the result of the usual arithmetic conversions between
3211 types L and R. */
3212
3213 case TRUNC_MOD_EXPR:
3214 case BIT_AND_EXPR:
3215 case BIT_IOR_EXPR:
3216 case BIT_XOR_EXPR:
3217 case LSHIFT_EXPR:
3218 case RSHIFT_EXPR:
3219 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3220 break;
3221 return;
3222
3223/* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3224 type, VQ is either volatile or empty, and R is a promoted arithmetic
3225 type, there exist candidate operator functions of the form
3226 VQ L& operator=(VQ L&, R);
3227 VQ L& operator*=(VQ L&, R);
3228 VQ L& operator/=(VQ L&, R);
3229 VQ L& operator+=(VQ L&, R);
3230 VQ L& operator-=(VQ L&, R);
3231
3232 20For every pair T, VQ), where T is any type and VQ is either volatile
3233 or empty, there exist candidate operator functions of the form
3234 T*VQ& operator=(T*VQ&, T*);
3235
3236 21For every pair T, VQ), where T is a pointer to member type and VQ is
3237 either volatile or empty, there exist candidate operator functions of
3238 the form
3239 VQ T& operator=(VQ T&, T);
3240
3241 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3242 unqualified complete object type, VQ is either volatile or empty, and
3243 I is a promoted integral type, there exist candidate operator func-
3244 tions of the form
3245 T*VQ& operator+=(T*VQ&, I);
3246 T*VQ& operator-=(T*VQ&, I);
3247
3248 23For every triple L, VQ, R), where L is an integral or enumeration
3249 type, VQ is either volatile or empty, and R is a promoted integral
3250 type, there exist candidate operator functions of the form
3251
3252 VQ L& operator%=(VQ L&, R);
3253 VQ L& operator<<=(VQ L&, R);
3254 VQ L& operator>>=(VQ L&, R);
3255 VQ L& operator&=(VQ L&, R);
3256 VQ L& operator^=(VQ L&, R);
3257 VQ L& operator|=(VQ L&, R); */
3258
3259 case MODIFY_EXPR:
3260 switch (code2)
3261 {
3262 case PLUS_EXPR:
3263 case MINUS_EXPR:
3264 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3265 {
3266 type2 = ptrdiff_type_node;
3267 break;
3268 }
3269 /* FALLTHRU */
3270 case MULT_EXPR:
3271 case TRUNC_DIV_EXPR:
3272 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3273 break;
3274 return;
3275
3276 case TRUNC_MOD_EXPR:
3277 case BIT_AND_EXPR:
3278 case BIT_IOR_EXPR:
3279 case BIT_XOR_EXPR:
3280 case LSHIFT_EXPR:
3281 case RSHIFT_EXPR:
3282 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3283 break;
3284 return;
3285
3286 case NOP_EXPR:
3287 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3288 break;
3289 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3290 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3291 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3292 || ((TYPE_PTRMEMFUNC_P (type1)
3293 || TYPE_PTR_P (type1))
3294 && null_ptr_cst_p (t: args[1])))
3295 {
3296 type2 = type1;
3297 break;
3298 }
3299 return;
3300
3301 default:
3302 gcc_unreachable ();
3303 }
3304 type1 = build_reference_type (type1);
3305 break;
3306
3307 case COND_EXPR:
3308 /* [over.built]
3309
3310 For every pair of promoted arithmetic types L and R, there
3311 exist candidate operator functions of the form
3312
3313 LR operator?(bool, L, R);
3314
3315 where LR is the result of the usual arithmetic conversions
3316 between types L and R.
3317
3318 For every type T, where T is a pointer or pointer-to-member
3319 type, there exist candidate operator functions of the form T
3320 operator?(bool, T, T); */
3321
3322 if (promoted_arithmetic_type_p (type: type1)
3323 && promoted_arithmetic_type_p (type: type2))
3324 /* That's OK. */
3325 break;
3326
3327 /* Otherwise, the types should be pointers. */
3328 if (!((TYPE_PTR_OR_PTRMEM_P (type1) || null_ptr_cst_p (t: args[0]))
3329 && (TYPE_PTR_OR_PTRMEM_P (type2) || null_ptr_cst_p (t: args[1]))))
3330 return;
3331
3332 /* We don't check that the two types are the same; the logic
3333 below will actually create two candidates; one in which both
3334 parameter types are TYPE1, and one in which both parameter
3335 types are TYPE2. */
3336 break;
3337
3338 case REALPART_EXPR:
3339 case IMAGPART_EXPR:
3340 if (ARITHMETIC_TYPE_P (type1))
3341 break;
3342 return;
3343
3344 default:
3345 gcc_unreachable ();
3346 }
3347
3348 /* Make sure we don't create builtin candidates with dependent types. */
3349 bool u1 = uses_template_parms (type1);
3350 bool u2 = type2 ? uses_template_parms (type2) : false;
3351 if (u1 || u2)
3352 {
3353 /* Try to recover if one of the types is non-dependent. But if
3354 there's only one type, there's nothing we can do. */
3355 if (!type2)
3356 return;
3357 /* And we lose if both are dependent. */
3358 if (u1 && u2)
3359 return;
3360 /* Or if they have different forms. */
3361 if (TREE_CODE (type1) != TREE_CODE (type2))
3362 return;
3363
3364 if (u1 && !u2)
3365 type1 = type2;
3366 else if (u2 && !u1)
3367 type2 = type1;
3368 }
3369
3370 /* If we're dealing with two pointer types or two enumeral types,
3371 we need candidates for both of them. */
3372 if (type2 && !same_type_p (type1, type2)
3373 && TREE_CODE (type1) == TREE_CODE (type2)
3374 && (TYPE_REF_P (type1)
3375 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3376 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3377 || TYPE_PTRMEMFUNC_P (type1)
3378 || MAYBE_CLASS_TYPE_P (type1)
3379 || TREE_CODE (type1) == ENUMERAL_TYPE))
3380 {
3381 if (TYPE_PTR_OR_PTRMEM_P (type1))
3382 {
3383 tree cptype = composite_pointer_type (input_location,
3384 type1, type2,
3385 error_mark_node,
3386 error_mark_node,
3387 CPO_CONVERSION,
3388 tf_none);
3389 if (cptype != error_mark_node)
3390 {
3391 build_builtin_candidate
3392 (candidates, fnname, type1: cptype, type2: cptype, args, argtypes,
3393 flags, complain);
3394 return;
3395 }
3396 }
3397
3398 build_builtin_candidate
3399 (candidates, fnname, type1, type2: type1, args, argtypes, flags, complain);
3400 build_builtin_candidate
3401 (candidates, fnname, type1: type2, type2, args, argtypes, flags, complain);
3402 return;
3403 }
3404
3405 build_builtin_candidate
3406 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3407}
3408
3409tree
3410type_decays_to (tree type)
3411{
3412 if (TREE_CODE (type) == ARRAY_TYPE)
3413 return build_pointer_type (TREE_TYPE (type));
3414 if (TREE_CODE (type) == FUNCTION_TYPE)
3415 return build_pointer_type (type);
3416 return type;
3417}
3418
3419/* There are three conditions of builtin candidates:
3420
3421 1) bool-taking candidates. These are the same regardless of the input.
3422 2) pointer-pair taking candidates. These are generated for each type
3423 one of the input types converts to.
3424 3) arithmetic candidates. According to the standard, we should generate
3425 all of these, but I'm trying not to...
3426
3427 Here we generate a superset of the possible candidates for this particular
3428 case. That is a subset of the full set the standard defines, plus some
3429 other cases which the standard disallows. add_builtin_candidate will
3430 filter out the invalid set. */
3431
3432static void
3433add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3434 enum tree_code code2, tree fnname,
3435 vec<tree, va_gc> *argv,
3436 int flags, tsubst_flags_t complain)
3437{
3438 int ref1;
3439 int enum_p = 0;
3440 tree type, argtypes[3], t;
3441 /* TYPES[i] is the set of possible builtin-operator parameter types
3442 we will consider for the Ith argument. */
3443 vec<tree, va_gc> *types[2];
3444 unsigned ix;
3445 vec<tree, va_gc> &args = *argv;
3446 unsigned len = args.length ();
3447
3448 for (unsigned i = 0; i < len; ++i)
3449 {
3450 if (args[i])
3451 argtypes[i] = unlowered_expr_type (args[i]);
3452 else
3453 argtypes[i] = NULL_TREE;
3454 }
3455
3456 switch (code)
3457 {
3458/* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3459 and VQ is either volatile or empty, there exist candidate operator
3460 functions of the form
3461 VQ T& operator++(VQ T&); */
3462
3463 case POSTINCREMENT_EXPR:
3464 case PREINCREMENT_EXPR:
3465 case POSTDECREMENT_EXPR:
3466 case PREDECREMENT_EXPR:
3467 case MODIFY_EXPR:
3468 ref1 = 1;
3469 break;
3470
3471/* 24There also exist candidate operator functions of the form
3472 bool operator!(bool);
3473 bool operator&&(bool, bool);
3474 bool operator||(bool, bool); */
3475
3476 case TRUTH_NOT_EXPR:
3477 build_builtin_candidate
3478 (candidates, fnname, boolean_type_node,
3479 NULL_TREE, args, argtypes, flags, complain);
3480 return;
3481
3482 case TRUTH_ORIF_EXPR:
3483 case TRUTH_ANDIF_EXPR:
3484 build_builtin_candidate
3485 (candidates, fnname, boolean_type_node,
3486 boolean_type_node, args, argtypes, flags, complain);
3487 return;
3488
3489 case ADDR_EXPR:
3490 case COMPOUND_EXPR:
3491 case COMPONENT_REF:
3492 case CO_AWAIT_EXPR:
3493 return;
3494
3495 case COND_EXPR:
3496 case EQ_EXPR:
3497 case NE_EXPR:
3498 case LT_EXPR:
3499 case LE_EXPR:
3500 case GT_EXPR:
3501 case GE_EXPR:
3502 case SPACESHIP_EXPR:
3503 enum_p = 1;
3504 /* Fall through. */
3505
3506 default:
3507 ref1 = 0;
3508 }
3509
3510 types[0] = make_tree_vector ();
3511 types[1] = make_tree_vector ();
3512
3513 if (len == 3)
3514 len = 2;
3515 for (unsigned i = 0; i < len; ++i)
3516 {
3517 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3518 {
3519 tree convs;
3520
3521 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3522 return;
3523
3524 convs = lookup_conversions (argtypes[i]);
3525
3526 if (code == COND_EXPR)
3527 {
3528 if (lvalue_p (args[i]))
3529 vec_safe_push (v&: types[i], obj: build_reference_type (argtypes[i]));
3530
3531 vec_safe_push (v&: types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3532 }
3533
3534 else if (! convs)
3535 return;
3536
3537 for (; convs; convs = TREE_CHAIN (convs))
3538 {
3539 type = TREE_TYPE (convs);
3540
3541 if (i == 0 && ref1
3542 && (!TYPE_REF_P (type)
3543 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3544 continue;
3545
3546 if (code == COND_EXPR && TYPE_REF_P (type))
3547 vec_safe_push (v&: types[i], obj: type);
3548
3549 type = non_reference (type);
3550 if (i != 0 || ! ref1)
3551 {
3552 type = cv_unqualified (type_decays_to (type));
3553 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3554 vec_safe_push (v&: types[i], obj: type);
3555 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3556 type = type_promotes_to (type);
3557 }
3558
3559 if (! vec_member (type, types[i]))
3560 vec_safe_push (v&: types[i], obj: type);
3561 }
3562 }
3563 else
3564 {
3565 if (code == COND_EXPR && lvalue_p (args[i]))
3566 vec_safe_push (v&: types[i], obj: build_reference_type (argtypes[i]));
3567 type = non_reference (argtypes[i]);
3568 if (i != 0 || ! ref1)
3569 {
3570 type = cv_unqualified (type_decays_to (type));
3571 if (enum_p && UNSCOPED_ENUM_P (type))
3572 vec_safe_push (v&: types[i], obj: type);
3573 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3574 type = type_promotes_to (type);
3575 }
3576 vec_safe_push (v&: types[i], obj: type);
3577 }
3578 }
3579
3580 /* Run through the possible parameter types of both arguments,
3581 creating candidates with those parameter types. */
3582 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3583 {
3584 unsigned jx;
3585 tree u;
3586
3587 if (!types[1]->is_empty ())
3588 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3589 add_builtin_candidate
3590 (candidates, code, code2, fnname, type1: t,
3591 type2: u, args, argtypes, flags, complain);
3592 else
3593 add_builtin_candidate
3594 (candidates, code, code2, fnname, type1: t,
3595 NULL_TREE, args, argtypes, flags, complain);
3596 }
3597
3598 release_tree_vector (types[0]);
3599 release_tree_vector (types[1]);
3600}
3601
3602
3603/* If TMPL can be successfully instantiated as indicated by
3604 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3605
3606 TMPL is the template. EXPLICIT_TARGS are any explicit template
3607 arguments. ARGLIST is the arguments provided at the call-site.
3608 This does not change ARGLIST. The RETURN_TYPE is the desired type
3609 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3610 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3611 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3612
3613 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3614
3615static struct z_candidate*
3616add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3617 tree ctype, tree explicit_targs, tree first_arg,
3618 const vec<tree, va_gc> *arglist, tree return_type,
3619 tree access_path, tree conversion_path,
3620 int flags, tree obj, unification_kind_t strict,
3621 bool shortcut_bad_convs, tsubst_flags_t complain)
3622{
3623 int ntparms = DECL_NTPARMS (tmpl);
3624 tree targs = make_tree_vec (ntparms);
3625 unsigned int len = vec_safe_length (v: arglist);
3626 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3627 unsigned int skip_without_in_chrg = 0;
3628 tree first_arg_without_in_chrg = first_arg;
3629 tree *args_without_in_chrg;
3630 unsigned int nargs_without_in_chrg;
3631 unsigned int ia, ix;
3632 tree arg;
3633 struct z_candidate *cand;
3634 tree fn;
3635 struct rejection_reason *reason = NULL;
3636 int errs;
3637 conversion **convs = NULL;
3638
3639 /* We don't do deduction on the in-charge parameter, the VTT
3640 parameter or 'this'. */
3641 if (DECL_IOBJ_MEMBER_FUNCTION_P (tmpl))
3642 {
3643 if (first_arg_without_in_chrg != NULL_TREE)
3644 first_arg_without_in_chrg = NULL_TREE;
3645 else if (return_type && strict == DEDUCE_CALL)
3646 /* We're deducing for a call to the result of a template conversion
3647 function, so the args don't contain 'this'; leave them alone. */;
3648 else
3649 ++skip_without_in_chrg;
3650 }
3651
3652 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3653 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3654 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3655 {
3656 if (first_arg_without_in_chrg != NULL_TREE)
3657 first_arg_without_in_chrg = NULL_TREE;
3658 else
3659 ++skip_without_in_chrg;
3660 }
3661
3662 if (len < skip_without_in_chrg)
3663 return add_ignored_candidate (candidates, fn: tmpl);
3664
3665 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3666 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3667 TREE_TYPE ((*arglist)[0])))
3668 {
3669 /* 12.8/6 says, "A declaration of a constructor for a class X is
3670 ill-formed if its first parameter is of type (optionally cv-qualified)
3671 X and either there are no other parameters or else all other
3672 parameters have default arguments. A member function template is never
3673 instantiated to produce such a constructor signature."
3674
3675 So if we're trying to copy an object of the containing class, don't
3676 consider a template constructor that has a first parameter type that
3677 is just a template parameter, as we would deduce a signature that we
3678 would then reject in the code below. */
3679 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3680 {
3681 firstparm = TREE_VALUE (firstparm);
3682 if (PACK_EXPANSION_P (firstparm))
3683 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3684 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3685 {
3686 gcc_assert (!explicit_targs);
3687 reason = invalid_copy_with_fn_template_rejection ();
3688 goto fail;
3689 }
3690 }
3691 }
3692
3693 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3694 + (len - skip_without_in_chrg));
3695 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3696 ia = 0;
3697 if (first_arg_without_in_chrg != NULL_TREE)
3698 {
3699 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3700 ++ia;
3701 }
3702 for (ix = skip_without_in_chrg;
3703 vec_safe_iterate (v: arglist, ix, ptr: &arg);
3704 ++ix)
3705 {
3706 args_without_in_chrg[ia] = arg;
3707 ++ia;
3708 }
3709 gcc_assert (ia == nargs_without_in_chrg);
3710
3711 if (!obj)
3712 {
3713 /* Check that there's no obvious arity mismatch before proceeding with
3714 deduction. This avoids substituting explicit template arguments
3715 into the template or e.g. derived-to-base parm/arg unification
3716 (which could result in an error outside the immediate context) when
3717 the resulting candidate would be unviable anyway. */
3718 int min_arity = 0, max_arity = 0;
3719 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3720 parms = skip_artificial_parms_for (tmpl, parms);
3721 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3722 {
3723 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3724 {
3725 max_arity = -1;
3726 break;
3727 }
3728 if (TREE_PURPOSE (parms))
3729 /* A parameter with a default argument. */
3730 ++max_arity;
3731 else
3732 ++min_arity, ++max_arity;
3733 }
3734 if (ia < (unsigned)min_arity)
3735 {
3736 /* Too few arguments. */
3737 reason = arity_rejection (NULL_TREE, expected: min_arity, actual: ia,
3738 /*least_p=*/(max_arity == -1));
3739 goto fail;
3740 }
3741 else if (max_arity != -1 && ia > (unsigned)max_arity)
3742 {
3743 /* Too many arguments. */
3744 reason = arity_rejection (NULL_TREE, expected: max_arity, actual: ia);
3745 goto fail;
3746 }
3747
3748 convs = alloc_conversions (n: nargs);
3749
3750 if (shortcut_bad_convs
3751 && DECL_IOBJ_MEMBER_FUNCTION_P (tmpl)
3752 && !DECL_CONSTRUCTOR_P (tmpl))
3753 {
3754 /* Check the 'this' conversion before proceeding with deduction.
3755 This is effectively an extension of the DR 1391 resolution
3756 that we perform in check_non_deducible_conversions, though it's
3757 convenient to do this extra check here instead of there. */
3758 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3759 tree argtype = lvalue_type (first_arg);
3760 tree arg = first_arg;
3761 conversion *t = build_this_conversion (fn: tmpl, ctype,
3762 parmtype, argtype, arg,
3763 flags, complain);
3764 convs[0] = t;
3765 if (t->bad_p)
3766 {
3767 reason = bad_arg_conversion_rejection (first_arg, n_arg: 0,
3768 from: arg, to: parmtype,
3769 EXPR_LOCATION (arg));
3770 goto fail;
3771 }
3772 }
3773 }
3774
3775 errs = errorcount+sorrycount;
3776 fn = fn_type_unification (tmpl, explicit_targs, targs,
3777 args_without_in_chrg,
3778 nargs_without_in_chrg,
3779 return_type, strict, flags, convs,
3780 false, complain & tf_decltype);
3781
3782 if (fn == error_mark_node)
3783 {
3784 /* Don't repeat unification later if it already resulted in errors. */
3785 if (errorcount+sorrycount == errs)
3786 reason = template_unification_rejection (tmpl, explicit_targs,
3787 targs, args: args_without_in_chrg,
3788 nargs: nargs_without_in_chrg,
3789 return_type, strict, flags);
3790 else
3791 reason = template_unification_error_rejection ();
3792 goto fail;
3793 }
3794
3795 /* Now the explicit specifier might have been deduced; check if this
3796 declaration is explicit. If it is and we're ignoring non-converting
3797 constructors, don't add this function to the set of candidates. */
3798 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3799 == LOOKUP_ONLYCONVERTING)
3800 && DECL_NONCONVERTING_P (fn))
3801 return add_ignored_candidate (candidates, fn);
3802
3803 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3804 {
3805 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3806 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3807 ctype))
3808 {
3809 /* We're trying to produce a constructor with a prohibited signature,
3810 as discussed above; handle here any cases we didn't catch then,
3811 such as X(X<T>). */
3812 reason = invalid_copy_with_fn_template_rejection ();
3813 goto fail;
3814 }
3815 }
3816
3817 if (obj != NULL_TREE)
3818 /* Aha, this is a conversion function. */
3819 cand = add_conv_candidate (candidates, fn, obj, arglist,
3820 access_path, conversion_path, complain);
3821 else
3822 cand = add_function_candidate (candidates, fn, ctype,
3823 first_arg, args: arglist, access_path,
3824 conversion_path, flags, convs,
3825 shortcut_bad_convs, complain);
3826 if (DECL_TI_TEMPLATE (fn) != tmpl)
3827 /* This situation can occur if a member template of a template
3828 class is specialized. Then, instantiate_template might return
3829 an instantiation of the specialization, in which case the
3830 DECL_TI_TEMPLATE field will point at the original
3831 specialization. For example:
3832
3833 template <class T> struct S { template <class U> void f(U);
3834 template <> void f(int) {}; };
3835 S<double> sd;
3836 sd.f(3);
3837
3838 Here, TMPL will be template <class U> S<double>::f(U).
3839 And, instantiate template will give us the specialization
3840 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3841 for this will point at template <class T> template <> S<T>::f(int),
3842 so that we can find the definition. For the purposes of
3843 overload resolution, however, we want the original TMPL. */
3844 cand->template_decl = build_template_info (tmpl, targs);
3845 else
3846 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3847 cand->explicit_targs = explicit_targs;
3848
3849 return cand;
3850 fail:
3851 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3852 return add_candidate (candidates, fn: tmpl, first_arg, args: arglist, num_convs: nargs, convs,
3853 access_path, conversion_path, viable, reason, flags);
3854}
3855
3856
3857static struct z_candidate *
3858add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3859 tree explicit_targs, tree first_arg,
3860 const vec<tree, va_gc> *arglist, tree return_type,
3861 tree access_path, tree conversion_path, int flags,
3862 unification_kind_t strict, bool shortcut_bad_convs,
3863 tsubst_flags_t complain)
3864{
3865 return
3866 add_template_candidate_real (candidates, tmpl, ctype,
3867 explicit_targs, first_arg, arglist,
3868 return_type, access_path, conversion_path,
3869 flags, NULL_TREE, strict, shortcut_bad_convs,
3870 complain);
3871}
3872
3873/* Create an overload candidate for the conversion function template TMPL,
3874 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3875 pointer-to-function which will in turn be called with the argument list
3876 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3877 passed on to implicit_conversion. */
3878
3879static struct z_candidate *
3880add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3881 tree obj,
3882 const vec<tree, va_gc> *arglist,
3883 tree return_type, tree access_path,
3884 tree conversion_path, tsubst_flags_t complain)
3885{
3886 return
3887 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3888 NULL_TREE, arglist, return_type, access_path,
3889 conversion_path, flags: 0, obj, strict: DEDUCE_CALL,
3890 /*shortcut_bad_convs=*/false, complain);
3891}
3892
3893/* The CANDS are the set of candidates that were considered for
3894 overload resolution. Sort CANDS so that the strictly viable
3895 candidates appear first, followed by non-strictly viable candidates,
3896 followed by non-viable candidates. Returns the first candidate
3897 in this sorted list. If any of the candidates were viable, set
3898 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3899 considered viable only if it is strictly viable when setting
3900 *ANY_VIABLE_P. */
3901
3902static struct z_candidate*
3903splice_viable (struct z_candidate *cands,
3904 bool strict_p,
3905 bool *any_viable_p)
3906{
3907 z_candidate *strictly_viable = nullptr;
3908 z_candidate **strictly_viable_tail = &strictly_viable;
3909
3910 z_candidate *non_strictly_viable = nullptr;
3911 z_candidate **non_strictly_viable_tail = &non_strictly_viable;
3912
3913 z_candidate *non_viable = nullptr;
3914 z_candidate **non_viable_tail = &non_viable;
3915
3916 z_candidate *non_viable_ignored = nullptr;
3917 z_candidate **non_viable_ignored_tail = &non_viable_ignored;
3918
3919 /* Be strict inside templates, since build_over_call won't actually
3920 do the conversions to get pedwarns. */
3921 if (processing_template_decl)
3922 strict_p = true;
3923
3924 for (z_candidate *cand = cands; cand; cand = cand->next)
3925 {
3926 if (!strict_p
3927 && (cand->viable == 1 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
3928 /* Be strict in the presence of a viable candidate. Also if
3929 there are template candidates, so that we get deduction errors
3930 for them instead of silently preferring a bad conversion. */
3931 strict_p = true;
3932
3933 /* Move this candidate to the appropriate list according to
3934 its viability. */
3935 auto& tail = (cand->viable == 1 ? strictly_viable_tail
3936 : cand->viable == -1 ? non_strictly_viable_tail
3937 : ignored_candidate_p (cand) ? non_viable_ignored_tail
3938 : non_viable_tail);
3939 *tail = cand;
3940 tail = &cand->next;
3941 }
3942
3943 *any_viable_p = (strictly_viable != nullptr
3944 || (!strict_p && non_strictly_viable != nullptr));
3945
3946 /* Combine the lists. */
3947 *non_viable_ignored_tail = nullptr;
3948 *non_viable_tail = non_viable_ignored;
3949 *non_strictly_viable_tail = non_viable;
3950 *strictly_viable_tail = non_strictly_viable;
3951
3952 return strictly_viable;
3953}
3954
3955static bool
3956any_strictly_viable (struct z_candidate *cands)
3957{
3958 for (; cands; cands = cands->next)
3959 if (cands->viable == 1)
3960 return true;
3961 return false;
3962}
3963
3964/* OBJ is being used in an expression like "OBJ.f (...)". In other
3965 words, it is about to become the "this" pointer for a member
3966 function call. Take the address of the object. */
3967
3968static tree
3969build_this (tree obj)
3970{
3971 /* In a template, we are only concerned about the type of the
3972 expression, so we can take a shortcut. */
3973 if (processing_template_decl)
3974 return build_address (obj);
3975
3976 return cp_build_addr_expr (obj, tf_warning_or_error);
3977}
3978
3979/* Returns true iff functions are equivalent. Equivalent functions are
3980 not '==' only if one is a function-local extern function or if
3981 both are extern "C". */
3982
3983static inline int
3984equal_functions (tree fn1, tree fn2)
3985{
3986 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3987 return 0;
3988 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3989 return fn1 == fn2;
3990 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3991 || DECL_EXTERN_C_FUNCTION_P (fn1))
3992 return decls_match (fn1, fn2);
3993 return fn1 == fn2;
3994}
3995
3996/* Print information about a candidate FN being rejected due to INFO. */
3997
3998static void
3999print_conversion_rejection (location_t loc, struct conversion_info *info,
4000 tree fn)
4001{
4002 tree from = info->from;
4003 if (!TYPE_P (from))
4004 from = lvalue_type (from);
4005 if (info->n_arg == -1)
4006 {
4007 /* Conversion of implicit `this' argument failed. */
4008 if (!TYPE_P (info->from))
4009 /* A bad conversion for 'this' must be discarding cv-quals. */
4010 inform (loc, "passing %qT as %<this%> "
4011 "argument discards qualifiers",
4012 from);
4013 else
4014 inform (loc, "no known conversion for implicit "
4015 "%<this%> parameter from %qH to %qI",
4016 from, info->to_type);
4017 }
4018 else if (!TYPE_P (info->from))
4019 {
4020 if (info->n_arg >= 0)
4021 inform (loc, "conversion of argument %d would be ill-formed:",
4022 info->n_arg + 1);
4023 iloc_sentinel ils = loc;
4024 perform_implicit_conversion (info->to_type, info->from,
4025 tf_warning_or_error);
4026 }
4027 else if (info->n_arg == -2)
4028 /* Conversion of conversion function return value failed. */
4029 inform (loc, "no known conversion from %qH to %qI",
4030 from, info->to_type);
4031 else
4032 {
4033 if (TREE_CODE (fn) == FUNCTION_DECL)
4034 loc = get_fndecl_argument_location (fn, info->n_arg);
4035 inform (loc, "no known conversion for argument %d from %qH to %qI",
4036 info->n_arg + 1, from, info->to_type);
4037 }
4038}
4039
4040/* Print information about a candidate with WANT parameters and we found
4041 HAVE. */
4042
4043static void
4044print_arity_information (location_t loc, unsigned int have, unsigned int want,
4045 bool least_p)
4046{
4047 if (least_p)
4048 inform_n (loc, want,
4049 "candidate expects at least %d argument, %d provided",
4050 "candidate expects at least %d arguments, %d provided",
4051 want, have);
4052 else
4053 inform_n (loc, want,
4054 "candidate expects %d argument, %d provided",
4055 "candidate expects %d arguments, %d provided",
4056 want, have);
4057}
4058
4059/* Print information about one overload candidate CANDIDATE. MSGSTR
4060 is the text to print before the candidate itself.
4061
4062 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
4063 to have been run through gettext by the caller. This wart makes
4064 life simpler in print_z_candidates and for the translators. */
4065
4066static void
4067print_z_candidate (location_t loc, const char *msgstr,
4068 struct z_candidate *candidate)
4069{
4070 const char *msg = (msgstr == NULL
4071 ? ""
4072 : ACONCAT ((_(msgstr), " ", NULL)));
4073 tree fn = candidate->fn;
4074 if (flag_new_inheriting_ctors)
4075 fn = strip_inheriting_ctors (fn);
4076 location_t cloc = location_of (fn);
4077
4078 if (identifier_p (t: fn))
4079 {
4080 cloc = loc;
4081 if (candidate->num_convs == 3)
4082 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
4083 candidate->convs[0]->type,
4084 candidate->convs[1]->type,
4085 candidate->convs[2]->type);
4086 else if (candidate->num_convs == 2)
4087 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
4088 candidate->convs[0]->type,
4089 candidate->convs[1]->type);
4090 else
4091 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
4092 candidate->convs[0]->type);
4093 }
4094 else if (TYPE_P (fn))
4095 inform (cloc, "%s%qT (conversion)", msg, fn);
4096 else if (candidate->viable == -1)
4097 inform (cloc, "%s%#qD (near match)", msg, fn);
4098 else if (ignored_candidate_p (cand: candidate))
4099 inform (cloc, "%s%#qD (ignored)", msg, fn);
4100 else if (DECL_DELETED_FN (fn))
4101 inform (cloc, "%s%#qD (deleted)", msg, fn);
4102 else if (candidate->reversed ())
4103 inform (cloc, "%s%#qD (reversed)", msg, fn);
4104 else if (candidate->rewritten ())
4105 inform (cloc, "%s%#qD (rewritten)", msg, fn);
4106 else
4107 inform (cloc, "%s%#qD", msg, fn);
4108
4109 auto_diagnostic_nesting_level sentinel;
4110
4111 if (fn != candidate->fn)
4112 {
4113 cloc = location_of (candidate->fn);
4114 inform (cloc, "inherited here");
4115 }
4116
4117 /* Give the user some information about why this candidate failed. */
4118 if (candidate->reason != NULL)
4119 {
4120 struct rejection_reason *r = candidate->reason;
4121
4122 switch (r->code)
4123 {
4124 case rr_arity:
4125 print_arity_information (loc: cloc, have: r->u.arity.actual,
4126 want: r->u.arity.expected,
4127 least_p: r->u.arity.least_p);
4128 break;
4129 case rr_arg_conversion:
4130 print_conversion_rejection (loc: cloc, info: &r->u.conversion, fn);
4131 break;
4132 case rr_bad_arg_conversion:
4133 print_conversion_rejection (loc: cloc, info: &r->u.bad_conversion, fn);
4134 break;
4135 case rr_explicit_conversion:
4136 inform (cloc, "return type %qT of explicit conversion function "
4137 "cannot be converted to %qT with a qualification "
4138 "conversion", r->u.conversion.from,
4139 r->u.conversion.to_type);
4140 break;
4141 case rr_template_conversion:
4142 inform (cloc, "conversion from return type %qT of template "
4143 "conversion function specialization to %qT is not an "
4144 "exact match", r->u.conversion.from,
4145 r->u.conversion.to_type);
4146 break;
4147 case rr_template_unification:
4148 /* We use template_unification_error_rejection if unification caused
4149 actual non-SFINAE errors, in which case we don't need to repeat
4150 them here. */
4151 if (r->u.template_unification.tmpl == NULL_TREE)
4152 {
4153 inform (cloc, "substitution of deduced template arguments "
4154 "resulted in errors seen above");
4155 break;
4156 }
4157 /* Re-run template unification with diagnostics. */
4158 inform (cloc, "template argument deduction/substitution failed:");
4159 {
4160 auto_diagnostic_nesting_level sentinel;
4161 fn_type_unification (r->u.template_unification.tmpl,
4162 r->u.template_unification.explicit_targs,
4163 (make_tree_vec
4164 (r->u.template_unification.num_targs)),
4165 r->u.template_unification.args,
4166 r->u.template_unification.nargs,
4167 r->u.template_unification.return_type,
4168 r->u.template_unification.strict,
4169 r->u.template_unification.flags,
4170 NULL, true, false);
4171 }
4172 break;
4173 case rr_invalid_copy:
4174 inform (cloc,
4175 "a constructor taking a single argument of its own "
4176 "class type is invalid");
4177 break;
4178 case rr_constraint_failure:
4179 diagnose_constraints (cloc, fn, NULL_TREE);
4180 break;
4181 case rr_inherited_ctor:
4182 inform (cloc, "an inherited constructor is not a candidate for "
4183 "initialization from an expression of the same or derived "
4184 "type");
4185 break;
4186 case rr_ignored:
4187 break;
4188 case rr_none:
4189 default:
4190 /* This candidate didn't have any issues or we failed to
4191 handle a particular code. Either way... */
4192 gcc_unreachable ();
4193 }
4194 }
4195}
4196
4197/* Print information about each overload candidate in CANDIDATES,
4198 which is assumed to have gone through splice_viable and tourney
4199 (if splice_viable succeeded). */
4200
4201static void
4202print_z_candidates (location_t loc, struct z_candidate *candidates,
4203 tristate only_viable_p /* = tristate::unknown () */)
4204{
4205 struct z_candidate *cand1;
4206 struct z_candidate **cand2;
4207
4208 if (!candidates)
4209 return;
4210
4211 /* Remove non-viable deleted candidates. */
4212 cand1 = candidates;
4213 for (cand2 = &cand1; *cand2; )
4214 {
4215 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4216 && !(*cand2)->viable
4217 && DECL_DELETED_FN ((*cand2)->fn))
4218 *cand2 = (*cand2)->next;
4219 else
4220 cand2 = &(*cand2)->next;
4221 }
4222 /* ...if there are any non-deleted ones. */
4223 if (cand1)
4224 candidates = cand1;
4225
4226 /* There may be duplicates in the set of candidates. We put off
4227 checking this condition as long as possible, since we have no way
4228 to eliminate duplicates from a set of functions in less than n^2
4229 time. Now we are about to emit an error message, so it is more
4230 permissible to go slowly. */
4231 for (cand1 = candidates; cand1; cand1 = cand1->next)
4232 {
4233 tree fn = cand1->fn;
4234 /* Skip builtin candidates and conversion functions. */
4235 if (!DECL_P (fn))
4236 continue;
4237 cand2 = &cand1->next;
4238 while (*cand2)
4239 {
4240 if (DECL_P ((*cand2)->fn)
4241 && equal_functions (fn1: fn, fn2: (*cand2)->fn))
4242 *cand2 = (*cand2)->next;
4243 else
4244 cand2 = &(*cand2)->next;
4245 }
4246 }
4247
4248 /* Unless otherwise specified, if there's a (strictly) viable candidate
4249 then we assume we're being called as part of diagnosing ambiguity, in
4250 which case we want to print only viable candidates since non-viable
4251 candidates couldn't have contributed to the ambiguity. */
4252 if (only_viable_p.is_unknown ())
4253 only_viable_p = candidates->viable == 1;
4254
4255 auto_diagnostic_nesting_level sentinel;
4256
4257 int num_candidates = 0;
4258 for (auto iter = candidates; iter; iter = iter->next)
4259 {
4260 if (only_viable_p.is_true () && iter->viable != 1)
4261 break;
4262 ++num_candidates;
4263 }
4264
4265 inform_num_candidates (loc, num_candidates);
4266
4267 auto_diagnostic_nesting_level sentinel2;
4268
4269 int candidate_idx = 0;
4270 for (; candidates; candidates = candidates->next)
4271 {
4272 if (only_viable_p.is_true () && candidates->viable != 1)
4273 break;
4274 if (ignored_candidate_p (cand: candidates) && !flag_diagnostics_all_candidates)
4275 {
4276 inform (loc, "some candidates omitted; "
4277 "use %<-fdiagnostics-all-candidates%> to display them");
4278 break;
4279 }
4280 pretty_printer pp;
4281 pp_printf (&pp, N_("candidate %i:"), candidate_idx + 1);
4282 const char *const msgstr = pp_formatted_text (&pp);
4283 print_z_candidate (loc, msgstr, candidate: candidates);
4284 ++candidate_idx;
4285 }
4286}
4287
4288/* USER_SEQ is a user-defined conversion sequence, beginning with a
4289 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4290 the result of the conversion function to convert it to the final
4291 desired type. Merge the two sequences into a single sequence,
4292 and return the merged sequence. */
4293
4294static conversion *
4295merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4296{
4297 conversion **t;
4298 bool bad = user_seq->bad_p;
4299
4300 gcc_assert (user_seq->kind == ck_user);
4301
4302 /* Find the end of the second conversion sequence. */
4303 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4304 {
4305 /* The entire sequence is a user-conversion sequence. */
4306 (*t)->user_conv_p = true;
4307 if (bad)
4308 (*t)->bad_p = true;
4309 }
4310
4311 if ((*t)->rvaluedness_matches_p)
4312 /* We're binding a reference directly to the result of the conversion.
4313 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4314 type, but we want it back. */
4315 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4316
4317 /* Replace the identity conversion with the user conversion
4318 sequence. */
4319 *t = user_seq;
4320
4321 return std_seq;
4322}
4323
4324/* Handle overload resolution for initializing an object of class type from
4325 an initializer list. First we look for a suitable constructor that
4326 takes a std::initializer_list; if we don't find one, we then look for a
4327 non-list constructor.
4328
4329 Parameters are as for add_candidates, except that the arguments are in
4330 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4331 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4332
4333static void
4334add_list_candidates (tree fns, tree first_arg,
4335 const vec<tree, va_gc> *args, tree totype,
4336 tree explicit_targs, bool template_only,
4337 tree conversion_path, tree access_path,
4338 int flags,
4339 struct z_candidate **candidates,
4340 tsubst_flags_t complain)
4341{
4342 gcc_assert (*candidates == NULL);
4343
4344 /* We're looking for a ctor for list-initialization. */
4345 flags |= LOOKUP_LIST_INIT_CTOR;
4346 /* And we don't allow narrowing conversions. We also use this flag to
4347 avoid the copy constructor call for copy-list-initialization. */
4348 flags |= LOOKUP_NO_NARROWING;
4349
4350 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4351 tree init_list = (*args)[nart];
4352
4353 /* Always use the default constructor if the list is empty (DR 990). */
4354 if (CONSTRUCTOR_NELTS (init_list) == 0
4355 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4356 ;
4357 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4358 && !CP_AGGREGATE_TYPE_P (totype))
4359 {
4360 if (complain & tf_error)
4361 error ("designated initializers cannot be used with a "
4362 "non-aggregate type %qT", totype);
4363 return;
4364 }
4365 /* If the class has a list ctor, try passing the list as a single
4366 argument first, but only consider list ctors. */
4367 else if (TYPE_HAS_LIST_CTOR (totype))
4368 {
4369 flags |= LOOKUP_LIST_ONLY;
4370 add_candidates (fns, first_arg, args, NULL_TREE,
4371 explicit_targs, template_only, conversion_path,
4372 access_path, flags, candidates, complain);
4373 if (any_strictly_viable (cands: *candidates))
4374 return;
4375 }
4376
4377 /* Expand the CONSTRUCTOR into a new argument vec. */
4378 vec<tree, va_gc> *new_args;
4379 vec_alloc (v&: new_args, nelems: nart + CONSTRUCTOR_NELTS (init_list));
4380 for (unsigned i = 0; i < nart; ++i)
4381 new_args->quick_push (obj: (*args)[i]);
4382 new_args = append_ctor_to_tree_vector (new_args, init_list);
4383
4384 /* We aren't looking for list-ctors anymore. */
4385 flags &= ~LOOKUP_LIST_ONLY;
4386 /* We allow more user-defined conversions within an init-list. */
4387 flags &= ~LOOKUP_NO_CONVERSION;
4388
4389 add_candidates (fns, first_arg, new_args, NULL_TREE,
4390 explicit_targs, template_only, conversion_path,
4391 access_path, flags, candidates, complain);
4392}
4393
4394/* Given C(std::initializer_list<A>), return A. */
4395
4396static tree
4397list_ctor_element_type (tree fn)
4398{
4399 gcc_checking_assert (is_list_ctor (fn));
4400
4401 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4402 parm = non_reference (TREE_VALUE (parm));
4403 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4404}
4405
4406/* If EXPR is a braced-init-list where the elements all decay to the same type,
4407 return that type. */
4408
4409static tree
4410braced_init_element_type (tree expr)
4411{
4412 if (TREE_CODE (expr) == CONSTRUCTOR
4413 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4414 return TREE_TYPE (TREE_TYPE (expr));
4415 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4416 return NULL_TREE;
4417
4418 tree elttype = NULL_TREE;
4419 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4420 {
4421 tree type = TREE_TYPE (e.value);
4422 type = type_decays_to (type);
4423 if (!elttype)
4424 elttype = type;
4425 else if (!same_type_p (type, elttype))
4426 return NULL_TREE;
4427 }
4428 return elttype;
4429}
4430
4431/* True iff EXPR contains any temporaries with non-trivial destruction.
4432
4433 ??? Also ignore classes with non-trivial but no-op destruction other than
4434 std::allocator? */
4435
4436static bool
4437has_non_trivial_temporaries (tree expr)
4438{
4439 auto_vec<tree*> temps;
4440 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4441 for (tree *p : temps)
4442 {
4443 tree t = TREE_TYPE (*p);
4444 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4445 && !is_std_allocator (t))
4446 return true;
4447 }
4448 return false;
4449}
4450
4451/* Return number of initialized elements in CTOR. */
4452
4453unsigned HOST_WIDE_INT
4454count_ctor_elements (tree ctor)
4455{
4456 unsigned HOST_WIDE_INT len = 0;
4457 for (constructor_elt &e: CONSTRUCTOR_ELTS (ctor))
4458 if (TREE_CODE (e.value) == RAW_DATA_CST)
4459 len += RAW_DATA_LENGTH (e.value);
4460 else
4461 ++len;
4462 return len;
4463}
4464
4465/* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4466 return INIT as an array (of its own type) so the caller can initialize the
4467 target array in a loop. */
4468
4469static tree
4470maybe_init_list_as_array (tree elttype, tree init)
4471{
4472 /* Only do this if the array can go in rodata but not once converted. */
4473 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4474 return NULL_TREE;
4475 tree init_elttype = braced_init_element_type (expr: init);
4476 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4477 return NULL_TREE;
4478
4479 /* Check with a stub expression to weed out special cases, and check whether
4480 we call the same function for direct-init as copy-list-init. */
4481 conversion_obstack_sentinel cos;
4482 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4483 tree arg = build_stub_object (init_elttype);
4484 conversion *c = implicit_conversion (to: elttype, from: init_elttype, expr: arg, c_cast_p: false,
4485 LOOKUP_NORMAL, complain: tf_none);
4486 if (c && c->kind == ck_rvalue)
4487 c = next_conversion (conv: c);
4488 if (!c || c->kind != ck_user)
4489 return NULL_TREE;
4490 /* Check that we actually can perform the conversion. */
4491 if (convert_like (c, arg, tf_none) == error_mark_node)
4492 /* Let the normal code give the error. */
4493 return NULL_TREE;
4494
4495 /* A glvalue initializer might be significant to a reference constructor
4496 or conversion operator. */
4497 if (!DECL_CONSTRUCTOR_P (c->cand->fn)
4498 || (TYPE_REF_P (TREE_VALUE
4499 (FUNCTION_FIRST_USER_PARMTYPE (c->cand->fn)))))
4500 for (auto &ce : CONSTRUCTOR_ELTS (init))
4501 if (non_mergeable_glvalue_p (ce.value))
4502 return NULL_TREE;
4503
4504 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4505 conversion *fc = implicit_conversion (to: elttype, from: init_elttype, expr: first, c_cast_p: false,
4506 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4507 complain: tf_none);
4508 if (fc && fc->kind == ck_rvalue)
4509 fc = next_conversion (conv: fc);
4510 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4511 return NULL_TREE;
4512 first = convert_like (fc, first, tf_none);
4513 if (first == error_mark_node)
4514 /* Let the normal code give the error. */
4515 return NULL_TREE;
4516
4517 /* Don't do this if the conversion would be constant. */
4518 first = maybe_constant_init (first);
4519 if (TREE_CONSTANT (first))
4520 return NULL_TREE;
4521
4522 /* We can't do this if the conversion creates temporaries that need
4523 to live until the whole array is initialized. */
4524 if (has_non_trivial_temporaries (expr: first))
4525 return NULL_TREE;
4526
4527 /* We can't do this if copying from the initializer_list would be
4528 ill-formed. */
4529 tree copy_argtypes = make_tree_vec (1);
4530 TREE_VEC_ELT (copy_argtypes, 0)
4531 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4532 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4533 return NULL_TREE;
4534
4535 unsigned HOST_WIDE_INT len = count_ctor_elements (ctor: init);
4536 tree arr = build_array_of_n_type (init_elttype, len);
4537 arr = finish_compound_literal (arr, init, tf_none);
4538 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4539 return arr;
4540}
4541
4542/* If we were going to call e.g. vector(initializer_list<string>) starting
4543 with a list of string-literals (which is inefficient, see PR105838),
4544 instead build an array of const char* and pass it to the range constructor.
4545 But only do this for standard library types, where we can assume the
4546 transformation makes sense.
4547
4548 Really the container classes should have initializer_list<U> constructors to
4549 get the same effect more simply; this is working around that lack. */
4550
4551static tree
4552maybe_init_list_as_range (tree fn, tree expr)
4553{
4554 if (!processing_template_decl
4555 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4556 && is_list_ctor (fn)
4557 && decl_in_std_namespace_p (fn))
4558 {
4559 tree to = list_ctor_element_type (fn);
4560 if (tree init = maybe_init_list_as_array (elttype: to, init: expr))
4561 {
4562 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4563 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4564 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4565 nelts, tf_none);
4566 begin = cp_build_compound_expr (init, begin, tf_none);
4567 return build_constructor_va (init_list_type_node, 2,
4568 NULL_TREE, begin, NULL_TREE, end);
4569 }
4570 }
4571
4572 return NULL_TREE;
4573}
4574
4575/* Returns the best overload candidate to perform the requested
4576 conversion. This function is used for three the overloading situations
4577 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4578 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4579 per [dcl.init.ref], so we ignore temporary bindings. */
4580
4581static struct z_candidate *
4582build_user_type_conversion_1 (tree totype, tree expr, int flags,
4583 tsubst_flags_t complain)
4584{
4585 struct z_candidate *candidates, *cand;
4586 tree fromtype;
4587 tree ctors = NULL_TREE;
4588 tree conv_fns = NULL_TREE;
4589 conversion *conv = NULL;
4590 tree first_arg = NULL_TREE;
4591 vec<tree, va_gc> *args = NULL;
4592 bool any_viable_p;
4593 int convflags;
4594
4595 if (!expr)
4596 return NULL;
4597
4598 fromtype = TREE_TYPE (expr);
4599
4600 /* We represent conversion within a hierarchy using RVALUE_CONV and
4601 BASE_CONV, as specified by [over.best.ics]; these become plain
4602 constructor calls, as specified in [dcl.init]. */
4603 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4604 || !DERIVED_FROM_P (totype, fromtype));
4605
4606 if (CLASS_TYPE_P (totype))
4607 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4608 creating a garbage BASELINK; constructors can't be inherited. */
4609 ctors = get_class_binding (totype, complete_ctor_identifier);
4610
4611 tree to_nonref = non_reference (totype);
4612 if (MAYBE_CLASS_TYPE_P (fromtype))
4613 {
4614 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4615 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4616 && DERIVED_FROM_P (to_nonref, fromtype)))
4617 {
4618 /* [class.conv.fct] A conversion function is never used to
4619 convert a (possibly cv-qualified) object to the (possibly
4620 cv-qualified) same object type (or a reference to it), to a
4621 (possibly cv-qualified) base class of that type (or a
4622 reference to it)... */
4623 }
4624 else
4625 conv_fns = lookup_conversions (fromtype);
4626 }
4627
4628 candidates = 0;
4629 flags |= LOOKUP_NO_CONVERSION;
4630 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4631 flags |= LOOKUP_NO_NARROWING;
4632 /* Prevent add_candidates from treating a non-strictly viable candidate
4633 as unviable. */
4634 complain |= tf_conv;
4635
4636 /* It's OK to bind a temporary for converting constructor arguments, but
4637 not in converting the return value of a conversion operator. */
4638 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4639 | (flags & LOOKUP_NO_NARROWING));
4640 flags &= ~LOOKUP_NO_TEMP_BIND;
4641
4642 if (ctors)
4643 {
4644 int ctorflags = flags;
4645
4646 first_arg = build_dummy_object (totype);
4647
4648 /* We should never try to call the abstract or base constructor
4649 from here. */
4650 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4651 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4652
4653 args = make_tree_vector_single (expr);
4654 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4655 {
4656 /* List-initialization. */
4657 add_list_candidates (fns: ctors, first_arg, args, totype, NULL_TREE,
4658 template_only: false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4659 flags: ctorflags, candidates: &candidates, complain);
4660 }
4661 else
4662 {
4663 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4664 TYPE_BINFO (totype), TYPE_BINFO (totype),
4665 ctorflags, &candidates, complain);
4666 }
4667
4668 for (cand = candidates; cand; cand = cand->next)
4669 {
4670 cand->second_conv = build_identity_conv (type: totype, NULL_TREE);
4671
4672 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4673 set, then this is copy-initialization. In that case, "The
4674 result of the call is then used to direct-initialize the
4675 object that is the destination of the copy-initialization."
4676 [dcl.init]
4677
4678 We represent this in the conversion sequence with an
4679 rvalue conversion, which means a constructor call. */
4680 if (!TYPE_REF_P (totype)
4681 && cxx_dialect < cxx17
4682 && (flags & LOOKUP_ONLYCONVERTING)
4683 && !(convflags & LOOKUP_NO_TEMP_BIND))
4684 cand->second_conv
4685 = build_conv (code: ck_rvalue, type: totype, from: cand->second_conv);
4686 }
4687 }
4688
4689 if (conv_fns)
4690 {
4691 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4692 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4693 else
4694 first_arg = expr;
4695 }
4696
4697 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4698 {
4699 tree conversion_path = TREE_PURPOSE (conv_fns);
4700 struct z_candidate *old_candidates;
4701
4702 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4703 would need an addional user-defined conversion, i.e. if the return
4704 type differs in class-ness from the desired type. So we avoid
4705 considering operator bool when calling a copy constructor.
4706
4707 This optimization avoids the failure in PR97600, and is allowed by
4708 [temp.inst]/9: "If the function selected by overload resolution can be
4709 determined without instantiating a class template definition, it is
4710 unspecified whether that instantiation actually takes place." */
4711 tree convtype = non_reference (TREE_TYPE (conv_fns));
4712 if ((flags & LOOKUP_NO_CONVERSION)
4713 && !WILDCARD_TYPE_P (convtype)
4714 && (CLASS_TYPE_P (to_nonref)
4715 != CLASS_TYPE_P (convtype)))
4716 continue;
4717
4718 /* If we are called to convert to a reference type, we are trying to
4719 find a direct binding, so don't even consider temporaries. If
4720 we don't find a direct binding, the caller will try again to
4721 look for a temporary binding. */
4722 if (TYPE_REF_P (totype))
4723 convflags |= LOOKUP_NO_TEMP_BIND;
4724
4725 old_candidates = candidates;
4726 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4727 NULL_TREE, false,
4728 conversion_path, TYPE_BINFO (fromtype),
4729 flags, &candidates, complain);
4730
4731 for (cand = candidates; cand != old_candidates; cand = cand->next)
4732 {
4733 if (cand->viable == 0)
4734 /* Already rejected, don't change to -1. */
4735 continue;
4736
4737 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4738 conversion *ics
4739 = implicit_conversion (to: totype,
4740 from: rettype,
4741 expr: 0,
4742 /*c_cast_p=*/false, flags: convflags,
4743 complain);
4744
4745 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4746 copy-initialization. In that case, "The result of the
4747 call is then used to direct-initialize the object that is
4748 the destination of the copy-initialization." [dcl.init]
4749
4750 We represent this in the conversion sequence with an
4751 rvalue conversion, which means a constructor call. But
4752 don't add a second rvalue conversion if there's already
4753 one there. Which there really shouldn't be, but it's
4754 harmless since we'd add it here anyway. */
4755 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4756 && !(convflags & LOOKUP_NO_TEMP_BIND))
4757 ics = build_conv (code: ck_rvalue, type: totype, from: ics);
4758
4759 cand->second_conv = ics;
4760
4761 if (!ics)
4762 {
4763 cand->viable = 0;
4764 cand->reason = arg_conversion_rejection (NULL_TREE, n_arg: -2,
4765 from: rettype, to: totype,
4766 EXPR_LOCATION (expr));
4767 }
4768 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4769 /* Limit this to non-templates for now (PR90546). */
4770 && !cand->template_decl
4771 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4772 {
4773 /* If we are called to convert to a reference type, we are trying
4774 to find a direct binding per [over.match.ref], so rvaluedness
4775 must match for non-functions. */
4776 cand->viable = 0;
4777 }
4778 else if (DECL_NONCONVERTING_P (cand->fn)
4779 && ics->rank > cr_exact)
4780 {
4781 /* 13.3.1.5: For direct-initialization, those explicit
4782 conversion functions that are not hidden within S and
4783 yield type T or a type that can be converted to type T
4784 with a qualification conversion (4.4) are also candidate
4785 functions. */
4786 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4787 I've raised this issue with the committee. --jason 9/2011 */
4788 cand->viable = -1;
4789 cand->reason = explicit_conversion_rejection (from: rettype, to: totype);
4790 }
4791 else if (cand->viable == 1 && ics->bad_p)
4792 {
4793 cand->viable = -1;
4794 cand->reason
4795 = bad_arg_conversion_rejection (NULL_TREE, n_arg: -2,
4796 from: rettype, to: totype,
4797 EXPR_LOCATION (expr));
4798 }
4799 else if (primary_template_specialization_p (cand->fn)
4800 && ics->rank > cr_exact)
4801 {
4802 /* 13.3.3.1.2: If the user-defined conversion is specified by
4803 a specialization of a conversion function template, the
4804 second standard conversion sequence shall have exact match
4805 rank. */
4806 cand->viable = -1;
4807 cand->reason = template_conversion_rejection (from: rettype, to: totype);
4808 }
4809 }
4810 }
4811
4812 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
4813 if (!any_viable_p)
4814 {
4815 if (args)
4816 release_tree_vector (args);
4817 return NULL;
4818 }
4819
4820 cand = tourney (candidates, complain);
4821 if (cand == NULL)
4822 {
4823 if (complain & tf_error)
4824 {
4825 auto_diagnostic_group d;
4826 error_at (cp_expr_loc_or_input_loc (t: expr),
4827 "conversion from %qH to %qI is ambiguous",
4828 fromtype, totype);
4829 print_z_candidates (loc: location_of (expr), candidates);
4830 }
4831
4832 cand = candidates; /* any one will do */
4833 cand->second_conv = build_ambiguous_conv (type: totype, expr);
4834 cand->second_conv->user_conv_p = true;
4835 if (!any_strictly_viable (cands: candidates))
4836 cand->second_conv->bad_p = true;
4837 if (flags & LOOKUP_ONLYCONVERTING)
4838 cand->second_conv->need_temporary_p = true;
4839 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4840 ambiguous conversion is no worse than another user-defined
4841 conversion. */
4842
4843 return cand;
4844 }
4845
4846 /* Maybe pass { } as iterators instead of an initializer_list. */
4847 if (tree iters = maybe_init_list_as_range (fn: cand->fn, expr))
4848 if (z_candidate *cand2
4849 = build_user_type_conversion_1 (totype, expr: iters, flags, complain: tf_none))
4850 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4851 {
4852 cand = cand2;
4853 expr = iters;
4854 }
4855
4856 tree convtype;
4857 if (!DECL_CONSTRUCTOR_P (cand->fn))
4858 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4859 else if (cand->second_conv->kind == ck_rvalue)
4860 /* DR 5: [in the first step of copy-initialization]...if the function
4861 is a constructor, the call initializes a temporary of the
4862 cv-unqualified version of the destination type. */
4863 convtype = cv_unqualified (totype);
4864 else
4865 convtype = totype;
4866 /* Build the user conversion sequence. */
4867 conv = build_conv
4868 (code: ck_user,
4869 type: convtype,
4870 from: build_identity_conv (TREE_TYPE (expr), expr));
4871 conv->cand = cand;
4872 if (cand->viable == -1)
4873 conv->bad_p = true;
4874
4875 /* Remember that this was a list-initialization. */
4876 if (flags & LOOKUP_NO_NARROWING)
4877 conv->check_narrowing = true;
4878
4879 /* Combine it with the second conversion sequence. */
4880 cand->second_conv = merge_conversion_sequences (user_seq: conv,
4881 std_seq: cand->second_conv);
4882
4883 return cand;
4884}
4885
4886/* Wrapper for above. */
4887
4888tree
4889build_user_type_conversion (tree totype, tree expr, int flags,
4890 tsubst_flags_t complain)
4891{
4892 struct z_candidate *cand;
4893 tree ret;
4894
4895 auto_cond_timevar tv (TV_OVERLOAD);
4896
4897 conversion_obstack_sentinel cos;
4898
4899 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4900
4901 if (cand)
4902 {
4903 if (cand->second_conv->kind == ck_ambig)
4904 ret = error_mark_node;
4905 else
4906 {
4907 expr = convert_like (cand->second_conv, expr, complain);
4908 ret = convert_from_reference (expr);
4909 }
4910 }
4911 else
4912 ret = NULL_TREE;
4913
4914 return ret;
4915}
4916
4917/* Give a helpful diagnostic when implicit_conversion fails. */
4918
4919static void
4920implicit_conversion_error (location_t loc, tree type, tree expr,
4921 int flags)
4922{
4923 tsubst_flags_t complain = tf_warning_or_error;
4924
4925 /* If expr has unknown type, then it is an overloaded function.
4926 Call instantiate_type to get good error messages. */
4927 if (TREE_TYPE (expr) == unknown_type_node)
4928 instantiate_type (type, expr, complain);
4929 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4930 /* We gave an error. */;
4931 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4932 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4933 && !CP_AGGREGATE_TYPE_P (type))
4934 error_at (loc, "designated initializers cannot be used with a "
4935 "non-aggregate type %qT", type);
4936 else
4937 {
4938 auto_diagnostic_group d;
4939 if (is_stub_object (expr))
4940 /* The expression is generated by a trait check, we don't have
4941 a useful location to highlight the label. */
4942 error_at (loc, "could not convert %qH to %qI",
4943 TREE_TYPE (expr), type);
4944 else
4945 {
4946 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4947 gcc_rich_location rich_loc (loc, &label,
4948 highlight_colors::percent_h);
4949 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4950 expr, TREE_TYPE (expr), type);
4951 }
4952 maybe_show_nonconverting_candidate (type, TREE_TYPE (expr), expr, flags);
4953 }
4954}
4955
4956/* Worker for build_converted_constant_expr. */
4957
4958static tree
4959build_converted_constant_expr_internal (tree type, tree expr,
4960 int flags, tsubst_flags_t complain)
4961{
4962 conversion *conv;
4963 tree t;
4964 location_t loc = cp_expr_loc_or_input_loc (t: expr);
4965
4966 if (error_operand_p (t: expr))
4967 return error_mark_node;
4968
4969 conversion_obstack_sentinel cos;
4970
4971 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
4972 /*c_cast_p=*/false, flags, complain);
4973
4974 /* A converted constant expression of type T is an expression, implicitly
4975 converted to type T, where the converted expression is a constant
4976 expression and the implicit conversion sequence contains only
4977
4978 * user-defined conversions,
4979 * lvalue-to-rvalue conversions (7.1),
4980 * array-to-pointer conversions (7.2),
4981 * function-to-pointer conversions (7.3),
4982 * qualification conversions (7.5),
4983 * integral promotions (7.6),
4984 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4985 * null pointer conversions (7.11) from std::nullptr_t,
4986 * null member pointer conversions (7.12) from std::nullptr_t, and
4987 * function pointer conversions (7.13),
4988
4989 and where the reference binding (if any) binds directly. */
4990
4991 for (conversion *c = conv;
4992 c && c->kind != ck_identity;
4993 c = next_conversion (conv: c))
4994 {
4995 switch (c->kind)
4996 {
4997 /* A conversion function is OK. If it isn't constexpr, we'll
4998 complain later that the argument isn't constant. */
4999 case ck_user:
5000 /* List-initialization is OK. */
5001 case ck_aggr:
5002 /* The lvalue-to-rvalue conversion is OK. */
5003 case ck_rvalue:
5004 /* Array-to-pointer and function-to-pointer. */
5005 case ck_lvalue:
5006 /* Function pointer conversions. */
5007 case ck_fnptr:
5008 /* Qualification conversions. */
5009 case ck_qual:
5010 break;
5011
5012 case ck_ref_bind:
5013 if (c->need_temporary_p)
5014 {
5015 if (complain & tf_error)
5016 error_at (loc, "initializing %qH with %qI in converted "
5017 "constant expression does not bind directly",
5018 type, next_conversion (conv: c)->type);
5019 conv = NULL;
5020 }
5021 break;
5022
5023 case ck_base:
5024 case ck_pmem:
5025 case ck_ptr:
5026 case ck_std:
5027 t = next_conversion (conv: c)->type;
5028 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
5029 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5030 /* Integral promotion or conversion. */
5031 break;
5032 if (NULLPTR_TYPE_P (t))
5033 /* Conversion from nullptr to pointer or pointer-to-member. */
5034 break;
5035
5036 if (complain & tf_error)
5037 error_at (loc, "conversion from %qH to %qI in a "
5038 "converted constant expression", t, type);
5039 /* fall through. */
5040
5041 default:
5042 conv = NULL;
5043 break;
5044 }
5045 }
5046
5047 /* Avoid confusing convert_nontype_argument by introducing
5048 a redundant conversion to the same reference type. */
5049 if (conv && conv->kind == ck_ref_bind
5050 && REFERENCE_REF_P (expr))
5051 {
5052 tree ref = TREE_OPERAND (expr, 0);
5053 if (same_type_p (type, TREE_TYPE (ref)))
5054 return ref;
5055 }
5056
5057 if (conv)
5058 {
5059 /* Don't copy a class in a template. */
5060 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
5061 && processing_template_decl)
5062 conv = next_conversion (conv);
5063
5064 /* Issuing conversion warnings for value-dependent expressions is
5065 likely too noisy. */
5066 warning_sentinel w (warn_conversion);
5067 conv->check_narrowing = true;
5068 conv->check_narrowing_const_only = true;
5069 expr = convert_like (conv, expr, complain);
5070 }
5071 else
5072 {
5073 if (complain & tf_error)
5074 implicit_conversion_error (loc, type, expr, flags);
5075 expr = error_mark_node;
5076 }
5077
5078 return expr;
5079}
5080
5081/* Subroutine of convert_nontype_argument.
5082
5083 EXPR is an expression used in a context that requires a converted
5084 constant-expression, such as a template non-type parameter. Do any
5085 necessary conversions (that are permitted for converted
5086 constant-expressions) to convert it to the desired type.
5087
5088 This function doesn't consider explicit conversion functions. If
5089 you mean to use "a contextually converted constant expression of type
5090 bool", use build_converted_constant_bool_expr.
5091
5092 If conversion is successful, returns the converted expression;
5093 otherwise, returns error_mark_node. */
5094
5095tree
5096build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
5097{
5098 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
5099 complain);
5100}
5101
5102/* Used to create "a contextually converted constant expression of type
5103 bool". This differs from build_converted_constant_expr in that it
5104 also considers explicit conversion functions. */
5105
5106tree
5107build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
5108{
5109 return build_converted_constant_expr_internal (boolean_type_node, expr,
5110 LOOKUP_NORMAL, complain);
5111}
5112
5113/* Do any initial processing on the arguments to a function call. */
5114
5115vec<tree, va_gc> *
5116resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
5117{
5118 unsigned int ix;
5119 tree arg;
5120
5121 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
5122 {
5123 if (error_operand_p (t: arg))
5124 return NULL;
5125 else if (VOID_TYPE_P (TREE_TYPE (arg)))
5126 {
5127 if (complain & tf_error)
5128 error_at (cp_expr_loc_or_input_loc (t: arg),
5129 "invalid use of void expression");
5130 return NULL;
5131 }
5132 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
5133 return NULL;
5134
5135 /* Force auto deduction now. Omit tf_warning to avoid redundant
5136 deprecated warning on deprecated-14.C. */
5137 if (!mark_single_function (arg, complain & ~tf_warning))
5138 return NULL;
5139 }
5140 return args;
5141}
5142
5143/* Perform overload resolution on FN, which is called with the ARGS.
5144
5145 Return the candidate function selected by overload resolution, or
5146 NULL if the event that overload resolution failed. In the case
5147 that overload resolution fails, *CANDIDATES will be the set of
5148 candidates considered, and ANY_VIABLE_P will be set to true or
5149 false to indicate whether or not any of the candidates were
5150 viable.
5151
5152 The ARGS should already have gone through RESOLVE_ARGS before this
5153 function is called. */
5154
5155static struct z_candidate *
5156perform_overload_resolution (tree fn,
5157 const vec<tree, va_gc> *args,
5158 struct z_candidate **candidates,
5159 bool *any_viable_p, tsubst_flags_t complain)
5160{
5161 struct z_candidate *cand;
5162 tree explicit_targs;
5163 int template_only;
5164
5165 auto_cond_timevar tv (TV_OVERLOAD);
5166
5167 explicit_targs = NULL_TREE;
5168 template_only = 0;
5169
5170 *candidates = NULL;
5171 *any_viable_p = true;
5172
5173 /* Check FN. */
5174 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
5175
5176 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5177 {
5178 explicit_targs = TREE_OPERAND (fn, 1);
5179 fn = TREE_OPERAND (fn, 0);
5180 template_only = 1;
5181 }
5182
5183 /* Add the various candidate functions. */
5184 add_candidates (fn, NULL_TREE, args, NULL_TREE,
5185 explicit_targs, template_only,
5186 /*conversion_path=*/NULL_TREE,
5187 /*access_path=*/NULL_TREE,
5188 LOOKUP_NORMAL,
5189 candidates, complain);
5190
5191 *candidates = splice_viable (cands: *candidates, strict_p: false, any_viable_p);
5192 if (*any_viable_p)
5193 cand = tourney (*candidates, complain);
5194 else
5195 cand = NULL;
5196
5197 return cand;
5198}
5199
5200/* Print an error message about being unable to build a call to FN with
5201 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
5202 be located; CANDIDATES is a possibly empty list of such
5203 functions. */
5204
5205static void
5206print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
5207 struct z_candidate *candidates)
5208{
5209 tree targs = NULL_TREE;
5210 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5211 {
5212 targs = TREE_OPERAND (fn, 1);
5213 fn = TREE_OPERAND (fn, 0);
5214 }
5215 tree name = OVL_NAME (fn);
5216 location_t loc = location_of (name);
5217 if (targs)
5218 name = lookup_template_function (name, targs);
5219
5220 auto_diagnostic_group d;
5221 if (!any_strictly_viable (cands: candidates))
5222 error_at (loc, "no matching function for call to %<%D(%A)%>",
5223 name, build_tree_list_vec (args));
5224 else
5225 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
5226 name, build_tree_list_vec (args));
5227 if (candidates)
5228 print_z_candidates (loc, candidates);
5229}
5230
5231/* Perform overload resolution on the set of deduction guides DGUIDES
5232 using ARGS. Returns the selected deduction guide, or error_mark_node
5233 if overload resolution fails. */
5234
5235tree
5236perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
5237 tsubst_flags_t complain)
5238{
5239 z_candidate *candidates;
5240 bool any_viable_p;
5241 tree result;
5242
5243 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
5244
5245 conversion_obstack_sentinel cos;
5246
5247 z_candidate *cand = perform_overload_resolution (fn: dguides, args, candidates: &candidates,
5248 any_viable_p: &any_viable_p, complain);
5249 if (!cand)
5250 {
5251 if (complain & tf_error)
5252 print_error_for_call_failure (fn: dguides, args, candidates);
5253 result = error_mark_node;
5254 }
5255 else
5256 result = cand->fn;
5257
5258 return result;
5259}
5260
5261/* Return an expression for a call to FN (a namespace-scope function,
5262 or a static member function) with the ARGS. This may change
5263 ARGS. */
5264
5265tree
5266build_new_function_call (tree fn, vec<tree, va_gc> **args,
5267 tsubst_flags_t complain)
5268{
5269 struct z_candidate *candidates, *cand;
5270 bool any_viable_p;
5271 tree result;
5272
5273 if (args != NULL && *args != NULL)
5274 {
5275 *args = resolve_args (args: *args, complain);
5276 if (*args == NULL)
5277 return error_mark_node;
5278 }
5279
5280 if (flag_tm)
5281 tm_malloc_replacement (fn);
5282
5283 conversion_obstack_sentinel cos;
5284
5285 cand = perform_overload_resolution (fn, args: *args, candidates: &candidates, any_viable_p: &any_viable_p,
5286 complain);
5287
5288 if (!cand)
5289 {
5290 if (complain & tf_error)
5291 {
5292 // If there is a single (non-viable) function candidate,
5293 // let the error be diagnosed by cp_build_function_call_vec.
5294 if (!any_viable_p && candidates && ! candidates->next
5295 && TREE_CODE (candidates->fn) == FUNCTION_DECL
5296 /* A template-id callee consisting of a single (ignored)
5297 non-template candidate needs to be diagnosed the
5298 ordinary way. */
5299 && (TREE_CODE (fn) != TEMPLATE_ID_EXPR
5300 || candidates->template_decl))
5301 return cp_build_function_call_vec (candidates->fn, args, complain);
5302
5303 // Otherwise, emit notes for non-viable candidates.
5304 print_error_for_call_failure (fn, args: *args, candidates);
5305 }
5306 result = error_mark_node;
5307 }
5308 else
5309 {
5310 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5311 }
5312
5313 if (flag_coroutines
5314 && result
5315 && TREE_CODE (result) == CALL_EXPR
5316 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5317 == BUILT_IN_NORMAL)
5318 result = coro_validate_builtin_call (result);
5319
5320 return result;
5321}
5322
5323/* Build a call to a global operator new. FNNAME is the name of the
5324 operator (either "operator new" or "operator new[]") and ARGS are
5325 the arguments provided. This may change ARGS. *SIZE points to the
5326 total number of bytes required by the allocation, and is updated if
5327 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5328 be used. If this function determines that no cookie should be
5329 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5330 is not NULL_TREE, it is evaluated before calculating the final
5331 array size, and if it fails, the array size is replaced with
5332 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5333 is non-NULL, it will be set, upon return, to the allocation
5334 function called. */
5335
5336tree
5337build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5338 tree *size, tree *cookie_size,
5339 tree align_arg, tree size_check,
5340 tree *fn, tsubst_flags_t complain)
5341{
5342 tree original_size = *size;
5343 tree fns;
5344 struct z_candidate *candidates;
5345 struct z_candidate *cand = NULL;
5346 bool any_viable_p;
5347
5348 if (fn)
5349 *fn = NULL_TREE;
5350 /* Set to (size_t)-1 if the size check fails. */
5351 if (size_check != NULL_TREE)
5352 {
5353 tree errval = TYPE_MAX_VALUE (sizetype);
5354 if (cxx_dialect >= cxx11 && flag_exceptions)
5355 errval = throw_bad_array_new_length ();
5356 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5357 original_size, errval);
5358 }
5359 vec_safe_insert (v&: *args, ix: 0, obj: *size);
5360 *args = resolve_args (args: *args, complain);
5361 if (*args == NULL)
5362 return error_mark_node;
5363
5364 conversion_obstack_sentinel cos;
5365
5366 /* Based on:
5367
5368 [expr.new]
5369
5370 If this lookup fails to find the name, or if the allocated type
5371 is not a class type, the allocation function's name is looked
5372 up in the global scope.
5373
5374 we disregard block-scope declarations of "operator new". */
5375 fns = lookup_qualified_name (global_namespace, name: fnname);
5376
5377 if (align_arg)
5378 {
5379 vec<tree, va_gc>* align_args
5380 = vec_copy_and_insert (*args, align_arg, 1);
5381 cand = perform_overload_resolution (fn: fns, args: align_args, candidates: &candidates,
5382 any_viable_p: &any_viable_p, complain: tf_none);
5383 if (cand)
5384 *args = align_args;
5385 /* If no aligned allocation function matches, try again without the
5386 alignment. */
5387 }
5388
5389 /* Figure out what function is being called. */
5390 if (!cand)
5391 cand = perform_overload_resolution (fn: fns, args: *args, candidates: &candidates, any_viable_p: &any_viable_p,
5392 complain);
5393
5394 /* If no suitable function could be found, issue an error message
5395 and give up. */
5396 if (!cand)
5397 {
5398 if (complain & tf_error)
5399 print_error_for_call_failure (fn: fns, args: *args, candidates);
5400 return error_mark_node;
5401 }
5402
5403 /* If a cookie is required, add some extra space. Whether
5404 or not a cookie is required cannot be determined until
5405 after we know which function was called. */
5406 if (*cookie_size)
5407 {
5408 bool use_cookie = true;
5409 tree arg_types;
5410
5411 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5412 /* Skip the size_t parameter. */
5413 arg_types = TREE_CHAIN (arg_types);
5414 /* Check the remaining parameters (if any). */
5415 if (arg_types
5416 && TREE_CHAIN (arg_types) == void_list_node
5417 && same_type_p (TREE_VALUE (arg_types),
5418 ptr_type_node))
5419 use_cookie = false;
5420 /* If we need a cookie, adjust the number of bytes allocated. */
5421 if (use_cookie)
5422 {
5423 /* Update the total size. */
5424 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5425 if (size_check)
5426 {
5427 /* Set to (size_t)-1 if the size check fails. */
5428 gcc_assert (size_check != NULL_TREE);
5429 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5430 *size, TYPE_MAX_VALUE (sizetype));
5431 }
5432 /* Update the argument list to reflect the adjusted size. */
5433 (**args)[0] = *size;
5434 }
5435 else
5436 *cookie_size = NULL_TREE;
5437 }
5438
5439 /* Tell our caller which function we decided to call. */
5440 if (fn)
5441 *fn = cand->fn;
5442
5443 /* Build the CALL_EXPR. */
5444 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5445
5446 /* Set this flag for all callers of this function. In addition to
5447 new-expressions, this is called for allocating coroutine state; treat
5448 that as an implicit new-expression. */
5449 tree call = extract_call_expr (ret);
5450 if (TREE_CODE (call) == CALL_EXPR)
5451 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5452
5453 return ret;
5454}
5455
5456/* Evaluate side-effects from OBJ before evaluating call
5457 to FN in RESULT expression.
5458 This is for expressions of the form `obj->fn(...)'
5459 where `fn' turns out to be a static member function and
5460 `obj' needs to be evaluated. `fn' could be also static operator[]
5461 or static operator(), in which cases the source expression
5462 would be `obj[...]' or `obj(...)'. */
5463
5464tree
5465keep_unused_object_arg (tree result, tree obj, tree fn)
5466{
5467 if (result == NULL_TREE
5468 || result == error_mark_node
5469 || DECL_OBJECT_MEMBER_FUNCTION_P (fn)
5470 || !TREE_SIDE_EFFECTS (obj))
5471 return result;
5472
5473 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5474 volatile. */
5475 tree a = obj;
5476 if (TREE_THIS_VOLATILE (a))
5477 a = build_this (obj: a);
5478 if (TREE_SIDE_EFFECTS (a))
5479 return cp_build_compound_expr (a, result, tf_error);
5480 return result;
5481}
5482
5483/* Build a new call to operator(). This may change ARGS. */
5484
5485tree
5486build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5487{
5488 struct z_candidate *candidates = 0, *cand;
5489 tree fns, convs, first_mem_arg = NULL_TREE;
5490 bool any_viable_p;
5491 tree result = NULL_TREE;
5492
5493 auto_cond_timevar tv (TV_OVERLOAD);
5494
5495 obj = mark_lvalue_use (obj);
5496
5497 if (error_operand_p (t: obj))
5498 return error_mark_node;
5499
5500 tree type = TREE_TYPE (obj);
5501
5502 obj = prep_operand (obj);
5503
5504 if (TYPE_PTRMEMFUNC_P (type))
5505 {
5506 if (complain & tf_error)
5507 /* It's no good looking for an overloaded operator() on a
5508 pointer-to-member-function. */
5509 error ("pointer-to-member function %qE cannot be called without "
5510 "an object; consider using %<.*%> or %<->*%>", obj);
5511 return error_mark_node;
5512 }
5513
5514 if (TYPE_BINFO (type))
5515 {
5516 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5517 if (fns == error_mark_node)
5518 return error_mark_node;
5519 }
5520 else
5521 fns = NULL_TREE;
5522
5523 if (args != NULL && *args != NULL)
5524 {
5525 *args = resolve_args (args: *args, complain);
5526 if (*args == NULL)
5527 return error_mark_node;
5528 }
5529
5530 conversion_obstack_sentinel cos;
5531
5532 if (fns)
5533 {
5534 first_mem_arg = obj;
5535
5536 add_candidates (BASELINK_FUNCTIONS (fns),
5537 first_mem_arg, *args, NULL_TREE,
5538 NULL_TREE, false,
5539 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5540 LOOKUP_NORMAL, &candidates, complain);
5541 }
5542
5543 bool any_call_ops = candidates != nullptr;
5544
5545 convs = lookup_conversions (type);
5546
5547 for (; convs; convs = TREE_CHAIN (convs))
5548 {
5549 tree totype = TREE_TYPE (convs);
5550
5551 if (TYPE_PTRFN_P (totype)
5552 || TYPE_REFFN_P (totype)
5553 || (TYPE_REF_P (totype)
5554 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5555 for (tree fn : ovl_range (TREE_VALUE (convs)))
5556 {
5557 if (DECL_NONCONVERTING_P (fn))
5558 continue;
5559
5560 if (TREE_CODE (fn) == TEMPLATE_DECL)
5561 {
5562 /* Making this work broke PR 71117 and 85118, so until the
5563 committee resolves core issue 2189, let's disable this
5564 candidate if there are any call operators. */
5565 if (any_call_ops)
5566 continue;
5567
5568 add_template_conv_candidate
5569 (candidates: &candidates, tmpl: fn, obj, arglist: *args, return_type: totype,
5570 /*access_path=*/NULL_TREE,
5571 /*conversion_path=*/NULL_TREE, complain);
5572 }
5573 else
5574 add_conv_candidate (candidates: &candidates, fn, obj,
5575 arglist: *args, /*conversion_path=*/NULL_TREE,
5576 /*access_path=*/NULL_TREE, complain);
5577 }
5578 }
5579
5580 /* Be strict here because if we choose a bad conversion candidate, the
5581 errors we get won't mention the call context. */
5582 candidates = splice_viable (cands: candidates, strict_p: true, any_viable_p: &any_viable_p);
5583 if (!any_viable_p)
5584 {
5585 if (complain & tf_error)
5586 {
5587 auto_diagnostic_group d;
5588 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5589 build_tree_list_vec (*args));
5590 print_z_candidates (loc: location_of (TREE_TYPE (obj)), candidates);
5591 }
5592 result = error_mark_node;
5593 }
5594 else
5595 {
5596 cand = tourney (candidates, complain);
5597 if (cand == 0)
5598 {
5599 if (complain & tf_error)
5600 {
5601 auto_diagnostic_group d;
5602 error ("call of %<(%T) (%A)%> is ambiguous",
5603 TREE_TYPE (obj), build_tree_list_vec (*args));
5604 print_z_candidates (loc: location_of (TREE_TYPE (obj)), candidates);
5605 }
5606 result = error_mark_node;
5607 }
5608 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5609 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5610 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5611 {
5612 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5613 /* In an expression of the form `a()' where cand->fn
5614 which is operator() turns out to be a static member function,
5615 `a' is none-the-less evaluated. */
5616 result = keep_unused_object_arg (result, obj, fn: cand->fn);
5617 }
5618 else
5619 {
5620 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5621 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5622 -1, complain);
5623 else
5624 {
5625 gcc_checking_assert (TYPE_P (cand->fn));
5626 obj = convert_like (cand->convs[0], obj, complain);
5627 }
5628 obj = convert_from_reference (obj);
5629 result = cp_build_function_call_vec (obj, args, complain);
5630 }
5631 }
5632
5633 return result;
5634}
5635
5636/* Subroutine for preparing format strings suitable for the error
5637 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5638 and SUFFIX. */
5639
5640static const char *
5641concat_op_error_string (bool match, const char *errmsg, const char *suffix)
5642{
5643 return concat (match
5644 ? G_("ambiguous overload for ")
5645 : G_("no match for "),
5646 errmsg, suffix, nullptr);
5647}
5648
5649/* Called by op_error to prepare format strings suitable for the error
5650 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5651 and a suffix (controlled by NTYPES). */
5652
5653static const char *
5654op_error_string (const char *errmsg, int ntypes, bool match)
5655{
5656 const char *suffix;
5657 if (ntypes == 3)
5658 suffix = G_(" (operand types are %qT, %qT, and %qT)");
5659 else if (ntypes == 2)
5660 suffix = G_(" (operand types are %qT and %qT)");
5661 else
5662 suffix = G_(" (operand type is %qT)");
5663 return concat_op_error_string (match, errmsg, suffix);
5664}
5665
5666/* Similar to op_error_string, but a special-case for binary ops that
5667 use %e for the args, rather than %qT. */
5668
5669static const char *
5670binop_error_string (const char *errmsg, bool match)
5671{
5672 return concat_op_error_string (match, errmsg,
5673 G_(" (operand types are %e and %e)"));
5674}
5675
5676static void
5677op_error (const op_location_t &loc,
5678 enum tree_code code, enum tree_code code2,
5679 tree arg1, tree arg2, tree arg3, bool match)
5680{
5681 bool assop = code == MODIFY_EXPR;
5682 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5683
5684 switch (code)
5685 {
5686 case COND_EXPR:
5687 if (flag_diagnostics_show_caret)
5688 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5689 ntypes: 3, match),
5690 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5691 else
5692 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5693 "in %<%E ? %E : %E%>"), ntypes: 3, match),
5694 arg1, arg2, arg3,
5695 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5696 break;
5697
5698 case POSTINCREMENT_EXPR:
5699 case POSTDECREMENT_EXPR:
5700 if (flag_diagnostics_show_caret)
5701 error_at (loc, op_error_string (G_("%<operator%s%>"), ntypes: 1, match),
5702 opname, TREE_TYPE (arg1));
5703 else
5704 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5705 ntypes: 1, match),
5706 opname, arg1, opname, TREE_TYPE (arg1));
5707 break;
5708
5709 case ARRAY_REF:
5710 if (flag_diagnostics_show_caret)
5711 error_at (loc, op_error_string (G_("%<operator[]%>"), ntypes: 2, match),
5712 TREE_TYPE (arg1), TREE_TYPE (arg2));
5713 else
5714 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5715 ntypes: 2, match),
5716 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5717 break;
5718
5719 case REALPART_EXPR:
5720 case IMAGPART_EXPR:
5721 if (flag_diagnostics_show_caret)
5722 error_at (loc, op_error_string (G_("%qs"), ntypes: 1, match),
5723 opname, TREE_TYPE (arg1));
5724 else
5725 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), ntypes: 1, match),
5726 opname, opname, arg1, TREE_TYPE (arg1));
5727 break;
5728
5729 case CO_AWAIT_EXPR:
5730 if (flag_diagnostics_show_caret)
5731 error_at (loc, op_error_string (G_("%<operator %s%>"), ntypes: 1, match),
5732 opname, TREE_TYPE (arg1));
5733 else
5734 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5735 ntypes: 1, match),
5736 opname, opname, arg1, TREE_TYPE (arg1));
5737 break;
5738
5739 default:
5740 if (arg2)
5741 if (flag_diagnostics_show_caret)
5742 {
5743 binary_op_rich_location richloc (loc, arg1, arg2, true);
5744 pp_markup::element_quoted_type element_0
5745 (TREE_TYPE (arg1), highlight_colors::lhs);
5746 pp_markup::element_quoted_type element_1
5747 (TREE_TYPE (arg2), highlight_colors::rhs);
5748 error_at (&richloc,
5749 binop_error_string (G_("%<operator%s%>"), match),
5750 opname, &element_0, &element_1);
5751 }
5752 else
5753 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5754 ntypes: 2, match),
5755 opname, arg1, opname, arg2,
5756 TREE_TYPE (arg1), TREE_TYPE (arg2));
5757 else
5758 if (flag_diagnostics_show_caret)
5759 error_at (loc, op_error_string (G_("%<operator%s%>"), ntypes: 1, match),
5760 opname, TREE_TYPE (arg1));
5761 else
5762 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5763 ntypes: 1, match),
5764 opname, opname, arg1, TREE_TYPE (arg1));
5765 break;
5766 }
5767}
5768
5769/* Return the implicit conversion sequence that could be used to
5770 convert E1 to E2 in [expr.cond]. */
5771
5772static conversion *
5773conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5774{
5775 tree t1 = non_reference (TREE_TYPE (e1));
5776 tree t2 = non_reference (TREE_TYPE (e2));
5777 conversion *conv;
5778 bool good_base;
5779
5780 /* [expr.cond]
5781
5782 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5783 implicitly converted (clause _conv_) to the type "lvalue reference to
5784 T2", subject to the constraint that in the conversion the
5785 reference must bind directly (_dcl.init.ref_) to an lvalue.
5786
5787 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5788 implicitly converted to the type "rvalue reference to T2", subject to
5789 the constraint that the reference must bind directly. */
5790 if (glvalue_p (e2))
5791 {
5792 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5793 conv = implicit_conversion (to: rtype,
5794 from: t1,
5795 expr: e1,
5796 /*c_cast_p=*/false,
5797 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5798 |LOOKUP_ONLYCONVERTING,
5799 complain);
5800 if (conv && !conv->bad_p)
5801 return conv;
5802 }
5803
5804 /* If E2 is a prvalue or if neither of the conversions above can be done
5805 and at least one of the operands has (possibly cv-qualified) class
5806 type: */
5807 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5808 return NULL;
5809
5810 /* [expr.cond]
5811
5812 If E1 and E2 have class type, and the underlying class types are
5813 the same or one is a base class of the other: E1 can be converted
5814 to match E2 if the class of T2 is the same type as, or a base
5815 class of, the class of T1, and the cv-qualification of T2 is the
5816 same cv-qualification as, or a greater cv-qualification than, the
5817 cv-qualification of T1. If the conversion is applied, E1 is
5818 changed to an rvalue of type T2 that still refers to the original
5819 source class object (or the appropriate subobject thereof). */
5820 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5821 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5822 {
5823 if (good_base && at_least_as_qualified_p (t2, t1))
5824 {
5825 conv = build_identity_conv (type: t1, expr: e1);
5826 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5827 TYPE_MAIN_VARIANT (t2)))
5828 conv = build_conv (code: ck_base, type: t2, from: conv);
5829 else
5830 conv = build_conv (code: ck_rvalue, type: t2, from: conv);
5831 return conv;
5832 }
5833 else
5834 return NULL;
5835 }
5836 else
5837 /* [expr.cond]
5838
5839 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5840 converted to the type that expression E2 would have if E2 were
5841 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5842 return implicit_conversion (to: t2, from: t1, expr: e1, /*c_cast_p=*/false,
5843 LOOKUP_IMPLICIT, complain);
5844}
5845
5846/* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5847 arguments to the conditional expression. */
5848
5849tree
5850build_conditional_expr (const op_location_t &loc,
5851 tree arg1, tree arg2, tree arg3,
5852 tsubst_flags_t complain)
5853{
5854 tree arg2_type;
5855 tree arg3_type;
5856 tree result = NULL_TREE;
5857 tree result_type = NULL_TREE;
5858 tree semantic_result_type = NULL_TREE;
5859 bool is_glvalue = true;
5860 struct z_candidate *candidates = 0;
5861 struct z_candidate *cand;
5862 tree orig_arg2, orig_arg3;
5863
5864 auto_cond_timevar tv (TV_OVERLOAD);
5865
5866 /* As a G++ extension, the second argument to the conditional can be
5867 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5868 c'.) If the second operand is omitted, make sure it is
5869 calculated only once. */
5870 if (!arg2)
5871 {
5872 if (complain & tf_error)
5873 pedwarn (loc, OPT_Wpedantic,
5874 "ISO C++ forbids omitting the middle term of "
5875 "a %<?:%> expression");
5876
5877 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5878 warn_for_omitted_condop (loc, arg1);
5879
5880 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5881 if (glvalue_p (arg1))
5882 {
5883 arg1 = cp_stabilize_reference (arg1);
5884 arg2 = arg1 = prevent_lifetime_extension (arg1);
5885 }
5886 else if (TREE_CODE (arg1) == TARGET_EXPR)
5887 /* arg1 can't be a prvalue result of the conditional
5888 expression, since it needs to be materialized for the
5889 conversion to bool, so treat it as an xvalue in arg2. */
5890 arg2 = move (TARGET_EXPR_SLOT (arg1));
5891 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5892 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5893 cp_save_expr (TREE_OPERAND (arg1, 0)));
5894 else
5895 arg2 = arg1 = cp_save_expr (arg1);
5896 }
5897
5898 /* If something has already gone wrong, just pass that fact up the
5899 tree. */
5900 if (error_operand_p (t: arg1)
5901 || error_operand_p (t: arg2)
5902 || error_operand_p (t: arg3))
5903 return error_mark_node;
5904
5905 conversion_obstack_sentinel cos;
5906
5907 orig_arg2 = arg2;
5908 orig_arg3 = arg3;
5909
5910 if (gnu_vector_type_p (TREE_TYPE (arg1))
5911 && (VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1))
5912 || VECTOR_BOOLEAN_TYPE_P (TREE_TYPE (arg1))))
5913 {
5914 tree arg1_type = TREE_TYPE (arg1);
5915
5916 /* If arg1 is another cond_expr choosing between -1 and 0,
5917 then we can use its comparison. It may help to avoid
5918 additional comparison, produce more accurate diagnostics
5919 and enables folding. */
5920 if (TREE_CODE (arg1) == VEC_COND_EXPR
5921 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5922 && integer_zerop (TREE_OPERAND (arg1, 2)))
5923 arg1 = TREE_OPERAND (arg1, 0);
5924
5925 arg1 = force_rvalue (arg1, complain);
5926 arg2 = force_rvalue (arg2, complain);
5927 arg3 = force_rvalue (arg3, complain);
5928
5929 /* force_rvalue can return error_mark on valid arguments. */
5930 if (error_operand_p (t: arg1)
5931 || error_operand_p (t: arg2)
5932 || error_operand_p (t: arg3))
5933 return error_mark_node;
5934
5935 arg2_type = TREE_TYPE (arg2);
5936 arg3_type = TREE_TYPE (arg3);
5937
5938 if (!VECTOR_TYPE_P (arg2_type)
5939 && !VECTOR_TYPE_P (arg3_type))
5940 {
5941 /* Rely on the error messages of the scalar version. */
5942 tree scal = build_conditional_expr (loc, integer_one_node,
5943 arg2: orig_arg2, arg3: orig_arg3, complain);
5944 if (scal == error_mark_node)
5945 return error_mark_node;
5946 tree stype = TREE_TYPE (scal);
5947 tree ctype = TREE_TYPE (arg1_type);
5948 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5949 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5950 {
5951 if (complain & tf_error)
5952 error_at (loc, "inferred scalar type %qT is not an integer or "
5953 "floating-point type of the same size as %qT", stype,
5954 COMPARISON_CLASS_P (arg1)
5955 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5956 : ctype);
5957 return error_mark_node;
5958 }
5959
5960 tree vtype = build_opaque_vector_type (stype,
5961 TYPE_VECTOR_SUBPARTS (node: arg1_type));
5962 /* We could pass complain & tf_warning to unsafe_conversion_p,
5963 but the warnings (like Wsign-conversion) have already been
5964 given by the scalar build_conditional_expr_1. We still check
5965 unsafe_conversion_p to forbid truncating long long -> float. */
5966 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5967 {
5968 if (complain & tf_error)
5969 error_at (loc, "conversion of scalar %qH to vector %qI "
5970 "involves truncation", arg2_type, vtype);
5971 return error_mark_node;
5972 }
5973 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5974 {
5975 if (complain & tf_error)
5976 error_at (loc, "conversion of scalar %qH to vector %qI "
5977 "involves truncation", arg3_type, vtype);
5978 return error_mark_node;
5979 }
5980
5981 arg2 = cp_convert (stype, arg2, complain);
5982 arg2 = save_expr (arg2);
5983 arg2 = build_vector_from_val (vtype, arg2);
5984 arg2_type = vtype;
5985 arg3 = cp_convert (stype, arg3, complain);
5986 arg3 = save_expr (arg3);
5987 arg3 = build_vector_from_val (vtype, arg3);
5988 arg3_type = vtype;
5989 }
5990
5991 if ((gnu_vector_type_p (type: arg2_type) && !VECTOR_TYPE_P (arg3_type))
5992 || (gnu_vector_type_p (type: arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5993 {
5994 enum stv_conv convert_flag =
5995 scalar_to_vector (loc, code: VEC_COND_EXPR, op0: arg2, op1: arg3,
5996 complain & tf_error);
5997
5998 switch (convert_flag)
5999 {
6000 case stv_error:
6001 return error_mark_node;
6002 case stv_firstarg:
6003 {
6004 arg2 = save_expr (arg2);
6005 arg2 = convert (TREE_TYPE (arg3_type), arg2);
6006 arg2 = build_vector_from_val (arg3_type, arg2);
6007 arg2_type = TREE_TYPE (arg2);
6008 break;
6009 }
6010 case stv_secondarg:
6011 {
6012 arg3 = save_expr (arg3);
6013 arg3 = convert (TREE_TYPE (arg2_type), arg3);
6014 arg3 = build_vector_from_val (arg2_type, arg3);
6015 arg3_type = TREE_TYPE (arg3);
6016 break;
6017 }
6018 default:
6019 break;
6020 }
6021 }
6022
6023 if (!gnu_vector_type_p (type: arg2_type)
6024 || !gnu_vector_type_p (type: arg3_type)
6025 || !same_type_p (arg2_type, arg3_type)
6026 || maybe_ne (a: TYPE_VECTOR_SUBPARTS (node: arg1_type),
6027 b: TYPE_VECTOR_SUBPARTS (node: arg2_type))
6028 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
6029 {
6030 if (complain & tf_error)
6031 error_at (loc,
6032 "incompatible vector types in conditional expression: "
6033 "%qT, %qT and %qT", TREE_TYPE (arg1),
6034 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
6035 return error_mark_node;
6036 }
6037
6038 if (!COMPARISON_CLASS_P (arg1))
6039 {
6040 tree cmp_type = truth_type_for (arg1_type);
6041 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
6042 }
6043 return build3_loc (loc, code: VEC_COND_EXPR, type: arg2_type, arg0: arg1, arg1: arg2, arg2: arg3);
6044 }
6045
6046 /* [expr.cond]
6047
6048 The first expression is implicitly converted to bool (clause
6049 _conv_). */
6050 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
6051 LOOKUP_NORMAL);
6052 if (error_operand_p (t: arg1))
6053 return error_mark_node;
6054
6055 arg2_type = unlowered_expr_type (arg2);
6056 arg3_type = unlowered_expr_type (arg3);
6057
6058 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
6059 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
6060 && (TREE_CODE (arg2_type) == INTEGER_TYPE
6061 || SCALAR_FLOAT_TYPE_P (arg2_type)
6062 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
6063 && (TREE_CODE (arg3_type) == INTEGER_TYPE
6064 || SCALAR_FLOAT_TYPE_P (arg3_type)
6065 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
6066 {
6067 semantic_result_type
6068 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6069 if (semantic_result_type == error_mark_node)
6070 {
6071 tree t1 = arg2_type;
6072 tree t2 = arg3_type;
6073 if (TREE_CODE (t1) == COMPLEX_TYPE)
6074 t1 = TREE_TYPE (t1);
6075 if (TREE_CODE (t2) == COMPLEX_TYPE)
6076 t2 = TREE_TYPE (t2);
6077 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6078 && SCALAR_FLOAT_TYPE_P (t2)
6079 && (extended_float_type_p (t1)
6080 || extended_float_type_p (t2))
6081 && cp_compare_floating_point_conversion_ranks
6082 (t1, t2) == 3);
6083 if (complain & tf_error)
6084 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6085 "have unordered conversion rank",
6086 arg2_type, arg3_type);
6087 return error_mark_node;
6088 }
6089 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
6090 {
6091 arg2 = TREE_OPERAND (arg2, 0);
6092 arg2_type = TREE_TYPE (arg2);
6093 }
6094 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
6095 {
6096 arg3 = TREE_OPERAND (arg3, 0);
6097 arg3_type = TREE_TYPE (arg3);
6098 }
6099 }
6100
6101 /* [expr.cond]
6102
6103 If either the second or the third operand has type (possibly
6104 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
6105 array-to-pointer (_conv.array_), and function-to-pointer
6106 (_conv.func_) standard conversions are performed on the second
6107 and third operands. */
6108 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
6109 {
6110 /* 'void' won't help in resolving an overloaded expression on the
6111 other side, so require it to resolve by itself. */
6112 if (arg2_type == unknown_type_node)
6113 {
6114 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
6115 arg2_type = TREE_TYPE (arg2);
6116 }
6117 if (arg3_type == unknown_type_node)
6118 {
6119 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
6120 arg3_type = TREE_TYPE (arg3);
6121 }
6122
6123 /* [expr.cond]
6124
6125 One of the following shall hold:
6126
6127 --The second or the third operand (but not both) is a
6128 throw-expression (_except.throw_); the result is of the type
6129 and value category of the other.
6130
6131 --Both the second and the third operands have type void; the
6132 result is of type void and is a prvalue. */
6133 if (TREE_CODE (arg2) == THROW_EXPR
6134 && TREE_CODE (arg3) != THROW_EXPR)
6135 {
6136 result_type = arg3_type;
6137 is_glvalue = glvalue_p (arg3);
6138 }
6139 else if (TREE_CODE (arg2) != THROW_EXPR
6140 && TREE_CODE (arg3) == THROW_EXPR)
6141 {
6142 result_type = arg2_type;
6143 is_glvalue = glvalue_p (arg2);
6144 }
6145 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
6146 {
6147 result_type = void_type_node;
6148 is_glvalue = false;
6149 }
6150 else
6151 {
6152 if (complain & tf_error)
6153 {
6154 if (VOID_TYPE_P (arg2_type))
6155 error_at (cp_expr_loc_or_loc (t: arg3, or_loc: loc),
6156 "second operand to the conditional operator "
6157 "is of type %<void%>, but the third operand is "
6158 "neither a throw-expression nor of type %<void%>");
6159 else
6160 error_at (cp_expr_loc_or_loc (t: arg2, or_loc: loc),
6161 "third operand to the conditional operator "
6162 "is of type %<void%>, but the second operand is "
6163 "neither a throw-expression nor of type %<void%>");
6164 }
6165 return error_mark_node;
6166 }
6167
6168 goto valid_operands;
6169 }
6170 /* [expr.cond]
6171
6172 Otherwise, if the second and third operand have different types,
6173 and either has (possibly cv-qualified) class type, or if both are
6174 glvalues of the same value category and the same type except for
6175 cv-qualification, an attempt is made to convert each of those operands
6176 to the type of the other. */
6177 else if (!same_type_p (arg2_type, arg3_type)
6178 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
6179 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
6180 arg3_type)
6181 && glvalue_p (arg2) && glvalue_p (arg3)
6182 && lvalue_p (arg2) == lvalue_p (arg3))))
6183 {
6184 conversion *conv2;
6185 conversion *conv3;
6186 bool converted = false;
6187
6188 conv2 = conditional_conversion (e1: arg2, e2: arg3, complain);
6189 conv3 = conditional_conversion (e1: arg3, e2: arg2, complain);
6190
6191 /* [expr.cond]
6192
6193 If both can be converted, or one can be converted but the
6194 conversion is ambiguous, the program is ill-formed. If
6195 neither can be converted, the operands are left unchanged and
6196 further checking is performed as described below. If exactly
6197 one conversion is possible, that conversion is applied to the
6198 chosen operand and the converted operand is used in place of
6199 the original operand for the remainder of this section. */
6200 if ((conv2 && !conv2->bad_p
6201 && conv3 && !conv3->bad_p)
6202 || (conv2 && conv2->kind == ck_ambig)
6203 || (conv3 && conv3->kind == ck_ambig))
6204 {
6205 if (complain & tf_error)
6206 {
6207 error_at (loc, "operands to %<?:%> have different types "
6208 "%qT and %qT",
6209 arg2_type, arg3_type);
6210 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
6211 inform (loc, " and each type can be converted to the other");
6212 else if (conv2 && conv2->kind == ck_ambig)
6213 convert_like (conv2, arg2, complain);
6214 else
6215 convert_like (conv3, arg3, complain);
6216 }
6217 result = error_mark_node;
6218 }
6219 else if (conv2 && !conv2->bad_p)
6220 {
6221 arg2 = convert_like (conv2, arg2, complain);
6222 arg2 = convert_from_reference (arg2);
6223 arg2_type = TREE_TYPE (arg2);
6224 /* Even if CONV2 is a valid conversion, the result of the
6225 conversion may be invalid. For example, if ARG3 has type
6226 "volatile X", and X does not have a copy constructor
6227 accepting a "volatile X&", then even if ARG2 can be
6228 converted to X, the conversion will fail. */
6229 if (error_operand_p (t: arg2))
6230 result = error_mark_node;
6231 converted = true;
6232 }
6233 else if (conv3 && !conv3->bad_p)
6234 {
6235 arg3 = convert_like (conv3, arg3, complain);
6236 arg3 = convert_from_reference (arg3);
6237 arg3_type = TREE_TYPE (arg3);
6238 if (error_operand_p (t: arg3))
6239 result = error_mark_node;
6240 converted = true;
6241 }
6242
6243 if (result)
6244 return result;
6245
6246 /* If, after the conversion, both operands have class type,
6247 treat the cv-qualification of both operands as if it were the
6248 union of the cv-qualification of the operands.
6249
6250 The standard is not clear about what to do in this
6251 circumstance. For example, if the first operand has type
6252 "const X" and the second operand has a user-defined
6253 conversion to "volatile X", what is the type of the second
6254 operand after this step? Making it be "const X" (matching
6255 the first operand) seems wrong, as that discards the
6256 qualification without actually performing a copy. Leaving it
6257 as "volatile X" seems wrong as that will result in the
6258 conditional expression failing altogether, even though,
6259 according to this step, the one operand could be converted to
6260 the type of the other. */
6261 if (converted
6262 && CLASS_TYPE_P (arg2_type)
6263 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
6264 arg2_type = arg3_type =
6265 cp_build_qualified_type (arg2_type,
6266 cp_type_quals (arg2_type)
6267 | cp_type_quals (arg3_type));
6268 }
6269
6270 /* [expr.cond]
6271
6272 If the second and third operands are glvalues of the same value
6273 category and have the same type, the result is of that type and
6274 value category. */
6275 if (((lvalue_p (arg2) && lvalue_p (arg3))
6276 || (xvalue_p (arg2) && xvalue_p (arg3)))
6277 && same_type_p (arg2_type, arg3_type))
6278 {
6279 result_type = arg2_type;
6280 goto valid_operands;
6281 }
6282
6283 /* [expr.cond]
6284
6285 Otherwise, the result is an rvalue. If the second and third
6286 operand do not have the same type, and either has (possibly
6287 cv-qualified) class type, overload resolution is used to
6288 determine the conversions (if any) to be applied to the operands
6289 (_over.match.oper_, _over.built_). */
6290 is_glvalue = false;
6291 if (!same_type_p (arg2_type, arg3_type)
6292 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6293 {
6294 releasing_vec args;
6295 conversion *conv;
6296 bool any_viable_p;
6297
6298 /* Rearrange the arguments so that add_builtin_candidate only has
6299 to know about two args. In build_builtin_candidate, the
6300 arguments are unscrambled. */
6301 args->quick_push (obj: arg2);
6302 args->quick_push (obj: arg3);
6303 args->quick_push (obj: arg1);
6304 add_builtin_candidates (candidates: &candidates,
6305 code: COND_EXPR,
6306 code2: NOP_EXPR,
6307 fnname: ovl_op_identifier (isass: false, code: COND_EXPR),
6308 argv: args,
6309 LOOKUP_NORMAL, complain);
6310
6311 /* [expr.cond]
6312
6313 If the overload resolution fails, the program is
6314 ill-formed. */
6315 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
6316 if (!any_viable_p)
6317 {
6318 if (complain & tf_error)
6319 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6320 arg2_type, arg3_type);
6321 return error_mark_node;
6322 }
6323 cand = tourney (candidates, complain);
6324 if (!cand)
6325 {
6326 if (complain & tf_error)
6327 {
6328 auto_diagnostic_group d;
6329 op_error (loc, code: COND_EXPR, code2: NOP_EXPR, arg1, arg2, arg3, match: false);
6330 print_z_candidates (loc, candidates);
6331 }
6332 return error_mark_node;
6333 }
6334
6335 /* [expr.cond]
6336
6337 Otherwise, the conversions thus determined are applied, and
6338 the converted operands are used in place of the original
6339 operands for the remainder of this section. */
6340 conv = cand->convs[0];
6341 arg1 = convert_like (conv, arg1, complain);
6342 conv = cand->convs[1];
6343 arg2 = convert_like (conv, arg2, complain);
6344 arg2_type = TREE_TYPE (arg2);
6345 conv = cand->convs[2];
6346 arg3 = convert_like (conv, arg3, complain);
6347 arg3_type = TREE_TYPE (arg3);
6348 }
6349
6350 /* [expr.cond]
6351
6352 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6353 and function-to-pointer (_conv.func_) standard conversions are
6354 performed on the second and third operands.
6355
6356 We need to force the lvalue-to-rvalue conversion here for class types,
6357 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6358 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6359 regions. */
6360
6361 arg2 = force_rvalue (arg2, complain);
6362 if (!CLASS_TYPE_P (arg2_type))
6363 arg2_type = TREE_TYPE (arg2);
6364
6365 arg3 = force_rvalue (arg3, complain);
6366 if (!CLASS_TYPE_P (arg3_type))
6367 arg3_type = TREE_TYPE (arg3);
6368
6369 if (arg2 == error_mark_node || arg3 == error_mark_node)
6370 return error_mark_node;
6371
6372 /* [expr.cond]
6373
6374 After those conversions, one of the following shall hold:
6375
6376 --The second and third operands have the same type; the result is of
6377 that type. */
6378 if (same_type_p (arg2_type, arg3_type))
6379 result_type = arg2_type;
6380 /* [expr.cond]
6381
6382 --The second and third operands have arithmetic or enumeration
6383 type; the usual arithmetic conversions are performed to bring
6384 them to a common type, and the result is of that type. */
6385 else if ((ARITHMETIC_TYPE_P (arg2_type)
6386 || UNSCOPED_ENUM_P (arg2_type))
6387 && (ARITHMETIC_TYPE_P (arg3_type)
6388 || UNSCOPED_ENUM_P (arg3_type)))
6389 {
6390 /* A conditional expression between a floating-point
6391 type and an integer type should convert the integer type to
6392 the evaluation format of the floating-point type, with
6393 possible excess precision. */
6394 tree eptype2 = arg2_type;
6395 tree eptype3 = arg3_type;
6396 tree eptype;
6397 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6398 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6399 {
6400 eptype3 = eptype;
6401 if (!semantic_result_type)
6402 semantic_result_type
6403 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6404 }
6405 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6406 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6407 {
6408 eptype2 = eptype;
6409 if (!semantic_result_type)
6410 semantic_result_type
6411 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6412 }
6413 result_type = type_after_usual_arithmetic_conversions (eptype2,
6414 eptype3);
6415 if (result_type == error_mark_node)
6416 {
6417 tree t1 = eptype2;
6418 tree t2 = eptype3;
6419 if (TREE_CODE (t1) == COMPLEX_TYPE)
6420 t1 = TREE_TYPE (t1);
6421 if (TREE_CODE (t2) == COMPLEX_TYPE)
6422 t2 = TREE_TYPE (t2);
6423 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6424 && SCALAR_FLOAT_TYPE_P (t2)
6425 && (extended_float_type_p (t1)
6426 || extended_float_type_p (t2))
6427 && cp_compare_floating_point_conversion_ranks
6428 (t1, t2) == 3);
6429 if (complain & tf_error)
6430 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6431 "have unordered conversion rank",
6432 eptype2, eptype3);
6433 return error_mark_node;
6434 }
6435 if (semantic_result_type == error_mark_node)
6436 {
6437 tree t1 = arg2_type;
6438 tree t2 = arg3_type;
6439 if (TREE_CODE (t1) == COMPLEX_TYPE)
6440 t1 = TREE_TYPE (t1);
6441 if (TREE_CODE (t2) == COMPLEX_TYPE)
6442 t2 = TREE_TYPE (t2);
6443 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6444 && SCALAR_FLOAT_TYPE_P (t2)
6445 && (extended_float_type_p (t1)
6446 || extended_float_type_p (t2))
6447 && cp_compare_floating_point_conversion_ranks
6448 (t1, t2) == 3);
6449 if (complain & tf_error)
6450 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6451 "have unordered conversion rank",
6452 arg2_type, arg3_type);
6453 return error_mark_node;
6454 }
6455
6456 if (complain & tf_warning)
6457 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6458 "implicit conversion from %qH to %qI to "
6459 "match other result of conditional",
6460 loc);
6461
6462 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6463 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6464 {
6465 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (exp: orig_arg2);
6466 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (exp: orig_arg3);
6467 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6468 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6469 && (DECL_CONTEXT (stripped_orig_arg2)
6470 == DECL_CONTEXT (stripped_orig_arg3)))
6471 /* Two enumerators from the same enumeration can have different
6472 types when the enumeration is still being defined. */;
6473 else if (complain & (cxx_dialect >= cxx26
6474 ? tf_warning_or_error : tf_warning))
6475 emit_diagnostic ((cxx_dialect >= cxx26
6476 ? diagnostics::kind::pedwarn
6477 : diagnostics::kind::warning),
6478 loc, OPT_Wenum_compare, "enumerated mismatch "
6479 "in conditional expression: %qT vs %qT",
6480 arg2_type, arg3_type);
6481 else if (cxx_dialect >= cxx26)
6482 return error_mark_node;
6483 }
6484 else if ((((complain & (cxx_dialect >= cxx26
6485 ? tf_warning_or_error : tf_warning))
6486 && warn_deprecated_enum_float_conv)
6487 || (cxx_dialect >= cxx26
6488 && (complain & tf_warning_or_error) == 0))
6489 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6490 && SCALAR_FLOAT_TYPE_P (arg3_type))
6491 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6492 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6493 {
6494 if (cxx_dialect >= cxx26 && (complain & tf_warning_or_error) == 0)
6495 return error_mark_node;
6496 if (cxx_dialect >= cxx26 && TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6497 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6498 "conditional expression between enumeration type "
6499 "%qT and floating-point type %qT", arg2_type, arg3_type);
6500 else if (cxx_dialect >= cxx26)
6501 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6502 "conditional expression between floating-point type "
6503 "%qT and enumeration type %qT", arg2_type, arg3_type);
6504 else if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6505 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6506 "conditional expression between enumeration type "
6507 "%qT and floating-point type %qT is deprecated",
6508 arg2_type, arg3_type);
6509 else
6510 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6511 "conditional expression between floating-point "
6512 "type %qT and enumeration type %qT is deprecated",
6513 arg2_type, arg3_type);
6514 }
6515 else if ((extra_warnings || warn_enum_conversion)
6516 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6517 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6518 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6519 && !same_type_p (arg2_type,
6520 type_promotes_to (arg3_type)))))
6521 {
6522 if (complain & tf_warning)
6523 {
6524 enum opt_code opt = (warn_enum_conversion
6525 ? OPT_Wenum_conversion
6526 : OPT_Wextra);
6527 warning_at (loc, opt, "enumerated and "
6528 "non-enumerated type in conditional expression");
6529 }
6530 }
6531
6532 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6533 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6534 }
6535 /* [expr.cond]
6536
6537 --The second and third operands have pointer type, or one has
6538 pointer type and the other is a null pointer constant; pointer
6539 conversions (_conv.ptr_) and qualification conversions
6540 (_conv.qual_) are performed to bring them to their composite
6541 pointer type (_expr.rel_). The result is of the composite
6542 pointer type.
6543
6544 --The second and third operands have pointer to member type, or
6545 one has pointer to member type and the other is a null pointer
6546 constant; pointer to member conversions (_conv.mem_) and
6547 qualification conversions (_conv.qual_) are performed to bring
6548 them to a common type, whose cv-qualification shall match the
6549 cv-qualification of either the second or the third operand.
6550 The result is of the common type. */
6551 else if ((null_ptr_cst_p (t: arg2)
6552 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6553 || (null_ptr_cst_p (t: arg3)
6554 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6555 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6556 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6557 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6558 {
6559 result_type = composite_pointer_type (loc,
6560 arg2_type, arg3_type, arg2,
6561 arg3, CPO_CONDITIONAL_EXPR,
6562 complain);
6563 if (result_type == error_mark_node)
6564 return error_mark_node;
6565 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6566 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6567 }
6568
6569 if (!result_type)
6570 {
6571 if (complain & tf_error)
6572 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6573 arg2_type, arg3_type);
6574 return error_mark_node;
6575 }
6576
6577 if (arg2 == error_mark_node || arg3 == error_mark_node)
6578 return error_mark_node;
6579
6580 valid_operands:
6581 if (processing_template_decl && is_glvalue)
6582 {
6583 /* Let lvalue_kind know this was a glvalue. */
6584 tree arg = (result_type == arg2_type ? arg2 : arg3);
6585 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6586 }
6587
6588 result = build3_loc (loc, code: COND_EXPR, type: result_type, arg0: arg1, arg1: arg2, arg2: arg3);
6589
6590 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6591 warn here, because the COND_EXPR will be turned into ARG2. */
6592 if (warn_duplicated_branches
6593 && (complain & tf_warning)
6594 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6595 flags: OEP_ADDRESS_OF_SAME_FIELD)))
6596 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6597 "this condition has identical branches");
6598
6599 /* We can't use result_type below, as fold might have returned a
6600 throw_expr. */
6601
6602 if (!is_glvalue)
6603 {
6604 /* Expand both sides into the same slot, hopefully the target of
6605 the ?: expression. We used to check for TARGET_EXPRs here,
6606 but now we sometimes wrap them in NOP_EXPRs so the test would
6607 fail. */
6608 if (CLASS_TYPE_P (TREE_TYPE (result)))
6609 {
6610 result = get_target_expr (result, complain);
6611 /* Tell gimplify_modify_expr_rhs not to strip this in
6612 assignment context: we want both arms to initialize
6613 the same temporary. */
6614 TARGET_EXPR_NO_ELIDE (result) = true;
6615 }
6616 /* If this expression is an rvalue, but might be mistaken for an
6617 lvalue, we must add a NON_LVALUE_EXPR. */
6618 result = rvalue (result);
6619 if (semantic_result_type)
6620 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6621 result);
6622 }
6623 else
6624 {
6625 result = force_paren_expr (result);
6626 gcc_assert (semantic_result_type == NULL_TREE);
6627 }
6628
6629 return result;
6630}
6631
6632/* OPERAND is an operand to an expression. Perform necessary steps
6633 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6634 returned. */
6635
6636static tree
6637prep_operand (tree operand)
6638{
6639 if (operand)
6640 {
6641 if (CLASS_TYPE_P (TREE_TYPE (operand))
6642 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6643 /* Make sure the template type is instantiated now. */
6644 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6645 }
6646
6647 return operand;
6648}
6649
6650/* True iff CONV represents a conversion sequence which no other can be better
6651 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6652 type (including binding to a reference to the same type). This is stronger
6653 than the standard's "identity" category, which also includes reference
6654 bindings that add cv-qualifiers or change rvalueness. */
6655
6656static bool
6657perfect_conversion_p (conversion *conv)
6658{
6659 if (CONVERSION_RANK (conv) != cr_identity)
6660 return false;
6661 if (conv->kind == ck_ref_bind)
6662 {
6663 if (!conv->rvaluedness_matches_p)
6664 return false;
6665 if (!same_type_p (TREE_TYPE (conv->type),
6666 next_conversion (conv)->type))
6667 return false;
6668 }
6669 if (conv->check_narrowing)
6670 /* Brace elision is imperfect. */
6671 return false;
6672 return true;
6673}
6674
6675/* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6676 other candidate can be a better match. Since the template/non-template
6677 tiebreaker comes immediately after the conversion comparison in
6678 [over.match.best], a perfect non-template candidate is better than all
6679 templates. */
6680
6681static bool
6682perfect_candidate_p (z_candidate *cand)
6683{
6684 if (cand->viable < 1)
6685 return false;
6686 /* CWG1402 makes an implicitly deleted move op worse than other
6687 candidates. */
6688 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6689 && move_fn_p (cand->fn))
6690 return false;
6691 int len = cand->num_convs;
6692 for (int i = 0; i < len; ++i)
6693 if (!perfect_conversion_p (conv: cand->convs[i]))
6694 return false;
6695 if (conversion *conv = cand->second_conv)
6696 if (!perfect_conversion_p (conv))
6697 return false;
6698 return true;
6699}
6700
6701/* True iff one of CAND's argument conversions is missing. */
6702
6703static bool
6704missing_conversion_p (const z_candidate *cand)
6705{
6706 for (unsigned i = 0; i < cand->num_convs; ++i)
6707 {
6708 conversion *conv = cand->convs[i];
6709 if (!conv)
6710 return true;
6711 if (conv->kind == ck_deferred_bad)
6712 {
6713 /* We don't know whether this conversion is outright invalid or
6714 just bad, so conservatively assume it's missing. */
6715 gcc_checking_assert (conv->bad_p);
6716 return true;
6717 }
6718 }
6719 return false;
6720}
6721
6722/* Add each of the viable functions in FNS (a FUNCTION_DECL or
6723 OVERLOAD) to the CANDIDATES, returning an updated list of
6724 CANDIDATES. The ARGS are the arguments provided to the call;
6725 if FIRST_ARG is non-null it is the implicit object argument,
6726 otherwise the first element of ARGS is used if needed. The
6727 EXPLICIT_TARGS are explicit template arguments provided.
6728 TEMPLATE_ONLY is true if only template functions should be
6729 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6730 add_function_candidate. */
6731
6732static void
6733add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6734 tree return_type,
6735 tree explicit_targs, bool template_only,
6736 tree conversion_path, tree access_path,
6737 int flags,
6738 struct z_candidate **candidates,
6739 tsubst_flags_t complain)
6740{
6741 tree ctype;
6742 const vec<tree, va_gc> *non_static_args;
6743 bool check_list_ctor = false;
6744 bool check_converting = false;
6745 unification_kind_t strict;
6746 tree ne_context = NULL_TREE;
6747 tree ne_fns = NULL_TREE;
6748
6749 if (!fns)
6750 return;
6751
6752 /* Precalculate special handling of constructors and conversion ops. */
6753 tree fn = OVL_FIRST (fns);
6754 if (DECL_CONV_FN_P (fn))
6755 {
6756 check_list_ctor = false;
6757 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6758 if (flags & LOOKUP_NO_CONVERSION)
6759 /* We're doing return_type(x). */
6760 strict = DEDUCE_CONV;
6761 else
6762 /* We're doing x.operator return_type(). */
6763 strict = DEDUCE_EXACT;
6764 /* [over.match.funcs] For conversion functions, the function
6765 is considered to be a member of the class of the implicit
6766 object argument for the purpose of defining the type of
6767 the implicit object parameter. */
6768 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6769 }
6770 else
6771 {
6772 if (DECL_CONSTRUCTOR_P (fn))
6773 {
6774 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6775 /* For list-initialization we consider explicit constructors
6776 and complain if one is chosen. */
6777 check_converting
6778 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6779 == LOOKUP_ONLYCONVERTING);
6780 }
6781 strict = DEDUCE_CALL;
6782 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6783 }
6784
6785 /* P2468: Check if operator== is a rewrite target with first operand
6786 (*args)[0]; for now just do the lookups. */
6787 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6788 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6789 {
6790 tree ne_name = ovl_op_identifier (isass: false, code: NE_EXPR);
6791 if (DECL_CLASS_SCOPE_P (fn))
6792 {
6793 ne_context = DECL_CONTEXT (fn);
6794 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6795 1, tf_none);
6796 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6797 ne_fns = NULL_TREE;
6798 else
6799 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6800 }
6801 else
6802 {
6803 ne_context = decl_namespace_context (fn);
6804 ne_fns = lookup_qualified_name (scope: ne_context, name: ne_name,
6805 LOOK_want::NORMAL,
6806 /*complain*/false);
6807 if (ne_fns == error_mark_node
6808 || !is_overloaded_fn (ne_fns))
6809 ne_fns = NULL_TREE;
6810 }
6811 }
6812
6813 if (first_arg)
6814 non_static_args = args;
6815 else
6816 /* Delay creating the implicit this parameter until it is needed. */
6817 non_static_args = NULL;
6818
6819 bool seen_strictly_viable = any_strictly_viable (cands: *candidates);
6820 /* If there's a non-template perfect match, we don't need to consider
6821 templates. So check non-templates first. This optimization is only
6822 really needed for the defaulted copy constructor of tuple and the like
6823 (96926), but it seems like we might as well enable it more generally. */
6824 bool seen_perfect = false;
6825 enum { templates, non_templates, either } which = either;
6826 if (template_only)
6827 which = templates;
6828 else /*if (flags & LOOKUP_DEFAULTED)*/
6829 which = non_templates;
6830
6831 /* Template candidates that we'll potentially ignore if the
6832 perfect candidate optimization succeeds. */
6833 z_candidate *ignored_template_cands = nullptr;
6834
6835 /* During overload resolution, we first consider each function under the
6836 assumption that we'll eventually find a strictly viable candidate.
6837 This allows us to circumvent our defacto behavior when checking
6838 argument conversions and shortcut consideration of the candidate
6839 upon encountering the first bad conversion. If this assumption
6840 turns out to be false, and all candidates end up being non-strictly
6841 viable, then we reconsider such candidates under the defacto behavior.
6842 This trick is important for pruning member function overloads according
6843 to their const/ref-qualifiers (since all 'this' conversions are at
6844 worst bad) without breaking -fpermissive. */
6845 z_candidate *bad_cands = nullptr;
6846 bool shortcut_bad_convs = true;
6847
6848 again:
6849 for (tree fn : lkp_range (fns))
6850 {
6851 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6852 {
6853 if (template_only)
6854 add_ignored_candidate (candidates, fn);
6855 continue;
6856 }
6857 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6858 {
6859 add_ignored_candidate (candidates: &ignored_template_cands, fn);
6860 continue;
6861 }
6862 if ((check_converting && DECL_NONCONVERTING_P (fn))
6863 || (check_list_ctor && !is_list_ctor (fn)))
6864 {
6865 add_ignored_candidate (candidates, fn);
6866 continue;
6867 }
6868
6869 tree fn_first_arg = NULL_TREE;
6870 const vec<tree, va_gc> *fn_args = args;
6871
6872 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn))
6873 {
6874 /* Figure out where the object arg comes from. If this
6875 function is a non-static member and we didn't get an
6876 implicit object argument, move it out of args. */
6877 if (first_arg == NULL_TREE)
6878 {
6879 unsigned int ix;
6880 tree arg;
6881 vec<tree, va_gc> *tempvec;
6882 vec_alloc (v&: tempvec, nelems: args->length () - 1);
6883 for (ix = 1; args->iterate (ix, ptr: &arg); ++ix)
6884 tempvec->quick_push (obj: arg);
6885 non_static_args = tempvec;
6886 first_arg = (*args)[0];
6887 }
6888
6889 fn_first_arg = first_arg;
6890 fn_args = non_static_args;
6891 }
6892
6893 /* Don't bother reversing an operator with two identical parameters. */
6894 else if (vec_safe_length (v: args) == 2 && (flags & LOOKUP_REVERSED))
6895 {
6896 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6897 if (same_type_p (TREE_VALUE (parmlist),
6898 TREE_VALUE (TREE_CHAIN (parmlist))))
6899 continue;
6900 }
6901
6902 /* When considering reversed operator==, if there's a corresponding
6903 operator!= in the same scope, it's not a rewrite target. */
6904 if (ne_context)
6905 {
6906 if (TREE_CODE (ne_context) == NAMESPACE_DECL)
6907 {
6908 /* With argument-dependent lookup, fns can span multiple
6909 namespaces; make sure we look in the fn's namespace for a
6910 corresponding operator!=. */
6911 tree fn_ns = decl_namespace_context (fn);
6912 if (fn_ns != ne_context)
6913 {
6914 ne_context = fn_ns;
6915 tree ne_name = ovl_op_identifier (isass: false, code: NE_EXPR);
6916 ne_fns = lookup_qualified_name (scope: ne_context, name: ne_name,
6917 LOOK_want::NORMAL,
6918 /*complain*/false);
6919 if (ne_fns == error_mark_node
6920 || !is_overloaded_fn (ne_fns))
6921 ne_fns = NULL_TREE;
6922 }
6923 }
6924 bool found = false;
6925 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6926 if (0 && !ne.using_p ()
6927 && DECL_NAMESPACE_SCOPE_P (fn)
6928 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6929 /* ??? This kludge excludes inline namespace members for the H
6930 test in spaceship-eq15.C, but I don't see why we would want
6931 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6932 else if (fns_correspond (fn, *ne))
6933 {
6934 found = true;
6935 break;
6936 }
6937 if (found)
6938 continue;
6939 }
6940
6941 /* Do not resolve any non-default function. Only the default version
6942 is resolvable (for the target_version attribute semantics.) */
6943 if (!TARGET_HAS_FMV_TARGET_ATTRIBUTE
6944 && TREE_CODE (fn) == FUNCTION_DECL
6945 && !is_function_default_version (fn))
6946 {
6947 add_ignored_candidate (candidates, fn);
6948 continue;
6949 }
6950
6951 if (TREE_CODE (fn) == TEMPLATE_DECL)
6952 add_template_candidate (candidates,
6953 tmpl: fn,
6954 ctype,
6955 explicit_targs,
6956 first_arg: fn_first_arg,
6957 arglist: fn_args,
6958 return_type,
6959 access_path,
6960 conversion_path,
6961 flags,
6962 strict,
6963 shortcut_bad_convs,
6964 complain);
6965 else
6966 {
6967 add_function_candidate (candidates,
6968 fn,
6969 ctype,
6970 first_arg: fn_first_arg,
6971 args: fn_args,
6972 access_path,
6973 conversion_path,
6974 flags,
6975 NULL,
6976 shortcut_bad_convs,
6977 complain);
6978 if (perfect_candidate_p (cand: *candidates))
6979 seen_perfect = true;
6980 }
6981
6982 z_candidate *cand = *candidates;
6983 if (cand->viable == 1)
6984 seen_strictly_viable = true;
6985
6986 if (cand->viable == -1
6987 && shortcut_bad_convs
6988 && (missing_conversion_p (cand)
6989 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
6990 {
6991 /* This candidate has been tentatively marked non-strictly viable,
6992 and we didn't compute all argument conversions for it (having
6993 stopped at the first bad conversion). Move it to BAD_CANDS to
6994 to fully reconsider later if we don't find any strictly viable
6995 candidates. */
6996 if (complain & (tf_error | tf_conv))
6997 {
6998 *candidates = cand->next;
6999 cand->next = bad_cands;
7000 bad_cands = cand;
7001 }
7002 else
7003 /* But if we're in a SFINAE context, just mark this candidate as
7004 unviable outright and avoid potentially reconsidering it.
7005 This is safe to do because in a SFINAE context, performing a bad
7006 conversion is always an error (even with -fpermissive), so a
7007 non-strictly viable candidate is effectively unviable anyway. */
7008 cand->viable = 0;
7009 }
7010 }
7011 if (which == non_templates && !seen_perfect)
7012 {
7013 which = templates;
7014 ignored_template_cands = nullptr;
7015 goto again;
7016 }
7017 else if (which == templates
7018 && !seen_strictly_viable
7019 && shortcut_bad_convs
7020 && bad_cands)
7021 {
7022 /* None of the candidates are strictly viable, so consider again those
7023 functions in BAD_CANDS, this time without shortcutting bad conversions
7024 so that all their argument conversions are computed. */
7025 which = either;
7026 fns = NULL_TREE;
7027 for (z_candidate *cand = bad_cands; cand; cand = cand->next)
7028 {
7029 tree fn = cand->fn;
7030 if (tree ti = cand->template_decl)
7031 fn = TI_TEMPLATE (ti);
7032 fns = ovl_make (fn, next: fns);
7033 }
7034 shortcut_bad_convs = false;
7035 bad_cands = nullptr;
7036 goto again;
7037 }
7038
7039 if (complain & tf_error)
7040 {
7041 /* Remember any omitted candidates; we may want to print all candidates
7042 as part of overload resolution failure diagnostics. */
7043 for (z_candidate *omitted_cands : { ignored_template_cands, bad_cands })
7044 {
7045 z_candidate **omitted_cands_tail = &omitted_cands;
7046 while (*omitted_cands_tail)
7047 omitted_cands_tail = &(*omitted_cands_tail)->next;
7048 *omitted_cands_tail = *candidates;
7049 *candidates = omitted_cands;
7050 }
7051 }
7052}
7053
7054/* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
7055 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
7056
7057static int
7058op_is_ordered (tree_code code)
7059{
7060 switch (code)
7061 {
7062 // 5. b @= a
7063 case MODIFY_EXPR:
7064 return (flag_strong_eval_order > 1 ? -1 : 0);
7065
7066 // 6. a[b]
7067 case ARRAY_REF:
7068 return (flag_strong_eval_order > 1 ? 1 : 0);
7069
7070 // 1. a.b
7071 // Not overloadable (yet).
7072 // 2. a->b
7073 // Only one argument.
7074 // 3. a->*b
7075 case MEMBER_REF:
7076 // 7. a << b
7077 case LSHIFT_EXPR:
7078 // 8. a >> b
7079 case RSHIFT_EXPR:
7080 // a && b
7081 // Predates P0145R3.
7082 case TRUTH_ANDIF_EXPR:
7083 // a || b
7084 // Predates P0145R3.
7085 case TRUTH_ORIF_EXPR:
7086 // a , b
7087 // Predates P0145R3.
7088 case COMPOUND_EXPR:
7089 return (flag_strong_eval_order ? 1 : 0);
7090
7091 default:
7092 return 0;
7093 }
7094}
7095
7096/* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
7097 operator indicated by CODE/CODE2. This function calls itself recursively to
7098 handle C++20 rewritten comparison operator candidates. Returns NULL_TREE
7099 upon success, and error_mark_node if something went wrong that prevented
7100 us from performing overload resolution (e.g. ambiguous member name lookup).
7101
7102 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
7103 overloads to consider. This parameter is used when instantiating a
7104 dependent operator expression and has the same structure as
7105 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
7106
7107static tree
7108add_operator_candidates (z_candidate **candidates,
7109 tree_code code, tree_code code2,
7110 vec<tree, va_gc> *arglist, tree lookups,
7111 int flags, tsubst_flags_t complain)
7112{
7113 z_candidate *start_candidates = *candidates;
7114 bool ismodop = code2 != ERROR_MARK;
7115 tree fnname = ovl_op_identifier (isass: ismodop, code: ismodop ? code2 : code);
7116
7117 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
7118 rewrite from, and also when we're looking for the e.g. < operator to use
7119 on the result of <=>. In the latter case, we don't want the flag set in
7120 the candidate, we just want to suppress looking for rewrites. */
7121 bool rewritten = (flags & LOOKUP_REWRITTEN);
7122 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
7123 flags &= ~LOOKUP_REWRITTEN;
7124
7125 bool memonly = false;
7126 switch (code)
7127 {
7128 /* =, ->, [], () must be non-static member functions. */
7129 case MODIFY_EXPR:
7130 if (code2 != NOP_EXPR)
7131 break;
7132 /* FALLTHRU */
7133 case COMPONENT_REF:
7134 case ARRAY_REF:
7135 memonly = true;
7136 break;
7137
7138 default:
7139 break;
7140 }
7141
7142 /* Add namespace-scope operators to the list of functions to
7143 consider. */
7144 if (!memonly)
7145 {
7146 tree fns;
7147 if (!lookups)
7148 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7149 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
7150 expression, and LOOKUPS is the result of stage 1 name lookup. */
7151 else if (tree found = purpose_member (fnname, lookups))
7152 fns = TREE_VALUE (found);
7153 else
7154 fns = NULL_TREE;
7155 fns = lookup_arg_dependent (fnname, fns, arglist);
7156 add_candidates (fns, NULL_TREE, args: arglist, NULL_TREE,
7157 NULL_TREE, template_only: false, NULL_TREE, NULL_TREE,
7158 flags, candidates, complain);
7159 }
7160
7161 /* Add class-member operators to the candidate set. */
7162 tree arg1_type = TREE_TYPE ((*arglist)[0]);
7163 unsigned nargs = arglist->length () > 1 ? 2 : 1;
7164 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
7165 if (CLASS_TYPE_P (arg1_type))
7166 {
7167 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
7168 if (fns == error_mark_node)
7169 return error_mark_node;
7170 if (fns)
7171 {
7172 if (code == ARRAY_REF)
7173 {
7174 vec<tree,va_gc> *restlist = make_tree_vector ();
7175 for (unsigned i = 1; i < nargs; ++i)
7176 vec_safe_push (v&: restlist, obj: (*arglist)[i]);
7177 z_candidate *save_cand = *candidates;
7178 add_candidates (BASELINK_FUNCTIONS (fns),
7179 first_arg: (*arglist)[0], args: restlist, NULL_TREE,
7180 NULL_TREE, template_only: false,
7181 BASELINK_BINFO (fns),
7182 BASELINK_ACCESS_BINFO (fns),
7183 flags, candidates, complain);
7184 /* Release the vec if we didn't add a candidate that uses it. */
7185 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7186 if (c->args == restlist)
7187 {
7188 restlist = NULL;
7189 break;
7190 }
7191 release_tree_vector (restlist);
7192 }
7193 else
7194 add_candidates (BASELINK_FUNCTIONS (fns),
7195 NULL_TREE, args: arglist, NULL_TREE,
7196 NULL_TREE, template_only: false,
7197 BASELINK_BINFO (fns),
7198 BASELINK_ACCESS_BINFO (fns),
7199 flags, candidates, complain);
7200 }
7201 }
7202 /* Per [over.match.oper]3.2, if no operand has a class type, then
7203 only non-member functions that have type T1 or reference to
7204 cv-qualified-opt T1 for the first argument, if the first argument
7205 has an enumeration type, or T2 or reference to cv-qualified-opt
7206 T2 for the second argument, if the second argument has an
7207 enumeration type. Filter out those that don't match. */
7208 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
7209 {
7210 struct z_candidate **candp, **next;
7211
7212 for (candp = candidates; *candp != start_candidates; candp = next)
7213 {
7214 unsigned i;
7215 z_candidate *cand = *candp;
7216 next = &cand->next;
7217
7218 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
7219
7220 for (i = 0; i < nargs; ++i)
7221 {
7222 tree parmtype = TREE_VALUE (parmlist);
7223 tree argtype = unlowered_expr_type ((*arglist)[i]);
7224
7225 if (TYPE_REF_P (parmtype))
7226 parmtype = TREE_TYPE (parmtype);
7227 if (TREE_CODE (argtype) == ENUMERAL_TYPE
7228 && (same_type_ignoring_top_level_qualifiers_p
7229 (argtype, parmtype)))
7230 break;
7231
7232 parmlist = TREE_CHAIN (parmlist);
7233 }
7234
7235 /* No argument has an appropriate type, so remove this
7236 candidate function from the list. */
7237 if (i == nargs)
7238 {
7239 *candp = cand->next;
7240 next = candp;
7241 }
7242 }
7243 }
7244
7245 if (!rewritten)
7246 {
7247 /* The standard says to rewrite built-in candidates, too,
7248 but there's no point. */
7249 add_builtin_candidates (candidates, code, code2, fnname, argv: arglist,
7250 flags, complain);
7251
7252 /* Maybe add C++20 rewritten comparison candidates. */
7253 tree_code rewrite_code = ERROR_MARK;
7254 if (cxx_dialect >= cxx20
7255 && nargs == 2
7256 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
7257 switch (code)
7258 {
7259 case LT_EXPR:
7260 case LE_EXPR:
7261 case GT_EXPR:
7262 case GE_EXPR:
7263 case SPACESHIP_EXPR:
7264 rewrite_code = SPACESHIP_EXPR;
7265 break;
7266
7267 case NE_EXPR:
7268 case EQ_EXPR:
7269 rewrite_code = EQ_EXPR;
7270 break;
7271
7272 default:;
7273 }
7274
7275 if (rewrite_code)
7276 {
7277 tree r;
7278 flags |= LOOKUP_REWRITTEN;
7279 if (rewrite_code != code)
7280 {
7281 /* Add rewritten candidates in same order. */
7282 r = add_operator_candidates (candidates, code: rewrite_code, code2: ERROR_MARK,
7283 arglist, lookups, flags, complain);
7284 if (r == error_mark_node)
7285 return error_mark_node;
7286 }
7287
7288 z_candidate *save_cand = *candidates;
7289
7290 /* Add rewritten candidates in reverse order. */
7291 flags |= LOOKUP_REVERSED;
7292 vec<tree,va_gc> *revlist = make_tree_vector ();
7293 revlist->quick_push (obj: (*arglist)[1]);
7294 revlist->quick_push (obj: (*arglist)[0]);
7295 r = add_operator_candidates (candidates, code: rewrite_code, code2: ERROR_MARK,
7296 arglist: revlist, lookups, flags, complain);
7297 if (r == error_mark_node)
7298 return error_mark_node;
7299
7300 /* Release the vec if we didn't add a candidate that uses it. */
7301 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7302 if (c->args == revlist)
7303 {
7304 revlist = NULL;
7305 break;
7306 }
7307 release_tree_vector (revlist);
7308 }
7309 }
7310
7311 return NULL_TREE;
7312}
7313
7314tree
7315build_new_op (const op_location_t &loc, enum tree_code code, int flags,
7316 tree arg1, tree arg2, tree arg3, tree lookups,
7317 tree *overload, tsubst_flags_t complain)
7318{
7319 struct z_candidate *candidates = 0, *cand;
7320 releasing_vec arglist;
7321 tree result = NULL_TREE;
7322 bool result_valid_p = false;
7323 enum tree_code code2 = ERROR_MARK;
7324 enum tree_code code_orig_arg1 = ERROR_MARK;
7325 enum tree_code code_orig_arg2 = ERROR_MARK;
7326 bool strict_p;
7327 bool any_viable_p;
7328
7329 auto_cond_timevar tv (TV_OVERLOAD);
7330
7331 if (error_operand_p (t: arg1)
7332 || error_operand_p (t: arg2)
7333 || error_operand_p (t: arg3))
7334 return error_mark_node;
7335
7336 conversion_obstack_sentinel cos;
7337
7338 bool ismodop = code == MODIFY_EXPR;
7339 if (ismodop)
7340 {
7341 code2 = TREE_CODE (arg3);
7342 arg3 = NULL_TREE;
7343 }
7344
7345 tree arg1_type = unlowered_expr_type (arg1);
7346 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
7347
7348 arg1 = prep_operand (operand: arg1);
7349
7350 switch (code)
7351 {
7352 case NEW_EXPR:
7353 case VEC_NEW_EXPR:
7354 case VEC_DELETE_EXPR:
7355 case DELETE_EXPR:
7356 /* Use build_operator_new_call and build_op_delete_call instead. */
7357 gcc_unreachable ();
7358
7359 case CALL_EXPR:
7360 /* Use build_op_call instead. */
7361 gcc_unreachable ();
7362
7363 case TRUTH_ORIF_EXPR:
7364 case TRUTH_ANDIF_EXPR:
7365 case TRUTH_AND_EXPR:
7366 case TRUTH_OR_EXPR:
7367 /* These are saved for the sake of warn_logical_operator. */
7368 code_orig_arg1 = TREE_CODE (arg1);
7369 code_orig_arg2 = TREE_CODE (arg2);
7370 break;
7371 case GT_EXPR:
7372 case LT_EXPR:
7373 case GE_EXPR:
7374 case LE_EXPR:
7375 case EQ_EXPR:
7376 case NE_EXPR:
7377 /* These are saved for the sake of maybe_warn_bool_compare. */
7378 code_orig_arg1 = TREE_CODE (arg1_type);
7379 code_orig_arg2 = TREE_CODE (arg2_type);
7380 break;
7381
7382 default:
7383 break;
7384 }
7385
7386 arg2 = prep_operand (operand: arg2);
7387 arg3 = prep_operand (operand: arg3);
7388
7389 if (code == COND_EXPR)
7390 /* Use build_conditional_expr instead. */
7391 gcc_unreachable ();
7392 else if (! OVERLOAD_TYPE_P (arg1_type)
7393 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7394 goto builtin;
7395
7396 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7397 {
7398 arg2 = integer_zero_node;
7399 arg2_type = integer_type_node;
7400 }
7401
7402 arglist->quick_push (obj: arg1);
7403 if (arg2 != NULL_TREE)
7404 arglist->quick_push (obj: arg2);
7405 if (arg3 != NULL_TREE)
7406 arglist->quick_push (obj: arg3);
7407
7408 result = add_operator_candidates (candidates: &candidates, code, code2, arglist,
7409 lookups, flags, complain);
7410 if (result == error_mark_node)
7411 return error_mark_node;
7412
7413 switch (code)
7414 {
7415 case COMPOUND_EXPR:
7416 case ADDR_EXPR:
7417 /* For these, the built-in candidates set is empty
7418 [over.match.oper]/3. We don't want non-strict matches
7419 because exact matches are always possible with built-in
7420 operators. The built-in candidate set for COMPONENT_REF
7421 would be empty too, but since there are no such built-in
7422 operators, we accept non-strict matches for them. */
7423 strict_p = true;
7424 break;
7425
7426 default:
7427 strict_p = false;
7428 break;
7429 }
7430
7431 candidates = splice_viable (cands: candidates, strict_p, any_viable_p: &any_viable_p);
7432 if (!any_viable_p)
7433 {
7434 switch (code)
7435 {
7436 case POSTINCREMENT_EXPR:
7437 case POSTDECREMENT_EXPR:
7438 /* Don't try anything fancy if we're not allowed to produce
7439 errors. */
7440 if (!(complain & tf_error))
7441 return error_mark_node;
7442
7443 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7444 distinguish between prefix and postfix ++ and
7445 operator++() was used for both, so we allow this with
7446 -fpermissive. */
7447 else
7448 {
7449 tree fnname = ovl_op_identifier (isass: ismodop, code: ismodop ? code2 : code);
7450 const char *msg = (flag_permissive)
7451 ? G_("no %<%D(int)%> declared for postfix %qs,"
7452 " trying prefix operator instead")
7453 : G_("no %<%D(int)%> declared for postfix %qs");
7454 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7455 }
7456
7457 if (!flag_permissive)
7458 return error_mark_node;
7459
7460 if (code == POSTINCREMENT_EXPR)
7461 code = PREINCREMENT_EXPR;
7462 else
7463 code = PREDECREMENT_EXPR;
7464 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7465 NULL_TREE, lookups, overload, complain);
7466 break;
7467
7468 /* The caller will deal with these. */
7469 case ADDR_EXPR:
7470 case COMPOUND_EXPR:
7471 case COMPONENT_REF:
7472 case CO_AWAIT_EXPR:
7473 result = NULL_TREE;
7474 result_valid_p = true;
7475 break;
7476
7477 default:
7478 if (complain & tf_error)
7479 {
7480 /* If one of the arguments of the operator represents
7481 an invalid use of member function pointer, try to report
7482 a meaningful error ... */
7483 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7484 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7485 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7486 /* We displayed the error message. */;
7487 else
7488 {
7489 /* ... Otherwise, report the more generic
7490 "no matching operator found" error */
7491 auto_diagnostic_group d;
7492 op_error (loc, code, code2, arg1, arg2, arg3, match: false);
7493 print_z_candidates (loc, candidates);
7494 }
7495 }
7496 result = error_mark_node;
7497 break;
7498 }
7499 }
7500 else
7501 {
7502 cand = tourney (candidates, complain);
7503 if (cand == 0)
7504 {
7505 if (complain & tf_error)
7506 {
7507 auto_diagnostic_group d;
7508 op_error (loc, code, code2, arg1, arg2, arg3, match: true);
7509 print_z_candidates (loc, candidates);
7510 }
7511 result = error_mark_node;
7512 if (overload)
7513 *overload = error_mark_node;
7514 }
7515 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7516 {
7517 if (overload)
7518 {
7519 if (cand->rewritten ())
7520 /* build_min_non_dep_op_overload needs to know whether the
7521 candidate is rewritten/reversed. */
7522 *overload = build_tree_list (build_int_cst (integer_type_node,
7523 cand->flags),
7524 cand->fn);
7525 else
7526 *overload = cand->fn;
7527 }
7528
7529 if (resolve_args (args: arglist, complain) == NULL)
7530 result = error_mark_node;
7531 else
7532 {
7533 tsubst_flags_t ocomplain = complain;
7534 if (cand->rewritten ())
7535 /* We'll wrap this call in another one. */
7536 ocomplain &= ~tf_decltype;
7537 if (cand->reversed ())
7538 {
7539 /* We swapped these in add_candidate, swap them back now. */
7540 std::swap (a&: cand->convs[0], b&: cand->convs[1]);
7541 if (cand->fn == current_function_decl)
7542 warning_at (loc, 0, "in C++20 this comparison calls the "
7543 "current function recursively with reversed "
7544 "arguments");
7545 }
7546 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7547 }
7548
7549 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7550 /* There won't be a CALL_EXPR. */;
7551 else if (result && result != error_mark_node)
7552 {
7553 tree call = extract_call_expr (result);
7554 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7555
7556 /* Specify evaluation order as per P0145R2. */
7557 CALL_EXPR_ORDERED_ARGS (call) = false;
7558 switch (op_is_ordered (code))
7559 {
7560 case -1:
7561 CALL_EXPR_REVERSE_ARGS (call) = true;
7562 break;
7563
7564 case 1:
7565 CALL_EXPR_ORDERED_ARGS (call) = true;
7566 break;
7567
7568 default:
7569 break;
7570 }
7571 }
7572
7573 /* If this was a C++20 rewritten comparison, adjust the result. */
7574 if (cand->rewritten ())
7575 {
7576 switch (code)
7577 {
7578 case EQ_EXPR:
7579 gcc_checking_assert (cand->reversed ());
7580 gcc_fallthrough ();
7581 case NE_EXPR:
7582 if (result == error_mark_node)
7583 ;
7584 /* If a rewritten operator== candidate is selected by
7585 overload resolution for an operator @, its return type
7586 shall be cv bool.... */
7587 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7588 {
7589 if (complain & tf_error)
7590 {
7591 auto_diagnostic_group d;
7592 error_at (loc, "return type of %qD is not %qs",
7593 cand->fn, "bool");
7594 inform (loc, "used as rewritten candidate for "
7595 "comparison of %qT and %qT",
7596 arg1_type, arg2_type);
7597 }
7598 result = error_mark_node;
7599 }
7600 else if (code == NE_EXPR)
7601 /* !(y == x) or !(x == y) */
7602 result = build1_loc (loc, code: TRUTH_NOT_EXPR,
7603 boolean_type_node, arg1: result);
7604 break;
7605
7606 /* If a rewritten operator<=> candidate is selected by
7607 overload resolution for an operator @, x @ y is
7608 interpreted as 0 @ (y <=> x) if the selected candidate is
7609 a synthesized candidate with reversed order of parameters,
7610 or (x <=> y) @ 0 otherwise, using the selected rewritten
7611 operator<=> candidate. */
7612 case SPACESHIP_EXPR:
7613 if (!cand->reversed ())
7614 /* We're in the build_new_op call below for an outer
7615 reversed call; we don't need to do anything more. */
7616 break;
7617 gcc_fallthrough ();
7618 case LT_EXPR:
7619 case LE_EXPR:
7620 case GT_EXPR:
7621 case GE_EXPR:
7622 {
7623 tree lhs = result;
7624 tree rhs = integer_zero_node;
7625 if (cand->reversed ())
7626 std::swap (a&: lhs, b&: rhs);
7627 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7628 result = build_new_op (loc, code,
7629 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7630 arg1: lhs, arg2: rhs, NULL_TREE, lookups,
7631 NULL, complain);
7632 }
7633 break;
7634
7635 default:
7636 gcc_unreachable ();
7637 }
7638 }
7639
7640 /* In an expression of the form `a[]' where cand->fn
7641 which is operator[] turns out to be a static member function,
7642 `a' is none-the-less evaluated. */
7643 if (code == ARRAY_REF)
7644 result = keep_unused_object_arg (result, obj: arg1, fn: cand->fn);
7645 }
7646 else
7647 {
7648 /* Give any warnings we noticed during overload resolution. */
7649 if (cand->warnings && (complain & tf_warning))
7650 {
7651 struct candidate_warning *w;
7652 for (w = cand->warnings; w; w = w->next)
7653 joust (cand, w->loser, 1, complain);
7654 }
7655
7656 /* Check for comparison of different enum types. */
7657 switch (code)
7658 {
7659 case GT_EXPR:
7660 case LT_EXPR:
7661 case GE_EXPR:
7662 case LE_EXPR:
7663 case EQ_EXPR:
7664 case NE_EXPR:
7665 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7666 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7667 && (TYPE_MAIN_VARIANT (arg1_type)
7668 != TYPE_MAIN_VARIANT (arg2_type)))
7669 {
7670 if (cxx_dialect >= cxx26
7671 && (complain & tf_warning_or_error) == 0)
7672 result = error_mark_node;
7673 else if (cxx_dialect >= cxx26 || (complain & tf_warning))
7674 emit_diagnostic ((cxx_dialect >= cxx26
7675 ? diagnostics::kind::pedwarn
7676 : diagnostics::kind::warning),
7677 loc, OPT_Wenum_compare,
7678 "comparison between %q#T and %q#T",
7679 arg1_type, arg2_type);
7680 }
7681 break;
7682 default:
7683 break;
7684 }
7685
7686 /* "If a built-in candidate is selected by overload resolution, the
7687 operands of class type are converted to the types of the
7688 corresponding parameters of the selected operation function,
7689 except that the second standard conversion sequence of a
7690 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7691 conversion *conv = cand->convs[0];
7692 if (conv->user_conv_p)
7693 {
7694 conv = strip_standard_conversion (conv);
7695 arg1 = convert_like (conv, arg1, complain);
7696 }
7697
7698 if (arg2)
7699 {
7700 conv = cand->convs[1];
7701 if (conv->user_conv_p)
7702 {
7703 conv = strip_standard_conversion (conv);
7704 arg2 = convert_like (conv, arg2, complain);
7705 }
7706 }
7707
7708 if (arg3)
7709 {
7710 conv = cand->convs[2];
7711 if (conv->user_conv_p)
7712 {
7713 conv = strip_standard_conversion (conv);
7714 arg3 = convert_like (conv, arg3, complain);
7715 }
7716 }
7717 }
7718 }
7719
7720 if (result || result_valid_p)
7721 return result;
7722
7723 builtin:
7724 switch (code)
7725 {
7726 case MODIFY_EXPR:
7727 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7728
7729 case INDIRECT_REF:
7730 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7731
7732 case TRUTH_ANDIF_EXPR:
7733 case TRUTH_ORIF_EXPR:
7734 case TRUTH_AND_EXPR:
7735 case TRUTH_OR_EXPR:
7736 if ((complain & tf_warning) && !processing_template_decl)
7737 warn_logical_operator (loc, code, boolean_type_node,
7738 code_orig_arg1, arg1,
7739 code_orig_arg2, arg2);
7740 /* Fall through. */
7741 case GT_EXPR:
7742 case LT_EXPR:
7743 case GE_EXPR:
7744 case LE_EXPR:
7745 case EQ_EXPR:
7746 case NE_EXPR:
7747 if ((complain & tf_warning)
7748 && ((code_orig_arg1 == BOOLEAN_TYPE)
7749 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7750 maybe_warn_bool_compare (loc, code, arg1, arg2);
7751 if (complain & tf_warning && warn_tautological_compare)
7752 warn_tautological_cmp (loc, code, arg1, arg2);
7753 /* Fall through. */
7754 case SPACESHIP_EXPR:
7755 case PLUS_EXPR:
7756 case MINUS_EXPR:
7757 case MULT_EXPR:
7758 case TRUNC_DIV_EXPR:
7759 case MAX_EXPR:
7760 case MIN_EXPR:
7761 case LSHIFT_EXPR:
7762 case RSHIFT_EXPR:
7763 case TRUNC_MOD_EXPR:
7764 case BIT_AND_EXPR:
7765 case BIT_IOR_EXPR:
7766 case BIT_XOR_EXPR:
7767 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7768
7769 case UNARY_PLUS_EXPR:
7770 case NEGATE_EXPR:
7771 case BIT_NOT_EXPR:
7772 case TRUTH_NOT_EXPR:
7773 case PREINCREMENT_EXPR:
7774 case POSTINCREMENT_EXPR:
7775 case PREDECREMENT_EXPR:
7776 case POSTDECREMENT_EXPR:
7777 case REALPART_EXPR:
7778 case IMAGPART_EXPR:
7779 case ABS_EXPR:
7780 case CO_AWAIT_EXPR:
7781 return cp_build_unary_op (code, arg1, false, complain);
7782
7783 case ARRAY_REF:
7784 return cp_build_array_ref (input_location, arg1, arg2, complain);
7785
7786 case MEMBER_REF:
7787 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7788 RO_ARROW_STAR,
7789 complain),
7790 arg2, complain);
7791
7792 /* The caller will deal with these. */
7793 case ADDR_EXPR:
7794 case COMPONENT_REF:
7795 case COMPOUND_EXPR:
7796 return NULL_TREE;
7797
7798 default:
7799 gcc_unreachable ();
7800 }
7801 return NULL_TREE;
7802}
7803
7804/* Build a new call to operator[]. This may change ARGS. */
7805
7806tree
7807build_op_subscript (const op_location_t &loc, tree obj,
7808 vec<tree, va_gc> **args, tree *overload,
7809 tsubst_flags_t complain)
7810{
7811 struct z_candidate *candidates = 0, *cand;
7812 tree fns, first_mem_arg = NULL_TREE;
7813 bool any_viable_p;
7814 tree result = NULL_TREE;
7815
7816 auto_cond_timevar tv (TV_OVERLOAD);
7817
7818 obj = mark_lvalue_use (obj);
7819
7820 if (error_operand_p (t: obj))
7821 return error_mark_node;
7822
7823 tree type = TREE_TYPE (obj);
7824
7825 obj = prep_operand (operand: obj);
7826
7827 if (TYPE_BINFO (type))
7828 {
7829 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (code: ARRAY_REF),
7830 1, complain);
7831 if (fns == error_mark_node)
7832 return error_mark_node;
7833 }
7834 else
7835 fns = NULL_TREE;
7836
7837 if (args != NULL && *args != NULL)
7838 {
7839 *args = resolve_args (args: *args, complain);
7840 if (*args == NULL)
7841 return error_mark_node;
7842 }
7843
7844 conversion_obstack_sentinel cos;
7845
7846 if (fns)
7847 {
7848 first_mem_arg = obj;
7849
7850 add_candidates (BASELINK_FUNCTIONS (fns),
7851 first_arg: first_mem_arg, args: *args, NULL_TREE,
7852 NULL_TREE, template_only: false,
7853 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7854 LOOKUP_NORMAL, candidates: &candidates, complain);
7855 }
7856
7857 /* Be strict here because if we choose a bad conversion candidate, the
7858 errors we get won't mention the call context. */
7859 candidates = splice_viable (cands: candidates, strict_p: true, any_viable_p: &any_viable_p);
7860 if (!any_viable_p)
7861 {
7862 if (complain & tf_error)
7863 {
7864 auto_diagnostic_group d;
7865 error ("no match for call to %<%T::operator[] (%A)%>",
7866 TREE_TYPE (obj), build_tree_list_vec (*args));
7867 print_z_candidates (loc, candidates);
7868 }
7869 result = error_mark_node;
7870 }
7871 else
7872 {
7873 cand = tourney (candidates, complain);
7874 if (cand == 0)
7875 {
7876 if (complain & tf_error)
7877 {
7878 auto_diagnostic_group d;
7879 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7880 TREE_TYPE (obj), build_tree_list_vec (*args));
7881 print_z_candidates (loc, candidates);
7882 }
7883 result = error_mark_node;
7884 }
7885 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7886 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7887 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7888 {
7889 if (overload)
7890 *overload = cand->fn;
7891 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7892 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7893 /* There won't be a CALL_EXPR. */;
7894 else if (result && result != error_mark_node)
7895 {
7896 tree call = extract_call_expr (result);
7897 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7898
7899 /* Specify evaluation order as per P0145R2. */
7900 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (code: ARRAY_REF) == 1;
7901 }
7902
7903 /* In an expression of the form `a[]' where cand->fn
7904 which is operator[] turns out to be a static member function,
7905 `a' is none-the-less evaluated. */
7906 result = keep_unused_object_arg (result, obj, fn: cand->fn);
7907 }
7908 else
7909 gcc_unreachable ();
7910 }
7911
7912 return result;
7913}
7914
7915/* CALL was returned by some call-building function; extract the actual
7916 CALL_EXPR from any bits that have been tacked on, e.g. by
7917 convert_from_reference. */
7918
7919tree
7920extract_call_expr (tree call)
7921{
7922 while (TREE_CODE (call) == COMPOUND_EXPR)
7923 call = TREE_OPERAND (call, 1);
7924 if (REFERENCE_REF_P (call))
7925 call = TREE_OPERAND (call, 0);
7926 if (TREE_CODE (call) == TARGET_EXPR)
7927 call = TARGET_EXPR_INITIAL (call);
7928
7929 if (TREE_CODE (call) != CALL_EXPR
7930 && TREE_CODE (call) != AGGR_INIT_EXPR
7931 && call != error_mark_node)
7932 return NULL_TREE;
7933 return call;
7934}
7935
7936/* Returns true if FN has two parameters, of which the second has type
7937 size_t. */
7938
7939static bool
7940second_parm_is_size_t (tree fn)
7941{
7942 tree t = FUNCTION_ARG_CHAIN (fn);
7943 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7944 return false;
7945 t = TREE_CHAIN (t);
7946 if (t == void_list_node)
7947 return true;
7948 return false;
7949}
7950
7951/* True if T, an allocation function, has std::align_val_t as its second
7952 argument. */
7953
7954bool
7955aligned_allocation_fn_p (tree t)
7956{
7957 if (!aligned_new_threshold)
7958 return false;
7959
7960 tree a = FUNCTION_ARG_CHAIN (t);
7961 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7962}
7963
7964/* True if T is std::destroying_delete_t. */
7965
7966static bool
7967std_destroying_delete_t_p (tree t)
7968{
7969 return (TYPE_CONTEXT (t) == std_node
7970 && id_equal (TYPE_IDENTIFIER (t), str: "destroying_delete_t"));
7971}
7972
7973/* A deallocation function with at least two parameters whose second parameter
7974 type is of type std::destroying_delete_t is a destroying operator delete. A
7975 destroying operator delete shall be a class member function named operator
7976 delete. [ Note: Array deletion cannot use a destroying operator
7977 delete. --end note ] */
7978
7979tree
7980destroying_delete_p (tree t)
7981{
7982 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7983 if (!a || !TREE_CHAIN (a))
7984 return NULL_TREE;
7985 tree type = TREE_VALUE (TREE_CHAIN (a));
7986 return std_destroying_delete_t_p (t: type) ? type : NULL_TREE;
7987}
7988
7989struct dealloc_info
7990{
7991 bool sized;
7992 bool aligned;
7993 tree destroying;
7994};
7995
7996/* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7997 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7998 non-null, also set *DI. */
7999
8000static bool
8001usual_deallocation_fn_p (tree t, dealloc_info *di)
8002{
8003 if (di) *di = dealloc_info();
8004
8005 /* A template instance is never a usual deallocation function,
8006 regardless of its signature. */
8007 if (TREE_CODE (t) == TEMPLATE_DECL
8008 || primary_template_specialization_p (t))
8009 return false;
8010
8011 /* A usual deallocation function is a deallocation function whose parameters
8012 after the first are
8013 - optionally, a parameter of type std::destroying_delete_t, then
8014 - optionally, a parameter of type std::size_t, then
8015 - optionally, a parameter of type std::align_val_t. */
8016 bool global = DECL_NAMESPACE_SCOPE_P (t);
8017 tree chain = FUNCTION_ARG_CHAIN (t);
8018 if (chain && destroying_delete_p (t))
8019 {
8020 if (di) di->destroying = TREE_VALUE (chain);
8021 chain = TREE_CHAIN (chain);
8022 }
8023 if (chain
8024 && (!global || flag_sized_deallocation)
8025 && same_type_p (TREE_VALUE (chain), size_type_node))
8026 {
8027 if (di) di->sized = true;
8028 chain = TREE_CHAIN (chain);
8029 }
8030 if (chain && aligned_new_threshold
8031 && same_type_p (TREE_VALUE (chain), align_type_node))
8032 {
8033 if (di) di->aligned = true;
8034 chain = TREE_CHAIN (chain);
8035 }
8036 return (chain == void_list_node);
8037}
8038
8039/* Just return whether FN is a usual deallocation function. */
8040
8041bool
8042usual_deallocation_fn_p (tree fn)
8043{
8044 return usual_deallocation_fn_p (t: fn, NULL);
8045}
8046
8047/* Build a call to operator delete. This has to be handled very specially,
8048 because the restrictions on what signatures match are different from all
8049 other call instances. For a normal delete, only a delete taking (void *)
8050 or (void *, size_t) is accepted. For a placement delete, only an exact
8051 match with the placement new is accepted.
8052
8053 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
8054 ADDR is the pointer to be deleted.
8055 SIZE is the size of the memory block to be deleted.
8056 GLOBAL_P is true if the delete-expression should not consider
8057 class-specific delete operators.
8058 CORO_P is true if the allocation is for a coroutine, where the two argument
8059 usual deallocation should be chosen in preference to the single argument
8060 version in a class context.
8061 PLACEMENT is the corresponding placement new call, or NULL_TREE.
8062
8063 If this call to "operator delete" is being generated as part to
8064 deallocate memory allocated via a new-expression (as per [expr.new]
8065 which requires that if the initialization throws an exception then
8066 we call a deallocation function), then ALLOC_FN is the allocation
8067 function. */
8068
8069static tree
8070build_op_delete_call_1 (enum tree_code code, tree addr, tree size,
8071 bool global_p, bool coro_p, tree placement,
8072 tree alloc_fn, tsubst_flags_t complain)
8073{
8074 tree fn = NULL_TREE;
8075 tree fns, fnname, type, t;
8076 dealloc_info di_fn = { };
8077
8078 if (addr == error_mark_node)
8079 return error_mark_node;
8080
8081 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
8082
8083 fnname = ovl_op_identifier (isass: false, code);
8084
8085 if (CLASS_TYPE_P (type)
8086 && COMPLETE_TYPE_P (complete_type (type))
8087 && !global_p)
8088 /* In [class.free]
8089
8090 If the result of the lookup is ambiguous or inaccessible, or if
8091 the lookup selects a placement deallocation function, the
8092 program is ill-formed.
8093
8094 Therefore, we ask lookup_fnfields to complain about ambiguity. */
8095 {
8096 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
8097 if (fns == error_mark_node)
8098 return error_mark_node;
8099 }
8100 else
8101 fns = NULL_TREE;
8102
8103 if (fns == NULL_TREE)
8104 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
8105
8106 /* Strip const and volatile from addr. */
8107 tree oaddr = addr;
8108 addr = cp_convert (ptr_type_node, addr, complain);
8109
8110 tree excluded_destroying = NULL_TREE;
8111
8112 if (placement)
8113 {
8114 /* "A declaration of a placement deallocation function matches the
8115 declaration of a placement allocation function if it has the same
8116 number of parameters and, after parameter transformations (8.3.5),
8117 all parameter types except the first are identical."
8118
8119 So we build up the function type we want and ask instantiate_type
8120 to get it for us. */
8121 t = FUNCTION_ARG_CHAIN (alloc_fn);
8122 t = tree_cons (NULL_TREE, ptr_type_node, t);
8123 t = build_function_type (void_type_node, t);
8124
8125 fn = instantiate_type (t, fns, tf_none);
8126 if (fn == error_mark_node)
8127 return NULL_TREE;
8128
8129 fn = MAYBE_BASELINK_FUNCTIONS (fn);
8130
8131 /* "If the lookup finds the two-parameter form of a usual deallocation
8132 function (3.7.4.2) and that function, considered as a placement
8133 deallocation function, would have been selected as a match for the
8134 allocation function, the program is ill-formed." */
8135 if (second_parm_is_size_t (fn))
8136 {
8137 const char *const msg1
8138 = G_("exception cleanup for this placement new selects "
8139 "non-placement %<operator delete%>");
8140 const char *const msg2
8141 = G_("%qD is a usual (non-placement) deallocation "
8142 "function in C++14 (or with %<-fsized-deallocation%>)");
8143
8144 /* But if the class has an operator delete (void *), then that is
8145 the usual deallocation function, so we shouldn't complain
8146 about using the operator delete (void *, size_t). */
8147 if (DECL_CLASS_SCOPE_P (fn))
8148 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
8149 {
8150 if (usual_deallocation_fn_p (fn: elt)
8151 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
8152 goto ok;
8153 }
8154 /* Before C++14 a two-parameter global deallocation function is
8155 always a placement deallocation function, but warn if
8156 -Wc++14-compat. */
8157 else if (!flag_sized_deallocation)
8158 {
8159 if (complain & tf_warning)
8160 {
8161 auto_diagnostic_group d;
8162 if (warning (OPT_Wc__14_compat, msg1))
8163 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
8164 }
8165 goto ok;
8166 }
8167
8168 if (complain & tf_warning_or_error)
8169 {
8170 auto_diagnostic_group d;
8171 if (permerror (input_location, msg1))
8172 {
8173 /* Only mention C++14 for namespace-scope delete. */
8174 if (DECL_NAMESPACE_SCOPE_P (fn))
8175 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
8176 else
8177 inform (DECL_SOURCE_LOCATION (fn),
8178 "%qD is a usual (non-placement) deallocation "
8179 "function", fn);
8180 }
8181 }
8182 else
8183 return error_mark_node;
8184 ok:;
8185 }
8186 }
8187 else
8188 /* "Any non-placement deallocation function matches a non-placement
8189 allocation function. If the lookup finds a single matching
8190 deallocation function, that function will be called; otherwise, no
8191 deallocation function will be called." */
8192 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
8193 {
8194 dealloc_info di_elt;
8195 if (usual_deallocation_fn_p (t: elt, di: &di_elt))
8196 {
8197 /* If we're called for an EH cleanup in a new-expression, we can't
8198 use a destroying delete; the exception was thrown before the
8199 object was constructed. */
8200 if (alloc_fn && di_elt.destroying)
8201 {
8202 excluded_destroying = elt;
8203 continue;
8204 }
8205
8206 if (!fn)
8207 {
8208 fn = elt;
8209 di_fn = di_elt;
8210 continue;
8211 }
8212
8213 /* -- If any of the deallocation functions is a destroying
8214 operator delete, all deallocation functions that are not
8215 destroying operator deletes are eliminated from further
8216 consideration. */
8217 if (di_elt.destroying != di_fn.destroying)
8218 {
8219 if (di_elt.destroying)
8220 {
8221 fn = elt;
8222 di_fn = di_elt;
8223 }
8224 continue;
8225 }
8226
8227 /* -- If the type has new-extended alignment, a function with a
8228 parameter of type std::align_val_t is preferred; otherwise a
8229 function without such a parameter is preferred. If exactly one
8230 preferred function is found, that function is selected and the
8231 selection process terminates. If more than one preferred
8232 function is found, all non-preferred functions are eliminated
8233 from further consideration. */
8234 if (aligned_new_threshold)
8235 {
8236 bool want_align = type_has_new_extended_alignment (type);
8237 if (di_elt.aligned != di_fn.aligned)
8238 {
8239 if (want_align == di_elt.aligned)
8240 {
8241 fn = elt;
8242 di_fn = di_elt;
8243 }
8244 continue;
8245 }
8246 }
8247
8248 /* -- If the deallocation functions have class scope, the one
8249 without a parameter of type std::size_t is selected. */
8250 bool want_size;
8251 if (DECL_CLASS_SCOPE_P (fn) && !coro_p)
8252 want_size = false;
8253
8254 /* -- If the type is complete and if, for the second alternative
8255 (delete array) only, the operand is a pointer to a class type
8256 with a non-trivial destructor or a (possibly multi-dimensional)
8257 array thereof, the function with a parameter of type std::size_t
8258 is selected.
8259
8260 -- Otherwise, it is unspecified whether a deallocation function
8261 with a parameter of type std::size_t is selected. */
8262 else
8263 {
8264 want_size = COMPLETE_TYPE_P (type);
8265 if (code == VEC_DELETE_EXPR
8266 && !TYPE_VEC_NEW_USES_COOKIE (type))
8267 /* We need a cookie to determine the array size. */
8268 want_size = false;
8269 }
8270 gcc_assert (di_fn.sized != di_elt.sized);
8271 if (want_size == di_elt.sized)
8272 {
8273 fn = elt;
8274 di_fn = di_elt;
8275 }
8276 }
8277 }
8278
8279 /* If we have a matching function, call it. */
8280 if (fn)
8281 {
8282 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8283
8284 /* If the FN is a member function, make sure that it is
8285 accessible. */
8286 if (BASELINK_P (fns))
8287 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
8288 complain);
8289
8290 /* Core issue 901: It's ok to new a type with deleted delete. */
8291 if (DECL_DELETED_FN (fn) && alloc_fn)
8292 return NULL_TREE;
8293
8294 tree ret;
8295 if (placement)
8296 {
8297 /* The placement args might not be suitable for overload
8298 resolution at this point, so build the call directly. */
8299 int nargs = call_expr_nargs (placement);
8300 tree *argarray = XALLOCAVEC (tree, nargs);
8301 int i;
8302 argarray[0] = addr;
8303 for (i = 1; i < nargs; i++)
8304 argarray[i] = CALL_EXPR_ARG (placement, i);
8305 if (!mark_used (fn, complain) && !(complain & tf_error))
8306 return error_mark_node;
8307 ret = build_cxx_call (fn, nargs, argarray, complain);
8308 }
8309 else
8310 {
8311 tree destroying = di_fn.destroying;
8312 if (destroying)
8313 {
8314 /* Strip const and volatile from addr but retain the type of the
8315 object. */
8316 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
8317 rtype = cv_unqualified (rtype);
8318 rtype = TYPE_POINTER_TO (rtype);
8319 addr = cp_convert (rtype, oaddr, complain);
8320 destroying = build_functional_cast (input_location,
8321 destroying, NULL_TREE,
8322 complain);
8323 }
8324
8325 releasing_vec args;
8326 args->quick_push (obj: addr);
8327 if (destroying)
8328 args->quick_push (obj: destroying);
8329 if (di_fn.sized)
8330 args->quick_push (obj: size);
8331 if (di_fn.aligned)
8332 {
8333 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
8334 args->quick_push (obj: al);
8335 }
8336 ret = cp_build_function_call_vec (fn, &args, complain);
8337 }
8338
8339 /* Set this flag for all callers of this function. In addition to
8340 delete-expressions, this is called for deallocating coroutine state;
8341 treat that as an implicit delete-expression. This is also called for
8342 the delete if the constructor throws in a new-expression, and for a
8343 deleting destructor (which implements a delete-expression). */
8344 /* But leave this flag off for destroying delete to avoid wrong
8345 assumptions in the optimizers. */
8346 tree call = extract_call_expr (call: ret);
8347 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (t: fn))
8348 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
8349
8350 return ret;
8351 }
8352
8353 /* If there's only a destroying delete that we can't use because the
8354 object isn't constructed yet, and we used global new, use global
8355 delete as well. */
8356 if (excluded_destroying
8357 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
8358 return build_op_delete_call (code, addr, size, true, placement,
8359 alloc_fn, complain);
8360
8361 /* [expr.new]
8362
8363 If no unambiguous matching deallocation function can be found,
8364 propagating the exception does not cause the object's memory to
8365 be freed. */
8366 if (alloc_fn)
8367 {
8368 if ((complain & tf_warning)
8369 && !placement)
8370 {
8371 bool w = warning (0,
8372 "no corresponding deallocation function for %qD",
8373 alloc_fn);
8374 if (w && excluded_destroying)
8375 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8376 "delete %qD cannot be used to release the allocated memory"
8377 " if the initialization throws because the object is not "
8378 "constructed yet", excluded_destroying);
8379 }
8380 return NULL_TREE;
8381 }
8382
8383 if (complain & tf_error)
8384 error ("no suitable %<operator %s%> for %qT",
8385 OVL_OP_INFO (false, code)->name, type);
8386 return error_mark_node;
8387}
8388
8389/* Arguments as per build_op_delete_call_1 (). */
8390
8391tree
8392build_op_delete_call (enum tree_code code, tree addr, tree size, bool global_p,
8393 tree placement, tree alloc_fn, tsubst_flags_t complain)
8394{
8395 return build_op_delete_call_1 (code, addr, size, global_p, /*coro_p*/false,
8396 placement, alloc_fn, complain);
8397}
8398
8399/* Arguments as per build_op_delete_call_1 (). */
8400
8401tree
8402build_coroutine_op_delete_call (enum tree_code code, tree addr, tree size,
8403 bool global_p, tree placement, tree alloc_fn,
8404 tsubst_flags_t complain)
8405{
8406 return build_op_delete_call_1 (code, addr, size, global_p, /*coro_p*/true,
8407 placement, alloc_fn, complain);
8408}
8409
8410/* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8411 in the diagnostics.
8412
8413 If ISSUE_ERROR is true, then issue an error about the access, followed
8414 by a note showing the declaration. Otherwise, just show the note.
8415
8416 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8417 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8418 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8419 would be because DECL was private). If not using NO_ACCESS_REASON,
8420 then it must be ak_none, and the access failure reason will be
8421 figured out by looking at the protection of DECL. */
8422
8423void
8424complain_about_access (tree decl, tree diag_decl, tree diag_location,
8425 bool issue_error, access_kind no_access_reason)
8426{
8427 /* If we have not already figured out why DECL is inaccessible... */
8428 if (no_access_reason == ak_none)
8429 {
8430 /* Examine the access of DECL to find out why. */
8431 if (TREE_PRIVATE (decl))
8432 no_access_reason = ak_private;
8433 else if (TREE_PROTECTED (decl))
8434 no_access_reason = ak_protected;
8435 }
8436
8437 /* Now generate an error message depending on calculated access. */
8438 if (no_access_reason == ak_private)
8439 {
8440 if (issue_error)
8441 error ("%q#D is private within this context", diag_decl);
8442 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8443 }
8444 else if (no_access_reason == ak_protected)
8445 {
8446 if (issue_error)
8447 error ("%q#D is protected within this context", diag_decl);
8448 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8449 }
8450 /* Couldn't figure out why DECL is inaccesible, so just say it's
8451 inaccessible. */
8452 else
8453 {
8454 if (issue_error)
8455 error ("%q#D is inaccessible within this context", diag_decl);
8456 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8457 }
8458}
8459
8460/* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8461 bitwise or of LOOKUP_* values. If any errors are warnings are
8462 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8463 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8464 to NULL. */
8465
8466static tree
8467build_temp (tree expr, tree type, int flags,
8468 enum diagnostics::kind *diagnostic_kind, tsubst_flags_t complain)
8469{
8470 int savew, savee;
8471
8472 *diagnostic_kind = diagnostics::kind::unspecified;
8473
8474 /* If the source is a packed field, calling the copy constructor will require
8475 binding the field to the reference parameter to the copy constructor, and
8476 we'll end up with an infinite loop. If we can use a bitwise copy, then
8477 do that now. */
8478 if ((lvalue_kind (expr) & clk_packed)
8479 && CLASS_TYPE_P (TREE_TYPE (expr))
8480 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8481 return get_target_expr (expr, complain);
8482
8483 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8484 But it turns out to be a subexpression, so perform temporary
8485 materialization now. */
8486 if (TREE_CODE (expr) == CALL_EXPR
8487 && CLASS_TYPE_P (type)
8488 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8489 expr = build_cplus_new (type, expr, complain);
8490
8491 savew = warningcount + werrorcount, savee = errorcount;
8492 releasing_vec args (make_tree_vector_single (expr));
8493 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8494 &args, type, flags, complain);
8495 if (warningcount + werrorcount > savew)
8496 *diagnostic_kind = diagnostics::kind::warning;
8497 else if (errorcount > savee)
8498 *diagnostic_kind = diagnostics::kind::error;
8499 return expr;
8500}
8501
8502/* Get any location for EXPR, falling back to input_location.
8503
8504 If the result is in a system header and is the virtual location for
8505 a token coming from the expansion of a macro, unwind it to the
8506 location of the expansion point of the macro (e.g. to avoid the
8507 diagnostic being suppressed for expansions of NULL where "NULL" is
8508 in a system header). */
8509
8510static location_t
8511get_location_for_expr_unwinding_for_system_header (tree expr)
8512{
8513 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8514 loc = expansion_point_location_if_in_system_header (loc);
8515 return loc;
8516}
8517
8518/* Perform warnings about peculiar, but valid, conversions from/to NULL.
8519 Also handle a subset of zero as null warnings.
8520 EXPR is implicitly converted to type TOTYPE.
8521 FN and ARGNUM are used for diagnostics. */
8522
8523static void
8524conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8525{
8526 /* Issue warnings about peculiar, but valid, uses of NULL. */
8527 if (TREE_CODE (totype) != BOOLEAN_TYPE
8528 && ARITHMETIC_TYPE_P (totype)
8529 && null_node_p (expr))
8530 {
8531 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8532 if (fn)
8533 {
8534 auto_diagnostic_group d;
8535 if (warning_at (loc, OPT_Wconversion_null,
8536 "passing NULL to non-pointer argument %P of %qD",
8537 argnum, fn))
8538 inform (get_fndecl_argument_location (fn, argnum),
8539 "declared here");
8540 }
8541 else
8542 warning_at (loc, OPT_Wconversion_null,
8543 "converting to non-pointer type %qT from NULL", totype);
8544 }
8545
8546 /* Issue warnings if "false" is converted to a NULL pointer */
8547 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8548 && TYPE_PTR_P (totype))
8549 {
8550 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8551 if (fn)
8552 {
8553 auto_diagnostic_group d;
8554 if (warning_at (loc, OPT_Wconversion_null,
8555 "converting %<false%> to pointer type for argument "
8556 "%P of %qD", argnum, fn))
8557 inform (get_fndecl_argument_location (fn, argnum),
8558 "declared here");
8559 }
8560 else
8561 warning_at (loc, OPT_Wconversion_null,
8562 "converting %<false%> to pointer type %qT", totype);
8563 }
8564 /* Handle zero as null pointer warnings for cases other
8565 than EQ_EXPR and NE_EXPR */
8566 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8567 && null_ptr_cst_p (t: expr))
8568 {
8569 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8570 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8571 }
8572}
8573
8574/* We gave a diagnostic during a conversion. If this was in the second
8575 standard conversion sequence of a user-defined conversion sequence, say
8576 which user-defined conversion. */
8577
8578static void
8579maybe_print_user_conv_context (conversion *convs)
8580{
8581 if (convs->user_conv_p)
8582 for (conversion *t = convs; t; t = next_conversion (conv: t))
8583 if (t->kind == ck_user)
8584 {
8585 print_z_candidate (loc: 0, N_(" after user-defined conversion:"),
8586 candidate: t->cand);
8587 break;
8588 }
8589}
8590
8591/* Locate the parameter with the given index within FNDECL.
8592 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8593 Return the location of the FNDECL itself if there are problems. */
8594
8595location_t
8596get_fndecl_argument_location (tree fndecl, int argnum)
8597{
8598 /* The locations of implicitly-declared functions are likely to be
8599 more meaningful than those of their parameters. */
8600 if (DECL_ARTIFICIAL (fndecl))
8601 return DECL_SOURCE_LOCATION (fndecl);
8602
8603 if (argnum == -1)
8604 return DECL_SOURCE_LOCATION (fndecl);
8605
8606 int i;
8607 tree param;
8608
8609 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8610 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8611 i < argnum && param;
8612 i++, param = TREE_CHAIN (param))
8613 ;
8614
8615 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8616 return the location of FNDECL. */
8617 if (param == NULL)
8618 return DECL_SOURCE_LOCATION (fndecl);
8619
8620 return DECL_SOURCE_LOCATION (param);
8621}
8622
8623/* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8624 within its declaration (or the fndecl itself if something went
8625 wrong). */
8626
8627void
8628maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum,
8629 const char *highlight_color)
8630{
8631 if (fn)
8632 {
8633 gcc_rich_location richloc (get_fndecl_argument_location (fndecl: fn, argnum));
8634 richloc.set_highlight_color (highlight_color);
8635 inform (&richloc,
8636 "initializing argument %P of %qD", argnum, fn);
8637 }
8638}
8639
8640/* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8641 the conversion, EXPR is the expression we're converting. */
8642
8643static void
8644maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8645{
8646 if (cxx_dialect >= cxx20)
8647 return;
8648
8649 tree type = TREE_TYPE (expr);
8650 type = strip_pointer_operator (type);
8651
8652 if (TREE_CODE (type) != ARRAY_TYPE
8653 || TYPE_DOMAIN (type) == NULL_TREE)
8654 return;
8655
8656 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8657 pedwarn (loc, OPT_Wc__20_extensions,
8658 "conversions to arrays of unknown bound "
8659 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8660}
8661
8662/* We call this recursively in convert_like_internal. */
8663static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8664 tsubst_flags_t);
8665
8666/* Adjust the result EXPR of a conversion to the expected type TOTYPE, which
8667 must be equivalent but might be a typedef. */
8668
8669static tree
8670maybe_adjust_type_name (tree type, tree expr, conversion_kind kind)
8671{
8672 if (expr == error_mark_node
8673 || processing_template_decl)
8674 return expr;
8675
8676 tree etype = TREE_TYPE (expr);
8677 if (etype == type)
8678 return expr;
8679
8680 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p (etype, type)
8681 || is_bitfield_expr_with_lowered_type (expr)
8682 || seen_error ());
8683
8684 if (SCALAR_TYPE_P (type)
8685 && (kind == ck_rvalue
8686 /* ??? We should be able to do this for ck_identity of more prvalue
8687 expressions, but checking !obvalue_p here breaks, so for now let's
8688 just handle NON_LVALUE_EXPR (such as the location wrapper for a
8689 literal). Maybe we want to express already-rvalue in the
8690 conversion somehow? */
8691 || TREE_CODE (expr) == NON_LVALUE_EXPR))
8692 expr = build_nop (type, expr);
8693
8694 return expr;
8695}
8696
8697/* Perform the conversions in CONVS on the expression EXPR. FN and
8698 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8699 indicates the `this' argument of a method. INNER is nonzero when
8700 being called to continue a conversion chain. It is negative when a
8701 reference binding will be applied, positive otherwise. If
8702 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8703 conversions will be emitted if appropriate. If C_CAST_P is true,
8704 this conversion is coming from a C-style cast; in that case,
8705 conversions to inaccessible bases are permitted. */
8706
8707static tree
8708convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8709 bool issue_conversion_warnings, bool c_cast_p,
8710 bool nested_p, tsubst_flags_t complain)
8711{
8712 tree totype = convs->type;
8713 enum diagnostics::kind diag_kind;
8714 int flags;
8715 location_t loc = cp_expr_loc_or_input_loc (t: expr);
8716 const bool stub_object_p = is_stub_object (expr);
8717
8718 if (convs->bad_p && !(complain & tf_error))
8719 return error_mark_node;
8720
8721 gcc_checking_assert (!TYPE_REF_P (TREE_TYPE (expr)));
8722
8723 if (convs->bad_p
8724 && convs->kind != ck_user
8725 && convs->kind != ck_list
8726 && convs->kind != ck_ambig
8727 && (convs->kind != ck_ref_bind
8728 || (convs->user_conv_p && next_conversion (conv: convs)->bad_p))
8729 && (convs->kind != ck_rvalue
8730 || SCALAR_TYPE_P (totype))
8731 && convs->kind != ck_base)
8732 {
8733 int complained = 0;
8734 conversion *t = convs;
8735
8736 /* Give a helpful error if this is bad because of excess braces. */
8737 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8738 && SCALAR_TYPE_P (totype)
8739 && CONSTRUCTOR_NELTS (expr) > 0
8740 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8741 {
8742 complained = permerror (loc, "too many braces around initializer "
8743 "for %qT", totype);
8744 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8745 && CONSTRUCTOR_NELTS (expr) == 1)
8746 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8747 }
8748
8749 /* Give a helpful error if this is bad because a conversion to bool
8750 from std::nullptr_t requires direct-initialization. */
8751 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8752 && TREE_CODE (totype) == BOOLEAN_TYPE)
8753 complained = permerror (loc, "converting to %qH from %qI requires "
8754 "direct-initialization",
8755 totype, TREE_TYPE (expr));
8756
8757 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8758 && SCALAR_FLOAT_TYPE_P (totype)
8759 && (extended_float_type_p (TREE_TYPE (expr))
8760 || extended_float_type_p (type: totype)))
8761 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8762 totype))
8763 {
8764 case 2:
8765 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8766 "converting to %qH from %qI with greater "
8767 "conversion rank", totype, TREE_TYPE (expr)))
8768 complained = 1;
8769 else if (!complained)
8770 complained = -1;
8771 break;
8772 case 3:
8773 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8774 "converting to %qH from %qI with unordered "
8775 "conversion rank", totype, TREE_TYPE (expr)))
8776 complained = 1;
8777 else if (!complained)
8778 complained = -1;
8779 break;
8780 default:
8781 break;
8782 }
8783
8784 for (; t ; t = next_conversion (conv: t))
8785 {
8786 if (t->kind == ck_user && t->cand->reason)
8787 {
8788 auto_diagnostic_group d;
8789 complained = permerror (loc, "invalid user-defined conversion "
8790 "from %qH to %qI", TREE_TYPE (expr),
8791 totype);
8792 if (complained)
8793 {
8794 auto_diagnostic_nesting_level sentinel;
8795 print_z_candidate (loc, N_("candidate is:"), candidate: t->cand);
8796 }
8797 expr = convert_like (t, expr, fn, argnum,
8798 /*issue_conversion_warnings=*/false,
8799 /*c_cast_p=*/false, /*nested_p=*/true,
8800 complain);
8801 break;
8802 }
8803 else if (t->kind == ck_user || !t->bad_p)
8804 {
8805 expr = convert_like (t, expr, fn, argnum,
8806 /*issue_conversion_warnings=*/false,
8807 /*c_cast_p=*/false, /*nested_p=*/true,
8808 complain);
8809 if (t->bad_p)
8810 complained = 1;
8811 break;
8812 }
8813 else if (t->kind == ck_ambig)
8814 return convert_like (t, expr, fn, argnum,
8815 /*issue_conversion_warnings=*/false,
8816 /*c_cast_p=*/false, /*nested_p=*/true,
8817 complain);
8818 else if (t->kind == ck_identity)
8819 break;
8820 }
8821 if (!complained && stub_object_p)
8822 {
8823 /* An error diagnosed within a trait, don't give extra labels. */
8824 error_at (loc, "invalid conversion from %qH to %qI",
8825 TREE_TYPE (expr), totype);
8826 complained = 1;
8827 }
8828 else if (!complained && expr != error_mark_node)
8829 {
8830 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8831 gcc_rich_location richloc (loc, &label, highlight_colors::percent_h);
8832 complained = permerror (&richloc,
8833 "invalid conversion from %qH to %qI",
8834 TREE_TYPE (expr), totype);
8835 if (complained)
8836 maybe_emit_indirection_note (loc, expr, expected_type: totype);
8837 }
8838 if (convs->kind == ck_ref_bind)
8839 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8840 LOOKUP_NORMAL, NULL_TREE,
8841 complain);
8842 else
8843 expr = cp_convert (totype, expr, complain);
8844 if (complained == 1)
8845 maybe_inform_about_fndecl_for_bogus_argument_init
8846 (fn, argnum, highlight_color: highlight_colors::percent_i);
8847 return expr;
8848 }
8849
8850 if (issue_conversion_warnings && (complain & tf_warning))
8851 conversion_null_warnings (totype, expr, fn, argnum);
8852
8853 switch (convs->kind)
8854 {
8855 case ck_user:
8856 {
8857 struct z_candidate *cand = convs->cand;
8858
8859 if (cand == NULL)
8860 /* We chose the surrogate function from add_conv_candidate, now we
8861 actually need to build the conversion. */
8862 cand = build_user_type_conversion_1 (totype, expr,
8863 LOOKUP_NO_CONVERSION, complain);
8864
8865 tree convfn = cand->fn;
8866
8867 /* When converting from an init list we consider explicit
8868 constructors, but actually trying to call one is an error. */
8869 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8870 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8871 /* Unless this is for direct-list-initialization. */
8872 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8873 /* And in C++98 a default constructor can't be explicit. */
8874 && cxx_dialect >= cxx11)
8875 {
8876 if (!(complain & tf_error))
8877 return error_mark_node;
8878 location_t loc = location_of (expr);
8879 if (CONSTRUCTOR_NELTS (expr) == 0
8880 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8881 {
8882 auto_diagnostic_group d;
8883 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8884 "would use explicit constructor %qD",
8885 totype, convfn))
8886 {
8887 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8888 convfn);
8889 inform (loc, "in C++11 and above a default constructor "
8890 "can be explicit");
8891 }
8892 }
8893 else
8894 {
8895 auto_diagnostic_group d;
8896 error ("converting to %qT from initializer list would use "
8897 "explicit constructor %qD", totype, convfn);
8898 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8899 convfn);
8900 }
8901 }
8902
8903 /* If we're initializing from {}, it's value-initialization. */
8904 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8905 && CONSTRUCTOR_NELTS (expr) == 0
8906 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8907 && !processing_template_decl)
8908 {
8909 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8910 return error_mark_node;
8911 expr = build_value_init (totype, complain);
8912 expr = get_target_expr (expr, complain);
8913 if (expr != error_mark_node)
8914 TARGET_EXPR_LIST_INIT_P (expr) = true;
8915 return expr;
8916 }
8917
8918 /* We don't know here whether EXPR is being used as an lvalue or
8919 rvalue, but we know it's read. */
8920 mark_exp_read (expr);
8921
8922 /* Give the conversion call the location of EXPR rather than the
8923 location of the context that caused the conversion. */
8924 iloc_sentinel ils (loc);
8925
8926 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8927 any more UDCs. */
8928 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8929 complain);
8930
8931 /* If this is a constructor or a function returning an aggr type,
8932 we need to build up a TARGET_EXPR. */
8933 if (DECL_CONSTRUCTOR_P (convfn))
8934 {
8935 expr = build_cplus_new (totype, expr, complain);
8936
8937 /* Remember that this was list-initialization. */
8938 if (convs->check_narrowing && expr != error_mark_node)
8939 TARGET_EXPR_LIST_INIT_P (expr) = true;
8940 }
8941
8942 return expr;
8943 }
8944 case ck_identity:
8945 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8946 {
8947 int nelts = CONSTRUCTOR_NELTS (expr);
8948 if (nelts == 0)
8949 expr = build_value_init (totype, complain);
8950 else if (nelts == 1)
8951 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8952 else
8953 gcc_unreachable ();
8954 }
8955 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8956 /*read_p=*/true, UNKNOWN_LOCATION,
8957 /*reject_builtin=*/true);
8958
8959 if (type_unknown_p (expr))
8960 expr = instantiate_type (totype, expr, complain);
8961 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8962 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8963 if (expr == null_node
8964 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8965 /* If __null has been converted to an integer type, we do not want to
8966 continue to warn about uses of EXPR as an integer, rather than as a
8967 pointer. */
8968 expr = build_int_cst (totype, 0);
8969 return maybe_adjust_type_name (type: totype, expr, kind: convs->kind);
8970 case ck_ambig:
8971 /* We leave bad_p off ck_ambig because overload resolution considers
8972 it valid, it just fails when we try to perform it. So we need to
8973 check complain here, too. */
8974 if (complain & tf_error)
8975 {
8976 /* Call build_user_type_conversion again for the error. */
8977 int flags = (convs->need_temporary_p
8978 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8979 build_user_type_conversion (totype, expr: convs->u.expr, flags, complain);
8980 gcc_assert (seen_error ());
8981 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8982 }
8983 return error_mark_node;
8984
8985 case ck_list:
8986 {
8987 /* Conversion to std::initializer_list<T>. */
8988 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8989 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (expr);
8990 tree array;
8991
8992 if (tree init = maybe_init_list_as_array (elttype, init: expr))
8993 {
8994 elttype
8995 = cp_build_qualified_type (elttype, (cp_type_quals (elttype)
8996 | TYPE_QUAL_CONST));
8997 tree index_type = TYPE_DOMAIN (TREE_TYPE (init));
8998 array = build_cplus_array_type (elttype, index_type);
8999 len = TREE_INT_CST_LOW (TYPE_MAX_VALUE (index_type)) + 1;
9000 array = build_vec_init_expr (array, init, complain);
9001 array = get_target_expr (array);
9002 array = cp_build_addr_expr (array, complain);
9003 }
9004 else if (len)
9005 {
9006 tree val;
9007 unsigned ix;
9008 tree new_ctor = build_constructor (init_list_type_node, NULL);
9009
9010 /* Convert all the elements. */
9011 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
9012 {
9013 if (TREE_CODE (val) == RAW_DATA_CST)
9014 {
9015 /* For conversion to initializer_list<unsigned char> or
9016 initializer_list<char> or initializer_list<signed char>
9017 we can optimize and keep RAW_DATA_CST with adjusted
9018 type if we report narrowing errors if needed, for
9019 others this converts each element separately. */
9020 if (convs->u.list[ix]->kind == ck_std)
9021 {
9022 tree et = convs->u.list[ix]->type;
9023 conversion *next = next_conversion (conv: convs->u.list[ix]);
9024 gcc_assert (et
9025 && (TREE_CODE (et) == INTEGER_TYPE
9026 || is_byte_access_type (et))
9027 && TYPE_PRECISION (et) == CHAR_BIT
9028 && next
9029 && next->kind == ck_identity);
9030 if (!TYPE_UNSIGNED (et)
9031 /* For RAW_DATA_CST, TREE_TYPE (val) can be
9032 either integer_type_node (when it has been
9033 created by the lexer from CPP_EMBED) or
9034 after digestion/conversion some integral
9035 type with CHAR_BIT precision. For int with
9036 precision higher than CHAR_BIT or unsigned char
9037 diagnose narrowing conversions from
9038 that int/unsigned char to signed char if any
9039 byte has most significant bit set. */
9040 && (TYPE_UNSIGNED (TREE_TYPE (val))
9041 || (TYPE_PRECISION (TREE_TYPE (val))
9042 > CHAR_BIT)))
9043 for (int i = 0; i < RAW_DATA_LENGTH (val); ++i)
9044 {
9045 if (RAW_DATA_SCHAR_ELT (val, i) >= 0)
9046 continue;
9047 else if (complain & tf_error)
9048 {
9049 location_t loc
9050 = cp_expr_loc_or_input_loc (t: val);
9051 int savederrorcount = errorcount;
9052 permerror_opt (loc, OPT_Wnarrowing,
9053 "narrowing conversion of "
9054 "%qd from %qH to %qI",
9055 RAW_DATA_UCHAR_ELT (val, i),
9056 TREE_TYPE (val), et);
9057 if (errorcount != savederrorcount)
9058 return error_mark_node;
9059 }
9060 else
9061 return error_mark_node;
9062 }
9063 tree sub = copy_node (val);
9064 TREE_TYPE (sub) = et;
9065 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
9066 NULL_TREE, sub);
9067 }
9068 else
9069 {
9070 conversion *conv = convs->u.list[ix];
9071 gcc_assert (conv->kind == ck_list);
9072 for (int i = 0; i < RAW_DATA_LENGTH (val); ++i)
9073 {
9074 tree elt
9075 = build_int_cst (TREE_TYPE (val),
9076 RAW_DATA_UCHAR_ELT (val, i));
9077 tree sub
9078 = convert_like (conv->u.list[i], elt,
9079 fn, argnum, false, false,
9080 /*nested_p=*/true, complain);
9081 if (sub == error_mark_node)
9082 return sub;
9083 if (!check_narrowing (TREE_TYPE (sub), elt,
9084 complain))
9085 return error_mark_node;
9086 tree nc = new_ctor;
9087 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (nc),
9088 NULL_TREE, sub);
9089 if (!TREE_CONSTANT (sub))
9090 TREE_CONSTANT (new_ctor) = false;
9091 }
9092 }
9093 len += RAW_DATA_LENGTH (val) - 1;
9094 continue;
9095 }
9096 tree sub = convert_like (convs->u.list[ix], val, fn,
9097 argnum, false, false,
9098 /*nested_p=*/true, complain);
9099 if (sub == error_mark_node)
9100 return sub;
9101 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
9102 && !check_narrowing (TREE_TYPE (sub), val, complain))
9103 return error_mark_node;
9104 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
9105 NULL_TREE, sub);
9106 if (!TREE_CONSTANT (sub))
9107 TREE_CONSTANT (new_ctor) = false;
9108 }
9109 /* Build up the array. */
9110 elttype
9111 = cp_build_qualified_type (elttype, (cp_type_quals (elttype)
9112 | TYPE_QUAL_CONST));
9113 array = build_array_of_n_type (elttype, len);
9114 array = finish_compound_literal (array, new_ctor, complain);
9115 /* This is dubious now, should be blessed by P2752. */
9116 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
9117 array = cp_build_addr_expr (array, complain);
9118 }
9119 else
9120 array = nullptr_node;
9121
9122 array = cp_convert (build_pointer_type (elttype), array, complain);
9123 if (array == error_mark_node)
9124 return error_mark_node;
9125
9126 /* Build up the initializer_list object. Note: fail gracefully
9127 if the object cannot be completed because, for example, no
9128 definition is provided (c++/80956). */
9129 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
9130 if (!totype)
9131 return error_mark_node;
9132 tree field = next_aggregate_field (TYPE_FIELDS (totype));
9133 vec<constructor_elt, va_gc> *vec = NULL;
9134 CONSTRUCTOR_APPEND_ELT (vec, field, array);
9135 field = next_aggregate_field (DECL_CHAIN (field));
9136 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
9137 tree new_ctor = build_constructor (totype, vec);
9138 return get_target_expr (new_ctor, complain);
9139 }
9140
9141 case ck_aggr:
9142 if (TREE_CODE (totype) == COMPLEX_TYPE)
9143 {
9144 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
9145 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
9146 real = perform_implicit_conversion (TREE_TYPE (totype),
9147 real, complain);
9148 imag = perform_implicit_conversion (TREE_TYPE (totype),
9149 imag, complain);
9150 expr = build2 (COMPLEX_EXPR, totype, real, imag);
9151 return expr;
9152 }
9153 expr = reshape_init (totype, expr, complain);
9154 expr = get_target_expr (digest_init (totype, expr, complain),
9155 complain);
9156 if (expr != error_mark_node)
9157 TARGET_EXPR_LIST_INIT_P (expr) = true;
9158 return expr;
9159
9160 default:
9161 break;
9162 };
9163
9164 conversion *nc = next_conversion (conv: convs);
9165 if (convs->kind == ck_ref_bind && nc->kind == ck_qual
9166 && !convs->need_temporary_p)
9167 /* direct_reference_binding might have inserted a ck_qual under
9168 this ck_ref_bind for the benefit of conversion sequence ranking.
9169 Don't actually perform that conversion. */
9170 nc = next_conversion (conv: nc);
9171
9172 expr = convert_like (nc, expr, fn, argnum,
9173 convs->kind == ck_ref_bind
9174 ? issue_conversion_warnings : false,
9175 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
9176 if (expr == error_mark_node)
9177 return error_mark_node;
9178
9179 switch (convs->kind)
9180 {
9181 case ck_rvalue:
9182 expr = decay_conversion (expr, complain);
9183 if (expr == error_mark_node)
9184 {
9185 if (complain & tf_error)
9186 {
9187 auto_diagnostic_group d;
9188 maybe_print_user_conv_context (convs);
9189 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
9190 }
9191 return error_mark_node;
9192 }
9193
9194 if ((complain & tf_warning) && fn
9195 && warn_suggest_attribute_format)
9196 {
9197 tree rhstype = TREE_TYPE (expr);
9198 const enum tree_code coder = TREE_CODE (rhstype);
9199 const enum tree_code codel = TREE_CODE (totype);
9200 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9201 && coder == codel
9202 && check_missing_format_attribute (totype, rhstype))
9203 warning (OPT_Wsuggest_attribute_format,
9204 "argument of function call might be a candidate "
9205 "for a format attribute");
9206 }
9207
9208 if (! MAYBE_CLASS_TYPE_P (totype))
9209 return maybe_adjust_type_name (type: totype, expr, kind: convs->kind);
9210
9211 /* Don't introduce copies when passing arguments along to the inherited
9212 constructor. */
9213 if (current_function_decl
9214 && flag_new_inheriting_ctors
9215 && DECL_INHERITED_CTOR (current_function_decl))
9216 return expr;
9217
9218 if (TREE_CODE (expr) == TARGET_EXPR
9219 && TARGET_EXPR_LIST_INIT_P (expr))
9220 /* Copy-list-initialization doesn't actually involve a copy. */
9221 return expr;
9222
9223 /* Fall through. */
9224 case ck_base:
9225 if (convs->kind == ck_base && !convs->need_temporary_p)
9226 {
9227 /* We are going to bind a reference directly to a base-class
9228 subobject of EXPR. */
9229 /* Build an expression for `*((base*) &expr)'. */
9230 expr = convert_to_base (expr, totype,
9231 !c_cast_p, /*nonnull=*/true, complain);
9232 return expr;
9233 }
9234
9235 /* Copy-initialization where the cv-unqualified version of the source
9236 type is the same class as, or a derived class of, the class of the
9237 destination [is treated as direct-initialization]. [dcl.init] */
9238 flags = LOOKUP_NORMAL;
9239 /* This conversion is being done in the context of a user-defined
9240 conversion (i.e. the second step of copy-initialization), so
9241 don't allow any more. */
9242 if (convs->user_conv_p)
9243 flags |= LOOKUP_NO_CONVERSION;
9244 /* We might be performing a conversion of the argument
9245 to the user-defined conversion, i.e., not a conversion of the
9246 result of the user-defined conversion. In which case we skip
9247 explicit constructors. */
9248 if (convs->copy_init_p)
9249 flags |= LOOKUP_ONLYCONVERTING;
9250 expr = build_temp (expr, type: totype, flags, diagnostic_kind: &diag_kind, complain);
9251 if (diag_kind != diagnostics::kind::unspecified && complain)
9252 {
9253 auto_diagnostic_group d;
9254 maybe_print_user_conv_context (convs);
9255 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
9256 }
9257
9258 return build_cplus_new (totype, expr, complain);
9259
9260 case ck_ref_bind:
9261 {
9262 tree ref_type = totype;
9263
9264 if (convs->bad_p && !next_conversion (conv: convs)->bad_p)
9265 {
9266 tree extype = TREE_TYPE (expr);
9267 auto_diagnostic_group d;
9268 if (TYPE_REF_IS_RVALUE (ref_type)
9269 && lvalue_p (expr))
9270 error_at (loc, "cannot bind rvalue reference of type %qH to "
9271 "lvalue of type %qI", totype, extype);
9272 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
9273 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
9274 {
9275 conversion *next = next_conversion (conv: convs);
9276 if (next->kind == ck_std)
9277 {
9278 next = next_conversion (conv: next);
9279 error_at (loc, "cannot bind non-const lvalue reference of "
9280 "type %qH to a value of type %qI",
9281 totype, next->type);
9282 }
9283 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
9284 error_at (loc, "cannot bind non-const lvalue reference of "
9285 "type %qH to an rvalue of type %qI", totype, extype);
9286 else // extype is volatile
9287 error_at (loc, "cannot bind lvalue reference of type "
9288 "%qH to an rvalue of type %qI", totype,
9289 extype);
9290 }
9291 else if (!reference_compatible_p (TREE_TYPE (totype), t2: extype))
9292 {
9293 /* If we're converting from T[] to T[N], don't talk
9294 about discarding qualifiers. (Converting from T[N] to
9295 T[] is allowed by P0388R4.) */
9296 if (TREE_CODE (extype) == ARRAY_TYPE
9297 && TYPE_DOMAIN (extype) == NULL_TREE
9298 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
9299 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
9300 error_at (loc, "cannot bind reference of type %qH to %qI "
9301 "due to different array bounds", totype, extype);
9302 else
9303 error_at (loc, "binding reference of type %qH to %qI "
9304 "discards qualifiers", totype, extype);
9305 }
9306 else
9307 gcc_unreachable ();
9308 maybe_print_user_conv_context (convs);
9309 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
9310
9311 return error_mark_node;
9312 }
9313 else if (complain & tf_warning)
9314 maybe_warn_array_conv (loc, c: convs, expr);
9315
9316 /* If necessary, create a temporary.
9317
9318 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
9319 that need temporaries, even when their types are reference
9320 compatible with the type of reference being bound, so the
9321 upcoming call to cp_build_addr_expr doesn't fail. */
9322 if (convs->need_temporary_p
9323 || TREE_CODE (expr) == CONSTRUCTOR
9324 || TREE_CODE (expr) == VA_ARG_EXPR)
9325 {
9326 /* Otherwise, a temporary of type "cv1 T1" is created and
9327 initialized from the initializer expression using the rules
9328 for a non-reference copy-initialization (8.5). */
9329
9330 tree type = TREE_TYPE (ref_type);
9331 cp_lvalue_kind lvalue = lvalue_kind (expr);
9332
9333 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
9334 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
9335 && !TYPE_REF_IS_RVALUE (ref_type))
9336 {
9337 /* If the reference is volatile or non-const, we
9338 cannot create a temporary. */
9339 if (complain & tf_error)
9340 {
9341 if (lvalue & clk_bitfield)
9342 error_at (loc, "cannot bind bit-field %qE to %qT",
9343 expr, ref_type);
9344 else if (lvalue & clk_packed)
9345 error_at (loc, "cannot bind packed field %qE to %qT",
9346 expr, ref_type);
9347 else
9348 error_at (loc, "cannot bind rvalue %qE to %qT",
9349 expr, ref_type);
9350 }
9351 return error_mark_node;
9352 }
9353 /* If the source is a packed field, and we must use a copy
9354 constructor, then building the target expr will require
9355 binding the field to the reference parameter to the
9356 copy constructor, and we'll end up with an infinite
9357 loop. If we can use a bitwise copy, then we'll be
9358 OK. */
9359 if ((lvalue & clk_packed)
9360 && CLASS_TYPE_P (type)
9361 && type_has_nontrivial_copy_init (type))
9362 {
9363 error_at (loc, "cannot bind packed field %qE to %qT",
9364 expr, ref_type);
9365 return error_mark_node;
9366 }
9367 if (lvalue & clk_bitfield)
9368 {
9369 expr = convert_bitfield_to_declared_type (expr);
9370 expr = fold_convert (type, expr);
9371 }
9372
9373 /* Creating &TARGET_EXPR<> in a template would break when
9374 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
9375 instead. This can happen even when there's no class
9376 involved, e.g., when converting an integer to a reference
9377 type. */
9378 if (processing_template_decl)
9379 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
9380 expr = build_target_expr_with_type (expr, type, complain);
9381 }
9382
9383 /* Take the address of the thing to which we will bind the
9384 reference. */
9385 expr = cp_build_addr_expr (expr, complain);
9386 if (expr == error_mark_node)
9387 return error_mark_node;
9388
9389 /* Convert it to a pointer to the type referred to by the
9390 reference. This will adjust the pointer if a derived to
9391 base conversion is being performed. */
9392 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
9393 expr, complain);
9394 /* Convert the pointer to the desired reference type. */
9395 return build_nop (ref_type, expr);
9396 }
9397
9398 case ck_lvalue:
9399 return decay_conversion (expr, complain);
9400
9401 case ck_fnptr:
9402 /* ??? Should the address of a transaction-safe pointer point to the TM
9403 clone, and this conversion look up the primary function? */
9404 return build_nop (totype, expr);
9405
9406 case ck_qual:
9407 /* Warn about deprecated conversion if appropriate. */
9408 if (complain & tf_warning)
9409 {
9410 string_conv_p (totype, expr, 1);
9411 maybe_warn_array_conv (loc, c: convs, expr);
9412 }
9413 break;
9414
9415 case ck_ptr:
9416 if (convs->base_p)
9417 expr = convert_to_base (expr, totype, !c_cast_p,
9418 /*nonnull=*/false, complain);
9419 return build_nop (totype, expr);
9420
9421 case ck_pmem:
9422 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
9423 c_cast_p, complain);
9424
9425 default:
9426 break;
9427 }
9428
9429 if (convs->check_narrowing
9430 && !check_narrowing (totype, expr, complain,
9431 convs->check_narrowing_const_only))
9432 return error_mark_node;
9433
9434 warning_sentinel w (warn_zero_as_null_pointer_constant);
9435 if (issue_conversion_warnings)
9436 expr = cp_convert_and_check (totype, expr, complain);
9437 else
9438 {
9439 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
9440 expr = TREE_OPERAND (expr, 0);
9441 expr = cp_convert (totype, expr, complain);
9442 }
9443
9444 return expr;
9445}
9446
9447/* Return true if converting FROM to TO is unsafe in a template. */
9448
9449static bool
9450conv_unsafe_in_template_p (tree to, tree from)
9451{
9452 /* Converting classes involves TARGET_EXPR. */
9453 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
9454 return true;
9455
9456 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
9457 doesn't handle. */
9458 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
9459 return true;
9460
9461 /* Converting integer to real isn't a trivial conversion, either. */
9462 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
9463 return true;
9464
9465 return false;
9466}
9467
9468/* Wrapper for convert_like_internal that handles creating
9469 IMPLICIT_CONV_EXPR. */
9470
9471static tree
9472convert_like (conversion *convs, tree expr, tree fn, int argnum,
9473 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
9474 tsubst_flags_t complain)
9475{
9476 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
9477 and creating a CALL_EXPR in a template breaks in finish_call_expr
9478 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
9479 created such codes e.g. when calling a user-defined conversion
9480 function. */
9481 tree conv_expr = NULL_TREE;
9482 if (processing_template_decl
9483 && convs->kind != ck_identity
9484 && conv_unsafe_in_template_p (to: convs->type, TREE_TYPE (expr)))
9485 {
9486 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
9487 if (convs->kind != ck_ref_bind)
9488 conv_expr = convert_from_reference (conv_expr);
9489 if (!convs->bad_p)
9490 return conv_expr;
9491 /* Do the normal processing to give the bad_p errors. But we still
9492 need to return the IMPLICIT_CONV_EXPR, unless we're returning
9493 error_mark_node. */
9494 }
9495 expr = convert_like_internal (convs, expr, fn, argnum,
9496 issue_conversion_warnings, c_cast_p,
9497 nested_p, complain);
9498 if (expr == error_mark_node)
9499 return error_mark_node;
9500 return conv_expr ? conv_expr : expr;
9501}
9502
9503/* Convenience wrapper for convert_like. */
9504
9505static inline tree
9506convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
9507{
9508 return convert_like (convs, expr, NULL_TREE, argnum: 0,
9509 /*issue_conversion_warnings=*/true,
9510 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9511}
9512
9513/* Convenience wrapper for convert_like. */
9514
9515static inline tree
9516convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
9517 tsubst_flags_t complain)
9518{
9519 return convert_like (convs, expr, fn, argnum,
9520 /*issue_conversion_warnings=*/true,
9521 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9522}
9523
9524/* ARG is being passed to a varargs function. Perform any conversions
9525 required. Return the converted value. */
9526
9527tree
9528convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
9529{
9530 tree arg_type = TREE_TYPE (arg);
9531 location_t loc = cp_expr_loc_or_input_loc (t: arg);
9532
9533 /* [expr.call]
9534
9535 If the argument has integral or enumeration type that is subject
9536 to the integral promotions (_conv.prom_), or a floating-point
9537 type that is subject to the floating-point promotion
9538 (_conv.fpprom_), the value of the argument is converted to the
9539 promoted type before the call. */
9540 if (SCALAR_FLOAT_TYPE_P (arg_type)
9541 && (TYPE_PRECISION (arg_type)
9542 < TYPE_PRECISION (double_type_node))
9543 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
9544 && !extended_float_type_p (type: arg_type))
9545 {
9546 if ((complain & tf_warning)
9547 && warn_double_promotion && !c_inhibit_evaluation_warnings)
9548 warning_at (loc, OPT_Wdouble_promotion,
9549 "implicit conversion from %qH to %qI when passing "
9550 "argument to function",
9551 arg_type, double_type_node);
9552 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
9553 arg = TREE_OPERAND (arg, 0);
9554 arg = mark_rvalue_use (arg);
9555 arg = convert_to_real_nofold (double_type_node, x: arg);
9556 }
9557 else if (NULLPTR_TYPE_P (arg_type))
9558 {
9559 arg = mark_rvalue_use (arg);
9560 if (TREE_SIDE_EFFECTS (arg))
9561 {
9562 warning_sentinel w(warn_unused_result);
9563 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9564 }
9565 else
9566 arg = null_pointer_node;
9567 }
9568 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9569 {
9570 if (SCOPED_ENUM_P (arg_type))
9571 {
9572 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9573 complain);
9574 prom = cp_perform_integral_promotions (prom, complain);
9575 if (abi_version_crosses (6)
9576 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9577 && (complain & tf_warning))
9578 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9579 " as %qT before %<-fabi-version=6%>, %qT after",
9580 arg_type,
9581 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9582 if (!abi_version_at_least (6))
9583 arg = prom;
9584 }
9585 else
9586 arg = cp_perform_integral_promotions (arg, complain);
9587 }
9588 else
9589 /* [expr.call]
9590
9591 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9592 standard conversions are performed. */
9593 arg = decay_conversion (arg, complain);
9594
9595 arg = require_complete_type (arg, complain);
9596 arg_type = TREE_TYPE (arg);
9597
9598 if (arg != error_mark_node
9599 /* In a template (or ill-formed code), we can have an incomplete type
9600 even after require_complete_type, in which case we don't know
9601 whether it has trivial copy or not. */
9602 && COMPLETE_TYPE_P (arg_type)
9603 && !cp_unevaluated_operand)
9604 {
9605 /* [expr.call] 5.2.2/7:
9606 Passing a potentially-evaluated argument of class type (Clause 9)
9607 with a non-trivial copy constructor or a non-trivial destructor
9608 with no corresponding parameter is conditionally-supported, with
9609 implementation-defined semantics.
9610
9611 We support it as pass-by-invisible-reference, just like a normal
9612 value parameter.
9613
9614 If the call appears in the context of a sizeof expression,
9615 it is not potentially-evaluated. */
9616 if (type_has_nontrivial_copy_init (arg_type)
9617 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9618 {
9619 arg = force_rvalue (arg, complain);
9620 if (complain & tf_warning)
9621 warning (OPT_Wconditionally_supported,
9622 "passing objects of non-trivially-copyable "
9623 "type %q#T through %<...%> is conditionally supported",
9624 arg_type);
9625 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9626 }
9627 /* Build up a real lvalue-to-rvalue conversion in case the
9628 copy constructor is trivial but not callable. */
9629 else if (CLASS_TYPE_P (arg_type))
9630 force_rvalue (arg, complain);
9631
9632 }
9633
9634 return arg;
9635}
9636
9637/* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9638
9639tree
9640build_x_va_arg (location_t loc, tree expr, tree type)
9641{
9642 if (processing_template_decl)
9643 {
9644 tree r = build_min (VA_ARG_EXPR, type, expr);
9645 SET_EXPR_LOCATION (r, loc);
9646 return r;
9647 }
9648
9649 type = complete_type_or_else (type, NULL_TREE);
9650
9651 if (expr == error_mark_node || !type)
9652 return error_mark_node;
9653
9654 expr = mark_lvalue_use (expr);
9655
9656 if (TYPE_REF_P (type))
9657 {
9658 error ("cannot receive reference type %qT through %<...%>", type);
9659 return error_mark_node;
9660 }
9661
9662 if (type_has_nontrivial_copy_init (type)
9663 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9664 {
9665 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9666 it as pass by invisible reference. */
9667 warning_at (loc, OPT_Wconditionally_supported,
9668 "receiving objects of non-trivially-copyable type %q#T "
9669 "through %<...%> is conditionally-supported", type);
9670
9671 tree ref = cp_build_reference_type (type, false);
9672 expr = build_va_arg (loc, expr, ref);
9673 return convert_from_reference (expr);
9674 }
9675
9676 tree ret = build_va_arg (loc, expr, type);
9677 if (CLASS_TYPE_P (type))
9678 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9679 know how to handle it. */
9680 ret = get_target_expr (ret);
9681 return ret;
9682}
9683
9684/* TYPE has been given to va_arg. Apply the default conversions which
9685 would have happened when passed via ellipsis. Return the promoted
9686 type, or the passed type if there is no change. */
9687
9688tree
9689cxx_type_promotes_to (tree type)
9690{
9691 tree promote;
9692
9693 /* Perform the array-to-pointer and function-to-pointer
9694 conversions. */
9695 type = type_decays_to (type);
9696
9697 promote = type_promotes_to (type);
9698 if (same_type_p (type, promote))
9699 promote = type;
9700
9701 return promote;
9702}
9703
9704/* ARG is a default argument expression being passed to a parameter of
9705 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9706 zero-based argument number. Do any required conversions. Return
9707 the converted value. */
9708
9709static GTY(()) vec<tree, va_gc> *default_arg_context;
9710void
9711push_defarg_context (tree fn)
9712{ vec_safe_push (v&: default_arg_context, obj: fn); }
9713
9714void
9715pop_defarg_context (void)
9716{ default_arg_context->pop (); }
9717
9718tree
9719convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9720 tsubst_flags_t complain)
9721{
9722 int i;
9723 tree t;
9724
9725 /* See through clones. */
9726 fn = DECL_ORIGIN (fn);
9727 /* And inheriting ctors. */
9728 if (flag_new_inheriting_ctors)
9729 fn = strip_inheriting_ctors (fn);
9730
9731 /* Detect recursion. */
9732 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9733 if (t == fn)
9734 {
9735 if (complain & tf_error)
9736 error ("recursive evaluation of default argument for %q#D", fn);
9737 return error_mark_node;
9738 }
9739
9740 /* If the ARG is an unparsed default argument expression, the
9741 conversion cannot be performed. */
9742 if (TREE_CODE (arg) == DEFERRED_PARSE)
9743 {
9744 if (complain & tf_error)
9745 error ("call to %qD uses the default argument for parameter %P, which "
9746 "is not yet defined", fn, parmnum);
9747 return error_mark_node;
9748 }
9749
9750 push_defarg_context (fn);
9751
9752 if (fn && DECL_TEMPLATE_INFO (fn))
9753 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9754
9755 /* Due to:
9756
9757 [dcl.fct.default]
9758
9759 The names in the expression are bound, and the semantic
9760 constraints are checked, at the point where the default
9761 expressions appears.
9762
9763 we must not perform access checks here. */
9764 push_deferring_access_checks (dk_no_check);
9765 /* We must make a copy of ARG, in case subsequent processing
9766 alters any part of it. */
9767 arg = break_out_target_exprs (arg, /*clear location*/true);
9768
9769 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9770 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9771 complain);
9772 arg = convert_for_arg_passing (type, arg, complain);
9773 pop_deferring_access_checks();
9774
9775 pop_defarg_context ();
9776
9777 return arg;
9778}
9779
9780/* Returns the type which will really be used for passing an argument of
9781 type TYPE. */
9782
9783tree
9784type_passed_as (tree type)
9785{
9786 /* Pass classes with copy ctors by invisible reference. */
9787 if (TREE_ADDRESSABLE (type))
9788 type = build_reference_type (type);
9789
9790 return type;
9791}
9792
9793/* Actually perform the appropriate conversion. */
9794
9795tree
9796convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9797{
9798 tree bitfield_type;
9799
9800 /* If VAL is a bitfield, then -- since it has already been converted
9801 to TYPE -- it cannot have a precision greater than TYPE.
9802
9803 If it has a smaller precision, we must widen it here. For
9804 example, passing "int f:3;" to a function expecting an "int" will
9805 not result in any conversion before this point.
9806
9807 If the precision is the same we must not risk widening. For
9808 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9809 often have type "int", even though the C++ type for the field is
9810 "long long". If the value is being passed to a function
9811 expecting an "int", then no conversions will be required. But,
9812 if we call convert_bitfield_to_declared_type, the bitfield will
9813 be converted to "long long". */
9814 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9815 if (bitfield_type
9816 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9817 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), x: val);
9818
9819 if (val == error_mark_node)
9820 ;
9821 /* Pass classes with copy ctors by invisible reference. */
9822 else if (TREE_ADDRESSABLE (type))
9823 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9824 if (complain & tf_warning)
9825 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (t: val));
9826
9827 if (complain & tf_warning)
9828 warn_for_address_of_packed_member (type, val);
9829
9830 /* gimplify_arg elides TARGET_EXPRs that initialize a function argument,
9831 unless the initializer is a CONSTRUCTOR. In that case, we fail to
9832 elide the copy anyway. See that function for more information. */
9833 if (SIMPLE_TARGET_EXPR_P (val)
9834 && TREE_CODE (TARGET_EXPR_INITIAL (val)) != CONSTRUCTOR)
9835 set_target_expr_eliding (val);
9836
9837 return val;
9838}
9839
9840/* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9841 which just decay_conversion or no conversions at all should be done.
9842 This is true for some builtins which don't act like normal functions.
9843 Return 2 if just decay_conversion and removal of excess precision should
9844 be done, 1 if just decay_conversion. Return 3 for special treatment of
9845 the 3rd argument for __builtin_*_overflow_p. Return 4 for special
9846 treatment of the 1st argument for
9847 __builtin_{clz,ctz,clrsb,ffs,parity,popcount}g. */
9848
9849int
9850magic_varargs_p (tree fn)
9851{
9852 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9853 switch (DECL_FUNCTION_CODE (decl: fn))
9854 {
9855 case BUILT_IN_CLASSIFY_TYPE:
9856 case BUILT_IN_CONSTANT_P:
9857 case BUILT_IN_NEXT_ARG:
9858 case BUILT_IN_VA_START:
9859 return 1;
9860
9861 case BUILT_IN_ADD_OVERFLOW_P:
9862 case BUILT_IN_SUB_OVERFLOW_P:
9863 case BUILT_IN_MUL_OVERFLOW_P:
9864 return 3;
9865
9866 case BUILT_IN_ISFINITE:
9867 case BUILT_IN_ISINF:
9868 case BUILT_IN_ISINF_SIGN:
9869 case BUILT_IN_ISNAN:
9870 case BUILT_IN_ISNORMAL:
9871 case BUILT_IN_FPCLASSIFY:
9872 return 2;
9873
9874 case BUILT_IN_CLZG:
9875 case BUILT_IN_CTZG:
9876 case BUILT_IN_CLRSBG:
9877 case BUILT_IN_FFSG:
9878 case BUILT_IN_PARITYG:
9879 case BUILT_IN_POPCOUNTG:
9880 return 4;
9881
9882 default:
9883 return lookup_attribute (attr_name: "type generic",
9884 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9885 }
9886
9887 return 0;
9888}
9889
9890/* Returns the decl of the dispatcher function if FN is a function version. */
9891
9892tree
9893get_function_version_dispatcher (tree fn)
9894{
9895 tree dispatcher_decl = NULL;
9896
9897 if (DECL_LOCAL_DECL_P (fn))
9898 fn = DECL_LOCAL_DECL_ALIAS (fn);
9899
9900 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9901 && DECL_FUNCTION_VERSIONED (fn));
9902
9903 gcc_assert (targetm.get_function_versions_dispatcher);
9904 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9905
9906 if (dispatcher_decl == NULL)
9907 {
9908 error_at (input_location, "use of multiversioned function "
9909 "without a default");
9910 return NULL;
9911 }
9912
9913 retrofit_lang_decl (dispatcher_decl);
9914 gcc_assert (dispatcher_decl != NULL);
9915 return dispatcher_decl;
9916}
9917
9918/* fn is a function version dispatcher that is marked used. Mark all the
9919 semantically identical function versions it will dispatch as used. */
9920
9921void
9922mark_versions_used (tree fn)
9923{
9924 struct cgraph_node *node;
9925 struct cgraph_function_version_info *node_v;
9926 struct cgraph_function_version_info *it_v;
9927
9928 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9929
9930 node = cgraph_node::get (decl: fn);
9931 if (node == NULL)
9932 return;
9933
9934 gcc_assert (node->dispatcher_function);
9935
9936 node_v = node->function_version ();
9937 if (node_v == NULL)
9938 return;
9939
9940 /* All semantically identical versions are chained. Traverse and mark each
9941 one of them as used. */
9942 it_v = node_v->next;
9943 while (it_v != NULL)
9944 {
9945 mark_used (it_v->this_node->decl);
9946 it_v = it_v->next;
9947 }
9948}
9949
9950/* Build a call to "the copy constructor" for the type of A, even if it
9951 wouldn't be selected by normal overload resolution. Used for
9952 diagnostics. */
9953
9954static tree
9955call_copy_ctor (tree a, tsubst_flags_t complain)
9956{
9957 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9958 tree binfo = TYPE_BINFO (ctype);
9959 tree copy = get_copy_ctor (ctype, complain);
9960 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9961 tree ob = build_dummy_object (ctype);
9962 releasing_vec args (make_tree_vector_single (a));
9963 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9964 LOOKUP_NORMAL, NULL, complain);
9965 return r;
9966}
9967
9968/* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9969
9970static tree
9971base_ctor_for (tree complete_ctor)
9972{
9973 tree clone;
9974 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9975 if (DECL_BASE_CONSTRUCTOR_P (clone))
9976 return clone;
9977 return NULL_TREE;
9978}
9979
9980/* Try to make EXP suitable to be used as the initializer for a base subobject,
9981 and return whether we were successful. EXP must have already been cleared
9982 by unsafe_copy_elision_p{,_opt}. */
9983
9984static bool
9985make_base_init_ok (tree exp)
9986{
9987 if (TREE_CODE (exp) == TARGET_EXPR)
9988 exp = TARGET_EXPR_INITIAL (exp);
9989 while (TREE_CODE (exp) == COMPOUND_EXPR)
9990 exp = TREE_OPERAND (exp, 1);
9991 if (TREE_CODE (exp) == COND_EXPR)
9992 {
9993 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9994 if (tree op1 = TREE_OPERAND (exp, 1))
9995 {
9996 bool r1 = make_base_init_ok (exp: op1);
9997 /* If unsafe_copy_elision_p was false, the arms should match. */
9998 gcc_assert (r1 == ret);
9999 }
10000 return ret;
10001 }
10002 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
10003 /* A trivial copy is OK. */
10004 return true;
10005 if (!AGGR_INIT_VIA_CTOR_P (exp))
10006 /* unsafe_copy_elision_p_opt must have said this is OK. */
10007 return true;
10008 tree fn = cp_get_callee_fndecl_nofold (exp);
10009 if (DECL_BASE_CONSTRUCTOR_P (fn))
10010 return true;
10011 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
10012 fn = base_ctor_for (complete_ctor: fn);
10013 if (!fn || DECL_HAS_VTT_PARM_P (fn))
10014 /* The base constructor has more parameters, so we can't just change the
10015 call target. It would be possible to splice in the appropriate
10016 arguments, but probably not worth the complexity. */
10017 return false;
10018 mark_used (fn);
10019 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
10020 return true;
10021}
10022
10023/* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
10024 neither of which can be used for return by invisible reference. We avoid
10025 doing C++17 mandatory copy elision for either of these cases.
10026
10027 This returns non-zero even if the type of T has no tail padding that other
10028 data could be allocated into, because that depends on the particular ABI.
10029 unsafe_copy_elision_p_opt does consider whether there is padding. */
10030
10031int
10032unsafe_return_slot_p (tree t)
10033{
10034 /* Check empty bases separately, they don't have fields. */
10035 if (is_empty_base_ref (t))
10036 return 2;
10037
10038 /* A delegating constructor might be used to initialize a base. */
10039 if (current_function_decl
10040 && DECL_CONSTRUCTOR_P (current_function_decl)
10041 && (t == current_class_ref
10042 || tree_strip_nop_conversions (t) == current_class_ptr))
10043 return 2;
10044
10045 STRIP_NOPS (t);
10046 if (TREE_CODE (t) == ADDR_EXPR)
10047 t = TREE_OPERAND (t, 0);
10048 if (TREE_CODE (t) == COMPONENT_REF)
10049 t = TREE_OPERAND (t, 1);
10050 if (TREE_CODE (t) != FIELD_DECL)
10051 return false;
10052 if (!CLASS_TYPE_P (TREE_TYPE (t)))
10053 /* The middle-end will do the right thing for scalar types. */
10054 return false;
10055 if (DECL_FIELD_IS_BASE (t))
10056 return 2;
10057 if (lookup_attribute (attr_name: "no_unique_address", DECL_ATTRIBUTES (t)))
10058 return 1;
10059 return 0;
10060}
10061
10062/* True IFF EXP is a prvalue that represents return by invisible reference. */
10063
10064static bool
10065init_by_return_slot_p (tree exp)
10066{
10067 /* Copy elision only happens with a TARGET_EXPR. */
10068 if (TREE_CODE (exp) != TARGET_EXPR)
10069 return false;
10070 tree init = TARGET_EXPR_INITIAL (exp);
10071 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
10072 while (TREE_CODE (init) == COMPOUND_EXPR)
10073 init = TREE_OPERAND (init, 1);
10074 if (TREE_CODE (init) == COND_EXPR)
10075 {
10076 /* We'll end up copying from each of the arms of the COND_EXPR directly
10077 into the target, so look at them. */
10078 if (tree op = TREE_OPERAND (init, 1))
10079 if (init_by_return_slot_p (exp: op))
10080 return true;
10081 return init_by_return_slot_p (TREE_OPERAND (init, 2));
10082 }
10083 return (TREE_CODE (init) == AGGR_INIT_EXPR
10084 && !AGGR_INIT_VIA_CTOR_P (init));
10085}
10086
10087/* We can't elide a copy from a function returning by value to a
10088 potentially-overlapping subobject, as the callee might clobber tail padding.
10089 Return true iff this could be that case.
10090
10091 Places that use this function (or _opt) to decide to elide a copy should
10092 probably use make_safe_copy_elision instead. */
10093
10094bool
10095unsafe_copy_elision_p (tree target, tree exp)
10096{
10097 return unsafe_return_slot_p (t: target) && init_by_return_slot_p (exp);
10098}
10099
10100/* As above, but for optimization allow more cases that are actually safe. */
10101
10102static bool
10103unsafe_copy_elision_p_opt (tree target, tree exp)
10104{
10105 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
10106 /* It's safe to elide the copy for a class with no tail padding. */
10107 if (!is_empty_class (type)
10108 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
10109 return false;
10110 return unsafe_copy_elision_p (target, exp);
10111}
10112
10113/* Try to make EXP suitable to be used as the initializer for TARGET,
10114 and return whether we were successful. */
10115
10116bool
10117make_safe_copy_elision (tree target, tree exp)
10118{
10119 int uns = unsafe_return_slot_p (t: target);
10120 if (!uns)
10121 return true;
10122 if (init_by_return_slot_p (exp))
10123 return false;
10124 if (uns == 1)
10125 return true;
10126 return make_base_init_ok (exp);
10127}
10128
10129/* True IFF the result of the conversion C is a prvalue. */
10130
10131static bool
10132conv_is_prvalue (conversion *c)
10133{
10134 if (c->kind == ck_rvalue)
10135 return true;
10136 if (c->kind == ck_base && c->need_temporary_p)
10137 return true;
10138 if (c->kind == ck_user && !TYPE_REF_P (c->type))
10139 return true;
10140 if (c->kind == ck_identity && c->u.expr
10141 && TREE_CODE (c->u.expr) == TARGET_EXPR)
10142 return true;
10143
10144 return false;
10145}
10146
10147/* True iff C is a conversion that binds a reference to a prvalue. */
10148
10149static bool
10150conv_binds_ref_to_prvalue (conversion *c)
10151{
10152 if (c->kind != ck_ref_bind)
10153 return false;
10154 if (c->need_temporary_p)
10155 return true;
10156
10157 return conv_is_prvalue (c: next_conversion (conv: c));
10158}
10159
10160/* True iff EXPR represents a (subobject of a) temporary. */
10161
10162static bool
10163expr_represents_temporary_p (tree expr)
10164{
10165 while (handled_component_p (t: expr))
10166 expr = TREE_OPERAND (expr, 0);
10167 return TREE_CODE (expr) == TARGET_EXPR;
10168}
10169
10170/* True iff C is a conversion that binds a reference to a temporary.
10171 This is a superset of conv_binds_ref_to_prvalue: here we're also
10172 interested in xvalues. */
10173
10174static bool
10175conv_binds_ref_to_temporary (conversion *c)
10176{
10177 if (conv_binds_ref_to_prvalue (c))
10178 return true;
10179 if (c->kind != ck_ref_bind)
10180 return false;
10181 c = next_conversion (conv: c);
10182 /* This is the case for
10183 struct Base {};
10184 struct Derived : Base {};
10185 const Base& b(Derived{});
10186 where we bind 'b' to the Base subobject of a temporary object of type
10187 Derived. The subobject is an xvalue; the whole object is a prvalue.
10188
10189 The ck_base doesn't have to be present for cases like X{}.m. */
10190 if (c->kind == ck_base)
10191 c = next_conversion (conv: c);
10192 if (c->kind == ck_identity && c->u.expr
10193 && expr_represents_temporary_p (expr: c->u.expr))
10194 return true;
10195 return false;
10196}
10197
10198/* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
10199 the reference to a temporary. Return tristate::TS_FALSE if converting
10200 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
10201 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
10202 says whether the conversion should be done in direct- or copy-initialization
10203 context. */
10204
10205tristate
10206ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
10207{
10208 gcc_assert (TYPE_REF_P (type));
10209
10210 conversion_obstack_sentinel cos;
10211
10212 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
10213 conversion *conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
10214 /*c_cast_p=*/false, flags, complain: tf_none);
10215 if (!conv || conv->bad_p)
10216 return tristate::unknown ();
10217
10218 if (conv_binds_ref_to_temporary (c: conv))
10219 {
10220 /* Actually perform the conversion to check access control. */
10221 if (convert_like (convs: conv, expr, complain: tf_none) != error_mark_node)
10222 return tristate (true);
10223 else
10224 return tristate::unknown ();
10225 }
10226
10227 return tristate (false);
10228}
10229
10230/* Call the trivial destructor for INSTANCE, which can be either an lvalue of
10231 class type or a pointer to class type. If NO_PTR_DEREF is true and
10232 INSTANCE has pointer type, clobber the pointer rather than what it points
10233 to. */
10234
10235tree
10236build_trivial_dtor_call (tree instance, bool no_ptr_deref)
10237{
10238 gcc_assert (!is_dummy_object (instance));
10239
10240 if (!flag_lifetime_dse)
10241 {
10242 no_clobber:
10243 return fold_convert (void_type_node, instance);
10244 }
10245
10246 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
10247 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
10248 {
10249 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
10250 goto no_clobber;
10251 instance = cp_build_fold_indirect_ref (instance);
10252 }
10253
10254 /* A trivial destructor should still clobber the object. */
10255 tree clobber = build_clobber (TREE_TYPE (instance), CLOBBER_OBJECT_END);
10256 return build2 (MODIFY_EXPR, void_type_node,
10257 instance, clobber);
10258}
10259
10260/* Return true if in an immediate function context, or an unevaluated operand,
10261 or a default argument/member initializer, or a subexpression of an immediate
10262 invocation. */
10263
10264bool
10265in_immediate_context ()
10266{
10267 return (cp_unevaluated_operand != 0
10268 || (current_function_decl != NULL_TREE
10269 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
10270 /* DR 2631: default args and DMI aren't immediately evaluated.
10271 Return true here so immediate_invocation_p returns false. */
10272 || current_binding_level->kind == sk_function_parms
10273 || current_binding_level->kind == sk_template_parms
10274 || parsing_nsdmi ()
10275 || in_consteval_if_p);
10276}
10277
10278/* Return true if a call to FN with number of arguments NARGS
10279 is an immediate invocation. */
10280
10281bool
10282immediate_invocation_p (tree fn)
10283{
10284 return (TREE_CODE (fn) == FUNCTION_DECL
10285 && DECL_IMMEDIATE_FUNCTION_P (fn)
10286 && !in_immediate_context ());
10287}
10288
10289/* Subroutine of the various build_*_call functions. Overload resolution
10290 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
10291 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
10292 bitmask of various LOOKUP_* flags which apply to the call itself. */
10293
10294static tree
10295build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
10296{
10297 tree fn = cand->fn;
10298 const vec<tree, va_gc> *args = cand->args;
10299 tree first_arg = cand->first_arg;
10300 conversion **convs = cand->convs;
10301 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
10302 int parmlen;
10303 tree val;
10304 int nargs;
10305 tree *argarray;
10306 bool already_used = false;
10307
10308 /* In a template, there is no need to perform all of the work that
10309 is normally done. We are only interested in the type of the call
10310 expression, i.e., the return type of the function. Any semantic
10311 errors will be deferred until the template is instantiated. */
10312 if (processing_template_decl)
10313 {
10314 if (undeduced_auto_decl (fn))
10315 mark_used (fn, complain);
10316 else
10317 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
10318 See PR80598. */
10319 TREE_USED (fn) = 1;
10320
10321 tree return_type = TREE_TYPE (TREE_TYPE (fn));
10322 tree callee;
10323 if (first_arg == NULL_TREE)
10324 {
10325 callee = build_addr_func (function: fn, complain);
10326 if (callee == error_mark_node)
10327 return error_mark_node;
10328 }
10329 else
10330 {
10331 callee = build_baselink (cand->conversion_path, cand->access_path,
10332 fn, NULL_TREE);
10333 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
10334 first_arg, callee, NULL_TREE);
10335 }
10336
10337 tree expr = build_call_vec (return_type, callee, args);
10338 SET_EXPR_LOCATION (expr, input_location);
10339 if (TREE_THIS_VOLATILE (fn) && cfun)
10340 current_function_returns_abnormally = 1;
10341 if (TREE_DEPRECATED (fn)
10342 && warning_suppressed_at (input_location,
10343 OPT_Wdeprecated_declarations))
10344 /* Make the expr consistent with the location. */
10345 TREE_NO_WARNING (expr) = true;
10346 if (immediate_invocation_p (fn))
10347 {
10348 tree obj_arg = NULL_TREE;
10349 if (DECL_CONSTRUCTOR_P (fn))
10350 obj_arg = first_arg;
10351 /* Look through *(const T *)&obj. */
10352 if (obj_arg && INDIRECT_REF_P (obj_arg))
10353 {
10354 tree addr = TREE_OPERAND (obj_arg, 0);
10355 STRIP_NOPS (addr);
10356 if (TREE_CODE (addr) == ADDR_EXPR)
10357 {
10358 tree typeo = TREE_TYPE (obj_arg);
10359 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
10360 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
10361 obj_arg = TREE_OPERAND (addr, 0);
10362 }
10363 }
10364 fold_non_dependent_expr (expr, complain,
10365 /*manifestly_const_eval=*/true,
10366 obj_arg);
10367 }
10368 return convert_from_reference (expr);
10369 }
10370
10371 /* Give any warnings we noticed during overload resolution. */
10372 if (cand->warnings && (complain & tf_warning))
10373 {
10374 struct candidate_warning *w;
10375 for (w = cand->warnings; w; w = w->next)
10376 joust (cand, w->loser, 1, complain);
10377 }
10378
10379 /* Core issue 2327: P0135 doesn't say how to handle the case where the
10380 argument to the copy constructor ends up being a prvalue after
10381 conversion. Let's do the normal processing, but pretend we aren't
10382 actually using the copy constructor. */
10383 bool force_elide = false;
10384 if (cxx_dialect >= cxx17
10385 && cand->num_convs == 1
10386 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
10387 && (DECL_COPY_CONSTRUCTOR_P (fn)
10388 || DECL_MOVE_CONSTRUCTOR_P (fn))
10389 && !unsafe_return_slot_p (t: first_arg)
10390 && conv_binds_ref_to_prvalue (c: convs[0]))
10391 {
10392 force_elide = true;
10393 goto not_really_used;
10394 }
10395
10396 /* OK, we're actually calling this inherited constructor; set its deletedness
10397 appropriately. We can get away with doing this here because calling is
10398 the only way to refer to a constructor. */
10399 if (DECL_INHERITED_CTOR (fn)
10400 && !deduce_inheriting_ctor (fn))
10401 {
10402 if (complain & tf_error)
10403 mark_used (fn);
10404 return error_mark_node;
10405 }
10406
10407 /* Make =delete work with SFINAE. */
10408 if (DECL_DELETED_FN (fn))
10409 {
10410 if (complain & tf_error)
10411 {
10412 mark_used (fn);
10413 if (cand->next)
10414 {
10415 if (flag_diagnostics_all_candidates)
10416 print_z_candidates (loc: input_location, candidates: cand, /*only_viable_p=*/false);
10417 else
10418 inform (input_location,
10419 "use %<-fdiagnostics-all-candidates%> to display "
10420 "considered candidates");
10421 }
10422 }
10423 return error_mark_node;
10424 }
10425
10426 if (DECL_FUNCTION_MEMBER_P (fn))
10427 {
10428 tree access_fn;
10429 /* If FN is a template function, two cases must be considered.
10430 For example:
10431
10432 struct A {
10433 protected:
10434 template <class T> void f();
10435 };
10436 template <class T> struct B {
10437 protected:
10438 void g();
10439 };
10440 struct C : A, B<int> {
10441 using A::f; // #1
10442 using B<int>::g; // #2
10443 };
10444
10445 In case #1 where `A::f' is a member template, DECL_ACCESS is
10446 recorded in the primary template but not in its specialization.
10447 We check access of FN using its primary template.
10448
10449 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
10450 because it is a member of class template B, DECL_ACCESS is
10451 recorded in the specialization `B<int>::g'. We cannot use its
10452 primary template because `B<T>::g' and `B<int>::g' may have
10453 different access. */
10454 if (DECL_TEMPLATE_INFO (fn)
10455 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
10456 access_fn = DECL_TI_TEMPLATE (fn);
10457 else
10458 access_fn = fn;
10459 if (!perform_or_defer_access_check (cand->access_path, access_fn,
10460 fn, complain))
10461 return error_mark_node;
10462 }
10463
10464 /* If we're checking for implicit delete, don't bother with argument
10465 conversions. */
10466 if (flags & LOOKUP_SPECULATIVE)
10467 {
10468 if (cand->viable == 1)
10469 return fn;
10470 else if (!(complain & tf_error))
10471 /* Reject bad conversions now. */
10472 return error_mark_node;
10473 /* else continue to get conversion error. */
10474 }
10475
10476 not_really_used:
10477
10478 /* N3276 magic doesn't apply to nested calls. */
10479 tsubst_flags_t decltype_flag = (complain & tf_decltype);
10480 complain &= ~tf_decltype;
10481 /* No-Cleanup doesn't apply to nested calls either. */
10482 tsubst_flags_t no_cleanup_complain = complain;
10483 complain &= ~tf_no_cleanup;
10484
10485 /* Find maximum size of vector to hold converted arguments. */
10486 parmlen = list_length (parm);
10487 nargs = vec_safe_length (v: args) + (first_arg != NULL_TREE ? 1 : 0);
10488 if (parmlen > nargs)
10489 nargs = parmlen;
10490 argarray = XALLOCAVEC (tree, nargs);
10491
10492 in_consteval_if_p_temp_override icip;
10493 /* If the call is immediate function invocation, make sure
10494 taking address of immediate functions is allowed in its arguments. */
10495 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
10496 in_consteval_if_p = true;
10497
10498 int argarray_size = 0;
10499 unsigned int arg_index = 0;
10500 int conv_index = 0;
10501 int param_index = 0;
10502 tree parmd = DECL_ARGUMENTS (fn);
10503
10504 auto consume_object_arg = [&arg_index, &first_arg, args]()
10505 {
10506 if (!first_arg)
10507 return (*args)[arg_index++];
10508 tree object_arg = first_arg;
10509 first_arg = NULL_TREE;
10510 return object_arg;
10511 };
10512
10513 /* The implicit parameters to a constructor are not considered by overload
10514 resolution, and must be of the proper type. */
10515 if (DECL_CONSTRUCTOR_P (fn))
10516 {
10517 tree object_arg = consume_object_arg ();
10518 argarray[argarray_size++] = build_this (obj: object_arg);
10519 parm = TREE_CHAIN (parm);
10520 if (parmd)
10521 parmd = DECL_CHAIN (parmd);
10522 /* We should never try to call the abstract constructor. */
10523 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
10524
10525 if (DECL_HAS_VTT_PARM_P (fn))
10526 {
10527 argarray[argarray_size++] = (*args)[arg_index];
10528 ++arg_index;
10529 parm = TREE_CHAIN (parm);
10530 if (parmd)
10531 parmd = DECL_CHAIN (parmd);
10532 }
10533 }
10534 /* Bypass access control for 'this' parameter. */
10535 else if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
10536 {
10537 tree arg = build_this (obj: consume_object_arg ());
10538 tree argtype = TREE_TYPE (arg);
10539
10540 if (arg == error_mark_node)
10541 return error_mark_node;
10542 if (convs[conv_index++]->bad_p)
10543 {
10544 if (complain & tf_error)
10545 {
10546 auto_diagnostic_group d;
10547 if (permerror (input_location, "passing %qT as %<this%> "
10548 "argument discards qualifiers",
10549 TREE_TYPE (argtype)))
10550 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
10551 }
10552 else
10553 return error_mark_node;
10554 }
10555
10556 /* The class where FN is defined. */
10557 tree ctx = DECL_CONTEXT (fn);
10558
10559 /* See if the function member or the whole class type is declared
10560 final and the call can be devirtualized. */
10561 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
10562 flags |= LOOKUP_NONVIRTUAL;
10563
10564 /* [class.mfct.non-static]: If a non-static member function of a class
10565 X is called for an object that is not of type X, or of a type
10566 derived from X, the behavior is undefined.
10567
10568 So we can assume that anything passed as 'this' is non-null, and
10569 optimize accordingly. */
10570 /* Check that the base class is accessible. */
10571 if (!accessible_base_p (TREE_TYPE (argtype),
10572 BINFO_TYPE (cand->conversion_path), true))
10573 {
10574 if (complain & tf_error)
10575 error ("%qT is not an accessible base of %qT",
10576 BINFO_TYPE (cand->conversion_path),
10577 TREE_TYPE (argtype));
10578 else
10579 return error_mark_node;
10580 }
10581 /* If fn was found by a using declaration, the conversion path
10582 will be to the derived class, not the base declaring fn. We
10583 must convert to the base. */
10584 tree base_binfo = cand->conversion_path;
10585 if (BINFO_TYPE (base_binfo) != ctx)
10586 {
10587 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10588 if (base_binfo == error_mark_node)
10589 return error_mark_node;
10590 }
10591
10592 /* If we know the dynamic type of the object, look up the final overrider
10593 in the BINFO. */
10594 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10595 && resolves_to_fixed_type_p (arg))
10596 {
10597 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10598
10599 /* And unwind base_binfo to match. If we don't find the type we're
10600 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10601 inheritance; for now do a normal virtual call in that case. */
10602 tree octx = DECL_CONTEXT (ov);
10603 tree obinfo = base_binfo;
10604 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10605 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10606 if (obinfo)
10607 {
10608 fn = ov;
10609 base_binfo = obinfo;
10610 flags |= LOOKUP_NONVIRTUAL;
10611 }
10612 }
10613
10614 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10615 base_binfo, 1, complain);
10616
10617 argarray[argarray_size++] = converted_arg;
10618 parm = TREE_CHAIN (parm);
10619 if (parmd)
10620 parmd = DECL_CHAIN (parmd);
10621 }
10622
10623 auto handle_arg = [fn, flags](tree type,
10624 tree arg,
10625 int const param_index,
10626 conversion *conv,
10627 tsubst_flags_t const arg_complain)
10628 {
10629 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10630 knows not to allow any more UDCs. This needs to happen after we
10631 process cand->warnings. */
10632 if (flags & LOOKUP_NO_CONVERSION)
10633 conv->user_conv_p = true;
10634
10635 if (arg_complain & tf_warning)
10636 maybe_warn_pessimizing_move (arg, type, /*return_p=*/false);
10637
10638 tree val = convert_like_with_context (convs: conv, expr: arg, fn,
10639 argnum: param_index, complain: arg_complain);
10640 val = convert_for_arg_passing (type, val, complain: arg_complain);
10641 return val;
10642 };
10643
10644 auto handle_indeterminate_arg = [](tree parmd, tree val)
10645 {
10646 if (parmd
10647 && lookup_attribute (NULL, attr_name: "indeterminate", DECL_ATTRIBUTES (parmd)))
10648 {
10649 STRIP_NOPS (val);
10650 if (TREE_CODE (val) == ADDR_EXPR
10651 && TREE_CODE (TREE_OPERAND (val, 0)) == TARGET_EXPR)
10652 {
10653 val = TARGET_EXPR_SLOT (TREE_OPERAND (val, 0));
10654 if (auto_var_p (val) && DECL_ARTIFICIAL (val))
10655 {
10656 tree id = get_identifier ("indeterminate");
10657 DECL_ATTRIBUTES (val)
10658 = tree_cons (build_tree_list (NULL_TREE, id), NULL_TREE,
10659 DECL_ATTRIBUTES (val));
10660 }
10661 }
10662 }
10663 };
10664
10665 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
10666 {
10667 gcc_assert (cand->num_convs > 0);
10668 tree object_arg = consume_object_arg ();
10669 val = handle_arg (TREE_VALUE (parm),
10670 object_arg,
10671 param_index++,
10672 convs[conv_index++],
10673 complain);
10674
10675 if (val == error_mark_node)
10676 return error_mark_node;
10677 else
10678 {
10679 argarray[argarray_size++] = val;
10680 handle_indeterminate_arg (parmd, val);
10681 }
10682 parm = TREE_CHAIN (parm);
10683 if (parmd)
10684 parmd = DECL_CHAIN (parmd);
10685 }
10686
10687 gcc_assert (first_arg == NULL_TREE);
10688 for (; arg_index < vec_safe_length (v: args) && parm;
10689 parm = TREE_CHAIN (parm), ++arg_index, ++param_index, ++conv_index)
10690 {
10691 tree current_arg = (*args)[arg_index];
10692
10693 /* If the argument is NULL and used to (implicitly) instantiate a
10694 template function (and bind one of the template arguments to
10695 the type of 'long int'), we don't want to warn about passing NULL
10696 to non-pointer argument.
10697 For example, if we have this template function:
10698
10699 template<typename T> void func(T x) {}
10700
10701 we want to warn (when -Wconversion is enabled) in this case:
10702
10703 void foo() {
10704 func<int>(NULL);
10705 }
10706
10707 but not in this case:
10708
10709 void foo() {
10710 func(NULL);
10711 }
10712 */
10713 bool const conversion_warning = !(null_node_p (expr: current_arg)
10714 && DECL_TEMPLATE_INFO (fn)
10715 && cand->template_decl
10716 && !cand->explicit_targs);
10717
10718 tsubst_flags_t const arg_complain
10719 = conversion_warning ? complain : complain & ~tf_warning;
10720
10721 val = handle_arg (TREE_VALUE (parm),
10722 current_arg,
10723 param_index,
10724 convs[conv_index],
10725 arg_complain);
10726
10727 if (val == error_mark_node)
10728 return error_mark_node;
10729 else
10730 {
10731 argarray[argarray_size++] = val;
10732 handle_indeterminate_arg (parmd, val);
10733 }
10734 if (parmd)
10735 parmd = DECL_CHAIN (parmd);
10736 }
10737
10738 /* Default arguments */
10739 for (; parm && parm != void_list_node;
10740 parm = TREE_CHAIN (parm), param_index++)
10741 {
10742 if (TREE_VALUE (parm) == error_mark_node)
10743 return error_mark_node;
10744 val = convert_default_arg (TREE_VALUE (parm),
10745 TREE_PURPOSE (parm),
10746 fn, parmnum: param_index,
10747 complain);
10748 if (val == error_mark_node)
10749 return error_mark_node;
10750 argarray[argarray_size++] = val;
10751 handle_indeterminate_arg (parmd, val);
10752 if (parmd)
10753 parmd = DECL_CHAIN (parmd);
10754 }
10755
10756 /* Ellipsis */
10757 int magic = magic_varargs_p (fn);
10758 for (; arg_index < vec_safe_length (v: args); ++arg_index)
10759 {
10760 tree a = (*args)[arg_index];
10761 if ((magic == 3 && arg_index == 2) || (magic == 4 && arg_index == 0))
10762 {
10763 /* Do no conversions for certain magic varargs. */
10764 a = mark_type_use (a);
10765 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10766 return error_mark_node;
10767 }
10768 else if (magic != 0)
10769 {
10770 /* Don't truncate excess precision to the semantic type. */
10771 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10772 a = TREE_OPERAND (a, 0);
10773 /* For other magic varargs only do decay_conversion. */
10774 a = decay_conversion (a, complain);
10775 }
10776 else if (DECL_CONSTRUCTOR_P (fn)
10777 && vec_safe_length (v: args) == 1
10778 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10779 TREE_TYPE (a)))
10780 {
10781 /* Avoid infinite recursion trying to call A(...). */
10782 if (complain & tf_error)
10783 /* Try to call the actual copy constructor for a good error. */
10784 call_copy_ctor (a, complain);
10785 return error_mark_node;
10786 }
10787 else
10788 a = convert_arg_to_ellipsis (arg: a, complain);
10789 if (a == error_mark_node)
10790 return error_mark_node;
10791 argarray[argarray_size++] = a;
10792 }
10793
10794 gcc_assert (argarray_size <= nargs);
10795 nargs = argarray_size;
10796 icip.reset ();
10797
10798 /* Avoid performing argument transformation if warnings are disabled.
10799 When tf_warning is set and at least one of the warnings is active
10800 the check_function_arguments function might warn about something. */
10801
10802 bool warned_p = false;
10803 if ((complain & tf_warning)
10804 && (warn_nonnull
10805 || warn_format
10806 || warn_suggest_attribute_format
10807 || warn_restrict))
10808 {
10809 tree *fargs = (!nargs ? argarray
10810 : (tree *) alloca (nargs * sizeof (tree)));
10811 for (int j = 0; j < nargs; j++)
10812 {
10813 /* For -Wformat undo the implicit passing by hidden reference
10814 done by convert_arg_to_ellipsis. */
10815 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10816 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10817 fargs[j] = TREE_OPERAND (argarray[j], 0);
10818 else
10819 fargs[j] = argarray[j];
10820 }
10821
10822 warned_p = check_function_arguments (loc: input_location, fn, TREE_TYPE (fn),
10823 nargs, fargs, NULL,
10824 comp_types: cp_comp_parm_types);
10825 }
10826
10827 if (DECL_INHERITED_CTOR (fn))
10828 {
10829 /* Check for passing ellipsis arguments to an inherited constructor. We
10830 could handle this by open-coding the inherited constructor rather than
10831 defining it, but let's not bother now. */
10832 if (!cp_unevaluated_operand
10833 && cand->num_convs
10834 && cand->convs[cand->num_convs-1]->ellipsis_p)
10835 {
10836 if (complain & tf_error)
10837 {
10838 sorry ("passing arguments to ellipsis of inherited constructor "
10839 "%qD", cand->fn);
10840 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10841 }
10842 return error_mark_node;
10843 }
10844
10845 /* A base constructor inheriting from a virtual base doesn't get the
10846 inherited arguments, just this and __vtt. */
10847 if (ctor_omit_inherited_parms (fn))
10848 nargs = 2;
10849 }
10850
10851 /* Avoid actually calling copy constructors and copy assignment operators,
10852 if possible. */
10853
10854 if (!force_elide
10855 && (!flag_elide_constructors
10856 /* It's unsafe to elide the operation when handling
10857 a noexcept-expression, it may evaluate to the wrong
10858 value (c++/53025, c++/96090). */
10859 || cp_noexcept_operand != 0))
10860 /* Do things the hard way. */;
10861 else if (cand->num_convs == 1
10862 && (DECL_COPY_CONSTRUCTOR_P (fn)
10863 || DECL_MOVE_CONSTRUCTOR_P (fn)))
10864 {
10865 tree targ;
10866 tree arg = argarray[num_artificial_parms_for (fn)];
10867 tree fa = argarray[0];
10868 bool trivial = trivial_fn_p (fn);
10869
10870 /* Pull out the real argument, disregarding const-correctness. */
10871 targ = arg;
10872 /* Strip the reference binding for the constructor parameter. */
10873 if (CONVERT_EXPR_P (targ)
10874 && TYPE_REF_P (TREE_TYPE (targ)))
10875 targ = TREE_OPERAND (targ, 0);
10876 /* But don't strip any other reference bindings; binding a temporary to a
10877 reference prevents copy elision. */
10878 while ((CONVERT_EXPR_P (targ)
10879 && !TYPE_REF_P (TREE_TYPE (targ)))
10880 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10881 targ = TREE_OPERAND (targ, 0);
10882 if (TREE_CODE (targ) == ADDR_EXPR)
10883 {
10884 targ = TREE_OPERAND (targ, 0);
10885 if (!same_type_ignoring_top_level_qualifiers_p
10886 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10887 targ = NULL_TREE;
10888 }
10889 else
10890 targ = NULL_TREE;
10891
10892 if (targ)
10893 arg = targ;
10894 else
10895 arg = cp_build_fold_indirect_ref (arg);
10896
10897 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10898 potentially-overlapping subobject. */
10899 if (CHECKING_P && cxx_dialect >= cxx17)
10900 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10901 || force_elide
10902 /* It's from binding the ref parm to a packed field. */
10903 || convs[0]->need_temporary_p
10904 || seen_error ()
10905 /* See unsafe_copy_elision_p. */
10906 || unsafe_return_slot_p (fa));
10907
10908 bool unsafe = unsafe_copy_elision_p_opt (target: fa, exp: arg);
10909 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10910
10911 /* [class.copy]: the copy constructor is implicitly defined even if the
10912 implementation elided its use. But don't warn about deprecation when
10913 eliding a temporary, as then no copy is actually performed. */
10914 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10915 if (force_elide)
10916 /* The language says this isn't called. */;
10917 else if (!trivial)
10918 {
10919 if (!mark_used (fn, complain) && !(complain & tf_error))
10920 return error_mark_node;
10921 already_used = true;
10922 }
10923 else
10924 cp_handle_deprecated_or_unavailable (fn, complain);
10925
10926 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10927 && !make_base_init_ok (exp: arg))
10928 unsafe = true;
10929
10930 /* If we're creating a temp and we already have one, don't create a
10931 new one. If we're not creating a temp but we get one, use
10932 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10933 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10934 temp or an INIT_EXPR otherwise. */
10935 if (is_dummy_object (fa))
10936 {
10937 if (TREE_CODE (arg) == TARGET_EXPR)
10938 return arg;
10939 else if (trivial)
10940 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10941 }
10942 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10943 && !unsafe)
10944 {
10945 tree to = cp_build_fold_indirect_ref (fa);
10946 val = cp_build_init_expr (t: to, i: arg);
10947 return val;
10948 }
10949 }
10950 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10951 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10952 && trivial_fn_p (fn))
10953 {
10954 tree to = cp_build_fold_indirect_ref (argarray[0]);
10955 tree type = TREE_TYPE (to);
10956 tree as_base = CLASSTYPE_AS_BASE (type);
10957 tree arg = argarray[1];
10958 location_t loc = cp_expr_loc_or_input_loc (t: arg);
10959
10960 if (is_really_empty_class (type, /*ignore_vptr*/true))
10961 {
10962 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10963 if the object argument isn't one. */
10964 to = force_lvalue (to, complain);
10965 val = build2 (COMPOUND_EXPR, type, arg, to);
10966 suppress_warning (val, OPT_Wunused);
10967 }
10968 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10969 {
10970 if (is_std_init_list (type)
10971 && conv_binds_ref_to_prvalue (c: convs[1]))
10972 warning_at (loc, OPT_Winit_list_lifetime,
10973 "assignment from temporary %<initializer_list%> does "
10974 "not extend the lifetime of the underlying array");
10975 arg = cp_build_fold_indirect_ref (arg);
10976 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10977 }
10978 else
10979 {
10980 /* We must only copy the non-tail padding parts. */
10981 tree arg0, arg2, t;
10982 tree array_type, alias_set;
10983
10984 arg2 = TYPE_SIZE_UNIT (as_base);
10985 /* Ensure op= returns an lvalue even if the object argument isn't
10986 one. */
10987 to = force_lvalue (to, complain);
10988 to = cp_stabilize_reference (to);
10989 arg0 = cp_build_addr_expr (to, complain);
10990
10991 array_type = build_array_type (unsigned_char_type_node,
10992 build_index_type
10993 (size_binop (MINUS_EXPR,
10994 arg2, size_int (1))));
10995 alias_set = build_int_cst (build_pointer_type (type), 0);
10996 t = build2 (MODIFY_EXPR, void_type_node,
10997 build2 (MEM_REF, array_type, arg0, alias_set),
10998 build2 (MEM_REF, array_type, arg, alias_set));
10999 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
11000 suppress_warning (val, OPT_Wunused);
11001 }
11002
11003 cp_handle_deprecated_or_unavailable (fn, complain);
11004
11005 return val;
11006 }
11007 else if (trivial_fn_p (fn))
11008 {
11009 if (DECL_DESTRUCTOR_P (fn))
11010 return build_trivial_dtor_call (instance: argarray[0]);
11011 else if (default_ctor_p (fn))
11012 {
11013 if (is_dummy_object (argarray[0]))
11014 return force_target_expr (DECL_CONTEXT (fn), void_node,
11015 no_cleanup_complain);
11016 else
11017 return cp_build_fold_indirect_ref (argarray[0]);
11018 }
11019 }
11020
11021 gcc_assert (!force_elide);
11022
11023 if (!already_used
11024 && !mark_used (fn, complain))
11025 return error_mark_node;
11026
11027 /* Warn if the built-in writes to an object of a non-trivial type. */
11028 if (warn_class_memaccess
11029 && vec_safe_length (v: args) >= 2
11030 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
11031 maybe_warn_class_memaccess (input_location, fn, args);
11032
11033 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
11034 {
11035 tree t;
11036 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
11037 DECL_CONTEXT (fn),
11038 ba_any, NULL, complain);
11039 gcc_assert (binfo && binfo != error_mark_node);
11040
11041 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
11042 complain);
11043 if (TREE_SIDE_EFFECTS (argarray[0]))
11044 argarray[0] = save_expr (argarray[0]);
11045 t = build_pointer_type (TREE_TYPE (fn));
11046 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
11047 TREE_TYPE (fn) = t;
11048 }
11049 else
11050 {
11051 /* If FN is marked deprecated or unavailable, then we've already
11052 issued a diagnostic from mark_used above, so avoid redundantly
11053 issuing another one from build_addr_func. */
11054 auto w = make_temp_override (var&: deprecated_state,
11055 overrider: UNAVAILABLE_DEPRECATED_SUPPRESS);
11056
11057 fn = build_addr_func (function: fn, complain);
11058 if (fn == error_mark_node)
11059 return error_mark_node;
11060
11061 /* We're actually invoking the function. (Immediate functions get an
11062 & when invoking it even though the user didn't use &.) */
11063 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
11064 }
11065
11066 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
11067 if (call == error_mark_node)
11068 return call;
11069 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
11070 {
11071 tree c = extract_call_expr (call);
11072 /* build_new_op will clear this when appropriate. */
11073 CALL_EXPR_ORDERED_ARGS (c) = true;
11074 }
11075 if (warned_p)
11076 {
11077 tree c = extract_call_expr (call);
11078 if (TREE_CODE (c) == CALL_EXPR)
11079 suppress_warning (c /* Suppress all warnings. */);
11080 }
11081 else if (TREE_DEPRECATED (fn)
11082 && warning_suppressed_at (input_location,
11083 OPT_Wdeprecated_declarations))
11084 {
11085 tree c = extract_call_expr (call);
11086 if (TREE_CODE (c) == CALL_EXPR)
11087 TREE_NO_WARNING (c) = true;
11088 }
11089
11090 return call;
11091}
11092
11093namespace
11094{
11095
11096/* Return the DECL of the first non-static subobject of class TYPE
11097 that satisfies the predicate PRED or null if none can be found. */
11098
11099template <class Predicate>
11100tree
11101first_non_static_field (tree type, Predicate pred)
11102{
11103 if (!type || !CLASS_TYPE_P (type))
11104 return NULL_TREE;
11105
11106 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
11107 {
11108 if (TREE_CODE (field) != FIELD_DECL)
11109 continue;
11110 if (TREE_STATIC (field))
11111 continue;
11112 if (pred (field))
11113 return field;
11114 }
11115
11116 int i = 0;
11117
11118 for (tree base_binfo, binfo = TYPE_BINFO (type);
11119 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
11120 {
11121 tree base = TREE_TYPE (base_binfo);
11122 if (pred (base))
11123 return base;
11124 if (tree field = first_non_static_field (base, pred))
11125 return field;
11126 }
11127
11128 return NULL_TREE;
11129}
11130
11131struct NonPublicField
11132{
11133 bool operator() (const_tree t) const
11134 {
11135 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
11136 }
11137};
11138
11139/* Return the DECL of the first non-public subobject of class TYPE
11140 or null if none can be found. */
11141
11142static inline tree
11143first_non_public_field (tree type)
11144{
11145 return first_non_static_field (type, pred: NonPublicField ());
11146}
11147
11148struct NonTrivialField
11149{
11150 bool operator() (const_tree t) const
11151 {
11152 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
11153 }
11154};
11155
11156/* Return the DECL of the first non-trivial subobject of class TYPE
11157 or null if none can be found. */
11158
11159static inline tree
11160first_non_trivial_field (tree type)
11161{
11162 return first_non_static_field (type, pred: NonTrivialField ());
11163}
11164
11165} /* unnamed namespace */
11166
11167/* Return true if all copy and move assignment operator overloads for
11168 class TYPE are trivial and at least one of them is not deleted and,
11169 when ACCESS is set, accessible. Return false otherwise. Set
11170 HASASSIGN to true when the TYPE has a (not necessarily trivial)
11171 copy or move assignment. */
11172
11173static bool
11174has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
11175{
11176 tree fns = get_class_binding (type, assign_op_identifier);
11177 bool all_trivial = true;
11178
11179 /* Iterate over overloads of the assignment operator, checking
11180 accessible copy assignments for triviality. */
11181
11182 for (tree f : ovl_range (fns))
11183 {
11184 /* Skip operators that aren't copy assignments. */
11185 if (!copy_fn_p (f))
11186 continue;
11187
11188 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
11189 || accessible_p (TYPE_BINFO (type), f, true));
11190
11191 /* Skip template assignment operators and deleted functions. */
11192 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
11193 continue;
11194
11195 if (accessible)
11196 *hasassign = true;
11197
11198 if (!accessible || !trivial_fn_p (f))
11199 all_trivial = false;
11200
11201 /* Break early when both properties have been determined. */
11202 if (*hasassign && !all_trivial)
11203 break;
11204 }
11205
11206 /* Return true if they're all trivial and one of the expressions
11207 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
11208 tree ref = cp_build_reference_type (type, false);
11209 return (all_trivial
11210 && (is_trivially_xible (MODIFY_EXPR, type, type)
11211 || is_trivially_xible (MODIFY_EXPR, type, ref)));
11212}
11213
11214/* Return true if all copy and move ctor overloads for class TYPE are
11215 trivial and at least one of them is not deleted and, when ACCESS is
11216 set, accessible. Return false otherwise. Set each element of HASCTOR[]
11217 to true when the TYPE has a (not necessarily trivial) default and copy
11218 (or move) ctor, respectively. */
11219
11220static bool
11221has_trivial_copy_p (tree type, bool access, bool hasctor[2])
11222{
11223 tree fns = get_class_binding (type, complete_ctor_identifier);
11224 bool all_trivial = true;
11225
11226 for (tree f : ovl_range (fns))
11227 {
11228 /* Skip template constructors. */
11229 if (TREE_CODE (f) != FUNCTION_DECL)
11230 continue;
11231
11232 bool cpy_or_move_ctor_p = copy_fn_p (f);
11233
11234 /* Skip ctors other than default, copy, and move. */
11235 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
11236 continue;
11237
11238 if (DECL_DELETED_FN (f))
11239 continue;
11240
11241 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
11242 || accessible_p (TYPE_BINFO (type), f, true));
11243
11244 if (accessible)
11245 hasctor[cpy_or_move_ctor_p] = true;
11246
11247 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
11248 all_trivial = false;
11249
11250 /* Break early when both properties have been determined. */
11251 if (hasctor[0] && hasctor[1] && !all_trivial)
11252 break;
11253 }
11254
11255 return all_trivial;
11256}
11257
11258/* Issue a warning on a call to the built-in function FNDECL if it is
11259 a raw memory write whose destination is not an object of (something
11260 like) trivial or standard layout type with a non-deleted assignment
11261 and copy ctor. Detects const correctness violations, corrupting
11262 references, virtual table pointers, and bypassing non-trivial
11263 assignments. */
11264
11265static void
11266maybe_warn_class_memaccess (location_t loc, tree fndecl,
11267 const vec<tree, va_gc> *args)
11268{
11269 /* Except for bcopy where it's second, the destination pointer is
11270 the first argument for all functions handled here. Compute
11271 the index of the destination and source arguments. */
11272 unsigned dstidx = DECL_FUNCTION_CODE (decl: fndecl) == BUILT_IN_BCOPY;
11273 unsigned srcidx = !dstidx;
11274
11275 tree dest = (*args)[dstidx];
11276 if (!TREE_TYPE (dest)
11277 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
11278 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
11279 return;
11280
11281 tree srctype = NULL_TREE;
11282
11283 /* Determine the type of the pointed-to object and whether it's
11284 a complete class type. */
11285 tree desttype = TREE_TYPE (TREE_TYPE (dest));
11286
11287 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
11288 return;
11289
11290 /* Check to see if the raw memory call is made by a non-static member
11291 function with THIS as the destination argument for the destination
11292 type. If so, and if the class has no non-trivial bases or members,
11293 be more permissive. */
11294 if (current_function_decl
11295 && DECL_OBJECT_MEMBER_FUNCTION_P (current_function_decl)
11296 && is_object_parameter (tree_strip_nop_conversions (dest)))
11297 {
11298 tree ctx = DECL_CONTEXT (current_function_decl);
11299 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
11300 tree binfo = TYPE_BINFO (ctx);
11301
11302 if (special
11303 && !BINFO_VTABLE (binfo)
11304 && !first_non_trivial_field (type: desttype))
11305 return;
11306 }
11307
11308 /* True if the class is trivial. */
11309 bool trivial = trivial_type_p (desttype);
11310
11311 /* Set to true if DESTYPE has an accessible copy assignment. */
11312 bool hasassign = false;
11313 /* True if all of the class' overloaded copy assignment operators
11314 are all trivial (and not deleted) and at least one of them is
11315 accessible. */
11316 bool trivassign = has_trivial_copy_assign_p (type: desttype, access: true, hasassign: &hasassign);
11317
11318 /* Set to true if DESTTYPE has an accessible default and copy ctor,
11319 respectively. */
11320 bool hasctors[2] = { false, false };
11321
11322 /* True if all of the class' overloaded copy constructors are all
11323 trivial (and not deleted) and at least one of them is accessible. */
11324 bool trivcopy = has_trivial_copy_p (type: desttype, access: true, hasctor: hasctors);
11325
11326 /* Set FLD to the first private/protected member of the class. */
11327 tree fld = trivial ? first_non_public_field (type: desttype) : NULL_TREE;
11328
11329 /* The warning format string. */
11330 const char *warnfmt = NULL;
11331 /* A suggested alternative to offer instead of the raw memory call.
11332 Empty string when none can be come up with. */
11333 const char *suggest = "";
11334 bool warned = false;
11335
11336 switch (DECL_FUNCTION_CODE (decl: fndecl))
11337 {
11338 case BUILT_IN_MEMSET:
11339 if (!integer_zerop (maybe_constant_value ((*args)[1])))
11340 {
11341 /* Diagnose setting non-copy-assignable or non-trivial types,
11342 or types with a private member, to (potentially) non-zero
11343 bytes. Since the value of the bytes being written is unknown,
11344 suggest using assignment instead (if one exists). Also warn
11345 for writes into objects for which zero-initialization doesn't
11346 mean all bits clear (pointer-to-member data, where null is all
11347 bits set). Since the value being written is (most likely)
11348 non-zero, simply suggest assignment (but not copy assignment). */
11349 suggest = "; use assignment instead";
11350 if (!trivassign)
11351 warnfmt = G_("%qD writing to an object of type %#qT with "
11352 "no trivial copy-assignment");
11353 else if (!trivial)
11354 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
11355 else if (fld)
11356 {
11357 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
11358 warned = warning_at (loc, OPT_Wclass_memaccess,
11359 "%qD writing to an object of type %#qT with "
11360 "%qs member %qD",
11361 fndecl, desttype, access, fld);
11362 }
11363 else if (!zero_init_p (desttype))
11364 warnfmt = G_("%qD writing to an object of type %#qT containing "
11365 "a pointer to data member%s");
11366
11367 break;
11368 }
11369 /* Fall through. */
11370
11371 case BUILT_IN_BZERO:
11372 /* Similarly to the above, diagnose clearing non-trivial or non-
11373 standard layout objects, or objects of types with no assignmenmt.
11374 Since the value being written is known to be zero, suggest either
11375 copy assignment, copy ctor, or default ctor as an alternative,
11376 depending on what's available. */
11377
11378 if (hasassign && hasctors[0])
11379 suggest = G_("; use assignment or value-initialization instead");
11380 else if (hasassign)
11381 suggest = G_("; use assignment instead");
11382 else if (hasctors[0])
11383 suggest = G_("; use value-initialization instead");
11384
11385 if (!trivassign)
11386 warnfmt = G_("%qD clearing an object of type %#qT with "
11387 "no trivial copy-assignment%s");
11388 else if (!trivial)
11389 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
11390 else if (!zero_init_p (desttype))
11391 warnfmt = G_("%qD clearing an object of type %#qT containing "
11392 "a pointer-to-member%s");
11393 break;
11394
11395 case BUILT_IN_BCOPY:
11396 case BUILT_IN_MEMCPY:
11397 case BUILT_IN_MEMMOVE:
11398 case BUILT_IN_MEMPCPY:
11399 /* Determine the type of the source object. */
11400 srctype = TREE_TYPE ((*args)[srcidx]);
11401 if (!srctype || !INDIRECT_TYPE_P (srctype))
11402 srctype = void_type_node;
11403 else
11404 srctype = TREE_TYPE (srctype);
11405
11406 /* Since it's impossible to determine wheter the byte copy is
11407 being used in place of assignment to an existing object or
11408 as a substitute for initialization, assume it's the former.
11409 Determine the best alternative to use instead depending on
11410 what's not deleted. */
11411 if (hasassign && hasctors[1])
11412 suggest = G_("; use copy-assignment or copy-initialization instead");
11413 else if (hasassign)
11414 suggest = G_("; use copy-assignment instead");
11415 else if (hasctors[1])
11416 suggest = G_("; use copy-initialization instead");
11417
11418 if (!trivassign)
11419 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
11420 "copy-assignment%s");
11421 else if (!trivially_copyable_p (desttype))
11422 warnfmt = G_("%qD writing to an object of non-trivially copyable "
11423 "type %#qT%s");
11424 else if (!trivcopy)
11425 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
11426
11427 else if (!trivial
11428 && !VOID_TYPE_P (srctype)
11429 && !is_byte_access_type (srctype)
11430 && !same_type_ignoring_top_level_qualifiers_p (desttype,
11431 srctype))
11432 {
11433 /* Warn when copying into a non-trivial object from an object
11434 of a different type other than void or char. */
11435 warned = warning_at (loc, OPT_Wclass_memaccess,
11436 "%qD copying an object of non-trivial type "
11437 "%#qT from an array of %#qT",
11438 fndecl, desttype, srctype);
11439 }
11440 else if (fld
11441 && !VOID_TYPE_P (srctype)
11442 && !is_byte_access_type (srctype)
11443 && !same_type_ignoring_top_level_qualifiers_p (desttype,
11444 srctype))
11445 {
11446 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
11447 warned = warning_at (loc, OPT_Wclass_memaccess,
11448 "%qD copying an object of type %#qT with "
11449 "%qs member %qD from an array of %#qT; use "
11450 "assignment or copy-initialization instead",
11451 fndecl, desttype, access, fld, srctype);
11452 }
11453 else if (!trivial && vec_safe_length (v: args) > 2)
11454 {
11455 tree sz = maybe_constant_value ((*args)[2]);
11456 if (!tree_fits_uhwi_p (sz))
11457 break;
11458
11459 /* Finally, warn on partial copies. */
11460 unsigned HOST_WIDE_INT typesize
11461 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
11462 if (typesize == 0)
11463 break;
11464 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
11465 warned = warning_at (loc, OPT_Wclass_memaccess,
11466 (typesize - partial > 1
11467 ? G_("%qD writing to an object of "
11468 "a non-trivial type %#qT leaves %wu "
11469 "bytes unchanged")
11470 : G_("%qD writing to an object of "
11471 "a non-trivial type %#qT leaves %wu "
11472 "byte unchanged")),
11473 fndecl, desttype, typesize - partial);
11474 }
11475 break;
11476
11477 case BUILT_IN_REALLOC:
11478
11479 if (!trivially_copyable_p (desttype))
11480 warnfmt = G_("%qD moving an object of non-trivially copyable type "
11481 "%#qT; use %<new%> and %<delete%> instead");
11482 else if (!trivcopy)
11483 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
11484 "constructor; use %<new%> and %<delete%> instead");
11485 else if (!get_dtor (desttype, tf_none))
11486 warnfmt = G_("%qD moving an object of type %#qT with deleted "
11487 "destructor");
11488 else if (!trivial)
11489 {
11490 tree sz = maybe_constant_value ((*args)[1]);
11491 if (TREE_CODE (sz) == INTEGER_CST
11492 && tree_int_cst_lt (t1: sz, TYPE_SIZE_UNIT (desttype)))
11493 /* Finally, warn on reallocation into insufficient space. */
11494 warned = warning_at (loc, OPT_Wclass_memaccess,
11495 "%qD moving an object of non-trivial type "
11496 "%#qT and size %E into a region of size %E",
11497 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
11498 sz);
11499 }
11500 break;
11501
11502 default:
11503 return;
11504 }
11505
11506 if (warnfmt)
11507 {
11508 if (suggest)
11509 warned = warning_at (loc, OPT_Wclass_memaccess,
11510 warnfmt, fndecl, desttype, suggest);
11511 else
11512 warned = warning_at (loc, OPT_Wclass_memaccess,
11513 warnfmt, fndecl, desttype);
11514 }
11515
11516 if (warned)
11517 inform (location_of (desttype), "%#qT declared here", desttype);
11518}
11519
11520/* Build and return a call to FN, using NARGS arguments in ARGARRAY.
11521 If FN is the result of resolving an overloaded target built-in,
11522 ORIG_FNDECL is the original function decl, otherwise it is null.
11523 This function performs no overload resolution, conversion, or other
11524 high-level operations. */
11525
11526tree
11527build_cxx_call (tree fn, int nargs, tree *argarray,
11528 tsubst_flags_t complain, tree orig_fndecl)
11529{
11530 tree fndecl;
11531
11532 /* Remember roughly where this call is. */
11533 location_t loc = cp_expr_loc_or_input_loc (t: fn);
11534 fn = build_call_a (function: fn, n: nargs, argarray);
11535 SET_EXPR_LOCATION (fn, loc);
11536
11537 fndecl = get_callee_fndecl (fn);
11538 if (!orig_fndecl)
11539 orig_fndecl = fndecl;
11540
11541 /* Check that arguments to builtin functions match the expectations. */
11542 if (fndecl
11543 && !processing_template_decl
11544 && fndecl_built_in_p (node: fndecl))
11545 {
11546 int i;
11547
11548 /* We need to take care that values to BUILT_IN_NORMAL
11549 are reduced. */
11550 for (i = 0; i < nargs; i++)
11551 argarray[i] = maybe_constant_value (argarray[i]);
11552
11553 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
11554 orig_fndecl, nargs, argarray,
11555 complain & tf_error))
11556 return error_mark_node;
11557 else if (fndecl_built_in_p (node: fndecl, name1: BUILT_IN_CLEAR_PADDING))
11558 {
11559 tree arg0 = argarray[0];
11560 STRIP_NOPS (arg0);
11561 if (TREE_CODE (arg0) == ADDR_EXPR
11562 && DECL_P (TREE_OPERAND (arg0, 0))
11563 && same_type_ignoring_top_level_qualifiers_p
11564 (TREE_TYPE (TREE_TYPE (argarray[0])),
11565 TREE_TYPE (TREE_TYPE (arg0))))
11566 /* For __builtin_clear_padding (&var) we know the type
11567 is for a complete object, so there is no risk in clearing
11568 padding that is reused in some derived class member. */;
11569 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
11570 {
11571 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
11572 "argument %u in call to function %qE "
11573 "has pointer to a non-trivially-copyable type (%qT)",
11574 1, fndecl, TREE_TYPE (argarray[0]));
11575 return error_mark_node;
11576 }
11577 }
11578 }
11579
11580 if (VOID_TYPE_P (TREE_TYPE (fn)))
11581 return maybe_contract_wrap_call (fndecl, fn);
11582
11583 /* 5.2.2/11: If a function call is a prvalue of object type: if the
11584 function call is either the operand of a decltype-specifier or the
11585 right operand of a comma operator that is the operand of a
11586 decltype-specifier, a temporary object is not introduced for the
11587 prvalue. The type of the prvalue may be incomplete. */
11588 if (!(complain & tf_decltype))
11589 {
11590 fn = require_complete_type (fn, complain);
11591 if (fn == error_mark_node)
11592 return error_mark_node;
11593 fn = maybe_contract_wrap_call (fndecl, fn);
11594
11595 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
11596 {
11597 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
11598 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
11599 }
11600 }
11601 else
11602 fn = maybe_contract_wrap_call (fndecl, fn);
11603 return convert_from_reference (fn);
11604}
11605
11606/* Returns the value to use for the in-charge parameter when making a
11607 call to a function with the indicated NAME.
11608
11609 FIXME:Can't we find a neater way to do this mapping? */
11610
11611tree
11612in_charge_arg_for_name (tree name)
11613{
11614 if (IDENTIFIER_CTOR_P (name))
11615 {
11616 if (name == complete_ctor_identifier)
11617 return integer_one_node;
11618 gcc_checking_assert (name == base_ctor_identifier);
11619 }
11620 else
11621 {
11622 if (name == complete_dtor_identifier)
11623 return integer_two_node;
11624 else if (name == deleting_dtor_identifier)
11625 /* The deleting dtor should now be handled by
11626 build_delete_destructor_body. */
11627 gcc_unreachable ();
11628 gcc_checking_assert (name == base_dtor_identifier);
11629 }
11630
11631 return integer_zero_node;
11632}
11633
11634/* We've built up a constructor call RET. Complain if it delegates to the
11635 constructor we're currently compiling. */
11636
11637static void
11638check_self_delegation (tree ret)
11639{
11640 if (TREE_CODE (ret) == TARGET_EXPR)
11641 ret = TARGET_EXPR_INITIAL (ret);
11642 tree fn = cp_get_callee_fndecl_nofold (ret);
11643 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11644 error ("constructor delegates to itself");
11645}
11646
11647/* Build a call to a constructor, destructor, or an assignment
11648 operator for INSTANCE, an expression with class type. NAME
11649 indicates the special member function to call; *ARGS are the
11650 arguments. ARGS may be NULL. This may change ARGS. BINFO
11651 indicates the base of INSTANCE that is to be passed as the `this'
11652 parameter to the member function called.
11653
11654 FLAGS are the LOOKUP_* flags to use when processing the call.
11655
11656 If NAME indicates a complete object constructor, INSTANCE may be
11657 NULL_TREE. In this case, the caller will call build_cplus_new to
11658 store the newly constructed object into a VAR_DECL. */
11659
11660tree
11661build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11662 tree binfo, int flags, tsubst_flags_t complain)
11663{
11664 tree fns;
11665 /* The type of the subobject to be constructed or destroyed. */
11666 tree class_type;
11667 vec<tree, va_gc> *allocated = NULL;
11668 tree ret;
11669
11670 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11671
11672 if (error_operand_p (t: instance))
11673 return error_mark_node;
11674
11675 if (IDENTIFIER_DTOR_P (name))
11676 {
11677 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11678 if (!type_build_dtor_call (TREE_TYPE (instance)))
11679 /* Shortcut to avoid lazy destructor declaration. */
11680 return build_trivial_dtor_call (instance);
11681 }
11682
11683 if (TYPE_P (binfo))
11684 {
11685 /* Resolve the name. */
11686 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11687 return error_mark_node;
11688
11689 binfo = TYPE_BINFO (binfo);
11690 }
11691
11692 gcc_assert (binfo != NULL_TREE);
11693
11694 class_type = BINFO_TYPE (binfo);
11695
11696 /* Handle the special case where INSTANCE is NULL_TREE. */
11697 if (name == complete_ctor_identifier && !instance)
11698 instance = build_dummy_object (class_type);
11699 else
11700 {
11701 /* Convert to the base class, if necessary. */
11702 if (!same_type_ignoring_top_level_qualifiers_p
11703 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11704 {
11705 if (IDENTIFIER_CDTOR_P (name))
11706 /* For constructors and destructors, either the base is
11707 non-virtual, or it is virtual but we are doing the
11708 conversion from a constructor or destructor for the
11709 complete object. In either case, we can convert
11710 statically. */
11711 instance = convert_to_base_statically (instance, binfo);
11712 else
11713 {
11714 /* However, for assignment operators, we must convert
11715 dynamically if the base is virtual. */
11716 gcc_checking_assert (name == assign_op_identifier);
11717 instance = build_base_path (PLUS_EXPR, instance,
11718 binfo, /*nonnull=*/1, complain);
11719 }
11720 }
11721 }
11722
11723 gcc_assert (instance != NULL_TREE);
11724
11725 /* In C++17, "If the initializer expression is a prvalue and the
11726 cv-unqualified version of the source type is the same class as the class
11727 of the destination, the initializer expression is used to initialize the
11728 destination object." Handle that here to avoid doing overload
11729 resolution. */
11730 if (cxx_dialect >= cxx17
11731 && args && vec_safe_length (v: *args) == 1
11732 && !unsafe_return_slot_p (t: instance))
11733 {
11734 tree arg = (**args)[0];
11735
11736 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11737 && !TYPE_HAS_LIST_CTOR (class_type)
11738 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11739 && CONSTRUCTOR_NELTS (arg) == 1)
11740 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11741
11742 if ((TREE_CODE (arg) == TARGET_EXPR
11743 || TREE_CODE (arg) == CONSTRUCTOR)
11744 && (same_type_ignoring_top_level_qualifiers_p
11745 (class_type, TREE_TYPE (arg))))
11746 {
11747 if (is_dummy_object (instance))
11748 return arg;
11749 else if (TREE_CODE (arg) == TARGET_EXPR)
11750 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11751
11752 if ((complain & tf_error)
11753 && (flags & LOOKUP_DELEGATING_CONS))
11754 check_self_delegation (ret: arg);
11755 /* Avoid change of behavior on Wunused-var-2.C. */
11756 instance = mark_lvalue_use (instance);
11757 return cp_build_init_expr (t: instance, i: arg);
11758 }
11759 }
11760
11761 fns = lookup_fnfields (binfo, name, 1, complain);
11762
11763 /* When making a call to a constructor or destructor for a subobject
11764 that uses virtual base classes, pass down a pointer to a VTT for
11765 the subobject. */
11766 if ((name == base_ctor_identifier
11767 || name == base_dtor_identifier)
11768 && CLASSTYPE_VBASECLASSES (class_type))
11769 {
11770 tree vtt;
11771 tree sub_vtt;
11772
11773 /* If the current function is a complete object constructor
11774 or destructor, then we fetch the VTT directly.
11775 Otherwise, we look it up using the VTT we were given. */
11776 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11777 vtt = decay_conversion (vtt, complain);
11778 if (vtt == error_mark_node)
11779 return error_mark_node;
11780 vtt = build_if_in_charge (true_stmt: vtt, current_vtt_parm);
11781 if (BINFO_SUBVTT_INDEX (binfo))
11782 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11783 else
11784 sub_vtt = vtt;
11785
11786 if (args == NULL)
11787 {
11788 allocated = make_tree_vector ();
11789 args = &allocated;
11790 }
11791
11792 vec_safe_insert (v&: *args, ix: 0, obj: sub_vtt);
11793 }
11794
11795 ret = build_new_method_call (instance, fns, args,
11796 TYPE_BINFO (BINFO_TYPE (binfo)),
11797 flags, /*fn=*/NULL,
11798 complain);
11799
11800 if (allocated != NULL)
11801 release_tree_vector (allocated);
11802
11803 if ((complain & tf_error)
11804 && (flags & LOOKUP_DELEGATING_CONS)
11805 && name == complete_ctor_identifier)
11806 check_self_delegation (ret);
11807
11808 return ret;
11809}
11810
11811/* Return the NAME, as a C string. The NAME indicates a function that
11812 is a member of TYPE. *FREE_P is set to true if the caller must
11813 free the memory returned.
11814
11815 Rather than go through all of this, we should simply set the names
11816 of constructors and destructors appropriately, and dispense with
11817 ctor_identifier, dtor_identifier, etc. */
11818
11819static char *
11820name_as_c_string (tree name, tree type, bool *free_p)
11821{
11822 const char *pretty_name;
11823
11824 /* Assume that we will not allocate memory. */
11825 *free_p = false;
11826 /* Constructors and destructors are special. */
11827 if (IDENTIFIER_CDTOR_P (name))
11828 {
11829 pretty_name
11830 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11831 /* For a destructor, add the '~'. */
11832 if (IDENTIFIER_DTOR_P (name))
11833 {
11834 pretty_name = concat ("~", pretty_name, NULL);
11835 /* Remember that we need to free the memory allocated. */
11836 *free_p = true;
11837 }
11838 }
11839 else if (IDENTIFIER_CONV_OP_P (name))
11840 {
11841 pretty_name = concat ("operator ",
11842 type_as_string_translate (TREE_TYPE (name),
11843 TFF_PLAIN_IDENTIFIER),
11844 NULL);
11845 /* Remember that we need to free the memory allocated. */
11846 *free_p = true;
11847 }
11848 else
11849 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11850
11851 return const_cast<char *> (pretty_name);
11852}
11853
11854/* If CANDIDATES contains exactly one candidate, return it, otherwise
11855 return NULL. */
11856
11857static z_candidate *
11858single_z_candidate (z_candidate *candidates)
11859{
11860 if (candidates == NULL)
11861 return NULL;
11862
11863 if (candidates->next)
11864 return NULL;
11865
11866 return candidates;
11867}
11868
11869/* If CANDIDATE is invalid due to a bad argument type, return the
11870 pertinent conversion_info.
11871
11872 Otherwise, return NULL. */
11873
11874static const conversion_info *
11875maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11876{
11877 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11878 rejection_reason *r = candidate->reason;
11879
11880 if (r == NULL)
11881 return NULL;
11882
11883 switch (r->code)
11884 {
11885 default:
11886 return NULL;
11887
11888 case rr_arg_conversion:
11889 return &r->u.conversion;
11890
11891 case rr_bad_arg_conversion:
11892 return &r->u.bad_conversion;
11893 }
11894}
11895
11896/* Issue an error and note complaining about a bad argument type at a
11897 callsite with a single candidate FNDECL.
11898
11899 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11900 case input_location is used).
11901 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11902 the formal parameter. */
11903
11904void
11905complain_about_bad_argument (location_t arg_loc,
11906 tree from_type, tree to_type,
11907 tree fndecl, int parmnum)
11908{
11909 auto_diagnostic_group d;
11910 range_label_for_type_mismatch rhs_label (from_type, to_type);
11911 range_label *label = &rhs_label;
11912 if (arg_loc == UNKNOWN_LOCATION)
11913 {
11914 arg_loc = input_location;
11915 label = NULL;
11916 }
11917 gcc_rich_location richloc (arg_loc, label, highlight_colors::percent_h);
11918 error_at (&richloc,
11919 "cannot convert %qH to %qI",
11920 from_type, to_type);
11921 maybe_inform_about_fndecl_for_bogus_argument_init
11922 (fn: fndecl,
11923 argnum: parmnum,
11924 highlight_color: highlight_colors::percent_i);
11925}
11926
11927/* Subroutine of build_new_method_call_1, for where there are no viable
11928 candidates for the call. */
11929
11930static void
11931complain_about_no_candidates_for_method_call (tree instance,
11932 z_candidate *candidates,
11933 tree explicit_targs,
11934 tree basetype,
11935 tree optype, tree name,
11936 bool skip_first_for_error,
11937 vec<tree, va_gc> *user_args)
11938{
11939 auto_diagnostic_group d;
11940 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11941 cxx_incomplete_type_error (value: instance, type: basetype);
11942 else if (optype)
11943 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11944 basetype, optype, build_tree_list_vec (user_args),
11945 TREE_TYPE (instance));
11946 else
11947 {
11948 /* Special-case for when there's a single candidate that's failing
11949 due to a bad argument type. */
11950 if (z_candidate *candidate = single_z_candidate (candidates))
11951 if (const conversion_info *conv
11952 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11953 {
11954 tree from_type = conv->from;
11955 if (!TYPE_P (conv->from))
11956 from_type = lvalue_type (conv->from);
11957 complain_about_bad_argument (arg_loc: conv->loc,
11958 from_type, to_type: conv->to_type,
11959 fndecl: candidate->fn, parmnum: conv->n_arg);
11960 return;
11961 }
11962
11963 tree arglist = build_tree_list_vec (user_args);
11964 tree errname = name;
11965 bool twiddle = false;
11966 if (IDENTIFIER_CDTOR_P (errname))
11967 {
11968 twiddle = IDENTIFIER_DTOR_P (errname);
11969 errname = constructor_name (basetype);
11970 }
11971 if (explicit_targs)
11972 errname = lookup_template_function (errname, explicit_targs);
11973 if (skip_first_for_error)
11974 arglist = TREE_CHAIN (arglist);
11975 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11976 basetype, &"~"[!twiddle], errname, arglist,
11977 TREE_TYPE (instance));
11978 }
11979 print_z_candidates (loc: location_of (name), candidates);
11980}
11981
11982/* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11983 be set, upon return, to the function called. ARGS may be NULL.
11984 This may change ARGS. */
11985
11986tree
11987build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11988 tree conversion_path, int flags,
11989 tree *fn_p, tsubst_flags_t complain)
11990{
11991 struct z_candidate *candidates = 0, *cand;
11992 tree explicit_targs = NULL_TREE;
11993 tree basetype = NULL_TREE;
11994 tree access_binfo;
11995 tree optype;
11996 tree first_mem_arg = NULL_TREE;
11997 tree name;
11998 bool skip_first_for_error;
11999 vec<tree, va_gc> *user_args;
12000 tree call;
12001 tree fn;
12002 int template_only = 0;
12003 bool any_viable_p;
12004 tree orig_instance;
12005 tree orig_fns;
12006 vec<tree, va_gc> *orig_args = NULL;
12007
12008 auto_cond_timevar tv (TV_OVERLOAD);
12009
12010 gcc_assert (instance != NULL_TREE);
12011
12012 /* We don't know what function we're going to call, yet. */
12013 if (fn_p)
12014 *fn_p = NULL_TREE;
12015
12016 if (error_operand_p (t: instance)
12017 || !fns || error_operand_p (t: fns))
12018 return error_mark_node;
12019
12020 if (!BASELINK_P (fns))
12021 {
12022 if (complain & tf_error)
12023 error ("call to non-function %qD", fns);
12024 return error_mark_node;
12025 }
12026
12027 orig_instance = instance;
12028 orig_fns = fns;
12029
12030 /* Dismantle the baselink to collect all the information we need. */
12031 if (!conversion_path)
12032 conversion_path = BASELINK_BINFO (fns);
12033 access_binfo = BASELINK_ACCESS_BINFO (fns);
12034 optype = BASELINK_OPTYPE (fns);
12035 fns = BASELINK_FUNCTIONS (fns);
12036 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
12037 {
12038 explicit_targs = TREE_OPERAND (fns, 1);
12039 fns = TREE_OPERAND (fns, 0);
12040 template_only = 1;
12041 }
12042 gcc_assert (OVL_P (fns));
12043 fn = OVL_FIRST (fns);
12044 name = DECL_NAME (fn);
12045
12046 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
12047 gcc_assert (CLASS_TYPE_P (basetype));
12048
12049 user_args = args == NULL ? NULL : *args;
12050 /* Under DR 147 A::A() is an invalid constructor call,
12051 not a functional cast. */
12052 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
12053 {
12054 if (! (complain & tf_error))
12055 return error_mark_node;
12056
12057 basetype = DECL_CONTEXT (fn);
12058 name = constructor_name (basetype);
12059 auto_diagnostic_group d;
12060 if (permerror (input_location,
12061 "cannot call constructor %<%T::%D%> directly",
12062 basetype, name))
12063 inform (input_location, "for a function-style cast, remove the "
12064 "redundant %<::%D%>", name);
12065 call = build_functional_cast (input_location, basetype,
12066 build_tree_list_vec (user_args),
12067 complain);
12068 return call;
12069 }
12070
12071 if (processing_template_decl)
12072 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
12073
12074 /* Process the argument list. */
12075 if (args != NULL && *args != NULL)
12076 {
12077 *args = resolve_args (args: *args, complain);
12078 if (*args == NULL)
12079 return error_mark_node;
12080 user_args = *args;
12081 }
12082
12083 /* Consider the object argument to be used even if we end up selecting a
12084 static member function. */
12085 instance = mark_type_use (instance);
12086
12087 /* Figure out whether to skip the first argument for the error
12088 message we will display to users if an error occurs. We don't
12089 want to display any compiler-generated arguments. The "this"
12090 pointer hasn't been added yet. However, we must remove the VTT
12091 pointer if this is a call to a base-class constructor or
12092 destructor. */
12093 skip_first_for_error = false;
12094 if (IDENTIFIER_CDTOR_P (name))
12095 {
12096 /* Callers should explicitly indicate whether they want to ctor
12097 the complete object or just the part without virtual bases. */
12098 gcc_assert (name != ctor_identifier);
12099
12100 /* Remove the VTT pointer, if present. */
12101 if ((name == base_ctor_identifier || name == base_dtor_identifier)
12102 && CLASSTYPE_VBASECLASSES (basetype))
12103 skip_first_for_error = true;
12104
12105 /* It's OK to call destructors and constructors on cv-qualified
12106 objects. Therefore, convert the INSTANCE to the unqualified
12107 type, if necessary. */
12108 if (!same_type_p (basetype, TREE_TYPE (instance)))
12109 {
12110 instance = build_this (obj: instance);
12111 instance = build_nop (build_pointer_type (basetype), instance);
12112 instance = build_fold_indirect_ref (instance);
12113 }
12114 }
12115 else
12116 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
12117
12118 /* For the overload resolution we need to find the actual `this`
12119 that would be captured if the call turns out to be to a
12120 non-static member function. Do not actually capture it at this
12121 point. */
12122 if (DECL_CONSTRUCTOR_P (fn))
12123 /* Constructors don't use the enclosing 'this'. */
12124 first_mem_arg = instance;
12125 else
12126 first_mem_arg = maybe_resolve_dummy (instance, false);
12127
12128 conversion_obstack_sentinel cos;
12129
12130 /* The number of arguments artificial parms in ARGS; we subtract one because
12131 there's no 'this' in ARGS. */
12132 unsigned skip = num_artificial_parms_for (fn) - 1;
12133
12134 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
12135 initializer, not T({ }). */
12136 if (DECL_CONSTRUCTOR_P (fn)
12137 && vec_safe_length (v: user_args) > skip
12138 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
12139 {
12140 tree init_list = (*user_args)[skip];
12141 tree init = NULL_TREE;
12142
12143 gcc_assert (user_args->length () == skip + 1
12144 && !(flags & LOOKUP_ONLYCONVERTING));
12145
12146 /* If the initializer list has no elements and T is a class type with
12147 a default constructor, the object is value-initialized. Handle
12148 this here so we don't need to handle it wherever we use
12149 build_special_member_call. */
12150 if (CONSTRUCTOR_NELTS (init_list) == 0
12151 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
12152 /* For a user-provided default constructor, use the normal
12153 mechanisms so that protected access works. */
12154 && type_has_non_user_provided_default_constructor (basetype)
12155 && !processing_template_decl)
12156 init = build_value_init (basetype, complain);
12157
12158 /* If BASETYPE is an aggregate, we need to do aggregate
12159 initialization. */
12160 else if (CP_AGGREGATE_TYPE_P (basetype))
12161 {
12162 init = reshape_init (basetype, init_list, complain);
12163 init = digest_init (basetype, init, complain);
12164 }
12165
12166 if (init)
12167 {
12168 if (is_dummy_object (instance))
12169 return get_target_expr (init, complain);
12170 return cp_build_init_expr (t: instance, i: init);
12171 }
12172
12173 /* Otherwise go ahead with overload resolution. */
12174 add_list_candidates (fns, first_arg: first_mem_arg, args: user_args,
12175 totype: basetype, explicit_targs, template_only,
12176 conversion_path, access_path: access_binfo, flags,
12177 candidates: &candidates, complain);
12178 }
12179 else
12180 add_candidates (fns, first_arg: first_mem_arg, args: user_args, return_type: optype,
12181 explicit_targs, template_only, conversion_path,
12182 access_path: access_binfo, flags, candidates: &candidates, complain);
12183
12184 any_viable_p = false;
12185 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
12186
12187 if (!any_viable_p)
12188 {
12189 /* [dcl.init], 17.6.2.2:
12190
12191 Otherwise, if no constructor is viable, the destination type is
12192 a (possibly cv-qualified) aggregate class A, and the initializer
12193 is a parenthesized expression-list, the object is initialized as
12194 follows...
12195
12196 We achieve this by building up a CONSTRUCTOR, as for list-init,
12197 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
12198 the two. */
12199 if (DECL_CONSTRUCTOR_P (fn)
12200 && !(flags & LOOKUP_ONLYCONVERTING)
12201 && cxx_dialect >= cxx20
12202 && CP_AGGREGATE_TYPE_P (basetype)
12203 && !vec_safe_is_empty (v: user_args))
12204 {
12205 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
12206 tree ctor = build_constructor_from_vec (init_list_type_node,
12207 user_args);
12208 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
12209 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
12210 if (is_dummy_object (instance))
12211 return ctor;
12212 else
12213 {
12214 ctor = digest_init (basetype, ctor, complain);
12215 if (ctor == error_mark_node)
12216 return error_mark_node;
12217 return cp_build_init_expr (t: instance, i: ctor);
12218 }
12219 }
12220 if (complain & tf_error)
12221 complain_about_no_candidates_for_method_call (instance, candidates,
12222 explicit_targs, basetype,
12223 optype, name,
12224 skip_first_for_error,
12225 user_args);
12226 call = error_mark_node;
12227 }
12228 else
12229 {
12230 cand = tourney (candidates, complain);
12231 if (cand == 0)
12232 {
12233 char *pretty_name;
12234 bool free_p;
12235 tree arglist;
12236
12237 if (complain & tf_error)
12238 {
12239 pretty_name = name_as_c_string (name, type: basetype, free_p: &free_p);
12240 arglist = build_tree_list_vec (user_args);
12241 if (skip_first_for_error)
12242 arglist = TREE_CHAIN (arglist);
12243 auto_diagnostic_group d;
12244 if (!any_strictly_viable (cands: candidates))
12245 error ("no matching function for call to %<%s(%A)%>",
12246 pretty_name, arglist);
12247 else
12248 error ("call of overloaded %<%s(%A)%> is ambiguous",
12249 pretty_name, arglist);
12250 print_z_candidates (loc: location_of (name), candidates);
12251 if (free_p)
12252 free (ptr: pretty_name);
12253 }
12254 call = error_mark_node;
12255 if (fn_p)
12256 *fn_p = error_mark_node;
12257 }
12258 else
12259 {
12260 fn = cand->fn;
12261 call = NULL_TREE;
12262
12263 if (!(flags & LOOKUP_NONVIRTUAL)
12264 && DECL_PURE_VIRTUAL_P (fn)
12265 && instance == current_class_ref
12266 && (complain & tf_warning))
12267 {
12268 /* This is not an error, it is runtime undefined
12269 behavior. */
12270 if (!current_function_decl)
12271 warning (0, "pure virtual %q#D called from "
12272 "non-static data member initializer", fn);
12273 else if (DECL_CONSTRUCTOR_P (current_function_decl)
12274 || DECL_DESTRUCTOR_P (current_function_decl))
12275 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
12276 ? G_("pure virtual %q#D called from constructor")
12277 : G_("pure virtual %q#D called from destructor")),
12278 fn);
12279 }
12280
12281 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn)
12282 && !DECL_CONSTRUCTOR_P (fn)
12283 && is_dummy_object (instance))
12284 {
12285 instance = maybe_resolve_dummy (instance, true);
12286 if (instance == error_mark_node)
12287 call = error_mark_node;
12288 else if (!is_dummy_object (instance))
12289 {
12290 /* We captured 'this' in the current lambda now that
12291 we know we really need it. */
12292 cand->first_arg = instance;
12293 }
12294 else if (current_class_ptr && any_dependent_bases_p ())
12295 /* We can't tell until instantiation time whether we can use
12296 *this as the implicit object argument. */;
12297 else
12298 {
12299 if (complain & tf_error)
12300 error ("cannot call member function %qD without object",
12301 fn);
12302 call = error_mark_node;
12303 }
12304 }
12305
12306 if (call != error_mark_node)
12307 {
12308 /* Now we know what function is being called. */
12309 if (fn_p)
12310 *fn_p = fn;
12311 /* Build the actual CALL_EXPR. */
12312 call = build_over_call (cand, flags, complain);
12313
12314 /* Suppress warnings for if (my_struct.operator= (x)) where
12315 my_struct is implicitly converted to bool. */
12316 if (TREE_CODE (call) == MODIFY_EXPR)
12317 suppress_warning (call, OPT_Wparentheses);
12318
12319 /* In an expression of the form `a->f()' where `f' turns
12320 out to be a static member function, `a' is
12321 none-the-less evaluated. */
12322 if (!is_dummy_object (instance))
12323 call = keep_unused_object_arg (result: call, obj: instance, fn);
12324 if (call != error_mark_node
12325 && DECL_DESTRUCTOR_P (cand->fn)
12326 && !VOID_TYPE_P (TREE_TYPE (call)))
12327 /* An explicit call of the form "x->~X()" has type
12328 "void". However, on platforms where destructors
12329 return "this" (i.e., those where
12330 targetm.cxx.cdtor_returns_this is true), such calls
12331 will appear to have a return value of pointer type
12332 to the low-level call machinery. We do not want to
12333 change the low-level machinery, since we want to be
12334 able to optimize "delete f()" on such platforms as
12335 "operator delete(~X(f()))" (rather than generating
12336 "t = f(), ~X(t), operator delete (t)"). */
12337 call = build_nop (void_type_node, call);
12338 }
12339 }
12340 }
12341
12342 if (processing_template_decl && call != error_mark_node)
12343 {
12344 bool cast_to_void = false;
12345
12346 if (TREE_CODE (call) == COMPOUND_EXPR)
12347 call = TREE_OPERAND (call, 1);
12348 else if (TREE_CODE (call) == NOP_EXPR)
12349 {
12350 cast_to_void = true;
12351 call = TREE_OPERAND (call, 0);
12352 }
12353 if (INDIRECT_REF_P (call))
12354 call = TREE_OPERAND (call, 0);
12355
12356 /* Prune all but the selected function from the original overload
12357 set so that we can avoid some duplicate work at instantiation time. */
12358 if (really_overloaded_fn (fns))
12359 {
12360 if (DECL_TEMPLATE_INFO (fn)
12361 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
12362 {
12363 /* Use the selected template, not the specialization, so that
12364 this looks like an actual lookup result for sake of
12365 filter_memfn_lookup. */
12366
12367 if (OVL_SINGLE_P (fns))
12368 /* If the original overload set consists of a single function
12369 template, this isn't beneficial. */
12370 goto skip_prune;
12371
12372 fn = ovl_make (DECL_TI_TEMPLATE (fn));
12373 if (template_only)
12374 fn = lookup_template_function (fn, explicit_targs);
12375 }
12376 orig_fns = copy_node (orig_fns);
12377 BASELINK_FUNCTIONS (orig_fns) = fn;
12378 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
12379 }
12380
12381skip_prune:
12382 call = (build_min_non_dep_call_vec
12383 (call,
12384 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
12385 orig_instance, orig_fns, NULL_TREE),
12386 orig_args));
12387 SET_EXPR_LOCATION (call, input_location);
12388 call = convert_from_reference (call);
12389 if (cast_to_void)
12390 call = build_nop (void_type_node, call);
12391 }
12392
12393 if (orig_args != NULL)
12394 release_tree_vector (orig_args);
12395
12396 return call;
12397}
12398
12399/* Returns true iff standard conversion sequence ICS1 is a proper
12400 subsequence of ICS2. */
12401
12402static bool
12403is_subseq (conversion *ics1, conversion *ics2)
12404{
12405 /* We can assume that a conversion of the same code
12406 between the same types indicates a subsequence since we only get
12407 here if the types we are converting from are the same. */
12408
12409 while (ics1->kind == ck_rvalue
12410 || ics1->kind == ck_lvalue)
12411 ics1 = next_conversion (conv: ics1);
12412
12413 while (1)
12414 {
12415 while (ics2->kind == ck_rvalue
12416 || ics2->kind == ck_lvalue)
12417 ics2 = next_conversion (conv: ics2);
12418
12419 if (ics2->kind == ck_user
12420 || !has_next (code: ics2->kind))
12421 /* At this point, ICS1 cannot be a proper subsequence of
12422 ICS2. We can get a USER_CONV when we are comparing the
12423 second standard conversion sequence of two user conversion
12424 sequences. */
12425 return false;
12426
12427 ics2 = next_conversion (conv: ics2);
12428
12429 while (ics2->kind == ck_rvalue
12430 || ics2->kind == ck_lvalue)
12431 ics2 = next_conversion (conv: ics2);
12432
12433 if (ics2->kind == ics1->kind
12434 && same_type_p (ics2->type, ics1->type)
12435 && (ics1->kind == ck_identity
12436 || same_type_p (next_conversion (ics2)->type,
12437 next_conversion (ics1)->type)))
12438 return true;
12439 }
12440}
12441
12442/* Returns nonzero iff DERIVED is derived from BASE. The inputs may
12443 be any _TYPE nodes. */
12444
12445bool
12446is_properly_derived_from (tree derived, tree base)
12447{
12448 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
12449 return false;
12450
12451 /* We only allow proper derivation here. The DERIVED_FROM_P macro
12452 considers every class derived from itself. */
12453 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
12454 && DERIVED_FROM_P (base, derived));
12455}
12456
12457/* We build the ICS for an implicit object parameter as a pointer
12458 conversion sequence. However, such a sequence should be compared
12459 as if it were a reference conversion sequence. If ICS is the
12460 implicit conversion sequence for an implicit object parameter,
12461 modify it accordingly. */
12462
12463static void
12464maybe_handle_implicit_object (conversion **ics)
12465{
12466 if ((*ics)->this_p)
12467 {
12468 /* [over.match.funcs]
12469
12470 For non-static member functions, the type of the
12471 implicit object parameter is "reference to cv X"
12472 where X is the class of which the function is a
12473 member and cv is the cv-qualification on the member
12474 function declaration. */
12475 conversion *t = *ics;
12476 tree reference_type;
12477
12478 /* The `this' parameter is a pointer to a class type. Make the
12479 implicit conversion talk about a reference to that same class
12480 type. */
12481 reference_type = TREE_TYPE (t->type);
12482 reference_type = build_reference_type (reference_type);
12483
12484 if (t->kind == ck_qual)
12485 t = next_conversion (conv: t);
12486 if (t->kind == ck_ptr)
12487 t = next_conversion (conv: t);
12488 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
12489 t = direct_reference_binding (type: reference_type, conv: t);
12490 t->this_p = 1;
12491 t->rvaluedness_matches_p = 0;
12492 *ics = t;
12493 }
12494}
12495
12496/* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
12497 and return the initial reference binding conversion. Otherwise,
12498 leave *ICS unchanged and return NULL. */
12499
12500static conversion *
12501maybe_handle_ref_bind (conversion **ics)
12502{
12503 if ((*ics)->kind == ck_ref_bind)
12504 {
12505 conversion *old_ics = *ics;
12506 *ics = next_conversion (conv: old_ics);
12507 (*ics)->user_conv_p = old_ics->user_conv_p;
12508 return old_ics;
12509 }
12510
12511 return NULL;
12512}
12513
12514/* Get the expression at the beginning of the conversion chain C. */
12515
12516static tree
12517conv_get_original_expr (conversion *c)
12518{
12519 for (; c; c = next_conversion (conv: c))
12520 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
12521 return c->u.expr;
12522 return NULL_TREE;
12523}
12524
12525/* Return a tree representing the number of elements initialized by the
12526 list-initialization C. The caller must check that C converts to an
12527 array type. */
12528
12529static tree
12530nelts_initialized_by_list_init (conversion *c)
12531{
12532 /* If the array we're converting to has a dimension, we'll use that. */
12533 if (TYPE_DOMAIN (c->type))
12534 return array_type_nelts_top (c->type);
12535 else
12536 {
12537 /* Otherwise, we look at how many elements the constructor we're
12538 initializing from has. */
12539 tree ctor = conv_get_original_expr (c);
12540 return size_int (CONSTRUCTOR_NELTS (ctor));
12541 }
12542}
12543
12544/* True iff C is a conversion that binds a reference or a pointer to
12545 an array of unknown bound. */
12546
12547static inline bool
12548conv_binds_to_array_of_unknown_bound (conversion *c)
12549{
12550 /* ck_ref_bind won't have the reference stripped. */
12551 tree type = non_reference (c->type);
12552 /* ck_qual won't have the pointer stripped. */
12553 type = strip_pointer_operator (type);
12554 return (TREE_CODE (type) == ARRAY_TYPE
12555 && TYPE_DOMAIN (type) == NULL_TREE);
12556}
12557
12558/* Compare two implicit conversion sequences according to the rules set out in
12559 [over.ics.rank]. Return values:
12560
12561 1: ics1 is better than ics2
12562 -1: ics2 is better than ics1
12563 0: ics1 and ics2 are indistinguishable */
12564
12565static int
12566compare_ics (conversion *ics1, conversion *ics2)
12567{
12568 tree from_type1;
12569 tree from_type2;
12570 tree to_type1;
12571 tree to_type2;
12572 tree deref_from_type1 = NULL_TREE;
12573 tree deref_from_type2 = NULL_TREE;
12574 tree deref_to_type1 = NULL_TREE;
12575 tree deref_to_type2 = NULL_TREE;
12576 conversion_rank rank1, rank2;
12577
12578 /* REF_BINDING is nonzero if the result of the conversion sequence
12579 is a reference type. In that case REF_CONV is the reference
12580 binding conversion. */
12581 conversion *ref_conv1;
12582 conversion *ref_conv2;
12583
12584 /* Compare badness before stripping the reference conversion. */
12585 if (ics1->bad_p > ics2->bad_p)
12586 return -1;
12587 else if (ics1->bad_p < ics2->bad_p)
12588 return 1;
12589
12590 /* Handle implicit object parameters. */
12591 maybe_handle_implicit_object (ics: &ics1);
12592 maybe_handle_implicit_object (ics: &ics2);
12593
12594 /* Handle reference parameters. */
12595 ref_conv1 = maybe_handle_ref_bind (ics: &ics1);
12596 ref_conv2 = maybe_handle_ref_bind (ics: &ics2);
12597
12598 /* List-initialization sequence L1 is a better conversion sequence than
12599 list-initialization sequence L2 if L1 converts to
12600 std::initializer_list<X> for some X and L2 does not. */
12601 if (ics1->kind == ck_list && ics2->kind != ck_list)
12602 return 1;
12603 if (ics2->kind == ck_list && ics1->kind != ck_list)
12604 return -1;
12605
12606 /* [over.ics.rank]
12607
12608 When comparing the basic forms of implicit conversion sequences (as
12609 defined in _over.best.ics_)
12610
12611 --a standard conversion sequence (_over.ics.scs_) is a better
12612 conversion sequence than a user-defined conversion sequence
12613 or an ellipsis conversion sequence, and
12614
12615 --a user-defined conversion sequence (_over.ics.user_) is a
12616 better conversion sequence than an ellipsis conversion sequence
12617 (_over.ics.ellipsis_). */
12618 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12619 mismatch. If both ICS are bad, we try to make a decision based on
12620 what would have happened if they'd been good. This is not an
12621 extension, we'll still give an error when we build up the call; this
12622 just helps us give a more helpful error message. */
12623 rank1 = BAD_CONVERSION_RANK (ics1);
12624 rank2 = BAD_CONVERSION_RANK (ics2);
12625
12626 if (rank1 > rank2)
12627 return -1;
12628 else if (rank1 < rank2)
12629 return 1;
12630
12631 if (ics1->ellipsis_p)
12632 /* Both conversions are ellipsis conversions. */
12633 return 0;
12634
12635 /* User-defined conversion sequence U1 is a better conversion sequence
12636 than another user-defined conversion sequence U2 if they contain the
12637 same user-defined conversion operator or constructor and if the sec-
12638 ond standard conversion sequence of U1 is better than the second
12639 standard conversion sequence of U2. */
12640
12641 /* Handle list-conversion with the same code even though it isn't always
12642 ranked as a user-defined conversion and it doesn't have a second
12643 standard conversion sequence; it will still have the desired effect.
12644 Specifically, we need to do the reference binding comparison at the
12645 end of this function. */
12646
12647 if (ics1->user_conv_p || ics1->kind == ck_list
12648 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12649 {
12650 conversion *t1 = strip_standard_conversion (conv: ics1);
12651 conversion *t2 = strip_standard_conversion (conv: ics2);
12652
12653 if (!t1 || !t2 || t1->kind != t2->kind)
12654 return 0;
12655 else if (t1->kind == ck_user)
12656 {
12657 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12658 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12659 if (f1 != f2)
12660 return 0;
12661 }
12662 /* List-initialization sequence L1 is a better conversion sequence than
12663 list-initialization sequence L2 if
12664
12665 -- L1 and L2 convert to arrays of the same element type, and either
12666 the number of elements n1 initialized by L1 is less than the number
12667 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12668 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12669 P0388R4.) */
12670 else if (t1->kind == ck_aggr
12671 && TREE_CODE (t1->type) == ARRAY_TYPE
12672 && TREE_CODE (t2->type) == ARRAY_TYPE
12673 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12674 {
12675 tree n1 = nelts_initialized_by_list_init (c: t1);
12676 tree n2 = nelts_initialized_by_list_init (c: t2);
12677 if (tree_int_cst_lt (t1: n1, t2: n2))
12678 return 1;
12679 else if (tree_int_cst_lt (t1: n2, t2: n1))
12680 return -1;
12681 /* The n1 == n2 case. */
12682 bool c1 = conv_binds_to_array_of_unknown_bound (c: t1);
12683 bool c2 = conv_binds_to_array_of_unknown_bound (c: t2);
12684 if (c1 && !c2)
12685 return -1;
12686 else if (!c1 && c2)
12687 return 1;
12688 else
12689 return 0;
12690 }
12691 else
12692 {
12693 /* For ambiguous or aggregate conversions, use the target type as
12694 a proxy for the conversion function. */
12695 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12696 return 0;
12697 }
12698
12699 /* We can just fall through here, after setting up
12700 FROM_TYPE1 and FROM_TYPE2. */
12701 from_type1 = t1->type;
12702 from_type2 = t2->type;
12703 }
12704 else
12705 {
12706 conversion *t1;
12707 conversion *t2;
12708
12709 /* We're dealing with two standard conversion sequences.
12710
12711 [over.ics.rank]
12712
12713 Standard conversion sequence S1 is a better conversion
12714 sequence than standard conversion sequence S2 if
12715
12716 --S1 is a proper subsequence of S2 (comparing the conversion
12717 sequences in the canonical form defined by _over.ics.scs_,
12718 excluding any Lvalue Transformation; the identity
12719 conversion sequence is considered to be a subsequence of
12720 any non-identity conversion sequence */
12721
12722 t1 = ics1;
12723 while (t1->kind != ck_identity)
12724 t1 = next_conversion (conv: t1);
12725 from_type1 = t1->type;
12726
12727 t2 = ics2;
12728 while (t2->kind != ck_identity)
12729 t2 = next_conversion (conv: t2);
12730 from_type2 = t2->type;
12731 }
12732
12733 /* One sequence can only be a subsequence of the other if they start with
12734 the same type. They can start with different types when comparing the
12735 second standard conversion sequence in two user-defined conversion
12736 sequences. */
12737 if (same_type_p (from_type1, from_type2))
12738 {
12739 if (is_subseq (ics1, ics2))
12740 return 1;
12741 if (is_subseq (ics1: ics2, ics2: ics1))
12742 return -1;
12743 }
12744
12745 /* [over.ics.rank]
12746
12747 Or, if not that,
12748
12749 --the rank of S1 is better than the rank of S2 (by the rules
12750 defined below):
12751
12752 Standard conversion sequences are ordered by their ranks: an Exact
12753 Match is a better conversion than a Promotion, which is a better
12754 conversion than a Conversion.
12755
12756 Two conversion sequences with the same rank are indistinguishable
12757 unless one of the following rules applies:
12758
12759 --A conversion that does not a convert a pointer, pointer to member,
12760 or std::nullptr_t to bool is better than one that does.
12761
12762 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12763 so that we do not have to check it explicitly. */
12764 if (ics1->rank < ics2->rank)
12765 return 1;
12766 else if (ics2->rank < ics1->rank)
12767 return -1;
12768
12769 to_type1 = ics1->type;
12770 to_type2 = ics2->type;
12771
12772 /* A conversion from scalar arithmetic type to complex is worse than a
12773 conversion between scalar arithmetic types. */
12774 if (same_type_p (from_type1, from_type2)
12775 && ARITHMETIC_TYPE_P (from_type1)
12776 && ARITHMETIC_TYPE_P (to_type1)
12777 && ARITHMETIC_TYPE_P (to_type2)
12778 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12779 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12780 {
12781 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12782 return -1;
12783 else
12784 return 1;
12785 }
12786
12787 {
12788 /* A conversion in either direction between floating-point type FP1 and
12789 floating-point type FP2 is better than a conversion in the same
12790 direction between FP1 and arithmetic type T3 if
12791 - the floating-point conversion rank of FP1 is equal to the rank of
12792 FP2, and
12793 - T3 is not a floating-point type, or T3 is a floating-point type
12794 whose rank is not equal to the rank of FP1, or the floating-point
12795 conversion subrank of FP2 is greater than the subrank of T3. */
12796 tree fp1 = from_type1;
12797 tree fp2 = to_type1;
12798 tree fp3 = from_type2;
12799 tree t3 = to_type2;
12800 int ret = 1;
12801 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12802 {
12803 std::swap (a&: fp1, b&: fp2);
12804 std::swap (a&: fp3, b&: t3);
12805 }
12806 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12807 && SCALAR_FLOAT_TYPE_P (fp1)
12808 /* Only apply this rule if at least one of the 3 types is
12809 extended floating-point type, otherwise keep them as
12810 before for compatibility reasons with types like __float128.
12811 float, double and long double alone have different conversion
12812 ranks and so when just those 3 types are involved, this
12813 rule doesn't trigger. */
12814 && (extended_float_type_p (type: fp1)
12815 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (type: fp2))
12816 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (type: t3))))
12817 {
12818 if (TREE_CODE (fp2) != REAL_TYPE)
12819 {
12820 ret = -ret;
12821 std::swap (a&: fp2, b&: t3);
12822 }
12823 if (SCALAR_FLOAT_TYPE_P (fp2))
12824 {
12825 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12826 if the conversion rank is equal (-1 or 1 if the subrank is
12827 different). */
12828 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12829 fp2),
12830 -1, 1))
12831 {
12832 /* Conversion ranks of FP1 and FP2 are equal. */
12833 if (TREE_CODE (t3) != REAL_TYPE
12834 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12835 (fp1, t3),
12836 -1, 1))
12837 /* FP1 <-> FP2 conversion is better. */
12838 return ret;
12839 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12840 gcc_assert (IN_RANGE (c, -1, 1));
12841 if (c == 1)
12842 /* Conversion subrank of FP2 is greater than subrank of T3.
12843 FP1 <-> FP2 conversion is better. */
12844 return ret;
12845 else if (c == -1)
12846 /* Conversion subrank of FP2 is less than subrank of T3.
12847 FP1 <-> T3 conversion is better. */
12848 return -ret;
12849 }
12850 else if (SCALAR_FLOAT_TYPE_P (t3)
12851 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12852 (fp1, t3),
12853 -1, 1))
12854 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12855 ranks of FP1 and T3 are equal.
12856 FP1 <-> T3 conversion is better. */
12857 return -ret;
12858 }
12859 }
12860 }
12861
12862 if (TYPE_PTR_P (from_type1)
12863 && TYPE_PTR_P (from_type2)
12864 && TYPE_PTR_P (to_type1)
12865 && TYPE_PTR_P (to_type2))
12866 {
12867 deref_from_type1 = TREE_TYPE (from_type1);
12868 deref_from_type2 = TREE_TYPE (from_type2);
12869 deref_to_type1 = TREE_TYPE (to_type1);
12870 deref_to_type2 = TREE_TYPE (to_type2);
12871 }
12872 /* The rules for pointers to members A::* are just like the rules
12873 for pointers A*, except opposite: if B is derived from A then
12874 A::* converts to B::*, not vice versa. For that reason, we
12875 switch the from_ and to_ variables here. */
12876 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12877 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12878 || (TYPE_PTRMEMFUNC_P (from_type1)
12879 && TYPE_PTRMEMFUNC_P (from_type2)
12880 && TYPE_PTRMEMFUNC_P (to_type1)
12881 && TYPE_PTRMEMFUNC_P (to_type2)))
12882 {
12883 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12884 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12885 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12886 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12887 }
12888
12889 if (deref_from_type1 != NULL_TREE
12890 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12891 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12892 {
12893 /* This was one of the pointer or pointer-like conversions.
12894
12895 [over.ics.rank]
12896
12897 --If class B is derived directly or indirectly from class A,
12898 conversion of B* to A* is better than conversion of B* to
12899 void*, and conversion of A* to void* is better than
12900 conversion of B* to void*. */
12901 if (VOID_TYPE_P (deref_to_type1)
12902 && VOID_TYPE_P (deref_to_type2))
12903 {
12904 if (is_properly_derived_from (derived: deref_from_type1,
12905 base: deref_from_type2))
12906 return -1;
12907 else if (is_properly_derived_from (derived: deref_from_type2,
12908 base: deref_from_type1))
12909 return 1;
12910 }
12911 else if (VOID_TYPE_P (deref_to_type1)
12912 || VOID_TYPE_P (deref_to_type2))
12913 {
12914 if (same_type_p (deref_from_type1, deref_from_type2))
12915 {
12916 if (VOID_TYPE_P (deref_to_type2))
12917 {
12918 if (is_properly_derived_from (derived: deref_from_type1,
12919 base: deref_to_type1))
12920 return 1;
12921 }
12922 /* We know that DEREF_TO_TYPE1 is `void' here. */
12923 else if (is_properly_derived_from (derived: deref_from_type1,
12924 base: deref_to_type2))
12925 return -1;
12926 }
12927 }
12928 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12929 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12930 {
12931 /* [over.ics.rank]
12932
12933 --If class B is derived directly or indirectly from class A
12934 and class C is derived directly or indirectly from B,
12935
12936 --conversion of C* to B* is better than conversion of C* to
12937 A*,
12938
12939 --conversion of B* to A* is better than conversion of C* to
12940 A* */
12941 if (same_type_p (deref_from_type1, deref_from_type2))
12942 {
12943 if (is_properly_derived_from (derived: deref_to_type1,
12944 base: deref_to_type2))
12945 return 1;
12946 else if (is_properly_derived_from (derived: deref_to_type2,
12947 base: deref_to_type1))
12948 return -1;
12949 }
12950 else if (same_type_p (deref_to_type1, deref_to_type2))
12951 {
12952 if (is_properly_derived_from (derived: deref_from_type2,
12953 base: deref_from_type1))
12954 return 1;
12955 else if (is_properly_derived_from (derived: deref_from_type1,
12956 base: deref_from_type2))
12957 return -1;
12958 }
12959 }
12960 }
12961 else if (CLASS_TYPE_P (non_reference (from_type1))
12962 && same_type_p (from_type1, from_type2))
12963 {
12964 tree from = non_reference (from_type1);
12965
12966 /* [over.ics.rank]
12967
12968 --binding of an expression of type C to a reference of type
12969 B& is better than binding an expression of type C to a
12970 reference of type A&
12971
12972 --conversion of C to B is better than conversion of C to A, */
12973 if (is_properly_derived_from (derived: from, base: to_type1)
12974 && is_properly_derived_from (derived: from, base: to_type2))
12975 {
12976 if (is_properly_derived_from (derived: to_type1, base: to_type2))
12977 return 1;
12978 else if (is_properly_derived_from (derived: to_type2, base: to_type1))
12979 return -1;
12980 }
12981 }
12982 else if (CLASS_TYPE_P (non_reference (to_type1))
12983 && same_type_p (to_type1, to_type2))
12984 {
12985 tree to = non_reference (to_type1);
12986
12987 /* [over.ics.rank]
12988
12989 --binding of an expression of type B to a reference of type
12990 A& is better than binding an expression of type C to a
12991 reference of type A&,
12992
12993 --conversion of B to A is better than conversion of C to A */
12994 if (is_properly_derived_from (derived: from_type1, base: to)
12995 && is_properly_derived_from (derived: from_type2, base: to))
12996 {
12997 if (is_properly_derived_from (derived: from_type2, base: from_type1))
12998 return 1;
12999 else if (is_properly_derived_from (derived: from_type1, base: from_type2))
13000 return -1;
13001 }
13002 }
13003
13004 /* [over.ics.rank]
13005
13006 --S1 and S2 differ only in their qualification conversion and yield
13007 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
13008 qualification signature of type T1 is a proper subset of the cv-
13009 qualification signature of type T2 */
13010 if (ics1->kind == ck_qual
13011 && ics2->kind == ck_qual
13012 && same_type_p (from_type1, from_type2))
13013 {
13014 int result = comp_cv_qual_signature (to_type1, to_type2);
13015 if (result != 0)
13016 return result;
13017 }
13018
13019 /* [over.ics.rank]
13020
13021 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
13022 to an implicit object parameter of a non-static member function
13023 declared without a ref-qualifier, and either S1 binds an lvalue
13024 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
13025 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
13026 draft standard, 13.3.3.2)
13027
13028 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
13029 types to which the references refer are the same type except for
13030 top-level cv-qualifiers, and the type to which the reference
13031 initialized by S2 refers is more cv-qualified than the type to
13032 which the reference initialized by S1 refers.
13033
13034 DR 1328 [over.match.best]: the context is an initialization by
13035 conversion function for direct reference binding (13.3.1.6) of a
13036 reference to function type, the return type of F1 is the same kind of
13037 reference (i.e. lvalue or rvalue) as the reference being initialized,
13038 and the return type of F2 is not. */
13039
13040 if (ref_conv1 && ref_conv2)
13041 {
13042 if (!ref_conv1->this_p && !ref_conv2->this_p
13043 && (ref_conv1->rvaluedness_matches_p
13044 != ref_conv2->rvaluedness_matches_p)
13045 && (same_type_p (ref_conv1->type, ref_conv2->type)
13046 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
13047 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
13048 {
13049 if (ref_conv1->bad_p
13050 && !same_type_p (TREE_TYPE (ref_conv1->type),
13051 TREE_TYPE (ref_conv2->type)))
13052 /* Don't prefer a bad conversion that drops cv-quals to a bad
13053 conversion with the wrong rvalueness. */
13054 return 0;
13055 return (ref_conv1->rvaluedness_matches_p
13056 - ref_conv2->rvaluedness_matches_p);
13057 }
13058
13059 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
13060 {
13061 /* Per P0388R4:
13062
13063 void f (int(&)[]), // (1)
13064 f (int(&)[1]), // (2)
13065 f (int*); // (3)
13066
13067 (2) is better than (1), but (3) should be equal to (1) and to
13068 (2). For that reason we don't use ck_qual for (1) which would
13069 give it the cr_exact rank while (3) remains ck_identity.
13070 Therefore we compare (1) and (2) here. For (1) we'll have
13071
13072 ck_ref_bind <- ck_identity
13073 int[] & int[1]
13074
13075 so to handle this we must look at ref_conv. */
13076 bool c1 = conv_binds_to_array_of_unknown_bound (c: ref_conv1);
13077 bool c2 = conv_binds_to_array_of_unknown_bound (c: ref_conv2);
13078 if (c1 && !c2)
13079 return -1;
13080 else if (!c1 && c2)
13081 return 1;
13082
13083 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
13084 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
13085 if (ref_conv1->bad_p)
13086 {
13087 /* Prefer the one that drops fewer cv-quals. */
13088 tree ftype = next_conversion (conv: ref_conv1)->type;
13089 int fquals = cp_type_quals (ftype);
13090 q1 ^= fquals;
13091 q2 ^= fquals;
13092 }
13093 return comp_cv_qualification (q2, q1);
13094 }
13095 }
13096
13097 /* [over.ics.rank]
13098
13099 Per CWG 1601:
13100 -- A conversion that promotes an enumeration whose underlying type
13101 is fixed to its underlying type is better than one that promotes to
13102 the promoted underlying type, if the two are different. */
13103 if (ics1->rank == cr_promotion
13104 && ics2->rank == cr_promotion
13105 && UNSCOPED_ENUM_P (from_type1)
13106 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
13107 && same_type_p (from_type1, from_type2))
13108 {
13109 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
13110 tree prom = type_promotes_to (from_type1);
13111 if (!same_type_p (utype, prom))
13112 {
13113 if (same_type_p (to_type1, utype)
13114 && same_type_p (to_type2, prom))
13115 return 1;
13116 else if (same_type_p (to_type2, utype)
13117 && same_type_p (to_type1, prom))
13118 return -1;
13119 }
13120 }
13121
13122 /* Neither conversion sequence is better than the other. */
13123 return 0;
13124}
13125
13126/* The source type for this standard conversion sequence. */
13127
13128static tree
13129source_type (conversion *t)
13130{
13131 return strip_standard_conversion (conv: t)->type;
13132}
13133
13134/* Note a warning about preferring WINNER to LOSER. We do this by storing
13135 a pointer to LOSER and re-running joust to produce the warning if WINNER
13136 is actually used. */
13137
13138static void
13139add_warning (struct z_candidate *winner, struct z_candidate *loser)
13140{
13141 candidate_warning *cw = (candidate_warning *)
13142 conversion_obstack_alloc (n: sizeof (candidate_warning));
13143 cw->loser = loser;
13144 cw->next = winner->warnings;
13145 winner->warnings = cw;
13146}
13147
13148/* CAND is a constructor candidate in joust in C++17 and up. If it copies a
13149 prvalue returned from a conversion function, return true. Otherwise, return
13150 false. */
13151
13152static bool
13153joust_maybe_elide_copy (z_candidate *cand)
13154{
13155 tree fn = cand->fn;
13156 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
13157 return false;
13158 conversion *conv = cand->convs[0];
13159 if (conv->kind == ck_ambig)
13160 return false;
13161 gcc_checking_assert (conv->kind == ck_ref_bind);
13162 conv = next_conversion (conv);
13163 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
13164 {
13165 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
13166 (conv->type, DECL_CONTEXT (fn)));
13167 z_candidate *uc = conv->cand;
13168 if (DECL_CONV_FN_P (uc->fn))
13169 return true;
13170 }
13171 return false;
13172}
13173
13174/* Return the class that CAND's implicit object parameter refers to. */
13175
13176static tree
13177class_of_implicit_object (z_candidate *cand)
13178{
13179 if (!DECL_IOBJ_MEMBER_FUNCTION_P (cand->fn))
13180 return NULL_TREE;
13181
13182 /* "For conversion functions that are implicit object member functions,
13183 the function is considered to be a member of the class of the implied
13184 object argument for the purpose of defining the type of the implicit
13185 object parameter." */
13186 if (DECL_CONV_FN_P (cand->fn))
13187 return TYPE_MAIN_VARIANT (TREE_TYPE (cand->first_arg));
13188
13189 /* "For non-conversion functions that are implicit object member
13190 functions nominated by a using-declaration in a derived class, the
13191 function is considered to be a member of the derived class for the
13192 purpose of defining the type of the implicit object parameter."
13193
13194 That derived class is reflected in the conversion_path binfo. */
13195 return BINFO_TYPE (cand->conversion_path);
13196}
13197
13198/* Return whether the first parameter of C1 matches the second parameter
13199 of C2. */
13200
13201static bool
13202reversed_match (z_candidate *c1, z_candidate *c2)
13203{
13204 tree fn1 = c1->fn;
13205 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (c2->fn));
13206 tree parm2 = TREE_VALUE (TREE_CHAIN (parms2));
13207 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn1))
13208 {
13209 tree ctx = class_of_implicit_object (cand: c1);
13210 return iobj_parm_corresponds_to (fn1, parm2, ctx);
13211 }
13212 else
13213 {
13214 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
13215 tree parm1 = TREE_VALUE (parms1);
13216 return same_type_p (parm1, parm2);
13217 }
13218}
13219
13220/* True if the defining declarations of the two candidates have equivalent
13221 parameters. MATCH_KIND controls whether we're trying to compare the
13222 original declarations (for a warning) or the actual candidates. */
13223
13224enum class pmatch { original, current };
13225
13226static bool
13227cand_parms_match (z_candidate *c1, z_candidate *c2, pmatch match_kind)
13228{
13229 tree fn1 = c1->fn;
13230 tree fn2 = c2->fn;
13231 bool reversed = (match_kind == pmatch::current
13232 && c1->reversed () != c2->reversed ());
13233 if (fn1 == fn2 && !reversed)
13234 return true;
13235 if (identifier_p (t: fn1) || identifier_p (t: fn2))
13236 return false;
13237 if (match_kind == pmatch::original)
13238 {
13239 /* We don't look at c1->template_decl because that's only set for
13240 primary templates, not e.g. non-template member functions of
13241 class templates. */
13242 tree t1 = most_general_template (fn1);
13243 tree t2 = most_general_template (fn2);
13244 if (t1 || t2)
13245 {
13246 if (!t1 || !t2)
13247 return false;
13248 if (t1 == t2)
13249 return true;
13250 fn1 = DECL_TEMPLATE_RESULT (t1);
13251 fn2 = DECL_TEMPLATE_RESULT (t2);
13252 }
13253 }
13254
13255 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
13256 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
13257
13258 if (DECL_FUNCTION_MEMBER_P (fn1)
13259 && DECL_FUNCTION_MEMBER_P (fn2))
13260 {
13261 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (fn1));
13262 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (fn2));
13263 if (base1 != base2)
13264 return false;
13265
13266 if (reversed)
13267 return (reversed_match (c1, c2)
13268 && reversed_match (c1: c2, c2: c1));
13269
13270 /* Use object_parms_correspond to simplify comparing iobj/xobj/static
13271 member functions. */
13272 if (!object_parms_correspond (fn1, fn2, base1))
13273 return false;
13274
13275 /* We just compared the object parameters, if they don't correspond
13276 we already returned false. */
13277 auto skip_parms = [] (tree fn, tree parms)
13278 {
13279 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
13280 return TREE_CHAIN (parms);
13281 else
13282 return skip_artificial_parms_for (fn, parms);
13283 };
13284 parms1 = skip_parms (fn1, parms1);
13285 parms2 = skip_parms (fn2, parms2);
13286 }
13287 else if (reversed)
13288 return (reversed_match (c1, c2)
13289 && reversed_match (c1: c2, c2: c1));
13290 return compparms (parms1, parms2);
13291}
13292
13293/* True iff FN is a copy or move constructor or assignment operator. */
13294
13295static bool
13296sfk_copy_or_move (tree fn)
13297{
13298 if (TREE_CODE (fn) != FUNCTION_DECL)
13299 return false;
13300 special_function_kind sfk = special_function_p (fn);
13301 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
13302}
13303
13304/* Compare two candidates for overloading as described in
13305 [over.match.best]. Return values:
13306
13307 1: cand1 is better than cand2
13308 -1: cand2 is better than cand1
13309 0: cand1 and cand2 are indistinguishable */
13310
13311static int
13312joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
13313 tsubst_flags_t complain)
13314{
13315 int winner = 0;
13316 int off1 = 0, off2 = 0;
13317 size_t i;
13318 size_t len;
13319
13320 /* Candidates that involve bad conversions are always worse than those
13321 that don't. */
13322 if (cand1->viable > cand2->viable)
13323 return 1;
13324 if (cand1->viable < cand2->viable)
13325 return -1;
13326
13327 /* If we have two pseudo-candidates for conversions to the same type,
13328 or two candidates for the same function, arbitrarily pick one. */
13329 if (cand1->fn == cand2->fn
13330 && cand1->reversed () == cand2->reversed ()
13331 && (IS_TYPE_OR_DECL_P (cand1->fn)))
13332 return 1;
13333
13334 /* Prefer a non-deleted function over an implicitly deleted move
13335 constructor or assignment operator. This differs slightly from the
13336 wording for issue 1402 (which says the move op is ignored by overload
13337 resolution), but this way produces better error messages. */
13338 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13339 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13340 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
13341 {
13342 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
13343 && move_fn_p (cand1->fn))
13344 return -1;
13345 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
13346 && move_fn_p (cand2->fn))
13347 return 1;
13348 }
13349
13350 /* a viable function F1
13351 is defined to be a better function than another viable function F2 if
13352 for all arguments i, ICSi(F1) is not a worse conversion sequence than
13353 ICSi(F2), and then */
13354
13355 /* for some argument j, ICSj(F1) is a better conversion sequence than
13356 ICSj(F2) */
13357
13358 /* For comparing static and non-static member functions, we ignore
13359 the implicit object parameter of the non-static function. The
13360 standard says to pretend that the static function has an object
13361 parm, but that won't work with operator overloading. */
13362 len = cand1->num_convs;
13363 if (len != cand2->num_convs)
13364 {
13365 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
13366 && DECL_STATIC_FUNCTION_P (cand1->fn));
13367 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
13368 && DECL_STATIC_FUNCTION_P (cand2->fn));
13369
13370 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13371 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13372 && DECL_CONSTRUCTOR_P (cand1->fn)
13373 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
13374 /* We're comparing a near-match list constructor and a near-match
13375 non-list constructor. Just treat them as unordered. */
13376 return 0;
13377
13378 gcc_assert (static_1 != static_2);
13379
13380 if (static_1)
13381 {
13382 /* C++23 [over.best.ics.general] says:
13383 When the parameter is the implicit object parameter of a static
13384 member function, the implicit conversion sequence is a standard
13385 conversion sequence that is neither better nor worse than any
13386 other standard conversion sequence. */
13387 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
13388 winner = 1;
13389 off2 = 1;
13390 }
13391 else
13392 {
13393 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
13394 winner = -1;
13395 off1 = 1;
13396 --len;
13397 }
13398 }
13399
13400 for (i = 0; i < len; ++i)
13401 {
13402 conversion *t1 = cand1->convs[i + off1];
13403 conversion *t2 = cand2->convs[i + off2];
13404 int comp = compare_ics (ics1: t1, ics2: t2);
13405
13406 if (comp != 0)
13407 {
13408 if ((complain & tf_warning)
13409 && warn_sign_promo
13410 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
13411 == cr_std + cr_promotion)
13412 && t1->kind == ck_std
13413 && t2->kind == ck_std
13414 && TREE_CODE (t1->type) == INTEGER_TYPE
13415 && TREE_CODE (t2->type) == INTEGER_TYPE
13416 && (TYPE_PRECISION (t1->type)
13417 == TYPE_PRECISION (t2->type))
13418 && (TYPE_UNSIGNED (next_conversion (t1)->type)
13419 || (TREE_CODE (next_conversion (t1)->type)
13420 == ENUMERAL_TYPE)))
13421 {
13422 tree type = next_conversion (conv: t1)->type;
13423 tree type1, type2;
13424 struct z_candidate *w, *l;
13425 if (comp > 0)
13426 type1 = t1->type, type2 = t2->type,
13427 w = cand1, l = cand2;
13428 else
13429 type1 = t2->type, type2 = t1->type,
13430 w = cand2, l = cand1;
13431
13432 if (warn)
13433 {
13434 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
13435 type, type1, type2);
13436 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
13437 }
13438 else
13439 add_warning (winner: w, loser: l);
13440 }
13441
13442 if (winner && comp != winner)
13443 {
13444 /* Ambiguity between normal and reversed comparison operators
13445 with the same parameter types. P2468 decided not to go with
13446 this approach to resolving the ambiguity, so pedwarn. */
13447 if ((complain & tf_warning_or_error)
13448 && (cand1->reversed () != cand2->reversed ())
13449 && cand_parms_match (c1: cand1, c2: cand2, match_kind: pmatch::original))
13450 {
13451 struct z_candidate *w, *l;
13452 if (cand2->reversed ())
13453 winner = 1, w = cand1, l = cand2;
13454 else
13455 winner = -1, w = cand2, l = cand1;
13456 if (warn)
13457 {
13458 auto_diagnostic_group d;
13459 if (pedwarn (input_location, 0,
13460 "C++20 says that these are ambiguous, "
13461 "even though the second is reversed:"))
13462 {
13463 print_z_candidate (loc: input_location,
13464 N_("candidate 1:"), candidate: w);
13465 print_z_candidate (loc: input_location,
13466 N_("candidate 2:"), candidate: l);
13467 if (w->fn == l->fn
13468 && DECL_IOBJ_MEMBER_FUNCTION_P (w->fn)
13469 && (type_memfn_quals (TREE_TYPE (w->fn))
13470 & TYPE_QUAL_CONST) == 0)
13471 {
13472 /* Suggest adding const to
13473 struct A { bool operator==(const A&); }; */
13474 tree parmtype
13475 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
13476 parmtype = TREE_VALUE (parmtype);
13477 if (TYPE_REF_P (parmtype)
13478 && TYPE_READONLY (TREE_TYPE (parmtype))
13479 && (same_type_ignoring_top_level_qualifiers_p
13480 (TREE_TYPE (parmtype),
13481 DECL_CONTEXT (w->fn))))
13482 inform (DECL_SOURCE_LOCATION (w->fn),
13483 "try making the operator a %<const%> "
13484 "member function");
13485 }
13486 }
13487 }
13488 else
13489 add_warning (winner: w, loser: l);
13490 return winner;
13491 }
13492
13493 winner = 0;
13494 goto tweak;
13495 }
13496 winner = comp;
13497 }
13498 }
13499
13500 /* warn about confusing overload resolution for user-defined conversions,
13501 either between a constructor and a conversion op, or between two
13502 conversion ops. */
13503 if ((complain & tf_warning)
13504 /* In C++17, the constructor might have been elided, which means that
13505 an originally null ->second_conv could become non-null. */
13506 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
13507 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
13508 && winner != compare_ics (ics1: cand1->second_conv, ics2: cand2->second_conv))
13509 {
13510 struct z_candidate *w, *l;
13511 bool give_warning = false;
13512
13513 if (winner == 1)
13514 w = cand1, l = cand2;
13515 else
13516 w = cand2, l = cand1;
13517
13518 /* We don't want to complain about `X::operator T1 ()'
13519 beating `X::operator T2 () const', when T2 is a no less
13520 cv-qualified version of T1. */
13521 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
13522 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
13523 {
13524 tree t = TREE_TYPE (TREE_TYPE (l->fn));
13525 tree f = TREE_TYPE (TREE_TYPE (w->fn));
13526
13527 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
13528 {
13529 t = TREE_TYPE (t);
13530 f = TREE_TYPE (f);
13531 }
13532 if (!comp_ptr_ttypes (t, f))
13533 give_warning = true;
13534 }
13535 else
13536 give_warning = true;
13537
13538 if (!give_warning)
13539 /*NOP*/;
13540 else if (warn)
13541 {
13542 tree source = source_type (t: w->convs[0]);
13543 if (INDIRECT_TYPE_P (source))
13544 source = TREE_TYPE (source);
13545 auto_diagnostic_group d;
13546 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
13547 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
13548 source, w->second_conv->type))
13549 {
13550 inform (input_location, " because conversion sequence "
13551 "for the argument is better");
13552 }
13553 }
13554 else
13555 add_warning (winner: w, loser: l);
13556 }
13557
13558 if (winner)
13559 return winner;
13560
13561 /* DR 495 moved this tiebreaker above the template ones. */
13562 /* or, if not that,
13563 the context is an initialization by user-defined conversion (see
13564 _dcl.init_ and _over.match.user_) and the standard conversion
13565 sequence from the return type of F1 to the destination type (i.e.,
13566 the type of the entity being initialized) is a better conversion
13567 sequence than the standard conversion sequence from the return type
13568 of F2 to the destination type. */
13569
13570 if (cand1->second_conv)
13571 {
13572 winner = compare_ics (ics1: cand1->second_conv, ics2: cand2->second_conv);
13573 if (winner)
13574 return winner;
13575 }
13576
13577 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
13578 explicit conversion (due to list-initialization) is worse. */
13579 {
13580 z_candidate *sp = nullptr;
13581 if (sfk_copy_or_move (fn: cand1->fn))
13582 sp = cand1;
13583 if (sfk_copy_or_move (fn: cand2->fn))
13584 sp = sp ? nullptr : cand2;
13585 if (sp)
13586 {
13587 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
13588 if (conv->user_conv_p)
13589 for (; conv; conv = next_conversion (conv))
13590 if (conv->kind == ck_user
13591 && DECL_P (conv->cand->fn)
13592 && DECL_NONCONVERTING_P (conv->cand->fn))
13593 return (sp == cand1) ? -1 : 1;
13594 }
13595 }
13596
13597 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
13598 The standard currently says that only constructors are candidates, but if
13599 one copies a prvalue returned by a conversion function we prefer that.
13600
13601 Clang does something similar, as discussed at
13602 http://lists.isocpp.org/core/2017/10/3166.php
13603 http://lists.isocpp.org/core/2019/03/5721.php */
13604 if (len == 1 && cxx_dialect >= cxx17
13605 && DECL_P (cand1->fn)
13606 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
13607 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
13608 {
13609 bool elided1 = joust_maybe_elide_copy (cand: cand1);
13610 bool elided2 = joust_maybe_elide_copy (cand: cand2);
13611 winner = elided1 - elided2;
13612 if (winner)
13613 return winner;
13614 }
13615
13616 /* or, if not that,
13617 F1 is a non-template function and F2 is a template function
13618 specialization. */
13619
13620 if (!cand1->template_decl && cand2->template_decl)
13621 return 1;
13622 else if (cand1->template_decl && !cand2->template_decl)
13623 return -1;
13624
13625 /* or, if not that,
13626 F1 and F2 are template functions and the function template for F1 is
13627 more specialized than the template for F2 according to the partial
13628 ordering rules. */
13629
13630 if (cand1->template_decl && cand2->template_decl)
13631 {
13632 winner = more_specialized_fn
13633 (TI_TEMPLATE (cand1->template_decl),
13634 TI_TEMPLATE (cand2->template_decl),
13635 /* [temp.func.order]: The presence of unused ellipsis and default
13636 arguments has no effect on the partial ordering of function
13637 templates. add_function_candidate() will not have
13638 counted the "this" argument for constructors. */
13639 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
13640 if (winner)
13641 return winner;
13642 }
13643
13644 /* F1 and F2 are non-template functions and
13645 - they have the same non-object-parameter-type-lists ([dcl.fct]), and
13646 - if they are member functions, both are direct members of the same
13647 class, and
13648 - if both are non-static member functions, they have the same types for
13649 their object parameters, and
13650 - F1 is more constrained than F2 according to the partial ordering of
13651 constraints described in [temp.constr.order]. */
13652 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
13653 && !cand1->template_decl && !cand2->template_decl
13654 && cand_parms_match (c1: cand1, c2: cand2, match_kind: pmatch::current))
13655 {
13656 winner = more_constrained (cand1->fn, cand2->fn);
13657 if (winner)
13658 return winner;
13659 }
13660
13661 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
13662 rewritten candidates, and F2 is a synthesized candidate with reversed
13663 order of parameters and F1 is not. */
13664 if (cand1->rewritten ())
13665 {
13666 if (!cand2->rewritten ())
13667 return -1;
13668 if (!cand1->reversed () && cand2->reversed ())
13669 return 1;
13670 if (cand1->reversed () && !cand2->reversed ())
13671 return -1;
13672 }
13673 else if (cand2->rewritten ())
13674 return 1;
13675
13676 if (deduction_guide_p (cand1->fn))
13677 {
13678 gcc_assert (deduction_guide_p (cand2->fn));
13679
13680 /* F1 and F2 are generated from class template argument deduction for a
13681 class D, and F2 is generated from inheriting constructors from a base
13682 class of D while F1 is not, and for each explicit function argument,
13683 the corresponding parameters of F1 and F2 are either both ellipses or
13684 have the same type. */
13685 bool inherited1 = inherited_guide_p (cand1->fn);
13686 bool inherited2 = inherited_guide_p (cand2->fn);
13687 if (int diff = inherited2 - inherited1)
13688 {
13689 for (i = 0; i < len; ++i)
13690 {
13691 conversion *t1 = cand1->convs[i + off1];
13692 conversion *t2 = cand2->convs[i + off2];
13693 /* ??? It seems the ellipses part of this tiebreaker isn't
13694 needed since a mismatch should have broken the tie earlier
13695 during ICS comparison. */
13696 gcc_checking_assert (t1->ellipsis_p == t2->ellipsis_p);
13697 if (!same_type_p (t1->type, t2->type))
13698 break;
13699 }
13700 if (i == len)
13701 return diff;
13702 }
13703
13704 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
13705 /* We distinguish between candidates from an explicit deduction guide and
13706 candidates built from a constructor based on DECL_ARTIFICIAL. */
13707 int art1 = DECL_ARTIFICIAL (cand1->fn);
13708 int art2 = DECL_ARTIFICIAL (cand2->fn);
13709 if (art1 != art2)
13710 return art2 - art1;
13711
13712 if (art1)
13713 {
13714 /* Prefer the special copy guide over a declared copy/move
13715 constructor. */
13716 if (copy_guide_p (cand1->fn))
13717 return 1;
13718 if (copy_guide_p (cand2->fn))
13719 return -1;
13720
13721 /* Prefer a candidate generated from a non-template constructor. */
13722 int tg1 = template_guide_p (cand1->fn);
13723 int tg2 = template_guide_p (cand2->fn);
13724 if (tg1 != tg2)
13725 return tg2 - tg1;
13726 }
13727 }
13728
13729 /* F1 is a constructor for a class D, F2 is a constructor for a base class B
13730 of D, and for all arguments the corresponding parameters of F1 and F2 have
13731 the same type (CWG 2273/2277). */
13732 if (DECL_INHERITED_CTOR (cand1->fn) || DECL_INHERITED_CTOR (cand2->fn))
13733 {
13734 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13735 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13736
13737 bool used1 = false;
13738 bool used2 = false;
13739 if (base1 == base2)
13740 /* No difference. */;
13741 else if (DERIVED_FROM_P (base1, base2))
13742 used1 = true;
13743 else if (DERIVED_FROM_P (base2, base1))
13744 used2 = true;
13745
13746 if (int diff = used2 - used1)
13747 {
13748 for (i = 0; i < len; ++i)
13749 {
13750 conversion *t1 = cand1->convs[i + off1];
13751 conversion *t2 = cand2->convs[i + off2];
13752 if (!same_type_p (t1->type, t2->type))
13753 break;
13754 }
13755 if (i == len)
13756 return diff;
13757 }
13758 }
13759
13760 /* Check whether we can discard a builtin candidate, either because we
13761 have two identical ones or matching builtin and non-builtin candidates.
13762
13763 (Pedantically in the latter case the builtin which matched the user
13764 function should not be added to the overload set, but we spot it here.
13765
13766 [over.match.oper]
13767 ... the builtin candidates include ...
13768 - do not have the same parameter type list as any non-template
13769 non-member candidate. */
13770
13771 if (identifier_p (t: cand1->fn) || identifier_p (t: cand2->fn))
13772 {
13773 for (i = 0; i < len; ++i)
13774 if (!same_type_p (cand1->convs[i]->type,
13775 cand2->convs[i]->type))
13776 break;
13777 if (i == cand1->num_convs)
13778 {
13779 if (cand1->fn == cand2->fn)
13780 /* Two built-in candidates; arbitrarily pick one. */
13781 return 1;
13782 else if (identifier_p (t: cand1->fn))
13783 /* cand1 is built-in; prefer cand2. */
13784 return -1;
13785 else
13786 /* cand2 is built-in; prefer cand1. */
13787 return 1;
13788 }
13789 }
13790
13791 /* For candidates of a multi-versioned function, make the version with
13792 the highest priority win. This version will be checked for dispatching
13793 first. If this version can be inlined into the caller, the front-end
13794 will simply make a direct call to this function. */
13795
13796 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13797 && DECL_FUNCTION_VERSIONED (cand1->fn)
13798 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13799 && DECL_FUNCTION_VERSIONED (cand2->fn))
13800 {
13801 tree f1 = TREE_TYPE (cand1->fn);
13802 tree f2 = TREE_TYPE (cand2->fn);
13803 tree p1 = TYPE_ARG_TYPES (f1);
13804 tree p2 = TYPE_ARG_TYPES (f2);
13805
13806 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13807 is possible that cand1->fn and cand2->fn are function versions but of
13808 different functions. Check types to see if they are versions of the same
13809 function. */
13810 if (compparms (p1, p2)
13811 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13812 {
13813 /* Always make the version with the higher priority, more
13814 specialized, win. */
13815 gcc_assert (targetm.compare_version_priority);
13816 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13817 return 1;
13818 else
13819 return -1;
13820 }
13821 }
13822
13823 /* If the two function declarations represent the same function (this can
13824 happen with declarations in multiple scopes and arg-dependent lookup),
13825 arbitrarily choose one. But first make sure the default args we're
13826 using match. */
13827 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13828 && equal_functions (fn1: cand1->fn, fn2: cand2->fn))
13829 {
13830 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13831 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13832
13833 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13834
13835 for (i = 0; i < len; ++i)
13836 {
13837 /* Don't crash if the fn is variadic. */
13838 if (!parms1)
13839 break;
13840 parms1 = TREE_CHAIN (parms1);
13841 parms2 = TREE_CHAIN (parms2);
13842 }
13843
13844 if (off1)
13845 parms1 = TREE_CHAIN (parms1);
13846 else if (off2)
13847 parms2 = TREE_CHAIN (parms2);
13848
13849 for (; parms1; ++i)
13850 {
13851 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13852 TREE_PURPOSE (parms2)))
13853 {
13854 if (warn)
13855 {
13856 if (complain & tf_error)
13857 {
13858 auto_diagnostic_group d;
13859 if (permerror (input_location,
13860 "default argument mismatch in "
13861 "overload resolution"))
13862 {
13863 inform (DECL_SOURCE_LOCATION (cand1->fn),
13864 " candidate 1: %q#F", cand1->fn);
13865 inform (DECL_SOURCE_LOCATION (cand2->fn),
13866 " candidate 2: %q#F", cand2->fn);
13867 }
13868 }
13869 else
13870 return 0;
13871 }
13872 else
13873 add_warning (winner: cand1, loser: cand2);
13874 break;
13875 }
13876 parms1 = TREE_CHAIN (parms1);
13877 parms2 = TREE_CHAIN (parms2);
13878 }
13879
13880 return 1;
13881 }
13882
13883tweak:
13884
13885 /* Extension: If the worst conversion for one candidate is better than the
13886 worst conversion for the other, take the first. */
13887 if (!pedantic && (complain & tf_warning_or_error))
13888 {
13889 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13890 struct z_candidate *w = 0, *l = 0;
13891
13892 for (i = 0; i < len; ++i)
13893 {
13894 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13895 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13896 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13897 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13898 }
13899 if (rank1 < rank2)
13900 winner = 1, w = cand1, l = cand2;
13901 if (rank1 > rank2)
13902 winner = -1, w = cand2, l = cand1;
13903 if (winner)
13904 {
13905 /* Don't choose a deleted function over ambiguity. */
13906 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13907 return 0;
13908 if (warn)
13909 {
13910 auto_diagnostic_group d;
13911 if (pedwarn (input_location, 0,
13912 "ISO C++ says that these are ambiguous, even "
13913 "though the worst conversion for the first is "
13914 "better than the worst conversion for the second:"))
13915 {
13916 print_z_candidate (loc: input_location, N_("candidate 1:"), candidate: w);
13917 print_z_candidate (loc: input_location, N_("candidate 2:"), candidate: l);
13918 }
13919 }
13920 else
13921 add_warning (winner: w, loser: l);
13922 return winner;
13923 }
13924 }
13925
13926 gcc_assert (!winner);
13927 return 0;
13928}
13929
13930/* Given a list of candidates for overloading, find the best one, if any.
13931 This algorithm has a worst case of O(2n) (winner is last), and a best
13932 case of O(n/2) (totally ambiguous); much better than a sorting
13933 algorithm. The candidates list is assumed to be sorted according
13934 to viability (via splice_viable). */
13935
13936static struct z_candidate *
13937tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13938{
13939 struct z_candidate **champ = &candidates, **challenger;
13940 int fate;
13941 struct z_candidate *previous_worse_champ = nullptr;
13942
13943 /* Walk through the list once, comparing each current champ to the next
13944 candidate, knocking out a candidate or two with each comparison. */
13945
13946 for (challenger = &candidates->next; *challenger && (*challenger)->viable; )
13947 {
13948 fate = joust (cand1: *champ, cand2: *challenger, warn: 0, complain);
13949 if (fate == 1)
13950 challenger = &(*challenger)->next;
13951 else if (fate == -1)
13952 {
13953 previous_worse_champ = *champ;
13954 champ = challenger;
13955 challenger = &(*challenger)->next;
13956 }
13957 else
13958 {
13959 previous_worse_champ = nullptr;
13960 champ = &(*challenger)->next;
13961 if (!*champ || !(*champ)->viable
13962 || (*champ)->viable < (*challenger)->viable)
13963 {
13964 champ = nullptr;
13965 break;
13966 }
13967 challenger = &(*champ)->next;
13968 }
13969 }
13970
13971 /* Make sure the champ is better than all the candidates it hasn't yet
13972 been compared to. */
13973
13974 if (champ)
13975 for (challenger = &candidates;
13976 challenger != champ;
13977 challenger = &(*challenger)->next)
13978 {
13979 if (*challenger == previous_worse_champ)
13980 /* We already know this candidate is worse than the champ. */
13981 continue;
13982 fate = joust (cand1: *champ, cand2: *challenger, warn: 0, complain);
13983 if (fate != 1)
13984 {
13985 champ = nullptr;
13986 break;
13987 }
13988 }
13989
13990 if (!champ)
13991 return nullptr;
13992
13993 /* Move the champ to the front of the candidate list. */
13994
13995 if (champ != &candidates)
13996 {
13997 z_candidate *saved_champ = *champ;
13998 *champ = saved_champ->next;
13999 saved_champ->next = candidates;
14000 candidates = saved_champ;
14001 }
14002
14003 return candidates;
14004}
14005
14006/* Returns nonzero if things of type FROM can be converted to TO. */
14007
14008bool
14009can_convert (tree to, tree from, tsubst_flags_t complain)
14010{
14011 tree arg = NULL_TREE;
14012 /* implicit_conversion only considers user-defined conversions
14013 if it has an expression for the call argument list. */
14014 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
14015 arg = build_stub_object (from);
14016 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
14017}
14018
14019/* Returns nonzero if things of type FROM can be converted to TO with a
14020 standard conversion. */
14021
14022bool
14023can_convert_standard (tree to, tree from, tsubst_flags_t complain)
14024{
14025 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
14026}
14027
14028/* Returns nonzero if ARG (of type FROM) can be converted to TO. */
14029
14030bool
14031can_convert_arg (tree to, tree from, tree arg, int flags,
14032 tsubst_flags_t complain)
14033{
14034 conversion *t;
14035 bool ok_p;
14036
14037 conversion_obstack_sentinel cos;
14038 /* We want to discard any access checks done for this test,
14039 as we might not be in the appropriate access context and
14040 we'll do the check again when we actually perform the
14041 conversion. */
14042 push_deferring_access_checks (dk_deferred);
14043
14044 /* Handle callers like check_local_shadow forgetting to
14045 convert_from_reference. */
14046 if (TYPE_REF_P (from) && arg)
14047 {
14048 arg = convert_from_reference (arg);
14049 from = TREE_TYPE (arg);
14050 }
14051
14052 t = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
14053 flags, complain);
14054 ok_p = (t && !t->bad_p);
14055
14056 /* Discard the access checks now. */
14057 pop_deferring_access_checks ();
14058
14059 return ok_p;
14060}
14061
14062/* Like can_convert_arg, but allows dubious conversions as well. */
14063
14064bool
14065can_convert_arg_bad (tree to, tree from, tree arg, int flags,
14066 tsubst_flags_t complain)
14067{
14068 conversion *t;
14069
14070 conversion_obstack_sentinel cos;
14071 /* Try to perform the conversion. */
14072 t = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
14073 flags, complain);
14074
14075 return t != NULL;
14076}
14077
14078/* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
14079 resolution FLAGS. */
14080
14081tree
14082build_implicit_conv_flags (tree type, tree expr, int flags)
14083{
14084 /* In a template, we are only concerned about determining the
14085 type of non-dependent expressions, so we do not have to
14086 perform the actual conversion. But for initializers, we
14087 need to be able to perform it at instantiation
14088 (or instantiate_non_dependent_expr) time. */
14089 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
14090 if (!(flags & LOOKUP_ONLYCONVERTING))
14091 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
14092 if (flags & LOOKUP_NO_NARROWING)
14093 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
14094 return expr;
14095}
14096
14097/* Convert EXPR to TYPE. Return the converted expression.
14098
14099 Note that we allow bad conversions here because by the time we get to
14100 this point we are committed to doing the conversion. If we end up
14101 doing a bad conversion, convert_like will complain. */
14102
14103tree
14104perform_implicit_conversion_flags (tree type, tree expr,
14105 tsubst_flags_t complain, int flags)
14106{
14107 conversion *conv;
14108 location_t loc = cp_expr_loc_or_input_loc (t: expr);
14109
14110 if (error_operand_p (t: expr))
14111 return error_mark_node;
14112
14113 conversion_obstack_sentinel cos;
14114
14115 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
14116 /*c_cast_p=*/false,
14117 flags, complain);
14118
14119 if (!conv)
14120 {
14121 if (complain & tf_error)
14122 implicit_conversion_error (loc, type, expr, flags);
14123 expr = error_mark_node;
14124 }
14125 else if (processing_template_decl && conv->kind != ck_identity)
14126 expr = build_implicit_conv_flags (type, expr, flags);
14127 else
14128 {
14129 /* Give a conversion call the same location as expr. */
14130 iloc_sentinel il (loc);
14131 expr = convert_like (convs: conv, expr, complain);
14132 }
14133
14134 return expr;
14135}
14136
14137tree
14138perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
14139{
14140 return perform_implicit_conversion_flags (type, expr, complain,
14141 LOOKUP_IMPLICIT);
14142}
14143
14144/* Convert EXPR to TYPE (as a direct-initialization) if that is
14145 permitted. If the conversion is valid, the converted expression is
14146 returned. Otherwise, NULL_TREE is returned, except in the case
14147 that TYPE is a class type; in that case, an error is issued. If
14148 C_CAST_P is true, then this direct-initialization is taking
14149 place as part of a static_cast being attempted as part of a C-style
14150 cast. */
14151
14152tree
14153perform_direct_initialization_if_possible (tree type,
14154 tree expr,
14155 bool c_cast_p,
14156 tsubst_flags_t complain)
14157{
14158 conversion *conv;
14159
14160 if (type == error_mark_node || error_operand_p (t: expr))
14161 return error_mark_node;
14162 /* [dcl.init]
14163
14164 If the destination type is a (possibly cv-qualified) class type:
14165
14166 -- If the initialization is direct-initialization ...,
14167 constructors are considered.
14168
14169 -- If overload resolution is successful, the selected constructor
14170 is called to initialize the object, with the initializer expression
14171 or expression-list as its argument(s).
14172
14173 -- Otherwise, if no constructor is viable, the destination type is
14174 a (possibly cv-qualified) aggregate class A, and the initializer is
14175 a parenthesized expression-list, the object is initialized as
14176 follows... */
14177 if (CLASS_TYPE_P (type))
14178 {
14179 releasing_vec args (make_tree_vector_single (expr));
14180 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
14181 args: &args, binfo: type, LOOKUP_NORMAL, complain);
14182 return build_cplus_new (type, expr, complain);
14183 }
14184
14185 conversion_obstack_sentinel cos;
14186
14187 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
14188 c_cast_p,
14189 LOOKUP_NORMAL, complain);
14190 if (!conv || conv->bad_p)
14191 expr = NULL_TREE;
14192 else if (processing_template_decl && conv->kind != ck_identity)
14193 {
14194 /* In a template, we are only concerned about determining the
14195 type of non-dependent expressions, so we do not have to
14196 perform the actual conversion. But for initializers, we
14197 need to be able to perform it at instantiation
14198 (or instantiate_non_dependent_expr) time. */
14199 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
14200 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
14201 }
14202 else
14203 expr = convert_like (convs: conv, expr, NULL_TREE, argnum: 0,
14204 /*issue_conversion_warnings=*/false,
14205 c_cast_p, /*nested_p=*/false, complain);
14206
14207 return expr;
14208}
14209
14210/* When initializing a reference that lasts longer than a full-expression,
14211 this special rule applies:
14212
14213 [class.temporary]
14214
14215 The temporary to which the reference is bound or the temporary
14216 that is the complete object to which the reference is bound
14217 persists for the lifetime of the reference.
14218
14219 The temporaries created during the evaluation of the expression
14220 initializing the reference, except the temporary to which the
14221 reference is bound, are destroyed at the end of the
14222 full-expression in which they are created.
14223
14224 In that case, we store the converted expression into a new
14225 VAR_DECL in a new scope.
14226
14227 However, we want to be careful not to create temporaries when
14228 they are not required. For example, given:
14229
14230 struct B {};
14231 struct D : public B {};
14232 D f();
14233 const B& b = f();
14234
14235 there is no need to copy the return value from "f"; we can just
14236 extend its lifetime. Similarly, given:
14237
14238 struct S {};
14239 struct T { operator S(); };
14240 T t;
14241 const S& s = t;
14242
14243 we can extend the lifetime of the return value of the conversion
14244 operator.
14245
14246 The next several functions are involved in this lifetime extension. */
14247
14248/* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
14249 reference is being bound to a temporary. Create and return a new
14250 VAR_DECL with the indicated TYPE; this variable will store the value to
14251 which the reference is bound. */
14252
14253tree
14254make_temporary_var_for_ref_to_temp (tree decl, tree type)
14255{
14256 tree var = create_temporary_var (type);
14257
14258 /* Register the variable. */
14259 if (VAR_P (decl)
14260 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
14261 {
14262 /* Namespace-scope or local static; give it a mangled name. */
14263
14264 /* If an initializer is visible to multiple translation units, those
14265 translation units must agree on the addresses of the
14266 temporaries. Therefore the temporaries must be given a consistent name
14267 and vague linkage. The mangled name of a temporary is the name of the
14268 non-temporary object in whose initializer they appear, prefixed with
14269 GR and suffixed with a sequence number mangled using the usual rules
14270 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
14271 left-to-right walk of the complete initializer. */
14272 copy_linkage (var, decl);
14273
14274 tree name = mangle_ref_init_variable (decl);
14275 DECL_NAME (var) = name;
14276 SET_DECL_ASSEMBLER_NAME (var, name);
14277
14278 /* Set the context to make the variable mergeable in modules. */
14279 DECL_CONTEXT (var) = current_scope ();
14280 }
14281 else
14282 /* Create a new cleanup level if necessary. */
14283 maybe_push_cleanup_level (type);
14284
14285 return pushdecl (var);
14286}
14287
14288static tree extend_temps_r (tree *, int *, void *);
14289
14290/* EXPR is the initializer for a variable DECL of reference or
14291 std::initializer_list type. Create, push and return a new VAR_DECL
14292 for the initializer so that it will live as long as DECL. Any
14293 cleanup for the new variable is returned through CLEANUP, and the
14294 code to initialize the new variable is returned through INITP. */
14295
14296static tree
14297set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
14298 tree *initp, tree *cond_guard,
14299 void *walk_data)
14300{
14301 tree init;
14302 tree type;
14303 tree var;
14304
14305 /* Create the temporary variable. */
14306 type = TREE_TYPE (expr);
14307 var = make_temporary_var_for_ref_to_temp (decl, type);
14308 layout_decl (var, 0);
14309 /* If the rvalue is the result of a function call it will be
14310 a TARGET_EXPR. If it is some other construct (such as a
14311 member access expression where the underlying object is
14312 itself the result of a function call), turn it into a
14313 TARGET_EXPR here. It is important that EXPR be a
14314 TARGET_EXPR below since otherwise the INIT_EXPR will
14315 attempt to make a bitwise copy of EXPR to initialize
14316 VAR. */
14317 if (TREE_CODE (expr) != TARGET_EXPR)
14318 expr = get_target_expr (expr);
14319 else
14320 {
14321 if (TREE_ADDRESSABLE (expr))
14322 TREE_ADDRESSABLE (var) = 1;
14323 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
14324 DECL_MERGEABLE (var) = true;
14325 }
14326
14327 if (TREE_CODE (decl) == FIELD_DECL
14328 && extra_warnings && !warning_suppressed_p (decl))
14329 {
14330 warning (OPT_Wextra, "a temporary bound to %qD only persists "
14331 "until the constructor exits", decl);
14332 suppress_warning (decl);
14333 }
14334
14335 /* Recursively extend temps in this initializer. The recursion needs to come
14336 after creating the variable to conform to the mangling ABI, and before
14337 maybe_constant_init because the extension might change its result. */
14338 if (walk_data)
14339 cp_walk_tree (&TARGET_EXPR_INITIAL (expr), extend_temps_r,
14340 walk_data, nullptr);
14341 else
14342 TARGET_EXPR_INITIAL (expr)
14343 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
14344 cond_guard);
14345
14346 /* Any reference temp has a non-trivial initializer. */
14347 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
14348
14349 /* If the initializer is constant, put it in DECL_INITIAL so we get
14350 static initialization and use in constant expressions. */
14351 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
14352 /* As in store_init_value. */
14353 init = cp_fully_fold (init);
14354 if (TREE_CONSTANT (init))
14355 {
14356 if (literal_type_p (type)
14357 && CP_TYPE_CONST_NON_VOLATILE_P (type)
14358 && !TYPE_HAS_MUTABLE_P (type))
14359 {
14360 /* 5.19 says that a constant expression can include an
14361 lvalue-rvalue conversion applied to "a glvalue of literal type
14362 that refers to a non-volatile temporary object initialized
14363 with a constant expression". Rather than try to communicate
14364 that this VAR_DECL is a temporary, just mark it constexpr. */
14365 DECL_DECLARED_CONSTEXPR_P (var) = true;
14366 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
14367 TREE_CONSTANT (var) = true;
14368 TREE_READONLY (var) = true;
14369 }
14370 DECL_INITIAL (var) = init;
14371 init = NULL_TREE;
14372 }
14373 else
14374 /* Create the INIT_EXPR that will initialize the temporary
14375 variable. */
14376 init = split_nonconstant_init (var, expr);
14377 if (at_function_scope_p ())
14378 {
14379 add_decl_expr (var);
14380
14381 if (TREE_STATIC (var))
14382 init = add_stmt_to_compound (init, register_dtor_fn (var));
14383 else
14384 {
14385 /* ??? Instead of rebuilding the cleanup, we could replace the slot
14386 with var in TARGET_EXPR_CLEANUP (expr). */
14387 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
14388 if (cleanup)
14389 {
14390 if (cond_guard && cleanup != error_mark_node)
14391 {
14392 if (*cond_guard == NULL_TREE)
14393 {
14394 *cond_guard = build_local_temp (boolean_type_node);
14395 add_decl_expr (*cond_guard);
14396 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
14397 *cond_guard, NOP_EXPR,
14398 boolean_false_node,
14399 tf_warning_or_error);
14400 finish_expr_stmt (set);
14401 }
14402 cleanup = build3 (COND_EXPR, void_type_node,
14403 *cond_guard, cleanup, NULL_TREE);
14404 }
14405 if (flag_exceptions && TREE_CODE (TREE_TYPE (var)) != ARRAY_TYPE)
14406 {
14407 /* The normal cleanup for this extended variable isn't pushed
14408 until cp_finish_decl, so we need to retain a TARGET_EXPR
14409 to clean it up in case a later initializer throws
14410 (g++.dg/eh/ref-temp3.C).
14411
14412 We don't do this for array temporaries because they have
14413 the array cleanup region from build_vec_init.
14414
14415 Unlike maybe_push_temp_cleanup, we don't actually need a
14416 flag, but a TARGET_EXPR needs a TARGET_EXPR_SLOT.
14417 Perhaps this could use WITH_CLEANUP_EXPR instead, but
14418 gimplify.cc doesn't handle that, and front-end handling
14419 was removed in r8-1725 and r8-1818.
14420
14421 Alternately it might be preferable to flatten an
14422 initialization with extended temps into a sequence of
14423 (non-full-expression) statements, so we could immediately
14424 push_cleanup here for only a single cleanup region, but we
14425 don't have a mechanism for that in the front-end, only the
14426 gimplifier. */
14427 tree targ = get_internal_target_expr (boolean_true_node);
14428 TARGET_EXPR_CLEANUP (targ) = cleanup;
14429 CLEANUP_EH_ONLY (targ) = true;
14430 /* Don't actually initialize the bool. */
14431 init = (!init ? void_node
14432 : convert_to_void (init, ICV_STATEMENT, tf_none));
14433 TARGET_EXPR_INITIAL (targ) = init;
14434 init = targ;
14435 }
14436 vec_safe_push (v&: *cleanups, obj: cleanup);
14437 }
14438 }
14439
14440 /* We must be careful to destroy the temporary only
14441 after its initialization has taken place. If the
14442 initialization throws an exception, then the
14443 destructor should not be run. We cannot simply
14444 transform INIT into something like:
14445
14446 (INIT, ({ CLEANUP_STMT; }))
14447
14448 because emit_local_var always treats the
14449 initializer as a full-expression. Thus, the
14450 destructor would run too early; it would run at the
14451 end of initializing the reference variable, rather
14452 than at the end of the block enclosing the
14453 reference variable.
14454
14455 The solution is to pass back a cleanup expression
14456 which the caller is responsible for attaching to
14457 the statement tree. */
14458 }
14459 else
14460 {
14461 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
14462 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
14463 {
14464 if (CP_DECL_THREAD_LOCAL_P (var))
14465 tls_aggregates = tree_cons (NULL_TREE, var,
14466 tls_aggregates);
14467 else
14468 static_aggregates = tree_cons (NULL_TREE, var,
14469 static_aggregates);
14470 }
14471 else
14472 /* Check whether the dtor is callable. */
14473 cxx_maybe_build_cleanup (var, tf_warning_or_error);
14474 }
14475 /* Avoid -Wunused-variable warning (c++/38958). */
14476 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
14477 && VAR_P (decl))
14478 TREE_USED (decl) = DECL_READ_P (decl) = true;
14479
14480 *initp = init;
14481 return var;
14482}
14483
14484/* Convert EXPR to the indicated reference TYPE, in a way suitable for
14485 initializing a variable of that TYPE. */
14486
14487tree
14488initialize_reference (tree type, tree expr,
14489 int flags, tsubst_flags_t complain)
14490{
14491 conversion *conv;
14492 location_t loc = cp_expr_loc_or_input_loc (t: expr);
14493
14494 if (type == error_mark_node || error_operand_p (t: expr))
14495 return error_mark_node;
14496
14497 conversion_obstack_sentinel cos;
14498
14499 conv = reference_binding (rto: type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
14500 flags, complain);
14501 /* If this conversion failed, we're in C++20, and we have something like
14502 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
14503 if ((!conv || conv->bad_p)
14504 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
14505 {
14506 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
14507 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
14508 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
14509 conversion *c = reference_binding (rto: type, TREE_TYPE (e), expr: e,
14510 /*c_cast_p=*/false, flags, complain);
14511 /* If this worked, use it. */
14512 if (c && !c->bad_p)
14513 expr = e, conv = c;
14514 }
14515 if (!conv || conv->bad_p)
14516 {
14517 if (complain & tf_error)
14518 {
14519 if (conv)
14520 convert_like (convs: conv, expr, complain);
14521 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
14522 && !TYPE_REF_IS_RVALUE (type)
14523 && !lvalue_p (expr))
14524 error_at (loc, "invalid initialization of non-const reference of "
14525 "type %qH from an rvalue of type %qI",
14526 type, TREE_TYPE (expr));
14527 else
14528 error_at (loc, "invalid initialization of reference of type "
14529 "%qH from expression of type %qI", type,
14530 TREE_TYPE (expr));
14531 }
14532 return error_mark_node;
14533 }
14534
14535 if (conv->kind == ck_ref_bind)
14536 /* Perform the conversion. */
14537 expr = convert_like (convs: conv, expr, complain);
14538 else if (conv->kind == ck_ambig)
14539 /* We gave an error in build_user_type_conversion_1. */
14540 expr = error_mark_node;
14541 else
14542 gcc_unreachable ();
14543
14544 return expr;
14545}
14546
14547/* Return true if T is std::pair<const T&, const T&>. */
14548
14549static bool
14550std_pair_ref_ref_p (tree t)
14551{
14552 /* First, check if we have std::pair. */
14553 if (!NON_UNION_CLASS_TYPE_P (t)
14554 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
14555 return false;
14556 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
14557 if (!decl_in_std_namespace_p (tdecl))
14558 return false;
14559 tree name = DECL_NAME (tdecl);
14560 if (!name || !id_equal (id: name, str: "pair"))
14561 return false;
14562
14563 /* Now see if the template arguments are both const T&. */
14564 tree args = CLASSTYPE_TI_ARGS (t);
14565 if (TREE_VEC_LENGTH (args) != 2)
14566 return false;
14567 for (int i = 0; i < 2; i++)
14568 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
14569 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
14570 return false;
14571
14572 return true;
14573}
14574
14575/* Return true if a class T has a reference member. */
14576
14577static bool
14578class_has_reference_member_p (tree t)
14579{
14580 for (tree fields = TYPE_FIELDS (t);
14581 fields;
14582 fields = DECL_CHAIN (fields))
14583 if (TREE_CODE (fields) == FIELD_DECL
14584 && !DECL_ARTIFICIAL (fields)
14585 && TYPE_REF_P (TREE_TYPE (fields)))
14586 return true;
14587 return false;
14588}
14589
14590/* A wrapper for the above suitable as a callback for dfs_walk_once. */
14591
14592static tree
14593class_has_reference_member_p_r (tree binfo, void *)
14594{
14595 return (class_has_reference_member_p (BINFO_TYPE (binfo))
14596 ? integer_one_node : NULL_TREE);
14597}
14598
14599
14600/* Return true if T (either a class or a function) has been marked as
14601 not-dangling. */
14602
14603static bool
14604no_dangling_p (tree t)
14605{
14606 t = lookup_attribute (attr_name: "no_dangling", TYPE_ATTRIBUTES (t));
14607 if (!t)
14608 return false;
14609
14610 t = TREE_VALUE (t);
14611 if (!t)
14612 return true;
14613
14614 t = build_converted_constant_bool_expr (TREE_VALUE (t), complain: tf_warning_or_error);
14615 t = cxx_constant_value (t);
14616 return t == boolean_true_node;
14617}
14618
14619/* Return true if a class CTYPE is either std::reference_wrapper or
14620 std::ref_view, or a reference wrapper class. We consider a class
14621 a reference wrapper class if it has a reference member. We no
14622 longer check that it has a constructor taking the same reference type
14623 since that approach still generated too many false positives. */
14624
14625static bool
14626reference_like_class_p (tree ctype)
14627{
14628 if (!CLASS_TYPE_P (ctype))
14629 return false;
14630
14631 if (no_dangling_p (t: ctype))
14632 return true;
14633
14634 /* Also accept a std::pair<const T&, const T&>. */
14635 if (std_pair_ref_ref_p (t: ctype))
14636 return true;
14637
14638 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
14639 if (decl_in_std_namespace_p (tdecl))
14640 {
14641 tree name = DECL_NAME (tdecl);
14642 if (name
14643 && (id_equal (id: name, str: "reference_wrapper")
14644 || id_equal (id: name, str: "span")
14645 || id_equal (id: name, str: "ref_view")))
14646 return true;
14647 }
14648
14649 /* Avoid warning if CTYPE looks like std::span: it has a T* member and
14650 a trivial destructor. For example,
14651
14652 template<typename T>
14653 struct Span {
14654 T* data_;
14655 std::size len_;
14656 };
14657
14658 is considered std::span-like. */
14659 if (NON_UNION_CLASS_TYPE_P (ctype) && TYPE_HAS_TRIVIAL_DESTRUCTOR (ctype))
14660 for (tree field = next_aggregate_field (TYPE_FIELDS (ctype));
14661 field; field = next_aggregate_field (DECL_CHAIN (field)))
14662 if (TYPE_PTR_P (TREE_TYPE (field)))
14663 return true;
14664
14665 /* Some classes, such as std::tuple, have the reference member in its
14666 (non-direct) base class. */
14667 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
14668 nullptr, nullptr))
14669 return true;
14670
14671 return false;
14672}
14673
14674/* Helper for maybe_warn_dangling_reference to find a problematic temporary
14675 in EXPR (as outlined in maybe_warn_dangling_reference), or NULL_TREE
14676 if none found. For instance:
14677
14678 const S& s = S().self(); // S()
14679 const int& r = (42, f(1)); // temporary for passing 1 to f
14680 const int& t = b ? f(1) : f(2); // temporary for 1
14681 const int& u = b ? f(1) : f(g); // temporary for 1
14682 const int& v = b ? f(g) : f(2); // temporary for 2
14683 const int& w = b ? f(g) : f(g); // NULL_TREE
14684 const int& y = (f(1), 42); // NULL_TREE
14685 const int& z = f(f(1)); // temporary for 1
14686
14687 EXPR is the initializer. If ARG_P is true, we're processing an argument
14688 to a function; the point is to distinguish between, for example,
14689
14690 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
14691
14692 where we shouldn't warn, and
14693
14694 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
14695
14696 where we should warn (Ref is a reference_like_class_p so we see through
14697 it. */
14698
14699static tree
14700do_warn_dangling_reference (tree expr, bool arg_p)
14701{
14702 STRIP_NOPS (expr);
14703
14704 if (arg_p && expr_represents_temporary_p (expr))
14705 {
14706 /* An attempt to reduce the number of -Wdangling-reference
14707 false positives concerning reference wrappers (c++/107532).
14708 When we encounter a reference_like_class_p, we don't warn
14709 just yet; instead, we keep recursing to see if there were
14710 any temporaries behind the reference-wrapper class. */
14711 tree e = expr;
14712 while (handled_component_p (t: e))
14713 e = TREE_OPERAND (e, 0);
14714 tree type = TREE_TYPE (e);
14715 /* If the temporary represents a lambda, we don't really know
14716 what's going on here. */
14717 if (!reference_like_class_p (ctype: type) && !LAMBDA_TYPE_P (type))
14718 return expr;
14719 }
14720
14721 switch (TREE_CODE (expr))
14722 {
14723 case CALL_EXPR:
14724 {
14725 tree fndecl = cp_get_callee_fndecl_nofold (expr);
14726 if (!fndecl
14727 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
14728 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
14729 opt_id: OPT_Wdangling_reference)
14730 /* Don't emit a false positive for:
14731 std::vector<int> v = ...;
14732 std::vector<int>::const_iterator it = v.begin();
14733 const int &r = *it++;
14734 because R refers to one of the int elements of V, not to
14735 a temporary object. Member operator* may return a reference
14736 but probably not to one of its arguments. */
14737 || (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
14738 && DECL_OVERLOADED_OPERATOR_P (fndecl)
14739 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF))
14740 || no_dangling_p (TREE_TYPE (fndecl)))
14741 return NULL_TREE;
14742
14743 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
14744 /* If the function doesn't return a reference, don't warn. This
14745 can be e.g.
14746 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
14747 which doesn't dangle: std::min here returns an int.
14748
14749 If the function returns a std::pair<const T&, const T&>, we
14750 warn, to detect e.g.
14751 std::pair<const int&, const int&> v = std::minmax(1, 2);
14752 which also creates a dangling reference, because std::minmax
14753 returns std::pair<const T&, const T&>(b, a). */
14754 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (ctype: rettype)))
14755 return NULL_TREE;
14756
14757 /* Here we're looking to see if any of the arguments is a temporary
14758 initializing a reference parameter. */
14759 for (int i = 0; i < call_expr_nargs (expr); ++i)
14760 {
14761 tree arg = CALL_EXPR_ARG (expr, i);
14762 /* Check that this argument initializes a reference, except for
14763 the argument initializing the object of a member function. */
14764 if (!DECL_IOBJ_MEMBER_FUNCTION_P (fndecl)
14765 && !TYPE_REF_P (TREE_TYPE (arg)))
14766 continue;
14767 STRIP_NOPS (arg);
14768 if (TREE_CODE (arg) == ADDR_EXPR)
14769 arg = TREE_OPERAND (arg, 0);
14770 /* Recurse to see if the argument is a temporary. It could also
14771 be another call taking a temporary and returning it and
14772 initializing this reference parameter. */
14773 if ((arg = do_warn_dangling_reference (expr: arg, /*arg_p=*/true)))
14774 {
14775 /* If we know the temporary could not bind to the return type,
14776 don't warn. This is for scalars and empty classes only
14777 because for other classes we can't be sure we are not
14778 returning its sub-object. */
14779 if ((SCALAR_TYPE_P (TREE_TYPE (arg))
14780 || is_empty_class (TREE_TYPE (arg)))
14781 && TYPE_REF_P (rettype)
14782 && !reference_related_p (TREE_TYPE (rettype),
14783 TREE_TYPE (arg)))
14784 continue;
14785 return arg;
14786 }
14787 /* Don't warn about member functions like:
14788 std::any a(...);
14789 S& s = a.emplace<S>({0}, 0);
14790 which construct a new object and return a reference to it, but
14791 we still want to detect:
14792 struct S { const S& self () { return *this; } };
14793 const S& s = S().self();
14794 where 's' dangles. If we've gotten here, the object this function
14795 is invoked on is not a temporary. */
14796 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl))
14797 break;
14798 }
14799 return NULL_TREE;
14800 }
14801 case COMPOUND_EXPR:
14802 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
14803 case COND_EXPR:
14804 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
14805 return t;
14806 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
14807 case PAREN_EXPR:
14808 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
14809 case TARGET_EXPR:
14810 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
14811 default:
14812 return NULL_TREE;
14813 }
14814}
14815
14816/* Implement -Wdangling-reference, to detect cases like
14817
14818 int n = 1;
14819 const int& r = std::max(n - 1, n + 1); // r is dangling
14820
14821 This creates temporaries from the arguments, returns a reference to
14822 one of the temporaries, but both temporaries are destroyed at the end
14823 of the full expression.
14824
14825 This works by checking if a reference is initialized with a function
14826 that returns a reference, and at least one parameter of the function
14827 is a reference that is bound to a temporary. It assumes that such a
14828 function actually returns one of its arguments.
14829
14830 DECL is the reference being initialized, INIT is the initializer. */
14831
14832static void
14833maybe_warn_dangling_reference (const_tree decl, tree init)
14834{
14835 if (!warn_dangling_reference)
14836 return;
14837 tree type = TREE_TYPE (decl);
14838 /* Only warn if what we're initializing has type T&& or const T&, or
14839 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14840 bind to a temporary.) */
14841 if (!((TYPE_REF_OBJ_P (type)
14842 && (TYPE_REF_IS_RVALUE (type)
14843 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14844 || std_pair_ref_ref_p (t: type)))
14845 return;
14846 /* Don't suppress the diagnostic just because the call comes from
14847 a system header. If the DECL is not in a system header, or if
14848 -Wsystem-headers was provided, warn. */
14849 auto wsh
14850 = make_temp_override (var&: global_dc->m_warn_system_headers,
14851 overrider: (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14852 || global_dc->m_warn_system_headers));
14853 if (tree call = do_warn_dangling_reference (expr: init, /*arg_p=*/false))
14854 {
14855 auto_diagnostic_group d;
14856 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14857 "possibly dangling reference to a temporary"))
14858 inform (EXPR_LOCATION (call), "%qT temporary created here",
14859 TREE_TYPE (call));
14860 }
14861}
14862
14863/* If *P is an xvalue expression, prevent temporary lifetime extension if it
14864 gets used to initialize a reference. */
14865
14866static tree
14867prevent_lifetime_extension (tree t)
14868{
14869 tree *p = &t;
14870 while (TREE_CODE (*p) == COMPOUND_EXPR)
14871 p = &TREE_OPERAND (*p, 1);
14872 while (handled_component_p (t: *p))
14873 p = &TREE_OPERAND (*p, 0);
14874 /* Change a TARGET_EXPR from prvalue to xvalue. */
14875 if (TREE_CODE (*p) == TARGET_EXPR)
14876 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14877 move (TARGET_EXPR_SLOT (*p)));
14878 return t;
14879}
14880
14881/* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14882 which is bound either to a reference or a std::initializer_list. */
14883
14884static tree
14885extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14886 tree *cond_guard)
14887{
14888 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14889 the temporary object that is the complete object of a subobject to which
14890 the reference is bound persists for the lifetime of the reference if the
14891 glvalue to which the reference is bound was obtained through one of the
14892 following:
14893 - a temporary materialization conversion ([conv.rval]),
14894 - ( expression ), where expression is one of these expressions,
14895 - subscripting ([expr.sub]) of an array operand, where that operand is one
14896 of these expressions,
14897 - a class member access ([expr.ref]) using the . operator where the left
14898 operand is one of these expressions and the right operand designates a
14899 non-static data member of non-reference type,
14900 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14901 where the left operand is one of these expressions and the right operand
14902 is a pointer to data member of non-reference type,
14903 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14904 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14905 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14906 a glvalue operand that is one of these expressions to a glvalue that
14907 refers to the object designated by the operand, or to its complete
14908 object or a subobject thereof,
14909 - a conditional expression ([expr.cond]) that is a glvalue where the
14910 second or third operand is one of these expressions, or
14911 - a comma expression ([expr.comma]) that is a glvalue where the right
14912 operand is one of these expressions. */
14913
14914 /* FIXME several cases are still handled wrong (101572, 81420). */
14915
14916 tree sub = init;
14917 tree *p;
14918 STRIP_NOPS (sub);
14919 if (TREE_CODE (sub) == COMPOUND_EXPR)
14920 {
14921 TREE_OPERAND (sub, 1)
14922 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14923 cond_guard);
14924 return init;
14925 }
14926 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14927 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14928 (TREE_OPERAND (sub, 1)))))
14929 {
14930 /* A pointer-to-member operation. */
14931 TREE_OPERAND (sub, 0)
14932 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14933 cond_guard);
14934 return init;
14935 }
14936 if (TREE_CODE (sub) == COND_EXPR)
14937 {
14938 tree cur_cond_guard = NULL_TREE;
14939 if (TREE_OPERAND (sub, 1))
14940 TREE_OPERAND (sub, 1)
14941 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14942 cond_guard: &cur_cond_guard);
14943 if (cur_cond_guard)
14944 {
14945 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14946 NOP_EXPR, boolean_true_node,
14947 tf_warning_or_error);
14948 TREE_OPERAND (sub, 1)
14949 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14950 tf_warning_or_error);
14951 }
14952 cur_cond_guard = NULL_TREE;
14953 if (TREE_OPERAND (sub, 2))
14954 TREE_OPERAND (sub, 2)
14955 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14956 cond_guard: &cur_cond_guard);
14957 if (cur_cond_guard)
14958 {
14959 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14960 NOP_EXPR, boolean_true_node,
14961 tf_warning_or_error);
14962 TREE_OPERAND (sub, 2)
14963 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14964 tf_warning_or_error);
14965 }
14966 return init;
14967 }
14968 if (TREE_CODE (sub) != ADDR_EXPR)
14969 return init;
14970 /* Deal with binding to a subobject. */
14971 for (p = &TREE_OPERAND (sub, 0);
14972 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14973 p = &TREE_OPERAND (*p, 0);
14974 if (TREE_CODE (*p) == TARGET_EXPR)
14975 {
14976 tree subinit = NULL_TREE;
14977 *p = set_up_extended_ref_temp (decl, expr: *p, cleanups, initp: &subinit,
14978 cond_guard, walk_data: nullptr);
14979 recompute_tree_invariant_for_addr_expr (sub);
14980 if (init != sub)
14981 init = fold_convert (TREE_TYPE (init), sub);
14982 if (subinit)
14983 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14984 }
14985 return init;
14986}
14987
14988/* Data for extend_temps_r, mostly matching the parameters of
14989 extend_ref_init_temps. */
14990
14991struct extend_temps_data
14992{
14993 tree decl;
14994 tree init;
14995 vec<tree, va_gc> **cleanups;
14996 tree* cond_guard;
14997 hash_set<tree> *pset; // For avoiding redundant walk_tree.
14998 hash_map<tree, tree> *var_map; // For remapping extended temps.
14999};
15000
15001/* Tree walk function for extend_all_temps. Generally parallel to
15002 extend_ref_init_temps_1, but adapted for walk_tree. */
15003
15004tree
15005extend_temps_r (tree *tp, int *walk_subtrees, void *data)
15006{
15007 extend_temps_data *d = (extend_temps_data *)data;
15008
15009 if (TREE_CODE (*tp) == VAR_DECL)
15010 {
15011 if (tree *r = d->var_map->get (k: *tp))
15012 *tp = *r;
15013 return NULL_TREE;
15014 }
15015
15016 if (TYPE_P (*tp) || TREE_CODE (*tp) == CLEANUP_POINT_EXPR
15017 || d->pset->add (k: *tp))
15018 {
15019 *walk_subtrees = 0;
15020 return NULL_TREE;
15021 }
15022
15023 if (TREE_CODE (*tp) == COND_EXPR)
15024 {
15025 cp_walk_tree (&TREE_OPERAND (*tp, 0), extend_temps_r, d, nullptr);
15026
15027 auto walk_arm = [d](tree &op)
15028 {
15029 tree cur_cond_guard = NULL_TREE;
15030 auto ov = make_temp_override (var&: d->cond_guard, overrider: &cur_cond_guard);
15031 cp_walk_tree (&op, extend_temps_r, d, nullptr);
15032 if (cur_cond_guard)
15033 {
15034 tree set = build2 (MODIFY_EXPR, boolean_type_node,
15035 cur_cond_guard, boolean_true_node);
15036 op = cp_build_compound_expr (set, op, tf_none);
15037 }
15038 };
15039 walk_arm (TREE_OPERAND (*tp, 1));
15040 walk_arm (TREE_OPERAND (*tp, 2));
15041
15042 *walk_subtrees = 0;
15043 return NULL_TREE;
15044 }
15045
15046 tree *p = tp;
15047
15048 if (TREE_CODE (*tp) == ADDR_EXPR)
15049 for (p = &TREE_OPERAND (*tp, 0);
15050 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
15051 p = &TREE_OPERAND (*p, 0);
15052
15053 if (TREE_CODE (*p) == TARGET_EXPR
15054 /* An eliding TARGET_EXPR isn't a temporary at all. */
15055 && !TARGET_EXPR_ELIDING_P (*p)
15056 /* A TARGET_EXPR with TARGET_EXPR_INTERNAL_P is an artificial variable
15057 used during initialization that need not be extended. */
15058 && !TARGET_EXPR_INTERNAL_P (*p))
15059 {
15060 /* A CLEANUP_EH_ONLY expr should also have TARGET_EXPR_INTERNAL_P. */
15061 gcc_checking_assert (!CLEANUP_EH_ONLY (*p));
15062
15063 tree subinit = NULL_TREE;
15064 tree slot = TARGET_EXPR_SLOT (*p);
15065 *p = set_up_extended_ref_temp (decl: d->decl, expr: *p, cleanups: d->cleanups, initp: &subinit,
15066 cond_guard: d->cond_guard, walk_data: d);
15067 if (TREE_CODE (*tp) == ADDR_EXPR)
15068 recompute_tree_invariant_for_addr_expr (*tp);
15069 if (subinit)
15070 *tp = cp_build_compound_expr (subinit, *tp, tf_none);
15071 d->var_map->put (k: slot, v: *p);
15072 }
15073
15074 return NULL_TREE;
15075}
15076
15077/* Extend all the temporaries in a for-range-initializer. */
15078
15079static tree
15080extend_all_temps (tree decl, tree init, vec<tree, va_gc> **cleanups)
15081{
15082 hash_set<tree> pset;
15083 hash_map<tree, tree> map;
15084 gcc_assert (!TREE_STATIC (decl));
15085 extend_temps_data d = { .decl: decl, .init: init, .cleanups: cleanups, .cond_guard: nullptr, .pset: &pset, .var_map: &map };
15086 cp_walk_tree (&init, extend_temps_r, &d, nullptr);
15087 return init;
15088}
15089
15090/* INIT is part of the initializer for DECL. If there are any
15091 reference or initializer lists being initialized, extend their
15092 lifetime to match that of DECL. */
15093
15094tree
15095extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
15096 tree *cond_guard)
15097{
15098 tree type = TREE_TYPE (init);
15099 if (processing_template_decl)
15100 return init;
15101
15102 /* P2718R0 - in C++23 for-range-initializer, extend all temps. */
15103 if (DECL_NAME (decl) == for_range__identifier
15104 && flag_range_for_ext_temps
15105 /* Iterating expansion statement decl is static right now, but that
15106 could change depending on CWG3044 and CWG3043. */
15107 && !TREE_STATIC (decl))
15108 {
15109 gcc_checking_assert (!cond_guard);
15110 return extend_all_temps (decl, init, cleanups);
15111 }
15112
15113 maybe_warn_dangling_reference (decl, init);
15114
15115 if (TYPE_REF_P (type))
15116 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
15117 else
15118 {
15119 tree ctor = init;
15120 if (TREE_CODE (ctor) == TARGET_EXPR)
15121 ctor = TARGET_EXPR_INITIAL (ctor);
15122 if (TREE_CODE (ctor) == CONSTRUCTOR)
15123 {
15124 /* [dcl.init] When initializing an aggregate from a parenthesized list
15125 of values... a temporary object bound to a reference does not have
15126 its lifetime extended. */
15127 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
15128 return init;
15129
15130 if (is_std_init_list (type))
15131 {
15132 /* The temporary array underlying a std::initializer_list
15133 is handled like a reference temporary. */
15134 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
15135 array = extend_ref_init_temps_1 (decl, init: array, cleanups,
15136 cond_guard);
15137 CONSTRUCTOR_ELT (ctor, 0)->value = array;
15138 }
15139 else
15140 {
15141 unsigned i;
15142 constructor_elt *p;
15143 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
15144 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
15145 p->value = extend_ref_init_temps (decl, init: p->value, cleanups,
15146 cond_guard);
15147 }
15148 recompute_constructor_flags (ctor);
15149 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
15150 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
15151 }
15152 }
15153
15154 return init;
15155}
15156
15157/* Returns true iff an initializer for TYPE could contain temporaries that
15158 need to be extended because they are bound to references or
15159 std::initializer_list. */
15160
15161bool
15162type_has_extended_temps (tree type)
15163{
15164 type = strip_array_types (type);
15165 if (TYPE_REF_P (type))
15166 return true;
15167 if (CLASS_TYPE_P (type))
15168 {
15169 if (is_std_init_list (type))
15170 return true;
15171 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
15172 f; f = next_aggregate_field (DECL_CHAIN (f)))
15173 if (type_has_extended_temps (TREE_TYPE (f)))
15174 return true;
15175 }
15176 return false;
15177}
15178
15179/* Returns true iff TYPE is some variant of std::initializer_list. */
15180
15181bool
15182is_std_init_list (tree type)
15183{
15184 if (!TYPE_P (type))
15185 return false;
15186 if (cxx_dialect == cxx98)
15187 return false;
15188 /* Look through typedefs. */
15189 type = TYPE_MAIN_VARIANT (type);
15190 return (CLASS_TYPE_P (type)
15191 && CP_TYPE_CONTEXT (type) == std_node
15192 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
15193}
15194
15195/* Returns true iff DECL is a list constructor: i.e. a constructor which
15196 will accept an argument list of a single std::initializer_list<T>. */
15197
15198bool
15199is_list_ctor (tree decl)
15200{
15201 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
15202 tree arg;
15203
15204 if (!args || args == void_list_node)
15205 return false;
15206
15207 arg = non_reference (TREE_VALUE (args));
15208 if (!is_std_init_list (type: arg))
15209 return false;
15210
15211 args = TREE_CHAIN (args);
15212
15213 if (args && args != void_list_node && !TREE_PURPOSE (args))
15214 /* There are more non-defaulted parms. */
15215 return false;
15216
15217 return true;
15218}
15219
15220/* We know that can_convert_arg_bad already said "no" when trying to convert
15221 FROM to TO with ARG and FLAGS. Try to figure out if it was because
15222 an explicit conversion function was skipped when looking for a way to
15223 perform the conversion. At this point we've already printed an error. */
15224
15225void
15226maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
15227{
15228 if (!(flags & LOOKUP_ONLYCONVERTING))
15229 return;
15230
15231 conversion_obstack_sentinel cos;
15232 conversion *c = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
15233 flags: flags & ~LOOKUP_ONLYCONVERTING, complain: tf_none);
15234 if (c && !c->bad_p && c->user_conv_p)
15235 /* Ay, the conversion would have worked in direct-init context. */
15236 for (; c; c = next_conversion (conv: c))
15237 if (c->kind == ck_user
15238 && DECL_P (c->cand->fn)
15239 && DECL_NONCONVERTING_P (c->cand->fn))
15240 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
15241 "function was not considered");
15242}
15243
15244/* We're converting EXPR to TYPE. If that conversion involves a conversion
15245 function and we're binding EXPR to a reference parameter of that function,
15246 return true. */
15247
15248bool
15249conv_binds_to_reference_parm_p (tree type, tree expr)
15250{
15251 conversion_obstack_sentinel cos;
15252 conversion *c = implicit_conversion (to: type, TREE_TYPE (expr), expr,
15253 /*c_cast_p=*/false, LOOKUP_NORMAL,
15254 complain: tf_none);
15255 if (c && !c->bad_p && c->user_conv_p)
15256 for (; c; c = next_conversion (conv: c))
15257 if (c->kind == ck_user)
15258 for (z_candidate *cand = c->cand; cand; cand = cand->next)
15259 if (cand->viable == 1)
15260 for (size_t i = 0; i < cand->num_convs; ++i)
15261 if (cand->convs[i]->kind == ck_ref_bind
15262 && conv_get_original_expr (c: cand->convs[i]) == expr)
15263 return true;
15264
15265 return false;
15266}
15267
15268#include "gt-cp-call.h"
15269

source code of gcc/cp/call.cc