1/* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2024 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com) and
4 modified by Brendan Kehoe (brendan@cygnus.com).
5
6This file is part of GCC.
7
8GCC is free software; you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation; either version 3, or (at your option)
11any later version.
12
13GCC is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with GCC; see the file COPYING3. If not see
20<http://www.gnu.org/licenses/>. */
21
22
23/* High-level class interface. */
24
25#include "config.h"
26#include "system.h"
27#include "coretypes.h"
28#include "target.h"
29#include "cp-tree.h"
30#include "timevar.h"
31#include "stringpool.h"
32#include "cgraph.h"
33#include "stor-layout.h"
34#include "trans-mem.h"
35#include "flags.h"
36#include "toplev.h"
37#include "intl.h"
38#include "convert.h"
39#include "langhooks.h"
40#include "c-family/c-objc.h"
41#include "internal-fn.h"
42#include "stringpool.h"
43#include "attribs.h"
44#include "decl.h"
45#include "gcc-rich-location.h"
46#include "tristate.h"
47
48/* The various kinds of conversion. */
49
50enum conversion_kind {
51 ck_identity,
52 ck_lvalue,
53 ck_fnptr,
54 ck_qual,
55 ck_std,
56 ck_ptr,
57 ck_pmem,
58 ck_base,
59 ck_ref_bind,
60 ck_user,
61 ck_ambig,
62 ck_list,
63 ck_aggr,
64 ck_rvalue,
65 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
66 this kind whenever we know the true conversion is either bad or outright
67 invalid, but we don't want to attempt to compute the bad conversion (for
68 sake of avoiding unnecessary instantiation). bad_p should always be set
69 for these. */
70 ck_deferred_bad,
71};
72
73/* The rank of the conversion. Order of the enumerals matters; better
74 conversions should come earlier in the list. */
75
76enum conversion_rank {
77 cr_identity,
78 cr_exact,
79 cr_promotion,
80 cr_std,
81 cr_pbool,
82 cr_user,
83 cr_ellipsis,
84 cr_bad
85};
86
87/* An implicit conversion sequence, in the sense of [over.best.ics].
88 The first conversion to be performed is at the end of the chain.
89 That conversion is always a cr_identity conversion. */
90
91struct conversion {
92 /* The kind of conversion represented by this step. */
93 conversion_kind kind;
94 /* The rank of this conversion. */
95 conversion_rank rank;
96 BOOL_BITFIELD user_conv_p : 1;
97 BOOL_BITFIELD ellipsis_p : 1;
98 BOOL_BITFIELD this_p : 1;
99 /* True if this conversion would be permitted with a bending of
100 language standards, e.g. disregarding pointer qualifiers or
101 converting integers to pointers. */
102 BOOL_BITFIELD bad_p : 1;
103 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
104 temporary should be created to hold the result of the
105 conversion. If KIND is ck_ambig or ck_user, true means force
106 copy-initialization. */
107 BOOL_BITFIELD need_temporary_p : 1;
108 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
109 from a pointer-to-derived to pointer-to-base is being performed. */
110 BOOL_BITFIELD base_p : 1;
111 /* If KIND is ck_ref_bind, true when either an lvalue reference is
112 being bound to an lvalue expression or an rvalue reference is
113 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
114 true when we are treating an lvalue as an rvalue (12.8p33). If
115 ck_identity, we will be binding a reference directly or decaying to
116 a pointer. */
117 BOOL_BITFIELD rvaluedness_matches_p: 1;
118 BOOL_BITFIELD check_narrowing: 1;
119 /* Whether check_narrowing should only check TREE_CONSTANTs; used
120 in build_converted_constant_expr. */
121 BOOL_BITFIELD check_narrowing_const_only: 1;
122 /* True if this conversion is taking place in a copy-initialization context
123 and we should only consider converting constructors. Only set in
124 ck_base and ck_rvalue. */
125 BOOL_BITFIELD copy_init_p : 1;
126 /* The type of the expression resulting from the conversion. */
127 tree type;
128 union {
129 /* The next conversion in the chain. Since the conversions are
130 arranged from outermost to innermost, the NEXT conversion will
131 actually be performed before this conversion. This variant is
132 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
133 ck_list. Please use the next_conversion function instead
134 of using this field directly. */
135 conversion *next;
136 /* The expression at the beginning of the conversion chain. This
137 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
138 You can use conv_get_original_expr to get this expression. */
139 tree expr;
140 /* The array of conversions for an initializer_list, so this
141 variant is used only when KIN D is ck_list. */
142 conversion **list;
143 } u;
144 /* The function candidate corresponding to this conversion
145 sequence. This field is only used if KIND is ck_user. */
146 struct z_candidate *cand;
147};
148
149#define CONVERSION_RANK(NODE) \
150 ((NODE)->bad_p ? cr_bad \
151 : (NODE)->ellipsis_p ? cr_ellipsis \
152 : (NODE)->user_conv_p ? cr_user \
153 : (NODE)->rank)
154
155#define BAD_CONVERSION_RANK(NODE) \
156 ((NODE)->ellipsis_p ? cr_ellipsis \
157 : (NODE)->user_conv_p ? cr_user \
158 : (NODE)->rank)
159
160static struct obstack conversion_obstack;
161static bool conversion_obstack_initialized;
162struct rejection_reason;
163
164static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
165static int equal_functions (tree, tree);
166static int joust (struct z_candidate *, struct z_candidate *, bool,
167 tsubst_flags_t);
168static int compare_ics (conversion *, conversion *);
169static void maybe_warn_class_memaccess (location_t, tree,
170 const vec<tree, va_gc> *);
171static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
172static tree convert_like (conversion *, tree, tsubst_flags_t);
173static tree convert_like_with_context (conversion *, tree, tree, int,
174 tsubst_flags_t);
175static void op_error (const op_location_t &, enum tree_code, enum tree_code,
176 tree, tree, tree, bool);
177static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
178 tsubst_flags_t);
179static void print_z_candidate (location_t, const char *, struct z_candidate *);
180static void print_z_candidates (location_t, struct z_candidate *,
181 tristate = tristate::unknown ());
182static tree build_this (tree);
183static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
184static bool any_strictly_viable (struct z_candidate *);
185static struct z_candidate *add_template_candidate
186 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
187 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
188static struct z_candidate *add_template_candidate_real
189 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
190 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
191static bool is_complete (tree);
192static struct z_candidate *add_conv_candidate
193 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
194 tree, tsubst_flags_t);
195static struct z_candidate *add_function_candidate
196 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
197 tree, int, conversion**, bool, tsubst_flags_t);
198static conversion *implicit_conversion (tree, tree, tree, bool, int,
199 tsubst_flags_t);
200static conversion *reference_binding (tree, tree, tree, bool, int,
201 tsubst_flags_t);
202static conversion *build_conv (conversion_kind, tree, conversion *);
203static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
204static conversion *next_conversion (conversion *);
205static bool is_subseq (conversion *, conversion *);
206static conversion *maybe_handle_ref_bind (conversion **);
207static void maybe_handle_implicit_object (conversion **);
208static struct z_candidate *add_candidate
209 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
210 conversion **, tree, tree, int, struct rejection_reason *, int);
211static tree source_type (conversion *);
212static void add_warning (struct z_candidate *, struct z_candidate *);
213static conversion *direct_reference_binding (tree, conversion *);
214static bool promoted_arithmetic_type_p (tree);
215static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
216static char *name_as_c_string (tree, tree, bool *);
217static tree prep_operand (tree);
218static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
219 bool, tree, tree, int, struct z_candidate **,
220 tsubst_flags_t);
221static conversion *merge_conversion_sequences (conversion *, conversion *);
222static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
223static conversion *build_identity_conv (tree, tree);
224static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
225static bool conv_is_prvalue (conversion *);
226static tree prevent_lifetime_extension (tree);
227
228/* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
229 NAME can take many forms... */
230
231bool
232check_dtor_name (tree basetype, tree name)
233{
234 /* Just accept something we've already complained about. */
235 if (name == error_mark_node)
236 return true;
237
238 if (TREE_CODE (name) == TYPE_DECL)
239 name = TREE_TYPE (name);
240 else if (TYPE_P (name))
241 /* OK */;
242 else if (identifier_p (t: name))
243 {
244 if ((MAYBE_CLASS_TYPE_P (basetype)
245 || TREE_CODE (basetype) == ENUMERAL_TYPE)
246 && name == constructor_name (basetype))
247 return true;
248
249 /* Otherwise lookup the name, it could be an unrelated typedef
250 of the correct type. */
251 name = lookup_name (name, want: LOOK_want::TYPE);
252 if (!name)
253 return false;
254 name = TREE_TYPE (name);
255 if (name == error_mark_node)
256 return false;
257 }
258 else
259 {
260 /* In the case of:
261
262 template <class T> struct S { ~S(); };
263 int i;
264 i.~S();
265
266 NAME will be a class template. */
267 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
268 return false;
269 }
270
271 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
272}
273
274/* We want the address of a function or method. We avoid creating a
275 pointer-to-member function. */
276
277tree
278build_addr_func (tree function, tsubst_flags_t complain)
279{
280 tree type = TREE_TYPE (function);
281
282 /* We have to do these by hand to avoid real pointer to member
283 functions. */
284 if (TREE_CODE (type) == METHOD_TYPE)
285 {
286 if (TREE_CODE (function) == OFFSET_REF)
287 {
288 tree object = build_address (TREE_OPERAND (function, 0));
289 return get_member_function_from_ptrfunc (&object,
290 TREE_OPERAND (function, 1),
291 complain);
292 }
293 function = build_address (function);
294 }
295 else if (TREE_CODE (function) == FUNCTION_DECL
296 && DECL_IMMEDIATE_FUNCTION_P (function))
297 function = build_address (function);
298 else
299 function = decay_conversion (function, complain, /*reject_builtin=*/false);
300
301 return function;
302}
303
304/* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
305 POINTER_TYPE to those. Note, pointer to member function types
306 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
307 two variants. build_call_a is the primitive taking an array of
308 arguments, while build_call_n is a wrapper that handles varargs. */
309
310tree
311build_call_n (tree function, int n, ...)
312{
313 if (n == 0)
314 return build_call_a (function, 0, NULL);
315 else
316 {
317 tree *argarray = XALLOCAVEC (tree, n);
318 va_list ap;
319 int i;
320
321 va_start (ap, n);
322 for (i = 0; i < n; i++)
323 argarray[i] = va_arg (ap, tree);
324 va_end (ap);
325 return build_call_a (function, n, argarray);
326 }
327}
328
329/* Update various flags in cfun and the call itself based on what is being
330 called. Split out of build_call_a so that bot_manip can use it too. */
331
332void
333set_flags_from_callee (tree call)
334{
335 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
336 tree decl = cp_get_callee_fndecl_nofold (call);
337
338 /* We check both the decl and the type; a function may be known not to
339 throw without being declared throw(). */
340 bool nothrow = decl && TREE_NOTHROW (decl);
341 tree callee = cp_get_callee (call);
342 if (callee)
343 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
344 else if (TREE_CODE (call) == CALL_EXPR
345 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
346 nothrow = true;
347
348 if (cfun && cp_function_chain && !cp_unevaluated_operand)
349 {
350 if (!nothrow && at_function_scope_p ())
351 cp_function_chain->can_throw = 1;
352
353 if (decl && TREE_THIS_VOLATILE (decl))
354 current_function_returns_abnormally = 1;
355 }
356
357 TREE_NOTHROW (call) = nothrow;
358}
359
360tree
361build_call_a (tree function, int n, tree *argarray)
362{
363 tree decl;
364 tree result_type;
365 tree fntype;
366 int i;
367
368 function = build_addr_func (function, complain: tf_warning_or_error);
369
370 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
371 fntype = TREE_TYPE (TREE_TYPE (function));
372 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
373 result_type = TREE_TYPE (fntype);
374 /* An rvalue has no cv-qualifiers. */
375 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
376 result_type = cv_unqualified (result_type);
377
378 function = build_call_array_loc (input_location,
379 result_type, function, n, argarray);
380 set_flags_from_callee (function);
381
382 decl = get_callee_fndecl (function);
383
384 if (decl && !TREE_USED (decl))
385 {
386 /* We invoke build_call directly for several library
387 functions. These may have been declared normally if
388 we're building libgcc, so we can't just check
389 DECL_ARTIFICIAL. */
390 gcc_assert (DECL_ARTIFICIAL (decl)
391 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
392 "__", 2));
393 mark_used (decl);
394 }
395
396 require_complete_eh_spec_types (fntype, decl);
397
398 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
399
400 /* Don't pass empty class objects by value. This is useful
401 for tags in STL, which are used to control overload resolution.
402 We don't need to handle other cases of copying empty classes. */
403 if (!decl || !fndecl_built_in_p (node: decl))
404 for (i = 0; i < n; i++)
405 {
406 tree arg = CALL_EXPR_ARG (function, i);
407 if (is_empty_class (TREE_TYPE (arg))
408 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
409 {
410 while (TREE_CODE (arg) == TARGET_EXPR)
411 /* We're disconnecting the initializer from its target,
412 don't create a temporary. */
413 arg = TARGET_EXPR_INITIAL (arg);
414 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
415 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
416 CALL_EXPR_ARG (function, i) = arg;
417 }
418 }
419
420 return function;
421}
422
423/* New overloading code. */
424
425struct z_candidate;
426
427struct candidate_warning {
428 z_candidate *loser;
429 candidate_warning *next;
430};
431
432/* Information for providing diagnostics about why overloading failed. */
433
434enum rejection_reason_code {
435 rr_none,
436 rr_arity,
437 rr_explicit_conversion,
438 rr_template_conversion,
439 rr_arg_conversion,
440 rr_bad_arg_conversion,
441 rr_template_unification,
442 rr_invalid_copy,
443 rr_inherited_ctor,
444 rr_constraint_failure,
445 rr_ignored,
446};
447
448struct conversion_info {
449 /* The index of the argument, 0-based. */
450 int n_arg;
451 /* The actual argument or its type. */
452 tree from;
453 /* The type of the parameter. */
454 tree to_type;
455 /* The location of the argument. */
456 location_t loc;
457};
458
459struct rejection_reason {
460 enum rejection_reason_code code;
461 union {
462 /* Information about an arity mismatch. */
463 struct {
464 /* The expected number of arguments. */
465 int expected;
466 /* The actual number of arguments in the call. */
467 int actual;
468 /* Whether EXPECTED should be treated as a lower bound. */
469 bool least_p;
470 } arity;
471 /* Information about an argument conversion mismatch. */
472 struct conversion_info conversion;
473 /* Same, but for bad argument conversions. */
474 struct conversion_info bad_conversion;
475 /* Information about template unification failures. These are the
476 parameters passed to fn_type_unification. */
477 struct {
478 tree tmpl;
479 tree explicit_targs;
480 int num_targs;
481 const tree *args;
482 unsigned int nargs;
483 tree return_type;
484 unification_kind_t strict;
485 int flags;
486 } template_unification;
487 /* Information about template instantiation failures. These are the
488 parameters passed to instantiate_template. */
489 struct {
490 tree tmpl;
491 tree targs;
492 } template_instantiation;
493 } u;
494};
495
496struct z_candidate {
497 /* The FUNCTION_DECL that will be called if this candidate is
498 selected by overload resolution. */
499 tree fn;
500 /* If not NULL_TREE, the first argument to use when calling this
501 function. */
502 tree first_arg;
503 /* The rest of the arguments to use when calling this function. If
504 there are no further arguments this may be NULL or it may be an
505 empty vector. */
506 const vec<tree, va_gc> *args;
507 /* The implicit conversion sequences for each of the arguments to
508 FN. */
509 conversion **convs;
510 /* The number of implicit conversion sequences. */
511 size_t num_convs;
512 /* If FN is a user-defined conversion, the standard conversion
513 sequence from the type returned by FN to the desired destination
514 type. */
515 conversion *second_conv;
516 struct rejection_reason *reason;
517 /* If FN is a member function, the binfo indicating the path used to
518 qualify the name of FN at the call site. This path is used to
519 determine whether or not FN is accessible if it is selected by
520 overload resolution. The DECL_CONTEXT of FN will always be a
521 (possibly improper) base of this binfo. */
522 tree access_path;
523 /* If FN is a non-static member function, the binfo indicating the
524 subobject to which the `this' pointer should be converted if FN
525 is selected by overload resolution. The type pointed to by
526 the `this' pointer must correspond to the most derived class
527 indicated by the CONVERSION_PATH. */
528 tree conversion_path;
529 tree template_decl;
530 tree explicit_targs;
531 candidate_warning *warnings;
532 z_candidate *next;
533 int viable;
534
535 /* The flags active in add_candidate. */
536 int flags;
537
538 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
539 bool reversed () const { return (flags & LOOKUP_REVERSED); }
540};
541
542/* Returns true iff T is a null pointer constant in the sense of
543 [conv.ptr]. */
544
545bool
546null_ptr_cst_p (tree t)
547{
548 tree type = TREE_TYPE (t);
549
550 /* [conv.ptr]
551
552 A null pointer constant is an integer literal ([lex.icon]) with value
553 zero or a prvalue of type std::nullptr_t. */
554 if (NULLPTR_TYPE_P (type))
555 return true;
556
557 if (cxx_dialect >= cxx11)
558 {
559 STRIP_ANY_LOCATION_WRAPPER (t);
560
561 /* Core issue 903 says only literal 0 is a null pointer constant. */
562 if (TREE_CODE (t) == INTEGER_CST
563 && !TREE_OVERFLOW (t)
564 && TREE_CODE (type) == INTEGER_TYPE
565 && integer_zerop (t)
566 && !char_type_p (type))
567 return true;
568 }
569 else if (CP_INTEGRAL_TYPE_P (type))
570 {
571 t = fold_non_dependent_expr (t, tf_none);
572 STRIP_NOPS (t);
573 if (integer_zerop (t) && !TREE_OVERFLOW (t))
574 return true;
575 }
576
577 return false;
578}
579
580/* Returns true iff T is a null member pointer value (4.11). */
581
582bool
583null_member_pointer_value_p (tree t)
584{
585 tree type = TREE_TYPE (t);
586 if (!type)
587 return false;
588 else if (TYPE_PTRMEMFUNC_P (type))
589 return (TREE_CODE (t) == CONSTRUCTOR
590 && CONSTRUCTOR_NELTS (t)
591 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
592 else if (TYPE_PTRDATAMEM_P (type))
593 return integer_all_onesp (t);
594 else
595 return false;
596}
597
598/* Returns nonzero if PARMLIST consists of only default parms,
599 ellipsis, and/or undeduced parameter packs. */
600
601bool
602sufficient_parms_p (const_tree parmlist)
603{
604 for (; parmlist && parmlist != void_list_node;
605 parmlist = TREE_CHAIN (parmlist))
606 if (!TREE_PURPOSE (parmlist)
607 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
608 return false;
609 return true;
610}
611
612/* Allocate N bytes of memory from the conversion obstack. The memory
613 is zeroed before being returned. */
614
615static void *
616conversion_obstack_alloc (size_t n)
617{
618 void *p;
619 if (!conversion_obstack_initialized)
620 {
621 gcc_obstack_init (&conversion_obstack);
622 conversion_obstack_initialized = true;
623 }
624 p = obstack_alloc (&conversion_obstack, n);
625 memset (s: p, c: 0, n: n);
626 return p;
627}
628
629/* RAII class to discard anything added to conversion_obstack. */
630
631struct conversion_obstack_sentinel
632{
633 void *p;
634 conversion_obstack_sentinel (): p (conversion_obstack_alloc (n: 0)) {}
635 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
636};
637
638/* Allocate rejection reasons. */
639
640static struct rejection_reason *
641alloc_rejection (enum rejection_reason_code code)
642{
643 struct rejection_reason *p;
644 p = (struct rejection_reason *) conversion_obstack_alloc (n: sizeof *p);
645 p->code = code;
646 return p;
647}
648
649static struct rejection_reason *
650arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
651{
652 struct rejection_reason *r = alloc_rejection (code: rr_arity);
653 int adjust = first_arg != NULL_TREE;
654 r->u.arity.expected = expected - adjust;
655 r->u.arity.actual = actual - adjust;
656 r->u.arity.least_p = least_p;
657 return r;
658}
659
660static struct rejection_reason *
661arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
662 location_t loc)
663{
664 struct rejection_reason *r = alloc_rejection (code: rr_arg_conversion);
665 int adjust = first_arg != NULL_TREE;
666 r->u.conversion.n_arg = n_arg - adjust;
667 r->u.conversion.from = from;
668 r->u.conversion.to_type = to;
669 r->u.conversion.loc = loc;
670 return r;
671}
672
673static struct rejection_reason *
674bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
675 location_t loc)
676{
677 struct rejection_reason *r = alloc_rejection (code: rr_bad_arg_conversion);
678 int adjust = first_arg != NULL_TREE;
679 r->u.bad_conversion.n_arg = n_arg - adjust;
680 r->u.bad_conversion.from = from;
681 r->u.bad_conversion.to_type = to;
682 r->u.bad_conversion.loc = loc;
683 return r;
684}
685
686static struct rejection_reason *
687explicit_conversion_rejection (tree from, tree to)
688{
689 struct rejection_reason *r = alloc_rejection (code: rr_explicit_conversion);
690 r->u.conversion.n_arg = 0;
691 r->u.conversion.from = from;
692 r->u.conversion.to_type = to;
693 r->u.conversion.loc = UNKNOWN_LOCATION;
694 return r;
695}
696
697static struct rejection_reason *
698template_conversion_rejection (tree from, tree to)
699{
700 struct rejection_reason *r = alloc_rejection (code: rr_template_conversion);
701 r->u.conversion.n_arg = 0;
702 r->u.conversion.from = from;
703 r->u.conversion.to_type = to;
704 r->u.conversion.loc = UNKNOWN_LOCATION;
705 return r;
706}
707
708static struct rejection_reason *
709template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
710 const tree *args, unsigned int nargs,
711 tree return_type, unification_kind_t strict,
712 int flags)
713{
714 size_t args_n_bytes = sizeof (*args) * nargs;
715 tree *args1 = (tree *) conversion_obstack_alloc (n: args_n_bytes);
716 struct rejection_reason *r = alloc_rejection (code: rr_template_unification);
717 r->u.template_unification.tmpl = tmpl;
718 r->u.template_unification.explicit_targs = explicit_targs;
719 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
720 /* Copy args to our own storage. */
721 memcpy (dest: args1, src: args, n: args_n_bytes);
722 r->u.template_unification.args = args1;
723 r->u.template_unification.nargs = nargs;
724 r->u.template_unification.return_type = return_type;
725 r->u.template_unification.strict = strict;
726 r->u.template_unification.flags = flags;
727 return r;
728}
729
730static struct rejection_reason *
731template_unification_error_rejection (void)
732{
733 return alloc_rejection (code: rr_template_unification);
734}
735
736static struct rejection_reason *
737invalid_copy_with_fn_template_rejection (void)
738{
739 struct rejection_reason *r = alloc_rejection (code: rr_invalid_copy);
740 return r;
741}
742
743static struct rejection_reason *
744inherited_ctor_rejection (void)
745{
746 struct rejection_reason *r = alloc_rejection (code: rr_inherited_ctor);
747 return r;
748}
749
750/* Build a constraint failure record. */
751
752static struct rejection_reason *
753constraint_failure (void)
754{
755 struct rejection_reason *r = alloc_rejection (code: rr_constraint_failure);
756 return r;
757}
758
759/* Dynamically allocate a conversion. */
760
761static conversion *
762alloc_conversion (conversion_kind kind)
763{
764 conversion *c;
765 c = (conversion *) conversion_obstack_alloc (n: sizeof (conversion));
766 c->kind = kind;
767 return c;
768}
769
770/* Make sure that all memory on the conversion obstack has been
771 freed. */
772
773void
774validate_conversion_obstack (void)
775{
776 if (conversion_obstack_initialized)
777 gcc_assert ((obstack_next_free (&conversion_obstack)
778 == obstack_base (&conversion_obstack)));
779}
780
781/* Dynamically allocate an array of N conversions. */
782
783static conversion **
784alloc_conversions (size_t n)
785{
786 return (conversion **) conversion_obstack_alloc (n: n * sizeof (conversion *));
787}
788
789/* True iff the active member of conversion::u for code CODE is NEXT. */
790
791static inline bool
792has_next (conversion_kind code)
793{
794 return !(code == ck_identity
795 || code == ck_ambig
796 || code == ck_list
797 || code == ck_aggr
798 || code == ck_deferred_bad);
799}
800
801static conversion *
802build_conv (conversion_kind code, tree type, conversion *from)
803{
804 conversion *t;
805 conversion_rank rank = CONVERSION_RANK (from);
806
807 /* Only call this function for conversions that use u.next. */
808 gcc_assert (from == NULL || has_next (code));
809
810 /* Note that the caller is responsible for filling in t->cand for
811 user-defined conversions. */
812 t = alloc_conversion (kind: code);
813 t->type = type;
814 t->u.next = from;
815
816 switch (code)
817 {
818 case ck_ptr:
819 case ck_pmem:
820 case ck_base:
821 case ck_std:
822 if (rank < cr_std)
823 rank = cr_std;
824 break;
825
826 case ck_qual:
827 case ck_fnptr:
828 if (rank < cr_exact)
829 rank = cr_exact;
830 break;
831
832 default:
833 break;
834 }
835 t->rank = rank;
836 t->user_conv_p = (code == ck_user || from->user_conv_p);
837 t->bad_p = from->bad_p;
838 t->base_p = false;
839 return t;
840}
841
842/* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
843 specialization of std::initializer_list<T>, if such a conversion is
844 possible. */
845
846static conversion *
847build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
848{
849 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
850 unsigned len = CONSTRUCTOR_NELTS (ctor);
851 conversion **subconvs = alloc_conversions (n: len);
852 conversion *t;
853 unsigned i;
854 tree val;
855
856 /* Within a list-initialization we can have more user-defined
857 conversions. */
858 flags &= ~LOOKUP_NO_CONVERSION;
859 /* But no narrowing conversions. */
860 flags |= LOOKUP_NO_NARROWING;
861
862 /* Can't make an array of these types. */
863 if (TYPE_REF_P (elttype)
864 || TREE_CODE (elttype) == FUNCTION_TYPE
865 || VOID_TYPE_P (elttype))
866 return NULL;
867
868 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
869 {
870 conversion *sub
871 = implicit_conversion (elttype, TREE_TYPE (val), val,
872 false, flags, complain);
873 if (sub == NULL)
874 return NULL;
875
876 subconvs[i] = sub;
877 }
878
879 t = alloc_conversion (kind: ck_list);
880 t->type = type;
881 t->u.list = subconvs;
882 t->rank = cr_exact;
883
884 for (i = 0; i < len; ++i)
885 {
886 conversion *sub = subconvs[i];
887 if (sub->rank > t->rank)
888 t->rank = sub->rank;
889 if (sub->user_conv_p)
890 t->user_conv_p = true;
891 if (sub->bad_p)
892 t->bad_p = true;
893 }
894
895 return t;
896}
897
898/* Return the next conversion of the conversion chain (if applicable),
899 or NULL otherwise. Please use this function instead of directly
900 accessing fields of struct conversion. */
901
902static conversion *
903next_conversion (conversion *conv)
904{
905 if (conv == NULL
906 || !has_next (code: conv->kind))
907 return NULL;
908 return conv->u.next;
909}
910
911/* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
912 encountered. */
913
914static conversion *
915strip_standard_conversion (conversion *conv)
916{
917 while (conv
918 && conv->kind != ck_user
919 && has_next (code: conv->kind))
920 conv = next_conversion (conv);
921 return conv;
922}
923
924/* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
925 initializer for array type ATYPE. */
926
927static bool
928can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
929{
930 tree elttype = TREE_TYPE (atype);
931 unsigned i;
932
933 if (TREE_CODE (from) == CONSTRUCTOR)
934 {
935 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
936 {
937 tree val = CONSTRUCTOR_ELT (from, i)->value;
938 bool ok;
939 if (TREE_CODE (elttype) == ARRAY_TYPE)
940 ok = can_convert_array (atype: elttype, from: val, flags, complain);
941 else
942 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
943 complain);
944 if (!ok)
945 return false;
946 }
947 return true;
948 }
949
950 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
951 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
952 return array_string_literal_compatible_p (atype, from);
953
954 /* No other valid way to aggregate initialize an array. */
955 return false;
956}
957
958/* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
959 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
960 is in PSET. */
961
962static bool
963field_in_pset (hash_set<tree, true> &pset, tree field)
964{
965 if (pset.contains (k: field))
966 return true;
967 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
968 for (field = TYPE_FIELDS (TREE_TYPE (field));
969 field; field = DECL_CHAIN (field))
970 {
971 field = next_aggregate_field (field);
972 if (field == NULL_TREE)
973 break;
974 if (field_in_pset (pset, field))
975 return true;
976 }
977 return false;
978}
979
980/* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
981 aggregate class, if such a conversion is possible. */
982
983static conversion *
984build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
985{
986 unsigned HOST_WIDE_INT i = 0;
987 conversion *c;
988 tree field = next_aggregate_field (TYPE_FIELDS (type));
989 tree empty_ctor = NULL_TREE;
990 hash_set<tree, true> pset;
991
992 /* We already called reshape_init in implicit_conversion, but it might not
993 have done anything in the case of parenthesized aggr init. */
994
995 /* The conversions within the init-list aren't affected by the enclosing
996 context; they're always simple copy-initialization. */
997 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
998
999 /* For designated initializers, verify that each initializer is convertible
1000 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
1001 visited. In the following loop then ignore already visited
1002 FIELD_DECLs. */
1003 tree idx, val;
1004 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1005 {
1006 if (!idx)
1007 break;
1008
1009 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1010
1011 tree ftype = TREE_TYPE (idx);
1012 bool ok;
1013
1014 if (TREE_CODE (ftype) == ARRAY_TYPE)
1015 ok = can_convert_array (atype: ftype, from: val, flags, complain);
1016 else
1017 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1018 complain);
1019
1020 if (!ok)
1021 return NULL;
1022
1023 /* For unions, there should be just one initializer. */
1024 if (TREE_CODE (type) == UNION_TYPE)
1025 {
1026 field = NULL_TREE;
1027 i = 1;
1028 break;
1029 }
1030 pset.add (k: idx);
1031 }
1032
1033 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1034 {
1035 tree ftype = TREE_TYPE (field);
1036 bool ok;
1037
1038 if (!pset.is_empty () && field_in_pset (pset, field))
1039 continue;
1040 if (i < CONSTRUCTOR_NELTS (ctor))
1041 {
1042 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1043 gcc_checking_assert (!ce->index);
1044 val = ce->value;
1045 ++i;
1046 }
1047 else if (DECL_INITIAL (field))
1048 val = get_nsdmi (field, /*ctor*/false, complain);
1049 else if (TYPE_REF_P (ftype))
1050 /* Value-initialization of reference is ill-formed. */
1051 return NULL;
1052 else
1053 {
1054 if (empty_ctor == NULL_TREE)
1055 empty_ctor = build_constructor (init_list_type_node, NULL);
1056 val = empty_ctor;
1057 }
1058
1059 if (TREE_CODE (ftype) == ARRAY_TYPE)
1060 ok = can_convert_array (atype: ftype, from: val, flags, complain);
1061 else
1062 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1063 complain);
1064
1065 if (!ok)
1066 return NULL;
1067
1068 if (TREE_CODE (type) == UNION_TYPE)
1069 break;
1070 }
1071
1072 if (i < CONSTRUCTOR_NELTS (ctor))
1073 return NULL;
1074
1075 c = alloc_conversion (kind: ck_aggr);
1076 c->type = type;
1077 c->rank = cr_exact;
1078 c->user_conv_p = true;
1079 c->check_narrowing = true;
1080 c->u.expr = ctor;
1081 return c;
1082}
1083
1084/* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1085 array type, if such a conversion is possible. */
1086
1087static conversion *
1088build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1089{
1090 conversion *c;
1091 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1092 tree elttype = TREE_TYPE (type);
1093 bool bad = false;
1094 bool user = false;
1095 enum conversion_rank rank = cr_exact;
1096
1097 /* We might need to propagate the size from the element to the array. */
1098 complete_type (type);
1099
1100 if (TYPE_DOMAIN (type)
1101 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1102 {
1103 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1104 if (alen < len)
1105 return NULL;
1106 }
1107
1108 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1109
1110 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1111 {
1112 conversion *sub
1113 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1114 false, flags, complain);
1115 if (sub == NULL)
1116 return NULL;
1117
1118 if (sub->rank > rank)
1119 rank = sub->rank;
1120 if (sub->user_conv_p)
1121 user = true;
1122 if (sub->bad_p)
1123 bad = true;
1124 }
1125
1126 c = alloc_conversion (kind: ck_aggr);
1127 c->type = type;
1128 c->rank = rank;
1129 c->user_conv_p = user;
1130 c->bad_p = bad;
1131 c->u.expr = ctor;
1132 return c;
1133}
1134
1135/* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1136 complex type, if such a conversion is possible. */
1137
1138static conversion *
1139build_complex_conv (tree type, tree ctor, int flags,
1140 tsubst_flags_t complain)
1141{
1142 conversion *c;
1143 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1144 tree elttype = TREE_TYPE (type);
1145 bool bad = false;
1146 bool user = false;
1147 enum conversion_rank rank = cr_exact;
1148
1149 if (len != 2)
1150 return NULL;
1151
1152 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1153
1154 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1155 {
1156 conversion *sub
1157 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1158 false, flags, complain);
1159 if (sub == NULL)
1160 return NULL;
1161
1162 if (sub->rank > rank)
1163 rank = sub->rank;
1164 if (sub->user_conv_p)
1165 user = true;
1166 if (sub->bad_p)
1167 bad = true;
1168 }
1169
1170 c = alloc_conversion (kind: ck_aggr);
1171 c->type = type;
1172 c->rank = rank;
1173 c->user_conv_p = user;
1174 c->bad_p = bad;
1175 c->u.expr = ctor;
1176 return c;
1177}
1178
1179/* Build a representation of the identity conversion from EXPR to
1180 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1181
1182static conversion *
1183build_identity_conv (tree type, tree expr)
1184{
1185 conversion *c;
1186
1187 c = alloc_conversion (kind: ck_identity);
1188 c->type = type;
1189 c->u.expr = expr;
1190
1191 return c;
1192}
1193
1194/* Converting from EXPR to TYPE was ambiguous in the sense that there
1195 were multiple user-defined conversions to accomplish the job.
1196 Build a conversion that indicates that ambiguity. */
1197
1198static conversion *
1199build_ambiguous_conv (tree type, tree expr)
1200{
1201 conversion *c;
1202
1203 c = alloc_conversion (kind: ck_ambig);
1204 c->type = type;
1205 c->u.expr = expr;
1206
1207 return c;
1208}
1209
1210tree
1211strip_top_quals (tree t)
1212{
1213 if (TREE_CODE (t) == ARRAY_TYPE)
1214 return t;
1215 return cp_build_qualified_type (t, 0);
1216}
1217
1218/* Returns the standard conversion path (see [conv]) from type FROM to type
1219 TO, if any. For proper handling of null pointer constants, you must
1220 also pass the expression EXPR to convert from. If C_CAST_P is true,
1221 this conversion is coming from a C-style cast. */
1222
1223static conversion *
1224standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1225 int flags, tsubst_flags_t complain)
1226{
1227 enum tree_code fcode, tcode;
1228 conversion *conv;
1229 bool fromref = false;
1230 tree qualified_to;
1231
1232 to = non_reference (to);
1233 if (TYPE_REF_P (from))
1234 {
1235 fromref = true;
1236 from = TREE_TYPE (from);
1237 }
1238 qualified_to = to;
1239 to = strip_top_quals (t: to);
1240 from = strip_top_quals (t: from);
1241
1242 if (expr && type_unknown_p (expr))
1243 {
1244 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1245 {
1246 tsubst_flags_t tflags = tf_conv;
1247 expr = instantiate_type (to, expr, tflags);
1248 if (expr == error_mark_node)
1249 return NULL;
1250 from = TREE_TYPE (expr);
1251 }
1252 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1253 {
1254 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1255 expr = resolve_nondeduced_context (expr, complain);
1256 from = TREE_TYPE (expr);
1257 }
1258 }
1259
1260 fcode = TREE_CODE (from);
1261 tcode = TREE_CODE (to);
1262
1263 conv = build_identity_conv (type: from, expr);
1264 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1265 {
1266 from = type_decays_to (from);
1267 fcode = TREE_CODE (from);
1268 /* Tell convert_like that we're using the address. */
1269 conv->rvaluedness_matches_p = true;
1270 conv = build_conv (code: ck_lvalue, type: from, from: conv);
1271 }
1272 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1273 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1274 express the copy constructor call required by copy-initialization. */
1275 else if (fromref || (expr && obvalue_p (expr)))
1276 {
1277 if (expr)
1278 {
1279 tree bitfield_type;
1280 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1281 if (bitfield_type)
1282 {
1283 from = strip_top_quals (t: bitfield_type);
1284 fcode = TREE_CODE (from);
1285 }
1286 }
1287 conv = build_conv (code: ck_rvalue, type: from, from: conv);
1288 /* If we're performing copy-initialization, remember to skip
1289 explicit constructors. */
1290 if (flags & LOOKUP_ONLYCONVERTING)
1291 conv->copy_init_p = true;
1292 }
1293
1294 /* Allow conversion between `__complex__' data types. */
1295 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1296 {
1297 /* The standard conversion sequence to convert FROM to TO is
1298 the standard conversion sequence to perform componentwise
1299 conversion. */
1300 conversion *part_conv = standard_conversion
1301 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1302 complain);
1303
1304 if (!part_conv)
1305 conv = NULL;
1306 else if (part_conv->kind == ck_identity)
1307 /* Leave conv alone. */;
1308 else
1309 {
1310 conv = build_conv (code: part_conv->kind, type: to, from: conv);
1311 conv->rank = part_conv->rank;
1312 }
1313
1314 return conv;
1315 }
1316
1317 if (same_type_p (from, to))
1318 {
1319 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1320 conv->type = qualified_to;
1321 return conv;
1322 }
1323
1324 /* [conv.ptr]
1325 A null pointer constant can be converted to a pointer type; ... A
1326 null pointer constant of integral type can be converted to an
1327 rvalue of type std::nullptr_t. */
1328 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1329 || NULLPTR_TYPE_P (to))
1330 && ((expr && null_ptr_cst_p (t: expr))
1331 || NULLPTR_TYPE_P (from)))
1332 conv = build_conv (code: ck_std, type: to, from: conv);
1333 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1334 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1335 {
1336 /* For backwards brain damage compatibility, allow interconversion of
1337 pointers and integers with a pedwarn. */
1338 conv = build_conv (code: ck_std, type: to, from: conv);
1339 conv->bad_p = true;
1340 }
1341 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1342 {
1343 /* For backwards brain damage compatibility, allow interconversion of
1344 enums and integers with a pedwarn. */
1345 conv = build_conv (code: ck_std, type: to, from: conv);
1346 conv->bad_p = true;
1347 }
1348 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1349 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1350 {
1351 tree to_pointee;
1352 tree from_pointee;
1353
1354 if (tcode == POINTER_TYPE)
1355 {
1356 to_pointee = TREE_TYPE (to);
1357 from_pointee = TREE_TYPE (from);
1358
1359 /* Since this is the target of a pointer, it can't have function
1360 qualifiers, so any TYPE_QUALS must be for attributes const or
1361 noreturn. Strip them. */
1362 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1363 && TYPE_QUALS (to_pointee))
1364 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1365 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1366 && TYPE_QUALS (from_pointee))
1367 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1368 }
1369 else
1370 {
1371 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1372 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1373 }
1374
1375 if (tcode == POINTER_TYPE
1376 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1377 to_pointee))
1378 ;
1379 else if (VOID_TYPE_P (to_pointee)
1380 && !TYPE_PTRDATAMEM_P (from)
1381 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1382 {
1383 tree nfrom = TREE_TYPE (from);
1384 /* Don't try to apply restrict to void. */
1385 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1386 from_pointee = cp_build_qualified_type (void_type_node, quals);
1387 from = build_pointer_type (from_pointee);
1388 conv = build_conv (code: ck_ptr, type: from, from: conv);
1389 }
1390 else if (TYPE_PTRDATAMEM_P (from))
1391 {
1392 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1393 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1394
1395 if (same_type_p (fbase, tbase))
1396 /* No base conversion needed. */;
1397 else if (DERIVED_FROM_P (fbase, tbase)
1398 && (same_type_ignoring_top_level_qualifiers_p
1399 (from_pointee, to_pointee)))
1400 {
1401 from = build_ptrmem_type (tbase, from_pointee);
1402 conv = build_conv (code: ck_pmem, type: from, from: conv);
1403 }
1404 else
1405 return NULL;
1406 }
1407 else if (CLASS_TYPE_P (from_pointee)
1408 && CLASS_TYPE_P (to_pointee)
1409 /* [conv.ptr]
1410
1411 An rvalue of type "pointer to cv D," where D is a
1412 class type, can be converted to an rvalue of type
1413 "pointer to cv B," where B is a base class (clause
1414 _class.derived_) of D. If B is an inaccessible
1415 (clause _class.access_) or ambiguous
1416 (_class.member.lookup_) base class of D, a program
1417 that necessitates this conversion is ill-formed.
1418 Therefore, we use DERIVED_FROM_P, and do not check
1419 access or uniqueness. */
1420 && DERIVED_FROM_P (to_pointee, from_pointee))
1421 {
1422 from_pointee
1423 = cp_build_qualified_type (to_pointee,
1424 cp_type_quals (from_pointee));
1425 from = build_pointer_type (from_pointee);
1426 conv = build_conv (code: ck_ptr, type: from, from: conv);
1427 conv->base_p = true;
1428 }
1429
1430 if (same_type_p (from, to))
1431 /* OK */;
1432 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1433 /* In a C-style cast, we ignore CV-qualification because we
1434 are allowed to perform a static_cast followed by a
1435 const_cast. */
1436 conv = build_conv (code: ck_qual, type: to, from: conv);
1437 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1438 conv = build_conv (code: ck_qual, type: to, from: conv);
1439 else if (expr && string_conv_p (to, expr, 0))
1440 /* converting from string constant to char *. */
1441 conv = build_conv (code: ck_qual, type: to, from: conv);
1442 else if (fnptr_conv_p (to, from))
1443 conv = build_conv (code: ck_fnptr, type: to, from: conv);
1444 /* Allow conversions among compatible ObjC pointer types (base
1445 conversions have been already handled above). */
1446 else if (c_dialect_objc ()
1447 && objc_compare_types (to, from, -4, NULL_TREE))
1448 conv = build_conv (code: ck_ptr, type: to, from: conv);
1449 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1450 {
1451 conv = build_conv (code: ck_ptr, type: to, from: conv);
1452 conv->bad_p = true;
1453 }
1454 else
1455 return NULL;
1456
1457 from = to;
1458 }
1459 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1460 {
1461 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1462 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1463 tree fbase = class_of_this_parm (fntype: fromfn);
1464 tree tbase = class_of_this_parm (fntype: tofn);
1465
1466 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1467 yields false. But a pointer to member of incomplete class is OK. */
1468 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1469 return NULL;
1470
1471 tree fstat = static_fn_type (fromfn);
1472 tree tstat = static_fn_type (tofn);
1473 if (same_type_p (tstat, fstat)
1474 || fnptr_conv_p (tstat, fstat))
1475 /* OK */;
1476 else
1477 return NULL;
1478
1479 if (!same_type_p (fbase, tbase))
1480 {
1481 from = build_memfn_type (fstat,
1482 tbase,
1483 cp_type_quals (tbase),
1484 type_memfn_rqual (tofn));
1485 from = build_ptrmemfunc_type (build_pointer_type (from));
1486 conv = build_conv (code: ck_pmem, type: from, from: conv);
1487 conv->base_p = true;
1488 }
1489 if (fnptr_conv_p (tstat, fstat))
1490 conv = build_conv (code: ck_fnptr, type: to, from: conv);
1491 }
1492 else if (tcode == BOOLEAN_TYPE)
1493 {
1494 /* [conv.bool]
1495
1496 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1497 to member type can be converted to a prvalue of type bool. ...
1498 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1499 std::nullptr_t can be converted to a prvalue of type bool; */
1500 if (ARITHMETIC_TYPE_P (from)
1501 || UNSCOPED_ENUM_P (from)
1502 || fcode == POINTER_TYPE
1503 || TYPE_PTRMEM_P (from)
1504 || NULLPTR_TYPE_P (from))
1505 {
1506 conv = build_conv (code: ck_std, type: to, from: conv);
1507 if (fcode == POINTER_TYPE
1508 || TYPE_PTRDATAMEM_P (from)
1509 || (TYPE_PTRMEMFUNC_P (from)
1510 && conv->rank < cr_pbool)
1511 || NULLPTR_TYPE_P (from))
1512 conv->rank = cr_pbool;
1513 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1514 conv->bad_p = true;
1515 if (flags & LOOKUP_NO_NARROWING)
1516 conv->check_narrowing = true;
1517 return conv;
1518 }
1519
1520 return NULL;
1521 }
1522 /* We don't check for ENUMERAL_TYPE here because there are no standard
1523 conversions to enum type. */
1524 /* As an extension, allow conversion to complex type. */
1525 else if (ARITHMETIC_TYPE_P (to))
1526 {
1527 if (! (INTEGRAL_CODE_P (fcode)
1528 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1529 || SCOPED_ENUM_P (from))
1530 return NULL;
1531
1532 /* If we're parsing an enum with no fixed underlying type, we're
1533 dealing with an incomplete type, which renders the conversion
1534 ill-formed. */
1535 if (!COMPLETE_TYPE_P (from))
1536 return NULL;
1537
1538 conv = build_conv (code: ck_std, type: to, from: conv);
1539
1540 tree underlying_type = NULL_TREE;
1541 if (TREE_CODE (from) == ENUMERAL_TYPE
1542 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1543 underlying_type = ENUM_UNDERLYING_TYPE (from);
1544
1545 /* Give this a better rank if it's a promotion.
1546
1547 To handle CWG 1601, also bump the rank if we are converting
1548 an enumeration with a fixed underlying type to the underlying
1549 type. */
1550 if ((same_type_p (to, type_promotes_to (from))
1551 || (underlying_type && same_type_p (to, underlying_type)))
1552 && next_conversion (conv)->rank <= cr_promotion)
1553 conv->rank = cr_promotion;
1554
1555 /* A prvalue of floating-point type can be converted to a prvalue of
1556 another floating-point type with a greater or equal conversion
1557 rank ([conv.rank]). A prvalue of standard floating-point type can
1558 be converted to a prvalue of another standard floating-point type.
1559 For backwards compatibility with handling __float128 and other
1560 non-standard floating point types, allow all implicit floating
1561 point conversions if neither type is extended floating-point
1562 type and if at least one of them is, fail if they have unordered
1563 conversion rank or from has higher conversion rank. */
1564 if (fcode == REAL_TYPE
1565 && tcode == REAL_TYPE
1566 && (extended_float_type_p (type: from)
1567 || extended_float_type_p (type: to))
1568 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1569 conv->bad_p = true;
1570 }
1571 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1572 && vector_types_convertible_p (t1: from, t2: to, emit_lax_note: false))
1573 return build_conv (code: ck_std, type: to, from: conv);
1574 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1575 && is_properly_derived_from (from, to))
1576 {
1577 if (conv->kind == ck_rvalue)
1578 conv = next_conversion (conv);
1579 conv = build_conv (code: ck_base, type: to, from: conv);
1580 /* The derived-to-base conversion indicates the initialization
1581 of a parameter with base type from an object of a derived
1582 type. A temporary object is created to hold the result of
1583 the conversion unless we're binding directly to a reference. */
1584 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1585 /* If we're performing copy-initialization, remember to skip
1586 explicit constructors. */
1587 if (flags & LOOKUP_ONLYCONVERTING)
1588 conv->copy_init_p = true;
1589 }
1590 else
1591 return NULL;
1592
1593 if (flags & LOOKUP_NO_NARROWING)
1594 conv->check_narrowing = true;
1595
1596 return conv;
1597}
1598
1599/* Returns nonzero if T1 is reference-related to T2.
1600
1601 This is considered when a reference to T1 is initialized by a T2. */
1602
1603bool
1604reference_related_p (tree t1, tree t2)
1605{
1606 if (t1 == error_mark_node || t2 == error_mark_node)
1607 return false;
1608
1609 t1 = TYPE_MAIN_VARIANT (t1);
1610 t2 = TYPE_MAIN_VARIANT (t2);
1611
1612 /* [dcl.init.ref]
1613
1614 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1615 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1616 return (similar_type_p (t1, t2)
1617 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1618 && DERIVED_FROM_P (t1, t2)));
1619}
1620
1621/* Returns nonzero if T1 is reference-compatible with T2. */
1622
1623bool
1624reference_compatible_p (tree t1, tree t2)
1625{
1626 /* [dcl.init.ref]
1627
1628 "cv1 T1" is reference compatible with "cv2 T2" if
1629 a prvalue of type "pointer to cv2 T2" can be converted to the type
1630 "pointer to cv1 T1" via a standard conversion sequence. */
1631 tree ptype1 = build_pointer_type (t1);
1632 tree ptype2 = build_pointer_type (t2);
1633 conversion *conv = standard_conversion (to: ptype1, from: ptype2, NULL_TREE,
1634 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1635 if (!conv || conv->bad_p)
1636 return false;
1637 return true;
1638}
1639
1640/* Return true if converting FROM to TO would involve a qualification
1641 conversion. */
1642
1643static bool
1644involves_qualification_conversion_p (tree to, tree from)
1645{
1646 /* If we're not convering a pointer to another one, we won't get
1647 a qualification conversion. */
1648 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1649 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1650 return false;
1651
1652 conversion *conv = standard_conversion (to, from, NULL_TREE,
1653 /*c_cast_p=*/false, flags: 0, complain: tf_none);
1654 for (conversion *t = conv; t; t = next_conversion (conv: t))
1655 if (t->kind == ck_qual)
1656 return true;
1657
1658 return false;
1659}
1660
1661/* A reference of the indicated TYPE is being bound directly to the
1662 expression represented by the implicit conversion sequence CONV.
1663 Return a conversion sequence for this binding. */
1664
1665static conversion *
1666direct_reference_binding (tree type, conversion *conv)
1667{
1668 tree t;
1669
1670 gcc_assert (TYPE_REF_P (type));
1671 gcc_assert (!TYPE_REF_P (conv->type));
1672
1673 t = TREE_TYPE (type);
1674
1675 if (conv->kind == ck_identity)
1676 /* Mark the identity conv as to not decay to rvalue. */
1677 conv->rvaluedness_matches_p = true;
1678
1679 /* [over.ics.rank]
1680
1681 When a parameter of reference type binds directly
1682 (_dcl.init.ref_) to an argument expression, the implicit
1683 conversion sequence is the identity conversion, unless the
1684 argument expression has a type that is a derived class of the
1685 parameter type, in which case the implicit conversion sequence is
1686 a derived-to-base Conversion.
1687
1688 If the parameter binds directly to the result of applying a
1689 conversion function to the argument expression, the implicit
1690 conversion sequence is a user-defined conversion sequence
1691 (_over.ics.user_), with the second standard conversion sequence
1692 either an identity conversion or, if the conversion function
1693 returns an entity of a type that is a derived class of the
1694 parameter type, a derived-to-base conversion. */
1695 if (is_properly_derived_from (conv->type, t))
1696 {
1697 /* Represent the derived-to-base conversion. */
1698 conv = build_conv (code: ck_base, type: t, from: conv);
1699 /* We will actually be binding to the base-class subobject in
1700 the derived class, so we mark this conversion appropriately.
1701 That way, convert_like knows not to generate a temporary. */
1702 conv->need_temporary_p = false;
1703 }
1704 else if (involves_qualification_conversion_p (to: t, from: conv->type))
1705 /* Represent the qualification conversion. After DR 2352
1706 #1 and #2 were indistinguishable conversion sequences:
1707
1708 void f(int*); // #1
1709 void f(const int* const &); // #2
1710 void g(int* p) { f(p); }
1711
1712 because the types "int *" and "const int *const" are
1713 reference-related and we were binding both directly and they
1714 had the same rank. To break it up, we add a ck_qual under the
1715 ck_ref_bind so that conversion sequence ranking chooses #1.
1716
1717 We strip_top_quals here which is also what standard_conversion
1718 does. Failure to do so would confuse comp_cv_qual_signature
1719 into thinking that in
1720
1721 void f(const int * const &); // #1
1722 void f(const int *); // #2
1723 int *x;
1724 f(x);
1725
1726 #2 is a better match than #1 even though they're ambiguous (97296). */
1727 conv = build_conv (code: ck_qual, type: strip_top_quals (t), from: conv);
1728
1729 return build_conv (code: ck_ref_bind, type, from: conv);
1730}
1731
1732/* Returns the conversion path from type FROM to reference type TO for
1733 purposes of reference binding. For lvalue binding, either pass a
1734 reference type to FROM or an lvalue expression to EXPR. If the
1735 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1736 the conversion returned. If C_CAST_P is true, this
1737 conversion is coming from a C-style cast. */
1738
1739static conversion *
1740reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1741 tsubst_flags_t complain)
1742{
1743 conversion *conv = NULL;
1744 conversion *bad_direct_conv = nullptr;
1745 tree to = TREE_TYPE (rto);
1746 tree from = rfrom;
1747 tree tfrom;
1748 bool related_p;
1749 bool compatible_p;
1750 cp_lvalue_kind gl_kind;
1751 bool is_lvalue;
1752
1753 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1754 {
1755 expr = instantiate_type (to, expr, tf_none);
1756 if (expr == error_mark_node)
1757 return NULL;
1758 from = TREE_TYPE (expr);
1759 }
1760
1761 bool copy_list_init = false;
1762 bool single_list_conv = false;
1763 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1764 {
1765 maybe_warn_cpp0x (str: CPP0X_INITIALIZER_LISTS);
1766 /* DR 1288: Otherwise, if the initializer list has a single element
1767 of type E and ... [T's] referenced type is reference-related to E,
1768 the object or reference is initialized from that element...
1769
1770 ??? With P0388R4, we should bind 't' directly to U{}:
1771 using U = A[2];
1772 A (&&t)[] = {U{}};
1773 because A[] and A[2] are reference-related. But we don't do it
1774 because grok_reference_init has deduced the array size (to 1), and
1775 A[1] and A[2] aren't reference-related. */
1776 if (CONSTRUCTOR_NELTS (expr) == 1
1777 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1778 {
1779 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1780 if (error_operand_p (t: elt))
1781 return NULL;
1782 tree etype = TREE_TYPE (elt);
1783 if (reference_related_p (t1: to, t2: etype))
1784 {
1785 expr = elt;
1786 from = etype;
1787 goto skip;
1788 }
1789 else if (CLASS_TYPE_P (etype) && TYPE_HAS_CONVERSION (etype))
1790 /* CWG1996: jason's proposed drafting adds "or initializing T from E
1791 would bind directly". We check that in the direct binding with
1792 conversion code below. */
1793 single_list_conv = true;
1794 }
1795 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1796 referenced by T is copy-list-initialized, and the reference is bound
1797 to that temporary. */
1798 copy_list_init = true;
1799 skip:;
1800 }
1801
1802 if (TYPE_REF_P (from))
1803 {
1804 from = TREE_TYPE (from);
1805 if (!TYPE_REF_IS_RVALUE (rfrom)
1806 || TREE_CODE (from) == FUNCTION_TYPE)
1807 gl_kind = clk_ordinary;
1808 else
1809 gl_kind = clk_rvalueref;
1810 }
1811 else if (expr)
1812 gl_kind = lvalue_kind (expr);
1813 else if (CLASS_TYPE_P (from)
1814 || TREE_CODE (from) == ARRAY_TYPE)
1815 gl_kind = clk_class;
1816 else
1817 gl_kind = clk_none;
1818
1819 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1820 if ((flags & LOOKUP_NO_TEMP_BIND)
1821 && (gl_kind & clk_class))
1822 gl_kind = clk_none;
1823
1824 /* Same mask as real_lvalue_p. */
1825 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1826
1827 tfrom = from;
1828 if ((gl_kind & clk_bitfield) != 0)
1829 tfrom = unlowered_expr_type (expr);
1830
1831 /* Figure out whether or not the types are reference-related and
1832 reference compatible. We have to do this after stripping
1833 references from FROM. */
1834 related_p = reference_related_p (t1: to, t2: tfrom);
1835 /* If this is a C cast, first convert to an appropriately qualified
1836 type, so that we can later do a const_cast to the desired type. */
1837 if (related_p && c_cast_p
1838 && !at_least_as_qualified_p (to, tfrom))
1839 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1840 compatible_p = reference_compatible_p (t1: to, t2: tfrom);
1841
1842 /* Directly bind reference when target expression's type is compatible with
1843 the reference and expression is an lvalue. In DR391, the wording in
1844 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1845 const and rvalue references to rvalues of compatible class type.
1846 We should also do direct bindings for non-class xvalues. */
1847 if ((related_p || compatible_p) && gl_kind)
1848 {
1849 /* [dcl.init.ref]
1850
1851 If the initializer expression
1852
1853 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1854 is reference-compatible with "cv2 T2,"
1855
1856 the reference is bound directly to the initializer expression
1857 lvalue.
1858
1859 [...]
1860 If the initializer expression is an rvalue, with T2 a class type,
1861 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1862 is bound to the object represented by the rvalue or to a sub-object
1863 within that object. */
1864
1865 conv = build_identity_conv (type: tfrom, expr);
1866 conv = direct_reference_binding (type: rto, conv);
1867
1868 if (TYPE_REF_P (rfrom))
1869 /* Handle rvalue reference to function properly. */
1870 conv->rvaluedness_matches_p
1871 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1872 else
1873 conv->rvaluedness_matches_p
1874 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1875
1876 if ((gl_kind & clk_bitfield) != 0
1877 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1878 /* For the purposes of overload resolution, we ignore the fact
1879 this expression is a bitfield or packed field. (In particular,
1880 [over.ics.ref] says specifically that a function with a
1881 non-const reference parameter is viable even if the
1882 argument is a bitfield.)
1883
1884 However, when we actually call the function we must create
1885 a temporary to which to bind the reference. If the
1886 reference is volatile, or isn't const, then we cannot make
1887 a temporary, so we just issue an error when the conversion
1888 actually occurs. */
1889 conv->need_temporary_p = true;
1890
1891 /* Don't allow binding of lvalues (other than function lvalues) to
1892 rvalue references. */
1893 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1894 && TREE_CODE (to) != FUNCTION_TYPE)
1895 conv->bad_p = true;
1896
1897 /* Nor the reverse. */
1898 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1899 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1900 But in C++23, such an expression is just an xvalue, not a special
1901 lvalue, so the binding is once again ill-formed. */
1902 && !(cxx_dialect <= cxx20
1903 && (gl_kind & clk_implicit_rval))
1904 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1905 || (flags & LOOKUP_NO_RVAL_BIND))
1906 && TREE_CODE (to) != FUNCTION_TYPE)
1907 conv->bad_p = true;
1908
1909 if (!compatible_p)
1910 conv->bad_p = true;
1911
1912 return conv;
1913 }
1914 /* [class.conv.fct] A conversion function is never used to convert a
1915 (possibly cv-qualified) object to the (possibly cv-qualified) same
1916 object type (or a reference to it), to a (possibly cv-qualified) base
1917 class of that type (or a reference to it).... */
1918 else if (!related_p
1919 && !(flags & LOOKUP_NO_CONVERSION)
1920 && (CLASS_TYPE_P (from) || single_list_conv))
1921 {
1922 tree rexpr = expr;
1923 if (single_list_conv)
1924 rexpr = CONSTRUCTOR_ELT (expr, 0)->value;
1925
1926 /* [dcl.init.ref]
1927
1928 If the initializer expression
1929
1930 -- has a class type (i.e., T2 is a class type) can be
1931 implicitly converted to an lvalue of type "cv3 T3," where
1932 "cv1 T1" is reference-compatible with "cv3 T3". (this
1933 conversion is selected by enumerating the applicable
1934 conversion functions (_over.match.ref_) and choosing the
1935 best one through overload resolution. (_over.match_).
1936
1937 the reference is bound to the lvalue result of the conversion
1938 in the second case. */
1939 z_candidate *cand = build_user_type_conversion_1 (rto, rexpr, flags,
1940 complain);
1941 if (cand)
1942 {
1943 if (!cand->second_conv->bad_p)
1944 return cand->second_conv;
1945
1946 /* Direct reference binding wasn't successful and yielded a bad
1947 conversion. Proceed with trying to go through a temporary
1948 instead, and if that also fails then we'll return this bad
1949 conversion rather than no conversion for sake of better
1950 diagnostics. */
1951 bad_direct_conv = cand->second_conv;
1952 }
1953 }
1954
1955 /* From this point on, we conceptually need temporaries, even if we
1956 elide them. Only the cases above are "direct bindings". */
1957 if (flags & LOOKUP_NO_TEMP_BIND)
1958 return bad_direct_conv ? bad_direct_conv : nullptr;
1959
1960 /* [over.ics.rank]
1961
1962 When a parameter of reference type is not bound directly to an
1963 argument expression, the conversion sequence is the one required
1964 to convert the argument expression to the underlying type of the
1965 reference according to _over.best.ics_. Conceptually, this
1966 conversion sequence corresponds to copy-initializing a temporary
1967 of the underlying type with the argument expression. Any
1968 difference in top-level cv-qualification is subsumed by the
1969 initialization itself and does not constitute a conversion. */
1970
1971 bool maybe_valid_p = true;
1972
1973 /* [dcl.init.ref]
1974
1975 Otherwise, the reference shall be an lvalue reference to a
1976 non-volatile const type, or the reference shall be an rvalue
1977 reference. */
1978 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1979 maybe_valid_p = false;
1980
1981 /* [dcl.init.ref]
1982
1983 Otherwise, a temporary of type "cv1 T1" is created and
1984 initialized from the initializer expression using the rules for a
1985 non-reference copy initialization. If T1 is reference-related to
1986 T2, cv1 must be the same cv-qualification as, or greater
1987 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1988 if (related_p && !at_least_as_qualified_p (to, from))
1989 maybe_valid_p = false;
1990
1991 /* We try below to treat an invalid reference binding as a bad conversion
1992 to improve diagnostics, but doing so may cause otherwise unnecessary
1993 instantiations that can lead to a hard error. So during the first pass
1994 of overload resolution wherein we shortcut bad conversions, instead just
1995 produce a special conversion indicating a second pass is necessary if
1996 there's no strictly viable candidate. */
1997 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1998 {
1999 if (bad_direct_conv)
2000 return bad_direct_conv;
2001
2002 conv = alloc_conversion (kind: ck_deferred_bad);
2003 conv->bad_p = true;
2004 return conv;
2005 }
2006
2007 /* We're generating a temporary now, but don't bind any more in the
2008 conversion (specifically, don't slice the temporary returned by a
2009 conversion operator). */
2010 flags |= LOOKUP_NO_TEMP_BIND;
2011
2012 /* Core issue 899: When [copy-]initializing a temporary to be bound
2013 to the first parameter of a copy constructor (12.8) called with
2014 a single argument in the context of direct-initialization,
2015 explicit conversion functions are also considered.
2016
2017 So don't set LOOKUP_ONLYCONVERTING in that case. */
2018 if (!(flags & LOOKUP_COPY_PARM))
2019 flags |= LOOKUP_ONLYCONVERTING;
2020
2021 if (!conv)
2022 conv = implicit_conversion (to, from, expr, c_cast_p,
2023 flags, complain);
2024 if (!conv)
2025 return bad_direct_conv ? bad_direct_conv : nullptr;
2026
2027 if (conv->user_conv_p)
2028 {
2029 if (copy_list_init)
2030 /* Remember this was copy-list-initialization. */
2031 conv->need_temporary_p = true;
2032
2033 /* If initializing the temporary used a conversion function,
2034 recalculate the second conversion sequence. */
2035 for (conversion *t = conv; t; t = next_conversion (conv: t))
2036 if (t->kind == ck_user
2037 && c_cast_p && !maybe_valid_p)
2038 {
2039 if (complain & tf_warning)
2040 warning (OPT_Wcast_user_defined,
2041 "casting %qT to %qT does not use %qD",
2042 from, rto, t->cand->fn);
2043 /* Don't let recalculation try to make this valid. */
2044 break;
2045 }
2046 else if (t->kind == ck_user
2047 && DECL_CONV_FN_P (t->cand->fn))
2048 {
2049 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2050 /* A prvalue of non-class type is cv-unqualified. */
2051 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2052 ftype = cv_unqualified (ftype);
2053 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2054 conversion *new_second
2055 = reference_binding (rto, rfrom: ftype, NULL_TREE, c_cast_p,
2056 flags: sflags, complain);
2057 if (!new_second)
2058 return bad_direct_conv ? bad_direct_conv : nullptr;
2059 conv = merge_conversion_sequences (t, new_second);
2060 gcc_assert (maybe_valid_p || conv->bad_p);
2061 return conv;
2062 }
2063 }
2064
2065 conv = build_conv (code: ck_ref_bind, type: rto, from: conv);
2066 /* This reference binding, unlike those above, requires the
2067 creation of a temporary. */
2068 conv->need_temporary_p = true;
2069 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2070 conv->bad_p |= !maybe_valid_p;
2071
2072 return conv;
2073}
2074
2075/* Returns the implicit conversion sequence (see [over.ics]) from type
2076 FROM to type TO. The optional expression EXPR may affect the
2077 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2078 true, this conversion is coming from a C-style cast. */
2079
2080static conversion *
2081implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2082 int flags, tsubst_flags_t complain)
2083{
2084 conversion *conv;
2085
2086 if (from == error_mark_node || to == error_mark_node
2087 || expr == error_mark_node)
2088 return NULL;
2089
2090 /* Other flags only apply to the primary function in overload
2091 resolution, or after we've chosen one. */
2092 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2093 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2094 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2095
2096 /* FIXME: actually we don't want warnings either, but we can't just
2097 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2098 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2099 We really ought not to issue that warning until we've committed
2100 to that conversion. */
2101 complain &= ~tf_error;
2102
2103 /* Call reshape_init early to remove redundant braces. */
2104 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2105 {
2106 to = complete_type (to);
2107 if (!COMPLETE_TYPE_P (to))
2108 return nullptr;
2109 if (!CLASSTYPE_NON_AGGREGATE (to))
2110 {
2111 expr = reshape_init (to, expr, complain);
2112 if (expr == error_mark_node)
2113 return nullptr;
2114 from = TREE_TYPE (expr);
2115 }
2116 }
2117
2118 if (TYPE_REF_P (to))
2119 conv = reference_binding (rto: to, rfrom: from, expr, c_cast_p, flags, complain);
2120 else
2121 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2122
2123 if (conv)
2124 return conv;
2125
2126 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2127 {
2128 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2129 return build_list_conv (type: to, ctor: expr, flags, complain);
2130
2131 /* As an extension, allow list-initialization of _Complex. */
2132 if (TREE_CODE (to) == COMPLEX_TYPE
2133 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2134 {
2135 conv = build_complex_conv (type: to, ctor: expr, flags, complain);
2136 if (conv)
2137 return conv;
2138 }
2139
2140 /* Allow conversion from an initializer-list with one element to a
2141 scalar type. */
2142 if (SCALAR_TYPE_P (to))
2143 {
2144 int nelts = CONSTRUCTOR_NELTS (expr);
2145 tree elt;
2146
2147 if (nelts == 0)
2148 elt = build_value_init (to, tf_none);
2149 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2150 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2151 else
2152 elt = error_mark_node;
2153
2154 conv = implicit_conversion (to, TREE_TYPE (elt), expr: elt,
2155 c_cast_p, flags, complain);
2156 if (conv)
2157 {
2158 conv->check_narrowing = true;
2159 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2160 /* Too many levels of braces, i.e. '{{1}}'. */
2161 conv->bad_p = true;
2162 return conv;
2163 }
2164 }
2165 else if (TREE_CODE (to) == ARRAY_TYPE)
2166 return build_array_conv (type: to, ctor: expr, flags, complain);
2167 }
2168
2169 if (expr != NULL_TREE
2170 && (MAYBE_CLASS_TYPE_P (from)
2171 || MAYBE_CLASS_TYPE_P (to))
2172 && (flags & LOOKUP_NO_CONVERSION) == 0)
2173 {
2174 struct z_candidate *cand;
2175
2176 if (CLASS_TYPE_P (to)
2177 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2178 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2179 return build_aggr_conv (type: to, ctor: expr, flags, complain);
2180
2181 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2182 if (cand)
2183 {
2184 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2185 && CONSTRUCTOR_NELTS (expr) == 1
2186 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2187 && !is_list_ctor (cand->fn))
2188 {
2189 /* "If C is not an initializer-list constructor and the
2190 initializer list has a single element of type cv U, where U is
2191 X or a class derived from X, the implicit conversion sequence
2192 has Exact Match rank if U is X, or Conversion rank if U is
2193 derived from X." */
2194 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2195 tree elttype = TREE_TYPE (elt);
2196 if (reference_related_p (t1: to, t2: elttype))
2197 return implicit_conversion (to, from: elttype, expr: elt,
2198 c_cast_p, flags, complain);
2199 }
2200 conv = cand->second_conv;
2201 }
2202
2203 /* We used to try to bind a reference to a temporary here, but that
2204 is now handled after the recursive call to this function at the end
2205 of reference_binding. */
2206 return conv;
2207 }
2208
2209 return NULL;
2210}
2211
2212/* Like implicit_conversion, but return NULL if the conversion is bad.
2213
2214 This is not static so that check_non_deducible_conversion can call it within
2215 add_template_candidate_real as part of overload resolution; it should not be
2216 called outside of overload resolution. */
2217
2218conversion *
2219good_conversion (tree to, tree from, tree expr,
2220 int flags, tsubst_flags_t complain)
2221{
2222 conversion *c = implicit_conversion (to, from, expr, /*cast*/c_cast_p: false,
2223 flags, complain);
2224 if (c && c->bad_p)
2225 c = NULL;
2226 return c;
2227}
2228
2229/* Add a new entry to the list of candidates. Used by the add_*_candidate
2230 functions. ARGS will not be changed until a single candidate is
2231 selected. */
2232
2233static struct z_candidate *
2234add_candidate (struct z_candidate **candidates,
2235 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2236 size_t num_convs, conversion **convs,
2237 tree access_path, tree conversion_path,
2238 int viable, struct rejection_reason *reason,
2239 int flags)
2240{
2241 struct z_candidate *cand = (struct z_candidate *)
2242 conversion_obstack_alloc (n: sizeof (struct z_candidate));
2243
2244 cand->fn = fn;
2245 cand->first_arg = first_arg;
2246 cand->args = args;
2247 cand->convs = convs;
2248 cand->num_convs = num_convs;
2249 cand->access_path = access_path;
2250 cand->conversion_path = conversion_path;
2251 cand->viable = viable;
2252 cand->reason = reason;
2253 cand->next = *candidates;
2254 cand->flags = flags;
2255 *candidates = cand;
2256
2257 if (convs && cand->reversed ())
2258 /* Swap the conversions for comparison in joust; we'll swap them back
2259 before build_over_call. */
2260 std::swap (a&: convs[0], b&: convs[1]);
2261
2262 return cand;
2263}
2264
2265/* FN is a function from the overload set that we outright didn't even
2266 consider (for some reason); add it to the list as an non-viable "ignored"
2267 candidate. */
2268
2269static z_candidate *
2270add_ignored_candidate (z_candidate **candidates, tree fn)
2271{
2272 /* No need to dynamically allocate these. */
2273 static const rejection_reason reason_ignored = { .code: rr_ignored, .u: {} };
2274
2275 struct z_candidate *cand = (struct z_candidate *)
2276 conversion_obstack_alloc (n: sizeof (struct z_candidate));
2277
2278 cand->fn = fn;
2279 cand->reason = const_cast<rejection_reason *> (&reason_ignored);
2280 cand->next = *candidates;
2281 *candidates = cand;
2282
2283 return cand;
2284}
2285
2286/* True iff CAND is a candidate added by add_ignored_candidate. */
2287
2288static bool
2289ignored_candidate_p (const z_candidate *cand)
2290{
2291 return cand->reason && cand->reason->code == rr_ignored;
2292}
2293
2294/* Return the number of remaining arguments in the parameter list
2295 beginning with ARG. */
2296
2297int
2298remaining_arguments (tree arg)
2299{
2300 int n;
2301
2302 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2303 arg = TREE_CHAIN (arg))
2304 n++;
2305
2306 return n;
2307}
2308
2309/* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2310 to the first parameter of a constructor where the parameter is of type
2311 "reference to possibly cv-qualified T" and the constructor is called with a
2312 single argument in the context of direct-initialization of an object of type
2313 "cv2 T", explicit conversion functions are also considered.
2314
2315 So set LOOKUP_COPY_PARM to let reference_binding know that
2316 it's being called in that context. */
2317
2318int
2319conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2320{
2321 int lflags = flags;
2322 tree t;
2323 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2324 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2325 && (same_type_ignoring_top_level_qualifiers_p
2326 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2327 {
2328 if (!(flags & LOOKUP_ONLYCONVERTING))
2329 lflags |= LOOKUP_COPY_PARM;
2330 if ((flags & LOOKUP_LIST_INIT_CTOR)
2331 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2332 lflags |= LOOKUP_NO_CONVERSION;
2333 }
2334 else
2335 lflags |= LOOKUP_ONLYCONVERTING;
2336
2337 return lflags;
2338}
2339
2340/* Build an appropriate 'this' conversion for the method FN and class
2341 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2342 This function modifies PARMTYPE, ARGTYPE and ARG. */
2343
2344static conversion *
2345build_this_conversion (tree fn, tree ctype,
2346 tree& parmtype, tree& argtype, tree& arg,
2347 int flags, tsubst_flags_t complain)
2348{
2349 gcc_assert (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2350 && !DECL_CONSTRUCTOR_P (fn));
2351
2352 /* The type of the implicit object parameter ('this') for
2353 overload resolution is not always the same as for the
2354 function itself; conversion functions are considered to
2355 be members of the class being converted, and functions
2356 introduced by a using-declaration are considered to be
2357 members of the class that uses them.
2358
2359 Since build_over_call ignores the ICS for the `this'
2360 parameter, we can just change the parm type. */
2361 parmtype = cp_build_qualified_type (ctype,
2362 cp_type_quals (TREE_TYPE (parmtype)));
2363 bool this_p = true;
2364 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2365 {
2366 /* If the function has a ref-qualifier, the implicit
2367 object parameter has reference type. */
2368 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2369 parmtype = cp_build_reference_type (parmtype, rv);
2370 /* The special handling of 'this' conversions in compare_ics
2371 does not apply if there is a ref-qualifier. */
2372 this_p = false;
2373 }
2374 else
2375 {
2376 parmtype = build_pointer_type (parmtype);
2377 /* We don't use build_this here because we don't want to
2378 capture the object argument until we've chosen a
2379 non-static member function. */
2380 arg = build_address (arg);
2381 argtype = lvalue_type (arg);
2382 }
2383 flags |= LOOKUP_ONLYCONVERTING;
2384 conversion *t = implicit_conversion (to: parmtype, from: argtype, expr: arg,
2385 /*c_cast_p=*/false, flags, complain);
2386 t->this_p = this_p;
2387 return t;
2388}
2389
2390/* Create an overload candidate for the function or method FN called
2391 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2392 FLAGS is passed on to implicit_conversion.
2393
2394 This does not change ARGS.
2395
2396 CTYPE, if non-NULL, is the type we want to pretend this function
2397 comes from for purposes of overload resolution.
2398
2399 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2400 If true, we stop computing conversions upon seeing the first bad
2401 conversion. This is used by add_candidates to avoid computing
2402 more conversions than necessary in the presence of a strictly viable
2403 candidate, while preserving the defacto behavior of overload resolution
2404 when it turns out there are only non-strictly viable candidates. */
2405
2406static struct z_candidate *
2407add_function_candidate (struct z_candidate **candidates,
2408 tree fn, tree ctype, tree first_arg,
2409 const vec<tree, va_gc> *args, tree access_path,
2410 tree conversion_path, int flags,
2411 conversion **convs,
2412 bool shortcut_bad_convs,
2413 tsubst_flags_t complain)
2414{
2415 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2416 int i, len;
2417 tree parmnode;
2418 tree orig_first_arg = first_arg;
2419 int skip;
2420 int viable = 1;
2421 struct rejection_reason *reason = NULL;
2422
2423 /* The `this', `in_chrg' and VTT arguments to constructors are not
2424 considered in overload resolution. */
2425 if (DECL_CONSTRUCTOR_P (fn))
2426 {
2427 if (ctor_omit_inherited_parms (fn))
2428 /* Bring back parameters omitted from an inherited ctor. */
2429 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2430 else
2431 parmlist = skip_artificial_parms_for (fn, parmlist);
2432 skip = num_artificial_parms_for (fn);
2433 if (skip > 0 && first_arg != NULL_TREE)
2434 {
2435 --skip;
2436 first_arg = NULL_TREE;
2437 }
2438 }
2439 else
2440 skip = 0;
2441
2442 len = vec_safe_length (v: args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2443 if (!convs)
2444 convs = alloc_conversions (n: len);
2445
2446 /* 13.3.2 - Viable functions [over.match.viable]
2447 First, to be a viable function, a candidate function shall have enough
2448 parameters to agree in number with the arguments in the list.
2449
2450 We need to check this first; otherwise, checking the ICSes might cause
2451 us to produce an ill-formed template instantiation. */
2452
2453 parmnode = parmlist;
2454 for (i = 0; i < len; ++i)
2455 {
2456 if (parmnode == NULL_TREE || parmnode == void_list_node)
2457 break;
2458 parmnode = TREE_CHAIN (parmnode);
2459 }
2460
2461 if ((i < len && parmnode)
2462 || !sufficient_parms_p (parmlist: parmnode))
2463 {
2464 int remaining = remaining_arguments (arg: parmnode);
2465 viable = 0;
2466 reason = arity_rejection (first_arg, expected: i + remaining, actual: len);
2467 }
2468
2469 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2470 parameter of type "reference to cv C" (including such a constructor
2471 instantiated from a template) is excluded from the set of candidate
2472 functions when used to construct an object of type D with an argument list
2473 containing a single argument if C is reference-related to D. */
2474 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2475 && flag_new_inheriting_ctors
2476 && DECL_INHERITED_CTOR (fn))
2477 {
2478 tree ptype = non_reference (TREE_VALUE (parmlist));
2479 tree dtype = DECL_CONTEXT (fn);
2480 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2481 if (reference_related_p (t1: ptype, t2: dtype)
2482 && reference_related_p (t1: btype, t2: ptype))
2483 {
2484 viable = false;
2485 reason = inherited_ctor_rejection ();
2486 }
2487 }
2488
2489 /* Second, for a function to be viable, its constraints must be
2490 satisfied. */
2491 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2492 {
2493 reason = constraint_failure ();
2494 viable = false;
2495 }
2496
2497 /* When looking for a function from a subobject from an implicit
2498 copy/move constructor/operator=, don't consider anything that takes (a
2499 reference to) an unrelated type. See c++/44909 and core 1092. */
2500 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2501 {
2502 if (DECL_CONSTRUCTOR_P (fn))
2503 i = 1;
2504 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2505 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2506 i = 2;
2507 else
2508 i = 0;
2509 if (i && len == i)
2510 {
2511 parmnode = chain_index (i-1, parmlist);
2512 if (!reference_related_p (t1: non_reference (TREE_VALUE (parmnode)),
2513 t2: ctype))
2514 viable = 0;
2515 }
2516
2517 /* This only applies at the top level. */
2518 flags &= ~LOOKUP_DEFAULTED;
2519 }
2520
2521 if (! viable)
2522 goto out;
2523
2524 if (shortcut_bad_convs)
2525 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2526 else
2527 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2528
2529 /* Third, for F to be a viable function, there shall exist for each
2530 argument an implicit conversion sequence that converts that argument
2531 to the corresponding parameter of F. */
2532
2533 parmnode = parmlist;
2534
2535 for (i = 0; i < len; ++i)
2536 {
2537 tree argtype, to_type;
2538 tree arg;
2539
2540 if (parmnode == void_list_node)
2541 break;
2542
2543 if (convs[i])
2544 {
2545 /* Already set during deduction. */
2546 parmnode = TREE_CHAIN (parmnode);
2547 continue;
2548 }
2549
2550 if (i == 0 && first_arg != NULL_TREE)
2551 arg = first_arg;
2552 else
2553 arg = CONST_CAST_TREE (
2554 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2555 argtype = lvalue_type (arg);
2556
2557 conversion *t;
2558 if (parmnode)
2559 {
2560 tree parmtype = TREE_VALUE (parmnode);
2561 if (i == 0
2562 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2563 && !DECL_CONSTRUCTOR_P (fn))
2564 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2565 flags, complain);
2566 else
2567 {
2568 int lflags = conv_flags (i, nargs: len-skip, fn, arg, flags);
2569 t = implicit_conversion (to: parmtype, from: argtype, expr: arg,
2570 /*c_cast_p=*/false, flags: lflags, complain);
2571 }
2572 to_type = parmtype;
2573 parmnode = TREE_CHAIN (parmnode);
2574 }
2575 else
2576 {
2577 t = build_identity_conv (type: argtype, expr: arg);
2578 t->ellipsis_p = true;
2579 to_type = argtype;
2580 }
2581
2582 convs[i] = t;
2583 if (! t)
2584 {
2585 viable = 0;
2586 reason = arg_conversion_rejection (first_arg, n_arg: i, from: argtype, to: to_type,
2587 EXPR_LOCATION (arg));
2588 break;
2589 }
2590
2591 if (t->bad_p)
2592 {
2593 viable = -1;
2594 reason = bad_arg_conversion_rejection (first_arg, n_arg: i, from: arg, to: to_type,
2595 EXPR_LOCATION (arg));
2596 if (shortcut_bad_convs)
2597 break;
2598 }
2599 }
2600
2601 out:
2602 return add_candidate (candidates, fn, first_arg: orig_first_arg, args, num_convs: len, convs,
2603 access_path, conversion_path, viable, reason, flags);
2604}
2605
2606/* Create an overload candidate for the conversion function FN which will
2607 be invoked for expression OBJ, producing a pointer-to-function which
2608 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2609 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2610 passed on to implicit_conversion.
2611
2612 Actually, we don't really care about FN; we care about the type it
2613 converts to. There may be multiple conversion functions that will
2614 convert to that type, and we rely on build_user_type_conversion_1 to
2615 choose the best one; so when we create our candidate, we record the type
2616 instead of the function. */
2617
2618static struct z_candidate *
2619add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2620 const vec<tree, va_gc> *arglist,
2621 tree access_path, tree conversion_path,
2622 tsubst_flags_t complain)
2623{
2624 tree totype = TREE_TYPE (TREE_TYPE (fn));
2625 int i, len, viable, flags;
2626 tree parmlist, parmnode;
2627 conversion **convs;
2628 struct rejection_reason *reason;
2629
2630 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2631 parmlist = TREE_TYPE (parmlist);
2632 parmlist = TYPE_ARG_TYPES (parmlist);
2633
2634 len = vec_safe_length (v: arglist) + 1;
2635 convs = alloc_conversions (n: len);
2636 parmnode = parmlist;
2637 viable = 1;
2638 flags = LOOKUP_IMPLICIT;
2639 reason = NULL;
2640
2641 /* Don't bother looking up the same type twice. */
2642 if (*candidates && (*candidates)->fn == totype)
2643 return NULL;
2644
2645 if (!constraints_satisfied_p (fn))
2646 {
2647 reason = constraint_failure ();
2648 viable = 0;
2649 return add_candidate (candidates, fn, first_arg: obj, args: arglist, num_convs: len, convs,
2650 access_path, conversion_path, viable, reason, flags);
2651 }
2652
2653 for (i = 0; i < len; ++i)
2654 {
2655 tree arg, argtype, convert_type = NULL_TREE;
2656 conversion *t;
2657
2658 if (i == 0)
2659 arg = obj;
2660 else
2661 arg = (*arglist)[i - 1];
2662 argtype = lvalue_type (arg);
2663
2664 if (i == 0)
2665 {
2666 t = build_identity_conv (type: argtype, NULL_TREE);
2667 t = build_conv (code: ck_user, type: totype, from: t);
2668 /* Leave the 'cand' field null; we'll figure out the conversion in
2669 convert_like if this candidate is chosen. */
2670 convert_type = totype;
2671 }
2672 else if (parmnode == void_list_node)
2673 break;
2674 else if (parmnode)
2675 {
2676 t = implicit_conversion (TREE_VALUE (parmnode), from: argtype, expr: arg,
2677 /*c_cast_p=*/false, flags, complain);
2678 convert_type = TREE_VALUE (parmnode);
2679 }
2680 else
2681 {
2682 t = build_identity_conv (type: argtype, expr: arg);
2683 t->ellipsis_p = true;
2684 convert_type = argtype;
2685 }
2686
2687 convs[i] = t;
2688 if (! t)
2689 break;
2690
2691 if (t->bad_p)
2692 {
2693 viable = -1;
2694 reason = bad_arg_conversion_rejection (NULL_TREE, n_arg: i, from: arg, to: convert_type,
2695 EXPR_LOCATION (arg));
2696 }
2697
2698 if (i == 0)
2699 continue;
2700
2701 if (parmnode)
2702 parmnode = TREE_CHAIN (parmnode);
2703 }
2704
2705 if (i < len
2706 || ! sufficient_parms_p (parmlist: parmnode))
2707 {
2708 int remaining = remaining_arguments (arg: parmnode);
2709 viable = 0;
2710 reason = arity_rejection (NULL_TREE, expected: i + remaining, actual: len);
2711 }
2712
2713 return add_candidate (candidates, fn: totype, first_arg: obj, args: arglist, num_convs: len, convs,
2714 access_path, conversion_path, viable, reason, flags);
2715}
2716
2717static void
2718build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2719 tree type1, tree type2, const vec<tree,va_gc> &args,
2720 tree *argtypes, int flags, tsubst_flags_t complain)
2721{
2722 conversion *t;
2723 conversion **convs;
2724 size_t num_convs;
2725 int viable = 1;
2726 tree types[2];
2727 struct rejection_reason *reason = NULL;
2728
2729 types[0] = type1;
2730 types[1] = type2;
2731
2732 num_convs = args.length ();
2733 convs = alloc_conversions (n: num_convs);
2734
2735 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2736 conversion ops are allowed. We handle that here by just checking for
2737 boolean_type_node because other operators don't ask for it. COND_EXPR
2738 also does contextual conversion to bool for the first operand, but we
2739 handle that in build_conditional_expr, and type1 here is operand 2. */
2740 if (type1 != boolean_type_node)
2741 flags |= LOOKUP_ONLYCONVERTING;
2742
2743 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2744 {
2745 t = implicit_conversion (to: types[i], from: argtypes[i], expr: args[i],
2746 /*c_cast_p=*/false, flags, complain);
2747 if (! t)
2748 {
2749 viable = 0;
2750 /* We need something for printing the candidate. */
2751 t = build_identity_conv (type: types[i], NULL_TREE);
2752 reason = arg_conversion_rejection (NULL_TREE, n_arg: i, from: argtypes[i],
2753 to: types[i], EXPR_LOCATION (args[i]));
2754 }
2755 else if (t->bad_p)
2756 {
2757 viable = 0;
2758 reason = bad_arg_conversion_rejection (NULL_TREE, n_arg: i, from: args[i],
2759 to: types[i],
2760 EXPR_LOCATION (args[i]));
2761 }
2762 convs[i] = t;
2763 }
2764
2765 /* For COND_EXPR we rearranged the arguments; undo that now. */
2766 if (num_convs == 3)
2767 {
2768 convs[2] = convs[1];
2769 convs[1] = convs[0];
2770 t = implicit_conversion (boolean_type_node, from: argtypes[2], expr: args[2],
2771 /*c_cast_p=*/false, flags,
2772 complain);
2773 if (t)
2774 convs[0] = t;
2775 else
2776 {
2777 viable = 0;
2778 reason = arg_conversion_rejection (NULL_TREE, n_arg: 0, from: argtypes[2],
2779 boolean_type_node,
2780 EXPR_LOCATION (args[2]));
2781 }
2782 }
2783
2784 add_candidate (candidates, fn: fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2785 num_convs, convs,
2786 /*access_path=*/NULL_TREE,
2787 /*conversion_path=*/NULL_TREE,
2788 viable, reason, flags);
2789}
2790
2791static bool
2792is_complete (tree t)
2793{
2794 return COMPLETE_TYPE_P (complete_type (t));
2795}
2796
2797/* Returns nonzero if TYPE is a promoted arithmetic type. */
2798
2799static bool
2800promoted_arithmetic_type_p (tree type)
2801{
2802 /* [over.built]
2803
2804 In this section, the term promoted integral type is used to refer
2805 to those integral types which are preserved by integral promotion
2806 (including e.g. int and long but excluding e.g. char).
2807 Similarly, the term promoted arithmetic type refers to promoted
2808 integral types plus floating types. */
2809 return ((CP_INTEGRAL_TYPE_P (type)
2810 && same_type_p (type_promotes_to (type), type))
2811 || SCALAR_FLOAT_TYPE_P (type));
2812}
2813
2814/* Create any builtin operator overload candidates for the operator in
2815 question given the converted operand types TYPE1 and TYPE2. The other
2816 args are passed through from add_builtin_candidates to
2817 build_builtin_candidate.
2818
2819 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2820 If CODE is requires candidates operands of the same type of the kind
2821 of which TYPE1 and TYPE2 are, we add both candidates
2822 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2823
2824static void
2825add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2826 enum tree_code code2, tree fnname, tree type1,
2827 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2828 int flags, tsubst_flags_t complain)
2829{
2830 switch (code)
2831 {
2832 case POSTINCREMENT_EXPR:
2833 case POSTDECREMENT_EXPR:
2834 args[1] = integer_zero_node;
2835 type2 = integer_type_node;
2836 break;
2837 default:
2838 break;
2839 }
2840
2841 switch (code)
2842 {
2843
2844/* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2845 and VQ is either volatile or empty, there exist candidate operator
2846 functions of the form
2847 VQ T& operator++(VQ T&);
2848 T operator++(VQ T&, int);
2849 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2850 and VQ is either volatile or empty, there exist candidate operator
2851 functions of the form
2852 VQ T& operator--(VQ T&);
2853 T operator--(VQ T&, int);
2854 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2855 type, and VQ is either volatile or empty, there exist candidate operator
2856 functions of the form
2857 T*VQ& operator++(T*VQ&);
2858 T*VQ& operator--(T*VQ&);
2859 T* operator++(T*VQ&, int);
2860 T* operator--(T*VQ&, int); */
2861
2862 case POSTDECREMENT_EXPR:
2863 case PREDECREMENT_EXPR:
2864 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2865 return;
2866 /* FALLTHRU */
2867 case POSTINCREMENT_EXPR:
2868 case PREINCREMENT_EXPR:
2869 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2870 to p4. */
2871 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2872 return;
2873 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2874 {
2875 type1 = build_reference_type (type1);
2876 break;
2877 }
2878 return;
2879
2880/* 7 For every cv-qualified or cv-unqualified object type T, there
2881 exist candidate operator functions of the form
2882
2883 T& operator*(T*);
2884
2885
2886 8 For every function type T that does not have cv-qualifiers or
2887 a ref-qualifier, there exist candidate operator functions of the form
2888 T& operator*(T*); */
2889
2890 case INDIRECT_REF:
2891 if (TYPE_PTR_P (type1)
2892 && (TYPE_PTROB_P (type1)
2893 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2894 break;
2895 return;
2896
2897/* 9 For every type T, there exist candidate operator functions of the form
2898 T* operator+(T*);
2899
2900 10 For every floating-point or promoted integral type T, there exist
2901 candidate operator functions of the form
2902 T operator+(T);
2903 T operator-(T); */
2904
2905 case UNARY_PLUS_EXPR: /* unary + */
2906 if (TYPE_PTR_P (type1))
2907 break;
2908 /* FALLTHRU */
2909 case NEGATE_EXPR:
2910 if (ARITHMETIC_TYPE_P (type1))
2911 break;
2912 return;
2913
2914/* 11 For every promoted integral type T, there exist candidate operator
2915 functions of the form
2916 T operator~(T); */
2917
2918 case BIT_NOT_EXPR:
2919 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2920 break;
2921 return;
2922
2923/* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2924 is the same type as C2 or is a derived class of C2, and T is an object
2925 type or a function type there exist candidate operator functions of the
2926 form
2927 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2928 where CV12 is the union of CV1 and CV2. */
2929
2930 case MEMBER_REF:
2931 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2932 {
2933 tree c1 = TREE_TYPE (type1);
2934 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2935
2936 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2937 && (TYPE_PTRMEMFUNC_P (type2)
2938 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2939 break;
2940 }
2941 return;
2942
2943/* 13 For every pair of types L and R, where each of L and R is a floating-point
2944 or promoted integral type, there exist candidate operator functions of the
2945 form
2946 LR operator*(L, R);
2947 LR operator/(L, R);
2948 LR operator+(L, R);
2949 LR operator-(L, R);
2950 bool operator<(L, R);
2951 bool operator>(L, R);
2952 bool operator<=(L, R);
2953 bool operator>=(L, R);
2954 bool operator==(L, R);
2955 bool operator!=(L, R);
2956 where LR is the result of the usual arithmetic conversions between
2957 types L and R.
2958
2959 14 For every integral type T there exists a candidate operator function of
2960 the form
2961
2962 std::strong_ordering operator<=>(T, T);
2963
2964 15 For every pair of floating-point types L and R, there exists a candidate
2965 operator function of the form
2966
2967 std::partial_ordering operator<=>(L, R);
2968
2969 16 For every cv-qualified or cv-unqualified object type T there exist
2970 candidate operator functions of the form
2971 T* operator+(T*, std::ptrdiff_t);
2972 T& operator[](T*, std::ptrdiff_t);
2973 T* operator-(T*, std::ptrdiff_t);
2974 T* operator+(std::ptrdiff_t, T*);
2975 T& operator[](std::ptrdiff_t, T*);
2976
2977 17 For every T, where T is a pointer to object type, there exist candidate
2978 operator functions of the form
2979 std::ptrdiff_t operator-(T, T);
2980
2981 18 For every T, where T is an enumeration type or a pointer type, there
2982 exist candidate operator functions of the form
2983 bool operator<(T, T);
2984 bool operator>(T, T);
2985 bool operator<=(T, T);
2986 bool operator>=(T, T);
2987 bool operator==(T, T);
2988 bool operator!=(T, T);
2989 R operator<=>(T, T);
2990
2991 where R is the result type specified in [expr.spaceship].
2992
2993 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2994 there exist candidate operator functions of the form
2995 bool operator==(T, T);
2996 bool operator!=(T, T); */
2997
2998 case MINUS_EXPR:
2999 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
3000 break;
3001 if (TYPE_PTROB_P (type1)
3002 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3003 {
3004 type2 = ptrdiff_type_node;
3005 break;
3006 }
3007 /* FALLTHRU */
3008 case MULT_EXPR:
3009 case TRUNC_DIV_EXPR:
3010 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3011 break;
3012 return;
3013
3014 /* This isn't exactly what's specified above for operator<=>, but it's
3015 close enough. In particular, we don't care about the return type
3016 specified above; it doesn't participate in overload resolution and it
3017 doesn't affect the semantics of the built-in operator. */
3018 case SPACESHIP_EXPR:
3019 case EQ_EXPR:
3020 case NE_EXPR:
3021 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3022 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
3023 break;
3024 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
3025 break;
3026 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (t: args[1]))
3027 {
3028 type2 = type1;
3029 break;
3030 }
3031 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (t: args[0]))
3032 {
3033 type1 = type2;
3034 break;
3035 }
3036 /* Fall through. */
3037 case LT_EXPR:
3038 case GT_EXPR:
3039 case LE_EXPR:
3040 case GE_EXPR:
3041 case MAX_EXPR:
3042 case MIN_EXPR:
3043 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3044 break;
3045 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3046 break;
3047 if (TREE_CODE (type1) == ENUMERAL_TYPE
3048 && TREE_CODE (type2) == ENUMERAL_TYPE)
3049 break;
3050 if (TYPE_PTR_P (type1)
3051 && null_ptr_cst_p (t: args[1]))
3052 {
3053 type2 = type1;
3054 break;
3055 }
3056 if (null_ptr_cst_p (t: args[0])
3057 && TYPE_PTR_P (type2))
3058 {
3059 type1 = type2;
3060 break;
3061 }
3062 return;
3063
3064 case PLUS_EXPR:
3065 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3066 break;
3067 /* FALLTHRU */
3068 case ARRAY_REF:
3069 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3070 {
3071 type1 = ptrdiff_type_node;
3072 break;
3073 }
3074 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3075 {
3076 type2 = ptrdiff_type_node;
3077 break;
3078 }
3079 return;
3080
3081/* 18For every pair of promoted integral types L and R, there exist candi-
3082 date operator functions of the form
3083 LR operator%(L, R);
3084 LR operator&(L, R);
3085 LR operator^(L, R);
3086 LR operator|(L, R);
3087 L operator<<(L, R);
3088 L operator>>(L, R);
3089 where LR is the result of the usual arithmetic conversions between
3090 types L and R. */
3091
3092 case TRUNC_MOD_EXPR:
3093 case BIT_AND_EXPR:
3094 case BIT_IOR_EXPR:
3095 case BIT_XOR_EXPR:
3096 case LSHIFT_EXPR:
3097 case RSHIFT_EXPR:
3098 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3099 break;
3100 return;
3101
3102/* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3103 type, VQ is either volatile or empty, and R is a promoted arithmetic
3104 type, there exist candidate operator functions of the form
3105 VQ L& operator=(VQ L&, R);
3106 VQ L& operator*=(VQ L&, R);
3107 VQ L& operator/=(VQ L&, R);
3108 VQ L& operator+=(VQ L&, R);
3109 VQ L& operator-=(VQ L&, R);
3110
3111 20For every pair T, VQ), where T is any type and VQ is either volatile
3112 or empty, there exist candidate operator functions of the form
3113 T*VQ& operator=(T*VQ&, T*);
3114
3115 21For every pair T, VQ), where T is a pointer to member type and VQ is
3116 either volatile or empty, there exist candidate operator functions of
3117 the form
3118 VQ T& operator=(VQ T&, T);
3119
3120 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3121 unqualified complete object type, VQ is either volatile or empty, and
3122 I is a promoted integral type, there exist candidate operator func-
3123 tions of the form
3124 T*VQ& operator+=(T*VQ&, I);
3125 T*VQ& operator-=(T*VQ&, I);
3126
3127 23For every triple L, VQ, R), where L is an integral or enumeration
3128 type, VQ is either volatile or empty, and R is a promoted integral
3129 type, there exist candidate operator functions of the form
3130
3131 VQ L& operator%=(VQ L&, R);
3132 VQ L& operator<<=(VQ L&, R);
3133 VQ L& operator>>=(VQ L&, R);
3134 VQ L& operator&=(VQ L&, R);
3135 VQ L& operator^=(VQ L&, R);
3136 VQ L& operator|=(VQ L&, R); */
3137
3138 case MODIFY_EXPR:
3139 switch (code2)
3140 {
3141 case PLUS_EXPR:
3142 case MINUS_EXPR:
3143 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3144 {
3145 type2 = ptrdiff_type_node;
3146 break;
3147 }
3148 /* FALLTHRU */
3149 case MULT_EXPR:
3150 case TRUNC_DIV_EXPR:
3151 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3152 break;
3153 return;
3154
3155 case TRUNC_MOD_EXPR:
3156 case BIT_AND_EXPR:
3157 case BIT_IOR_EXPR:
3158 case BIT_XOR_EXPR:
3159 case LSHIFT_EXPR:
3160 case RSHIFT_EXPR:
3161 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3162 break;
3163 return;
3164
3165 case NOP_EXPR:
3166 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3167 break;
3168 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3169 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3170 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3171 || ((TYPE_PTRMEMFUNC_P (type1)
3172 || TYPE_PTR_P (type1))
3173 && null_ptr_cst_p (t: args[1])))
3174 {
3175 type2 = type1;
3176 break;
3177 }
3178 return;
3179
3180 default:
3181 gcc_unreachable ();
3182 }
3183 type1 = build_reference_type (type1);
3184 break;
3185
3186 case COND_EXPR:
3187 /* [over.built]
3188
3189 For every pair of promoted arithmetic types L and R, there
3190 exist candidate operator functions of the form
3191
3192 LR operator?(bool, L, R);
3193
3194 where LR is the result of the usual arithmetic conversions
3195 between types L and R.
3196
3197 For every type T, where T is a pointer or pointer-to-member
3198 type, there exist candidate operator functions of the form T
3199 operator?(bool, T, T); */
3200
3201 if (promoted_arithmetic_type_p (type: type1)
3202 && promoted_arithmetic_type_p (type: type2))
3203 /* That's OK. */
3204 break;
3205
3206 /* Otherwise, the types should be pointers. */
3207 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3208 return;
3209
3210 /* We don't check that the two types are the same; the logic
3211 below will actually create two candidates; one in which both
3212 parameter types are TYPE1, and one in which both parameter
3213 types are TYPE2. */
3214 break;
3215
3216 case REALPART_EXPR:
3217 case IMAGPART_EXPR:
3218 if (ARITHMETIC_TYPE_P (type1))
3219 break;
3220 return;
3221
3222 default:
3223 gcc_unreachable ();
3224 }
3225
3226 /* Make sure we don't create builtin candidates with dependent types. */
3227 bool u1 = uses_template_parms (type1);
3228 bool u2 = type2 ? uses_template_parms (type2) : false;
3229 if (u1 || u2)
3230 {
3231 /* Try to recover if one of the types is non-dependent. But if
3232 there's only one type, there's nothing we can do. */
3233 if (!type2)
3234 return;
3235 /* And we lose if both are dependent. */
3236 if (u1 && u2)
3237 return;
3238 /* Or if they have different forms. */
3239 if (TREE_CODE (type1) != TREE_CODE (type2))
3240 return;
3241
3242 if (u1 && !u2)
3243 type1 = type2;
3244 else if (u2 && !u1)
3245 type2 = type1;
3246 }
3247
3248 /* If we're dealing with two pointer types or two enumeral types,
3249 we need candidates for both of them. */
3250 if (type2 && !same_type_p (type1, type2)
3251 && TREE_CODE (type1) == TREE_CODE (type2)
3252 && (TYPE_REF_P (type1)
3253 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3254 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3255 || TYPE_PTRMEMFUNC_P (type1)
3256 || MAYBE_CLASS_TYPE_P (type1)
3257 || TREE_CODE (type1) == ENUMERAL_TYPE))
3258 {
3259 if (TYPE_PTR_OR_PTRMEM_P (type1))
3260 {
3261 tree cptype = composite_pointer_type (input_location,
3262 type1, type2,
3263 error_mark_node,
3264 error_mark_node,
3265 CPO_CONVERSION,
3266 tf_none);
3267 if (cptype != error_mark_node)
3268 {
3269 build_builtin_candidate
3270 (candidates, fnname, type1: cptype, type2: cptype, args, argtypes,
3271 flags, complain);
3272 return;
3273 }
3274 }
3275
3276 build_builtin_candidate
3277 (candidates, fnname, type1, type2: type1, args, argtypes, flags, complain);
3278 build_builtin_candidate
3279 (candidates, fnname, type1: type2, type2, args, argtypes, flags, complain);
3280 return;
3281 }
3282
3283 build_builtin_candidate
3284 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3285}
3286
3287tree
3288type_decays_to (tree type)
3289{
3290 if (TREE_CODE (type) == ARRAY_TYPE)
3291 return build_pointer_type (TREE_TYPE (type));
3292 if (TREE_CODE (type) == FUNCTION_TYPE)
3293 return build_pointer_type (type);
3294 return type;
3295}
3296
3297/* There are three conditions of builtin candidates:
3298
3299 1) bool-taking candidates. These are the same regardless of the input.
3300 2) pointer-pair taking candidates. These are generated for each type
3301 one of the input types converts to.
3302 3) arithmetic candidates. According to the standard, we should generate
3303 all of these, but I'm trying not to...
3304
3305 Here we generate a superset of the possible candidates for this particular
3306 case. That is a subset of the full set the standard defines, plus some
3307 other cases which the standard disallows. add_builtin_candidate will
3308 filter out the invalid set. */
3309
3310static void
3311add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3312 enum tree_code code2, tree fnname,
3313 vec<tree, va_gc> *argv,
3314 int flags, tsubst_flags_t complain)
3315{
3316 int ref1;
3317 int enum_p = 0;
3318 tree type, argtypes[3], t;
3319 /* TYPES[i] is the set of possible builtin-operator parameter types
3320 we will consider for the Ith argument. */
3321 vec<tree, va_gc> *types[2];
3322 unsigned ix;
3323 vec<tree, va_gc> &args = *argv;
3324 unsigned len = args.length ();
3325
3326 for (unsigned i = 0; i < len; ++i)
3327 {
3328 if (args[i])
3329 argtypes[i] = unlowered_expr_type (args[i]);
3330 else
3331 argtypes[i] = NULL_TREE;
3332 }
3333
3334 switch (code)
3335 {
3336/* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3337 and VQ is either volatile or empty, there exist candidate operator
3338 functions of the form
3339 VQ T& operator++(VQ T&); */
3340
3341 case POSTINCREMENT_EXPR:
3342 case PREINCREMENT_EXPR:
3343 case POSTDECREMENT_EXPR:
3344 case PREDECREMENT_EXPR:
3345 case MODIFY_EXPR:
3346 ref1 = 1;
3347 break;
3348
3349/* 24There also exist candidate operator functions of the form
3350 bool operator!(bool);
3351 bool operator&&(bool, bool);
3352 bool operator||(bool, bool); */
3353
3354 case TRUTH_NOT_EXPR:
3355 build_builtin_candidate
3356 (candidates, fnname, boolean_type_node,
3357 NULL_TREE, args, argtypes, flags, complain);
3358 return;
3359
3360 case TRUTH_ORIF_EXPR:
3361 case TRUTH_ANDIF_EXPR:
3362 build_builtin_candidate
3363 (candidates, fnname, boolean_type_node,
3364 boolean_type_node, args, argtypes, flags, complain);
3365 return;
3366
3367 case ADDR_EXPR:
3368 case COMPOUND_EXPR:
3369 case COMPONENT_REF:
3370 case CO_AWAIT_EXPR:
3371 return;
3372
3373 case COND_EXPR:
3374 case EQ_EXPR:
3375 case NE_EXPR:
3376 case LT_EXPR:
3377 case LE_EXPR:
3378 case GT_EXPR:
3379 case GE_EXPR:
3380 case SPACESHIP_EXPR:
3381 enum_p = 1;
3382 /* Fall through. */
3383
3384 default:
3385 ref1 = 0;
3386 }
3387
3388 types[0] = make_tree_vector ();
3389 types[1] = make_tree_vector ();
3390
3391 if (len == 3)
3392 len = 2;
3393 for (unsigned i = 0; i < len; ++i)
3394 {
3395 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3396 {
3397 tree convs;
3398
3399 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3400 return;
3401
3402 convs = lookup_conversions (argtypes[i]);
3403
3404 if (code == COND_EXPR)
3405 {
3406 if (lvalue_p (args[i]))
3407 vec_safe_push (v&: types[i], obj: build_reference_type (argtypes[i]));
3408
3409 vec_safe_push (v&: types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3410 }
3411
3412 else if (! convs)
3413 return;
3414
3415 for (; convs; convs = TREE_CHAIN (convs))
3416 {
3417 type = TREE_TYPE (convs);
3418
3419 if (i == 0 && ref1
3420 && (!TYPE_REF_P (type)
3421 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3422 continue;
3423
3424 if (code == COND_EXPR && TYPE_REF_P (type))
3425 vec_safe_push (v&: types[i], obj: type);
3426
3427 type = non_reference (type);
3428 if (i != 0 || ! ref1)
3429 {
3430 type = cv_unqualified (type_decays_to (type));
3431 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3432 vec_safe_push (v&: types[i], obj: type);
3433 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3434 type = type_promotes_to (type);
3435 }
3436
3437 if (! vec_member (type, types[i]))
3438 vec_safe_push (v&: types[i], obj: type);
3439 }
3440 }
3441 else
3442 {
3443 if (code == COND_EXPR && lvalue_p (args[i]))
3444 vec_safe_push (v&: types[i], obj: build_reference_type (argtypes[i]));
3445 type = non_reference (argtypes[i]);
3446 if (i != 0 || ! ref1)
3447 {
3448 type = cv_unqualified (type_decays_to (type));
3449 if (enum_p && UNSCOPED_ENUM_P (type))
3450 vec_safe_push (v&: types[i], obj: type);
3451 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3452 type = type_promotes_to (type);
3453 }
3454 vec_safe_push (v&: types[i], obj: type);
3455 }
3456 }
3457
3458 /* Run through the possible parameter types of both arguments,
3459 creating candidates with those parameter types. */
3460 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3461 {
3462 unsigned jx;
3463 tree u;
3464
3465 if (!types[1]->is_empty ())
3466 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3467 add_builtin_candidate
3468 (candidates, code, code2, fnname, type1: t,
3469 type2: u, args, argtypes, flags, complain);
3470 else
3471 add_builtin_candidate
3472 (candidates, code, code2, fnname, type1: t,
3473 NULL_TREE, args, argtypes, flags, complain);
3474 }
3475
3476 release_tree_vector (types[0]);
3477 release_tree_vector (types[1]);
3478}
3479
3480
3481/* If TMPL can be successfully instantiated as indicated by
3482 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3483
3484 TMPL is the template. EXPLICIT_TARGS are any explicit template
3485 arguments. ARGLIST is the arguments provided at the call-site.
3486 This does not change ARGLIST. The RETURN_TYPE is the desired type
3487 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3488 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3489 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3490
3491 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3492
3493static struct z_candidate*
3494add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3495 tree ctype, tree explicit_targs, tree first_arg,
3496 const vec<tree, va_gc> *arglist, tree return_type,
3497 tree access_path, tree conversion_path,
3498 int flags, tree obj, unification_kind_t strict,
3499 bool shortcut_bad_convs, tsubst_flags_t complain)
3500{
3501 int ntparms = DECL_NTPARMS (tmpl);
3502 tree targs = make_tree_vec (ntparms);
3503 unsigned int len = vec_safe_length (v: arglist);
3504 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3505 unsigned int skip_without_in_chrg = 0;
3506 tree first_arg_without_in_chrg = first_arg;
3507 tree *args_without_in_chrg;
3508 unsigned int nargs_without_in_chrg;
3509 unsigned int ia, ix;
3510 tree arg;
3511 struct z_candidate *cand;
3512 tree fn;
3513 struct rejection_reason *reason = NULL;
3514 int errs;
3515 conversion **convs = NULL;
3516
3517 /* We don't do deduction on the in-charge parameter, the VTT
3518 parameter or 'this'. */
3519 if (DECL_IOBJ_MEMBER_FUNCTION_P (tmpl))
3520 {
3521 if (first_arg_without_in_chrg != NULL_TREE)
3522 first_arg_without_in_chrg = NULL_TREE;
3523 else if (return_type && strict == DEDUCE_CALL)
3524 /* We're deducing for a call to the result of a template conversion
3525 function, so the args don't contain 'this'; leave them alone. */;
3526 else
3527 ++skip_without_in_chrg;
3528 }
3529
3530 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3531 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3532 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3533 {
3534 if (first_arg_without_in_chrg != NULL_TREE)
3535 first_arg_without_in_chrg = NULL_TREE;
3536 else
3537 ++skip_without_in_chrg;
3538 }
3539
3540 if (len < skip_without_in_chrg)
3541 return add_ignored_candidate (candidates, fn: tmpl);
3542
3543 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3544 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3545 TREE_TYPE ((*arglist)[0])))
3546 {
3547 /* 12.8/6 says, "A declaration of a constructor for a class X is
3548 ill-formed if its first parameter is of type (optionally cv-qualified)
3549 X and either there are no other parameters or else all other
3550 parameters have default arguments. A member function template is never
3551 instantiated to produce such a constructor signature."
3552
3553 So if we're trying to copy an object of the containing class, don't
3554 consider a template constructor that has a first parameter type that
3555 is just a template parameter, as we would deduce a signature that we
3556 would then reject in the code below. */
3557 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3558 {
3559 firstparm = TREE_VALUE (firstparm);
3560 if (PACK_EXPANSION_P (firstparm))
3561 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3562 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3563 {
3564 gcc_assert (!explicit_targs);
3565 reason = invalid_copy_with_fn_template_rejection ();
3566 goto fail;
3567 }
3568 }
3569 }
3570
3571 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3572 + (len - skip_without_in_chrg));
3573 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3574 ia = 0;
3575 if (first_arg_without_in_chrg != NULL_TREE)
3576 {
3577 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3578 ++ia;
3579 }
3580 for (ix = skip_without_in_chrg;
3581 vec_safe_iterate (v: arglist, ix, ptr: &arg);
3582 ++ix)
3583 {
3584 args_without_in_chrg[ia] = arg;
3585 ++ia;
3586 }
3587 gcc_assert (ia == nargs_without_in_chrg);
3588
3589 if (!obj)
3590 {
3591 /* Check that there's no obvious arity mismatch before proceeding with
3592 deduction. This avoids substituting explicit template arguments
3593 into the template or e.g. derived-to-base parm/arg unification
3594 (which could result in an error outside the immediate context) when
3595 the resulting candidate would be unviable anyway. */
3596 int min_arity = 0, max_arity = 0;
3597 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3598 parms = skip_artificial_parms_for (tmpl, parms);
3599 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3600 {
3601 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3602 {
3603 max_arity = -1;
3604 break;
3605 }
3606 if (TREE_PURPOSE (parms))
3607 /* A parameter with a default argument. */
3608 ++max_arity;
3609 else
3610 ++min_arity, ++max_arity;
3611 }
3612 if (ia < (unsigned)min_arity)
3613 {
3614 /* Too few arguments. */
3615 reason = arity_rejection (NULL_TREE, expected: min_arity, actual: ia,
3616 /*least_p=*/(max_arity == -1));
3617 goto fail;
3618 }
3619 else if (max_arity != -1 && ia > (unsigned)max_arity)
3620 {
3621 /* Too many arguments. */
3622 reason = arity_rejection (NULL_TREE, expected: max_arity, actual: ia);
3623 goto fail;
3624 }
3625
3626 convs = alloc_conversions (n: nargs);
3627
3628 if (shortcut_bad_convs
3629 && DECL_IOBJ_MEMBER_FUNCTION_P (tmpl)
3630 && !DECL_CONSTRUCTOR_P (tmpl))
3631 {
3632 /* Check the 'this' conversion before proceeding with deduction.
3633 This is effectively an extension of the DR 1391 resolution
3634 that we perform in check_non_deducible_conversions, though it's
3635 convenient to do this extra check here instead of there. */
3636 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3637 tree argtype = lvalue_type (first_arg);
3638 tree arg = first_arg;
3639 conversion *t = build_this_conversion (fn: tmpl, ctype,
3640 parmtype, argtype, arg,
3641 flags, complain);
3642 convs[0] = t;
3643 if (t->bad_p)
3644 {
3645 reason = bad_arg_conversion_rejection (first_arg, n_arg: 0,
3646 from: arg, to: parmtype,
3647 EXPR_LOCATION (arg));
3648 goto fail;
3649 }
3650 }
3651 }
3652
3653 errs = errorcount+sorrycount;
3654 fn = fn_type_unification (tmpl, explicit_targs, targs,
3655 args_without_in_chrg,
3656 nargs_without_in_chrg,
3657 return_type, strict, flags, convs,
3658 false, complain & tf_decltype);
3659
3660 if (fn == error_mark_node)
3661 {
3662 /* Don't repeat unification later if it already resulted in errors. */
3663 if (errorcount+sorrycount == errs)
3664 reason = template_unification_rejection (tmpl, explicit_targs,
3665 targs, args: args_without_in_chrg,
3666 nargs: nargs_without_in_chrg,
3667 return_type, strict, flags);
3668 else
3669 reason = template_unification_error_rejection ();
3670 goto fail;
3671 }
3672
3673 /* Now the explicit specifier might have been deduced; check if this
3674 declaration is explicit. If it is and we're ignoring non-converting
3675 constructors, don't add this function to the set of candidates. */
3676 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3677 == LOOKUP_ONLYCONVERTING)
3678 && DECL_NONCONVERTING_P (fn))
3679 return add_ignored_candidate (candidates, fn);
3680
3681 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3682 {
3683 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3684 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3685 ctype))
3686 {
3687 /* We're trying to produce a constructor with a prohibited signature,
3688 as discussed above; handle here any cases we didn't catch then,
3689 such as X(X<T>). */
3690 reason = invalid_copy_with_fn_template_rejection ();
3691 goto fail;
3692 }
3693 }
3694
3695 if (obj != NULL_TREE)
3696 /* Aha, this is a conversion function. */
3697 cand = add_conv_candidate (candidates, fn, obj, arglist,
3698 access_path, conversion_path, complain);
3699 else
3700 cand = add_function_candidate (candidates, fn, ctype,
3701 first_arg, args: arglist, access_path,
3702 conversion_path, flags, convs,
3703 shortcut_bad_convs, complain);
3704 if (DECL_TI_TEMPLATE (fn) != tmpl)
3705 /* This situation can occur if a member template of a template
3706 class is specialized. Then, instantiate_template might return
3707 an instantiation of the specialization, in which case the
3708 DECL_TI_TEMPLATE field will point at the original
3709 specialization. For example:
3710
3711 template <class T> struct S { template <class U> void f(U);
3712 template <> void f(int) {}; };
3713 S<double> sd;
3714 sd.f(3);
3715
3716 Here, TMPL will be template <class U> S<double>::f(U).
3717 And, instantiate template will give us the specialization
3718 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3719 for this will point at template <class T> template <> S<T>::f(int),
3720 so that we can find the definition. For the purposes of
3721 overload resolution, however, we want the original TMPL. */
3722 cand->template_decl = build_template_info (tmpl, targs);
3723 else
3724 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3725 cand->explicit_targs = explicit_targs;
3726
3727 return cand;
3728 fail:
3729 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3730 return add_candidate (candidates, fn: tmpl, first_arg, args: arglist, num_convs: nargs, convs,
3731 access_path, conversion_path, viable, reason, flags);
3732}
3733
3734
3735static struct z_candidate *
3736add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3737 tree explicit_targs, tree first_arg,
3738 const vec<tree, va_gc> *arglist, tree return_type,
3739 tree access_path, tree conversion_path, int flags,
3740 unification_kind_t strict, bool shortcut_bad_convs,
3741 tsubst_flags_t complain)
3742{
3743 return
3744 add_template_candidate_real (candidates, tmpl, ctype,
3745 explicit_targs, first_arg, arglist,
3746 return_type, access_path, conversion_path,
3747 flags, NULL_TREE, strict, shortcut_bad_convs,
3748 complain);
3749}
3750
3751/* Create an overload candidate for the conversion function template TMPL,
3752 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3753 pointer-to-function which will in turn be called with the argument list
3754 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3755 passed on to implicit_conversion. */
3756
3757static struct z_candidate *
3758add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3759 tree obj,
3760 const vec<tree, va_gc> *arglist,
3761 tree return_type, tree access_path,
3762 tree conversion_path, tsubst_flags_t complain)
3763{
3764 return
3765 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3766 NULL_TREE, arglist, return_type, access_path,
3767 conversion_path, flags: 0, obj, strict: DEDUCE_CALL,
3768 /*shortcut_bad_convs=*/false, complain);
3769}
3770
3771/* The CANDS are the set of candidates that were considered for
3772 overload resolution. Sort CANDS so that the strictly viable
3773 candidates appear first, followed by non-strictly viable candidates,
3774 followed by non-viable candidates. Returns the first candidate
3775 in this sorted list. If any of the candidates were viable, set
3776 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3777 considered viable only if it is strictly viable when setting
3778 *ANY_VIABLE_P. */
3779
3780static struct z_candidate*
3781splice_viable (struct z_candidate *cands,
3782 bool strict_p,
3783 bool *any_viable_p)
3784{
3785 z_candidate *strictly_viable = nullptr;
3786 z_candidate **strictly_viable_tail = &strictly_viable;
3787
3788 z_candidate *non_strictly_viable = nullptr;
3789 z_candidate **non_strictly_viable_tail = &non_strictly_viable;
3790
3791 z_candidate *non_viable = nullptr;
3792 z_candidate **non_viable_tail = &non_viable;
3793
3794 z_candidate *non_viable_ignored = nullptr;
3795 z_candidate **non_viable_ignored_tail = &non_viable_ignored;
3796
3797 /* Be strict inside templates, since build_over_call won't actually
3798 do the conversions to get pedwarns. */
3799 if (processing_template_decl)
3800 strict_p = true;
3801
3802 for (z_candidate *cand = cands; cand; cand = cand->next)
3803 {
3804 if (!strict_p
3805 && (cand->viable == 1 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
3806 /* Be strict in the presence of a viable candidate. Also if
3807 there are template candidates, so that we get deduction errors
3808 for them instead of silently preferring a bad conversion. */
3809 strict_p = true;
3810
3811 /* Move this candidate to the appropriate list according to
3812 its viability. */
3813 auto& tail = (cand->viable == 1 ? strictly_viable_tail
3814 : cand->viable == -1 ? non_strictly_viable_tail
3815 : ignored_candidate_p (cand) ? non_viable_ignored_tail
3816 : non_viable_tail);
3817 *tail = cand;
3818 tail = &cand->next;
3819 }
3820
3821 *any_viable_p = (strictly_viable != nullptr
3822 || (!strict_p && non_strictly_viable != nullptr));
3823
3824 /* Combine the lists. */
3825 *non_viable_ignored_tail = nullptr;
3826 *non_viable_tail = non_viable_ignored;
3827 *non_strictly_viable_tail = non_viable;
3828 *strictly_viable_tail = non_strictly_viable;
3829
3830 return strictly_viable;
3831}
3832
3833static bool
3834any_strictly_viable (struct z_candidate *cands)
3835{
3836 for (; cands; cands = cands->next)
3837 if (cands->viable == 1)
3838 return true;
3839 return false;
3840}
3841
3842/* OBJ is being used in an expression like "OBJ.f (...)". In other
3843 words, it is about to become the "this" pointer for a member
3844 function call. Take the address of the object. */
3845
3846static tree
3847build_this (tree obj)
3848{
3849 /* In a template, we are only concerned about the type of the
3850 expression, so we can take a shortcut. */
3851 if (processing_template_decl)
3852 return build_address (obj);
3853
3854 return cp_build_addr_expr (obj, tf_warning_or_error);
3855}
3856
3857/* Returns true iff functions are equivalent. Equivalent functions are
3858 not '==' only if one is a function-local extern function or if
3859 both are extern "C". */
3860
3861static inline int
3862equal_functions (tree fn1, tree fn2)
3863{
3864 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3865 return 0;
3866 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3867 return fn1 == fn2;
3868 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3869 || DECL_EXTERN_C_FUNCTION_P (fn1))
3870 return decls_match (fn1, fn2);
3871 return fn1 == fn2;
3872}
3873
3874/* Print information about a candidate FN being rejected due to INFO. */
3875
3876static void
3877print_conversion_rejection (location_t loc, struct conversion_info *info,
3878 tree fn)
3879{
3880 tree from = info->from;
3881 if (!TYPE_P (from))
3882 from = lvalue_type (from);
3883 if (info->n_arg == -1)
3884 {
3885 /* Conversion of implicit `this' argument failed. */
3886 if (!TYPE_P (info->from))
3887 /* A bad conversion for 'this' must be discarding cv-quals. */
3888 inform (loc, " passing %qT as %<this%> "
3889 "argument discards qualifiers",
3890 from);
3891 else
3892 inform (loc, " no known conversion for implicit "
3893 "%<this%> parameter from %qH to %qI",
3894 from, info->to_type);
3895 }
3896 else if (!TYPE_P (info->from))
3897 {
3898 if (info->n_arg >= 0)
3899 inform (loc, " conversion of argument %d would be ill-formed:",
3900 info->n_arg + 1);
3901 iloc_sentinel ils = loc;
3902 perform_implicit_conversion (info->to_type, info->from,
3903 tf_warning_or_error);
3904 }
3905 else if (info->n_arg == -2)
3906 /* Conversion of conversion function return value failed. */
3907 inform (loc, " no known conversion from %qH to %qI",
3908 from, info->to_type);
3909 else
3910 {
3911 if (TREE_CODE (fn) == FUNCTION_DECL)
3912 loc = get_fndecl_argument_location (fn, info->n_arg);
3913 inform (loc, " no known conversion for argument %d from %qH to %qI",
3914 info->n_arg + 1, from, info->to_type);
3915 }
3916}
3917
3918/* Print information about a candidate with WANT parameters and we found
3919 HAVE. */
3920
3921static void
3922print_arity_information (location_t loc, unsigned int have, unsigned int want,
3923 bool least_p)
3924{
3925 if (least_p)
3926 inform_n (loc, want,
3927 " candidate expects at least %d argument, %d provided",
3928 " candidate expects at least %d arguments, %d provided",
3929 want, have);
3930 else
3931 inform_n (loc, want,
3932 " candidate expects %d argument, %d provided",
3933 " candidate expects %d arguments, %d provided",
3934 want, have);
3935}
3936
3937/* Print information about one overload candidate CANDIDATE. MSGSTR
3938 is the text to print before the candidate itself.
3939
3940 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3941 to have been run through gettext by the caller. This wart makes
3942 life simpler in print_z_candidates and for the translators. */
3943
3944static void
3945print_z_candidate (location_t loc, const char *msgstr,
3946 struct z_candidate *candidate)
3947{
3948 const char *msg = (msgstr == NULL
3949 ? ""
3950 : ACONCAT ((_(msgstr), " ", NULL)));
3951 tree fn = candidate->fn;
3952 if (flag_new_inheriting_ctors)
3953 fn = strip_inheriting_ctors (fn);
3954 location_t cloc = location_of (fn);
3955
3956 if (identifier_p (t: fn))
3957 {
3958 cloc = loc;
3959 if (candidate->num_convs == 3)
3960 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3961 candidate->convs[0]->type,
3962 candidate->convs[1]->type,
3963 candidate->convs[2]->type);
3964 else if (candidate->num_convs == 2)
3965 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3966 candidate->convs[0]->type,
3967 candidate->convs[1]->type);
3968 else
3969 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3970 candidate->convs[0]->type);
3971 }
3972 else if (TYPE_P (fn))
3973 inform (cloc, "%s%qT (conversion)", msg, fn);
3974 else if (candidate->viable == -1)
3975 inform (cloc, "%s%#qD (near match)", msg, fn);
3976 else if (ignored_candidate_p (cand: candidate))
3977 inform (cloc, "%s%#qD (ignored)", msg, fn);
3978 else if (DECL_DELETED_FN (fn))
3979 inform (cloc, "%s%#qD (deleted)", msg, fn);
3980 else if (candidate->reversed ())
3981 inform (cloc, "%s%#qD (reversed)", msg, fn);
3982 else if (candidate->rewritten ())
3983 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3984 else
3985 inform (cloc, "%s%#qD", msg, fn);
3986 if (fn != candidate->fn)
3987 {
3988 cloc = location_of (candidate->fn);
3989 inform (cloc, " inherited here");
3990 }
3991 /* Give the user some information about why this candidate failed. */
3992 if (candidate->reason != NULL)
3993 {
3994 struct rejection_reason *r = candidate->reason;
3995
3996 switch (r->code)
3997 {
3998 case rr_arity:
3999 print_arity_information (loc: cloc, have: r->u.arity.actual,
4000 want: r->u.arity.expected,
4001 least_p: r->u.arity.least_p);
4002 break;
4003 case rr_arg_conversion:
4004 print_conversion_rejection (loc: cloc, info: &r->u.conversion, fn);
4005 break;
4006 case rr_bad_arg_conversion:
4007 print_conversion_rejection (loc: cloc, info: &r->u.bad_conversion, fn);
4008 break;
4009 case rr_explicit_conversion:
4010 inform (cloc, " return type %qT of explicit conversion function "
4011 "cannot be converted to %qT with a qualification "
4012 "conversion", r->u.conversion.from,
4013 r->u.conversion.to_type);
4014 break;
4015 case rr_template_conversion:
4016 inform (cloc, " conversion from return type %qT of template "
4017 "conversion function specialization to %qT is not an "
4018 "exact match", r->u.conversion.from,
4019 r->u.conversion.to_type);
4020 break;
4021 case rr_template_unification:
4022 /* We use template_unification_error_rejection if unification caused
4023 actual non-SFINAE errors, in which case we don't need to repeat
4024 them here. */
4025 if (r->u.template_unification.tmpl == NULL_TREE)
4026 {
4027 inform (cloc, " substitution of deduced template arguments "
4028 "resulted in errors seen above");
4029 break;
4030 }
4031 /* Re-run template unification with diagnostics. */
4032 inform (cloc, " template argument deduction/substitution failed:");
4033 fn_type_unification (r->u.template_unification.tmpl,
4034 r->u.template_unification.explicit_targs,
4035 (make_tree_vec
4036 (r->u.template_unification.num_targs)),
4037 r->u.template_unification.args,
4038 r->u.template_unification.nargs,
4039 r->u.template_unification.return_type,
4040 r->u.template_unification.strict,
4041 r->u.template_unification.flags,
4042 NULL, true, false);
4043 break;
4044 case rr_invalid_copy:
4045 inform (cloc,
4046 " a constructor taking a single argument of its own "
4047 "class type is invalid");
4048 break;
4049 case rr_constraint_failure:
4050 diagnose_constraints (cloc, fn, NULL_TREE);
4051 break;
4052 case rr_inherited_ctor:
4053 inform (cloc, " an inherited constructor is not a candidate for "
4054 "initialization from an expression of the same or derived "
4055 "type");
4056 break;
4057 case rr_ignored:
4058 break;
4059 case rr_none:
4060 default:
4061 /* This candidate didn't have any issues or we failed to
4062 handle a particular code. Either way... */
4063 gcc_unreachable ();
4064 }
4065 }
4066}
4067
4068/* Print information about each overload candidate in CANDIDATES,
4069 which is assumed to have gone through splice_viable and tourney
4070 (if splice_viable succeeded). */
4071
4072static void
4073print_z_candidates (location_t loc, struct z_candidate *candidates,
4074 tristate only_viable_p /* = tristate::unknown () */)
4075{
4076 struct z_candidate *cand1;
4077 struct z_candidate **cand2;
4078
4079 if (!candidates)
4080 return;
4081
4082 /* Remove non-viable deleted candidates. */
4083 cand1 = candidates;
4084 for (cand2 = &cand1; *cand2; )
4085 {
4086 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4087 && !(*cand2)->viable
4088 && DECL_DELETED_FN ((*cand2)->fn))
4089 *cand2 = (*cand2)->next;
4090 else
4091 cand2 = &(*cand2)->next;
4092 }
4093 /* ...if there are any non-deleted ones. */
4094 if (cand1)
4095 candidates = cand1;
4096
4097 /* There may be duplicates in the set of candidates. We put off
4098 checking this condition as long as possible, since we have no way
4099 to eliminate duplicates from a set of functions in less than n^2
4100 time. Now we are about to emit an error message, so it is more
4101 permissible to go slowly. */
4102 for (cand1 = candidates; cand1; cand1 = cand1->next)
4103 {
4104 tree fn = cand1->fn;
4105 /* Skip builtin candidates and conversion functions. */
4106 if (!DECL_P (fn))
4107 continue;
4108 cand2 = &cand1->next;
4109 while (*cand2)
4110 {
4111 if (DECL_P ((*cand2)->fn)
4112 && equal_functions (fn1: fn, fn2: (*cand2)->fn))
4113 *cand2 = (*cand2)->next;
4114 else
4115 cand2 = &(*cand2)->next;
4116 }
4117 }
4118
4119 /* Unless otherwise specified, if there's a (strictly) viable candidate
4120 then we assume we're being called as part of diagnosing ambiguity, in
4121 which case we want to print only viable candidates since non-viable
4122 candidates couldn't have contributed to the ambiguity. */
4123 if (only_viable_p.is_unknown ())
4124 only_viable_p = candidates->viable == 1;
4125
4126 for (; candidates; candidates = candidates->next)
4127 {
4128 if (only_viable_p.is_true () && candidates->viable != 1)
4129 break;
4130 if (ignored_candidate_p (cand: candidates) && !flag_diagnostics_all_candidates)
4131 {
4132 inform (loc, "some candidates omitted; "
4133 "use %<-fdiagnostics-all-candidates%> to display them");
4134 break;
4135 }
4136 print_z_candidate (loc, N_("candidate:"), candidate: candidates);
4137 }
4138}
4139
4140/* USER_SEQ is a user-defined conversion sequence, beginning with a
4141 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4142 the result of the conversion function to convert it to the final
4143 desired type. Merge the two sequences into a single sequence,
4144 and return the merged sequence. */
4145
4146static conversion *
4147merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4148{
4149 conversion **t;
4150 bool bad = user_seq->bad_p;
4151
4152 gcc_assert (user_seq->kind == ck_user);
4153
4154 /* Find the end of the second conversion sequence. */
4155 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4156 {
4157 /* The entire sequence is a user-conversion sequence. */
4158 (*t)->user_conv_p = true;
4159 if (bad)
4160 (*t)->bad_p = true;
4161 }
4162
4163 if ((*t)->rvaluedness_matches_p)
4164 /* We're binding a reference directly to the result of the conversion.
4165 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4166 type, but we want it back. */
4167 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4168
4169 /* Replace the identity conversion with the user conversion
4170 sequence. */
4171 *t = user_seq;
4172
4173 return std_seq;
4174}
4175
4176/* Handle overload resolution for initializing an object of class type from
4177 an initializer list. First we look for a suitable constructor that
4178 takes a std::initializer_list; if we don't find one, we then look for a
4179 non-list constructor.
4180
4181 Parameters are as for add_candidates, except that the arguments are in
4182 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4183 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4184
4185static void
4186add_list_candidates (tree fns, tree first_arg,
4187 const vec<tree, va_gc> *args, tree totype,
4188 tree explicit_targs, bool template_only,
4189 tree conversion_path, tree access_path,
4190 int flags,
4191 struct z_candidate **candidates,
4192 tsubst_flags_t complain)
4193{
4194 gcc_assert (*candidates == NULL);
4195
4196 /* We're looking for a ctor for list-initialization. */
4197 flags |= LOOKUP_LIST_INIT_CTOR;
4198 /* And we don't allow narrowing conversions. We also use this flag to
4199 avoid the copy constructor call for copy-list-initialization. */
4200 flags |= LOOKUP_NO_NARROWING;
4201
4202 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4203 tree init_list = (*args)[nart];
4204
4205 /* Always use the default constructor if the list is empty (DR 990). */
4206 if (CONSTRUCTOR_NELTS (init_list) == 0
4207 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4208 ;
4209 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4210 && !CP_AGGREGATE_TYPE_P (totype))
4211 {
4212 if (complain & tf_error)
4213 error ("designated initializers cannot be used with a "
4214 "non-aggregate type %qT", totype);
4215 return;
4216 }
4217 /* If the class has a list ctor, try passing the list as a single
4218 argument first, but only consider list ctors. */
4219 else if (TYPE_HAS_LIST_CTOR (totype))
4220 {
4221 flags |= LOOKUP_LIST_ONLY;
4222 add_candidates (fns, first_arg, args, NULL_TREE,
4223 explicit_targs, template_only, conversion_path,
4224 access_path, flags, candidates, complain);
4225 if (any_strictly_viable (cands: *candidates))
4226 return;
4227 }
4228
4229 /* Expand the CONSTRUCTOR into a new argument vec. */
4230 vec<tree, va_gc> *new_args;
4231 vec_alloc (v&: new_args, nelems: nart + CONSTRUCTOR_NELTS (init_list));
4232 for (unsigned i = 0; i < nart; ++i)
4233 new_args->quick_push (obj: (*args)[i]);
4234 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4235 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4236
4237 /* We aren't looking for list-ctors anymore. */
4238 flags &= ~LOOKUP_LIST_ONLY;
4239 /* We allow more user-defined conversions within an init-list. */
4240 flags &= ~LOOKUP_NO_CONVERSION;
4241
4242 add_candidates (fns, first_arg, new_args, NULL_TREE,
4243 explicit_targs, template_only, conversion_path,
4244 access_path, flags, candidates, complain);
4245}
4246
4247/* Given C(std::initializer_list<A>), return A. */
4248
4249static tree
4250list_ctor_element_type (tree fn)
4251{
4252 gcc_checking_assert (is_list_ctor (fn));
4253
4254 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4255 parm = non_reference (TREE_VALUE (parm));
4256 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4257}
4258
4259/* If EXPR is a braced-init-list where the elements all decay to the same type,
4260 return that type. */
4261
4262static tree
4263braced_init_element_type (tree expr)
4264{
4265 if (TREE_CODE (expr) == CONSTRUCTOR
4266 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4267 return TREE_TYPE (TREE_TYPE (expr));
4268 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4269 return NULL_TREE;
4270
4271 tree elttype = NULL_TREE;
4272 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4273 {
4274 tree type = TREE_TYPE (e.value);
4275 type = type_decays_to (type);
4276 if (!elttype)
4277 elttype = type;
4278 else if (!same_type_p (type, elttype))
4279 return NULL_TREE;
4280 }
4281 return elttype;
4282}
4283
4284/* True iff EXPR contains any temporaries with non-trivial destruction.
4285
4286 ??? Also ignore classes with non-trivial but no-op destruction other than
4287 std::allocator? */
4288
4289static bool
4290has_non_trivial_temporaries (tree expr)
4291{
4292 auto_vec<tree*> temps;
4293 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4294 for (tree *p : temps)
4295 {
4296 tree t = TREE_TYPE (*p);
4297 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4298 && !is_std_allocator (t))
4299 return true;
4300 }
4301 return false;
4302}
4303
4304/* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4305 return INIT as an array (of its own type) so the caller can initialize the
4306 target array in a loop. */
4307
4308static tree
4309maybe_init_list_as_array (tree elttype, tree init)
4310{
4311 /* Only do this if the array can go in rodata but not once converted. */
4312 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4313 return NULL_TREE;
4314 tree init_elttype = braced_init_element_type (expr: init);
4315 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4316 return NULL_TREE;
4317
4318 /* Check with a stub expression to weed out special cases, and check whether
4319 we call the same function for direct-init as copy-list-init. */
4320 conversion_obstack_sentinel cos;
4321 tree arg = build_stub_object (init_elttype);
4322 conversion *c = implicit_conversion (to: elttype, from: init_elttype, expr: arg, c_cast_p: false,
4323 LOOKUP_NORMAL, complain: tf_none);
4324 if (c && c->kind == ck_rvalue)
4325 c = next_conversion (conv: c);
4326 if (!c || c->kind != ck_user)
4327 return NULL_TREE;
4328
4329 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4330 conversion *fc = implicit_conversion (to: elttype, from: init_elttype, expr: first, c_cast_p: false,
4331 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4332 complain: tf_none);
4333 if (fc && fc->kind == ck_rvalue)
4334 fc = next_conversion (conv: fc);
4335 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4336 return NULL_TREE;
4337 first = convert_like (fc, first, tf_none);
4338 if (first == error_mark_node)
4339 /* Let the normal code give the error. */
4340 return NULL_TREE;
4341
4342 /* Don't do this if the conversion would be constant. */
4343 first = maybe_constant_init (first);
4344 if (TREE_CONSTANT (first))
4345 return NULL_TREE;
4346
4347 /* We can't do this if the conversion creates temporaries that need
4348 to live until the whole array is initialized. */
4349 if (has_non_trivial_temporaries (expr: first))
4350 return NULL_TREE;
4351
4352 /* We can't do this if copying from the initializer_list would be
4353 ill-formed. */
4354 tree copy_argtypes = make_tree_vec (1);
4355 TREE_VEC_ELT (copy_argtypes, 0)
4356 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4357 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4358 return NULL_TREE;
4359
4360 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4361 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4362 arr = finish_compound_literal (arr, init, tf_none);
4363 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4364 return arr;
4365}
4366
4367/* If we were going to call e.g. vector(initializer_list<string>) starting
4368 with a list of string-literals (which is inefficient, see PR105838),
4369 instead build an array of const char* and pass it to the range constructor.
4370 But only do this for standard library types, where we can assume the
4371 transformation makes sense.
4372
4373 Really the container classes should have initializer_list<U> constructors to
4374 get the same effect more simply; this is working around that lack. */
4375
4376static tree
4377maybe_init_list_as_range (tree fn, tree expr)
4378{
4379 if (!processing_template_decl
4380 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4381 && is_list_ctor (fn)
4382 && decl_in_std_namespace_p (fn))
4383 {
4384 tree to = list_ctor_element_type (fn);
4385 if (tree init = maybe_init_list_as_array (elttype: to, init: expr))
4386 {
4387 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4388 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4389 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4390 nelts, tf_none);
4391 begin = cp_build_compound_expr (init, begin, tf_none);
4392 return build_constructor_va (init_list_type_node, 2,
4393 NULL_TREE, begin, NULL_TREE, end);
4394 }
4395 }
4396
4397 return NULL_TREE;
4398}
4399
4400/* Returns the best overload candidate to perform the requested
4401 conversion. This function is used for three the overloading situations
4402 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4403 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4404 per [dcl.init.ref], so we ignore temporary bindings. */
4405
4406static struct z_candidate *
4407build_user_type_conversion_1 (tree totype, tree expr, int flags,
4408 tsubst_flags_t complain)
4409{
4410 struct z_candidate *candidates, *cand;
4411 tree fromtype;
4412 tree ctors = NULL_TREE;
4413 tree conv_fns = NULL_TREE;
4414 conversion *conv = NULL;
4415 tree first_arg = NULL_TREE;
4416 vec<tree, va_gc> *args = NULL;
4417 bool any_viable_p;
4418 int convflags;
4419
4420 if (!expr)
4421 return NULL;
4422
4423 fromtype = TREE_TYPE (expr);
4424
4425 /* We represent conversion within a hierarchy using RVALUE_CONV and
4426 BASE_CONV, as specified by [over.best.ics]; these become plain
4427 constructor calls, as specified in [dcl.init]. */
4428 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4429 || !DERIVED_FROM_P (totype, fromtype));
4430
4431 if (CLASS_TYPE_P (totype))
4432 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4433 creating a garbage BASELINK; constructors can't be inherited. */
4434 ctors = get_class_binding (totype, complete_ctor_identifier);
4435
4436 tree to_nonref = non_reference (totype);
4437 if (MAYBE_CLASS_TYPE_P (fromtype))
4438 {
4439 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4440 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4441 && DERIVED_FROM_P (to_nonref, fromtype)))
4442 {
4443 /* [class.conv.fct] A conversion function is never used to
4444 convert a (possibly cv-qualified) object to the (possibly
4445 cv-qualified) same object type (or a reference to it), to a
4446 (possibly cv-qualified) base class of that type (or a
4447 reference to it)... */
4448 }
4449 else
4450 conv_fns = lookup_conversions (fromtype);
4451 }
4452
4453 candidates = 0;
4454 flags |= LOOKUP_NO_CONVERSION;
4455 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4456 flags |= LOOKUP_NO_NARROWING;
4457 /* Prevent add_candidates from treating a non-strictly viable candidate
4458 as unviable. */
4459 complain |= tf_conv;
4460
4461 /* It's OK to bind a temporary for converting constructor arguments, but
4462 not in converting the return value of a conversion operator. */
4463 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4464 | (flags & LOOKUP_NO_NARROWING));
4465 flags &= ~LOOKUP_NO_TEMP_BIND;
4466
4467 if (ctors)
4468 {
4469 int ctorflags = flags;
4470
4471 first_arg = build_dummy_object (totype);
4472
4473 /* We should never try to call the abstract or base constructor
4474 from here. */
4475 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4476 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4477
4478 args = make_tree_vector_single (expr);
4479 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4480 {
4481 /* List-initialization. */
4482 add_list_candidates (fns: ctors, first_arg, args, totype, NULL_TREE,
4483 template_only: false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4484 flags: ctorflags, candidates: &candidates, complain);
4485 }
4486 else
4487 {
4488 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4489 TYPE_BINFO (totype), TYPE_BINFO (totype),
4490 ctorflags, &candidates, complain);
4491 }
4492
4493 for (cand = candidates; cand; cand = cand->next)
4494 {
4495 cand->second_conv = build_identity_conv (type: totype, NULL_TREE);
4496
4497 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4498 set, then this is copy-initialization. In that case, "The
4499 result of the call is then used to direct-initialize the
4500 object that is the destination of the copy-initialization."
4501 [dcl.init]
4502
4503 We represent this in the conversion sequence with an
4504 rvalue conversion, which means a constructor call. */
4505 if (!TYPE_REF_P (totype)
4506 && cxx_dialect < cxx17
4507 && (flags & LOOKUP_ONLYCONVERTING)
4508 && !(convflags & LOOKUP_NO_TEMP_BIND))
4509 cand->second_conv
4510 = build_conv (code: ck_rvalue, type: totype, from: cand->second_conv);
4511 }
4512 }
4513
4514 if (conv_fns)
4515 {
4516 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4517 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4518 else
4519 first_arg = expr;
4520 }
4521
4522 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4523 {
4524 tree conversion_path = TREE_PURPOSE (conv_fns);
4525 struct z_candidate *old_candidates;
4526
4527 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4528 would need an addional user-defined conversion, i.e. if the return
4529 type differs in class-ness from the desired type. So we avoid
4530 considering operator bool when calling a copy constructor.
4531
4532 This optimization avoids the failure in PR97600, and is allowed by
4533 [temp.inst]/9: "If the function selected by overload resolution can be
4534 determined without instantiating a class template definition, it is
4535 unspecified whether that instantiation actually takes place." */
4536 tree convtype = non_reference (TREE_TYPE (conv_fns));
4537 if ((flags & LOOKUP_NO_CONVERSION)
4538 && !WILDCARD_TYPE_P (convtype)
4539 && (CLASS_TYPE_P (to_nonref)
4540 != CLASS_TYPE_P (convtype)))
4541 continue;
4542
4543 /* If we are called to convert to a reference type, we are trying to
4544 find a direct binding, so don't even consider temporaries. If
4545 we don't find a direct binding, the caller will try again to
4546 look for a temporary binding. */
4547 if (TYPE_REF_P (totype))
4548 convflags |= LOOKUP_NO_TEMP_BIND;
4549
4550 old_candidates = candidates;
4551 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4552 NULL_TREE, false,
4553 conversion_path, TYPE_BINFO (fromtype),
4554 flags, &candidates, complain);
4555
4556 for (cand = candidates; cand != old_candidates; cand = cand->next)
4557 {
4558 if (cand->viable == 0)
4559 /* Already rejected, don't change to -1. */
4560 continue;
4561
4562 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4563 conversion *ics
4564 = implicit_conversion (to: totype,
4565 from: rettype,
4566 expr: 0,
4567 /*c_cast_p=*/false, flags: convflags,
4568 complain);
4569
4570 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4571 copy-initialization. In that case, "The result of the
4572 call is then used to direct-initialize the object that is
4573 the destination of the copy-initialization." [dcl.init]
4574
4575 We represent this in the conversion sequence with an
4576 rvalue conversion, which means a constructor call. But
4577 don't add a second rvalue conversion if there's already
4578 one there. Which there really shouldn't be, but it's
4579 harmless since we'd add it here anyway. */
4580 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4581 && !(convflags & LOOKUP_NO_TEMP_BIND))
4582 ics = build_conv (code: ck_rvalue, type: totype, from: ics);
4583
4584 cand->second_conv = ics;
4585
4586 if (!ics)
4587 {
4588 cand->viable = 0;
4589 cand->reason = arg_conversion_rejection (NULL_TREE, n_arg: -2,
4590 from: rettype, to: totype,
4591 EXPR_LOCATION (expr));
4592 }
4593 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4594 /* Limit this to non-templates for now (PR90546). */
4595 && !cand->template_decl
4596 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4597 {
4598 /* If we are called to convert to a reference type, we are trying
4599 to find a direct binding per [over.match.ref], so rvaluedness
4600 must match for non-functions. */
4601 cand->viable = 0;
4602 }
4603 else if (DECL_NONCONVERTING_P (cand->fn)
4604 && ics->rank > cr_exact)
4605 {
4606 /* 13.3.1.5: For direct-initialization, those explicit
4607 conversion functions that are not hidden within S and
4608 yield type T or a type that can be converted to type T
4609 with a qualification conversion (4.4) are also candidate
4610 functions. */
4611 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4612 I've raised this issue with the committee. --jason 9/2011 */
4613 cand->viable = -1;
4614 cand->reason = explicit_conversion_rejection (from: rettype, to: totype);
4615 }
4616 else if (cand->viable == 1 && ics->bad_p)
4617 {
4618 cand->viable = -1;
4619 cand->reason
4620 = bad_arg_conversion_rejection (NULL_TREE, n_arg: -2,
4621 from: rettype, to: totype,
4622 EXPR_LOCATION (expr));
4623 }
4624 else if (primary_template_specialization_p (cand->fn)
4625 && ics->rank > cr_exact)
4626 {
4627 /* 13.3.3.1.2: If the user-defined conversion is specified by
4628 a specialization of a conversion function template, the
4629 second standard conversion sequence shall have exact match
4630 rank. */
4631 cand->viable = -1;
4632 cand->reason = template_conversion_rejection (from: rettype, to: totype);
4633 }
4634 }
4635 }
4636
4637 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
4638 if (!any_viable_p)
4639 {
4640 if (args)
4641 release_tree_vector (args);
4642 return NULL;
4643 }
4644
4645 cand = tourney (candidates, complain);
4646 if (cand == NULL)
4647 {
4648 if (complain & tf_error)
4649 {
4650 auto_diagnostic_group d;
4651 error_at (cp_expr_loc_or_input_loc (t: expr),
4652 "conversion from %qH to %qI is ambiguous",
4653 fromtype, totype);
4654 print_z_candidates (loc: location_of (expr), candidates);
4655 }
4656
4657 cand = candidates; /* any one will do */
4658 cand->second_conv = build_ambiguous_conv (type: totype, expr);
4659 cand->second_conv->user_conv_p = true;
4660 if (!any_strictly_viable (cands: candidates))
4661 cand->second_conv->bad_p = true;
4662 if (flags & LOOKUP_ONLYCONVERTING)
4663 cand->second_conv->need_temporary_p = true;
4664 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4665 ambiguous conversion is no worse than another user-defined
4666 conversion. */
4667
4668 return cand;
4669 }
4670
4671 /* Maybe pass { } as iterators instead of an initializer_list. */
4672 if (tree iters = maybe_init_list_as_range (fn: cand->fn, expr))
4673 if (z_candidate *cand2
4674 = build_user_type_conversion_1 (totype, expr: iters, flags, complain: tf_none))
4675 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4676 {
4677 cand = cand2;
4678 expr = iters;
4679 }
4680
4681 tree convtype;
4682 if (!DECL_CONSTRUCTOR_P (cand->fn))
4683 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4684 else if (cand->second_conv->kind == ck_rvalue)
4685 /* DR 5: [in the first step of copy-initialization]...if the function
4686 is a constructor, the call initializes a temporary of the
4687 cv-unqualified version of the destination type. */
4688 convtype = cv_unqualified (totype);
4689 else
4690 convtype = totype;
4691 /* Build the user conversion sequence. */
4692 conv = build_conv
4693 (code: ck_user,
4694 type: convtype,
4695 from: build_identity_conv (TREE_TYPE (expr), expr));
4696 conv->cand = cand;
4697 if (cand->viable == -1)
4698 conv->bad_p = true;
4699
4700 /* Remember that this was a list-initialization. */
4701 if (flags & LOOKUP_NO_NARROWING)
4702 conv->check_narrowing = true;
4703
4704 /* Combine it with the second conversion sequence. */
4705 cand->second_conv = merge_conversion_sequences (user_seq: conv,
4706 std_seq: cand->second_conv);
4707
4708 return cand;
4709}
4710
4711/* Wrapper for above. */
4712
4713tree
4714build_user_type_conversion (tree totype, tree expr, int flags,
4715 tsubst_flags_t complain)
4716{
4717 struct z_candidate *cand;
4718 tree ret;
4719
4720 auto_cond_timevar tv (TV_OVERLOAD);
4721
4722 conversion_obstack_sentinel cos;
4723
4724 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4725
4726 if (cand)
4727 {
4728 if (cand->second_conv->kind == ck_ambig)
4729 ret = error_mark_node;
4730 else
4731 {
4732 expr = convert_like (cand->second_conv, expr, complain);
4733 ret = convert_from_reference (expr);
4734 }
4735 }
4736 else
4737 ret = NULL_TREE;
4738
4739 return ret;
4740}
4741
4742/* Give a helpful diagnostic when implicit_conversion fails. */
4743
4744static void
4745implicit_conversion_error (location_t loc, tree type, tree expr)
4746{
4747 tsubst_flags_t complain = tf_warning_or_error;
4748
4749 /* If expr has unknown type, then it is an overloaded function.
4750 Call instantiate_type to get good error messages. */
4751 if (TREE_TYPE (expr) == unknown_type_node)
4752 instantiate_type (type, expr, complain);
4753 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4754 /* We gave an error. */;
4755 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4756 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4757 && !CP_AGGREGATE_TYPE_P (type))
4758 error_at (loc, "designated initializers cannot be used with a "
4759 "non-aggregate type %qT", type);
4760 else
4761 {
4762 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4763 gcc_rich_location rich_loc (loc, &label);
4764 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4765 expr, TREE_TYPE (expr), type);
4766 }
4767}
4768
4769/* Worker for build_converted_constant_expr. */
4770
4771static tree
4772build_converted_constant_expr_internal (tree type, tree expr,
4773 int flags, tsubst_flags_t complain)
4774{
4775 conversion *conv;
4776 tree t;
4777 location_t loc = cp_expr_loc_or_input_loc (t: expr);
4778
4779 if (error_operand_p (t: expr))
4780 return error_mark_node;
4781
4782 conversion_obstack_sentinel cos;
4783
4784 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
4785 /*c_cast_p=*/false, flags, complain);
4786
4787 /* A converted constant expression of type T is an expression, implicitly
4788 converted to type T, where the converted expression is a constant
4789 expression and the implicit conversion sequence contains only
4790
4791 * user-defined conversions,
4792 * lvalue-to-rvalue conversions (7.1),
4793 * array-to-pointer conversions (7.2),
4794 * function-to-pointer conversions (7.3),
4795 * qualification conversions (7.5),
4796 * integral promotions (7.6),
4797 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4798 * null pointer conversions (7.11) from std::nullptr_t,
4799 * null member pointer conversions (7.12) from std::nullptr_t, and
4800 * function pointer conversions (7.13),
4801
4802 and where the reference binding (if any) binds directly. */
4803
4804 for (conversion *c = conv;
4805 c && c->kind != ck_identity;
4806 c = next_conversion (conv: c))
4807 {
4808 switch (c->kind)
4809 {
4810 /* A conversion function is OK. If it isn't constexpr, we'll
4811 complain later that the argument isn't constant. */
4812 case ck_user:
4813 /* List-initialization is OK. */
4814 case ck_aggr:
4815 /* The lvalue-to-rvalue conversion is OK. */
4816 case ck_rvalue:
4817 /* Array-to-pointer and function-to-pointer. */
4818 case ck_lvalue:
4819 /* Function pointer conversions. */
4820 case ck_fnptr:
4821 /* Qualification conversions. */
4822 case ck_qual:
4823 break;
4824
4825 case ck_ref_bind:
4826 if (c->need_temporary_p)
4827 {
4828 if (complain & tf_error)
4829 error_at (loc, "initializing %qH with %qI in converted "
4830 "constant expression does not bind directly",
4831 type, next_conversion (conv: c)->type);
4832 conv = NULL;
4833 }
4834 break;
4835
4836 case ck_base:
4837 case ck_pmem:
4838 case ck_ptr:
4839 case ck_std:
4840 t = next_conversion (conv: c)->type;
4841 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4842 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4843 /* Integral promotion or conversion. */
4844 break;
4845 if (NULLPTR_TYPE_P (t))
4846 /* Conversion from nullptr to pointer or pointer-to-member. */
4847 break;
4848
4849 if (complain & tf_error)
4850 error_at (loc, "conversion from %qH to %qI in a "
4851 "converted constant expression", t, type);
4852 /* fall through. */
4853
4854 default:
4855 conv = NULL;
4856 break;
4857 }
4858 }
4859
4860 /* Avoid confusing convert_nontype_argument by introducing
4861 a redundant conversion to the same reference type. */
4862 if (conv && conv->kind == ck_ref_bind
4863 && REFERENCE_REF_P (expr))
4864 {
4865 tree ref = TREE_OPERAND (expr, 0);
4866 if (same_type_p (type, TREE_TYPE (ref)))
4867 return ref;
4868 }
4869
4870 if (conv)
4871 {
4872 /* Don't copy a class in a template. */
4873 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4874 && processing_template_decl)
4875 conv = next_conversion (conv);
4876
4877 /* Issuing conversion warnings for value-dependent expressions is
4878 likely too noisy. */
4879 warning_sentinel w (warn_conversion);
4880 conv->check_narrowing = true;
4881 conv->check_narrowing_const_only = true;
4882 expr = convert_like (conv, expr, complain);
4883 }
4884 else
4885 {
4886 if (complain & tf_error)
4887 implicit_conversion_error (loc, type, expr);
4888 expr = error_mark_node;
4889 }
4890
4891 return expr;
4892}
4893
4894/* Subroutine of convert_nontype_argument.
4895
4896 EXPR is an expression used in a context that requires a converted
4897 constant-expression, such as a template non-type parameter. Do any
4898 necessary conversions (that are permitted for converted
4899 constant-expressions) to convert it to the desired type.
4900
4901 This function doesn't consider explicit conversion functions. If
4902 you mean to use "a contextually converted constant expression of type
4903 bool", use build_converted_constant_bool_expr.
4904
4905 If conversion is successful, returns the converted expression;
4906 otherwise, returns error_mark_node. */
4907
4908tree
4909build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4910{
4911 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4912 complain);
4913}
4914
4915/* Used to create "a contextually converted constant expression of type
4916 bool". This differs from build_converted_constant_expr in that it
4917 also considers explicit conversion functions. */
4918
4919tree
4920build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4921{
4922 return build_converted_constant_expr_internal (boolean_type_node, expr,
4923 LOOKUP_NORMAL, complain);
4924}
4925
4926/* Do any initial processing on the arguments to a function call. */
4927
4928vec<tree, va_gc> *
4929resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4930{
4931 unsigned int ix;
4932 tree arg;
4933
4934 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4935 {
4936 if (error_operand_p (t: arg))
4937 return NULL;
4938 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4939 {
4940 if (complain & tf_error)
4941 error_at (cp_expr_loc_or_input_loc (t: arg),
4942 "invalid use of void expression");
4943 return NULL;
4944 }
4945 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4946 return NULL;
4947
4948 /* Force auto deduction now. Omit tf_warning to avoid redundant
4949 deprecated warning on deprecated-14.C. */
4950 if (!mark_single_function (arg, complain & ~tf_warning))
4951 return NULL;
4952 }
4953 return args;
4954}
4955
4956/* Perform overload resolution on FN, which is called with the ARGS.
4957
4958 Return the candidate function selected by overload resolution, or
4959 NULL if the event that overload resolution failed. In the case
4960 that overload resolution fails, *CANDIDATES will be the set of
4961 candidates considered, and ANY_VIABLE_P will be set to true or
4962 false to indicate whether or not any of the candidates were
4963 viable.
4964
4965 The ARGS should already have gone through RESOLVE_ARGS before this
4966 function is called. */
4967
4968static struct z_candidate *
4969perform_overload_resolution (tree fn,
4970 const vec<tree, va_gc> *args,
4971 struct z_candidate **candidates,
4972 bool *any_viable_p, tsubst_flags_t complain)
4973{
4974 struct z_candidate *cand;
4975 tree explicit_targs;
4976 int template_only;
4977
4978 auto_cond_timevar tv (TV_OVERLOAD);
4979
4980 explicit_targs = NULL_TREE;
4981 template_only = 0;
4982
4983 *candidates = NULL;
4984 *any_viable_p = true;
4985
4986 /* Check FN. */
4987 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4988
4989 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4990 {
4991 explicit_targs = TREE_OPERAND (fn, 1);
4992 fn = TREE_OPERAND (fn, 0);
4993 template_only = 1;
4994 }
4995
4996 /* Add the various candidate functions. */
4997 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4998 explicit_targs, template_only,
4999 /*conversion_path=*/NULL_TREE,
5000 /*access_path=*/NULL_TREE,
5001 LOOKUP_NORMAL,
5002 candidates, complain);
5003
5004 *candidates = splice_viable (cands: *candidates, strict_p: false, any_viable_p);
5005 if (*any_viable_p)
5006 cand = tourney (*candidates, complain);
5007 else
5008 cand = NULL;
5009
5010 return cand;
5011}
5012
5013/* Print an error message about being unable to build a call to FN with
5014 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
5015 be located; CANDIDATES is a possibly empty list of such
5016 functions. */
5017
5018static void
5019print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
5020 struct z_candidate *candidates)
5021{
5022 tree targs = NULL_TREE;
5023 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5024 {
5025 targs = TREE_OPERAND (fn, 1);
5026 fn = TREE_OPERAND (fn, 0);
5027 }
5028 tree name = OVL_NAME (fn);
5029 location_t loc = location_of (name);
5030 if (targs)
5031 name = lookup_template_function (name, targs);
5032
5033 auto_diagnostic_group d;
5034 if (!any_strictly_viable (cands: candidates))
5035 error_at (loc, "no matching function for call to %<%D(%A)%>",
5036 name, build_tree_list_vec (args));
5037 else
5038 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
5039 name, build_tree_list_vec (args));
5040 if (candidates)
5041 print_z_candidates (loc, candidates);
5042}
5043
5044/* Perform overload resolution on the set of deduction guides DGUIDES
5045 using ARGS. Returns the selected deduction guide, or error_mark_node
5046 if overload resolution fails. */
5047
5048tree
5049perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
5050 tsubst_flags_t complain)
5051{
5052 z_candidate *candidates;
5053 bool any_viable_p;
5054 tree result;
5055
5056 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
5057
5058 conversion_obstack_sentinel cos;
5059
5060 z_candidate *cand = perform_overload_resolution (fn: dguides, args, candidates: &candidates,
5061 any_viable_p: &any_viable_p, complain);
5062 if (!cand)
5063 {
5064 if (complain & tf_error)
5065 print_error_for_call_failure (fn: dguides, args, candidates);
5066 result = error_mark_node;
5067 }
5068 else
5069 result = cand->fn;
5070
5071 return result;
5072}
5073
5074/* Return an expression for a call to FN (a namespace-scope function,
5075 or a static member function) with the ARGS. This may change
5076 ARGS. */
5077
5078tree
5079build_new_function_call (tree fn, vec<tree, va_gc> **args,
5080 tsubst_flags_t complain)
5081{
5082 struct z_candidate *candidates, *cand;
5083 bool any_viable_p;
5084 tree result;
5085
5086 if (args != NULL && *args != NULL)
5087 {
5088 *args = resolve_args (args: *args, complain);
5089 if (*args == NULL)
5090 return error_mark_node;
5091 }
5092
5093 if (flag_tm)
5094 tm_malloc_replacement (fn);
5095
5096 conversion_obstack_sentinel cos;
5097
5098 cand = perform_overload_resolution (fn, args: *args, candidates: &candidates, any_viable_p: &any_viable_p,
5099 complain);
5100
5101 if (!cand)
5102 {
5103 if (complain & tf_error)
5104 {
5105 // If there is a single (non-viable) function candidate,
5106 // let the error be diagnosed by cp_build_function_call_vec.
5107 if (!any_viable_p && candidates && ! candidates->next
5108 && TREE_CODE (candidates->fn) == FUNCTION_DECL
5109 /* A template-id callee consisting of a single (ignored)
5110 non-template candidate needs to be diagnosed the
5111 ordinary way. */
5112 && (TREE_CODE (fn) != TEMPLATE_ID_EXPR
5113 || candidates->template_decl))
5114 return cp_build_function_call_vec (candidates->fn, args, complain);
5115
5116 // Otherwise, emit notes for non-viable candidates.
5117 print_error_for_call_failure (fn, args: *args, candidates);
5118 }
5119 result = error_mark_node;
5120 }
5121 else
5122 {
5123 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5124 }
5125
5126 if (flag_coroutines
5127 && result
5128 && TREE_CODE (result) == CALL_EXPR
5129 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5130 == BUILT_IN_NORMAL)
5131 result = coro_validate_builtin_call (result);
5132
5133 return result;
5134}
5135
5136/* Build a call to a global operator new. FNNAME is the name of the
5137 operator (either "operator new" or "operator new[]") and ARGS are
5138 the arguments provided. This may change ARGS. *SIZE points to the
5139 total number of bytes required by the allocation, and is updated if
5140 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5141 be used. If this function determines that no cookie should be
5142 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5143 is not NULL_TREE, it is evaluated before calculating the final
5144 array size, and if it fails, the array size is replaced with
5145 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5146 is non-NULL, it will be set, upon return, to the allocation
5147 function called. */
5148
5149tree
5150build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5151 tree *size, tree *cookie_size,
5152 tree align_arg, tree size_check,
5153 tree *fn, tsubst_flags_t complain)
5154{
5155 tree original_size = *size;
5156 tree fns;
5157 struct z_candidate *candidates;
5158 struct z_candidate *cand = NULL;
5159 bool any_viable_p;
5160
5161 if (fn)
5162 *fn = NULL_TREE;
5163 /* Set to (size_t)-1 if the size check fails. */
5164 if (size_check != NULL_TREE)
5165 {
5166 tree errval = TYPE_MAX_VALUE (sizetype);
5167 if (cxx_dialect >= cxx11 && flag_exceptions)
5168 errval = throw_bad_array_new_length ();
5169 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5170 original_size, errval);
5171 }
5172 vec_safe_insert (v&: *args, ix: 0, obj: *size);
5173 *args = resolve_args (args: *args, complain);
5174 if (*args == NULL)
5175 return error_mark_node;
5176
5177 conversion_obstack_sentinel cos;
5178
5179 /* Based on:
5180
5181 [expr.new]
5182
5183 If this lookup fails to find the name, or if the allocated type
5184 is not a class type, the allocation function's name is looked
5185 up in the global scope.
5186
5187 we disregard block-scope declarations of "operator new". */
5188 fns = lookup_qualified_name (global_namespace, name: fnname);
5189
5190 if (align_arg)
5191 {
5192 vec<tree, va_gc>* align_args
5193 = vec_copy_and_insert (*args, align_arg, 1);
5194 cand = perform_overload_resolution (fn: fns, args: align_args, candidates: &candidates,
5195 any_viable_p: &any_viable_p, complain: tf_none);
5196 if (cand)
5197 *args = align_args;
5198 /* If no aligned allocation function matches, try again without the
5199 alignment. */
5200 }
5201
5202 /* Figure out what function is being called. */
5203 if (!cand)
5204 cand = perform_overload_resolution (fn: fns, args: *args, candidates: &candidates, any_viable_p: &any_viable_p,
5205 complain);
5206
5207 /* If no suitable function could be found, issue an error message
5208 and give up. */
5209 if (!cand)
5210 {
5211 if (complain & tf_error)
5212 print_error_for_call_failure (fn: fns, args: *args, candidates);
5213 return error_mark_node;
5214 }
5215
5216 /* If a cookie is required, add some extra space. Whether
5217 or not a cookie is required cannot be determined until
5218 after we know which function was called. */
5219 if (*cookie_size)
5220 {
5221 bool use_cookie = true;
5222 tree arg_types;
5223
5224 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5225 /* Skip the size_t parameter. */
5226 arg_types = TREE_CHAIN (arg_types);
5227 /* Check the remaining parameters (if any). */
5228 if (arg_types
5229 && TREE_CHAIN (arg_types) == void_list_node
5230 && same_type_p (TREE_VALUE (arg_types),
5231 ptr_type_node))
5232 use_cookie = false;
5233 /* If we need a cookie, adjust the number of bytes allocated. */
5234 if (use_cookie)
5235 {
5236 /* Update the total size. */
5237 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5238 if (size_check)
5239 {
5240 /* Set to (size_t)-1 if the size check fails. */
5241 gcc_assert (size_check != NULL_TREE);
5242 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5243 *size, TYPE_MAX_VALUE (sizetype));
5244 }
5245 /* Update the argument list to reflect the adjusted size. */
5246 (**args)[0] = *size;
5247 }
5248 else
5249 *cookie_size = NULL_TREE;
5250 }
5251
5252 /* Tell our caller which function we decided to call. */
5253 if (fn)
5254 *fn = cand->fn;
5255
5256 /* Build the CALL_EXPR. */
5257 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5258
5259 /* Set this flag for all callers of this function. In addition to
5260 new-expressions, this is called for allocating coroutine state; treat
5261 that as an implicit new-expression. */
5262 tree call = extract_call_expr (ret);
5263 if (TREE_CODE (call) == CALL_EXPR)
5264 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5265
5266 return ret;
5267}
5268
5269/* Evaluate side-effects from OBJ before evaluating call
5270 to FN in RESULT expression.
5271 This is for expressions of the form `obj->fn(...)'
5272 where `fn' turns out to be a static member function and
5273 `obj' needs to be evaluated. `fn' could be also static operator[]
5274 or static operator(), in which cases the source expression
5275 would be `obj[...]' or `obj(...)'. */
5276
5277tree
5278keep_unused_object_arg (tree result, tree obj, tree fn)
5279{
5280 if (result == NULL_TREE
5281 || result == error_mark_node
5282 || DECL_OBJECT_MEMBER_FUNCTION_P (fn)
5283 || !TREE_SIDE_EFFECTS (obj))
5284 return result;
5285
5286 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5287 volatile. */
5288 tree a = obj;
5289 if (TREE_THIS_VOLATILE (a))
5290 a = build_this (obj: a);
5291 if (TREE_SIDE_EFFECTS (a))
5292 return cp_build_compound_expr (a, result, tf_error);
5293 return result;
5294}
5295
5296/* Build a new call to operator(). This may change ARGS. */
5297
5298tree
5299build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5300{
5301 struct z_candidate *candidates = 0, *cand;
5302 tree fns, convs, first_mem_arg = NULL_TREE;
5303 bool any_viable_p;
5304 tree result = NULL_TREE;
5305
5306 auto_cond_timevar tv (TV_OVERLOAD);
5307
5308 obj = mark_lvalue_use (obj);
5309
5310 if (error_operand_p (t: obj))
5311 return error_mark_node;
5312
5313 tree type = TREE_TYPE (obj);
5314
5315 obj = prep_operand (obj);
5316
5317 if (TYPE_PTRMEMFUNC_P (type))
5318 {
5319 if (complain & tf_error)
5320 /* It's no good looking for an overloaded operator() on a
5321 pointer-to-member-function. */
5322 error ("pointer-to-member function %qE cannot be called without "
5323 "an object; consider using %<.*%> or %<->*%>", obj);
5324 return error_mark_node;
5325 }
5326
5327 if (TYPE_BINFO (type))
5328 {
5329 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5330 if (fns == error_mark_node)
5331 return error_mark_node;
5332 }
5333 else
5334 fns = NULL_TREE;
5335
5336 if (args != NULL && *args != NULL)
5337 {
5338 *args = resolve_args (args: *args, complain);
5339 if (*args == NULL)
5340 return error_mark_node;
5341 }
5342
5343 conversion_obstack_sentinel cos;
5344
5345 if (fns)
5346 {
5347 first_mem_arg = obj;
5348
5349 add_candidates (BASELINK_FUNCTIONS (fns),
5350 first_mem_arg, *args, NULL_TREE,
5351 NULL_TREE, false,
5352 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5353 LOOKUP_NORMAL, &candidates, complain);
5354 }
5355
5356 bool any_call_ops = candidates != nullptr;
5357
5358 convs = lookup_conversions (type);
5359
5360 for (; convs; convs = TREE_CHAIN (convs))
5361 {
5362 tree totype = TREE_TYPE (convs);
5363
5364 if (TYPE_PTRFN_P (totype)
5365 || TYPE_REFFN_P (totype)
5366 || (TYPE_REF_P (totype)
5367 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5368 for (tree fn : ovl_range (TREE_VALUE (convs)))
5369 {
5370 if (DECL_NONCONVERTING_P (fn))
5371 continue;
5372
5373 if (TREE_CODE (fn) == TEMPLATE_DECL)
5374 {
5375 /* Making this work broke PR 71117 and 85118, so until the
5376 committee resolves core issue 2189, let's disable this
5377 candidate if there are any call operators. */
5378 if (any_call_ops)
5379 continue;
5380
5381 add_template_conv_candidate
5382 (candidates: &candidates, tmpl: fn, obj, arglist: *args, return_type: totype,
5383 /*access_path=*/NULL_TREE,
5384 /*conversion_path=*/NULL_TREE, complain);
5385 }
5386 else
5387 add_conv_candidate (candidates: &candidates, fn, obj,
5388 arglist: *args, /*conversion_path=*/NULL_TREE,
5389 /*access_path=*/NULL_TREE, complain);
5390 }
5391 }
5392
5393 /* Be strict here because if we choose a bad conversion candidate, the
5394 errors we get won't mention the call context. */
5395 candidates = splice_viable (cands: candidates, strict_p: true, any_viable_p: &any_viable_p);
5396 if (!any_viable_p)
5397 {
5398 if (complain & tf_error)
5399 {
5400 auto_diagnostic_group d;
5401 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5402 build_tree_list_vec (*args));
5403 print_z_candidates (loc: location_of (TREE_TYPE (obj)), candidates);
5404 }
5405 result = error_mark_node;
5406 }
5407 else
5408 {
5409 cand = tourney (candidates, complain);
5410 if (cand == 0)
5411 {
5412 if (complain & tf_error)
5413 {
5414 auto_diagnostic_group d;
5415 error ("call of %<(%T) (%A)%> is ambiguous",
5416 TREE_TYPE (obj), build_tree_list_vec (*args));
5417 print_z_candidates (loc: location_of (TREE_TYPE (obj)), candidates);
5418 }
5419 result = error_mark_node;
5420 }
5421 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5422 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5423 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5424 {
5425 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5426 /* In an expression of the form `a()' where cand->fn
5427 which is operator() turns out to be a static member function,
5428 `a' is none-the-less evaluated. */
5429 result = keep_unused_object_arg (result, obj, fn: cand->fn);
5430 }
5431 else
5432 {
5433 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5434 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5435 -1, complain);
5436 else
5437 {
5438 gcc_checking_assert (TYPE_P (cand->fn));
5439 obj = convert_like (cand->convs[0], obj, complain);
5440 }
5441 obj = convert_from_reference (obj);
5442 result = cp_build_function_call_vec (obj, args, complain);
5443 }
5444 }
5445
5446 return result;
5447}
5448
5449/* Called by op_error to prepare format strings suitable for the error
5450 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5451 and a suffix (controlled by NTYPES). */
5452
5453static const char *
5454op_error_string (const char *errmsg, int ntypes, bool match)
5455{
5456 const char *msg;
5457
5458 const char *msgp = concat (match ? G_("ambiguous overload for ")
5459 : G_("no match for "), errmsg, NULL);
5460
5461 if (ntypes == 3)
5462 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5463 else if (ntypes == 2)
5464 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5465 else
5466 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5467
5468 return msg;
5469}
5470
5471static void
5472op_error (const op_location_t &loc,
5473 enum tree_code code, enum tree_code code2,
5474 tree arg1, tree arg2, tree arg3, bool match)
5475{
5476 bool assop = code == MODIFY_EXPR;
5477 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5478
5479 switch (code)
5480 {
5481 case COND_EXPR:
5482 if (flag_diagnostics_show_caret)
5483 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5484 ntypes: 3, match),
5485 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5486 else
5487 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5488 "in %<%E ? %E : %E%>"), ntypes: 3, match),
5489 arg1, arg2, arg3,
5490 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5491 break;
5492
5493 case POSTINCREMENT_EXPR:
5494 case POSTDECREMENT_EXPR:
5495 if (flag_diagnostics_show_caret)
5496 error_at (loc, op_error_string (G_("%<operator%s%>"), ntypes: 1, match),
5497 opname, TREE_TYPE (arg1));
5498 else
5499 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5500 ntypes: 1, match),
5501 opname, arg1, opname, TREE_TYPE (arg1));
5502 break;
5503
5504 case ARRAY_REF:
5505 if (flag_diagnostics_show_caret)
5506 error_at (loc, op_error_string (G_("%<operator[]%>"), ntypes: 2, match),
5507 TREE_TYPE (arg1), TREE_TYPE (arg2));
5508 else
5509 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5510 ntypes: 2, match),
5511 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5512 break;
5513
5514 case REALPART_EXPR:
5515 case IMAGPART_EXPR:
5516 if (flag_diagnostics_show_caret)
5517 error_at (loc, op_error_string (G_("%qs"), ntypes: 1, match),
5518 opname, TREE_TYPE (arg1));
5519 else
5520 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), ntypes: 1, match),
5521 opname, opname, arg1, TREE_TYPE (arg1));
5522 break;
5523
5524 case CO_AWAIT_EXPR:
5525 if (flag_diagnostics_show_caret)
5526 error_at (loc, op_error_string (G_("%<operator %s%>"), ntypes: 1, match),
5527 opname, TREE_TYPE (arg1));
5528 else
5529 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5530 ntypes: 1, match),
5531 opname, opname, arg1, TREE_TYPE (arg1));
5532 break;
5533
5534 default:
5535 if (arg2)
5536 if (flag_diagnostics_show_caret)
5537 {
5538 binary_op_rich_location richloc (loc, arg1, arg2, true);
5539 error_at (&richloc,
5540 op_error_string (G_("%<operator%s%>"), ntypes: 2, match),
5541 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5542 }
5543 else
5544 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5545 ntypes: 2, match),
5546 opname, arg1, opname, arg2,
5547 TREE_TYPE (arg1), TREE_TYPE (arg2));
5548 else
5549 if (flag_diagnostics_show_caret)
5550 error_at (loc, op_error_string (G_("%<operator%s%>"), ntypes: 1, match),
5551 opname, TREE_TYPE (arg1));
5552 else
5553 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5554 ntypes: 1, match),
5555 opname, opname, arg1, TREE_TYPE (arg1));
5556 break;
5557 }
5558}
5559
5560/* Return the implicit conversion sequence that could be used to
5561 convert E1 to E2 in [expr.cond]. */
5562
5563static conversion *
5564conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5565{
5566 tree t1 = non_reference (TREE_TYPE (e1));
5567 tree t2 = non_reference (TREE_TYPE (e2));
5568 conversion *conv;
5569 bool good_base;
5570
5571 /* [expr.cond]
5572
5573 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5574 implicitly converted (clause _conv_) to the type "lvalue reference to
5575 T2", subject to the constraint that in the conversion the
5576 reference must bind directly (_dcl.init.ref_) to an lvalue.
5577
5578 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5579 implicitly converted to the type "rvalue reference to T2", subject to
5580 the constraint that the reference must bind directly. */
5581 if (glvalue_p (e2))
5582 {
5583 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5584 conv = implicit_conversion (to: rtype,
5585 from: t1,
5586 expr: e1,
5587 /*c_cast_p=*/false,
5588 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5589 |LOOKUP_ONLYCONVERTING,
5590 complain);
5591 if (conv && !conv->bad_p)
5592 return conv;
5593 }
5594
5595 /* If E2 is a prvalue or if neither of the conversions above can be done
5596 and at least one of the operands has (possibly cv-qualified) class
5597 type: */
5598 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5599 return NULL;
5600
5601 /* [expr.cond]
5602
5603 If E1 and E2 have class type, and the underlying class types are
5604 the same or one is a base class of the other: E1 can be converted
5605 to match E2 if the class of T2 is the same type as, or a base
5606 class of, the class of T1, and the cv-qualification of T2 is the
5607 same cv-qualification as, or a greater cv-qualification than, the
5608 cv-qualification of T1. If the conversion is applied, E1 is
5609 changed to an rvalue of type T2 that still refers to the original
5610 source class object (or the appropriate subobject thereof). */
5611 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5612 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5613 {
5614 if (good_base && at_least_as_qualified_p (t2, t1))
5615 {
5616 conv = build_identity_conv (type: t1, expr: e1);
5617 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5618 TYPE_MAIN_VARIANT (t2)))
5619 conv = build_conv (code: ck_base, type: t2, from: conv);
5620 else
5621 conv = build_conv (code: ck_rvalue, type: t2, from: conv);
5622 return conv;
5623 }
5624 else
5625 return NULL;
5626 }
5627 else
5628 /* [expr.cond]
5629
5630 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5631 converted to the type that expression E2 would have if E2 were
5632 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5633 return implicit_conversion (to: t2, from: t1, expr: e1, /*c_cast_p=*/false,
5634 LOOKUP_IMPLICIT, complain);
5635}
5636
5637/* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5638 arguments to the conditional expression. */
5639
5640tree
5641build_conditional_expr (const op_location_t &loc,
5642 tree arg1, tree arg2, tree arg3,
5643 tsubst_flags_t complain)
5644{
5645 tree arg2_type;
5646 tree arg3_type;
5647 tree result = NULL_TREE;
5648 tree result_type = NULL_TREE;
5649 tree semantic_result_type = NULL_TREE;
5650 bool is_glvalue = true;
5651 struct z_candidate *candidates = 0;
5652 struct z_candidate *cand;
5653 tree orig_arg2, orig_arg3;
5654
5655 auto_cond_timevar tv (TV_OVERLOAD);
5656
5657 /* As a G++ extension, the second argument to the conditional can be
5658 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5659 c'.) If the second operand is omitted, make sure it is
5660 calculated only once. */
5661 if (!arg2)
5662 {
5663 if (complain & tf_error)
5664 pedwarn (loc, OPT_Wpedantic,
5665 "ISO C++ forbids omitting the middle term of "
5666 "a %<?:%> expression");
5667
5668 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5669 warn_for_omitted_condop (loc, arg1);
5670
5671 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5672 if (glvalue_p (arg1))
5673 {
5674 arg1 = cp_stabilize_reference (arg1);
5675 arg2 = arg1 = prevent_lifetime_extension (arg1);
5676 }
5677 else if (TREE_CODE (arg1) == TARGET_EXPR)
5678 /* arg1 can't be a prvalue result of the conditional
5679 expression, since it needs to be materialized for the
5680 conversion to bool, so treat it as an xvalue in arg2. */
5681 arg2 = move (TARGET_EXPR_SLOT (arg1));
5682 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5683 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5684 cp_save_expr (TREE_OPERAND (arg1, 0)));
5685 else
5686 arg2 = arg1 = cp_save_expr (arg1);
5687 }
5688
5689 /* If something has already gone wrong, just pass that fact up the
5690 tree. */
5691 if (error_operand_p (t: arg1)
5692 || error_operand_p (t: arg2)
5693 || error_operand_p (t: arg3))
5694 return error_mark_node;
5695
5696 conversion_obstack_sentinel cos;
5697
5698 orig_arg2 = arg2;
5699 orig_arg3 = arg3;
5700
5701 if (gnu_vector_type_p (TREE_TYPE (arg1))
5702 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5703 {
5704 tree arg1_type = TREE_TYPE (arg1);
5705
5706 /* If arg1 is another cond_expr choosing between -1 and 0,
5707 then we can use its comparison. It may help to avoid
5708 additional comparison, produce more accurate diagnostics
5709 and enables folding. */
5710 if (TREE_CODE (arg1) == VEC_COND_EXPR
5711 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5712 && integer_zerop (TREE_OPERAND (arg1, 2)))
5713 arg1 = TREE_OPERAND (arg1, 0);
5714
5715 arg1 = force_rvalue (arg1, complain);
5716 arg2 = force_rvalue (arg2, complain);
5717 arg3 = force_rvalue (arg3, complain);
5718
5719 /* force_rvalue can return error_mark on valid arguments. */
5720 if (error_operand_p (t: arg1)
5721 || error_operand_p (t: arg2)
5722 || error_operand_p (t: arg3))
5723 return error_mark_node;
5724
5725 arg2_type = TREE_TYPE (arg2);
5726 arg3_type = TREE_TYPE (arg3);
5727
5728 if (!VECTOR_TYPE_P (arg2_type)
5729 && !VECTOR_TYPE_P (arg3_type))
5730 {
5731 /* Rely on the error messages of the scalar version. */
5732 tree scal = build_conditional_expr (loc, integer_one_node,
5733 arg2: orig_arg2, arg3: orig_arg3, complain);
5734 if (scal == error_mark_node)
5735 return error_mark_node;
5736 tree stype = TREE_TYPE (scal);
5737 tree ctype = TREE_TYPE (arg1_type);
5738 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5739 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5740 {
5741 if (complain & tf_error)
5742 error_at (loc, "inferred scalar type %qT is not an integer or "
5743 "floating-point type of the same size as %qT", stype,
5744 COMPARISON_CLASS_P (arg1)
5745 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5746 : ctype);
5747 return error_mark_node;
5748 }
5749
5750 tree vtype = build_opaque_vector_type (stype,
5751 TYPE_VECTOR_SUBPARTS (node: arg1_type));
5752 /* We could pass complain & tf_warning to unsafe_conversion_p,
5753 but the warnings (like Wsign-conversion) have already been
5754 given by the scalar build_conditional_expr_1. We still check
5755 unsafe_conversion_p to forbid truncating long long -> float. */
5756 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5757 {
5758 if (complain & tf_error)
5759 error_at (loc, "conversion of scalar %qH to vector %qI "
5760 "involves truncation", arg2_type, vtype);
5761 return error_mark_node;
5762 }
5763 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5764 {
5765 if (complain & tf_error)
5766 error_at (loc, "conversion of scalar %qH to vector %qI "
5767 "involves truncation", arg3_type, vtype);
5768 return error_mark_node;
5769 }
5770
5771 arg2 = cp_convert (stype, arg2, complain);
5772 arg2 = save_expr (arg2);
5773 arg2 = build_vector_from_val (vtype, arg2);
5774 arg2_type = vtype;
5775 arg3 = cp_convert (stype, arg3, complain);
5776 arg3 = save_expr (arg3);
5777 arg3 = build_vector_from_val (vtype, arg3);
5778 arg3_type = vtype;
5779 }
5780
5781 if ((gnu_vector_type_p (type: arg2_type) && !VECTOR_TYPE_P (arg3_type))
5782 || (gnu_vector_type_p (type: arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5783 {
5784 enum stv_conv convert_flag =
5785 scalar_to_vector (loc, code: VEC_COND_EXPR, op0: arg2, op1: arg3,
5786 complain & tf_error);
5787
5788 switch (convert_flag)
5789 {
5790 case stv_error:
5791 return error_mark_node;
5792 case stv_firstarg:
5793 {
5794 arg2 = save_expr (arg2);
5795 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5796 arg2 = build_vector_from_val (arg3_type, arg2);
5797 arg2_type = TREE_TYPE (arg2);
5798 break;
5799 }
5800 case stv_secondarg:
5801 {
5802 arg3 = save_expr (arg3);
5803 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5804 arg3 = build_vector_from_val (arg2_type, arg3);
5805 arg3_type = TREE_TYPE (arg3);
5806 break;
5807 }
5808 default:
5809 break;
5810 }
5811 }
5812
5813 if (!gnu_vector_type_p (type: arg2_type)
5814 || !gnu_vector_type_p (type: arg3_type)
5815 || !same_type_p (arg2_type, arg3_type)
5816 || maybe_ne (a: TYPE_VECTOR_SUBPARTS (node: arg1_type),
5817 b: TYPE_VECTOR_SUBPARTS (node: arg2_type))
5818 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5819 {
5820 if (complain & tf_error)
5821 error_at (loc,
5822 "incompatible vector types in conditional expression: "
5823 "%qT, %qT and %qT", TREE_TYPE (arg1),
5824 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5825 return error_mark_node;
5826 }
5827
5828 if (!COMPARISON_CLASS_P (arg1))
5829 {
5830 tree cmp_type = truth_type_for (arg1_type);
5831 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5832 }
5833 return build3_loc (loc, code: VEC_COND_EXPR, type: arg2_type, arg0: arg1, arg1: arg2, arg2: arg3);
5834 }
5835
5836 /* [expr.cond]
5837
5838 The first expression is implicitly converted to bool (clause
5839 _conv_). */
5840 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5841 LOOKUP_NORMAL);
5842 if (error_operand_p (t: arg1))
5843 return error_mark_node;
5844
5845 arg2_type = unlowered_expr_type (arg2);
5846 arg3_type = unlowered_expr_type (arg3);
5847
5848 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5849 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5850 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5851 || SCALAR_FLOAT_TYPE_P (arg2_type)
5852 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5853 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5854 || SCALAR_FLOAT_TYPE_P (arg3_type)
5855 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5856 {
5857 semantic_result_type
5858 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5859 if (semantic_result_type == error_mark_node)
5860 {
5861 tree t1 = arg2_type;
5862 tree t2 = arg3_type;
5863 if (TREE_CODE (t1) == COMPLEX_TYPE)
5864 t1 = TREE_TYPE (t1);
5865 if (TREE_CODE (t2) == COMPLEX_TYPE)
5866 t2 = TREE_TYPE (t2);
5867 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
5868 && SCALAR_FLOAT_TYPE_P (t2)
5869 && (extended_float_type_p (t1)
5870 || extended_float_type_p (t2))
5871 && cp_compare_floating_point_conversion_ranks
5872 (t1, t2) == 3);
5873 if (complain & tf_error)
5874 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5875 "have unordered conversion rank",
5876 arg2_type, arg3_type);
5877 return error_mark_node;
5878 }
5879 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5880 {
5881 arg2 = TREE_OPERAND (arg2, 0);
5882 arg2_type = TREE_TYPE (arg2);
5883 }
5884 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5885 {
5886 arg3 = TREE_OPERAND (arg3, 0);
5887 arg3_type = TREE_TYPE (arg3);
5888 }
5889 }
5890
5891 /* [expr.cond]
5892
5893 If either the second or the third operand has type (possibly
5894 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5895 array-to-pointer (_conv.array_), and function-to-pointer
5896 (_conv.func_) standard conversions are performed on the second
5897 and third operands. */
5898 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5899 {
5900 /* 'void' won't help in resolving an overloaded expression on the
5901 other side, so require it to resolve by itself. */
5902 if (arg2_type == unknown_type_node)
5903 {
5904 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5905 arg2_type = TREE_TYPE (arg2);
5906 }
5907 if (arg3_type == unknown_type_node)
5908 {
5909 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5910 arg3_type = TREE_TYPE (arg3);
5911 }
5912
5913 /* [expr.cond]
5914
5915 One of the following shall hold:
5916
5917 --The second or the third operand (but not both) is a
5918 throw-expression (_except.throw_); the result is of the type
5919 and value category of the other.
5920
5921 --Both the second and the third operands have type void; the
5922 result is of type void and is a prvalue. */
5923 if (TREE_CODE (arg2) == THROW_EXPR
5924 && TREE_CODE (arg3) != THROW_EXPR)
5925 {
5926 result_type = arg3_type;
5927 is_glvalue = glvalue_p (arg3);
5928 }
5929 else if (TREE_CODE (arg2) != THROW_EXPR
5930 && TREE_CODE (arg3) == THROW_EXPR)
5931 {
5932 result_type = arg2_type;
5933 is_glvalue = glvalue_p (arg2);
5934 }
5935 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5936 {
5937 result_type = void_type_node;
5938 is_glvalue = false;
5939 }
5940 else
5941 {
5942 if (complain & tf_error)
5943 {
5944 if (VOID_TYPE_P (arg2_type))
5945 error_at (cp_expr_loc_or_loc (t: arg3, or_loc: loc),
5946 "second operand to the conditional operator "
5947 "is of type %<void%>, but the third operand is "
5948 "neither a throw-expression nor of type %<void%>");
5949 else
5950 error_at (cp_expr_loc_or_loc (t: arg2, or_loc: loc),
5951 "third operand to the conditional operator "
5952 "is of type %<void%>, but the second operand is "
5953 "neither a throw-expression nor of type %<void%>");
5954 }
5955 return error_mark_node;
5956 }
5957
5958 goto valid_operands;
5959 }
5960 /* [expr.cond]
5961
5962 Otherwise, if the second and third operand have different types,
5963 and either has (possibly cv-qualified) class type, or if both are
5964 glvalues of the same value category and the same type except for
5965 cv-qualification, an attempt is made to convert each of those operands
5966 to the type of the other. */
5967 else if (!same_type_p (arg2_type, arg3_type)
5968 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5969 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5970 arg3_type)
5971 && glvalue_p (arg2) && glvalue_p (arg3)
5972 && lvalue_p (arg2) == lvalue_p (arg3))))
5973 {
5974 conversion *conv2;
5975 conversion *conv3;
5976 bool converted = false;
5977
5978 conv2 = conditional_conversion (e1: arg2, e2: arg3, complain);
5979 conv3 = conditional_conversion (e1: arg3, e2: arg2, complain);
5980
5981 /* [expr.cond]
5982
5983 If both can be converted, or one can be converted but the
5984 conversion is ambiguous, the program is ill-formed. If
5985 neither can be converted, the operands are left unchanged and
5986 further checking is performed as described below. If exactly
5987 one conversion is possible, that conversion is applied to the
5988 chosen operand and the converted operand is used in place of
5989 the original operand for the remainder of this section. */
5990 if ((conv2 && !conv2->bad_p
5991 && conv3 && !conv3->bad_p)
5992 || (conv2 && conv2->kind == ck_ambig)
5993 || (conv3 && conv3->kind == ck_ambig))
5994 {
5995 if (complain & tf_error)
5996 {
5997 error_at (loc, "operands to %<?:%> have different types "
5998 "%qT and %qT",
5999 arg2_type, arg3_type);
6000 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
6001 inform (loc, " and each type can be converted to the other");
6002 else if (conv2 && conv2->kind == ck_ambig)
6003 convert_like (conv2, arg2, complain);
6004 else
6005 convert_like (conv3, arg3, complain);
6006 }
6007 result = error_mark_node;
6008 }
6009 else if (conv2 && !conv2->bad_p)
6010 {
6011 arg2 = convert_like (conv2, arg2, complain);
6012 arg2 = convert_from_reference (arg2);
6013 arg2_type = TREE_TYPE (arg2);
6014 /* Even if CONV2 is a valid conversion, the result of the
6015 conversion may be invalid. For example, if ARG3 has type
6016 "volatile X", and X does not have a copy constructor
6017 accepting a "volatile X&", then even if ARG2 can be
6018 converted to X, the conversion will fail. */
6019 if (error_operand_p (t: arg2))
6020 result = error_mark_node;
6021 converted = true;
6022 }
6023 else if (conv3 && !conv3->bad_p)
6024 {
6025 arg3 = convert_like (conv3, arg3, complain);
6026 arg3 = convert_from_reference (arg3);
6027 arg3_type = TREE_TYPE (arg3);
6028 if (error_operand_p (t: arg3))
6029 result = error_mark_node;
6030 converted = true;
6031 }
6032
6033 if (result)
6034 return result;
6035
6036 /* If, after the conversion, both operands have class type,
6037 treat the cv-qualification of both operands as if it were the
6038 union of the cv-qualification of the operands.
6039
6040 The standard is not clear about what to do in this
6041 circumstance. For example, if the first operand has type
6042 "const X" and the second operand has a user-defined
6043 conversion to "volatile X", what is the type of the second
6044 operand after this step? Making it be "const X" (matching
6045 the first operand) seems wrong, as that discards the
6046 qualification without actually performing a copy. Leaving it
6047 as "volatile X" seems wrong as that will result in the
6048 conditional expression failing altogether, even though,
6049 according to this step, the one operand could be converted to
6050 the type of the other. */
6051 if (converted
6052 && CLASS_TYPE_P (arg2_type)
6053 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
6054 arg2_type = arg3_type =
6055 cp_build_qualified_type (arg2_type,
6056 cp_type_quals (arg2_type)
6057 | cp_type_quals (arg3_type));
6058 }
6059
6060 /* [expr.cond]
6061
6062 If the second and third operands are glvalues of the same value
6063 category and have the same type, the result is of that type and
6064 value category. */
6065 if (((lvalue_p (arg2) && lvalue_p (arg3))
6066 || (xvalue_p (arg2) && xvalue_p (arg3)))
6067 && same_type_p (arg2_type, arg3_type))
6068 {
6069 result_type = arg2_type;
6070 goto valid_operands;
6071 }
6072
6073 /* [expr.cond]
6074
6075 Otherwise, the result is an rvalue. If the second and third
6076 operand do not have the same type, and either has (possibly
6077 cv-qualified) class type, overload resolution is used to
6078 determine the conversions (if any) to be applied to the operands
6079 (_over.match.oper_, _over.built_). */
6080 is_glvalue = false;
6081 if (!same_type_p (arg2_type, arg3_type)
6082 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6083 {
6084 releasing_vec args;
6085 conversion *conv;
6086 bool any_viable_p;
6087
6088 /* Rearrange the arguments so that add_builtin_candidate only has
6089 to know about two args. In build_builtin_candidate, the
6090 arguments are unscrambled. */
6091 args->quick_push (obj: arg2);
6092 args->quick_push (obj: arg3);
6093 args->quick_push (obj: arg1);
6094 add_builtin_candidates (candidates: &candidates,
6095 code: COND_EXPR,
6096 code2: NOP_EXPR,
6097 fnname: ovl_op_identifier (isass: false, code: COND_EXPR),
6098 argv: args,
6099 LOOKUP_NORMAL, complain);
6100
6101 /* [expr.cond]
6102
6103 If the overload resolution fails, the program is
6104 ill-formed. */
6105 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
6106 if (!any_viable_p)
6107 {
6108 if (complain & tf_error)
6109 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6110 arg2_type, arg3_type);
6111 return error_mark_node;
6112 }
6113 cand = tourney (candidates, complain);
6114 if (!cand)
6115 {
6116 if (complain & tf_error)
6117 {
6118 auto_diagnostic_group d;
6119 op_error (loc, code: COND_EXPR, code2: NOP_EXPR, arg1, arg2, arg3, match: false);
6120 print_z_candidates (loc, candidates);
6121 }
6122 return error_mark_node;
6123 }
6124
6125 /* [expr.cond]
6126
6127 Otherwise, the conversions thus determined are applied, and
6128 the converted operands are used in place of the original
6129 operands for the remainder of this section. */
6130 conv = cand->convs[0];
6131 arg1 = convert_like (conv, arg1, complain);
6132 conv = cand->convs[1];
6133 arg2 = convert_like (conv, arg2, complain);
6134 arg2_type = TREE_TYPE (arg2);
6135 conv = cand->convs[2];
6136 arg3 = convert_like (conv, arg3, complain);
6137 arg3_type = TREE_TYPE (arg3);
6138 }
6139
6140 /* [expr.cond]
6141
6142 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6143 and function-to-pointer (_conv.func_) standard conversions are
6144 performed on the second and third operands.
6145
6146 We need to force the lvalue-to-rvalue conversion here for class types,
6147 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6148 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6149 regions. */
6150
6151 arg2 = force_rvalue (arg2, complain);
6152 if (!CLASS_TYPE_P (arg2_type))
6153 arg2_type = TREE_TYPE (arg2);
6154
6155 arg3 = force_rvalue (arg3, complain);
6156 if (!CLASS_TYPE_P (arg3_type))
6157 arg3_type = TREE_TYPE (arg3);
6158
6159 if (arg2 == error_mark_node || arg3 == error_mark_node)
6160 return error_mark_node;
6161
6162 /* [expr.cond]
6163
6164 After those conversions, one of the following shall hold:
6165
6166 --The second and third operands have the same type; the result is of
6167 that type. */
6168 if (same_type_p (arg2_type, arg3_type))
6169 result_type = arg2_type;
6170 /* [expr.cond]
6171
6172 --The second and third operands have arithmetic or enumeration
6173 type; the usual arithmetic conversions are performed to bring
6174 them to a common type, and the result is of that type. */
6175 else if ((ARITHMETIC_TYPE_P (arg2_type)
6176 || UNSCOPED_ENUM_P (arg2_type))
6177 && (ARITHMETIC_TYPE_P (arg3_type)
6178 || UNSCOPED_ENUM_P (arg3_type)))
6179 {
6180 /* A conditional expression between a floating-point
6181 type and an integer type should convert the integer type to
6182 the evaluation format of the floating-point type, with
6183 possible excess precision. */
6184 tree eptype2 = arg2_type;
6185 tree eptype3 = arg3_type;
6186 tree eptype;
6187 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6188 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6189 {
6190 eptype3 = eptype;
6191 if (!semantic_result_type)
6192 semantic_result_type
6193 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6194 }
6195 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6196 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6197 {
6198 eptype2 = eptype;
6199 if (!semantic_result_type)
6200 semantic_result_type
6201 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6202 }
6203 result_type = type_after_usual_arithmetic_conversions (eptype2,
6204 eptype3);
6205 if (result_type == error_mark_node)
6206 {
6207 tree t1 = eptype2;
6208 tree t2 = eptype3;
6209 if (TREE_CODE (t1) == COMPLEX_TYPE)
6210 t1 = TREE_TYPE (t1);
6211 if (TREE_CODE (t2) == COMPLEX_TYPE)
6212 t2 = TREE_TYPE (t2);
6213 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6214 && SCALAR_FLOAT_TYPE_P (t2)
6215 && (extended_float_type_p (t1)
6216 || extended_float_type_p (t2))
6217 && cp_compare_floating_point_conversion_ranks
6218 (t1, t2) == 3);
6219 if (complain & tf_error)
6220 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6221 "have unordered conversion rank",
6222 eptype2, eptype3);
6223 return error_mark_node;
6224 }
6225 if (semantic_result_type == error_mark_node)
6226 {
6227 tree t1 = arg2_type;
6228 tree t2 = arg3_type;
6229 if (TREE_CODE (t1) == COMPLEX_TYPE)
6230 t1 = TREE_TYPE (t1);
6231 if (TREE_CODE (t2) == COMPLEX_TYPE)
6232 t2 = TREE_TYPE (t2);
6233 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6234 && SCALAR_FLOAT_TYPE_P (t2)
6235 && (extended_float_type_p (t1)
6236 || extended_float_type_p (t2))
6237 && cp_compare_floating_point_conversion_ranks
6238 (t1, t2) == 3);
6239 if (complain & tf_error)
6240 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6241 "have unordered conversion rank",
6242 arg2_type, arg3_type);
6243 return error_mark_node;
6244 }
6245
6246 if (complain & tf_warning)
6247 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6248 "implicit conversion from %qH to %qI to "
6249 "match other result of conditional",
6250 loc);
6251
6252 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6253 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6254 {
6255 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (exp: orig_arg2);
6256 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (exp: orig_arg3);
6257 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6258 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6259 && (DECL_CONTEXT (stripped_orig_arg2)
6260 == DECL_CONTEXT (stripped_orig_arg3)))
6261 /* Two enumerators from the same enumeration can have different
6262 types when the enumeration is still being defined. */;
6263 else if (complain & (cxx_dialect >= cxx26
6264 ? tf_warning_or_error : tf_warning))
6265 emit_diagnostic (cxx_dialect >= cxx26 ? DK_PEDWARN : DK_WARNING,
6266 loc, OPT_Wenum_compare, "enumerated mismatch "
6267 "in conditional expression: %qT vs %qT",
6268 arg2_type, arg3_type);
6269 else if (cxx_dialect >= cxx26)
6270 return error_mark_node;
6271 }
6272 else if ((((complain & (cxx_dialect >= cxx26
6273 ? tf_warning_or_error : tf_warning))
6274 && warn_deprecated_enum_float_conv)
6275 || (cxx_dialect >= cxx26
6276 && (complain & tf_warning_or_error) == 0))
6277 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6278 && SCALAR_FLOAT_TYPE_P (arg3_type))
6279 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6280 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6281 {
6282 if (cxx_dialect >= cxx26 && (complain & tf_warning_or_error) == 0)
6283 return error_mark_node;
6284 if (cxx_dialect >= cxx26 && TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6285 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6286 "conditional expression between enumeration type "
6287 "%qT and floating-point type %qT", arg2_type, arg3_type);
6288 else if (cxx_dialect >= cxx26)
6289 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6290 "conditional expression between floating-point type "
6291 "%qT and enumeration type %qT", arg2_type, arg3_type);
6292 else if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6293 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6294 "conditional expression between enumeration type "
6295 "%qT and floating-point type %qT is deprecated",
6296 arg2_type, arg3_type);
6297 else
6298 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6299 "conditional expression between floating-point "
6300 "type %qT and enumeration type %qT is deprecated",
6301 arg2_type, arg3_type);
6302 }
6303 else if ((extra_warnings || warn_enum_conversion)
6304 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6305 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6306 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6307 && !same_type_p (arg2_type,
6308 type_promotes_to (arg3_type)))))
6309 {
6310 if (complain & tf_warning)
6311 {
6312 enum opt_code opt = (warn_enum_conversion
6313 ? OPT_Wenum_conversion
6314 : OPT_Wextra);
6315 warning_at (loc, opt, "enumerated and "
6316 "non-enumerated type in conditional expression");
6317 }
6318 }
6319
6320 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6321 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6322 }
6323 /* [expr.cond]
6324
6325 --The second and third operands have pointer type, or one has
6326 pointer type and the other is a null pointer constant; pointer
6327 conversions (_conv.ptr_) and qualification conversions
6328 (_conv.qual_) are performed to bring them to their composite
6329 pointer type (_expr.rel_). The result is of the composite
6330 pointer type.
6331
6332 --The second and third operands have pointer to member type, or
6333 one has pointer to member type and the other is a null pointer
6334 constant; pointer to member conversions (_conv.mem_) and
6335 qualification conversions (_conv.qual_) are performed to bring
6336 them to a common type, whose cv-qualification shall match the
6337 cv-qualification of either the second or the third operand.
6338 The result is of the common type. */
6339 else if ((null_ptr_cst_p (t: arg2)
6340 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6341 || (null_ptr_cst_p (t: arg3)
6342 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6343 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6344 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6345 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6346 {
6347 result_type = composite_pointer_type (loc,
6348 arg2_type, arg3_type, arg2,
6349 arg3, CPO_CONDITIONAL_EXPR,
6350 complain);
6351 if (result_type == error_mark_node)
6352 return error_mark_node;
6353 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6354 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6355 }
6356
6357 if (!result_type)
6358 {
6359 if (complain & tf_error)
6360 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6361 arg2_type, arg3_type);
6362 return error_mark_node;
6363 }
6364
6365 if (arg2 == error_mark_node || arg3 == error_mark_node)
6366 return error_mark_node;
6367
6368 valid_operands:
6369 if (processing_template_decl && is_glvalue)
6370 {
6371 /* Let lvalue_kind know this was a glvalue. */
6372 tree arg = (result_type == arg2_type ? arg2 : arg3);
6373 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6374 }
6375
6376 result = build3_loc (loc, code: COND_EXPR, type: result_type, arg0: arg1, arg1: arg2, arg2: arg3);
6377
6378 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6379 warn here, because the COND_EXPR will be turned into ARG2. */
6380 if (warn_duplicated_branches
6381 && (complain & tf_warning)
6382 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6383 flags: OEP_ADDRESS_OF_SAME_FIELD)))
6384 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6385 "this condition has identical branches");
6386
6387 /* We can't use result_type below, as fold might have returned a
6388 throw_expr. */
6389
6390 if (!is_glvalue)
6391 {
6392 /* Expand both sides into the same slot, hopefully the target of
6393 the ?: expression. We used to check for TARGET_EXPRs here,
6394 but now we sometimes wrap them in NOP_EXPRs so the test would
6395 fail. */
6396 if (CLASS_TYPE_P (TREE_TYPE (result)))
6397 {
6398 result = get_target_expr (result, complain);
6399 /* Tell gimplify_modify_expr_rhs not to strip this in
6400 assignment context: we want both arms to initialize
6401 the same temporary. */
6402 TARGET_EXPR_NO_ELIDE (result) = true;
6403 }
6404 /* If this expression is an rvalue, but might be mistaken for an
6405 lvalue, we must add a NON_LVALUE_EXPR. */
6406 result = rvalue (result);
6407 if (semantic_result_type)
6408 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6409 result);
6410 }
6411 else
6412 {
6413 result = force_paren_expr (result);
6414 gcc_assert (semantic_result_type == NULL_TREE);
6415 }
6416
6417 return result;
6418}
6419
6420/* OPERAND is an operand to an expression. Perform necessary steps
6421 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6422 returned. */
6423
6424static tree
6425prep_operand (tree operand)
6426{
6427 if (operand)
6428 {
6429 if (CLASS_TYPE_P (TREE_TYPE (operand))
6430 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6431 /* Make sure the template type is instantiated now. */
6432 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6433 }
6434
6435 return operand;
6436}
6437
6438/* True iff CONV represents a conversion sequence which no other can be better
6439 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6440 type (including binding to a reference to the same type). This is stronger
6441 than the standard's "identity" category, which also includes reference
6442 bindings that add cv-qualifiers or change rvalueness. */
6443
6444static bool
6445perfect_conversion_p (conversion *conv)
6446{
6447 if (CONVERSION_RANK (conv) != cr_identity)
6448 return false;
6449 if (conv->kind == ck_ref_bind)
6450 {
6451 if (!conv->rvaluedness_matches_p)
6452 return false;
6453 if (!same_type_p (TREE_TYPE (conv->type),
6454 next_conversion (conv)->type))
6455 return false;
6456 }
6457 if (conv->check_narrowing)
6458 /* Brace elision is imperfect. */
6459 return false;
6460 return true;
6461}
6462
6463/* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6464 other candidate can be a better match. Since the template/non-template
6465 tiebreaker comes immediately after the conversion comparison in
6466 [over.match.best], a perfect non-template candidate is better than all
6467 templates. */
6468
6469static bool
6470perfect_candidate_p (z_candidate *cand)
6471{
6472 if (cand->viable < 1)
6473 return false;
6474 /* CWG1402 makes an implicitly deleted move op worse than other
6475 candidates. */
6476 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6477 && move_fn_p (cand->fn))
6478 return false;
6479 int len = cand->num_convs;
6480 for (int i = 0; i < len; ++i)
6481 if (!perfect_conversion_p (conv: cand->convs[i]))
6482 return false;
6483 if (conversion *conv = cand->second_conv)
6484 if (!perfect_conversion_p (conv))
6485 return false;
6486 return true;
6487}
6488
6489/* True iff one of CAND's argument conversions is missing. */
6490
6491static bool
6492missing_conversion_p (const z_candidate *cand)
6493{
6494 for (unsigned i = 0; i < cand->num_convs; ++i)
6495 {
6496 conversion *conv = cand->convs[i];
6497 if (!conv)
6498 return true;
6499 if (conv->kind == ck_deferred_bad)
6500 {
6501 /* We don't know whether this conversion is outright invalid or
6502 just bad, so conservatively assume it's missing. */
6503 gcc_checking_assert (conv->bad_p);
6504 return true;
6505 }
6506 }
6507 return false;
6508}
6509
6510/* Add each of the viable functions in FNS (a FUNCTION_DECL or
6511 OVERLOAD) to the CANDIDATES, returning an updated list of
6512 CANDIDATES. The ARGS are the arguments provided to the call;
6513 if FIRST_ARG is non-null it is the implicit object argument,
6514 otherwise the first element of ARGS is used if needed. The
6515 EXPLICIT_TARGS are explicit template arguments provided.
6516 TEMPLATE_ONLY is true if only template functions should be
6517 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6518 add_function_candidate. */
6519
6520static void
6521add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6522 tree return_type,
6523 tree explicit_targs, bool template_only,
6524 tree conversion_path, tree access_path,
6525 int flags,
6526 struct z_candidate **candidates,
6527 tsubst_flags_t complain)
6528{
6529 tree ctype;
6530 const vec<tree, va_gc> *non_static_args;
6531 bool check_list_ctor = false;
6532 bool check_converting = false;
6533 unification_kind_t strict;
6534 tree ne_fns = NULL_TREE;
6535
6536 if (!fns)
6537 return;
6538
6539 /* Precalculate special handling of constructors and conversion ops. */
6540 tree fn = OVL_FIRST (fns);
6541 if (DECL_CONV_FN_P (fn))
6542 {
6543 check_list_ctor = false;
6544 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6545 if (flags & LOOKUP_NO_CONVERSION)
6546 /* We're doing return_type(x). */
6547 strict = DEDUCE_CONV;
6548 else
6549 /* We're doing x.operator return_type(). */
6550 strict = DEDUCE_EXACT;
6551 /* [over.match.funcs] For conversion functions, the function
6552 is considered to be a member of the class of the implicit
6553 object argument for the purpose of defining the type of
6554 the implicit object parameter. */
6555 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6556 }
6557 else
6558 {
6559 if (DECL_CONSTRUCTOR_P (fn))
6560 {
6561 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6562 /* For list-initialization we consider explicit constructors
6563 and complain if one is chosen. */
6564 check_converting
6565 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6566 == LOOKUP_ONLYCONVERTING);
6567 }
6568 strict = DEDUCE_CALL;
6569 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6570 }
6571
6572 /* P2468: Check if operator== is a rewrite target with first operand
6573 (*args)[0]; for now just do the lookups. */
6574 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6575 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6576 {
6577 tree ne_name = ovl_op_identifier (isass: false, code: NE_EXPR);
6578 if (DECL_CLASS_SCOPE_P (fn))
6579 {
6580 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6581 1, tf_none);
6582 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6583 ne_fns = NULL_TREE;
6584 else
6585 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6586 }
6587 else
6588 {
6589 tree context = decl_namespace_context (fn);
6590 ne_fns = lookup_qualified_name (scope: context, name: ne_name, LOOK_want::NORMAL,
6591 /*complain*/false);
6592 if (ne_fns == error_mark_node
6593 || !is_overloaded_fn (ne_fns))
6594 ne_fns = NULL_TREE;
6595 }
6596 }
6597
6598 if (first_arg)
6599 non_static_args = args;
6600 else
6601 /* Delay creating the implicit this parameter until it is needed. */
6602 non_static_args = NULL;
6603
6604 bool seen_strictly_viable = any_strictly_viable (cands: *candidates);
6605 /* If there's a non-template perfect match, we don't need to consider
6606 templates. So check non-templates first. This optimization is only
6607 really needed for the defaulted copy constructor of tuple and the like
6608 (96926), but it seems like we might as well enable it more generally. */
6609 bool seen_perfect = false;
6610 enum { templates, non_templates, either } which = either;
6611 if (template_only)
6612 which = templates;
6613 else /*if (flags & LOOKUP_DEFAULTED)*/
6614 which = non_templates;
6615
6616 /* Template candidates that we'll potentially ignore if the
6617 perfect candidate optimization succeeds. */
6618 z_candidate *ignored_template_cands = nullptr;
6619
6620 /* During overload resolution, we first consider each function under the
6621 assumption that we'll eventually find a strictly viable candidate.
6622 This allows us to circumvent our defacto behavior when checking
6623 argument conversions and shortcut consideration of the candidate
6624 upon encountering the first bad conversion. If this assumption
6625 turns out to be false, and all candidates end up being non-strictly
6626 viable, then we reconsider such candidates under the defacto behavior.
6627 This trick is important for pruning member function overloads according
6628 to their const/ref-qualifiers (since all 'this' conversions are at
6629 worst bad) without breaking -fpermissive. */
6630 z_candidate *bad_cands = nullptr;
6631 bool shortcut_bad_convs = true;
6632
6633 again:
6634 for (tree fn : lkp_range (fns))
6635 {
6636 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6637 {
6638 if (template_only)
6639 add_ignored_candidate (candidates, fn);
6640 continue;
6641 }
6642 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6643 {
6644 add_ignored_candidate (candidates: &ignored_template_cands, fn);
6645 continue;
6646 }
6647 if ((check_converting && DECL_NONCONVERTING_P (fn))
6648 || (check_list_ctor && !is_list_ctor (fn)))
6649 {
6650 add_ignored_candidate (candidates, fn);
6651 continue;
6652 }
6653
6654 tree fn_first_arg = NULL_TREE;
6655 const vec<tree, va_gc> *fn_args = args;
6656
6657 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn))
6658 {
6659 /* Figure out where the object arg comes from. If this
6660 function is a non-static member and we didn't get an
6661 implicit object argument, move it out of args. */
6662 if (first_arg == NULL_TREE)
6663 {
6664 unsigned int ix;
6665 tree arg;
6666 vec<tree, va_gc> *tempvec;
6667 vec_alloc (v&: tempvec, nelems: args->length () - 1);
6668 for (ix = 1; args->iterate (ix, ptr: &arg); ++ix)
6669 tempvec->quick_push (obj: arg);
6670 non_static_args = tempvec;
6671 first_arg = (*args)[0];
6672 }
6673
6674 fn_first_arg = first_arg;
6675 fn_args = non_static_args;
6676 }
6677
6678 /* Don't bother reversing an operator with two identical parameters. */
6679 else if (vec_safe_length (v: args) == 2 && (flags & LOOKUP_REVERSED))
6680 {
6681 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6682 if (same_type_p (TREE_VALUE (parmlist),
6683 TREE_VALUE (TREE_CHAIN (parmlist))))
6684 continue;
6685 }
6686
6687 /* When considering reversed operator==, if there's a corresponding
6688 operator!= in the same scope, it's not a rewrite target. */
6689 if (ne_fns)
6690 {
6691 bool found = false;
6692 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6693 if (0 && !ne.using_p ()
6694 && DECL_NAMESPACE_SCOPE_P (fn)
6695 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6696 /* ??? This kludge excludes inline namespace members for the H
6697 test in spaceship-eq15.C, but I don't see why we would want
6698 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6699 else if (fns_correspond (fn, *ne))
6700 {
6701 found = true;
6702 break;
6703 }
6704 if (found)
6705 continue;
6706 }
6707
6708 if (TREE_CODE (fn) == TEMPLATE_DECL)
6709 add_template_candidate (candidates,
6710 tmpl: fn,
6711 ctype,
6712 explicit_targs,
6713 first_arg: fn_first_arg,
6714 arglist: fn_args,
6715 return_type,
6716 access_path,
6717 conversion_path,
6718 flags,
6719 strict,
6720 shortcut_bad_convs,
6721 complain);
6722 else
6723 {
6724 add_function_candidate (candidates,
6725 fn,
6726 ctype,
6727 first_arg: fn_first_arg,
6728 args: fn_args,
6729 access_path,
6730 conversion_path,
6731 flags,
6732 NULL,
6733 shortcut_bad_convs,
6734 complain);
6735 if (perfect_candidate_p (cand: *candidates))
6736 seen_perfect = true;
6737 }
6738
6739 z_candidate *cand = *candidates;
6740 if (cand->viable == 1)
6741 seen_strictly_viable = true;
6742
6743 if (cand->viable == -1
6744 && shortcut_bad_convs
6745 && missing_conversion_p (cand))
6746 {
6747 /* This candidate has been tentatively marked non-strictly viable,
6748 and we didn't compute all argument conversions for it (having
6749 stopped at the first bad conversion). Move it to BAD_CANDS to
6750 to fully reconsider later if we don't find any strictly viable
6751 candidates. */
6752 if (complain & (tf_error | tf_conv))
6753 {
6754 *candidates = cand->next;
6755 cand->next = bad_cands;
6756 bad_cands = cand;
6757 }
6758 else
6759 /* But if we're in a SFINAE context, just mark this candidate as
6760 unviable outright and avoid potentially reconsidering it.
6761 This is safe to do because in a SFINAE context, performing a bad
6762 conversion is always an error (even with -fpermissive), so a
6763 non-strictly viable candidate is effectively unviable anyway. */
6764 cand->viable = 0;
6765 }
6766 }
6767 if (which == non_templates && !seen_perfect)
6768 {
6769 which = templates;
6770 ignored_template_cands = nullptr;
6771 goto again;
6772 }
6773 else if (which == templates
6774 && !seen_strictly_viable
6775 && shortcut_bad_convs
6776 && bad_cands)
6777 {
6778 /* None of the candidates are strictly viable, so consider again those
6779 functions in BAD_CANDS, this time without shortcutting bad conversions
6780 so that all their argument conversions are computed. */
6781 which = either;
6782 fns = NULL_TREE;
6783 for (z_candidate *cand = bad_cands; cand; cand = cand->next)
6784 {
6785 tree fn = cand->fn;
6786 if (tree ti = cand->template_decl)
6787 fn = TI_TEMPLATE (ti);
6788 fns = ovl_make (fn, next: fns);
6789 }
6790 shortcut_bad_convs = false;
6791 bad_cands = nullptr;
6792 goto again;
6793 }
6794
6795 if (complain & tf_error)
6796 {
6797 /* Remember any omitted candidates; we may want to print all candidates
6798 as part of overload resolution failure diagnostics. */
6799 for (z_candidate *omitted_cands : { ignored_template_cands, bad_cands })
6800 {
6801 z_candidate **omitted_cands_tail = &omitted_cands;
6802 while (*omitted_cands_tail)
6803 omitted_cands_tail = &(*omitted_cands_tail)->next;
6804 *omitted_cands_tail = *candidates;
6805 *candidates = omitted_cands;
6806 }
6807 }
6808}
6809
6810/* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6811 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6812
6813static int
6814op_is_ordered (tree_code code)
6815{
6816 switch (code)
6817 {
6818 // 5. b @= a
6819 case MODIFY_EXPR:
6820 return (flag_strong_eval_order > 1 ? -1 : 0);
6821
6822 // 6. a[b]
6823 case ARRAY_REF:
6824 return (flag_strong_eval_order > 1 ? 1 : 0);
6825
6826 // 1. a.b
6827 // Not overloadable (yet).
6828 // 2. a->b
6829 // Only one argument.
6830 // 3. a->*b
6831 case MEMBER_REF:
6832 // 7. a << b
6833 case LSHIFT_EXPR:
6834 // 8. a >> b
6835 case RSHIFT_EXPR:
6836 // a && b
6837 // Predates P0145R3.
6838 case TRUTH_ANDIF_EXPR:
6839 // a || b
6840 // Predates P0145R3.
6841 case TRUTH_ORIF_EXPR:
6842 // a , b
6843 // Predates P0145R3.
6844 case COMPOUND_EXPR:
6845 return (flag_strong_eval_order ? 1 : 0);
6846
6847 default:
6848 return 0;
6849 }
6850}
6851
6852/* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6853 operator indicated by CODE/CODE2. This function calls itself recursively to
6854 handle C++20 rewritten comparison operator candidates. Returns NULL_TREE
6855 upon success, and error_mark_node if something went wrong that prevented
6856 us from performing overload resolution (e.g. ambiguous member name lookup).
6857
6858 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6859 overloads to consider. This parameter is used when instantiating a
6860 dependent operator expression and has the same structure as
6861 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6862
6863static tree
6864add_operator_candidates (z_candidate **candidates,
6865 tree_code code, tree_code code2,
6866 vec<tree, va_gc> *arglist, tree lookups,
6867 int flags, tsubst_flags_t complain)
6868{
6869 z_candidate *start_candidates = *candidates;
6870 bool ismodop = code2 != ERROR_MARK;
6871 tree fnname = ovl_op_identifier (isass: ismodop, code: ismodop ? code2 : code);
6872
6873 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6874 rewrite from, and also when we're looking for the e.g. < operator to use
6875 on the result of <=>. In the latter case, we don't want the flag set in
6876 the candidate, we just want to suppress looking for rewrites. */
6877 bool rewritten = (flags & LOOKUP_REWRITTEN);
6878 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6879 flags &= ~LOOKUP_REWRITTEN;
6880
6881 bool memonly = false;
6882 switch (code)
6883 {
6884 /* =, ->, [], () must be non-static member functions. */
6885 case MODIFY_EXPR:
6886 if (code2 != NOP_EXPR)
6887 break;
6888 /* FALLTHRU */
6889 case COMPONENT_REF:
6890 case ARRAY_REF:
6891 memonly = true;
6892 break;
6893
6894 default:
6895 break;
6896 }
6897
6898 /* Add namespace-scope operators to the list of functions to
6899 consider. */
6900 if (!memonly)
6901 {
6902 tree fns;
6903 if (!lookups)
6904 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6905 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6906 expression, and LOOKUPS is the result of stage 1 name lookup. */
6907 else if (tree found = purpose_member (fnname, lookups))
6908 fns = TREE_VALUE (found);
6909 else
6910 fns = NULL_TREE;
6911 fns = lookup_arg_dependent (fnname, fns, arglist);
6912 add_candidates (fns, NULL_TREE, args: arglist, NULL_TREE,
6913 NULL_TREE, template_only: false, NULL_TREE, NULL_TREE,
6914 flags, candidates, complain);
6915 }
6916
6917 /* Add class-member operators to the candidate set. */
6918 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6919 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6920 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6921 if (CLASS_TYPE_P (arg1_type))
6922 {
6923 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6924 if (fns == error_mark_node)
6925 return error_mark_node;
6926 if (fns)
6927 {
6928 if (code == ARRAY_REF)
6929 {
6930 vec<tree,va_gc> *restlist = make_tree_vector ();
6931 for (unsigned i = 1; i < nargs; ++i)
6932 vec_safe_push (v&: restlist, obj: (*arglist)[i]);
6933 z_candidate *save_cand = *candidates;
6934 add_candidates (BASELINK_FUNCTIONS (fns),
6935 first_arg: (*arglist)[0], args: restlist, NULL_TREE,
6936 NULL_TREE, template_only: false,
6937 BASELINK_BINFO (fns),
6938 BASELINK_ACCESS_BINFO (fns),
6939 flags, candidates, complain);
6940 /* Release the vec if we didn't add a candidate that uses it. */
6941 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6942 if (c->args == restlist)
6943 {
6944 restlist = NULL;
6945 break;
6946 }
6947 release_tree_vector (restlist);
6948 }
6949 else
6950 add_candidates (BASELINK_FUNCTIONS (fns),
6951 NULL_TREE, args: arglist, NULL_TREE,
6952 NULL_TREE, template_only: false,
6953 BASELINK_BINFO (fns),
6954 BASELINK_ACCESS_BINFO (fns),
6955 flags, candidates, complain);
6956 }
6957 }
6958 /* Per [over.match.oper]3.2, if no operand has a class type, then
6959 only non-member functions that have type T1 or reference to
6960 cv-qualified-opt T1 for the first argument, if the first argument
6961 has an enumeration type, or T2 or reference to cv-qualified-opt
6962 T2 for the second argument, if the second argument has an
6963 enumeration type. Filter out those that don't match. */
6964 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6965 {
6966 struct z_candidate **candp, **next;
6967
6968 for (candp = candidates; *candp != start_candidates; candp = next)
6969 {
6970 unsigned i;
6971 z_candidate *cand = *candp;
6972 next = &cand->next;
6973
6974 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6975
6976 for (i = 0; i < nargs; ++i)
6977 {
6978 tree parmtype = TREE_VALUE (parmlist);
6979 tree argtype = unlowered_expr_type ((*arglist)[i]);
6980
6981 if (TYPE_REF_P (parmtype))
6982 parmtype = TREE_TYPE (parmtype);
6983 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6984 && (same_type_ignoring_top_level_qualifiers_p
6985 (argtype, parmtype)))
6986 break;
6987
6988 parmlist = TREE_CHAIN (parmlist);
6989 }
6990
6991 /* No argument has an appropriate type, so remove this
6992 candidate function from the list. */
6993 if (i == nargs)
6994 {
6995 *candp = cand->next;
6996 next = candp;
6997 }
6998 }
6999 }
7000
7001 if (!rewritten)
7002 {
7003 /* The standard says to rewrite built-in candidates, too,
7004 but there's no point. */
7005 add_builtin_candidates (candidates, code, code2, fnname, argv: arglist,
7006 flags, complain);
7007
7008 /* Maybe add C++20 rewritten comparison candidates. */
7009 tree_code rewrite_code = ERROR_MARK;
7010 if (cxx_dialect >= cxx20
7011 && nargs == 2
7012 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
7013 switch (code)
7014 {
7015 case LT_EXPR:
7016 case LE_EXPR:
7017 case GT_EXPR:
7018 case GE_EXPR:
7019 case SPACESHIP_EXPR:
7020 rewrite_code = SPACESHIP_EXPR;
7021 break;
7022
7023 case NE_EXPR:
7024 case EQ_EXPR:
7025 rewrite_code = EQ_EXPR;
7026 break;
7027
7028 default:;
7029 }
7030
7031 if (rewrite_code)
7032 {
7033 tree r;
7034 flags |= LOOKUP_REWRITTEN;
7035 if (rewrite_code != code)
7036 {
7037 /* Add rewritten candidates in same order. */
7038 r = add_operator_candidates (candidates, code: rewrite_code, code2: ERROR_MARK,
7039 arglist, lookups, flags, complain);
7040 if (r == error_mark_node)
7041 return error_mark_node;
7042 }
7043
7044 z_candidate *save_cand = *candidates;
7045
7046 /* Add rewritten candidates in reverse order. */
7047 flags |= LOOKUP_REVERSED;
7048 vec<tree,va_gc> *revlist = make_tree_vector ();
7049 revlist->quick_push (obj: (*arglist)[1]);
7050 revlist->quick_push (obj: (*arglist)[0]);
7051 r = add_operator_candidates (candidates, code: rewrite_code, code2: ERROR_MARK,
7052 arglist: revlist, lookups, flags, complain);
7053 if (r == error_mark_node)
7054 return error_mark_node;
7055
7056 /* Release the vec if we didn't add a candidate that uses it. */
7057 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7058 if (c->args == revlist)
7059 {
7060 revlist = NULL;
7061 break;
7062 }
7063 release_tree_vector (revlist);
7064 }
7065 }
7066
7067 return NULL_TREE;
7068}
7069
7070tree
7071build_new_op (const op_location_t &loc, enum tree_code code, int flags,
7072 tree arg1, tree arg2, tree arg3, tree lookups,
7073 tree *overload, tsubst_flags_t complain)
7074{
7075 struct z_candidate *candidates = 0, *cand;
7076 releasing_vec arglist;
7077 tree result = NULL_TREE;
7078 bool result_valid_p = false;
7079 enum tree_code code2 = ERROR_MARK;
7080 enum tree_code code_orig_arg1 = ERROR_MARK;
7081 enum tree_code code_orig_arg2 = ERROR_MARK;
7082 bool strict_p;
7083 bool any_viable_p;
7084
7085 auto_cond_timevar tv (TV_OVERLOAD);
7086
7087 if (error_operand_p (t: arg1)
7088 || error_operand_p (t: arg2)
7089 || error_operand_p (t: arg3))
7090 return error_mark_node;
7091
7092 conversion_obstack_sentinel cos;
7093
7094 bool ismodop = code == MODIFY_EXPR;
7095 if (ismodop)
7096 {
7097 code2 = TREE_CODE (arg3);
7098 arg3 = NULL_TREE;
7099 }
7100
7101 tree arg1_type = unlowered_expr_type (arg1);
7102 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
7103
7104 arg1 = prep_operand (operand: arg1);
7105
7106 switch (code)
7107 {
7108 case NEW_EXPR:
7109 case VEC_NEW_EXPR:
7110 case VEC_DELETE_EXPR:
7111 case DELETE_EXPR:
7112 /* Use build_operator_new_call and build_op_delete_call instead. */
7113 gcc_unreachable ();
7114
7115 case CALL_EXPR:
7116 /* Use build_op_call instead. */
7117 gcc_unreachable ();
7118
7119 case TRUTH_ORIF_EXPR:
7120 case TRUTH_ANDIF_EXPR:
7121 case TRUTH_AND_EXPR:
7122 case TRUTH_OR_EXPR:
7123 /* These are saved for the sake of warn_logical_operator. */
7124 code_orig_arg1 = TREE_CODE (arg1);
7125 code_orig_arg2 = TREE_CODE (arg2);
7126 break;
7127 case GT_EXPR:
7128 case LT_EXPR:
7129 case GE_EXPR:
7130 case LE_EXPR:
7131 case EQ_EXPR:
7132 case NE_EXPR:
7133 /* These are saved for the sake of maybe_warn_bool_compare. */
7134 code_orig_arg1 = TREE_CODE (arg1_type);
7135 code_orig_arg2 = TREE_CODE (arg2_type);
7136 break;
7137
7138 default:
7139 break;
7140 }
7141
7142 arg2 = prep_operand (operand: arg2);
7143 arg3 = prep_operand (operand: arg3);
7144
7145 if (code == COND_EXPR)
7146 /* Use build_conditional_expr instead. */
7147 gcc_unreachable ();
7148 else if (! OVERLOAD_TYPE_P (arg1_type)
7149 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7150 goto builtin;
7151
7152 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7153 {
7154 arg2 = integer_zero_node;
7155 arg2_type = integer_type_node;
7156 }
7157
7158 arglist->quick_push (obj: arg1);
7159 if (arg2 != NULL_TREE)
7160 arglist->quick_push (obj: arg2);
7161 if (arg3 != NULL_TREE)
7162 arglist->quick_push (obj: arg3);
7163
7164 result = add_operator_candidates (candidates: &candidates, code, code2, arglist,
7165 lookups, flags, complain);
7166 if (result == error_mark_node)
7167 return error_mark_node;
7168
7169 switch (code)
7170 {
7171 case COMPOUND_EXPR:
7172 case ADDR_EXPR:
7173 /* For these, the built-in candidates set is empty
7174 [over.match.oper]/3. We don't want non-strict matches
7175 because exact matches are always possible with built-in
7176 operators. The built-in candidate set for COMPONENT_REF
7177 would be empty too, but since there are no such built-in
7178 operators, we accept non-strict matches for them. */
7179 strict_p = true;
7180 break;
7181
7182 default:
7183 strict_p = false;
7184 break;
7185 }
7186
7187 candidates = splice_viable (cands: candidates, strict_p, any_viable_p: &any_viable_p);
7188 if (!any_viable_p)
7189 {
7190 switch (code)
7191 {
7192 case POSTINCREMENT_EXPR:
7193 case POSTDECREMENT_EXPR:
7194 /* Don't try anything fancy if we're not allowed to produce
7195 errors. */
7196 if (!(complain & tf_error))
7197 return error_mark_node;
7198
7199 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7200 distinguish between prefix and postfix ++ and
7201 operator++() was used for both, so we allow this with
7202 -fpermissive. */
7203 else
7204 {
7205 tree fnname = ovl_op_identifier (isass: ismodop, code: ismodop ? code2 : code);
7206 const char *msg = (flag_permissive)
7207 ? G_("no %<%D(int)%> declared for postfix %qs,"
7208 " trying prefix operator instead")
7209 : G_("no %<%D(int)%> declared for postfix %qs");
7210 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7211 }
7212
7213 if (!flag_permissive)
7214 return error_mark_node;
7215
7216 if (code == POSTINCREMENT_EXPR)
7217 code = PREINCREMENT_EXPR;
7218 else
7219 code = PREDECREMENT_EXPR;
7220 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7221 NULL_TREE, lookups, overload, complain);
7222 break;
7223
7224 /* The caller will deal with these. */
7225 case ADDR_EXPR:
7226 case COMPOUND_EXPR:
7227 case COMPONENT_REF:
7228 case CO_AWAIT_EXPR:
7229 result = NULL_TREE;
7230 result_valid_p = true;
7231 break;
7232
7233 default:
7234 if (complain & tf_error)
7235 {
7236 /* If one of the arguments of the operator represents
7237 an invalid use of member function pointer, try to report
7238 a meaningful error ... */
7239 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7240 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7241 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7242 /* We displayed the error message. */;
7243 else
7244 {
7245 /* ... Otherwise, report the more generic
7246 "no matching operator found" error */
7247 auto_diagnostic_group d;
7248 op_error (loc, code, code2, arg1, arg2, arg3, match: false);
7249 print_z_candidates (loc, candidates);
7250 }
7251 }
7252 result = error_mark_node;
7253 break;
7254 }
7255 }
7256 else
7257 {
7258 cand = tourney (candidates, complain);
7259 if (cand == 0)
7260 {
7261 if (complain & tf_error)
7262 {
7263 auto_diagnostic_group d;
7264 op_error (loc, code, code2, arg1, arg2, arg3, match: true);
7265 print_z_candidates (loc, candidates);
7266 }
7267 result = error_mark_node;
7268 if (overload)
7269 *overload = error_mark_node;
7270 }
7271 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7272 {
7273 if (overload)
7274 *overload = cand->fn;
7275
7276 if (resolve_args (args: arglist, complain) == NULL)
7277 result = error_mark_node;
7278 else
7279 {
7280 tsubst_flags_t ocomplain = complain;
7281 if (cand->rewritten ())
7282 /* We'll wrap this call in another one. */
7283 ocomplain &= ~tf_decltype;
7284 if (cand->reversed ())
7285 {
7286 /* We swapped these in add_candidate, swap them back now. */
7287 std::swap (a&: cand->convs[0], b&: cand->convs[1]);
7288 if (cand->fn == current_function_decl)
7289 warning_at (loc, 0, "in C++20 this comparison calls the "
7290 "current function recursively with reversed "
7291 "arguments");
7292 }
7293 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7294 }
7295
7296 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7297 /* There won't be a CALL_EXPR. */;
7298 else if (result && result != error_mark_node)
7299 {
7300 tree call = extract_call_expr (result);
7301 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7302
7303 /* Specify evaluation order as per P0145R2. */
7304 CALL_EXPR_ORDERED_ARGS (call) = false;
7305 switch (op_is_ordered (code))
7306 {
7307 case -1:
7308 CALL_EXPR_REVERSE_ARGS (call) = true;
7309 break;
7310
7311 case 1:
7312 CALL_EXPR_ORDERED_ARGS (call) = true;
7313 break;
7314
7315 default:
7316 break;
7317 }
7318 }
7319
7320 /* If this was a C++20 rewritten comparison, adjust the result. */
7321 if (cand->rewritten ())
7322 {
7323 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7324 if (overload)
7325 *overload = NULL_TREE;
7326 switch (code)
7327 {
7328 case EQ_EXPR:
7329 gcc_checking_assert (cand->reversed ());
7330 gcc_fallthrough ();
7331 case NE_EXPR:
7332 if (result == error_mark_node)
7333 ;
7334 /* If a rewritten operator== candidate is selected by
7335 overload resolution for an operator @, its return type
7336 shall be cv bool.... */
7337 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7338 {
7339 if (complain & tf_error)
7340 {
7341 auto_diagnostic_group d;
7342 error_at (loc, "return type of %qD is not %qs",
7343 cand->fn, "bool");
7344 inform (loc, "used as rewritten candidate for "
7345 "comparison of %qT and %qT",
7346 arg1_type, arg2_type);
7347 }
7348 result = error_mark_node;
7349 }
7350 else if (code == NE_EXPR)
7351 /* !(y == x) or !(x == y) */
7352 result = build1_loc (loc, code: TRUTH_NOT_EXPR,
7353 boolean_type_node, arg1: result);
7354 break;
7355
7356 /* If a rewritten operator<=> candidate is selected by
7357 overload resolution for an operator @, x @ y is
7358 interpreted as 0 @ (y <=> x) if the selected candidate is
7359 a synthesized candidate with reversed order of parameters,
7360 or (x <=> y) @ 0 otherwise, using the selected rewritten
7361 operator<=> candidate. */
7362 case SPACESHIP_EXPR:
7363 if (!cand->reversed ())
7364 /* We're in the build_new_op call below for an outer
7365 reversed call; we don't need to do anything more. */
7366 break;
7367 gcc_fallthrough ();
7368 case LT_EXPR:
7369 case LE_EXPR:
7370 case GT_EXPR:
7371 case GE_EXPR:
7372 {
7373 tree lhs = result;
7374 tree rhs = integer_zero_node;
7375 if (cand->reversed ())
7376 std::swap (a&: lhs, b&: rhs);
7377 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7378 result = build_new_op (loc, code,
7379 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7380 arg1: lhs, arg2: rhs, NULL_TREE, lookups,
7381 NULL, complain);
7382 }
7383 break;
7384
7385 default:
7386 gcc_unreachable ();
7387 }
7388 }
7389
7390 /* In an expression of the form `a[]' where cand->fn
7391 which is operator[] turns out to be a static member function,
7392 `a' is none-the-less evaluated. */
7393 if (code == ARRAY_REF)
7394 result = keep_unused_object_arg (result, obj: arg1, fn: cand->fn);
7395 }
7396 else
7397 {
7398 /* Give any warnings we noticed during overload resolution. */
7399 if (cand->warnings && (complain & tf_warning))
7400 {
7401 struct candidate_warning *w;
7402 for (w = cand->warnings; w; w = w->next)
7403 joust (cand, w->loser, 1, complain);
7404 }
7405
7406 /* Check for comparison of different enum types. */
7407 switch (code)
7408 {
7409 case GT_EXPR:
7410 case LT_EXPR:
7411 case GE_EXPR:
7412 case LE_EXPR:
7413 case EQ_EXPR:
7414 case NE_EXPR:
7415 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7416 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7417 && (TYPE_MAIN_VARIANT (arg1_type)
7418 != TYPE_MAIN_VARIANT (arg2_type)))
7419 {
7420 if (cxx_dialect >= cxx26
7421 && (complain & tf_warning_or_error) == 0)
7422 result = error_mark_node;
7423 else if (cxx_dialect >= cxx26 || (complain & tf_warning))
7424 emit_diagnostic (cxx_dialect >= cxx26
7425 ? DK_PEDWARN : DK_WARNING,
7426 loc, OPT_Wenum_compare,
7427 "comparison between %q#T and %q#T",
7428 arg1_type, arg2_type);
7429 }
7430 break;
7431 default:
7432 break;
7433 }
7434
7435 /* "If a built-in candidate is selected by overload resolution, the
7436 operands of class type are converted to the types of the
7437 corresponding parameters of the selected operation function,
7438 except that the second standard conversion sequence of a
7439 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7440 conversion *conv = cand->convs[0];
7441 if (conv->user_conv_p)
7442 {
7443 conv = strip_standard_conversion (conv);
7444 arg1 = convert_like (conv, arg1, complain);
7445 }
7446
7447 if (arg2)
7448 {
7449 conv = cand->convs[1];
7450 if (conv->user_conv_p)
7451 {
7452 conv = strip_standard_conversion (conv);
7453 arg2 = convert_like (conv, arg2, complain);
7454 }
7455 }
7456
7457 if (arg3)
7458 {
7459 conv = cand->convs[2];
7460 if (conv->user_conv_p)
7461 {
7462 conv = strip_standard_conversion (conv);
7463 arg3 = convert_like (conv, arg3, complain);
7464 }
7465 }
7466 }
7467 }
7468
7469 if (result || result_valid_p)
7470 return result;
7471
7472 builtin:
7473 switch (code)
7474 {
7475 case MODIFY_EXPR:
7476 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7477
7478 case INDIRECT_REF:
7479 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7480
7481 case TRUTH_ANDIF_EXPR:
7482 case TRUTH_ORIF_EXPR:
7483 case TRUTH_AND_EXPR:
7484 case TRUTH_OR_EXPR:
7485 if ((complain & tf_warning) && !processing_template_decl)
7486 warn_logical_operator (loc, code, boolean_type_node,
7487 code_orig_arg1, arg1,
7488 code_orig_arg2, arg2);
7489 /* Fall through. */
7490 case GT_EXPR:
7491 case LT_EXPR:
7492 case GE_EXPR:
7493 case LE_EXPR:
7494 case EQ_EXPR:
7495 case NE_EXPR:
7496 if ((complain & tf_warning)
7497 && ((code_orig_arg1 == BOOLEAN_TYPE)
7498 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7499 maybe_warn_bool_compare (loc, code, arg1, arg2);
7500 if (complain & tf_warning && warn_tautological_compare)
7501 warn_tautological_cmp (loc, code, arg1, arg2);
7502 /* Fall through. */
7503 case SPACESHIP_EXPR:
7504 case PLUS_EXPR:
7505 case MINUS_EXPR:
7506 case MULT_EXPR:
7507 case TRUNC_DIV_EXPR:
7508 case MAX_EXPR:
7509 case MIN_EXPR:
7510 case LSHIFT_EXPR:
7511 case RSHIFT_EXPR:
7512 case TRUNC_MOD_EXPR:
7513 case BIT_AND_EXPR:
7514 case BIT_IOR_EXPR:
7515 case BIT_XOR_EXPR:
7516 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7517
7518 case UNARY_PLUS_EXPR:
7519 case NEGATE_EXPR:
7520 case BIT_NOT_EXPR:
7521 case TRUTH_NOT_EXPR:
7522 case PREINCREMENT_EXPR:
7523 case POSTINCREMENT_EXPR:
7524 case PREDECREMENT_EXPR:
7525 case POSTDECREMENT_EXPR:
7526 case REALPART_EXPR:
7527 case IMAGPART_EXPR:
7528 case ABS_EXPR:
7529 case CO_AWAIT_EXPR:
7530 return cp_build_unary_op (code, arg1, false, complain);
7531
7532 case ARRAY_REF:
7533 return cp_build_array_ref (input_location, arg1, arg2, complain);
7534
7535 case MEMBER_REF:
7536 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7537 RO_ARROW_STAR,
7538 complain),
7539 arg2, complain);
7540
7541 /* The caller will deal with these. */
7542 case ADDR_EXPR:
7543 case COMPONENT_REF:
7544 case COMPOUND_EXPR:
7545 return NULL_TREE;
7546
7547 default:
7548 gcc_unreachable ();
7549 }
7550 return NULL_TREE;
7551}
7552
7553/* Build a new call to operator[]. This may change ARGS. */
7554
7555tree
7556build_op_subscript (const op_location_t &loc, tree obj,
7557 vec<tree, va_gc> **args, tree *overload,
7558 tsubst_flags_t complain)
7559{
7560 struct z_candidate *candidates = 0, *cand;
7561 tree fns, first_mem_arg = NULL_TREE;
7562 bool any_viable_p;
7563 tree result = NULL_TREE;
7564
7565 auto_cond_timevar tv (TV_OVERLOAD);
7566
7567 obj = mark_lvalue_use (obj);
7568
7569 if (error_operand_p (t: obj))
7570 return error_mark_node;
7571
7572 tree type = TREE_TYPE (obj);
7573
7574 obj = prep_operand (operand: obj);
7575
7576 if (TYPE_BINFO (type))
7577 {
7578 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (code: ARRAY_REF),
7579 1, complain);
7580 if (fns == error_mark_node)
7581 return error_mark_node;
7582 }
7583 else
7584 fns = NULL_TREE;
7585
7586 if (args != NULL && *args != NULL)
7587 {
7588 *args = resolve_args (args: *args, complain);
7589 if (*args == NULL)
7590 return error_mark_node;
7591 }
7592
7593 conversion_obstack_sentinel cos;
7594
7595 if (fns)
7596 {
7597 first_mem_arg = obj;
7598
7599 add_candidates (BASELINK_FUNCTIONS (fns),
7600 first_arg: first_mem_arg, args: *args, NULL_TREE,
7601 NULL_TREE, template_only: false,
7602 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7603 LOOKUP_NORMAL, candidates: &candidates, complain);
7604 }
7605
7606 /* Be strict here because if we choose a bad conversion candidate, the
7607 errors we get won't mention the call context. */
7608 candidates = splice_viable (cands: candidates, strict_p: true, any_viable_p: &any_viable_p);
7609 if (!any_viable_p)
7610 {
7611 if (complain & tf_error)
7612 {
7613 auto_diagnostic_group d;
7614 error ("no match for call to %<%T::operator[] (%A)%>",
7615 TREE_TYPE (obj), build_tree_list_vec (*args));
7616 print_z_candidates (loc, candidates);
7617 }
7618 result = error_mark_node;
7619 }
7620 else
7621 {
7622 cand = tourney (candidates, complain);
7623 if (cand == 0)
7624 {
7625 if (complain & tf_error)
7626 {
7627 auto_diagnostic_group d;
7628 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7629 TREE_TYPE (obj), build_tree_list_vec (*args));
7630 print_z_candidates (loc, candidates);
7631 }
7632 result = error_mark_node;
7633 }
7634 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7635 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7636 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7637 {
7638 if (overload)
7639 *overload = cand->fn;
7640 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7641 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7642 /* There won't be a CALL_EXPR. */;
7643 else if (result && result != error_mark_node)
7644 {
7645 tree call = extract_call_expr (result);
7646 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7647
7648 /* Specify evaluation order as per P0145R2. */
7649 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (code: ARRAY_REF) == 1;
7650 }
7651
7652 /* In an expression of the form `a[]' where cand->fn
7653 which is operator[] turns out to be a static member function,
7654 `a' is none-the-less evaluated. */
7655 result = keep_unused_object_arg (result, obj, fn: cand->fn);
7656 }
7657 else
7658 gcc_unreachable ();
7659 }
7660
7661 return result;
7662}
7663
7664/* CALL was returned by some call-building function; extract the actual
7665 CALL_EXPR from any bits that have been tacked on, e.g. by
7666 convert_from_reference. */
7667
7668tree
7669extract_call_expr (tree call)
7670{
7671 while (TREE_CODE (call) == COMPOUND_EXPR)
7672 call = TREE_OPERAND (call, 1);
7673 if (REFERENCE_REF_P (call))
7674 call = TREE_OPERAND (call, 0);
7675 if (TREE_CODE (call) == TARGET_EXPR)
7676 call = TARGET_EXPR_INITIAL (call);
7677 if (cxx_dialect >= cxx20)
7678 switch (TREE_CODE (call))
7679 {
7680 /* C++20 rewritten comparison operators. */
7681 case TRUTH_NOT_EXPR:
7682 call = TREE_OPERAND (call, 0);
7683 break;
7684 case LT_EXPR:
7685 case LE_EXPR:
7686 case GT_EXPR:
7687 case GE_EXPR:
7688 case SPACESHIP_EXPR:
7689 {
7690 tree op0 = TREE_OPERAND (call, 0);
7691 if (integer_zerop (op0))
7692 call = TREE_OPERAND (call, 1);
7693 else
7694 call = op0;
7695 }
7696 break;
7697 default:;
7698 }
7699
7700 if (TREE_CODE (call) != CALL_EXPR
7701 && TREE_CODE (call) != AGGR_INIT_EXPR
7702 && call != error_mark_node)
7703 return NULL_TREE;
7704 return call;
7705}
7706
7707/* Returns true if FN has two parameters, of which the second has type
7708 size_t. */
7709
7710static bool
7711second_parm_is_size_t (tree fn)
7712{
7713 tree t = FUNCTION_ARG_CHAIN (fn);
7714 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7715 return false;
7716 t = TREE_CHAIN (t);
7717 if (t == void_list_node)
7718 return true;
7719 return false;
7720}
7721
7722/* True if T, an allocation function, has std::align_val_t as its second
7723 argument. */
7724
7725bool
7726aligned_allocation_fn_p (tree t)
7727{
7728 if (!aligned_new_threshold)
7729 return false;
7730
7731 tree a = FUNCTION_ARG_CHAIN (t);
7732 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7733}
7734
7735/* True if T is std::destroying_delete_t. */
7736
7737static bool
7738std_destroying_delete_t_p (tree t)
7739{
7740 return (TYPE_CONTEXT (t) == std_node
7741 && id_equal (TYPE_IDENTIFIER (t), str: "destroying_delete_t"));
7742}
7743
7744/* A deallocation function with at least two parameters whose second parameter
7745 type is of type std::destroying_delete_t is a destroying operator delete. A
7746 destroying operator delete shall be a class member function named operator
7747 delete. [ Note: Array deletion cannot use a destroying operator
7748 delete. --end note ] */
7749
7750tree
7751destroying_delete_p (tree t)
7752{
7753 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7754 if (!a || !TREE_CHAIN (a))
7755 return NULL_TREE;
7756 tree type = TREE_VALUE (TREE_CHAIN (a));
7757 return std_destroying_delete_t_p (t: type) ? type : NULL_TREE;
7758}
7759
7760struct dealloc_info
7761{
7762 bool sized;
7763 bool aligned;
7764 tree destroying;
7765};
7766
7767/* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7768 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7769 non-null, also set *DI. */
7770
7771static bool
7772usual_deallocation_fn_p (tree t, dealloc_info *di)
7773{
7774 if (di) *di = dealloc_info();
7775
7776 /* A template instance is never a usual deallocation function,
7777 regardless of its signature. */
7778 if (TREE_CODE (t) == TEMPLATE_DECL
7779 || primary_template_specialization_p (t))
7780 return false;
7781
7782 /* A usual deallocation function is a deallocation function whose parameters
7783 after the first are
7784 - optionally, a parameter of type std::destroying_delete_t, then
7785 - optionally, a parameter of type std::size_t, then
7786 - optionally, a parameter of type std::align_val_t. */
7787 bool global = DECL_NAMESPACE_SCOPE_P (t);
7788 tree chain = FUNCTION_ARG_CHAIN (t);
7789 if (chain && destroying_delete_p (t))
7790 {
7791 if (di) di->destroying = TREE_VALUE (chain);
7792 chain = TREE_CHAIN (chain);
7793 }
7794 if (chain
7795 && (!global || flag_sized_deallocation)
7796 && same_type_p (TREE_VALUE (chain), size_type_node))
7797 {
7798 if (di) di->sized = true;
7799 chain = TREE_CHAIN (chain);
7800 }
7801 if (chain && aligned_new_threshold
7802 && same_type_p (TREE_VALUE (chain), align_type_node))
7803 {
7804 if (di) di->aligned = true;
7805 chain = TREE_CHAIN (chain);
7806 }
7807 return (chain == void_list_node);
7808}
7809
7810/* Just return whether FN is a usual deallocation function. */
7811
7812bool
7813usual_deallocation_fn_p (tree fn)
7814{
7815 return usual_deallocation_fn_p (t: fn, NULL);
7816}
7817
7818/* Build a call to operator delete. This has to be handled very specially,
7819 because the restrictions on what signatures match are different from all
7820 other call instances. For a normal delete, only a delete taking (void *)
7821 or (void *, size_t) is accepted. For a placement delete, only an exact
7822 match with the placement new is accepted.
7823
7824 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7825 ADDR is the pointer to be deleted.
7826 SIZE is the size of the memory block to be deleted.
7827 GLOBAL_P is true if the delete-expression should not consider
7828 class-specific delete operators.
7829 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7830
7831 If this call to "operator delete" is being generated as part to
7832 deallocate memory allocated via a new-expression (as per [expr.new]
7833 which requires that if the initialization throws an exception then
7834 we call a deallocation function), then ALLOC_FN is the allocation
7835 function. */
7836
7837tree
7838build_op_delete_call (enum tree_code code, tree addr, tree size,
7839 bool global_p, tree placement,
7840 tree alloc_fn, tsubst_flags_t complain)
7841{
7842 tree fn = NULL_TREE;
7843 tree fns, fnname, type, t;
7844 dealloc_info di_fn = { };
7845
7846 if (addr == error_mark_node)
7847 return error_mark_node;
7848
7849 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7850
7851 fnname = ovl_op_identifier (isass: false, code);
7852
7853 if (CLASS_TYPE_P (type)
7854 && COMPLETE_TYPE_P (complete_type (type))
7855 && !global_p)
7856 /* In [class.free]
7857
7858 If the result of the lookup is ambiguous or inaccessible, or if
7859 the lookup selects a placement deallocation function, the
7860 program is ill-formed.
7861
7862 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7863 {
7864 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7865 if (fns == error_mark_node)
7866 return error_mark_node;
7867 }
7868 else
7869 fns = NULL_TREE;
7870
7871 if (fns == NULL_TREE)
7872 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7873
7874 /* Strip const and volatile from addr. */
7875 tree oaddr = addr;
7876 addr = cp_convert (ptr_type_node, addr, complain);
7877
7878 tree excluded_destroying = NULL_TREE;
7879
7880 if (placement)
7881 {
7882 /* "A declaration of a placement deallocation function matches the
7883 declaration of a placement allocation function if it has the same
7884 number of parameters and, after parameter transformations (8.3.5),
7885 all parameter types except the first are identical."
7886
7887 So we build up the function type we want and ask instantiate_type
7888 to get it for us. */
7889 t = FUNCTION_ARG_CHAIN (alloc_fn);
7890 t = tree_cons (NULL_TREE, ptr_type_node, t);
7891 t = build_function_type (void_type_node, t);
7892
7893 fn = instantiate_type (t, fns, tf_none);
7894 if (fn == error_mark_node)
7895 return NULL_TREE;
7896
7897 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7898
7899 /* "If the lookup finds the two-parameter form of a usual deallocation
7900 function (3.7.4.2) and that function, considered as a placement
7901 deallocation function, would have been selected as a match for the
7902 allocation function, the program is ill-formed." */
7903 if (second_parm_is_size_t (fn))
7904 {
7905 const char *const msg1
7906 = G_("exception cleanup for this placement new selects "
7907 "non-placement %<operator delete%>");
7908 const char *const msg2
7909 = G_("%qD is a usual (non-placement) deallocation "
7910 "function in C++14 (or with %<-fsized-deallocation%>)");
7911
7912 /* But if the class has an operator delete (void *), then that is
7913 the usual deallocation function, so we shouldn't complain
7914 about using the operator delete (void *, size_t). */
7915 if (DECL_CLASS_SCOPE_P (fn))
7916 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7917 {
7918 if (usual_deallocation_fn_p (fn: elt)
7919 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7920 goto ok;
7921 }
7922 /* Before C++14 a two-parameter global deallocation function is
7923 always a placement deallocation function, but warn if
7924 -Wc++14-compat. */
7925 else if (!flag_sized_deallocation)
7926 {
7927 if (complain & tf_warning)
7928 {
7929 auto_diagnostic_group d;
7930 if (warning (OPT_Wc__14_compat, msg1))
7931 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7932 }
7933 goto ok;
7934 }
7935
7936 if (complain & tf_warning_or_error)
7937 {
7938 auto_diagnostic_group d;
7939 if (permerror (input_location, msg1))
7940 {
7941 /* Only mention C++14 for namespace-scope delete. */
7942 if (DECL_NAMESPACE_SCOPE_P (fn))
7943 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7944 else
7945 inform (DECL_SOURCE_LOCATION (fn),
7946 "%qD is a usual (non-placement) deallocation "
7947 "function", fn);
7948 }
7949 }
7950 else
7951 return error_mark_node;
7952 ok:;
7953 }
7954 }
7955 else
7956 /* "Any non-placement deallocation function matches a non-placement
7957 allocation function. If the lookup finds a single matching
7958 deallocation function, that function will be called; otherwise, no
7959 deallocation function will be called." */
7960 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7961 {
7962 dealloc_info di_elt;
7963 if (usual_deallocation_fn_p (t: elt, di: &di_elt))
7964 {
7965 /* If we're called for an EH cleanup in a new-expression, we can't
7966 use a destroying delete; the exception was thrown before the
7967 object was constructed. */
7968 if (alloc_fn && di_elt.destroying)
7969 {
7970 excluded_destroying = elt;
7971 continue;
7972 }
7973
7974 if (!fn)
7975 {
7976 fn = elt;
7977 di_fn = di_elt;
7978 continue;
7979 }
7980
7981 /* -- If any of the deallocation functions is a destroying
7982 operator delete, all deallocation functions that are not
7983 destroying operator deletes are eliminated from further
7984 consideration. */
7985 if (di_elt.destroying != di_fn.destroying)
7986 {
7987 if (di_elt.destroying)
7988 {
7989 fn = elt;
7990 di_fn = di_elt;
7991 }
7992 continue;
7993 }
7994
7995 /* -- If the type has new-extended alignment, a function with a
7996 parameter of type std::align_val_t is preferred; otherwise a
7997 function without such a parameter is preferred. If exactly one
7998 preferred function is found, that function is selected and the
7999 selection process terminates. If more than one preferred
8000 function is found, all non-preferred functions are eliminated
8001 from further consideration. */
8002 if (aligned_new_threshold)
8003 {
8004 bool want_align = type_has_new_extended_alignment (type);
8005 if (di_elt.aligned != di_fn.aligned)
8006 {
8007 if (want_align == di_elt.aligned)
8008 {
8009 fn = elt;
8010 di_fn = di_elt;
8011 }
8012 continue;
8013 }
8014 }
8015
8016 /* -- If the deallocation functions have class scope, the one
8017 without a parameter of type std::size_t is selected. */
8018 bool want_size;
8019 if (DECL_CLASS_SCOPE_P (fn))
8020 want_size = false;
8021
8022 /* -- If the type is complete and if, for the second alternative
8023 (delete array) only, the operand is a pointer to a class type
8024 with a non-trivial destructor or a (possibly multi-dimensional)
8025 array thereof, the function with a parameter of type std::size_t
8026 is selected.
8027
8028 -- Otherwise, it is unspecified whether a deallocation function
8029 with a parameter of type std::size_t is selected. */
8030 else
8031 {
8032 want_size = COMPLETE_TYPE_P (type);
8033 if (code == VEC_DELETE_EXPR
8034 && !TYPE_VEC_NEW_USES_COOKIE (type))
8035 /* We need a cookie to determine the array size. */
8036 want_size = false;
8037 }
8038 gcc_assert (di_fn.sized != di_elt.sized);
8039 if (want_size == di_elt.sized)
8040 {
8041 fn = elt;
8042 di_fn = di_elt;
8043 }
8044 }
8045 }
8046
8047 /* If we have a matching function, call it. */
8048 if (fn)
8049 {
8050 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8051
8052 /* If the FN is a member function, make sure that it is
8053 accessible. */
8054 if (BASELINK_P (fns))
8055 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
8056 complain);
8057
8058 /* Core issue 901: It's ok to new a type with deleted delete. */
8059 if (DECL_DELETED_FN (fn) && alloc_fn)
8060 return NULL_TREE;
8061
8062 tree ret;
8063 if (placement)
8064 {
8065 /* The placement args might not be suitable for overload
8066 resolution at this point, so build the call directly. */
8067 int nargs = call_expr_nargs (placement);
8068 tree *argarray = XALLOCAVEC (tree, nargs);
8069 int i;
8070 argarray[0] = addr;
8071 for (i = 1; i < nargs; i++)
8072 argarray[i] = CALL_EXPR_ARG (placement, i);
8073 if (!mark_used (fn, complain) && !(complain & tf_error))
8074 return error_mark_node;
8075 ret = build_cxx_call (fn, nargs, argarray, complain);
8076 }
8077 else
8078 {
8079 tree destroying = di_fn.destroying;
8080 if (destroying)
8081 {
8082 /* Strip const and volatile from addr but retain the type of the
8083 object. */
8084 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
8085 rtype = cv_unqualified (rtype);
8086 rtype = TYPE_POINTER_TO (rtype);
8087 addr = cp_convert (rtype, oaddr, complain);
8088 destroying = build_functional_cast (input_location,
8089 destroying, NULL_TREE,
8090 complain);
8091 }
8092
8093 releasing_vec args;
8094 args->quick_push (obj: addr);
8095 if (destroying)
8096 args->quick_push (obj: destroying);
8097 if (di_fn.sized)
8098 args->quick_push (obj: size);
8099 if (di_fn.aligned)
8100 {
8101 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
8102 args->quick_push (obj: al);
8103 }
8104 ret = cp_build_function_call_vec (fn, &args, complain);
8105 }
8106
8107 /* Set this flag for all callers of this function. In addition to
8108 delete-expressions, this is called for deallocating coroutine state;
8109 treat that as an implicit delete-expression. This is also called for
8110 the delete if the constructor throws in a new-expression, and for a
8111 deleting destructor (which implements a delete-expression). */
8112 /* But leave this flag off for destroying delete to avoid wrong
8113 assumptions in the optimizers. */
8114 tree call = extract_call_expr (call: ret);
8115 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (t: fn))
8116 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
8117
8118 return ret;
8119 }
8120
8121 /* If there's only a destroying delete that we can't use because the
8122 object isn't constructed yet, and we used global new, use global
8123 delete as well. */
8124 if (excluded_destroying
8125 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
8126 return build_op_delete_call (code, addr, size, global_p: true, placement,
8127 alloc_fn, complain);
8128
8129 /* [expr.new]
8130
8131 If no unambiguous matching deallocation function can be found,
8132 propagating the exception does not cause the object's memory to
8133 be freed. */
8134 if (alloc_fn)
8135 {
8136 if ((complain & tf_warning)
8137 && !placement)
8138 {
8139 bool w = warning (0,
8140 "no corresponding deallocation function for %qD",
8141 alloc_fn);
8142 if (w && excluded_destroying)
8143 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8144 "delete %qD cannot be used to release the allocated memory"
8145 " if the initialization throws because the object is not "
8146 "constructed yet", excluded_destroying);
8147 }
8148 return NULL_TREE;
8149 }
8150
8151 if (complain & tf_error)
8152 error ("no suitable %<operator %s%> for %qT",
8153 OVL_OP_INFO (false, code)->name, type);
8154 return error_mark_node;
8155}
8156
8157/* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8158 in the diagnostics.
8159
8160 If ISSUE_ERROR is true, then issue an error about the access, followed
8161 by a note showing the declaration. Otherwise, just show the note.
8162
8163 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8164 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8165 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8166 would be because DECL was private). If not using NO_ACCESS_REASON,
8167 then it must be ak_none, and the access failure reason will be
8168 figured out by looking at the protection of DECL. */
8169
8170void
8171complain_about_access (tree decl, tree diag_decl, tree diag_location,
8172 bool issue_error, access_kind no_access_reason)
8173{
8174 /* If we have not already figured out why DECL is inaccessible... */
8175 if (no_access_reason == ak_none)
8176 {
8177 /* Examine the access of DECL to find out why. */
8178 if (TREE_PRIVATE (decl))
8179 no_access_reason = ak_private;
8180 else if (TREE_PROTECTED (decl))
8181 no_access_reason = ak_protected;
8182 }
8183
8184 /* Now generate an error message depending on calculated access. */
8185 if (no_access_reason == ak_private)
8186 {
8187 if (issue_error)
8188 error ("%q#D is private within this context", diag_decl);
8189 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8190 }
8191 else if (no_access_reason == ak_protected)
8192 {
8193 if (issue_error)
8194 error ("%q#D is protected within this context", diag_decl);
8195 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8196 }
8197 /* Couldn't figure out why DECL is inaccesible, so just say it's
8198 inaccessible. */
8199 else
8200 {
8201 if (issue_error)
8202 error ("%q#D is inaccessible within this context", diag_decl);
8203 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8204 }
8205}
8206
8207/* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8208 bitwise or of LOOKUP_* values. If any errors are warnings are
8209 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8210 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8211 to NULL. */
8212
8213static tree
8214build_temp (tree expr, tree type, int flags,
8215 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8216{
8217 int savew, savee;
8218
8219 *diagnostic_kind = DK_UNSPECIFIED;
8220
8221 /* If the source is a packed field, calling the copy constructor will require
8222 binding the field to the reference parameter to the copy constructor, and
8223 we'll end up with an infinite loop. If we can use a bitwise copy, then
8224 do that now. */
8225 if ((lvalue_kind (expr) & clk_packed)
8226 && CLASS_TYPE_P (TREE_TYPE (expr))
8227 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8228 return get_target_expr (expr, complain);
8229
8230 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8231 But it turns out to be a subexpression, so perform temporary
8232 materialization now. */
8233 if (TREE_CODE (expr) == CALL_EXPR
8234 && CLASS_TYPE_P (type)
8235 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8236 expr = build_cplus_new (type, expr, complain);
8237
8238 savew = warningcount + werrorcount, savee = errorcount;
8239 releasing_vec args (make_tree_vector_single (expr));
8240 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8241 &args, type, flags, complain);
8242 if (warningcount + werrorcount > savew)
8243 *diagnostic_kind = DK_WARNING;
8244 else if (errorcount > savee)
8245 *diagnostic_kind = DK_ERROR;
8246 return expr;
8247}
8248
8249/* Get any location for EXPR, falling back to input_location.
8250
8251 If the result is in a system header and is the virtual location for
8252 a token coming from the expansion of a macro, unwind it to the
8253 location of the expansion point of the macro (e.g. to avoid the
8254 diagnostic being suppressed for expansions of NULL where "NULL" is
8255 in a system header). */
8256
8257static location_t
8258get_location_for_expr_unwinding_for_system_header (tree expr)
8259{
8260 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8261 loc = expansion_point_location_if_in_system_header (loc);
8262 return loc;
8263}
8264
8265/* Perform warnings about peculiar, but valid, conversions from/to NULL.
8266 Also handle a subset of zero as null warnings.
8267 EXPR is implicitly converted to type TOTYPE.
8268 FN and ARGNUM are used for diagnostics. */
8269
8270static void
8271conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8272{
8273 /* Issue warnings about peculiar, but valid, uses of NULL. */
8274 if (TREE_CODE (totype) != BOOLEAN_TYPE
8275 && ARITHMETIC_TYPE_P (totype)
8276 && null_node_p (expr))
8277 {
8278 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8279 if (fn)
8280 {
8281 auto_diagnostic_group d;
8282 if (warning_at (loc, OPT_Wconversion_null,
8283 "passing NULL to non-pointer argument %P of %qD",
8284 argnum, fn))
8285 inform (get_fndecl_argument_location (fn, argnum),
8286 " declared here");
8287 }
8288 else
8289 warning_at (loc, OPT_Wconversion_null,
8290 "converting to non-pointer type %qT from NULL", totype);
8291 }
8292
8293 /* Issue warnings if "false" is converted to a NULL pointer */
8294 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8295 && TYPE_PTR_P (totype))
8296 {
8297 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8298 if (fn)
8299 {
8300 auto_diagnostic_group d;
8301 if (warning_at (loc, OPT_Wconversion_null,
8302 "converting %<false%> to pointer type for argument "
8303 "%P of %qD", argnum, fn))
8304 inform (get_fndecl_argument_location (fn, argnum),
8305 " declared here");
8306 }
8307 else
8308 warning_at (loc, OPT_Wconversion_null,
8309 "converting %<false%> to pointer type %qT", totype);
8310 }
8311 /* Handle zero as null pointer warnings for cases other
8312 than EQ_EXPR and NE_EXPR */
8313 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8314 && null_ptr_cst_p (t: expr))
8315 {
8316 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8317 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8318 }
8319}
8320
8321/* We gave a diagnostic during a conversion. If this was in the second
8322 standard conversion sequence of a user-defined conversion sequence, say
8323 which user-defined conversion. */
8324
8325static void
8326maybe_print_user_conv_context (conversion *convs)
8327{
8328 if (convs->user_conv_p)
8329 for (conversion *t = convs; t; t = next_conversion (conv: t))
8330 if (t->kind == ck_user)
8331 {
8332 print_z_candidate (loc: 0, N_(" after user-defined conversion:"),
8333 candidate: t->cand);
8334 break;
8335 }
8336}
8337
8338/* Locate the parameter with the given index within FNDECL.
8339 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8340 Return the location of the FNDECL itself if there are problems. */
8341
8342location_t
8343get_fndecl_argument_location (tree fndecl, int argnum)
8344{
8345 /* The locations of implicitly-declared functions are likely to be
8346 more meaningful than those of their parameters. */
8347 if (DECL_ARTIFICIAL (fndecl))
8348 return DECL_SOURCE_LOCATION (fndecl);
8349
8350 int i;
8351 tree param;
8352
8353 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8354 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8355 i < argnum && param;
8356 i++, param = TREE_CHAIN (param))
8357 ;
8358
8359 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8360 return the location of FNDECL. */
8361 if (param == NULL)
8362 return DECL_SOURCE_LOCATION (fndecl);
8363
8364 return DECL_SOURCE_LOCATION (param);
8365}
8366
8367/* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8368 within its declaration (or the fndecl itself if something went
8369 wrong). */
8370
8371void
8372maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
8373{
8374 if (fn)
8375 inform (get_fndecl_argument_location (fndecl: fn, argnum),
8376 " initializing argument %P of %qD", argnum, fn);
8377}
8378
8379/* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8380 the conversion, EXPR is the expression we're converting. */
8381
8382static void
8383maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8384{
8385 if (cxx_dialect >= cxx20)
8386 return;
8387
8388 tree type = TREE_TYPE (expr);
8389 type = strip_pointer_operator (type);
8390
8391 if (TREE_CODE (type) != ARRAY_TYPE
8392 || TYPE_DOMAIN (type) == NULL_TREE)
8393 return;
8394
8395 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8396 pedwarn (loc, OPT_Wc__20_extensions,
8397 "conversions to arrays of unknown bound "
8398 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8399}
8400
8401/* We call this recursively in convert_like_internal. */
8402static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8403 tsubst_flags_t);
8404
8405/* Perform the conversions in CONVS on the expression EXPR. FN and
8406 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8407 indicates the `this' argument of a method. INNER is nonzero when
8408 being called to continue a conversion chain. It is negative when a
8409 reference binding will be applied, positive otherwise. If
8410 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8411 conversions will be emitted if appropriate. If C_CAST_P is true,
8412 this conversion is coming from a C-style cast; in that case,
8413 conversions to inaccessible bases are permitted. */
8414
8415static tree
8416convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8417 bool issue_conversion_warnings, bool c_cast_p,
8418 bool nested_p, tsubst_flags_t complain)
8419{
8420 tree totype = convs->type;
8421 diagnostic_t diag_kind;
8422 int flags;
8423 location_t loc = cp_expr_loc_or_input_loc (t: expr);
8424
8425 if (convs->bad_p && !(complain & tf_error))
8426 return error_mark_node;
8427
8428 if (convs->bad_p
8429 && convs->kind != ck_user
8430 && convs->kind != ck_list
8431 && convs->kind != ck_ambig
8432 && (convs->kind != ck_ref_bind
8433 || (convs->user_conv_p && next_conversion (conv: convs)->bad_p))
8434 && (convs->kind != ck_rvalue
8435 || SCALAR_TYPE_P (totype))
8436 && convs->kind != ck_base)
8437 {
8438 int complained = 0;
8439 conversion *t = convs;
8440
8441 /* Give a helpful error if this is bad because of excess braces. */
8442 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8443 && SCALAR_TYPE_P (totype)
8444 && CONSTRUCTOR_NELTS (expr) > 0
8445 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8446 {
8447 complained = permerror (loc, "too many braces around initializer "
8448 "for %qT", totype);
8449 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8450 && CONSTRUCTOR_NELTS (expr) == 1)
8451 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8452 }
8453
8454 /* Give a helpful error if this is bad because a conversion to bool
8455 from std::nullptr_t requires direct-initialization. */
8456 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8457 && TREE_CODE (totype) == BOOLEAN_TYPE)
8458 complained = permerror (loc, "converting to %qH from %qI requires "
8459 "direct-initialization",
8460 totype, TREE_TYPE (expr));
8461
8462 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8463 && SCALAR_FLOAT_TYPE_P (totype)
8464 && (extended_float_type_p (TREE_TYPE (expr))
8465 || extended_float_type_p (type: totype)))
8466 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8467 totype))
8468 {
8469 case 2:
8470 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8471 "converting to %qH from %qI with greater "
8472 "conversion rank", totype, TREE_TYPE (expr)))
8473 complained = 1;
8474 else if (!complained)
8475 complained = -1;
8476 break;
8477 case 3:
8478 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8479 "converting to %qH from %qI with unordered "
8480 "conversion rank", totype, TREE_TYPE (expr)))
8481 complained = 1;
8482 else if (!complained)
8483 complained = -1;
8484 break;
8485 default:
8486 break;
8487 }
8488
8489 for (; t ; t = next_conversion (conv: t))
8490 {
8491 if (t->kind == ck_user && t->cand->reason)
8492 {
8493 auto_diagnostic_group d;
8494 complained = permerror (loc, "invalid user-defined conversion "
8495 "from %qH to %qI", TREE_TYPE (expr),
8496 totype);
8497 if (complained)
8498 print_z_candidate (loc, N_("candidate is:"), candidate: t->cand);
8499 expr = convert_like (t, expr, fn, argnum,
8500 /*issue_conversion_warnings=*/false,
8501 /*c_cast_p=*/false, /*nested_p=*/true,
8502 complain);
8503 }
8504 else if (t->kind == ck_user || !t->bad_p)
8505 {
8506 expr = convert_like (t, expr, fn, argnum,
8507 /*issue_conversion_warnings=*/false,
8508 /*c_cast_p=*/false, /*nested_p=*/true,
8509 complain);
8510 if (t->bad_p)
8511 complained = 1;
8512 break;
8513 }
8514 else if (t->kind == ck_ambig)
8515 return convert_like (t, expr, fn, argnum,
8516 /*issue_conversion_warnings=*/false,
8517 /*c_cast_p=*/false, /*nested_p=*/true,
8518 complain);
8519 else if (t->kind == ck_identity)
8520 break;
8521 }
8522 if (!complained && expr != error_mark_node)
8523 {
8524 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8525 gcc_rich_location richloc (loc, &label);
8526 complained = permerror (&richloc,
8527 "invalid conversion from %qH to %qI",
8528 TREE_TYPE (expr), totype);
8529 }
8530 if (convs->kind == ck_ref_bind)
8531 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8532 LOOKUP_NORMAL, NULL_TREE,
8533 complain);
8534 else
8535 expr = cp_convert (totype, expr, complain);
8536 if (complained == 1)
8537 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8538 return expr;
8539 }
8540
8541 if (issue_conversion_warnings && (complain & tf_warning))
8542 conversion_null_warnings (totype, expr, fn, argnum);
8543
8544 switch (convs->kind)
8545 {
8546 case ck_user:
8547 {
8548 struct z_candidate *cand = convs->cand;
8549
8550 if (cand == NULL)
8551 /* We chose the surrogate function from add_conv_candidate, now we
8552 actually need to build the conversion. */
8553 cand = build_user_type_conversion_1 (totype, expr,
8554 LOOKUP_NO_CONVERSION, complain);
8555
8556 tree convfn = cand->fn;
8557
8558 /* When converting from an init list we consider explicit
8559 constructors, but actually trying to call one is an error. */
8560 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8561 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8562 /* Unless this is for direct-list-initialization. */
8563 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8564 /* And in C++98 a default constructor can't be explicit. */
8565 && cxx_dialect >= cxx11)
8566 {
8567 if (!(complain & tf_error))
8568 return error_mark_node;
8569 location_t loc = location_of (expr);
8570 if (CONSTRUCTOR_NELTS (expr) == 0
8571 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8572 {
8573 auto_diagnostic_group d;
8574 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8575 "would use explicit constructor %qD",
8576 totype, convfn))
8577 {
8578 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8579 convfn);
8580 inform (loc, "in C++11 and above a default constructor "
8581 "can be explicit");
8582 }
8583 }
8584 else
8585 {
8586 auto_diagnostic_group d;
8587 error ("converting to %qT from initializer list would use "
8588 "explicit constructor %qD", totype, convfn);
8589 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8590 convfn);
8591 }
8592 }
8593
8594 /* If we're initializing from {}, it's value-initialization. */
8595 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8596 && CONSTRUCTOR_NELTS (expr) == 0
8597 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8598 && !processing_template_decl)
8599 {
8600 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8601 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8602 return error_mark_node;
8603 expr = build_value_init (totype, complain);
8604 expr = get_target_expr (expr, complain);
8605 if (expr != error_mark_node)
8606 {
8607 TARGET_EXPR_LIST_INIT_P (expr) = true;
8608 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8609 }
8610 return expr;
8611 }
8612
8613 /* We don't know here whether EXPR is being used as an lvalue or
8614 rvalue, but we know it's read. */
8615 mark_exp_read (expr);
8616
8617 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8618 any more UDCs. */
8619 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8620 complain);
8621
8622 /* If this is a constructor or a function returning an aggr type,
8623 we need to build up a TARGET_EXPR. */
8624 if (DECL_CONSTRUCTOR_P (convfn))
8625 {
8626 expr = build_cplus_new (totype, expr, complain);
8627
8628 /* Remember that this was list-initialization. */
8629 if (convs->check_narrowing && expr != error_mark_node)
8630 TARGET_EXPR_LIST_INIT_P (expr) = true;
8631 }
8632
8633 return expr;
8634 }
8635 case ck_identity:
8636 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8637 {
8638 int nelts = CONSTRUCTOR_NELTS (expr);
8639 if (nelts == 0)
8640 expr = build_value_init (totype, complain);
8641 else if (nelts == 1)
8642 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8643 else
8644 gcc_unreachable ();
8645 }
8646 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8647 /*read_p=*/true, UNKNOWN_LOCATION,
8648 /*reject_builtin=*/true);
8649
8650 if (type_unknown_p (expr))
8651 expr = instantiate_type (totype, expr, complain);
8652 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8653 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8654 if (expr == null_node
8655 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8656 /* If __null has been converted to an integer type, we do not want to
8657 continue to warn about uses of EXPR as an integer, rather than as a
8658 pointer. */
8659 expr = build_int_cst (totype, 0);
8660 return expr;
8661 case ck_ambig:
8662 /* We leave bad_p off ck_ambig because overload resolution considers
8663 it valid, it just fails when we try to perform it. So we need to
8664 check complain here, too. */
8665 if (complain & tf_error)
8666 {
8667 /* Call build_user_type_conversion again for the error. */
8668 int flags = (convs->need_temporary_p
8669 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8670 build_user_type_conversion (totype, expr: convs->u.expr, flags, complain);
8671 gcc_assert (seen_error ());
8672 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8673 }
8674 return error_mark_node;
8675
8676 case ck_list:
8677 {
8678 /* Conversion to std::initializer_list<T>. */
8679 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8680 unsigned len = CONSTRUCTOR_NELTS (expr);
8681 tree array;
8682
8683 if (tree init = maybe_init_list_as_array (elttype, init: expr))
8684 {
8685 elttype = cp_build_qualified_type
8686 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8687 array = build_array_of_n_type (elttype, len);
8688 array = build_vec_init_expr (array, init, complain);
8689 array = get_target_expr (array);
8690 array = cp_build_addr_expr (array, complain);
8691 }
8692 else if (len)
8693 {
8694 tree val; unsigned ix;
8695
8696 tree new_ctor = build_constructor (init_list_type_node, NULL);
8697
8698 /* Convert all the elements. */
8699 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8700 {
8701 tree sub = convert_like (convs->u.list[ix], val, fn,
8702 argnum, false, false,
8703 /*nested_p=*/true, complain);
8704 if (sub == error_mark_node)
8705 return sub;
8706 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8707 && !check_narrowing (TREE_TYPE (sub), val, complain))
8708 return error_mark_node;
8709 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8710 NULL_TREE, sub);
8711 if (!TREE_CONSTANT (sub))
8712 TREE_CONSTANT (new_ctor) = false;
8713 }
8714 /* Build up the array. */
8715 elttype = cp_build_qualified_type
8716 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8717 array = build_array_of_n_type (elttype, len);
8718 array = finish_compound_literal (array, new_ctor, complain);
8719 /* This is dubious now, should be blessed by P2752. */
8720 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
8721 array = cp_build_addr_expr (array, complain);
8722 }
8723 else
8724 array = nullptr_node;
8725
8726 array = cp_convert (build_pointer_type (elttype), array, complain);
8727 if (array == error_mark_node)
8728 return error_mark_node;
8729
8730 /* Build up the initializer_list object. Note: fail gracefully
8731 if the object cannot be completed because, for example, no
8732 definition is provided (c++/80956). */
8733 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8734 if (!totype)
8735 return error_mark_node;
8736 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8737 vec<constructor_elt, va_gc> *vec = NULL;
8738 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8739 field = next_aggregate_field (DECL_CHAIN (field));
8740 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8741 tree new_ctor = build_constructor (totype, vec);
8742 return get_target_expr (new_ctor, complain);
8743 }
8744
8745 case ck_aggr:
8746 if (TREE_CODE (totype) == COMPLEX_TYPE)
8747 {
8748 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8749 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8750 real = perform_implicit_conversion (TREE_TYPE (totype),
8751 real, complain);
8752 imag = perform_implicit_conversion (TREE_TYPE (totype),
8753 imag, complain);
8754 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8755 return expr;
8756 }
8757 expr = reshape_init (totype, expr, complain);
8758 expr = get_target_expr (digest_init (totype, expr, complain),
8759 complain);
8760 if (expr != error_mark_node)
8761 TARGET_EXPR_LIST_INIT_P (expr) = true;
8762 return expr;
8763
8764 default:
8765 break;
8766 };
8767
8768 conversion *nc = next_conversion (conv: convs);
8769 if (convs->kind == ck_ref_bind && nc->kind == ck_qual
8770 && !convs->need_temporary_p)
8771 /* direct_reference_binding might have inserted a ck_qual under
8772 this ck_ref_bind for the benefit of conversion sequence ranking.
8773 Don't actually perform that conversion. */
8774 nc = next_conversion (conv: nc);
8775
8776 expr = convert_like (nc, expr, fn, argnum,
8777 convs->kind == ck_ref_bind
8778 ? issue_conversion_warnings : false,
8779 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8780 if (expr == error_mark_node)
8781 return error_mark_node;
8782
8783 switch (convs->kind)
8784 {
8785 case ck_rvalue:
8786 expr = decay_conversion (expr, complain);
8787 if (expr == error_mark_node)
8788 {
8789 if (complain & tf_error)
8790 {
8791 auto_diagnostic_group d;
8792 maybe_print_user_conv_context (convs);
8793 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8794 }
8795 return error_mark_node;
8796 }
8797
8798 if (! MAYBE_CLASS_TYPE_P (totype))
8799 return expr;
8800
8801 /* Don't introduce copies when passing arguments along to the inherited
8802 constructor. */
8803 if (current_function_decl
8804 && flag_new_inheriting_ctors
8805 && DECL_INHERITED_CTOR (current_function_decl))
8806 return expr;
8807
8808 if (TREE_CODE (expr) == TARGET_EXPR
8809 && TARGET_EXPR_LIST_INIT_P (expr))
8810 /* Copy-list-initialization doesn't actually involve a copy. */
8811 return expr;
8812
8813 /* Fall through. */
8814 case ck_base:
8815 if (convs->kind == ck_base && !convs->need_temporary_p)
8816 {
8817 /* We are going to bind a reference directly to a base-class
8818 subobject of EXPR. */
8819 /* Build an expression for `*((base*) &expr)'. */
8820 expr = convert_to_base (expr, totype,
8821 !c_cast_p, /*nonnull=*/true, complain);
8822 return expr;
8823 }
8824
8825 /* Copy-initialization where the cv-unqualified version of the source
8826 type is the same class as, or a derived class of, the class of the
8827 destination [is treated as direct-initialization]. [dcl.init] */
8828 flags = LOOKUP_NORMAL;
8829 /* This conversion is being done in the context of a user-defined
8830 conversion (i.e. the second step of copy-initialization), so
8831 don't allow any more. */
8832 if (convs->user_conv_p)
8833 flags |= LOOKUP_NO_CONVERSION;
8834 /* We might be performing a conversion of the argument
8835 to the user-defined conversion, i.e., not a conversion of the
8836 result of the user-defined conversion. In which case we skip
8837 explicit constructors. */
8838 if (convs->copy_init_p)
8839 flags |= LOOKUP_ONLYCONVERTING;
8840 expr = build_temp (expr, type: totype, flags, diagnostic_kind: &diag_kind, complain);
8841 if (diag_kind && complain)
8842 {
8843 auto_diagnostic_group d;
8844 maybe_print_user_conv_context (convs);
8845 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8846 }
8847
8848 return build_cplus_new (totype, expr, complain);
8849
8850 case ck_ref_bind:
8851 {
8852 tree ref_type = totype;
8853
8854 if (convs->bad_p && !next_conversion (conv: convs)->bad_p)
8855 {
8856 tree extype = TREE_TYPE (expr);
8857 auto_diagnostic_group d;
8858 if (TYPE_REF_IS_RVALUE (ref_type)
8859 && lvalue_p (expr))
8860 error_at (loc, "cannot bind rvalue reference of type %qH to "
8861 "lvalue of type %qI", totype, extype);
8862 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8863 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8864 {
8865 conversion *next = next_conversion (conv: convs);
8866 if (next->kind == ck_std)
8867 {
8868 next = next_conversion (conv: next);
8869 error_at (loc, "cannot bind non-const lvalue reference of "
8870 "type %qH to a value of type %qI",
8871 totype, next->type);
8872 }
8873 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8874 error_at (loc, "cannot bind non-const lvalue reference of "
8875 "type %qH to an rvalue of type %qI", totype, extype);
8876 else // extype is volatile
8877 error_at (loc, "cannot bind lvalue reference of type "
8878 "%qH to an rvalue of type %qI", totype,
8879 extype);
8880 }
8881 else if (!reference_compatible_p (TREE_TYPE (totype), t2: extype))
8882 {
8883 /* If we're converting from T[] to T[N], don't talk
8884 about discarding qualifiers. (Converting from T[N] to
8885 T[] is allowed by P0388R4.) */
8886 if (TREE_CODE (extype) == ARRAY_TYPE
8887 && TYPE_DOMAIN (extype) == NULL_TREE
8888 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8889 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8890 error_at (loc, "cannot bind reference of type %qH to %qI "
8891 "due to different array bounds", totype, extype);
8892 else
8893 error_at (loc, "binding reference of type %qH to %qI "
8894 "discards qualifiers", totype, extype);
8895 }
8896 else
8897 gcc_unreachable ();
8898 maybe_print_user_conv_context (convs);
8899 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8900
8901 return error_mark_node;
8902 }
8903 else if (complain & tf_warning)
8904 maybe_warn_array_conv (loc, c: convs, expr);
8905
8906 /* If necessary, create a temporary.
8907
8908 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8909 that need temporaries, even when their types are reference
8910 compatible with the type of reference being bound, so the
8911 upcoming call to cp_build_addr_expr doesn't fail. */
8912 if (convs->need_temporary_p
8913 || TREE_CODE (expr) == CONSTRUCTOR
8914 || TREE_CODE (expr) == VA_ARG_EXPR)
8915 {
8916 /* Otherwise, a temporary of type "cv1 T1" is created and
8917 initialized from the initializer expression using the rules
8918 for a non-reference copy-initialization (8.5). */
8919
8920 tree type = TREE_TYPE (ref_type);
8921 cp_lvalue_kind lvalue = lvalue_kind (expr);
8922
8923 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8924 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8925 && !TYPE_REF_IS_RVALUE (ref_type))
8926 {
8927 /* If the reference is volatile or non-const, we
8928 cannot create a temporary. */
8929 if (complain & tf_error)
8930 {
8931 if (lvalue & clk_bitfield)
8932 error_at (loc, "cannot bind bit-field %qE to %qT",
8933 expr, ref_type);
8934 else if (lvalue & clk_packed)
8935 error_at (loc, "cannot bind packed field %qE to %qT",
8936 expr, ref_type);
8937 else
8938 error_at (loc, "cannot bind rvalue %qE to %qT",
8939 expr, ref_type);
8940 }
8941 return error_mark_node;
8942 }
8943 /* If the source is a packed field, and we must use a copy
8944 constructor, then building the target expr will require
8945 binding the field to the reference parameter to the
8946 copy constructor, and we'll end up with an infinite
8947 loop. If we can use a bitwise copy, then we'll be
8948 OK. */
8949 if ((lvalue & clk_packed)
8950 && CLASS_TYPE_P (type)
8951 && type_has_nontrivial_copy_init (type))
8952 {
8953 error_at (loc, "cannot bind packed field %qE to %qT",
8954 expr, ref_type);
8955 return error_mark_node;
8956 }
8957 if (lvalue & clk_bitfield)
8958 {
8959 expr = convert_bitfield_to_declared_type (expr);
8960 expr = fold_convert (type, expr);
8961 }
8962
8963 /* Creating &TARGET_EXPR<> in a template would break when
8964 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8965 instead. This can happen even when there's no class
8966 involved, e.g., when converting an integer to a reference
8967 type. */
8968 if (processing_template_decl)
8969 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8970 expr = build_target_expr_with_type (expr, type, complain);
8971 }
8972
8973 /* Take the address of the thing to which we will bind the
8974 reference. */
8975 expr = cp_build_addr_expr (expr, complain);
8976 if (expr == error_mark_node)
8977 return error_mark_node;
8978
8979 /* Convert it to a pointer to the type referred to by the
8980 reference. This will adjust the pointer if a derived to
8981 base conversion is being performed. */
8982 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8983 expr, complain);
8984 /* Convert the pointer to the desired reference type. */
8985 return build_nop (ref_type, expr);
8986 }
8987
8988 case ck_lvalue:
8989 return decay_conversion (expr, complain);
8990
8991 case ck_fnptr:
8992 /* ??? Should the address of a transaction-safe pointer point to the TM
8993 clone, and this conversion look up the primary function? */
8994 return build_nop (totype, expr);
8995
8996 case ck_qual:
8997 /* Warn about deprecated conversion if appropriate. */
8998 if (complain & tf_warning)
8999 {
9000 string_conv_p (totype, expr, 1);
9001 maybe_warn_array_conv (loc, c: convs, expr);
9002 }
9003 break;
9004
9005 case ck_ptr:
9006 if (convs->base_p)
9007 expr = convert_to_base (expr, totype, !c_cast_p,
9008 /*nonnull=*/false, complain);
9009 return build_nop (totype, expr);
9010
9011 case ck_pmem:
9012 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
9013 c_cast_p, complain);
9014
9015 default:
9016 break;
9017 }
9018
9019 if (convs->check_narrowing
9020 && !check_narrowing (totype, expr, complain,
9021 convs->check_narrowing_const_only))
9022 return error_mark_node;
9023
9024 warning_sentinel w (warn_zero_as_null_pointer_constant);
9025 if (issue_conversion_warnings)
9026 expr = cp_convert_and_check (totype, expr, complain);
9027 else
9028 {
9029 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
9030 expr = TREE_OPERAND (expr, 0);
9031 expr = cp_convert (totype, expr, complain);
9032 }
9033
9034 return expr;
9035}
9036
9037/* Return true if converting FROM to TO is unsafe in a template. */
9038
9039static bool
9040conv_unsafe_in_template_p (tree to, tree from)
9041{
9042 /* Converting classes involves TARGET_EXPR. */
9043 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
9044 return true;
9045
9046 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
9047 doesn't handle. */
9048 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
9049 return true;
9050
9051 /* Converting integer to real isn't a trivial conversion, either. */
9052 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
9053 return true;
9054
9055 return false;
9056}
9057
9058/* Wrapper for convert_like_internal that handles creating
9059 IMPLICIT_CONV_EXPR. */
9060
9061static tree
9062convert_like (conversion *convs, tree expr, tree fn, int argnum,
9063 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
9064 tsubst_flags_t complain)
9065{
9066 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
9067 and creating a CALL_EXPR in a template breaks in finish_call_expr
9068 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
9069 created such codes e.g. when calling a user-defined conversion
9070 function. */
9071 tree conv_expr = NULL_TREE;
9072 if (processing_template_decl
9073 && convs->kind != ck_identity
9074 && conv_unsafe_in_template_p (to: convs->type, TREE_TYPE (expr)))
9075 {
9076 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
9077 if (convs->kind != ck_ref_bind)
9078 conv_expr = convert_from_reference (conv_expr);
9079 if (!convs->bad_p)
9080 return conv_expr;
9081 /* Do the normal processing to give the bad_p errors. But we still
9082 need to return the IMPLICIT_CONV_EXPR, unless we're returning
9083 error_mark_node. */
9084 }
9085 expr = convert_like_internal (convs, expr, fn, argnum,
9086 issue_conversion_warnings, c_cast_p,
9087 nested_p, complain);
9088 if (expr == error_mark_node)
9089 return error_mark_node;
9090 return conv_expr ? conv_expr : expr;
9091}
9092
9093/* Convenience wrapper for convert_like. */
9094
9095static inline tree
9096convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
9097{
9098 return convert_like (convs, expr, NULL_TREE, argnum: 0,
9099 /*issue_conversion_warnings=*/true,
9100 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9101}
9102
9103/* Convenience wrapper for convert_like. */
9104
9105static inline tree
9106convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
9107 tsubst_flags_t complain)
9108{
9109 return convert_like (convs, expr, fn, argnum,
9110 /*issue_conversion_warnings=*/true,
9111 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9112}
9113
9114/* ARG is being passed to a varargs function. Perform any conversions
9115 required. Return the converted value. */
9116
9117tree
9118convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
9119{
9120 tree arg_type = TREE_TYPE (arg);
9121 location_t loc = cp_expr_loc_or_input_loc (t: arg);
9122
9123 /* [expr.call]
9124
9125 If the argument has integral or enumeration type that is subject
9126 to the integral promotions (_conv.prom_), or a floating-point
9127 type that is subject to the floating-point promotion
9128 (_conv.fpprom_), the value of the argument is converted to the
9129 promoted type before the call. */
9130 if (SCALAR_FLOAT_TYPE_P (arg_type)
9131 && (TYPE_PRECISION (arg_type)
9132 < TYPE_PRECISION (double_type_node))
9133 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
9134 && !extended_float_type_p (type: arg_type))
9135 {
9136 if ((complain & tf_warning)
9137 && warn_double_promotion && !c_inhibit_evaluation_warnings)
9138 warning_at (loc, OPT_Wdouble_promotion,
9139 "implicit conversion from %qH to %qI when passing "
9140 "argument to function",
9141 arg_type, double_type_node);
9142 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
9143 arg = TREE_OPERAND (arg, 0);
9144 arg = mark_rvalue_use (arg);
9145 arg = convert_to_real_nofold (double_type_node, x: arg);
9146 }
9147 else if (NULLPTR_TYPE_P (arg_type))
9148 {
9149 arg = mark_rvalue_use (arg);
9150 if (TREE_SIDE_EFFECTS (arg))
9151 {
9152 warning_sentinel w(warn_unused_result);
9153 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9154 }
9155 else
9156 arg = null_pointer_node;
9157 }
9158 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9159 {
9160 if (SCOPED_ENUM_P (arg_type))
9161 {
9162 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9163 complain);
9164 prom = cp_perform_integral_promotions (prom, complain);
9165 if (abi_version_crosses (6)
9166 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9167 && (complain & tf_warning))
9168 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9169 " as %qT before %<-fabi-version=6%>, %qT after",
9170 arg_type,
9171 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9172 if (!abi_version_at_least (6))
9173 arg = prom;
9174 }
9175 else
9176 arg = cp_perform_integral_promotions (arg, complain);
9177 }
9178 else
9179 /* [expr.call]
9180
9181 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9182 standard conversions are performed. */
9183 arg = decay_conversion (arg, complain);
9184
9185 arg = require_complete_type (arg, complain);
9186 arg_type = TREE_TYPE (arg);
9187
9188 if (arg != error_mark_node
9189 /* In a template (or ill-formed code), we can have an incomplete type
9190 even after require_complete_type, in which case we don't know
9191 whether it has trivial copy or not. */
9192 && COMPLETE_TYPE_P (arg_type)
9193 && !cp_unevaluated_operand)
9194 {
9195 /* [expr.call] 5.2.2/7:
9196 Passing a potentially-evaluated argument of class type (Clause 9)
9197 with a non-trivial copy constructor or a non-trivial destructor
9198 with no corresponding parameter is conditionally-supported, with
9199 implementation-defined semantics.
9200
9201 We support it as pass-by-invisible-reference, just like a normal
9202 value parameter.
9203
9204 If the call appears in the context of a sizeof expression,
9205 it is not potentially-evaluated. */
9206 if (type_has_nontrivial_copy_init (arg_type)
9207 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9208 {
9209 arg = force_rvalue (arg, complain);
9210 if (complain & tf_warning)
9211 warning (OPT_Wconditionally_supported,
9212 "passing objects of non-trivially-copyable "
9213 "type %q#T through %<...%> is conditionally supported",
9214 arg_type);
9215 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9216 }
9217 /* Build up a real lvalue-to-rvalue conversion in case the
9218 copy constructor is trivial but not callable. */
9219 else if (CLASS_TYPE_P (arg_type))
9220 force_rvalue (arg, complain);
9221
9222 }
9223
9224 return arg;
9225}
9226
9227/* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9228
9229tree
9230build_x_va_arg (location_t loc, tree expr, tree type)
9231{
9232 if (processing_template_decl)
9233 {
9234 tree r = build_min (VA_ARG_EXPR, type, expr);
9235 SET_EXPR_LOCATION (r, loc);
9236 return r;
9237 }
9238
9239 type = complete_type_or_else (type, NULL_TREE);
9240
9241 if (expr == error_mark_node || !type)
9242 return error_mark_node;
9243
9244 expr = mark_lvalue_use (expr);
9245
9246 if (TYPE_REF_P (type))
9247 {
9248 error ("cannot receive reference type %qT through %<...%>", type);
9249 return error_mark_node;
9250 }
9251
9252 if (type_has_nontrivial_copy_init (type)
9253 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9254 {
9255 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9256 it as pass by invisible reference. */
9257 warning_at (loc, OPT_Wconditionally_supported,
9258 "receiving objects of non-trivially-copyable type %q#T "
9259 "through %<...%> is conditionally-supported", type);
9260
9261 tree ref = cp_build_reference_type (type, false);
9262 expr = build_va_arg (loc, expr, ref);
9263 return convert_from_reference (expr);
9264 }
9265
9266 tree ret = build_va_arg (loc, expr, type);
9267 if (CLASS_TYPE_P (type))
9268 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9269 know how to handle it. */
9270 ret = get_target_expr (ret);
9271 return ret;
9272}
9273
9274/* TYPE has been given to va_arg. Apply the default conversions which
9275 would have happened when passed via ellipsis. Return the promoted
9276 type, or the passed type if there is no change. */
9277
9278tree
9279cxx_type_promotes_to (tree type)
9280{
9281 tree promote;
9282
9283 /* Perform the array-to-pointer and function-to-pointer
9284 conversions. */
9285 type = type_decays_to (type);
9286
9287 promote = type_promotes_to (type);
9288 if (same_type_p (type, promote))
9289 promote = type;
9290
9291 return promote;
9292}
9293
9294/* ARG is a default argument expression being passed to a parameter of
9295 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9296 zero-based argument number. Do any required conversions. Return
9297 the converted value. */
9298
9299static GTY(()) vec<tree, va_gc> *default_arg_context;
9300void
9301push_defarg_context (tree fn)
9302{ vec_safe_push (v&: default_arg_context, obj: fn); }
9303
9304void
9305pop_defarg_context (void)
9306{ default_arg_context->pop (); }
9307
9308tree
9309convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9310 tsubst_flags_t complain)
9311{
9312 int i;
9313 tree t;
9314
9315 /* See through clones. */
9316 fn = DECL_ORIGIN (fn);
9317 /* And inheriting ctors. */
9318 if (flag_new_inheriting_ctors)
9319 fn = strip_inheriting_ctors (fn);
9320
9321 /* Detect recursion. */
9322 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9323 if (t == fn)
9324 {
9325 if (complain & tf_error)
9326 error ("recursive evaluation of default argument for %q#D", fn);
9327 return error_mark_node;
9328 }
9329
9330 /* If the ARG is an unparsed default argument expression, the
9331 conversion cannot be performed. */
9332 if (TREE_CODE (arg) == DEFERRED_PARSE)
9333 {
9334 if (complain & tf_error)
9335 error ("call to %qD uses the default argument for parameter %P, which "
9336 "is not yet defined", fn, parmnum);
9337 return error_mark_node;
9338 }
9339
9340 push_defarg_context (fn);
9341
9342 if (fn && DECL_TEMPLATE_INFO (fn))
9343 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9344
9345 /* Due to:
9346
9347 [dcl.fct.default]
9348
9349 The names in the expression are bound, and the semantic
9350 constraints are checked, at the point where the default
9351 expressions appears.
9352
9353 we must not perform access checks here. */
9354 push_deferring_access_checks (dk_no_check);
9355 /* We must make a copy of ARG, in case subsequent processing
9356 alters any part of it. */
9357 arg = break_out_target_exprs (arg, /*clear location*/true);
9358
9359 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9360 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9361 complain);
9362 arg = convert_for_arg_passing (type, arg, complain);
9363 pop_deferring_access_checks();
9364
9365 pop_defarg_context ();
9366
9367 return arg;
9368}
9369
9370/* Returns the type which will really be used for passing an argument of
9371 type TYPE. */
9372
9373tree
9374type_passed_as (tree type)
9375{
9376 /* Pass classes with copy ctors by invisible reference. */
9377 if (TREE_ADDRESSABLE (type))
9378 type = build_reference_type (type);
9379 else if (targetm.calls.promote_prototypes (NULL_TREE)
9380 && INTEGRAL_TYPE_P (type)
9381 && COMPLETE_TYPE_P (type)
9382 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9383 type = integer_type_node;
9384
9385 return type;
9386}
9387
9388/* Actually perform the appropriate conversion. */
9389
9390tree
9391convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9392{
9393 tree bitfield_type;
9394
9395 /* If VAL is a bitfield, then -- since it has already been converted
9396 to TYPE -- it cannot have a precision greater than TYPE.
9397
9398 If it has a smaller precision, we must widen it here. For
9399 example, passing "int f:3;" to a function expecting an "int" will
9400 not result in any conversion before this point.
9401
9402 If the precision is the same we must not risk widening. For
9403 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9404 often have type "int", even though the C++ type for the field is
9405 "long long". If the value is being passed to a function
9406 expecting an "int", then no conversions will be required. But,
9407 if we call convert_bitfield_to_declared_type, the bitfield will
9408 be converted to "long long". */
9409 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9410 if (bitfield_type
9411 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9412 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), x: val);
9413
9414 if (val == error_mark_node)
9415 ;
9416 /* Pass classes with copy ctors by invisible reference. */
9417 else if (TREE_ADDRESSABLE (type))
9418 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9419 else if (targetm.calls.promote_prototypes (NULL_TREE)
9420 && INTEGRAL_TYPE_P (type)
9421 && COMPLETE_TYPE_P (type)
9422 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9423 val = cp_perform_integral_promotions (val, complain);
9424 if (complain & tf_warning)
9425 {
9426 if (warn_suggest_attribute_format)
9427 {
9428 tree rhstype = TREE_TYPE (val);
9429 const enum tree_code coder = TREE_CODE (rhstype);
9430 const enum tree_code codel = TREE_CODE (type);
9431 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9432 && coder == codel
9433 && check_missing_format_attribute (type, rhstype))
9434 warning (OPT_Wsuggest_attribute_format,
9435 "argument of function call might be a candidate "
9436 "for a format attribute");
9437 }
9438 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (t: val));
9439 }
9440
9441 if (complain & tf_warning)
9442 warn_for_address_of_packed_member (type, val);
9443
9444 return val;
9445}
9446
9447/* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9448 which just decay_conversion or no conversions at all should be done.
9449 This is true for some builtins which don't act like normal functions.
9450 Return 2 if just decay_conversion and removal of excess precision should
9451 be done, 1 if just decay_conversion. Return 3 for special treatment of
9452 the 3rd argument for __builtin_*_overflow_p. Return 4 for special
9453 treatment of the 1st argument for
9454 __builtin_{clz,ctz,clrsb,ffs,parity,popcount}g. */
9455
9456int
9457magic_varargs_p (tree fn)
9458{
9459 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9460 switch (DECL_FUNCTION_CODE (decl: fn))
9461 {
9462 case BUILT_IN_CLASSIFY_TYPE:
9463 case BUILT_IN_CONSTANT_P:
9464 case BUILT_IN_NEXT_ARG:
9465 case BUILT_IN_VA_START:
9466 return 1;
9467
9468 case BUILT_IN_ADD_OVERFLOW_P:
9469 case BUILT_IN_SUB_OVERFLOW_P:
9470 case BUILT_IN_MUL_OVERFLOW_P:
9471 return 3;
9472
9473 case BUILT_IN_ISFINITE:
9474 case BUILT_IN_ISINF:
9475 case BUILT_IN_ISINF_SIGN:
9476 case BUILT_IN_ISNAN:
9477 case BUILT_IN_ISNORMAL:
9478 case BUILT_IN_FPCLASSIFY:
9479 return 2;
9480
9481 case BUILT_IN_CLZG:
9482 case BUILT_IN_CTZG:
9483 case BUILT_IN_CLRSBG:
9484 case BUILT_IN_FFSG:
9485 case BUILT_IN_PARITYG:
9486 case BUILT_IN_POPCOUNTG:
9487 return 4;
9488
9489 default:
9490 return lookup_attribute (attr_name: "type generic",
9491 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9492 }
9493
9494 return 0;
9495}
9496
9497/* Returns the decl of the dispatcher function if FN is a function version. */
9498
9499tree
9500get_function_version_dispatcher (tree fn)
9501{
9502 tree dispatcher_decl = NULL;
9503
9504 if (DECL_LOCAL_DECL_P (fn))
9505 fn = DECL_LOCAL_DECL_ALIAS (fn);
9506
9507 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9508 && DECL_FUNCTION_VERSIONED (fn));
9509
9510 gcc_assert (targetm.get_function_versions_dispatcher);
9511 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9512
9513 if (dispatcher_decl == NULL)
9514 {
9515 error_at (input_location, "use of multiversioned function "
9516 "without a default");
9517 return NULL;
9518 }
9519
9520 retrofit_lang_decl (dispatcher_decl);
9521 gcc_assert (dispatcher_decl != NULL);
9522 return dispatcher_decl;
9523}
9524
9525/* fn is a function version dispatcher that is marked used. Mark all the
9526 semantically identical function versions it will dispatch as used. */
9527
9528void
9529mark_versions_used (tree fn)
9530{
9531 struct cgraph_node *node;
9532 struct cgraph_function_version_info *node_v;
9533 struct cgraph_function_version_info *it_v;
9534
9535 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9536
9537 node = cgraph_node::get (decl: fn);
9538 if (node == NULL)
9539 return;
9540
9541 gcc_assert (node->dispatcher_function);
9542
9543 node_v = node->function_version ();
9544 if (node_v == NULL)
9545 return;
9546
9547 /* All semantically identical versions are chained. Traverse and mark each
9548 one of them as used. */
9549 it_v = node_v->next;
9550 while (it_v != NULL)
9551 {
9552 mark_used (it_v->this_node->decl);
9553 it_v = it_v->next;
9554 }
9555}
9556
9557/* Build a call to "the copy constructor" for the type of A, even if it
9558 wouldn't be selected by normal overload resolution. Used for
9559 diagnostics. */
9560
9561static tree
9562call_copy_ctor (tree a, tsubst_flags_t complain)
9563{
9564 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9565 tree binfo = TYPE_BINFO (ctype);
9566 tree copy = get_copy_ctor (ctype, complain);
9567 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9568 tree ob = build_dummy_object (ctype);
9569 releasing_vec args (make_tree_vector_single (a));
9570 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9571 LOOKUP_NORMAL, NULL, complain);
9572 return r;
9573}
9574
9575/* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9576
9577static tree
9578base_ctor_for (tree complete_ctor)
9579{
9580 tree clone;
9581 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9582 if (DECL_BASE_CONSTRUCTOR_P (clone))
9583 return clone;
9584 return NULL_TREE;
9585}
9586
9587/* Try to make EXP suitable to be used as the initializer for a base subobject,
9588 and return whether we were successful. EXP must have already been cleared
9589 by unsafe_copy_elision_p{,_opt}. */
9590
9591static bool
9592make_base_init_ok (tree exp)
9593{
9594 if (TREE_CODE (exp) == TARGET_EXPR)
9595 exp = TARGET_EXPR_INITIAL (exp);
9596 while (TREE_CODE (exp) == COMPOUND_EXPR)
9597 exp = TREE_OPERAND (exp, 1);
9598 if (TREE_CODE (exp) == COND_EXPR)
9599 {
9600 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9601 if (tree op1 = TREE_OPERAND (exp, 1))
9602 {
9603 bool r1 = make_base_init_ok (exp: op1);
9604 /* If unsafe_copy_elision_p was false, the arms should match. */
9605 gcc_assert (r1 == ret);
9606 }
9607 return ret;
9608 }
9609 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9610 /* A trivial copy is OK. */
9611 return true;
9612 if (!AGGR_INIT_VIA_CTOR_P (exp))
9613 /* unsafe_copy_elision_p_opt must have said this is OK. */
9614 return true;
9615 tree fn = cp_get_callee_fndecl_nofold (exp);
9616 if (DECL_BASE_CONSTRUCTOR_P (fn))
9617 return true;
9618 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9619 fn = base_ctor_for (complete_ctor: fn);
9620 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9621 /* The base constructor has more parameters, so we can't just change the
9622 call target. It would be possible to splice in the appropriate
9623 arguments, but probably not worth the complexity. */
9624 return false;
9625 mark_used (fn);
9626 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9627 return true;
9628}
9629
9630/* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9631 neither of which can be used for return by invisible reference. We avoid
9632 doing C++17 mandatory copy elision for either of these cases.
9633
9634 This returns non-zero even if the type of T has no tail padding that other
9635 data could be allocated into, because that depends on the particular ABI.
9636 unsafe_copy_elision_p_opt does consider whether there is padding. */
9637
9638int
9639unsafe_return_slot_p (tree t)
9640{
9641 /* Check empty bases separately, they don't have fields. */
9642 if (is_empty_base_ref (t))
9643 return 2;
9644
9645 /* A delegating constructor might be used to initialize a base. */
9646 if (current_function_decl
9647 && DECL_CONSTRUCTOR_P (current_function_decl)
9648 && (t == current_class_ref
9649 || tree_strip_nop_conversions (t) == current_class_ptr))
9650 return 2;
9651
9652 STRIP_NOPS (t);
9653 if (TREE_CODE (t) == ADDR_EXPR)
9654 t = TREE_OPERAND (t, 0);
9655 if (TREE_CODE (t) == COMPONENT_REF)
9656 t = TREE_OPERAND (t, 1);
9657 if (TREE_CODE (t) != FIELD_DECL)
9658 return false;
9659 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9660 /* The middle-end will do the right thing for scalar types. */
9661 return false;
9662 if (DECL_FIELD_IS_BASE (t))
9663 return 2;
9664 if (lookup_attribute (attr_name: "no_unique_address", DECL_ATTRIBUTES (t)))
9665 return 1;
9666 return 0;
9667}
9668
9669/* True IFF EXP is a prvalue that represents return by invisible reference. */
9670
9671static bool
9672init_by_return_slot_p (tree exp)
9673{
9674 /* Copy elision only happens with a TARGET_EXPR. */
9675 if (TREE_CODE (exp) != TARGET_EXPR)
9676 return false;
9677 tree init = TARGET_EXPR_INITIAL (exp);
9678 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9679 while (TREE_CODE (init) == COMPOUND_EXPR)
9680 init = TREE_OPERAND (init, 1);
9681 if (TREE_CODE (init) == COND_EXPR)
9682 {
9683 /* We'll end up copying from each of the arms of the COND_EXPR directly
9684 into the target, so look at them. */
9685 if (tree op = TREE_OPERAND (init, 1))
9686 if (init_by_return_slot_p (exp: op))
9687 return true;
9688 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9689 }
9690 return (TREE_CODE (init) == AGGR_INIT_EXPR
9691 && !AGGR_INIT_VIA_CTOR_P (init));
9692}
9693
9694/* We can't elide a copy from a function returning by value to a
9695 potentially-overlapping subobject, as the callee might clobber tail padding.
9696 Return true iff this could be that case.
9697
9698 Places that use this function (or _opt) to decide to elide a copy should
9699 probably use make_safe_copy_elision instead. */
9700
9701bool
9702unsafe_copy_elision_p (tree target, tree exp)
9703{
9704 return unsafe_return_slot_p (t: target) && init_by_return_slot_p (exp);
9705}
9706
9707/* As above, but for optimization allow more cases that are actually safe. */
9708
9709static bool
9710unsafe_copy_elision_p_opt (tree target, tree exp)
9711{
9712 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9713 /* It's safe to elide the copy for a class with no tail padding. */
9714 if (!is_empty_class (type)
9715 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9716 return false;
9717 return unsafe_copy_elision_p (target, exp);
9718}
9719
9720/* Try to make EXP suitable to be used as the initializer for TARGET,
9721 and return whether we were successful. */
9722
9723bool
9724make_safe_copy_elision (tree target, tree exp)
9725{
9726 int uns = unsafe_return_slot_p (t: target);
9727 if (!uns)
9728 return true;
9729 if (init_by_return_slot_p (exp))
9730 return false;
9731 if (uns == 1)
9732 return true;
9733 return make_base_init_ok (exp);
9734}
9735
9736/* True IFF the result of the conversion C is a prvalue. */
9737
9738static bool
9739conv_is_prvalue (conversion *c)
9740{
9741 if (c->kind == ck_rvalue)
9742 return true;
9743 if (c->kind == ck_base && c->need_temporary_p)
9744 return true;
9745 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9746 return true;
9747 if (c->kind == ck_identity && c->u.expr
9748 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9749 return true;
9750
9751 return false;
9752}
9753
9754/* True iff C is a conversion that binds a reference to a prvalue. */
9755
9756static bool
9757conv_binds_ref_to_prvalue (conversion *c)
9758{
9759 if (c->kind != ck_ref_bind)
9760 return false;
9761 if (c->need_temporary_p)
9762 return true;
9763
9764 return conv_is_prvalue (c: next_conversion (conv: c));
9765}
9766
9767/* True iff EXPR represents a (subobject of a) temporary. */
9768
9769static bool
9770expr_represents_temporary_p (tree expr)
9771{
9772 while (handled_component_p (t: expr))
9773 expr = TREE_OPERAND (expr, 0);
9774 return TREE_CODE (expr) == TARGET_EXPR;
9775}
9776
9777/* True iff C is a conversion that binds a reference to a temporary.
9778 This is a superset of conv_binds_ref_to_prvalue: here we're also
9779 interested in xvalues. */
9780
9781static bool
9782conv_binds_ref_to_temporary (conversion *c)
9783{
9784 if (conv_binds_ref_to_prvalue (c))
9785 return true;
9786 if (c->kind != ck_ref_bind)
9787 return false;
9788 c = next_conversion (conv: c);
9789 /* This is the case for
9790 struct Base {};
9791 struct Derived : Base {};
9792 const Base& b(Derived{});
9793 where we bind 'b' to the Base subobject of a temporary object of type
9794 Derived. The subobject is an xvalue; the whole object is a prvalue.
9795
9796 The ck_base doesn't have to be present for cases like X{}.m. */
9797 if (c->kind == ck_base)
9798 c = next_conversion (conv: c);
9799 if (c->kind == ck_identity && c->u.expr
9800 && expr_represents_temporary_p (expr: c->u.expr))
9801 return true;
9802 return false;
9803}
9804
9805/* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9806 the reference to a temporary. Return tristate::TS_FALSE if converting
9807 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9808 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9809 says whether the conversion should be done in direct- or copy-initialization
9810 context. */
9811
9812tristate
9813ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9814{
9815 gcc_assert (TYPE_REF_P (type));
9816
9817 conversion_obstack_sentinel cos;
9818
9819 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9820 conversion *conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
9821 /*c_cast_p=*/false, flags, complain: tf_none);
9822 tristate ret (tristate::TS_UNKNOWN);
9823 if (conv && !conv->bad_p)
9824 ret = tristate (conv_binds_ref_to_temporary (c: conv));
9825
9826 return ret;
9827}
9828
9829/* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9830 class type or a pointer to class type. If NO_PTR_DEREF is true and
9831 INSTANCE has pointer type, clobber the pointer rather than what it points
9832 to. */
9833
9834tree
9835build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9836{
9837 gcc_assert (!is_dummy_object (instance));
9838
9839 if (!flag_lifetime_dse)
9840 {
9841 no_clobber:
9842 return fold_convert (void_type_node, instance);
9843 }
9844
9845 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9846 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9847 {
9848 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9849 goto no_clobber;
9850 instance = cp_build_fold_indirect_ref (instance);
9851 }
9852
9853 /* A trivial destructor should still clobber the object. */
9854 tree clobber = build_clobber (TREE_TYPE (instance), CLOBBER_OBJECT_END);
9855 return build2 (MODIFY_EXPR, void_type_node,
9856 instance, clobber);
9857}
9858
9859/* Return true if in an immediate function context, or an unevaluated operand,
9860 or a default argument/member initializer, or a subexpression of an immediate
9861 invocation. */
9862
9863bool
9864in_immediate_context ()
9865{
9866 return (cp_unevaluated_operand != 0
9867 || (current_function_decl != NULL_TREE
9868 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9869 /* DR 2631: default args and DMI aren't immediately evaluated.
9870 Return true here so immediate_invocation_p returns false. */
9871 || current_binding_level->kind == sk_function_parms
9872 || current_binding_level->kind == sk_template_parms
9873 || parsing_nsdmi ()
9874 || in_consteval_if_p);
9875}
9876
9877/* Return true if a call to FN with number of arguments NARGS
9878 is an immediate invocation. */
9879
9880bool
9881immediate_invocation_p (tree fn)
9882{
9883 return (TREE_CODE (fn) == FUNCTION_DECL
9884 && DECL_IMMEDIATE_FUNCTION_P (fn)
9885 && !in_immediate_context ());
9886}
9887
9888/* Subroutine of the various build_*_call functions. Overload resolution
9889 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9890 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9891 bitmask of various LOOKUP_* flags which apply to the call itself. */
9892
9893static tree
9894build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9895{
9896 tree fn = cand->fn;
9897 const vec<tree, va_gc> *args = cand->args;
9898 tree first_arg = cand->first_arg;
9899 conversion **convs = cand->convs;
9900 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9901 int parmlen;
9902 tree val;
9903 int nargs;
9904 tree *argarray;
9905 bool already_used = false;
9906
9907 /* In a template, there is no need to perform all of the work that
9908 is normally done. We are only interested in the type of the call
9909 expression, i.e., the return type of the function. Any semantic
9910 errors will be deferred until the template is instantiated. */
9911 if (processing_template_decl)
9912 {
9913 if (undeduced_auto_decl (fn))
9914 mark_used (fn, complain);
9915 else
9916 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9917 See PR80598. */
9918 TREE_USED (fn) = 1;
9919
9920 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9921 tree callee;
9922 if (first_arg == NULL_TREE)
9923 {
9924 callee = build_addr_func (function: fn, complain);
9925 if (callee == error_mark_node)
9926 return error_mark_node;
9927 }
9928 else
9929 {
9930 callee = build_baselink (cand->conversion_path, cand->access_path,
9931 fn, NULL_TREE);
9932 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9933 first_arg, callee, NULL_TREE);
9934 }
9935
9936 tree expr = build_call_vec (return_type, callee, args);
9937 SET_EXPR_LOCATION (expr, input_location);
9938 if (TREE_THIS_VOLATILE (fn) && cfun)
9939 current_function_returns_abnormally = 1;
9940 if (immediate_invocation_p (fn))
9941 {
9942 tree obj_arg = NULL_TREE, exprimm = expr;
9943 if (DECL_CONSTRUCTOR_P (fn))
9944 obj_arg = first_arg;
9945 if (obj_arg
9946 && is_dummy_object (obj_arg)
9947 && !type_dependent_expression_p (obj_arg))
9948 {
9949 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9950 obj_arg = NULL_TREE;
9951 }
9952 /* Look through *(const T *)&obj. */
9953 else if (obj_arg && INDIRECT_REF_P (obj_arg))
9954 {
9955 tree addr = TREE_OPERAND (obj_arg, 0);
9956 STRIP_NOPS (addr);
9957 if (TREE_CODE (addr) == ADDR_EXPR)
9958 {
9959 tree typeo = TREE_TYPE (obj_arg);
9960 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9961 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9962 obj_arg = TREE_OPERAND (addr, 0);
9963 }
9964 }
9965 fold_non_dependent_expr (exprimm, complain,
9966 /*manifestly_const_eval=*/true,
9967 obj_arg);
9968 }
9969 return convert_from_reference (expr);
9970 }
9971
9972 /* Give any warnings we noticed during overload resolution. */
9973 if (cand->warnings && (complain & tf_warning))
9974 {
9975 struct candidate_warning *w;
9976 for (w = cand->warnings; w; w = w->next)
9977 joust (cand, w->loser, 1, complain);
9978 }
9979
9980 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9981 argument to the copy constructor ends up being a prvalue after
9982 conversion. Let's do the normal processing, but pretend we aren't
9983 actually using the copy constructor. */
9984 bool force_elide = false;
9985 if (cxx_dialect >= cxx17
9986 && cand->num_convs == 1
9987 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9988 && (DECL_COPY_CONSTRUCTOR_P (fn)
9989 || DECL_MOVE_CONSTRUCTOR_P (fn))
9990 && !unsafe_return_slot_p (t: first_arg)
9991 && conv_binds_ref_to_prvalue (c: convs[0]))
9992 {
9993 force_elide = true;
9994 goto not_really_used;
9995 }
9996
9997 /* OK, we're actually calling this inherited constructor; set its deletedness
9998 appropriately. We can get away with doing this here because calling is
9999 the only way to refer to a constructor. */
10000 if (DECL_INHERITED_CTOR (fn)
10001 && !deduce_inheriting_ctor (fn))
10002 {
10003 if (complain & tf_error)
10004 mark_used (fn);
10005 return error_mark_node;
10006 }
10007
10008 /* Make =delete work with SFINAE. */
10009 if (DECL_DELETED_FN (fn))
10010 {
10011 if (complain & tf_error)
10012 {
10013 mark_used (fn);
10014 if (cand->next)
10015 {
10016 if (flag_diagnostics_all_candidates)
10017 print_z_candidates (loc: input_location, candidates: cand, /*only_viable_p=*/false);
10018 else
10019 inform (input_location,
10020 "use %<-fdiagnostics-all-candidates%> to display "
10021 "considered candidates");
10022 }
10023 }
10024 return error_mark_node;
10025 }
10026
10027 if (DECL_FUNCTION_MEMBER_P (fn))
10028 {
10029 tree access_fn;
10030 /* If FN is a template function, two cases must be considered.
10031 For example:
10032
10033 struct A {
10034 protected:
10035 template <class T> void f();
10036 };
10037 template <class T> struct B {
10038 protected:
10039 void g();
10040 };
10041 struct C : A, B<int> {
10042 using A::f; // #1
10043 using B<int>::g; // #2
10044 };
10045
10046 In case #1 where `A::f' is a member template, DECL_ACCESS is
10047 recorded in the primary template but not in its specialization.
10048 We check access of FN using its primary template.
10049
10050 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
10051 because it is a member of class template B, DECL_ACCESS is
10052 recorded in the specialization `B<int>::g'. We cannot use its
10053 primary template because `B<T>::g' and `B<int>::g' may have
10054 different access. */
10055 if (DECL_TEMPLATE_INFO (fn)
10056 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
10057 access_fn = DECL_TI_TEMPLATE (fn);
10058 else
10059 access_fn = fn;
10060 if (!perform_or_defer_access_check (cand->access_path, access_fn,
10061 fn, complain))
10062 return error_mark_node;
10063 }
10064
10065 /* If we're checking for implicit delete, don't bother with argument
10066 conversions. */
10067 if (flags & LOOKUP_SPECULATIVE)
10068 {
10069 if (cand->viable == 1)
10070 return fn;
10071 else if (!(complain & tf_error))
10072 /* Reject bad conversions now. */
10073 return error_mark_node;
10074 /* else continue to get conversion error. */
10075 }
10076
10077 not_really_used:
10078
10079 /* N3276 magic doesn't apply to nested calls. */
10080 tsubst_flags_t decltype_flag = (complain & tf_decltype);
10081 complain &= ~tf_decltype;
10082 /* No-Cleanup doesn't apply to nested calls either. */
10083 tsubst_flags_t no_cleanup_complain = complain;
10084 complain &= ~tf_no_cleanup;
10085
10086 /* Find maximum size of vector to hold converted arguments. */
10087 parmlen = list_length (parm);
10088 nargs = vec_safe_length (v: args) + (first_arg != NULL_TREE ? 1 : 0);
10089 if (parmlen > nargs)
10090 nargs = parmlen;
10091 argarray = XALLOCAVEC (tree, nargs);
10092
10093 in_consteval_if_p_temp_override icip;
10094 /* If the call is immediate function invocation, make sure
10095 taking address of immediate functions is allowed in its arguments. */
10096 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
10097 in_consteval_if_p = true;
10098
10099 int argarray_size = 0;
10100 unsigned int arg_index = 0;
10101 int conv_index = 0;
10102 int param_index = 0;
10103
10104 auto consume_object_arg = [&arg_index, &first_arg, args]()
10105 {
10106 if (!first_arg)
10107 return (*args)[arg_index++];
10108 tree object_arg = first_arg;
10109 first_arg = NULL_TREE;
10110 return object_arg;
10111 };
10112
10113 /* The implicit parameters to a constructor are not considered by overload
10114 resolution, and must be of the proper type. */
10115 if (DECL_CONSTRUCTOR_P (fn))
10116 {
10117 tree object_arg = consume_object_arg ();
10118 argarray[argarray_size++] = build_this (obj: object_arg);
10119 parm = TREE_CHAIN (parm);
10120 /* We should never try to call the abstract constructor. */
10121 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
10122
10123 if (DECL_HAS_VTT_PARM_P (fn))
10124 {
10125 argarray[argarray_size++] = (*args)[arg_index];
10126 ++arg_index;
10127 parm = TREE_CHAIN (parm);
10128 }
10129 }
10130 /* Bypass access control for 'this' parameter. */
10131 else if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
10132 {
10133 tree arg = build_this (obj: consume_object_arg ());
10134 tree argtype = TREE_TYPE (arg);
10135
10136 if (arg == error_mark_node)
10137 return error_mark_node;
10138 if (convs[conv_index++]->bad_p)
10139 {
10140 if (complain & tf_error)
10141 {
10142 auto_diagnostic_group d;
10143 if (permerror (input_location, "passing %qT as %<this%> "
10144 "argument discards qualifiers",
10145 TREE_TYPE (argtype)))
10146 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
10147 }
10148 else
10149 return error_mark_node;
10150 }
10151
10152 /* The class where FN is defined. */
10153 tree ctx = DECL_CONTEXT (fn);
10154
10155 /* See if the function member or the whole class type is declared
10156 final and the call can be devirtualized. */
10157 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
10158 flags |= LOOKUP_NONVIRTUAL;
10159
10160 /* [class.mfct.non-static]: If a non-static member function of a class
10161 X is called for an object that is not of type X, or of a type
10162 derived from X, the behavior is undefined.
10163
10164 So we can assume that anything passed as 'this' is non-null, and
10165 optimize accordingly. */
10166 /* Check that the base class is accessible. */
10167 if (!accessible_base_p (TREE_TYPE (argtype),
10168 BINFO_TYPE (cand->conversion_path), true))
10169 {
10170 if (complain & tf_error)
10171 error ("%qT is not an accessible base of %qT",
10172 BINFO_TYPE (cand->conversion_path),
10173 TREE_TYPE (argtype));
10174 else
10175 return error_mark_node;
10176 }
10177 /* If fn was found by a using declaration, the conversion path
10178 will be to the derived class, not the base declaring fn. We
10179 must convert to the base. */
10180 tree base_binfo = cand->conversion_path;
10181 if (BINFO_TYPE (base_binfo) != ctx)
10182 {
10183 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10184 if (base_binfo == error_mark_node)
10185 return error_mark_node;
10186 }
10187
10188 /* If we know the dynamic type of the object, look up the final overrider
10189 in the BINFO. */
10190 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10191 && resolves_to_fixed_type_p (arg))
10192 {
10193 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10194
10195 /* And unwind base_binfo to match. If we don't find the type we're
10196 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10197 inheritance; for now do a normal virtual call in that case. */
10198 tree octx = DECL_CONTEXT (ov);
10199 tree obinfo = base_binfo;
10200 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10201 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10202 if (obinfo)
10203 {
10204 fn = ov;
10205 base_binfo = obinfo;
10206 flags |= LOOKUP_NONVIRTUAL;
10207 }
10208 }
10209
10210 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10211 base_binfo, 1, complain);
10212
10213 argarray[argarray_size++] = converted_arg;
10214 parm = TREE_CHAIN (parm);
10215 }
10216
10217 auto handle_arg = [fn, flags](tree type,
10218 tree arg,
10219 int const param_index,
10220 conversion *conv,
10221 tsubst_flags_t const arg_complain)
10222 {
10223 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10224 knows not to allow any more UDCs. This needs to happen after we
10225 process cand->warnings. */
10226 if (flags & LOOKUP_NO_CONVERSION)
10227 conv->user_conv_p = true;
10228
10229 if (arg_complain & tf_warning)
10230 maybe_warn_pessimizing_move (arg, type, /*return_p=*/false);
10231
10232 tree val = convert_like_with_context (convs: conv, expr: arg, fn,
10233 argnum: param_index, complain: arg_complain);
10234 val = convert_for_arg_passing (type, val, complain: arg_complain);
10235 return val;
10236 };
10237
10238 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
10239 {
10240 gcc_assert (cand->num_convs > 0);
10241 tree object_arg = consume_object_arg ();
10242 val = handle_arg (TREE_VALUE (parm),
10243 object_arg,
10244 param_index++,
10245 convs[conv_index++],
10246 complain);
10247
10248 if (val == error_mark_node)
10249 return error_mark_node;
10250 else
10251 argarray[argarray_size++] = val;
10252 parm = TREE_CHAIN (parm);
10253 }
10254
10255 gcc_assert (first_arg == NULL_TREE);
10256 for (; arg_index < vec_safe_length (v: args) && parm;
10257 parm = TREE_CHAIN (parm), ++arg_index, ++param_index, ++conv_index)
10258 {
10259 tree current_arg = (*args)[arg_index];
10260
10261 /* If the argument is NULL and used to (implicitly) instantiate a
10262 template function (and bind one of the template arguments to
10263 the type of 'long int'), we don't want to warn about passing NULL
10264 to non-pointer argument.
10265 For example, if we have this template function:
10266
10267 template<typename T> void func(T x) {}
10268
10269 we want to warn (when -Wconversion is enabled) in this case:
10270
10271 void foo() {
10272 func<int>(NULL);
10273 }
10274
10275 but not in this case:
10276
10277 void foo() {
10278 func(NULL);
10279 }
10280 */
10281 bool const conversion_warning = !(null_node_p (expr: current_arg)
10282 && DECL_TEMPLATE_INFO (fn)
10283 && cand->template_decl
10284 && !cand->explicit_targs);
10285
10286 tsubst_flags_t const arg_complain
10287 = conversion_warning ? complain : complain & ~tf_warning;
10288
10289 val = handle_arg (TREE_VALUE (parm),
10290 current_arg,
10291 param_index,
10292 convs[conv_index],
10293 arg_complain);
10294
10295 if (val == error_mark_node)
10296 return error_mark_node;
10297 else
10298 argarray[argarray_size++] = val;
10299 }
10300
10301 /* Default arguments */
10302 for (; parm && parm != void_list_node;
10303 parm = TREE_CHAIN (parm), param_index++)
10304 {
10305 if (TREE_VALUE (parm) == error_mark_node)
10306 return error_mark_node;
10307 val = convert_default_arg (TREE_VALUE (parm),
10308 TREE_PURPOSE (parm),
10309 fn, parmnum: param_index,
10310 complain);
10311 if (val == error_mark_node)
10312 return error_mark_node;
10313 argarray[argarray_size++] = val;
10314 }
10315
10316 /* Ellipsis */
10317 int magic = magic_varargs_p (fn);
10318 for (; arg_index < vec_safe_length (v: args); ++arg_index)
10319 {
10320 tree a = (*args)[arg_index];
10321 if ((magic == 3 && arg_index == 2) || (magic == 4 && arg_index == 0))
10322 {
10323 /* Do no conversions for certain magic varargs. */
10324 a = mark_type_use (a);
10325 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10326 return error_mark_node;
10327 }
10328 else if (magic != 0)
10329 {
10330 /* Don't truncate excess precision to the semantic type. */
10331 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10332 a = TREE_OPERAND (a, 0);
10333 /* For other magic varargs only do decay_conversion. */
10334 a = decay_conversion (a, complain);
10335 }
10336 else if (DECL_CONSTRUCTOR_P (fn)
10337 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10338 TREE_TYPE (a)))
10339 {
10340 /* Avoid infinite recursion trying to call A(...). */
10341 if (complain & tf_error)
10342 /* Try to call the actual copy constructor for a good error. */
10343 call_copy_ctor (a, complain);
10344 return error_mark_node;
10345 }
10346 else
10347 a = convert_arg_to_ellipsis (arg: a, complain);
10348 if (a == error_mark_node)
10349 return error_mark_node;
10350 argarray[argarray_size++] = a;
10351 }
10352
10353 gcc_assert (argarray_size <= nargs);
10354 nargs = argarray_size;
10355 icip.reset ();
10356
10357 /* Avoid performing argument transformation if warnings are disabled.
10358 When tf_warning is set and at least one of the warnings is active
10359 the check_function_arguments function might warn about something. */
10360
10361 bool warned_p = false;
10362 if ((complain & tf_warning)
10363 && (warn_nonnull
10364 || warn_format
10365 || warn_suggest_attribute_format
10366 || warn_restrict))
10367 {
10368 tree *fargs = (!nargs ? argarray
10369 : (tree *) alloca (nargs * sizeof (tree)));
10370 for (int j = 0; j < nargs; j++)
10371 {
10372 /* For -Wformat undo the implicit passing by hidden reference
10373 done by convert_arg_to_ellipsis. */
10374 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10375 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10376 fargs[j] = TREE_OPERAND (argarray[j], 0);
10377 else
10378 fargs[j] = argarray[j];
10379 }
10380
10381 warned_p = check_function_arguments (loc: input_location, fn, TREE_TYPE (fn),
10382 nargs, fargs, NULL);
10383 }
10384
10385 if (DECL_INHERITED_CTOR (fn))
10386 {
10387 /* Check for passing ellipsis arguments to an inherited constructor. We
10388 could handle this by open-coding the inherited constructor rather than
10389 defining it, but let's not bother now. */
10390 if (!cp_unevaluated_operand
10391 && cand->num_convs
10392 && cand->convs[cand->num_convs-1]->ellipsis_p)
10393 {
10394 if (complain & tf_error)
10395 {
10396 sorry ("passing arguments to ellipsis of inherited constructor "
10397 "%qD", cand->fn);
10398 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10399 }
10400 return error_mark_node;
10401 }
10402
10403 /* A base constructor inheriting from a virtual base doesn't get the
10404 inherited arguments, just this and __vtt. */
10405 if (ctor_omit_inherited_parms (fn))
10406 nargs = 2;
10407 }
10408
10409 /* Avoid actually calling copy constructors and copy assignment operators,
10410 if possible. */
10411
10412 if (!force_elide
10413 && (!flag_elide_constructors
10414 /* It's unsafe to elide the operation when handling
10415 a noexcept-expression, it may evaluate to the wrong
10416 value (c++/53025, c++/96090). */
10417 || cp_noexcept_operand != 0))
10418 /* Do things the hard way. */;
10419 else if (cand->num_convs == 1
10420 && (DECL_COPY_CONSTRUCTOR_P (fn)
10421 || DECL_MOVE_CONSTRUCTOR_P (fn)))
10422 {
10423 tree targ;
10424 tree arg = argarray[num_artificial_parms_for (fn)];
10425 tree fa = argarray[0];
10426 bool trivial = trivial_fn_p (fn);
10427
10428 /* Pull out the real argument, disregarding const-correctness. */
10429 targ = arg;
10430 /* Strip the reference binding for the constructor parameter. */
10431 if (CONVERT_EXPR_P (targ)
10432 && TYPE_REF_P (TREE_TYPE (targ)))
10433 targ = TREE_OPERAND (targ, 0);
10434 /* But don't strip any other reference bindings; binding a temporary to a
10435 reference prevents copy elision. */
10436 while ((CONVERT_EXPR_P (targ)
10437 && !TYPE_REF_P (TREE_TYPE (targ)))
10438 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10439 targ = TREE_OPERAND (targ, 0);
10440 if (TREE_CODE (targ) == ADDR_EXPR)
10441 {
10442 targ = TREE_OPERAND (targ, 0);
10443 if (!same_type_ignoring_top_level_qualifiers_p
10444 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10445 targ = NULL_TREE;
10446 }
10447 else
10448 targ = NULL_TREE;
10449
10450 if (targ)
10451 arg = targ;
10452 else
10453 arg = cp_build_fold_indirect_ref (arg);
10454
10455 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10456 potentially-overlapping subobject. */
10457 if (CHECKING_P && cxx_dialect >= cxx17)
10458 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10459 || force_elide
10460 /* It's from binding the ref parm to a packed field. */
10461 || convs[0]->need_temporary_p
10462 || seen_error ()
10463 /* See unsafe_copy_elision_p. */
10464 || unsafe_return_slot_p (fa));
10465
10466 bool unsafe = unsafe_copy_elision_p_opt (target: fa, exp: arg);
10467 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10468
10469 /* [class.copy]: the copy constructor is implicitly defined even if the
10470 implementation elided its use. But don't warn about deprecation when
10471 eliding a temporary, as then no copy is actually performed. */
10472 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10473 if (force_elide)
10474 /* The language says this isn't called. */;
10475 else if (!trivial)
10476 {
10477 if (!mark_used (fn, complain) && !(complain & tf_error))
10478 return error_mark_node;
10479 already_used = true;
10480 }
10481 else
10482 cp_handle_deprecated_or_unavailable (fn, complain);
10483
10484 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10485 && !make_base_init_ok (exp: arg))
10486 unsafe = true;
10487
10488 /* If we're creating a temp and we already have one, don't create a
10489 new one. If we're not creating a temp but we get one, use
10490 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10491 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10492 temp or an INIT_EXPR otherwise. */
10493 if (is_dummy_object (fa))
10494 {
10495 if (TREE_CODE (arg) == TARGET_EXPR)
10496 return arg;
10497 else if (trivial)
10498 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10499 }
10500 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10501 && !unsafe)
10502 {
10503 tree to = cp_build_fold_indirect_ref (fa);
10504 val = cp_build_init_expr (t: to, i: arg);
10505 return val;
10506 }
10507 }
10508 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10509 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10510 && trivial_fn_p (fn))
10511 {
10512 tree to = cp_build_fold_indirect_ref (argarray[0]);
10513 tree type = TREE_TYPE (to);
10514 tree as_base = CLASSTYPE_AS_BASE (type);
10515 tree arg = argarray[1];
10516 location_t loc = cp_expr_loc_or_input_loc (t: arg);
10517
10518 if (is_really_empty_class (type, /*ignore_vptr*/true))
10519 {
10520 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10521 if the object argument isn't one. This isn't needed in other cases
10522 since MODIFY_EXPR is always considered an lvalue. */
10523 to = cp_build_addr_expr (to, tf_none);
10524 to = cp_build_indirect_ref (input_location, to, RO_ARROW, complain);
10525 val = build2 (COMPOUND_EXPR, type, arg, to);
10526 suppress_warning (val, OPT_Wunused);
10527 }
10528 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10529 {
10530 if (is_std_init_list (type)
10531 && conv_binds_ref_to_prvalue (c: convs[1]))
10532 warning_at (loc, OPT_Winit_list_lifetime,
10533 "assignment from temporary %<initializer_list%> does "
10534 "not extend the lifetime of the underlying array");
10535 arg = cp_build_fold_indirect_ref (arg);
10536 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10537 }
10538 else
10539 {
10540 /* We must only copy the non-tail padding parts. */
10541 tree arg0, arg2, t;
10542 tree array_type, alias_set;
10543
10544 arg2 = TYPE_SIZE_UNIT (as_base);
10545 to = cp_stabilize_reference (to);
10546 arg0 = cp_build_addr_expr (to, complain);
10547
10548 array_type = build_array_type (unsigned_char_type_node,
10549 build_index_type
10550 (size_binop (MINUS_EXPR,
10551 arg2, size_int (1))));
10552 alias_set = build_int_cst (build_pointer_type (type), 0);
10553 t = build2 (MODIFY_EXPR, void_type_node,
10554 build2 (MEM_REF, array_type, arg0, alias_set),
10555 build2 (MEM_REF, array_type, arg, alias_set));
10556 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10557 suppress_warning (val, OPT_Wunused);
10558 }
10559
10560 cp_handle_deprecated_or_unavailable (fn, complain);
10561
10562 return val;
10563 }
10564 else if (trivial_fn_p (fn))
10565 {
10566 if (DECL_DESTRUCTOR_P (fn))
10567 return build_trivial_dtor_call (instance: argarray[0]);
10568 else if (default_ctor_p (fn))
10569 {
10570 if (is_dummy_object (argarray[0]))
10571 return force_target_expr (DECL_CONTEXT (fn), void_node,
10572 no_cleanup_complain);
10573 else
10574 return cp_build_fold_indirect_ref (argarray[0]);
10575 }
10576 }
10577
10578 gcc_assert (!force_elide);
10579
10580 if (!already_used
10581 && !mark_used (fn, complain))
10582 return error_mark_node;
10583
10584 /* Warn if the built-in writes to an object of a non-trivial type. */
10585 if (warn_class_memaccess
10586 && vec_safe_length (v: args) >= 2
10587 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10588 maybe_warn_class_memaccess (input_location, fn, args);
10589
10590 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10591 {
10592 tree t;
10593 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10594 DECL_CONTEXT (fn),
10595 ba_any, NULL, complain);
10596 gcc_assert (binfo && binfo != error_mark_node);
10597
10598 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10599 complain);
10600 if (TREE_SIDE_EFFECTS (argarray[0]))
10601 argarray[0] = save_expr (argarray[0]);
10602 t = build_pointer_type (TREE_TYPE (fn));
10603 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10604 TREE_TYPE (fn) = t;
10605 }
10606 else
10607 {
10608 /* If FN is marked deprecated or unavailable, then we've already
10609 issued a diagnostic from mark_used above, so avoid redundantly
10610 issuing another one from build_addr_func. */
10611 auto w = make_temp_override (var&: deprecated_state,
10612 overrider: UNAVAILABLE_DEPRECATED_SUPPRESS);
10613
10614 fn = build_addr_func (function: fn, complain);
10615 if (fn == error_mark_node)
10616 return error_mark_node;
10617
10618 /* We're actually invoking the function. (Immediate functions get an
10619 & when invoking it even though the user didn't use &.) */
10620 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
10621 }
10622
10623 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10624 if (call == error_mark_node)
10625 return call;
10626 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10627 {
10628 tree c = extract_call_expr (call);
10629 /* build_new_op will clear this when appropriate. */
10630 CALL_EXPR_ORDERED_ARGS (c) = true;
10631 }
10632 if (warned_p)
10633 {
10634 tree c = extract_call_expr (call);
10635 if (TREE_CODE (c) == CALL_EXPR)
10636 suppress_warning (c /* Suppress all warnings. */);
10637 }
10638
10639 return call;
10640}
10641
10642namespace
10643{
10644
10645/* Return the DECL of the first non-static subobject of class TYPE
10646 that satisfies the predicate PRED or null if none can be found. */
10647
10648template <class Predicate>
10649tree
10650first_non_static_field (tree type, Predicate pred)
10651{
10652 if (!type || !CLASS_TYPE_P (type))
10653 return NULL_TREE;
10654
10655 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10656 {
10657 if (TREE_CODE (field) != FIELD_DECL)
10658 continue;
10659 if (TREE_STATIC (field))
10660 continue;
10661 if (pred (field))
10662 return field;
10663 }
10664
10665 int i = 0;
10666
10667 for (tree base_binfo, binfo = TYPE_BINFO (type);
10668 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10669 {
10670 tree base = TREE_TYPE (base_binfo);
10671 if (pred (base))
10672 return base;
10673 if (tree field = first_non_static_field (base, pred))
10674 return field;
10675 }
10676
10677 return NULL_TREE;
10678}
10679
10680struct NonPublicField
10681{
10682 bool operator() (const_tree t) const
10683 {
10684 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10685 }
10686};
10687
10688/* Return the DECL of the first non-public subobject of class TYPE
10689 or null if none can be found. */
10690
10691static inline tree
10692first_non_public_field (tree type)
10693{
10694 return first_non_static_field (type, pred: NonPublicField ());
10695}
10696
10697struct NonTrivialField
10698{
10699 bool operator() (const_tree t) const
10700 {
10701 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10702 }
10703};
10704
10705/* Return the DECL of the first non-trivial subobject of class TYPE
10706 or null if none can be found. */
10707
10708static inline tree
10709first_non_trivial_field (tree type)
10710{
10711 return first_non_static_field (type, pred: NonTrivialField ());
10712}
10713
10714} /* unnamed namespace */
10715
10716/* Return true if all copy and move assignment operator overloads for
10717 class TYPE are trivial and at least one of them is not deleted and,
10718 when ACCESS is set, accessible. Return false otherwise. Set
10719 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10720 copy or move assignment. */
10721
10722static bool
10723has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10724{
10725 tree fns = get_class_binding (type, assign_op_identifier);
10726 bool all_trivial = true;
10727
10728 /* Iterate over overloads of the assignment operator, checking
10729 accessible copy assignments for triviality. */
10730
10731 for (tree f : ovl_range (fns))
10732 {
10733 /* Skip operators that aren't copy assignments. */
10734 if (!copy_fn_p (f))
10735 continue;
10736
10737 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10738 || accessible_p (TYPE_BINFO (type), f, true));
10739
10740 /* Skip template assignment operators and deleted functions. */
10741 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10742 continue;
10743
10744 if (accessible)
10745 *hasassign = true;
10746
10747 if (!accessible || !trivial_fn_p (f))
10748 all_trivial = false;
10749
10750 /* Break early when both properties have been determined. */
10751 if (*hasassign && !all_trivial)
10752 break;
10753 }
10754
10755 /* Return true if they're all trivial and one of the expressions
10756 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10757 tree ref = cp_build_reference_type (type, false);
10758 return (all_trivial
10759 && (is_trivially_xible (MODIFY_EXPR, type, type)
10760 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10761}
10762
10763/* Return true if all copy and move ctor overloads for class TYPE are
10764 trivial and at least one of them is not deleted and, when ACCESS is
10765 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10766 to true when the TYPE has a (not necessarily trivial) default and copy
10767 (or move) ctor, respectively. */
10768
10769static bool
10770has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10771{
10772 tree fns = get_class_binding (type, complete_ctor_identifier);
10773 bool all_trivial = true;
10774
10775 for (tree f : ovl_range (fns))
10776 {
10777 /* Skip template constructors. */
10778 if (TREE_CODE (f) != FUNCTION_DECL)
10779 continue;
10780
10781 bool cpy_or_move_ctor_p = copy_fn_p (f);
10782
10783 /* Skip ctors other than default, copy, and move. */
10784 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10785 continue;
10786
10787 if (DECL_DELETED_FN (f))
10788 continue;
10789
10790 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10791 || accessible_p (TYPE_BINFO (type), f, true));
10792
10793 if (accessible)
10794 hasctor[cpy_or_move_ctor_p] = true;
10795
10796 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10797 all_trivial = false;
10798
10799 /* Break early when both properties have been determined. */
10800 if (hasctor[0] && hasctor[1] && !all_trivial)
10801 break;
10802 }
10803
10804 return all_trivial;
10805}
10806
10807/* Issue a warning on a call to the built-in function FNDECL if it is
10808 a raw memory write whose destination is not an object of (something
10809 like) trivial or standard layout type with a non-deleted assignment
10810 and copy ctor. Detects const correctness violations, corrupting
10811 references, virtual table pointers, and bypassing non-trivial
10812 assignments. */
10813
10814static void
10815maybe_warn_class_memaccess (location_t loc, tree fndecl,
10816 const vec<tree, va_gc> *args)
10817{
10818 /* Except for bcopy where it's second, the destination pointer is
10819 the first argument for all functions handled here. Compute
10820 the index of the destination and source arguments. */
10821 unsigned dstidx = DECL_FUNCTION_CODE (decl: fndecl) == BUILT_IN_BCOPY;
10822 unsigned srcidx = !dstidx;
10823
10824 tree dest = (*args)[dstidx];
10825 if (!TREE_TYPE (dest)
10826 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10827 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10828 return;
10829
10830 tree srctype = NULL_TREE;
10831
10832 /* Determine the type of the pointed-to object and whether it's
10833 a complete class type. */
10834 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10835
10836 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10837 return;
10838
10839 /* Check to see if the raw memory call is made by a non-static member
10840 function with THIS as the destination argument for the destination
10841 type. If so, and if the class has no non-trivial bases or members,
10842 be more permissive. */
10843 if (current_function_decl
10844 && DECL_OBJECT_MEMBER_FUNCTION_P (current_function_decl)
10845 && is_object_parameter (tree_strip_nop_conversions (dest)))
10846 {
10847 tree ctx = DECL_CONTEXT (current_function_decl);
10848 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10849 tree binfo = TYPE_BINFO (ctx);
10850
10851 if (special
10852 && !BINFO_VTABLE (binfo)
10853 && !first_non_trivial_field (type: desttype))
10854 return;
10855 }
10856
10857 /* True if the class is trivial. */
10858 bool trivial = trivial_type_p (desttype);
10859
10860 /* Set to true if DESTYPE has an accessible copy assignment. */
10861 bool hasassign = false;
10862 /* True if all of the class' overloaded copy assignment operators
10863 are all trivial (and not deleted) and at least one of them is
10864 accessible. */
10865 bool trivassign = has_trivial_copy_assign_p (type: desttype, access: true, hasassign: &hasassign);
10866
10867 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10868 respectively. */
10869 bool hasctors[2] = { false, false };
10870
10871 /* True if all of the class' overloaded copy constructors are all
10872 trivial (and not deleted) and at least one of them is accessible. */
10873 bool trivcopy = has_trivial_copy_p (type: desttype, access: true, hasctor: hasctors);
10874
10875 /* Set FLD to the first private/protected member of the class. */
10876 tree fld = trivial ? first_non_public_field (type: desttype) : NULL_TREE;
10877
10878 /* The warning format string. */
10879 const char *warnfmt = NULL;
10880 /* A suggested alternative to offer instead of the raw memory call.
10881 Empty string when none can be come up with. */
10882 const char *suggest = "";
10883 bool warned = false;
10884
10885 switch (DECL_FUNCTION_CODE (decl: fndecl))
10886 {
10887 case BUILT_IN_MEMSET:
10888 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10889 {
10890 /* Diagnose setting non-copy-assignable or non-trivial types,
10891 or types with a private member, to (potentially) non-zero
10892 bytes. Since the value of the bytes being written is unknown,
10893 suggest using assignment instead (if one exists). Also warn
10894 for writes into objects for which zero-initialization doesn't
10895 mean all bits clear (pointer-to-member data, where null is all
10896 bits set). Since the value being written is (most likely)
10897 non-zero, simply suggest assignment (but not copy assignment). */
10898 suggest = "; use assignment instead";
10899 if (!trivassign)
10900 warnfmt = G_("%qD writing to an object of type %#qT with "
10901 "no trivial copy-assignment");
10902 else if (!trivial)
10903 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10904 else if (fld)
10905 {
10906 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10907 warned = warning_at (loc, OPT_Wclass_memaccess,
10908 "%qD writing to an object of type %#qT with "
10909 "%qs member %qD",
10910 fndecl, desttype, access, fld);
10911 }
10912 else if (!zero_init_p (desttype))
10913 warnfmt = G_("%qD writing to an object of type %#qT containing "
10914 "a pointer to data member%s");
10915
10916 break;
10917 }
10918 /* Fall through. */
10919
10920 case BUILT_IN_BZERO:
10921 /* Similarly to the above, diagnose clearing non-trivial or non-
10922 standard layout objects, or objects of types with no assignmenmt.
10923 Since the value being written is known to be zero, suggest either
10924 copy assignment, copy ctor, or default ctor as an alternative,
10925 depending on what's available. */
10926
10927 if (hasassign && hasctors[0])
10928 suggest = G_("; use assignment or value-initialization instead");
10929 else if (hasassign)
10930 suggest = G_("; use assignment instead");
10931 else if (hasctors[0])
10932 suggest = G_("; use value-initialization instead");
10933
10934 if (!trivassign)
10935 warnfmt = G_("%qD clearing an object of type %#qT with "
10936 "no trivial copy-assignment%s");
10937 else if (!trivial)
10938 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10939 else if (!zero_init_p (desttype))
10940 warnfmt = G_("%qD clearing an object of type %#qT containing "
10941 "a pointer-to-member%s");
10942 break;
10943
10944 case BUILT_IN_BCOPY:
10945 case BUILT_IN_MEMCPY:
10946 case BUILT_IN_MEMMOVE:
10947 case BUILT_IN_MEMPCPY:
10948 /* Determine the type of the source object. */
10949 srctype = TREE_TYPE ((*args)[srcidx]);
10950 if (!srctype || !INDIRECT_TYPE_P (srctype))
10951 srctype = void_type_node;
10952 else
10953 srctype = TREE_TYPE (srctype);
10954
10955 /* Since it's impossible to determine wheter the byte copy is
10956 being used in place of assignment to an existing object or
10957 as a substitute for initialization, assume it's the former.
10958 Determine the best alternative to use instead depending on
10959 what's not deleted. */
10960 if (hasassign && hasctors[1])
10961 suggest = G_("; use copy-assignment or copy-initialization instead");
10962 else if (hasassign)
10963 suggest = G_("; use copy-assignment instead");
10964 else if (hasctors[1])
10965 suggest = G_("; use copy-initialization instead");
10966
10967 if (!trivassign)
10968 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10969 "copy-assignment%s");
10970 else if (!trivially_copyable_p (desttype))
10971 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10972 "type %#qT%s");
10973 else if (!trivcopy)
10974 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10975
10976 else if (!trivial
10977 && !VOID_TYPE_P (srctype)
10978 && !is_byte_access_type (srctype)
10979 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10980 srctype))
10981 {
10982 /* Warn when copying into a non-trivial object from an object
10983 of a different type other than void or char. */
10984 warned = warning_at (loc, OPT_Wclass_memaccess,
10985 "%qD copying an object of non-trivial type "
10986 "%#qT from an array of %#qT",
10987 fndecl, desttype, srctype);
10988 }
10989 else if (fld
10990 && !VOID_TYPE_P (srctype)
10991 && !is_byte_access_type (srctype)
10992 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10993 srctype))
10994 {
10995 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10996 warned = warning_at (loc, OPT_Wclass_memaccess,
10997 "%qD copying an object of type %#qT with "
10998 "%qs member %qD from an array of %#qT; use "
10999 "assignment or copy-initialization instead",
11000 fndecl, desttype, access, fld, srctype);
11001 }
11002 else if (!trivial && vec_safe_length (v: args) > 2)
11003 {
11004 tree sz = maybe_constant_value ((*args)[2]);
11005 if (!tree_fits_uhwi_p (sz))
11006 break;
11007
11008 /* Finally, warn on partial copies. */
11009 unsigned HOST_WIDE_INT typesize
11010 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
11011 if (typesize == 0)
11012 break;
11013 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
11014 warned = warning_at (loc, OPT_Wclass_memaccess,
11015 (typesize - partial > 1
11016 ? G_("%qD writing to an object of "
11017 "a non-trivial type %#qT leaves %wu "
11018 "bytes unchanged")
11019 : G_("%qD writing to an object of "
11020 "a non-trivial type %#qT leaves %wu "
11021 "byte unchanged")),
11022 fndecl, desttype, typesize - partial);
11023 }
11024 break;
11025
11026 case BUILT_IN_REALLOC:
11027
11028 if (!trivially_copyable_p (desttype))
11029 warnfmt = G_("%qD moving an object of non-trivially copyable type "
11030 "%#qT; use %<new%> and %<delete%> instead");
11031 else if (!trivcopy)
11032 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
11033 "constructor; use %<new%> and %<delete%> instead");
11034 else if (!get_dtor (desttype, tf_none))
11035 warnfmt = G_("%qD moving an object of type %#qT with deleted "
11036 "destructor");
11037 else if (!trivial)
11038 {
11039 tree sz = maybe_constant_value ((*args)[1]);
11040 if (TREE_CODE (sz) == INTEGER_CST
11041 && tree_int_cst_lt (t1: sz, TYPE_SIZE_UNIT (desttype)))
11042 /* Finally, warn on reallocation into insufficient space. */
11043 warned = warning_at (loc, OPT_Wclass_memaccess,
11044 "%qD moving an object of non-trivial type "
11045 "%#qT and size %E into a region of size %E",
11046 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
11047 sz);
11048 }
11049 break;
11050
11051 default:
11052 return;
11053 }
11054
11055 if (warnfmt)
11056 {
11057 if (suggest)
11058 warned = warning_at (loc, OPT_Wclass_memaccess,
11059 warnfmt, fndecl, desttype, suggest);
11060 else
11061 warned = warning_at (loc, OPT_Wclass_memaccess,
11062 warnfmt, fndecl, desttype);
11063 }
11064
11065 if (warned)
11066 inform (location_of (desttype), "%#qT declared here", desttype);
11067}
11068
11069/* Build and return a call to FN, using NARGS arguments in ARGARRAY.
11070 If FN is the result of resolving an overloaded target built-in,
11071 ORIG_FNDECL is the original function decl, otherwise it is null.
11072 This function performs no overload resolution, conversion, or other
11073 high-level operations. */
11074
11075tree
11076build_cxx_call (tree fn, int nargs, tree *argarray,
11077 tsubst_flags_t complain, tree orig_fndecl)
11078{
11079 tree fndecl;
11080
11081 /* Remember roughly where this call is. */
11082 location_t loc = cp_expr_loc_or_input_loc (t: fn);
11083 fn = build_call_a (function: fn, n: nargs, argarray);
11084 SET_EXPR_LOCATION (fn, loc);
11085
11086 fndecl = get_callee_fndecl (fn);
11087 if (!orig_fndecl)
11088 orig_fndecl = fndecl;
11089
11090 /* Check that arguments to builtin functions match the expectations. */
11091 if (fndecl
11092 && !processing_template_decl
11093 && fndecl_built_in_p (node: fndecl))
11094 {
11095 int i;
11096
11097 /* We need to take care that values to BUILT_IN_NORMAL
11098 are reduced. */
11099 for (i = 0; i < nargs; i++)
11100 argarray[i] = maybe_constant_value (argarray[i]);
11101
11102 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
11103 orig_fndecl, nargs, argarray))
11104 return error_mark_node;
11105 else if (fndecl_built_in_p (node: fndecl, name1: BUILT_IN_CLEAR_PADDING))
11106 {
11107 tree arg0 = argarray[0];
11108 STRIP_NOPS (arg0);
11109 if (TREE_CODE (arg0) == ADDR_EXPR
11110 && DECL_P (TREE_OPERAND (arg0, 0))
11111 && same_type_ignoring_top_level_qualifiers_p
11112 (TREE_TYPE (TREE_TYPE (argarray[0])),
11113 TREE_TYPE (TREE_TYPE (arg0))))
11114 /* For __builtin_clear_padding (&var) we know the type
11115 is for a complete object, so there is no risk in clearing
11116 padding that is reused in some derived class member. */;
11117 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
11118 {
11119 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
11120 "argument %u in call to function %qE "
11121 "has pointer to a non-trivially-copyable type (%qT)",
11122 1, fndecl, TREE_TYPE (argarray[0]));
11123 return error_mark_node;
11124 }
11125 }
11126 }
11127
11128 if (VOID_TYPE_P (TREE_TYPE (fn)))
11129 return fn;
11130
11131 /* 5.2.2/11: If a function call is a prvalue of object type: if the
11132 function call is either the operand of a decltype-specifier or the
11133 right operand of a comma operator that is the operand of a
11134 decltype-specifier, a temporary object is not introduced for the
11135 prvalue. The type of the prvalue may be incomplete. */
11136 if (!(complain & tf_decltype))
11137 {
11138 fn = require_complete_type (fn, complain);
11139 if (fn == error_mark_node)
11140 return error_mark_node;
11141
11142 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
11143 {
11144 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
11145 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
11146 }
11147 }
11148 return convert_from_reference (fn);
11149}
11150
11151/* Returns the value to use for the in-charge parameter when making a
11152 call to a function with the indicated NAME.
11153
11154 FIXME:Can't we find a neater way to do this mapping? */
11155
11156tree
11157in_charge_arg_for_name (tree name)
11158{
11159 if (IDENTIFIER_CTOR_P (name))
11160 {
11161 if (name == complete_ctor_identifier)
11162 return integer_one_node;
11163 gcc_checking_assert (name == base_ctor_identifier);
11164 }
11165 else
11166 {
11167 if (name == complete_dtor_identifier)
11168 return integer_two_node;
11169 else if (name == deleting_dtor_identifier)
11170 return integer_three_node;
11171 gcc_checking_assert (name == base_dtor_identifier);
11172 }
11173
11174 return integer_zero_node;
11175}
11176
11177/* We've built up a constructor call RET. Complain if it delegates to the
11178 constructor we're currently compiling. */
11179
11180static void
11181check_self_delegation (tree ret)
11182{
11183 if (TREE_CODE (ret) == TARGET_EXPR)
11184 ret = TARGET_EXPR_INITIAL (ret);
11185 tree fn = cp_get_callee_fndecl_nofold (ret);
11186 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11187 error ("constructor delegates to itself");
11188}
11189
11190/* Build a call to a constructor, destructor, or an assignment
11191 operator for INSTANCE, an expression with class type. NAME
11192 indicates the special member function to call; *ARGS are the
11193 arguments. ARGS may be NULL. This may change ARGS. BINFO
11194 indicates the base of INSTANCE that is to be passed as the `this'
11195 parameter to the member function called.
11196
11197 FLAGS are the LOOKUP_* flags to use when processing the call.
11198
11199 If NAME indicates a complete object constructor, INSTANCE may be
11200 NULL_TREE. In this case, the caller will call build_cplus_new to
11201 store the newly constructed object into a VAR_DECL. */
11202
11203tree
11204build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11205 tree binfo, int flags, tsubst_flags_t complain)
11206{
11207 tree fns;
11208 /* The type of the subobject to be constructed or destroyed. */
11209 tree class_type;
11210 vec<tree, va_gc> *allocated = NULL;
11211 tree ret;
11212
11213 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11214
11215 if (error_operand_p (t: instance))
11216 return error_mark_node;
11217
11218 if (IDENTIFIER_DTOR_P (name))
11219 {
11220 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11221 if (!type_build_dtor_call (TREE_TYPE (instance)))
11222 /* Shortcut to avoid lazy destructor declaration. */
11223 return build_trivial_dtor_call (instance);
11224 }
11225
11226 if (TYPE_P (binfo))
11227 {
11228 /* Resolve the name. */
11229 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11230 return error_mark_node;
11231
11232 binfo = TYPE_BINFO (binfo);
11233 }
11234
11235 gcc_assert (binfo != NULL_TREE);
11236
11237 class_type = BINFO_TYPE (binfo);
11238
11239 /* Handle the special case where INSTANCE is NULL_TREE. */
11240 if (name == complete_ctor_identifier && !instance)
11241 instance = build_dummy_object (class_type);
11242 else
11243 {
11244 /* Convert to the base class, if necessary. */
11245 if (!same_type_ignoring_top_level_qualifiers_p
11246 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11247 {
11248 if (IDENTIFIER_CDTOR_P (name))
11249 /* For constructors and destructors, either the base is
11250 non-virtual, or it is virtual but we are doing the
11251 conversion from a constructor or destructor for the
11252 complete object. In either case, we can convert
11253 statically. */
11254 instance = convert_to_base_statically (instance, binfo);
11255 else
11256 {
11257 /* However, for assignment operators, we must convert
11258 dynamically if the base is virtual. */
11259 gcc_checking_assert (name == assign_op_identifier);
11260 instance = build_base_path (PLUS_EXPR, instance,
11261 binfo, /*nonnull=*/1, complain);
11262 }
11263 }
11264 }
11265
11266 gcc_assert (instance != NULL_TREE);
11267
11268 /* In C++17, "If the initializer expression is a prvalue and the
11269 cv-unqualified version of the source type is the same class as the class
11270 of the destination, the initializer expression is used to initialize the
11271 destination object." Handle that here to avoid doing overload
11272 resolution. */
11273 if (cxx_dialect >= cxx17
11274 && args && vec_safe_length (v: *args) == 1
11275 && !unsafe_return_slot_p (t: instance))
11276 {
11277 tree arg = (**args)[0];
11278
11279 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11280 && !TYPE_HAS_LIST_CTOR (class_type)
11281 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11282 && CONSTRUCTOR_NELTS (arg) == 1)
11283 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11284
11285 if ((TREE_CODE (arg) == TARGET_EXPR
11286 || TREE_CODE (arg) == CONSTRUCTOR)
11287 && (same_type_ignoring_top_level_qualifiers_p
11288 (class_type, TREE_TYPE (arg))))
11289 {
11290 if (is_dummy_object (instance))
11291 return arg;
11292 else if (TREE_CODE (arg) == TARGET_EXPR)
11293 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11294
11295 if ((complain & tf_error)
11296 && (flags & LOOKUP_DELEGATING_CONS))
11297 check_self_delegation (ret: arg);
11298 /* Avoid change of behavior on Wunused-var-2.C. */
11299 instance = mark_lvalue_use (instance);
11300 return cp_build_init_expr (t: instance, i: arg);
11301 }
11302 }
11303
11304 fns = lookup_fnfields (binfo, name, 1, complain);
11305
11306 /* When making a call to a constructor or destructor for a subobject
11307 that uses virtual base classes, pass down a pointer to a VTT for
11308 the subobject. */
11309 if ((name == base_ctor_identifier
11310 || name == base_dtor_identifier)
11311 && CLASSTYPE_VBASECLASSES (class_type))
11312 {
11313 tree vtt;
11314 tree sub_vtt;
11315
11316 /* If the current function is a complete object constructor
11317 or destructor, then we fetch the VTT directly.
11318 Otherwise, we look it up using the VTT we were given. */
11319 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11320 vtt = decay_conversion (vtt, complain);
11321 if (vtt == error_mark_node)
11322 return error_mark_node;
11323 vtt = build_if_in_charge (true_stmt: vtt, current_vtt_parm);
11324 if (BINFO_SUBVTT_INDEX (binfo))
11325 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11326 else
11327 sub_vtt = vtt;
11328
11329 if (args == NULL)
11330 {
11331 allocated = make_tree_vector ();
11332 args = &allocated;
11333 }
11334
11335 vec_safe_insert (v&: *args, ix: 0, obj: sub_vtt);
11336 }
11337
11338 ret = build_new_method_call (instance, fns, args,
11339 TYPE_BINFO (BINFO_TYPE (binfo)),
11340 flags, /*fn=*/NULL,
11341 complain);
11342
11343 if (allocated != NULL)
11344 release_tree_vector (allocated);
11345
11346 if ((complain & tf_error)
11347 && (flags & LOOKUP_DELEGATING_CONS)
11348 && name == complete_ctor_identifier)
11349 check_self_delegation (ret);
11350
11351 return ret;
11352}
11353
11354/* Return the NAME, as a C string. The NAME indicates a function that
11355 is a member of TYPE. *FREE_P is set to true if the caller must
11356 free the memory returned.
11357
11358 Rather than go through all of this, we should simply set the names
11359 of constructors and destructors appropriately, and dispense with
11360 ctor_identifier, dtor_identifier, etc. */
11361
11362static char *
11363name_as_c_string (tree name, tree type, bool *free_p)
11364{
11365 const char *pretty_name;
11366
11367 /* Assume that we will not allocate memory. */
11368 *free_p = false;
11369 /* Constructors and destructors are special. */
11370 if (IDENTIFIER_CDTOR_P (name))
11371 {
11372 pretty_name
11373 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11374 /* For a destructor, add the '~'. */
11375 if (IDENTIFIER_DTOR_P (name))
11376 {
11377 pretty_name = concat ("~", pretty_name, NULL);
11378 /* Remember that we need to free the memory allocated. */
11379 *free_p = true;
11380 }
11381 }
11382 else if (IDENTIFIER_CONV_OP_P (name))
11383 {
11384 pretty_name = concat ("operator ",
11385 type_as_string_translate (TREE_TYPE (name),
11386 TFF_PLAIN_IDENTIFIER),
11387 NULL);
11388 /* Remember that we need to free the memory allocated. */
11389 *free_p = true;
11390 }
11391 else
11392 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11393
11394 return CONST_CAST (char *, pretty_name);
11395}
11396
11397/* If CANDIDATES contains exactly one candidate, return it, otherwise
11398 return NULL. */
11399
11400static z_candidate *
11401single_z_candidate (z_candidate *candidates)
11402{
11403 if (candidates == NULL)
11404 return NULL;
11405
11406 if (candidates->next)
11407 return NULL;
11408
11409 return candidates;
11410}
11411
11412/* If CANDIDATE is invalid due to a bad argument type, return the
11413 pertinent conversion_info.
11414
11415 Otherwise, return NULL. */
11416
11417static const conversion_info *
11418maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11419{
11420 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11421 rejection_reason *r = candidate->reason;
11422
11423 if (r == NULL)
11424 return NULL;
11425
11426 switch (r->code)
11427 {
11428 default:
11429 return NULL;
11430
11431 case rr_arg_conversion:
11432 return &r->u.conversion;
11433
11434 case rr_bad_arg_conversion:
11435 return &r->u.bad_conversion;
11436 }
11437}
11438
11439/* Issue an error and note complaining about a bad argument type at a
11440 callsite with a single candidate FNDECL.
11441
11442 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11443 case input_location is used).
11444 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11445 the formal parameter. */
11446
11447void
11448complain_about_bad_argument (location_t arg_loc,
11449 tree from_type, tree to_type,
11450 tree fndecl, int parmnum)
11451{
11452 auto_diagnostic_group d;
11453 range_label_for_type_mismatch rhs_label (from_type, to_type);
11454 range_label *label = &rhs_label;
11455 if (arg_loc == UNKNOWN_LOCATION)
11456 {
11457 arg_loc = input_location;
11458 label = NULL;
11459 }
11460 gcc_rich_location richloc (arg_loc, label);
11461 error_at (&richloc,
11462 "cannot convert %qH to %qI",
11463 from_type, to_type);
11464 maybe_inform_about_fndecl_for_bogus_argument_init (fn: fndecl,
11465 argnum: parmnum);
11466}
11467
11468/* Subroutine of build_new_method_call_1, for where there are no viable
11469 candidates for the call. */
11470
11471static void
11472complain_about_no_candidates_for_method_call (tree instance,
11473 z_candidate *candidates,
11474 tree explicit_targs,
11475 tree basetype,
11476 tree optype, tree name,
11477 bool skip_first_for_error,
11478 vec<tree, va_gc> *user_args)
11479{
11480 auto_diagnostic_group d;
11481 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11482 cxx_incomplete_type_error (value: instance, type: basetype);
11483 else if (optype)
11484 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11485 basetype, optype, build_tree_list_vec (user_args),
11486 TREE_TYPE (instance));
11487 else
11488 {
11489 /* Special-case for when there's a single candidate that's failing
11490 due to a bad argument type. */
11491 if (z_candidate *candidate = single_z_candidate (candidates))
11492 if (const conversion_info *conv
11493 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11494 {
11495 tree from_type = conv->from;
11496 if (!TYPE_P (conv->from))
11497 from_type = lvalue_type (conv->from);
11498 complain_about_bad_argument (arg_loc: conv->loc,
11499 from_type, to_type: conv->to_type,
11500 fndecl: candidate->fn, parmnum: conv->n_arg);
11501 return;
11502 }
11503
11504 tree arglist = build_tree_list_vec (user_args);
11505 tree errname = name;
11506 bool twiddle = false;
11507 if (IDENTIFIER_CDTOR_P (errname))
11508 {
11509 twiddle = IDENTIFIER_DTOR_P (errname);
11510 errname = constructor_name (basetype);
11511 }
11512 if (explicit_targs)
11513 errname = lookup_template_function (errname, explicit_targs);
11514 if (skip_first_for_error)
11515 arglist = TREE_CHAIN (arglist);
11516 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11517 basetype, &"~"[!twiddle], errname, arglist,
11518 TREE_TYPE (instance));
11519 }
11520 print_z_candidates (loc: location_of (name), candidates);
11521}
11522
11523/* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11524 be set, upon return, to the function called. ARGS may be NULL.
11525 This may change ARGS. */
11526
11527tree
11528build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11529 tree conversion_path, int flags,
11530 tree *fn_p, tsubst_flags_t complain)
11531{
11532 struct z_candidate *candidates = 0, *cand;
11533 tree explicit_targs = NULL_TREE;
11534 tree basetype = NULL_TREE;
11535 tree access_binfo;
11536 tree optype;
11537 tree first_mem_arg = NULL_TREE;
11538 tree name;
11539 bool skip_first_for_error;
11540 vec<tree, va_gc> *user_args;
11541 tree call;
11542 tree fn;
11543 int template_only = 0;
11544 bool any_viable_p;
11545 tree orig_instance;
11546 tree orig_fns;
11547 vec<tree, va_gc> *orig_args = NULL;
11548
11549 auto_cond_timevar tv (TV_OVERLOAD);
11550
11551 gcc_assert (instance != NULL_TREE);
11552
11553 /* We don't know what function we're going to call, yet. */
11554 if (fn_p)
11555 *fn_p = NULL_TREE;
11556
11557 if (error_operand_p (t: instance)
11558 || !fns || error_operand_p (t: fns))
11559 return error_mark_node;
11560
11561 if (!BASELINK_P (fns))
11562 {
11563 if (complain & tf_error)
11564 error ("call to non-function %qD", fns);
11565 return error_mark_node;
11566 }
11567
11568 orig_instance = instance;
11569 orig_fns = fns;
11570
11571 /* Dismantle the baselink to collect all the information we need. */
11572 if (!conversion_path)
11573 conversion_path = BASELINK_BINFO (fns);
11574 access_binfo = BASELINK_ACCESS_BINFO (fns);
11575 optype = BASELINK_OPTYPE (fns);
11576 fns = BASELINK_FUNCTIONS (fns);
11577 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11578 {
11579 explicit_targs = TREE_OPERAND (fns, 1);
11580 fns = TREE_OPERAND (fns, 0);
11581 template_only = 1;
11582 }
11583 gcc_assert (OVL_P (fns));
11584 fn = OVL_FIRST (fns);
11585 name = DECL_NAME (fn);
11586
11587 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11588 gcc_assert (CLASS_TYPE_P (basetype));
11589
11590 user_args = args == NULL ? NULL : *args;
11591 /* Under DR 147 A::A() is an invalid constructor call,
11592 not a functional cast. */
11593 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11594 {
11595 if (! (complain & tf_error))
11596 return error_mark_node;
11597
11598 basetype = DECL_CONTEXT (fn);
11599 name = constructor_name (basetype);
11600 auto_diagnostic_group d;
11601 if (permerror (input_location,
11602 "cannot call constructor %<%T::%D%> directly",
11603 basetype, name))
11604 inform (input_location, "for a function-style cast, remove the "
11605 "redundant %<::%D%>", name);
11606 call = build_functional_cast (input_location, basetype,
11607 build_tree_list_vec (user_args),
11608 complain);
11609 return call;
11610 }
11611
11612 if (processing_template_decl)
11613 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11614
11615 /* Process the argument list. */
11616 if (args != NULL && *args != NULL)
11617 {
11618 *args = resolve_args (args: *args, complain);
11619 if (*args == NULL)
11620 return error_mark_node;
11621 user_args = *args;
11622 }
11623
11624 /* Consider the object argument to be used even if we end up selecting a
11625 static member function. */
11626 instance = mark_type_use (instance);
11627
11628 /* Figure out whether to skip the first argument for the error
11629 message we will display to users if an error occurs. We don't
11630 want to display any compiler-generated arguments. The "this"
11631 pointer hasn't been added yet. However, we must remove the VTT
11632 pointer if this is a call to a base-class constructor or
11633 destructor. */
11634 skip_first_for_error = false;
11635 if (IDENTIFIER_CDTOR_P (name))
11636 {
11637 /* Callers should explicitly indicate whether they want to ctor
11638 the complete object or just the part without virtual bases. */
11639 gcc_assert (name != ctor_identifier);
11640
11641 /* Remove the VTT pointer, if present. */
11642 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11643 && CLASSTYPE_VBASECLASSES (basetype))
11644 skip_first_for_error = true;
11645
11646 /* It's OK to call destructors and constructors on cv-qualified
11647 objects. Therefore, convert the INSTANCE to the unqualified
11648 type, if necessary. */
11649 if (!same_type_p (basetype, TREE_TYPE (instance)))
11650 {
11651 instance = build_this (obj: instance);
11652 instance = build_nop (build_pointer_type (basetype), instance);
11653 instance = build_fold_indirect_ref (instance);
11654 }
11655 }
11656 else
11657 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11658
11659 /* For the overload resolution we need to find the actual `this`
11660 that would be captured if the call turns out to be to a
11661 non-static member function. Do not actually capture it at this
11662 point. */
11663 if (DECL_CONSTRUCTOR_P (fn))
11664 /* Constructors don't use the enclosing 'this'. */
11665 first_mem_arg = instance;
11666 else
11667 first_mem_arg = maybe_resolve_dummy (instance, false);
11668
11669 conversion_obstack_sentinel cos;
11670
11671 /* The number of arguments artificial parms in ARGS; we subtract one because
11672 there's no 'this' in ARGS. */
11673 unsigned skip = num_artificial_parms_for (fn) - 1;
11674
11675 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11676 initializer, not T({ }). */
11677 if (DECL_CONSTRUCTOR_P (fn)
11678 && vec_safe_length (v: user_args) > skip
11679 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11680 {
11681 tree init_list = (*user_args)[skip];
11682 tree init = NULL_TREE;
11683
11684 gcc_assert (user_args->length () == skip + 1
11685 && !(flags & LOOKUP_ONLYCONVERTING));
11686
11687 /* If the initializer list has no elements and T is a class type with
11688 a default constructor, the object is value-initialized. Handle
11689 this here so we don't need to handle it wherever we use
11690 build_special_member_call. */
11691 if (CONSTRUCTOR_NELTS (init_list) == 0
11692 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11693 /* For a user-provided default constructor, use the normal
11694 mechanisms so that protected access works. */
11695 && type_has_non_user_provided_default_constructor (basetype)
11696 && !processing_template_decl)
11697 init = build_value_init (basetype, complain);
11698
11699 /* If BASETYPE is an aggregate, we need to do aggregate
11700 initialization. */
11701 else if (CP_AGGREGATE_TYPE_P (basetype))
11702 {
11703 init = reshape_init (basetype, init_list, complain);
11704 init = digest_init (basetype, init, complain);
11705 }
11706
11707 if (init)
11708 {
11709 if (is_dummy_object (instance))
11710 return get_target_expr (init, complain);
11711 return cp_build_init_expr (t: instance, i: init);
11712 }
11713
11714 /* Otherwise go ahead with overload resolution. */
11715 add_list_candidates (fns, first_arg: first_mem_arg, args: user_args,
11716 totype: basetype, explicit_targs, template_only,
11717 conversion_path, access_path: access_binfo, flags,
11718 candidates: &candidates, complain);
11719 }
11720 else
11721 add_candidates (fns, first_arg: first_mem_arg, args: user_args, return_type: optype,
11722 explicit_targs, template_only, conversion_path,
11723 access_path: access_binfo, flags, candidates: &candidates, complain);
11724
11725 any_viable_p = false;
11726 candidates = splice_viable (cands: candidates, strict_p: false, any_viable_p: &any_viable_p);
11727
11728 if (!any_viable_p)
11729 {
11730 /* [dcl.init], 17.6.2.2:
11731
11732 Otherwise, if no constructor is viable, the destination type is
11733 a (possibly cv-qualified) aggregate class A, and the initializer
11734 is a parenthesized expression-list, the object is initialized as
11735 follows...
11736
11737 We achieve this by building up a CONSTRUCTOR, as for list-init,
11738 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11739 the two. */
11740 if (DECL_CONSTRUCTOR_P (fn)
11741 && !(flags & LOOKUP_ONLYCONVERTING)
11742 && cxx_dialect >= cxx20
11743 && CP_AGGREGATE_TYPE_P (basetype)
11744 && !vec_safe_is_empty (v: user_args))
11745 {
11746 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11747 tree ctor = build_constructor_from_vec (init_list_type_node,
11748 user_args);
11749 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11750 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11751 if (is_dummy_object (instance))
11752 return ctor;
11753 else
11754 {
11755 ctor = digest_init (basetype, ctor, complain);
11756 if (ctor == error_mark_node)
11757 return error_mark_node;
11758 return cp_build_init_expr (t: instance, i: ctor);
11759 }
11760 }
11761 if (complain & tf_error)
11762 complain_about_no_candidates_for_method_call (instance, candidates,
11763 explicit_targs, basetype,
11764 optype, name,
11765 skip_first_for_error,
11766 user_args);
11767 call = error_mark_node;
11768 }
11769 else
11770 {
11771 cand = tourney (candidates, complain);
11772 if (cand == 0)
11773 {
11774 char *pretty_name;
11775 bool free_p;
11776 tree arglist;
11777
11778 if (complain & tf_error)
11779 {
11780 pretty_name = name_as_c_string (name, type: basetype, free_p: &free_p);
11781 arglist = build_tree_list_vec (user_args);
11782 if (skip_first_for_error)
11783 arglist = TREE_CHAIN (arglist);
11784 auto_diagnostic_group d;
11785 if (!any_strictly_viable (cands: candidates))
11786 error ("no matching function for call to %<%s(%A)%>",
11787 pretty_name, arglist);
11788 else
11789 error ("call of overloaded %<%s(%A)%> is ambiguous",
11790 pretty_name, arglist);
11791 print_z_candidates (loc: location_of (name), candidates);
11792 if (free_p)
11793 free (ptr: pretty_name);
11794 }
11795 call = error_mark_node;
11796 if (fn_p)
11797 *fn_p = error_mark_node;
11798 }
11799 else
11800 {
11801 fn = cand->fn;
11802 call = NULL_TREE;
11803
11804 if (!(flags & LOOKUP_NONVIRTUAL)
11805 && DECL_PURE_VIRTUAL_P (fn)
11806 && instance == current_class_ref
11807 && (complain & tf_warning))
11808 {
11809 /* This is not an error, it is runtime undefined
11810 behavior. */
11811 if (!current_function_decl)
11812 warning (0, "pure virtual %q#D called from "
11813 "non-static data member initializer", fn);
11814 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11815 || DECL_DESTRUCTOR_P (current_function_decl))
11816 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11817 ? G_("pure virtual %q#D called from constructor")
11818 : G_("pure virtual %q#D called from destructor")),
11819 fn);
11820 }
11821
11822 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11823 && !DECL_CONSTRUCTOR_P (fn)
11824 && is_dummy_object (instance))
11825 {
11826 instance = maybe_resolve_dummy (instance, true);
11827 if (instance == error_mark_node)
11828 call = error_mark_node;
11829 else if (!is_dummy_object (instance))
11830 {
11831 /* We captured 'this' in the current lambda now that
11832 we know we really need it. */
11833 cand->first_arg = instance;
11834 }
11835 else if (current_class_ptr && any_dependent_bases_p ())
11836 /* We can't tell until instantiation time whether we can use
11837 *this as the implicit object argument. */;
11838 else
11839 {
11840 if (complain & tf_error)
11841 error ("cannot call member function %qD without object",
11842 fn);
11843 call = error_mark_node;
11844 }
11845 }
11846
11847 if (call != error_mark_node)
11848 {
11849 /* Now we know what function is being called. */
11850 if (fn_p)
11851 *fn_p = fn;
11852 /* Build the actual CALL_EXPR. */
11853 call = build_over_call (cand, flags, complain);
11854
11855 /* Suppress warnings for if (my_struct.operator= (x)) where
11856 my_struct is implicitly converted to bool. */
11857 if (TREE_CODE (call) == MODIFY_EXPR)
11858 suppress_warning (call, OPT_Wparentheses);
11859
11860 /* In an expression of the form `a->f()' where `f' turns
11861 out to be a static member function, `a' is
11862 none-the-less evaluated. */
11863 if (!is_dummy_object (instance))
11864 call = keep_unused_object_arg (result: call, obj: instance, fn);
11865 if (call != error_mark_node
11866 && DECL_DESTRUCTOR_P (cand->fn)
11867 && !VOID_TYPE_P (TREE_TYPE (call)))
11868 /* An explicit call of the form "x->~X()" has type
11869 "void". However, on platforms where destructors
11870 return "this" (i.e., those where
11871 targetm.cxx.cdtor_returns_this is true), such calls
11872 will appear to have a return value of pointer type
11873 to the low-level call machinery. We do not want to
11874 change the low-level machinery, since we want to be
11875 able to optimize "delete f()" on such platforms as
11876 "operator delete(~X(f()))" (rather than generating
11877 "t = f(), ~X(t), operator delete (t)"). */
11878 call = build_nop (void_type_node, call);
11879 }
11880 }
11881 }
11882
11883 if (processing_template_decl && call != error_mark_node)
11884 {
11885 bool cast_to_void = false;
11886
11887 if (TREE_CODE (call) == COMPOUND_EXPR)
11888 call = TREE_OPERAND (call, 1);
11889 else if (TREE_CODE (call) == NOP_EXPR)
11890 {
11891 cast_to_void = true;
11892 call = TREE_OPERAND (call, 0);
11893 }
11894 if (INDIRECT_REF_P (call))
11895 call = TREE_OPERAND (call, 0);
11896
11897 /* Prune all but the selected function from the original overload
11898 set so that we can avoid some duplicate work at instantiation time. */
11899 if (really_overloaded_fn (fns))
11900 {
11901 if (DECL_TEMPLATE_INFO (fn)
11902 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11903 {
11904 /* Use the selected template, not the specialization, so that
11905 this looks like an actual lookup result for sake of
11906 filter_memfn_lookup. */
11907
11908 if (OVL_SINGLE_P (fns))
11909 /* If the original overload set consists of a single function
11910 template, this isn't beneficial. */
11911 goto skip_prune;
11912
11913 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11914 if (template_only)
11915 fn = lookup_template_function (fn, explicit_targs);
11916 }
11917 orig_fns = copy_node (orig_fns);
11918 BASELINK_FUNCTIONS (orig_fns) = fn;
11919 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11920 }
11921
11922skip_prune:
11923 call = (build_min_non_dep_call_vec
11924 (call,
11925 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11926 orig_instance, orig_fns, NULL_TREE),
11927 orig_args));
11928 SET_EXPR_LOCATION (call, input_location);
11929 call = convert_from_reference (call);
11930 if (cast_to_void)
11931 call = build_nop (void_type_node, call);
11932 }
11933
11934 if (orig_args != NULL)
11935 release_tree_vector (orig_args);
11936
11937 return call;
11938}
11939
11940/* Returns true iff standard conversion sequence ICS1 is a proper
11941 subsequence of ICS2. */
11942
11943static bool
11944is_subseq (conversion *ics1, conversion *ics2)
11945{
11946 /* We can assume that a conversion of the same code
11947 between the same types indicates a subsequence since we only get
11948 here if the types we are converting from are the same. */
11949
11950 while (ics1->kind == ck_rvalue
11951 || ics1->kind == ck_lvalue)
11952 ics1 = next_conversion (conv: ics1);
11953
11954 while (1)
11955 {
11956 while (ics2->kind == ck_rvalue
11957 || ics2->kind == ck_lvalue)
11958 ics2 = next_conversion (conv: ics2);
11959
11960 if (ics2->kind == ck_user
11961 || !has_next (code: ics2->kind))
11962 /* At this point, ICS1 cannot be a proper subsequence of
11963 ICS2. We can get a USER_CONV when we are comparing the
11964 second standard conversion sequence of two user conversion
11965 sequences. */
11966 return false;
11967
11968 ics2 = next_conversion (conv: ics2);
11969
11970 while (ics2->kind == ck_rvalue
11971 || ics2->kind == ck_lvalue)
11972 ics2 = next_conversion (conv: ics2);
11973
11974 if (ics2->kind == ics1->kind
11975 && same_type_p (ics2->type, ics1->type)
11976 && (ics1->kind == ck_identity
11977 || same_type_p (next_conversion (ics2)->type,
11978 next_conversion (ics1)->type)))
11979 return true;
11980 }
11981}
11982
11983/* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11984 be any _TYPE nodes. */
11985
11986bool
11987is_properly_derived_from (tree derived, tree base)
11988{
11989 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11990 return false;
11991
11992 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11993 considers every class derived from itself. */
11994 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11995 && DERIVED_FROM_P (base, derived));
11996}
11997
11998/* We build the ICS for an implicit object parameter as a pointer
11999 conversion sequence. However, such a sequence should be compared
12000 as if it were a reference conversion sequence. If ICS is the
12001 implicit conversion sequence for an implicit object parameter,
12002 modify it accordingly. */
12003
12004static void
12005maybe_handle_implicit_object (conversion **ics)
12006{
12007 if ((*ics)->this_p)
12008 {
12009 /* [over.match.funcs]
12010
12011 For non-static member functions, the type of the
12012 implicit object parameter is "reference to cv X"
12013 where X is the class of which the function is a
12014 member and cv is the cv-qualification on the member
12015 function declaration. */
12016 conversion *t = *ics;
12017 tree reference_type;
12018
12019 /* The `this' parameter is a pointer to a class type. Make the
12020 implicit conversion talk about a reference to that same class
12021 type. */
12022 reference_type = TREE_TYPE (t->type);
12023 reference_type = build_reference_type (reference_type);
12024
12025 if (t->kind == ck_qual)
12026 t = next_conversion (conv: t);
12027 if (t->kind == ck_ptr)
12028 t = next_conversion (conv: t);
12029 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
12030 t = direct_reference_binding (type: reference_type, conv: t);
12031 t->this_p = 1;
12032 t->rvaluedness_matches_p = 0;
12033 *ics = t;
12034 }
12035}
12036
12037/* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
12038 and return the initial reference binding conversion. Otherwise,
12039 leave *ICS unchanged and return NULL. */
12040
12041static conversion *
12042maybe_handle_ref_bind (conversion **ics)
12043{
12044 if ((*ics)->kind == ck_ref_bind)
12045 {
12046 conversion *old_ics = *ics;
12047 *ics = next_conversion (conv: old_ics);
12048 (*ics)->user_conv_p = old_ics->user_conv_p;
12049 return old_ics;
12050 }
12051
12052 return NULL;
12053}
12054
12055/* Get the expression at the beginning of the conversion chain C. */
12056
12057static tree
12058conv_get_original_expr (conversion *c)
12059{
12060 for (; c; c = next_conversion (conv: c))
12061 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
12062 return c->u.expr;
12063 return NULL_TREE;
12064}
12065
12066/* Return a tree representing the number of elements initialized by the
12067 list-initialization C. The caller must check that C converts to an
12068 array type. */
12069
12070static tree
12071nelts_initialized_by_list_init (conversion *c)
12072{
12073 /* If the array we're converting to has a dimension, we'll use that. */
12074 if (TYPE_DOMAIN (c->type))
12075 return array_type_nelts_top (c->type);
12076 else
12077 {
12078 /* Otherwise, we look at how many elements the constructor we're
12079 initializing from has. */
12080 tree ctor = conv_get_original_expr (c);
12081 return size_int (CONSTRUCTOR_NELTS (ctor));
12082 }
12083}
12084
12085/* True iff C is a conversion that binds a reference or a pointer to
12086 an array of unknown bound. */
12087
12088static inline bool
12089conv_binds_to_array_of_unknown_bound (conversion *c)
12090{
12091 /* ck_ref_bind won't have the reference stripped. */
12092 tree type = non_reference (c->type);
12093 /* ck_qual won't have the pointer stripped. */
12094 type = strip_pointer_operator (type);
12095 return (TREE_CODE (type) == ARRAY_TYPE
12096 && TYPE_DOMAIN (type) == NULL_TREE);
12097}
12098
12099/* Compare two implicit conversion sequences according to the rules set out in
12100 [over.ics.rank]. Return values:
12101
12102 1: ics1 is better than ics2
12103 -1: ics2 is better than ics1
12104 0: ics1 and ics2 are indistinguishable */
12105
12106static int
12107compare_ics (conversion *ics1, conversion *ics2)
12108{
12109 tree from_type1;
12110 tree from_type2;
12111 tree to_type1;
12112 tree to_type2;
12113 tree deref_from_type1 = NULL_TREE;
12114 tree deref_from_type2 = NULL_TREE;
12115 tree deref_to_type1 = NULL_TREE;
12116 tree deref_to_type2 = NULL_TREE;
12117 conversion_rank rank1, rank2;
12118
12119 /* REF_BINDING is nonzero if the result of the conversion sequence
12120 is a reference type. In that case REF_CONV is the reference
12121 binding conversion. */
12122 conversion *ref_conv1;
12123 conversion *ref_conv2;
12124
12125 /* Compare badness before stripping the reference conversion. */
12126 if (ics1->bad_p > ics2->bad_p)
12127 return -1;
12128 else if (ics1->bad_p < ics2->bad_p)
12129 return 1;
12130
12131 /* Handle implicit object parameters. */
12132 maybe_handle_implicit_object (ics: &ics1);
12133 maybe_handle_implicit_object (ics: &ics2);
12134
12135 /* Handle reference parameters. */
12136 ref_conv1 = maybe_handle_ref_bind (ics: &ics1);
12137 ref_conv2 = maybe_handle_ref_bind (ics: &ics2);
12138
12139 /* List-initialization sequence L1 is a better conversion sequence than
12140 list-initialization sequence L2 if L1 converts to
12141 std::initializer_list<X> for some X and L2 does not. */
12142 if (ics1->kind == ck_list && ics2->kind != ck_list)
12143 return 1;
12144 if (ics2->kind == ck_list && ics1->kind != ck_list)
12145 return -1;
12146
12147 /* [over.ics.rank]
12148
12149 When comparing the basic forms of implicit conversion sequences (as
12150 defined in _over.best.ics_)
12151
12152 --a standard conversion sequence (_over.ics.scs_) is a better
12153 conversion sequence than a user-defined conversion sequence
12154 or an ellipsis conversion sequence, and
12155
12156 --a user-defined conversion sequence (_over.ics.user_) is a
12157 better conversion sequence than an ellipsis conversion sequence
12158 (_over.ics.ellipsis_). */
12159 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12160 mismatch. If both ICS are bad, we try to make a decision based on
12161 what would have happened if they'd been good. This is not an
12162 extension, we'll still give an error when we build up the call; this
12163 just helps us give a more helpful error message. */
12164 rank1 = BAD_CONVERSION_RANK (ics1);
12165 rank2 = BAD_CONVERSION_RANK (ics2);
12166
12167 if (rank1 > rank2)
12168 return -1;
12169 else if (rank1 < rank2)
12170 return 1;
12171
12172 if (ics1->ellipsis_p)
12173 /* Both conversions are ellipsis conversions. */
12174 return 0;
12175
12176 /* User-defined conversion sequence U1 is a better conversion sequence
12177 than another user-defined conversion sequence U2 if they contain the
12178 same user-defined conversion operator or constructor and if the sec-
12179 ond standard conversion sequence of U1 is better than the second
12180 standard conversion sequence of U2. */
12181
12182 /* Handle list-conversion with the same code even though it isn't always
12183 ranked as a user-defined conversion and it doesn't have a second
12184 standard conversion sequence; it will still have the desired effect.
12185 Specifically, we need to do the reference binding comparison at the
12186 end of this function. */
12187
12188 if (ics1->user_conv_p || ics1->kind == ck_list
12189 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12190 {
12191 conversion *t1 = strip_standard_conversion (conv: ics1);
12192 conversion *t2 = strip_standard_conversion (conv: ics2);
12193
12194 if (!t1 || !t2 || t1->kind != t2->kind)
12195 return 0;
12196 else if (t1->kind == ck_user)
12197 {
12198 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12199 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12200 if (f1 != f2)
12201 return 0;
12202 }
12203 /* List-initialization sequence L1 is a better conversion sequence than
12204 list-initialization sequence L2 if
12205
12206 -- L1 and L2 convert to arrays of the same element type, and either
12207 the number of elements n1 initialized by L1 is less than the number
12208 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12209 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12210 P0388R4.) */
12211 else if (t1->kind == ck_aggr
12212 && TREE_CODE (t1->type) == ARRAY_TYPE
12213 && TREE_CODE (t2->type) == ARRAY_TYPE
12214 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12215 {
12216 tree n1 = nelts_initialized_by_list_init (c: t1);
12217 tree n2 = nelts_initialized_by_list_init (c: t2);
12218 if (tree_int_cst_lt (t1: n1, t2: n2))
12219 return 1;
12220 else if (tree_int_cst_lt (t1: n2, t2: n1))
12221 return -1;
12222 /* The n1 == n2 case. */
12223 bool c1 = conv_binds_to_array_of_unknown_bound (c: t1);
12224 bool c2 = conv_binds_to_array_of_unknown_bound (c: t2);
12225 if (c1 && !c2)
12226 return -1;
12227 else if (!c1 && c2)
12228 return 1;
12229 else
12230 return 0;
12231 }
12232 else
12233 {
12234 /* For ambiguous or aggregate conversions, use the target type as
12235 a proxy for the conversion function. */
12236 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12237 return 0;
12238 }
12239
12240 /* We can just fall through here, after setting up
12241 FROM_TYPE1 and FROM_TYPE2. */
12242 from_type1 = t1->type;
12243 from_type2 = t2->type;
12244 }
12245 else
12246 {
12247 conversion *t1;
12248 conversion *t2;
12249
12250 /* We're dealing with two standard conversion sequences.
12251
12252 [over.ics.rank]
12253
12254 Standard conversion sequence S1 is a better conversion
12255 sequence than standard conversion sequence S2 if
12256
12257 --S1 is a proper subsequence of S2 (comparing the conversion
12258 sequences in the canonical form defined by _over.ics.scs_,
12259 excluding any Lvalue Transformation; the identity
12260 conversion sequence is considered to be a subsequence of
12261 any non-identity conversion sequence */
12262
12263 t1 = ics1;
12264 while (t1->kind != ck_identity)
12265 t1 = next_conversion (conv: t1);
12266 from_type1 = t1->type;
12267
12268 t2 = ics2;
12269 while (t2->kind != ck_identity)
12270 t2 = next_conversion (conv: t2);
12271 from_type2 = t2->type;
12272 }
12273
12274 /* One sequence can only be a subsequence of the other if they start with
12275 the same type. They can start with different types when comparing the
12276 second standard conversion sequence in two user-defined conversion
12277 sequences. */
12278 if (same_type_p (from_type1, from_type2))
12279 {
12280 if (is_subseq (ics1, ics2))
12281 return 1;
12282 if (is_subseq (ics1: ics2, ics2: ics1))
12283 return -1;
12284 }
12285
12286 /* [over.ics.rank]
12287
12288 Or, if not that,
12289
12290 --the rank of S1 is better than the rank of S2 (by the rules
12291 defined below):
12292
12293 Standard conversion sequences are ordered by their ranks: an Exact
12294 Match is a better conversion than a Promotion, which is a better
12295 conversion than a Conversion.
12296
12297 Two conversion sequences with the same rank are indistinguishable
12298 unless one of the following rules applies:
12299
12300 --A conversion that does not a convert a pointer, pointer to member,
12301 or std::nullptr_t to bool is better than one that does.
12302
12303 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12304 so that we do not have to check it explicitly. */
12305 if (ics1->rank < ics2->rank)
12306 return 1;
12307 else if (ics2->rank < ics1->rank)
12308 return -1;
12309
12310 to_type1 = ics1->type;
12311 to_type2 = ics2->type;
12312
12313 /* A conversion from scalar arithmetic type to complex is worse than a
12314 conversion between scalar arithmetic types. */
12315 if (same_type_p (from_type1, from_type2)
12316 && ARITHMETIC_TYPE_P (from_type1)
12317 && ARITHMETIC_TYPE_P (to_type1)
12318 && ARITHMETIC_TYPE_P (to_type2)
12319 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12320 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12321 {
12322 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12323 return -1;
12324 else
12325 return 1;
12326 }
12327
12328 {
12329 /* A conversion in either direction between floating-point type FP1 and
12330 floating-point type FP2 is better than a conversion in the same
12331 direction between FP1 and arithmetic type T3 if
12332 - the floating-point conversion rank of FP1 is equal to the rank of
12333 FP2, and
12334 - T3 is not a floating-point type, or T3 is a floating-point type
12335 whose rank is not equal to the rank of FP1, or the floating-point
12336 conversion subrank of FP2 is greater than the subrank of T3. */
12337 tree fp1 = from_type1;
12338 tree fp2 = to_type1;
12339 tree fp3 = from_type2;
12340 tree t3 = to_type2;
12341 int ret = 1;
12342 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12343 {
12344 std::swap (a&: fp1, b&: fp2);
12345 std::swap (a&: fp3, b&: t3);
12346 }
12347 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12348 && SCALAR_FLOAT_TYPE_P (fp1)
12349 /* Only apply this rule if at least one of the 3 types is
12350 extended floating-point type, otherwise keep them as
12351 before for compatibility reasons with types like __float128.
12352 float, double and long double alone have different conversion
12353 ranks and so when just those 3 types are involved, this
12354 rule doesn't trigger. */
12355 && (extended_float_type_p (type: fp1)
12356 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (type: fp2))
12357 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (type: t3))))
12358 {
12359 if (TREE_CODE (fp2) != REAL_TYPE)
12360 {
12361 ret = -ret;
12362 std::swap (a&: fp2, b&: t3);
12363 }
12364 if (SCALAR_FLOAT_TYPE_P (fp2))
12365 {
12366 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12367 if the conversion rank is equal (-1 or 1 if the subrank is
12368 different). */
12369 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12370 fp2),
12371 -1, 1))
12372 {
12373 /* Conversion ranks of FP1 and FP2 are equal. */
12374 if (TREE_CODE (t3) != REAL_TYPE
12375 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12376 (fp1, t3),
12377 -1, 1))
12378 /* FP1 <-> FP2 conversion is better. */
12379 return ret;
12380 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12381 gcc_assert (IN_RANGE (c, -1, 1));
12382 if (c == 1)
12383 /* Conversion subrank of FP2 is greater than subrank of T3.
12384 FP1 <-> FP2 conversion is better. */
12385 return ret;
12386 else if (c == -1)
12387 /* Conversion subrank of FP2 is less than subrank of T3.
12388 FP1 <-> T3 conversion is better. */
12389 return -ret;
12390 }
12391 else if (SCALAR_FLOAT_TYPE_P (t3)
12392 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12393 (fp1, t3),
12394 -1, 1))
12395 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12396 ranks of FP1 and T3 are equal.
12397 FP1 <-> T3 conversion is better. */
12398 return -ret;
12399 }
12400 }
12401 }
12402
12403 if (TYPE_PTR_P (from_type1)
12404 && TYPE_PTR_P (from_type2)
12405 && TYPE_PTR_P (to_type1)
12406 && TYPE_PTR_P (to_type2))
12407 {
12408 deref_from_type1 = TREE_TYPE (from_type1);
12409 deref_from_type2 = TREE_TYPE (from_type2);
12410 deref_to_type1 = TREE_TYPE (to_type1);
12411 deref_to_type2 = TREE_TYPE (to_type2);
12412 }
12413 /* The rules for pointers to members A::* are just like the rules
12414 for pointers A*, except opposite: if B is derived from A then
12415 A::* converts to B::*, not vice versa. For that reason, we
12416 switch the from_ and to_ variables here. */
12417 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12418 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12419 || (TYPE_PTRMEMFUNC_P (from_type1)
12420 && TYPE_PTRMEMFUNC_P (from_type2)
12421 && TYPE_PTRMEMFUNC_P (to_type1)
12422 && TYPE_PTRMEMFUNC_P (to_type2)))
12423 {
12424 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12425 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12426 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12427 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12428 }
12429
12430 if (deref_from_type1 != NULL_TREE
12431 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12432 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12433 {
12434 /* This was one of the pointer or pointer-like conversions.
12435
12436 [over.ics.rank]
12437
12438 --If class B is derived directly or indirectly from class A,
12439 conversion of B* to A* is better than conversion of B* to
12440 void*, and conversion of A* to void* is better than
12441 conversion of B* to void*. */
12442 if (VOID_TYPE_P (deref_to_type1)
12443 && VOID_TYPE_P (deref_to_type2))
12444 {
12445 if (is_properly_derived_from (derived: deref_from_type1,
12446 base: deref_from_type2))
12447 return -1;
12448 else if (is_properly_derived_from (derived: deref_from_type2,
12449 base: deref_from_type1))
12450 return 1;
12451 }
12452 else if (VOID_TYPE_P (deref_to_type1)
12453 || VOID_TYPE_P (deref_to_type2))
12454 {
12455 if (same_type_p (deref_from_type1, deref_from_type2))
12456 {
12457 if (VOID_TYPE_P (deref_to_type2))
12458 {
12459 if (is_properly_derived_from (derived: deref_from_type1,
12460 base: deref_to_type1))
12461 return 1;
12462 }
12463 /* We know that DEREF_TO_TYPE1 is `void' here. */
12464 else if (is_properly_derived_from (derived: deref_from_type1,
12465 base: deref_to_type2))
12466 return -1;
12467 }
12468 }
12469 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12470 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12471 {
12472 /* [over.ics.rank]
12473
12474 --If class B is derived directly or indirectly from class A
12475 and class C is derived directly or indirectly from B,
12476
12477 --conversion of C* to B* is better than conversion of C* to
12478 A*,
12479
12480 --conversion of B* to A* is better than conversion of C* to
12481 A* */
12482 if (same_type_p (deref_from_type1, deref_from_type2))
12483 {
12484 if (is_properly_derived_from (derived: deref_to_type1,
12485 base: deref_to_type2))
12486 return 1;
12487 else if (is_properly_derived_from (derived: deref_to_type2,
12488 base: deref_to_type1))
12489 return -1;
12490 }
12491 else if (same_type_p (deref_to_type1, deref_to_type2))
12492 {
12493 if (is_properly_derived_from (derived: deref_from_type2,
12494 base: deref_from_type1))
12495 return 1;
12496 else if (is_properly_derived_from (derived: deref_from_type1,
12497 base: deref_from_type2))
12498 return -1;
12499 }
12500 }
12501 }
12502 else if (CLASS_TYPE_P (non_reference (from_type1))
12503 && same_type_p (from_type1, from_type2))
12504 {
12505 tree from = non_reference (from_type1);
12506
12507 /* [over.ics.rank]
12508
12509 --binding of an expression of type C to a reference of type
12510 B& is better than binding an expression of type C to a
12511 reference of type A&
12512
12513 --conversion of C to B is better than conversion of C to A, */
12514 if (is_properly_derived_from (derived: from, base: to_type1)
12515 && is_properly_derived_from (derived: from, base: to_type2))
12516 {
12517 if (is_properly_derived_from (derived: to_type1, base: to_type2))
12518 return 1;
12519 else if (is_properly_derived_from (derived: to_type2, base: to_type1))
12520 return -1;
12521 }
12522 }
12523 else if (CLASS_TYPE_P (non_reference (to_type1))
12524 && same_type_p (to_type1, to_type2))
12525 {
12526 tree to = non_reference (to_type1);
12527
12528 /* [over.ics.rank]
12529
12530 --binding of an expression of type B to a reference of type
12531 A& is better than binding an expression of type C to a
12532 reference of type A&,
12533
12534 --conversion of B to A is better than conversion of C to A */
12535 if (is_properly_derived_from (derived: from_type1, base: to)
12536 && is_properly_derived_from (derived: from_type2, base: to))
12537 {
12538 if (is_properly_derived_from (derived: from_type2, base: from_type1))
12539 return 1;
12540 else if (is_properly_derived_from (derived: from_type1, base: from_type2))
12541 return -1;
12542 }
12543 }
12544
12545 /* [over.ics.rank]
12546
12547 --S1 and S2 differ only in their qualification conversion and yield
12548 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12549 qualification signature of type T1 is a proper subset of the cv-
12550 qualification signature of type T2 */
12551 if (ics1->kind == ck_qual
12552 && ics2->kind == ck_qual
12553 && same_type_p (from_type1, from_type2))
12554 {
12555 int result = comp_cv_qual_signature (to_type1, to_type2);
12556 if (result != 0)
12557 return result;
12558 }
12559
12560 /* [over.ics.rank]
12561
12562 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12563 to an implicit object parameter of a non-static member function
12564 declared without a ref-qualifier, and either S1 binds an lvalue
12565 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12566 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12567 draft standard, 13.3.3.2)
12568
12569 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12570 types to which the references refer are the same type except for
12571 top-level cv-qualifiers, and the type to which the reference
12572 initialized by S2 refers is more cv-qualified than the type to
12573 which the reference initialized by S1 refers.
12574
12575 DR 1328 [over.match.best]: the context is an initialization by
12576 conversion function for direct reference binding (13.3.1.6) of a
12577 reference to function type, the return type of F1 is the same kind of
12578 reference (i.e. lvalue or rvalue) as the reference being initialized,
12579 and the return type of F2 is not. */
12580
12581 if (ref_conv1 && ref_conv2)
12582 {
12583 if (!ref_conv1->this_p && !ref_conv2->this_p
12584 && (ref_conv1->rvaluedness_matches_p
12585 != ref_conv2->rvaluedness_matches_p)
12586 && (same_type_p (ref_conv1->type, ref_conv2->type)
12587 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12588 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12589 {
12590 if (ref_conv1->bad_p
12591 && !same_type_p (TREE_TYPE (ref_conv1->type),
12592 TREE_TYPE (ref_conv2->type)))
12593 /* Don't prefer a bad conversion that drops cv-quals to a bad
12594 conversion with the wrong rvalueness. */
12595 return 0;
12596 return (ref_conv1->rvaluedness_matches_p
12597 - ref_conv2->rvaluedness_matches_p);
12598 }
12599
12600 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12601 {
12602 /* Per P0388R4:
12603
12604 void f (int(&)[]), // (1)
12605 f (int(&)[1]), // (2)
12606 f (int*); // (3)
12607
12608 (2) is better than (1), but (3) should be equal to (1) and to
12609 (2). For that reason we don't use ck_qual for (1) which would
12610 give it the cr_exact rank while (3) remains ck_identity.
12611 Therefore we compare (1) and (2) here. For (1) we'll have
12612
12613 ck_ref_bind <- ck_identity
12614 int[] & int[1]
12615
12616 so to handle this we must look at ref_conv. */
12617 bool c1 = conv_binds_to_array_of_unknown_bound (c: ref_conv1);
12618 bool c2 = conv_binds_to_array_of_unknown_bound (c: ref_conv2);
12619 if (c1 && !c2)
12620 return -1;
12621 else if (!c1 && c2)
12622 return 1;
12623
12624 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12625 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12626 if (ref_conv1->bad_p)
12627 {
12628 /* Prefer the one that drops fewer cv-quals. */
12629 tree ftype = next_conversion (conv: ref_conv1)->type;
12630 int fquals = cp_type_quals (ftype);
12631 q1 ^= fquals;
12632 q2 ^= fquals;
12633 }
12634 return comp_cv_qualification (q2, q1);
12635 }
12636 }
12637
12638 /* [over.ics.rank]
12639
12640 Per CWG 1601:
12641 -- A conversion that promotes an enumeration whose underlying type
12642 is fixed to its underlying type is better than one that promotes to
12643 the promoted underlying type, if the two are different. */
12644 if (ics1->rank == cr_promotion
12645 && ics2->rank == cr_promotion
12646 && UNSCOPED_ENUM_P (from_type1)
12647 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12648 && same_type_p (from_type1, from_type2))
12649 {
12650 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12651 tree prom = type_promotes_to (from_type1);
12652 if (!same_type_p (utype, prom))
12653 {
12654 if (same_type_p (to_type1, utype)
12655 && same_type_p (to_type2, prom))
12656 return 1;
12657 else if (same_type_p (to_type2, utype)
12658 && same_type_p (to_type1, prom))
12659 return -1;
12660 }
12661 }
12662
12663 /* Neither conversion sequence is better than the other. */
12664 return 0;
12665}
12666
12667/* The source type for this standard conversion sequence. */
12668
12669static tree
12670source_type (conversion *t)
12671{
12672 return strip_standard_conversion (conv: t)->type;
12673}
12674
12675/* Note a warning about preferring WINNER to LOSER. We do this by storing
12676 a pointer to LOSER and re-running joust to produce the warning if WINNER
12677 is actually used. */
12678
12679static void
12680add_warning (struct z_candidate *winner, struct z_candidate *loser)
12681{
12682 candidate_warning *cw = (candidate_warning *)
12683 conversion_obstack_alloc (n: sizeof (candidate_warning));
12684 cw->loser = loser;
12685 cw->next = winner->warnings;
12686 winner->warnings = cw;
12687}
12688
12689/* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12690 prvalue returned from a conversion function, return true. Otherwise, return
12691 false. */
12692
12693static bool
12694joust_maybe_elide_copy (z_candidate *cand)
12695{
12696 tree fn = cand->fn;
12697 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12698 return false;
12699 conversion *conv = cand->convs[0];
12700 if (conv->kind == ck_ambig)
12701 return false;
12702 gcc_checking_assert (conv->kind == ck_ref_bind);
12703 conv = next_conversion (conv);
12704 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12705 {
12706 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12707 (conv->type, DECL_CONTEXT (fn)));
12708 z_candidate *uc = conv->cand;
12709 if (DECL_CONV_FN_P (uc->fn))
12710 return true;
12711 }
12712 return false;
12713}
12714
12715/* Return the class that CAND's implicit object parameter refers to. */
12716
12717static tree
12718class_of_implicit_object (z_candidate *cand)
12719{
12720 if (!DECL_IOBJ_MEMBER_FUNCTION_P (cand->fn))
12721 return NULL_TREE;
12722
12723 /* "For conversion functions that are implicit object member functions,
12724 the function is considered to be a member of the class of the implied
12725 object argument for the purpose of defining the type of the implicit
12726 object parameter." */
12727 if (DECL_CONV_FN_P (cand->fn))
12728 return TYPE_MAIN_VARIANT (TREE_TYPE (cand->first_arg));
12729
12730 /* "For non-conversion functions that are implicit object member
12731 functions nominated by a using-declaration in a derived class, the
12732 function is considered to be a member of the derived class for the
12733 purpose of defining the type of the implicit object parameter."
12734
12735 That derived class is reflected in the conversion_path binfo. */
12736 return BINFO_TYPE (cand->conversion_path);
12737}
12738
12739/* True if candidates C1 and C2 have corresponding object parameters per
12740 [basic.scope.scope]. */
12741
12742static bool
12743object_parms_correspond (z_candidate *c1, tree fn1, z_candidate *c2, tree fn2)
12744{
12745 tree context = class_of_implicit_object (cand: c1);
12746 tree ctx2 = class_of_implicit_object (cand: c2);
12747 if (!ctx2)
12748 /* Leave context as is. */;
12749 else if (!context)
12750 context = ctx2;
12751 else if (context != ctx2)
12752 /* This can't happen for normal function calls, since it means finding
12753 functions in multiple bases which would fail with an ambiguous lookup,
12754 but it can occur with reversed operators. */
12755 return false;
12756
12757 return object_parms_correspond (fn1, fn2, context);
12758}
12759
12760/* Return whether the first parameter of C1 matches the second parameter
12761 of C2. */
12762
12763static bool
12764reversed_match (z_candidate *c1, z_candidate *c2)
12765{
12766 tree fn1 = c1->fn;
12767 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (c2->fn));
12768 tree parm2 = TREE_VALUE (TREE_CHAIN (parms2));
12769 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn1))
12770 {
12771 tree ctx = class_of_implicit_object (cand: c1);
12772 return iobj_parm_corresponds_to (fn1, parm2, ctx);
12773 }
12774 else
12775 {
12776 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12777 tree parm1 = TREE_VALUE (parms1);
12778 return same_type_p (parm1, parm2);
12779 }
12780}
12781
12782/* True if the defining declarations of the two candidates have equivalent
12783 parameters. MATCH_KIND controls whether we're trying to compare the
12784 original declarations (for a warning) or the actual candidates. */
12785
12786enum class pmatch { original, current };
12787
12788static bool
12789cand_parms_match (z_candidate *c1, z_candidate *c2, pmatch match_kind)
12790{
12791 tree fn1 = c1->fn;
12792 tree fn2 = c2->fn;
12793 bool reversed = (match_kind == pmatch::current
12794 && c1->reversed () != c2->reversed ());
12795 if (fn1 == fn2 && !reversed)
12796 return true;
12797 if (identifier_p (t: fn1) || identifier_p (t: fn2))
12798 return false;
12799 if (match_kind == pmatch::original)
12800 {
12801 /* We don't look at c1->template_decl because that's only set for
12802 primary templates, not e.g. non-template member functions of
12803 class templates. */
12804 tree t1 = most_general_template (fn1);
12805 tree t2 = most_general_template (fn2);
12806 if (t1 || t2)
12807 {
12808 if (!t1 || !t2)
12809 return false;
12810 if (t1 == t2)
12811 return true;
12812 fn1 = DECL_TEMPLATE_RESULT (t1);
12813 fn2 = DECL_TEMPLATE_RESULT (t2);
12814 }
12815 }
12816
12817 else if (reversed)
12818 return (reversed_match (c1, c2)
12819 && reversed_match (c1: c2, c2: c1));
12820
12821 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12822 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12823
12824 if (!(DECL_FUNCTION_MEMBER_P (fn1)
12825 && DECL_FUNCTION_MEMBER_P (fn2)))
12826 /* Early escape. */;
12827
12828 /* CWG2789 is not adequate, it should specify corresponding object
12829 parameters, not same typed object parameters. */
12830 else if (!object_parms_correspond (c1, fn1, c2, fn2))
12831 return false;
12832 else
12833 {
12834 /* We just compared the object parameters, if they don't correspond
12835 we already returned false. */
12836 auto skip_parms = [] (tree fn, tree parms)
12837 {
12838 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
12839 return TREE_CHAIN (parms);
12840 else
12841 return skip_artificial_parms_for (fn, parms);
12842 };
12843 parms1 = skip_parms (fn1, parms1);
12844 parms2 = skip_parms (fn2, parms2);
12845 }
12846 return compparms (parms1, parms2);
12847}
12848
12849/* True iff FN is a copy or move constructor or assignment operator. */
12850
12851static bool
12852sfk_copy_or_move (tree fn)
12853{
12854 if (TREE_CODE (fn) != FUNCTION_DECL)
12855 return false;
12856 special_function_kind sfk = special_function_p (fn);
12857 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
12858}
12859
12860/* Compare two candidates for overloading as described in
12861 [over.match.best]. Return values:
12862
12863 1: cand1 is better than cand2
12864 -1: cand2 is better than cand1
12865 0: cand1 and cand2 are indistinguishable */
12866
12867static int
12868joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12869 tsubst_flags_t complain)
12870{
12871 int winner = 0;
12872 int off1 = 0, off2 = 0;
12873 size_t i;
12874 size_t len;
12875
12876 /* Candidates that involve bad conversions are always worse than those
12877 that don't. */
12878 if (cand1->viable > cand2->viable)
12879 return 1;
12880 if (cand1->viable < cand2->viable)
12881 return -1;
12882
12883 /* If we have two pseudo-candidates for conversions to the same type,
12884 or two candidates for the same function, arbitrarily pick one. */
12885 if (cand1->fn == cand2->fn
12886 && cand1->reversed () == cand2->reversed ()
12887 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12888 return 1;
12889
12890 /* Prefer a non-deleted function over an implicitly deleted move
12891 constructor or assignment operator. This differs slightly from the
12892 wording for issue 1402 (which says the move op is ignored by overload
12893 resolution), but this way produces better error messages. */
12894 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12895 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12896 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12897 {
12898 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12899 && move_fn_p (cand1->fn))
12900 return -1;
12901 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12902 && move_fn_p (cand2->fn))
12903 return 1;
12904 }
12905
12906 /* a viable function F1
12907 is defined to be a better function than another viable function F2 if
12908 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12909 ICSi(F2), and then */
12910
12911 /* for some argument j, ICSj(F1) is a better conversion sequence than
12912 ICSj(F2) */
12913
12914 /* For comparing static and non-static member functions, we ignore
12915 the implicit object parameter of the non-static function. The
12916 standard says to pretend that the static function has an object
12917 parm, but that won't work with operator overloading. */
12918 len = cand1->num_convs;
12919 if (len != cand2->num_convs)
12920 {
12921 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12922 && DECL_STATIC_FUNCTION_P (cand1->fn));
12923 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12924 && DECL_STATIC_FUNCTION_P (cand2->fn));
12925
12926 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12927 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12928 && DECL_CONSTRUCTOR_P (cand1->fn)
12929 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12930 /* We're comparing a near-match list constructor and a near-match
12931 non-list constructor. Just treat them as unordered. */
12932 return 0;
12933
12934 gcc_assert (static_1 != static_2);
12935
12936 if (static_1)
12937 {
12938 /* C++23 [over.best.ics.general] says:
12939 When the parameter is the implicit object parameter of a static
12940 member function, the implicit conversion sequence is a standard
12941 conversion sequence that is neither better nor worse than any
12942 other standard conversion sequence. */
12943 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12944 winner = 1;
12945 off2 = 1;
12946 }
12947 else
12948 {
12949 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12950 winner = -1;
12951 off1 = 1;
12952 --len;
12953 }
12954 }
12955
12956 for (i = 0; i < len; ++i)
12957 {
12958 conversion *t1 = cand1->convs[i + off1];
12959 conversion *t2 = cand2->convs[i + off2];
12960 int comp = compare_ics (ics1: t1, ics2: t2);
12961
12962 if (comp != 0)
12963 {
12964 if ((complain & tf_warning)
12965 && warn_sign_promo
12966 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12967 == cr_std + cr_promotion)
12968 && t1->kind == ck_std
12969 && t2->kind == ck_std
12970 && TREE_CODE (t1->type) == INTEGER_TYPE
12971 && TREE_CODE (t2->type) == INTEGER_TYPE
12972 && (TYPE_PRECISION (t1->type)
12973 == TYPE_PRECISION (t2->type))
12974 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12975 || (TREE_CODE (next_conversion (t1)->type)
12976 == ENUMERAL_TYPE)))
12977 {
12978 tree type = next_conversion (conv: t1)->type;
12979 tree type1, type2;
12980 struct z_candidate *w, *l;
12981 if (comp > 0)
12982 type1 = t1->type, type2 = t2->type,
12983 w = cand1, l = cand2;
12984 else
12985 type1 = t2->type, type2 = t1->type,
12986 w = cand2, l = cand1;
12987
12988 if (warn)
12989 {
12990 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12991 type, type1, type2);
12992 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12993 }
12994 else
12995 add_warning (winner: w, loser: l);
12996 }
12997
12998 if (winner && comp != winner)
12999 {
13000 /* Ambiguity between normal and reversed comparison operators
13001 with the same parameter types. P2468 decided not to go with
13002 this approach to resolving the ambiguity, so pedwarn. */
13003 if ((complain & tf_warning_or_error)
13004 && (cand1->reversed () != cand2->reversed ())
13005 && cand_parms_match (c1: cand1, c2: cand2, match_kind: pmatch::original))
13006 {
13007 struct z_candidate *w, *l;
13008 if (cand2->reversed ())
13009 winner = 1, w = cand1, l = cand2;
13010 else
13011 winner = -1, w = cand2, l = cand1;
13012 if (warn)
13013 {
13014 auto_diagnostic_group d;
13015 if (pedwarn (input_location, 0,
13016 "C++20 says that these are ambiguous, "
13017 "even though the second is reversed:"))
13018 {
13019 print_z_candidate (loc: input_location,
13020 N_("candidate 1:"), candidate: w);
13021 print_z_candidate (loc: input_location,
13022 N_("candidate 2:"), candidate: l);
13023 if (w->fn == l->fn
13024 && DECL_IOBJ_MEMBER_FUNCTION_P (w->fn)
13025 && (type_memfn_quals (TREE_TYPE (w->fn))
13026 & TYPE_QUAL_CONST) == 0)
13027 {
13028 /* Suggest adding const to
13029 struct A { bool operator==(const A&); }; */
13030 tree parmtype
13031 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
13032 parmtype = TREE_VALUE (parmtype);
13033 if (TYPE_REF_P (parmtype)
13034 && TYPE_READONLY (TREE_TYPE (parmtype))
13035 && (same_type_ignoring_top_level_qualifiers_p
13036 (TREE_TYPE (parmtype),
13037 DECL_CONTEXT (w->fn))))
13038 inform (DECL_SOURCE_LOCATION (w->fn),
13039 "try making the operator a %<const%> "
13040 "member function");
13041 }
13042 }
13043 }
13044 else
13045 add_warning (winner: w, loser: l);
13046 return winner;
13047 }
13048
13049 winner = 0;
13050 goto tweak;
13051 }
13052 winner = comp;
13053 }
13054 }
13055
13056 /* warn about confusing overload resolution for user-defined conversions,
13057 either between a constructor and a conversion op, or between two
13058 conversion ops. */
13059 if ((complain & tf_warning)
13060 /* In C++17, the constructor might have been elided, which means that
13061 an originally null ->second_conv could become non-null. */
13062 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
13063 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
13064 && winner != compare_ics (ics1: cand1->second_conv, ics2: cand2->second_conv))
13065 {
13066 struct z_candidate *w, *l;
13067 bool give_warning = false;
13068
13069 if (winner == 1)
13070 w = cand1, l = cand2;
13071 else
13072 w = cand2, l = cand1;
13073
13074 /* We don't want to complain about `X::operator T1 ()'
13075 beating `X::operator T2 () const', when T2 is a no less
13076 cv-qualified version of T1. */
13077 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
13078 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
13079 {
13080 tree t = TREE_TYPE (TREE_TYPE (l->fn));
13081 tree f = TREE_TYPE (TREE_TYPE (w->fn));
13082
13083 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
13084 {
13085 t = TREE_TYPE (t);
13086 f = TREE_TYPE (f);
13087 }
13088 if (!comp_ptr_ttypes (t, f))
13089 give_warning = true;
13090 }
13091 else
13092 give_warning = true;
13093
13094 if (!give_warning)
13095 /*NOP*/;
13096 else if (warn)
13097 {
13098 tree source = source_type (t: w->convs[0]);
13099 if (INDIRECT_TYPE_P (source))
13100 source = TREE_TYPE (source);
13101 auto_diagnostic_group d;
13102 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
13103 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
13104 source, w->second_conv->type))
13105 {
13106 inform (input_location, " because conversion sequence "
13107 "for the argument is better");
13108 }
13109 }
13110 else
13111 add_warning (winner: w, loser: l);
13112 }
13113
13114 if (winner)
13115 return winner;
13116
13117 /* DR 495 moved this tiebreaker above the template ones. */
13118 /* or, if not that,
13119 the context is an initialization by user-defined conversion (see
13120 _dcl.init_ and _over.match.user_) and the standard conversion
13121 sequence from the return type of F1 to the destination type (i.e.,
13122 the type of the entity being initialized) is a better conversion
13123 sequence than the standard conversion sequence from the return type
13124 of F2 to the destination type. */
13125
13126 if (cand1->second_conv)
13127 {
13128 winner = compare_ics (ics1: cand1->second_conv, ics2: cand2->second_conv);
13129 if (winner)
13130 return winner;
13131 }
13132
13133 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
13134 explicit conversion (due to list-initialization) is worse. */
13135 {
13136 z_candidate *sp = nullptr;
13137 if (sfk_copy_or_move (fn: cand1->fn))
13138 sp = cand1;
13139 if (sfk_copy_or_move (fn: cand2->fn))
13140 sp = sp ? nullptr : cand2;
13141 if (sp)
13142 {
13143 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
13144 if (conv->user_conv_p)
13145 for (; conv; conv = next_conversion (conv))
13146 if (conv->kind == ck_user
13147 && DECL_P (conv->cand->fn)
13148 && DECL_NONCONVERTING_P (conv->cand->fn))
13149 return (sp == cand1) ? -1 : 1;
13150 }
13151 }
13152
13153 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
13154 The standard currently says that only constructors are candidates, but if
13155 one copies a prvalue returned by a conversion function we prefer that.
13156
13157 Clang does something similar, as discussed at
13158 http://lists.isocpp.org/core/2017/10/3166.php
13159 http://lists.isocpp.org/core/2019/03/5721.php */
13160 if (len == 1 && cxx_dialect >= cxx17
13161 && DECL_P (cand1->fn)
13162 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
13163 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
13164 {
13165 bool elided1 = joust_maybe_elide_copy (cand: cand1);
13166 bool elided2 = joust_maybe_elide_copy (cand: cand2);
13167 winner = elided1 - elided2;
13168 if (winner)
13169 return winner;
13170 }
13171
13172 /* or, if not that,
13173 F1 is a non-template function and F2 is a template function
13174 specialization. */
13175
13176 if (!cand1->template_decl && cand2->template_decl)
13177 return 1;
13178 else if (cand1->template_decl && !cand2->template_decl)
13179 return -1;
13180
13181 /* or, if not that,
13182 F1 and F2 are template functions and the function template for F1 is
13183 more specialized than the template for F2 according to the partial
13184 ordering rules. */
13185
13186 if (cand1->template_decl && cand2->template_decl)
13187 {
13188 winner = more_specialized_fn
13189 (TI_TEMPLATE (cand1->template_decl),
13190 TI_TEMPLATE (cand2->template_decl),
13191 /* [temp.func.order]: The presence of unused ellipsis and default
13192 arguments has no effect on the partial ordering of function
13193 templates. add_function_candidate() will not have
13194 counted the "this" argument for constructors. */
13195 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
13196 if (winner)
13197 return winner;
13198 }
13199
13200 /* Concepts: F1 and F2 are non-template functions with the same
13201 parameter-type-lists, and F1 is more constrained than F2 according to the
13202 partial ordering of constraints described in 13.5.4. */
13203
13204 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
13205 && !cand1->template_decl && !cand2->template_decl
13206 && cand_parms_match (c1: cand1, c2: cand2, match_kind: pmatch::current))
13207 {
13208 winner = more_constrained (cand1->fn, cand2->fn);
13209 if (winner)
13210 return winner;
13211 }
13212
13213 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
13214 rewritten candidates, and F2 is a synthesized candidate with reversed
13215 order of parameters and F1 is not. */
13216 if (cand1->rewritten ())
13217 {
13218 if (!cand2->rewritten ())
13219 return -1;
13220 if (!cand1->reversed () && cand2->reversed ())
13221 return 1;
13222 if (cand1->reversed () && !cand2->reversed ())
13223 return -1;
13224 }
13225 else if (cand2->rewritten ())
13226 return 1;
13227
13228 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
13229 if (deduction_guide_p (cand1->fn))
13230 {
13231 gcc_assert (deduction_guide_p (cand2->fn));
13232 /* We distinguish between candidates from an explicit deduction guide and
13233 candidates built from a constructor based on DECL_ARTIFICIAL. */
13234 int art1 = DECL_ARTIFICIAL (cand1->fn);
13235 int art2 = DECL_ARTIFICIAL (cand2->fn);
13236 if (art1 != art2)
13237 return art2 - art1;
13238
13239 if (art1)
13240 {
13241 /* Prefer the special copy guide over a declared copy/move
13242 constructor. */
13243 if (copy_guide_p (cand1->fn))
13244 return 1;
13245 if (copy_guide_p (cand2->fn))
13246 return -1;
13247
13248 /* Prefer a candidate generated from a non-template constructor. */
13249 int tg1 = template_guide_p (cand1->fn);
13250 int tg2 = template_guide_p (cand2->fn);
13251 if (tg1 != tg2)
13252 return tg2 - tg1;
13253 }
13254 }
13255
13256 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
13257 for all arguments the corresponding parameters of F1 and F2 have the same
13258 type (CWG 2273/2277). */
13259 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
13260 && !DECL_CONV_FN_P (cand1->fn)
13261 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
13262 && !DECL_CONV_FN_P (cand2->fn))
13263 {
13264 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13265 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13266
13267 bool used1 = false;
13268 bool used2 = false;
13269 if (base1 == base2)
13270 /* No difference. */;
13271 else if (DERIVED_FROM_P (base1, base2))
13272 used1 = true;
13273 else if (DERIVED_FROM_P (base2, base1))
13274 used2 = true;
13275
13276 if (int diff = used2 - used1)
13277 {
13278 for (i = 0; i < len; ++i)
13279 {
13280 conversion *t1 = cand1->convs[i + off1];
13281 conversion *t2 = cand2->convs[i + off2];
13282 if (!same_type_p (t1->type, t2->type))
13283 break;
13284 }
13285 if (i == len)
13286 return diff;
13287 }
13288 }
13289
13290 /* Check whether we can discard a builtin candidate, either because we
13291 have two identical ones or matching builtin and non-builtin candidates.
13292
13293 (Pedantically in the latter case the builtin which matched the user
13294 function should not be added to the overload set, but we spot it here.
13295
13296 [over.match.oper]
13297 ... the builtin candidates include ...
13298 - do not have the same parameter type list as any non-template
13299 non-member candidate. */
13300
13301 if (identifier_p (t: cand1->fn) || identifier_p (t: cand2->fn))
13302 {
13303 for (i = 0; i < len; ++i)
13304 if (!same_type_p (cand1->convs[i]->type,
13305 cand2->convs[i]->type))
13306 break;
13307 if (i == cand1->num_convs)
13308 {
13309 if (cand1->fn == cand2->fn)
13310 /* Two built-in candidates; arbitrarily pick one. */
13311 return 1;
13312 else if (identifier_p (t: cand1->fn))
13313 /* cand1 is built-in; prefer cand2. */
13314 return -1;
13315 else
13316 /* cand2 is built-in; prefer cand1. */
13317 return 1;
13318 }
13319 }
13320
13321 /* For candidates of a multi-versioned function, make the version with
13322 the highest priority win. This version will be checked for dispatching
13323 first. If this version can be inlined into the caller, the front-end
13324 will simply make a direct call to this function. */
13325
13326 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13327 && DECL_FUNCTION_VERSIONED (cand1->fn)
13328 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13329 && DECL_FUNCTION_VERSIONED (cand2->fn))
13330 {
13331 tree f1 = TREE_TYPE (cand1->fn);
13332 tree f2 = TREE_TYPE (cand2->fn);
13333 tree p1 = TYPE_ARG_TYPES (f1);
13334 tree p2 = TYPE_ARG_TYPES (f2);
13335
13336 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13337 is possible that cand1->fn and cand2->fn are function versions but of
13338 different functions. Check types to see if they are versions of the same
13339 function. */
13340 if (compparms (p1, p2)
13341 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13342 {
13343 /* Always make the version with the higher priority, more
13344 specialized, win. */
13345 gcc_assert (targetm.compare_version_priority);
13346 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13347 return 1;
13348 else
13349 return -1;
13350 }
13351 }
13352
13353 /* If the two function declarations represent the same function (this can
13354 happen with declarations in multiple scopes and arg-dependent lookup),
13355 arbitrarily choose one. But first make sure the default args we're
13356 using match. */
13357 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13358 && equal_functions (fn1: cand1->fn, fn2: cand2->fn))
13359 {
13360 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13361 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13362
13363 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13364
13365 for (i = 0; i < len; ++i)
13366 {
13367 /* Don't crash if the fn is variadic. */
13368 if (!parms1)
13369 break;
13370 parms1 = TREE_CHAIN (parms1);
13371 parms2 = TREE_CHAIN (parms2);
13372 }
13373
13374 if (off1)
13375 parms1 = TREE_CHAIN (parms1);
13376 else if (off2)
13377 parms2 = TREE_CHAIN (parms2);
13378
13379 for (; parms1; ++i)
13380 {
13381 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13382 TREE_PURPOSE (parms2)))
13383 {
13384 if (warn)
13385 {
13386 if (complain & tf_error)
13387 {
13388 auto_diagnostic_group d;
13389 if (permerror (input_location,
13390 "default argument mismatch in "
13391 "overload resolution"))
13392 {
13393 inform (DECL_SOURCE_LOCATION (cand1->fn),
13394 " candidate 1: %q#F", cand1->fn);
13395 inform (DECL_SOURCE_LOCATION (cand2->fn),
13396 " candidate 2: %q#F", cand2->fn);
13397 }
13398 }
13399 else
13400 return 0;
13401 }
13402 else
13403 add_warning (winner: cand1, loser: cand2);
13404 break;
13405 }
13406 parms1 = TREE_CHAIN (parms1);
13407 parms2 = TREE_CHAIN (parms2);
13408 }
13409
13410 return 1;
13411 }
13412
13413tweak:
13414
13415 /* Extension: If the worst conversion for one candidate is better than the
13416 worst conversion for the other, take the first. */
13417 if (!pedantic && (complain & tf_warning_or_error))
13418 {
13419 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13420 struct z_candidate *w = 0, *l = 0;
13421
13422 for (i = 0; i < len; ++i)
13423 {
13424 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13425 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13426 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13427 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13428 }
13429 if (rank1 < rank2)
13430 winner = 1, w = cand1, l = cand2;
13431 if (rank1 > rank2)
13432 winner = -1, w = cand2, l = cand1;
13433 if (winner)
13434 {
13435 /* Don't choose a deleted function over ambiguity. */
13436 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13437 return 0;
13438 if (warn)
13439 {
13440 auto_diagnostic_group d;
13441 if (pedwarn (input_location, 0,
13442 "ISO C++ says that these are ambiguous, even "
13443 "though the worst conversion for the first is "
13444 "better than the worst conversion for the second:"))
13445 {
13446 print_z_candidate (loc: input_location, N_("candidate 1:"), candidate: w);
13447 print_z_candidate (loc: input_location, N_("candidate 2:"), candidate: l);
13448 }
13449 }
13450 else
13451 add_warning (winner: w, loser: l);
13452 return winner;
13453 }
13454 }
13455
13456 gcc_assert (!winner);
13457 return 0;
13458}
13459
13460/* Given a list of candidates for overloading, find the best one, if any.
13461 This algorithm has a worst case of O(2n) (winner is last), and a best
13462 case of O(n/2) (totally ambiguous); much better than a sorting
13463 algorithm. The candidates list is assumed to be sorted according
13464 to viability (via splice_viable). */
13465
13466static struct z_candidate *
13467tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13468{
13469 struct z_candidate **champ = &candidates, **challenger;
13470 int fate;
13471 struct z_candidate *previous_worse_champ = nullptr;
13472
13473 /* Walk through the list once, comparing each current champ to the next
13474 candidate, knocking out a candidate or two with each comparison. */
13475
13476 for (challenger = &candidates->next; *challenger && (*challenger)->viable; )
13477 {
13478 fate = joust (cand1: *champ, cand2: *challenger, warn: 0, complain);
13479 if (fate == 1)
13480 challenger = &(*challenger)->next;
13481 else if (fate == -1)
13482 {
13483 previous_worse_champ = *champ;
13484 champ = challenger;
13485 challenger = &(*challenger)->next;
13486 }
13487 else
13488 {
13489 previous_worse_champ = nullptr;
13490 champ = &(*challenger)->next;
13491 if (!*champ || !(*champ)->viable)
13492 {
13493 champ = nullptr;
13494 break;
13495 }
13496 challenger = &(*champ)->next;
13497 }
13498 }
13499
13500 /* Make sure the champ is better than all the candidates it hasn't yet
13501 been compared to. */
13502
13503 if (champ)
13504 for (challenger = &candidates;
13505 challenger != champ;
13506 challenger = &(*challenger)->next)
13507 {
13508 if (*challenger == previous_worse_champ)
13509 /* We already know this candidate is worse than the champ. */
13510 continue;
13511 fate = joust (cand1: *champ, cand2: *challenger, warn: 0, complain);
13512 if (fate != 1)
13513 {
13514 champ = nullptr;
13515 break;
13516 }
13517 }
13518
13519 if (!champ)
13520 return nullptr;
13521
13522 /* Move the champ to the front of the candidate list. */
13523
13524 if (champ != &candidates)
13525 {
13526 z_candidate *saved_champ = *champ;
13527 *champ = saved_champ->next;
13528 saved_champ->next = candidates;
13529 candidates = saved_champ;
13530 }
13531
13532 return candidates;
13533}
13534
13535/* Returns nonzero if things of type FROM can be converted to TO. */
13536
13537bool
13538can_convert (tree to, tree from, tsubst_flags_t complain)
13539{
13540 tree arg = NULL_TREE;
13541 /* implicit_conversion only considers user-defined conversions
13542 if it has an expression for the call argument list. */
13543 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13544 arg = build_stub_object (from);
13545 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13546}
13547
13548/* Returns nonzero if things of type FROM can be converted to TO with a
13549 standard conversion. */
13550
13551bool
13552can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13553{
13554 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13555}
13556
13557/* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13558
13559bool
13560can_convert_arg (tree to, tree from, tree arg, int flags,
13561 tsubst_flags_t complain)
13562{
13563 conversion *t;
13564 bool ok_p;
13565
13566 conversion_obstack_sentinel cos;
13567 /* We want to discard any access checks done for this test,
13568 as we might not be in the appropriate access context and
13569 we'll do the check again when we actually perform the
13570 conversion. */
13571 push_deferring_access_checks (dk_deferred);
13572
13573 t = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
13574 flags, complain);
13575 ok_p = (t && !t->bad_p);
13576
13577 /* Discard the access checks now. */
13578 pop_deferring_access_checks ();
13579
13580 return ok_p;
13581}
13582
13583/* Like can_convert_arg, but allows dubious conversions as well. */
13584
13585bool
13586can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13587 tsubst_flags_t complain)
13588{
13589 conversion *t;
13590
13591 conversion_obstack_sentinel cos;
13592 /* Try to perform the conversion. */
13593 t = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
13594 flags, complain);
13595
13596 return t != NULL;
13597}
13598
13599/* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13600 resolution FLAGS. */
13601
13602tree
13603build_implicit_conv_flags (tree type, tree expr, int flags)
13604{
13605 /* In a template, we are only concerned about determining the
13606 type of non-dependent expressions, so we do not have to
13607 perform the actual conversion. But for initializers, we
13608 need to be able to perform it at instantiation
13609 (or instantiate_non_dependent_expr) time. */
13610 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13611 if (!(flags & LOOKUP_ONLYCONVERTING))
13612 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13613 if (flags & LOOKUP_NO_NARROWING)
13614 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13615 return expr;
13616}
13617
13618/* Convert EXPR to TYPE. Return the converted expression.
13619
13620 Note that we allow bad conversions here because by the time we get to
13621 this point we are committed to doing the conversion. If we end up
13622 doing a bad conversion, convert_like will complain. */
13623
13624tree
13625perform_implicit_conversion_flags (tree type, tree expr,
13626 tsubst_flags_t complain, int flags)
13627{
13628 conversion *conv;
13629 location_t loc = cp_expr_loc_or_input_loc (t: expr);
13630
13631 if (TYPE_REF_P (type))
13632 expr = mark_lvalue_use (expr);
13633 else
13634 expr = mark_rvalue_use (expr);
13635
13636 if (error_operand_p (t: expr))
13637 return error_mark_node;
13638
13639 conversion_obstack_sentinel cos;
13640
13641 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
13642 /*c_cast_p=*/false,
13643 flags, complain);
13644
13645 if (!conv)
13646 {
13647 if (complain & tf_error)
13648 implicit_conversion_error (loc, type, expr);
13649 expr = error_mark_node;
13650 }
13651 else if (processing_template_decl && conv->kind != ck_identity)
13652 expr = build_implicit_conv_flags (type, expr, flags);
13653 else
13654 {
13655 /* Give a conversion call the same location as expr. */
13656 iloc_sentinel il (loc);
13657 expr = convert_like (convs: conv, expr, complain);
13658 }
13659
13660 return expr;
13661}
13662
13663tree
13664perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13665{
13666 return perform_implicit_conversion_flags (type, expr, complain,
13667 LOOKUP_IMPLICIT);
13668}
13669
13670/* Convert EXPR to TYPE (as a direct-initialization) if that is
13671 permitted. If the conversion is valid, the converted expression is
13672 returned. Otherwise, NULL_TREE is returned, except in the case
13673 that TYPE is a class type; in that case, an error is issued. If
13674 C_CAST_P is true, then this direct-initialization is taking
13675 place as part of a static_cast being attempted as part of a C-style
13676 cast. */
13677
13678tree
13679perform_direct_initialization_if_possible (tree type,
13680 tree expr,
13681 bool c_cast_p,
13682 tsubst_flags_t complain)
13683{
13684 conversion *conv;
13685
13686 if (type == error_mark_node || error_operand_p (t: expr))
13687 return error_mark_node;
13688 /* [dcl.init]
13689
13690 If the destination type is a (possibly cv-qualified) class type:
13691
13692 -- If the initialization is direct-initialization ...,
13693 constructors are considered.
13694
13695 -- If overload resolution is successful, the selected constructor
13696 is called to initialize the object, with the initializer expression
13697 or expression-list as its argument(s).
13698
13699 -- Otherwise, if no constructor is viable, the destination type is
13700 a (possibly cv-qualified) aggregate class A, and the initializer is
13701 a parenthesized expression-list, the object is initialized as
13702 follows... */
13703 if (CLASS_TYPE_P (type))
13704 {
13705 releasing_vec args (make_tree_vector_single (expr));
13706 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13707 args: &args, binfo: type, LOOKUP_NORMAL, complain);
13708 return build_cplus_new (type, expr, complain);
13709 }
13710
13711 conversion_obstack_sentinel cos;
13712
13713 conv = implicit_conversion (to: type, TREE_TYPE (expr), expr,
13714 c_cast_p,
13715 LOOKUP_NORMAL, complain);
13716 if (!conv || conv->bad_p)
13717 expr = NULL_TREE;
13718 else if (processing_template_decl && conv->kind != ck_identity)
13719 {
13720 /* In a template, we are only concerned about determining the
13721 type of non-dependent expressions, so we do not have to
13722 perform the actual conversion. But for initializers, we
13723 need to be able to perform it at instantiation
13724 (or instantiate_non_dependent_expr) time. */
13725 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13726 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13727 }
13728 else
13729 expr = convert_like (convs: conv, expr, NULL_TREE, argnum: 0,
13730 /*issue_conversion_warnings=*/false,
13731 c_cast_p, /*nested_p=*/false, complain);
13732
13733 return expr;
13734}
13735
13736/* When initializing a reference that lasts longer than a full-expression,
13737 this special rule applies:
13738
13739 [class.temporary]
13740
13741 The temporary to which the reference is bound or the temporary
13742 that is the complete object to which the reference is bound
13743 persists for the lifetime of the reference.
13744
13745 The temporaries created during the evaluation of the expression
13746 initializing the reference, except the temporary to which the
13747 reference is bound, are destroyed at the end of the
13748 full-expression in which they are created.
13749
13750 In that case, we store the converted expression into a new
13751 VAR_DECL in a new scope.
13752
13753 However, we want to be careful not to create temporaries when
13754 they are not required. For example, given:
13755
13756 struct B {};
13757 struct D : public B {};
13758 D f();
13759 const B& b = f();
13760
13761 there is no need to copy the return value from "f"; we can just
13762 extend its lifetime. Similarly, given:
13763
13764 struct S {};
13765 struct T { operator S(); };
13766 T t;
13767 const S& s = t;
13768
13769 we can extend the lifetime of the return value of the conversion
13770 operator.
13771
13772 The next several functions are involved in this lifetime extension. */
13773
13774/* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13775 reference is being bound to a temporary. Create and return a new
13776 VAR_DECL with the indicated TYPE; this variable will store the value to
13777 which the reference is bound. */
13778
13779tree
13780make_temporary_var_for_ref_to_temp (tree decl, tree type)
13781{
13782 tree var = create_temporary_var (type);
13783
13784 /* Register the variable. */
13785 if (VAR_P (decl)
13786 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13787 {
13788 /* Namespace-scope or local static; give it a mangled name. */
13789
13790 /* If an initializer is visible to multiple translation units, those
13791 translation units must agree on the addresses of the
13792 temporaries. Therefore the temporaries must be given a consistent name
13793 and vague linkage. The mangled name of a temporary is the name of the
13794 non-temporary object in whose initializer they appear, prefixed with
13795 GR and suffixed with a sequence number mangled using the usual rules
13796 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13797 left-to-right walk of the complete initializer. */
13798 copy_linkage (var, decl);
13799
13800 tree name = mangle_ref_init_variable (decl);
13801 DECL_NAME (var) = name;
13802 SET_DECL_ASSEMBLER_NAME (var, name);
13803 }
13804 else
13805 /* Create a new cleanup level if necessary. */
13806 maybe_push_cleanup_level (type);
13807
13808 return pushdecl (var);
13809}
13810
13811/* EXPR is the initializer for a variable DECL of reference or
13812 std::initializer_list type. Create, push and return a new VAR_DECL
13813 for the initializer so that it will live as long as DECL. Any
13814 cleanup for the new variable is returned through CLEANUP, and the
13815 code to initialize the new variable is returned through INITP. */
13816
13817static tree
13818set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13819 tree *initp, tree *cond_guard)
13820{
13821 tree init;
13822 tree type;
13823 tree var;
13824
13825 /* Create the temporary variable. */
13826 type = TREE_TYPE (expr);
13827 var = make_temporary_var_for_ref_to_temp (decl, type);
13828 layout_decl (var, 0);
13829 /* If the rvalue is the result of a function call it will be
13830 a TARGET_EXPR. If it is some other construct (such as a
13831 member access expression where the underlying object is
13832 itself the result of a function call), turn it into a
13833 TARGET_EXPR here. It is important that EXPR be a
13834 TARGET_EXPR below since otherwise the INIT_EXPR will
13835 attempt to make a bitwise copy of EXPR to initialize
13836 VAR. */
13837 if (TREE_CODE (expr) != TARGET_EXPR)
13838 expr = get_target_expr (expr);
13839 else
13840 {
13841 if (TREE_ADDRESSABLE (expr))
13842 TREE_ADDRESSABLE (var) = 1;
13843 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
13844 DECL_MERGEABLE (var) = true;
13845 }
13846
13847 if (TREE_CODE (decl) == FIELD_DECL
13848 && extra_warnings && !warning_suppressed_p (decl))
13849 {
13850 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13851 "until the constructor exits", decl);
13852 suppress_warning (decl);
13853 }
13854
13855 /* Recursively extend temps in this initializer. */
13856 TARGET_EXPR_INITIAL (expr)
13857 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13858 cond_guard);
13859
13860 /* Any reference temp has a non-trivial initializer. */
13861 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13862
13863 /* If the initializer is constant, put it in DECL_INITIAL so we get
13864 static initialization and use in constant expressions. */
13865 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13866 /* As in store_init_value. */
13867 init = cp_fully_fold (init);
13868 if (TREE_CONSTANT (init))
13869 {
13870 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13871 {
13872 /* 5.19 says that a constant expression can include an
13873 lvalue-rvalue conversion applied to "a glvalue of literal type
13874 that refers to a non-volatile temporary object initialized
13875 with a constant expression". Rather than try to communicate
13876 that this VAR_DECL is a temporary, just mark it constexpr. */
13877 DECL_DECLARED_CONSTEXPR_P (var) = true;
13878 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13879 TREE_CONSTANT (var) = true;
13880 TREE_READONLY (var) = true;
13881 }
13882 DECL_INITIAL (var) = init;
13883 init = NULL_TREE;
13884 }
13885 else
13886 /* Create the INIT_EXPR that will initialize the temporary
13887 variable. */
13888 init = split_nonconstant_init (var, expr);
13889 if (at_function_scope_p ())
13890 {
13891 add_decl_expr (var);
13892
13893 if (TREE_STATIC (var))
13894 init = add_stmt_to_compound (init, register_dtor_fn (var));
13895 else
13896 {
13897 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13898 if (cleanup)
13899 {
13900 if (cond_guard && cleanup != error_mark_node)
13901 {
13902 if (*cond_guard == NULL_TREE)
13903 {
13904 *cond_guard = build_local_temp (boolean_type_node);
13905 add_decl_expr (*cond_guard);
13906 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13907 *cond_guard, NOP_EXPR,
13908 boolean_false_node,
13909 tf_warning_or_error);
13910 finish_expr_stmt (set);
13911 }
13912 cleanup = build3 (COND_EXPR, void_type_node,
13913 *cond_guard, cleanup, NULL_TREE);
13914 }
13915 vec_safe_push (v&: *cleanups, obj: cleanup);
13916 }
13917 }
13918
13919 /* We must be careful to destroy the temporary only
13920 after its initialization has taken place. If the
13921 initialization throws an exception, then the
13922 destructor should not be run. We cannot simply
13923 transform INIT into something like:
13924
13925 (INIT, ({ CLEANUP_STMT; }))
13926
13927 because emit_local_var always treats the
13928 initializer as a full-expression. Thus, the
13929 destructor would run too early; it would run at the
13930 end of initializing the reference variable, rather
13931 than at the end of the block enclosing the
13932 reference variable.
13933
13934 The solution is to pass back a cleanup expression
13935 which the caller is responsible for attaching to
13936 the statement tree. */
13937 }
13938 else
13939 {
13940 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13941 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13942 {
13943 if (CP_DECL_THREAD_LOCAL_P (var))
13944 tls_aggregates = tree_cons (NULL_TREE, var,
13945 tls_aggregates);
13946 else
13947 static_aggregates = tree_cons (NULL_TREE, var,
13948 static_aggregates);
13949 }
13950 else
13951 /* Check whether the dtor is callable. */
13952 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13953 }
13954 /* Avoid -Wunused-variable warning (c++/38958). */
13955 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13956 && VAR_P (decl))
13957 TREE_USED (decl) = DECL_READ_P (decl) = true;
13958
13959 *initp = init;
13960 return var;
13961}
13962
13963/* Convert EXPR to the indicated reference TYPE, in a way suitable for
13964 initializing a variable of that TYPE. */
13965
13966tree
13967initialize_reference (tree type, tree expr,
13968 int flags, tsubst_flags_t complain)
13969{
13970 conversion *conv;
13971 location_t loc = cp_expr_loc_or_input_loc (t: expr);
13972
13973 if (type == error_mark_node || error_operand_p (t: expr))
13974 return error_mark_node;
13975
13976 conversion_obstack_sentinel cos;
13977
13978 conv = reference_binding (rto: type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13979 flags, complain);
13980 /* If this conversion failed, we're in C++20, and we have something like
13981 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13982 if ((!conv || conv->bad_p)
13983 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13984 {
13985 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13986 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13987 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13988 conversion *c = reference_binding (rto: type, TREE_TYPE (e), expr: e,
13989 /*c_cast_p=*/false, flags, complain);
13990 /* If this worked, use it. */
13991 if (c && !c->bad_p)
13992 expr = e, conv = c;
13993 }
13994 if (!conv || conv->bad_p)
13995 {
13996 if (complain & tf_error)
13997 {
13998 if (conv)
13999 convert_like (convs: conv, expr, complain);
14000 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
14001 && !TYPE_REF_IS_RVALUE (type)
14002 && !lvalue_p (expr))
14003 error_at (loc, "invalid initialization of non-const reference of "
14004 "type %qH from an rvalue of type %qI",
14005 type, TREE_TYPE (expr));
14006 else
14007 error_at (loc, "invalid initialization of reference of type "
14008 "%qH from expression of type %qI", type,
14009 TREE_TYPE (expr));
14010 }
14011 return error_mark_node;
14012 }
14013
14014 if (conv->kind == ck_ref_bind)
14015 /* Perform the conversion. */
14016 expr = convert_like (convs: conv, expr, complain);
14017 else if (conv->kind == ck_ambig)
14018 /* We gave an error in build_user_type_conversion_1. */
14019 expr = error_mark_node;
14020 else
14021 gcc_unreachable ();
14022
14023 return expr;
14024}
14025
14026/* Return true if T is std::pair<const T&, const T&>. */
14027
14028static bool
14029std_pair_ref_ref_p (tree t)
14030{
14031 /* First, check if we have std::pair. */
14032 if (!NON_UNION_CLASS_TYPE_P (t)
14033 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
14034 return false;
14035 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
14036 if (!decl_in_std_namespace_p (tdecl))
14037 return false;
14038 tree name = DECL_NAME (tdecl);
14039 if (!name || !id_equal (id: name, str: "pair"))
14040 return false;
14041
14042 /* Now see if the template arguments are both const T&. */
14043 tree args = CLASSTYPE_TI_ARGS (t);
14044 if (TREE_VEC_LENGTH (args) != 2)
14045 return false;
14046 for (int i = 0; i < 2; i++)
14047 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
14048 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
14049 return false;
14050
14051 return true;
14052}
14053
14054/* Return true if a class T has a reference member. */
14055
14056static bool
14057class_has_reference_member_p (tree t)
14058{
14059 for (tree fields = TYPE_FIELDS (t);
14060 fields;
14061 fields = DECL_CHAIN (fields))
14062 if (TREE_CODE (fields) == FIELD_DECL
14063 && !DECL_ARTIFICIAL (fields)
14064 && TYPE_REF_P (TREE_TYPE (fields)))
14065 return true;
14066 return false;
14067}
14068
14069/* A wrapper for the above suitable as a callback for dfs_walk_once. */
14070
14071static tree
14072class_has_reference_member_p_r (tree binfo, void *)
14073{
14074 return (class_has_reference_member_p (BINFO_TYPE (binfo))
14075 ? integer_one_node : NULL_TREE);
14076}
14077
14078
14079/* Return true if T (either a class or a function) has been marked as
14080 not-dangling. */
14081
14082static bool
14083no_dangling_p (tree t)
14084{
14085 t = lookup_attribute (attr_name: "no_dangling", TYPE_ATTRIBUTES (t));
14086 if (!t)
14087 return false;
14088
14089 t = TREE_VALUE (t);
14090 if (!t)
14091 return true;
14092
14093 t = build_converted_constant_bool_expr (TREE_VALUE (t), complain: tf_warning_or_error);
14094 t = cxx_constant_value (t);
14095 return t == boolean_true_node;
14096}
14097
14098/* Return true if a class CTYPE is either std::reference_wrapper or
14099 std::ref_view, or a reference wrapper class. We consider a class
14100 a reference wrapper class if it has a reference member. We no
14101 longer check that it has a constructor taking the same reference type
14102 since that approach still generated too many false positives. */
14103
14104static bool
14105reference_like_class_p (tree ctype)
14106{
14107 if (!CLASS_TYPE_P (ctype))
14108 return false;
14109
14110 if (no_dangling_p (t: ctype))
14111 return true;
14112
14113 /* Also accept a std::pair<const T&, const T&>. */
14114 if (std_pair_ref_ref_p (t: ctype))
14115 return true;
14116
14117 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
14118 if (decl_in_std_namespace_p (tdecl))
14119 {
14120 tree name = DECL_NAME (tdecl);
14121 if (name
14122 && (id_equal (id: name, str: "reference_wrapper")
14123 || id_equal (id: name, str: "span")
14124 || id_equal (id: name, str: "ref_view")))
14125 return true;
14126 }
14127
14128 /* Avoid warning if CTYPE looks like std::span: it has a T* member and
14129 a trivial destructor. For example,
14130
14131 template<typename T>
14132 struct Span {
14133 T* data_;
14134 std::size len_;
14135 };
14136
14137 is considered std::span-like. */
14138 if (NON_UNION_CLASS_TYPE_P (ctype) && TYPE_HAS_TRIVIAL_DESTRUCTOR (ctype))
14139 for (tree field = next_aggregate_field (TYPE_FIELDS (ctype));
14140 field; field = next_aggregate_field (DECL_CHAIN (field)))
14141 if (TYPE_PTR_P (TREE_TYPE (field)))
14142 return true;
14143
14144 /* Some classes, such as std::tuple, have the reference member in its
14145 (non-direct) base class. */
14146 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
14147 nullptr, nullptr))
14148 return true;
14149
14150 return false;
14151}
14152
14153/* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
14154 that initializes the LHS (and at least one of its arguments represents
14155 a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
14156 if none found. For instance:
14157
14158 const S& s = S().self(); // S::self (&TARGET_EXPR <...>)
14159 const int& r = (42, f(1)); // f(1)
14160 const int& t = b ? f(1) : f(2); // f(1)
14161 const int& u = b ? f(1) : f(g); // f(1)
14162 const int& v = b ? f(g) : f(2); // f(2)
14163 const int& w = b ? f(g) : f(g); // NULL_TREE
14164 const int& y = (f(1), 42); // NULL_TREE
14165 const int& z = f(f(1)); // f(f(1))
14166
14167 EXPR is the initializer. If ARG_P is true, we're processing an argument
14168 to a function; the point is to distinguish between, for example,
14169
14170 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
14171
14172 where we shouldn't warn, and
14173
14174 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
14175
14176 where we should warn (Ref is a reference_like_class_p so we see through
14177 it. */
14178
14179static tree
14180do_warn_dangling_reference (tree expr, bool arg_p)
14181{
14182 STRIP_NOPS (expr);
14183
14184 if (arg_p && expr_represents_temporary_p (expr))
14185 {
14186 /* An attempt to reduce the number of -Wdangling-reference
14187 false positives concerning reference wrappers (c++/107532).
14188 When we encounter a reference_like_class_p, we don't warn
14189 just yet; instead, we keep recursing to see if there were
14190 any temporaries behind the reference-wrapper class. */
14191 tree e = expr;
14192 while (handled_component_p (t: e))
14193 e = TREE_OPERAND (e, 0);
14194 tree type = TREE_TYPE (e);
14195 /* If the temporary represents a lambda, we don't really know
14196 what's going on here. */
14197 if (!reference_like_class_p (ctype: type) && !LAMBDA_TYPE_P (type))
14198 return expr;
14199 }
14200
14201 switch (TREE_CODE (expr))
14202 {
14203 case CALL_EXPR:
14204 {
14205 tree fndecl = cp_get_callee_fndecl_nofold (expr);
14206 if (!fndecl
14207 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
14208 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
14209 opt: OPT_Wdangling_reference)
14210 /* Don't emit a false positive for:
14211 std::vector<int> v = ...;
14212 std::vector<int>::const_iterator it = v.begin();
14213 const int &r = *it++;
14214 because R refers to one of the int elements of V, not to
14215 a temporary object. Member operator* may return a reference
14216 but probably not to one of its arguments. */
14217 || (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
14218 && DECL_OVERLOADED_OPERATOR_P (fndecl)
14219 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF))
14220 || no_dangling_p (TREE_TYPE (fndecl)))
14221 return NULL_TREE;
14222
14223 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
14224 /* If the function doesn't return a reference, don't warn. This
14225 can be e.g.
14226 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
14227 which doesn't dangle: std::min here returns an int.
14228
14229 If the function returns a std::pair<const T&, const T&>, we
14230 warn, to detect e.g.
14231 std::pair<const int&, const int&> v = std::minmax(1, 2);
14232 which also creates a dangling reference, because std::minmax
14233 returns std::pair<const T&, const T&>(b, a). */
14234 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (ctype: rettype)))
14235 return NULL_TREE;
14236
14237 /* Here we're looking to see if any of the arguments is a temporary
14238 initializing a reference parameter. */
14239 for (int i = 0; i < call_expr_nargs (expr); ++i)
14240 {
14241 tree arg = CALL_EXPR_ARG (expr, i);
14242 /* Check that this argument initializes a reference, except for
14243 the argument initializing the object of a member function. */
14244 if (!DECL_IOBJ_MEMBER_FUNCTION_P (fndecl)
14245 && !TYPE_REF_P (TREE_TYPE (arg)))
14246 continue;
14247 STRIP_NOPS (arg);
14248 if (TREE_CODE (arg) == ADDR_EXPR)
14249 arg = TREE_OPERAND (arg, 0);
14250 /* Recurse to see if the argument is a temporary. It could also
14251 be another call taking a temporary and returning it and
14252 initializing this reference parameter. */
14253 if (do_warn_dangling_reference (expr: arg, /*arg_p=*/true))
14254 return expr;
14255 /* Don't warn about member functions like:
14256 std::any a(...);
14257 S& s = a.emplace<S>({0}, 0);
14258 which construct a new object and return a reference to it, but
14259 we still want to detect:
14260 struct S { const S& self () { return *this; } };
14261 const S& s = S().self();
14262 where 's' dangles. If we've gotten here, the object this function
14263 is invoked on is not a temporary. */
14264 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl))
14265 break;
14266 }
14267 return NULL_TREE;
14268 }
14269 case COMPOUND_EXPR:
14270 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
14271 case COND_EXPR:
14272 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
14273 return t;
14274 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
14275 case PAREN_EXPR:
14276 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
14277 case TARGET_EXPR:
14278 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
14279 default:
14280 return NULL_TREE;
14281 }
14282}
14283
14284/* Implement -Wdangling-reference, to detect cases like
14285
14286 int n = 1;
14287 const int& r = std::max(n - 1, n + 1); // r is dangling
14288
14289 This creates temporaries from the arguments, returns a reference to
14290 one of the temporaries, but both temporaries are destroyed at the end
14291 of the full expression.
14292
14293 This works by checking if a reference is initialized with a function
14294 that returns a reference, and at least one parameter of the function
14295 is a reference that is bound to a temporary. It assumes that such a
14296 function actually returns one of its arguments.
14297
14298 DECL is the reference being initialized, INIT is the initializer. */
14299
14300static void
14301maybe_warn_dangling_reference (const_tree decl, tree init)
14302{
14303 if (!warn_dangling_reference)
14304 return;
14305 tree type = TREE_TYPE (decl);
14306 /* Only warn if what we're initializing has type T&& or const T&, or
14307 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14308 bind to a temporary.) */
14309 if (!((TYPE_REF_OBJ_P (type)
14310 && (TYPE_REF_IS_RVALUE (type)
14311 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14312 || std_pair_ref_ref_p (t: type)))
14313 return;
14314 /* Don't suppress the diagnostic just because the call comes from
14315 a system header. If the DECL is not in a system header, or if
14316 -Wsystem-headers was provided, warn. */
14317 auto wsh
14318 = make_temp_override (var&: global_dc->m_warn_system_headers,
14319 overrider: (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14320 || global_dc->m_warn_system_headers));
14321 if (tree call = do_warn_dangling_reference (expr: init, /*arg_p=*/false))
14322 {
14323 auto_diagnostic_group d;
14324 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14325 "possibly dangling reference to a temporary"))
14326 inform (EXPR_LOCATION (call), "the temporary was destroyed at "
14327 "the end of the full expression %qE", call);
14328 }
14329}
14330
14331/* If *P is an xvalue expression, prevent temporary lifetime extension if it
14332 gets used to initialize a reference. */
14333
14334static tree
14335prevent_lifetime_extension (tree t)
14336{
14337 tree *p = &t;
14338 while (TREE_CODE (*p) == COMPOUND_EXPR)
14339 p = &TREE_OPERAND (*p, 1);
14340 while (handled_component_p (t: *p))
14341 p = &TREE_OPERAND (*p, 0);
14342 /* Change a TARGET_EXPR from prvalue to xvalue. */
14343 if (TREE_CODE (*p) == TARGET_EXPR)
14344 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14345 move (TARGET_EXPR_SLOT (*p)));
14346 return t;
14347}
14348
14349/* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14350 which is bound either to a reference or a std::initializer_list. */
14351
14352static tree
14353extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14354 tree *cond_guard)
14355{
14356 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14357 the temporary object that is the complete object of a subobject to which
14358 the reference is bound persists for the lifetime of the reference if the
14359 glvalue to which the reference is bound was obtained through one of the
14360 following:
14361 - a temporary materialization conversion ([conv.rval]),
14362 - ( expression ), where expression is one of these expressions,
14363 - subscripting ([expr.sub]) of an array operand, where that operand is one
14364 of these expressions,
14365 - a class member access ([expr.ref]) using the . operator where the left
14366 operand is one of these expressions and the right operand designates a
14367 non-static data member of non-reference type,
14368 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14369 where the left operand is one of these expressions and the right operand
14370 is a pointer to data member of non-reference type,
14371 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14372 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14373 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14374 a glvalue operand that is one of these expressions to a glvalue that
14375 refers to the object designated by the operand, or to its complete
14376 object or a subobject thereof,
14377 - a conditional expression ([expr.cond]) that is a glvalue where the
14378 second or third operand is one of these expressions, or
14379 - a comma expression ([expr.comma]) that is a glvalue where the right
14380 operand is one of these expressions. */
14381
14382 /* FIXME several cases are still handled wrong (101572, 81420). */
14383
14384 tree sub = init;
14385 tree *p;
14386 STRIP_NOPS (sub);
14387 if (TREE_CODE (sub) == COMPOUND_EXPR)
14388 {
14389 TREE_OPERAND (sub, 1)
14390 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14391 cond_guard);
14392 return init;
14393 }
14394 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14395 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14396 (TREE_OPERAND (sub, 1)))))
14397 {
14398 /* A pointer-to-member operation. */
14399 TREE_OPERAND (sub, 0)
14400 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14401 cond_guard);
14402 return init;
14403 }
14404 if (TREE_CODE (sub) == COND_EXPR)
14405 {
14406 tree cur_cond_guard = NULL_TREE;
14407 if (TREE_OPERAND (sub, 1))
14408 TREE_OPERAND (sub, 1)
14409 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14410 cond_guard: &cur_cond_guard);
14411 if (cur_cond_guard)
14412 {
14413 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14414 NOP_EXPR, boolean_true_node,
14415 tf_warning_or_error);
14416 TREE_OPERAND (sub, 1)
14417 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14418 tf_warning_or_error);
14419 }
14420 cur_cond_guard = NULL_TREE;
14421 if (TREE_OPERAND (sub, 2))
14422 TREE_OPERAND (sub, 2)
14423 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14424 cond_guard: &cur_cond_guard);
14425 if (cur_cond_guard)
14426 {
14427 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14428 NOP_EXPR, boolean_true_node,
14429 tf_warning_or_error);
14430 TREE_OPERAND (sub, 2)
14431 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14432 tf_warning_or_error);
14433 }
14434 return init;
14435 }
14436 if (TREE_CODE (sub) != ADDR_EXPR)
14437 return init;
14438 /* Deal with binding to a subobject. */
14439 for (p = &TREE_OPERAND (sub, 0);
14440 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14441 p = &TREE_OPERAND (*p, 0);
14442 if (TREE_CODE (*p) == TARGET_EXPR)
14443 {
14444 tree subinit = NULL_TREE;
14445 *p = set_up_extended_ref_temp (decl, expr: *p, cleanups, initp: &subinit, cond_guard);
14446 recompute_tree_invariant_for_addr_expr (sub);
14447 if (init != sub)
14448 init = fold_convert (TREE_TYPE (init), sub);
14449 if (subinit)
14450 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14451 }
14452 return init;
14453}
14454
14455/* INIT is part of the initializer for DECL. If there are any
14456 reference or initializer lists being initialized, extend their
14457 lifetime to match that of DECL. */
14458
14459tree
14460extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14461 tree *cond_guard)
14462{
14463 tree type = TREE_TYPE (init);
14464 if (processing_template_decl)
14465 return init;
14466
14467 maybe_warn_dangling_reference (decl, init);
14468
14469 if (TYPE_REF_P (type))
14470 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14471 else
14472 {
14473 tree ctor = init;
14474 if (TREE_CODE (ctor) == TARGET_EXPR)
14475 ctor = TARGET_EXPR_INITIAL (ctor);
14476 if (TREE_CODE (ctor) == CONSTRUCTOR)
14477 {
14478 /* [dcl.init] When initializing an aggregate from a parenthesized list
14479 of values... a temporary object bound to a reference does not have
14480 its lifetime extended. */
14481 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14482 return init;
14483
14484 if (is_std_init_list (type))
14485 {
14486 /* The temporary array underlying a std::initializer_list
14487 is handled like a reference temporary. */
14488 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14489 array = extend_ref_init_temps_1 (decl, init: array, cleanups,
14490 cond_guard);
14491 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14492 }
14493 else
14494 {
14495 unsigned i;
14496 constructor_elt *p;
14497 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14498 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14499 p->value = extend_ref_init_temps (decl, init: p->value, cleanups,
14500 cond_guard);
14501 }
14502 recompute_constructor_flags (ctor);
14503 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14504 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14505 }
14506 }
14507
14508 return init;
14509}
14510
14511/* Returns true iff an initializer for TYPE could contain temporaries that
14512 need to be extended because they are bound to references or
14513 std::initializer_list. */
14514
14515bool
14516type_has_extended_temps (tree type)
14517{
14518 type = strip_array_types (type);
14519 if (TYPE_REF_P (type))
14520 return true;
14521 if (CLASS_TYPE_P (type))
14522 {
14523 if (is_std_init_list (type))
14524 return true;
14525 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14526 f; f = next_aggregate_field (DECL_CHAIN (f)))
14527 if (type_has_extended_temps (TREE_TYPE (f)))
14528 return true;
14529 }
14530 return false;
14531}
14532
14533/* Returns true iff TYPE is some variant of std::initializer_list. */
14534
14535bool
14536is_std_init_list (tree type)
14537{
14538 if (!TYPE_P (type))
14539 return false;
14540 if (cxx_dialect == cxx98)
14541 return false;
14542 /* Look through typedefs. */
14543 type = TYPE_MAIN_VARIANT (type);
14544 return (CLASS_TYPE_P (type)
14545 && CP_TYPE_CONTEXT (type) == std_node
14546 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14547}
14548
14549/* Returns true iff DECL is a list constructor: i.e. a constructor which
14550 will accept an argument list of a single std::initializer_list<T>. */
14551
14552bool
14553is_list_ctor (tree decl)
14554{
14555 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14556 tree arg;
14557
14558 if (!args || args == void_list_node)
14559 return false;
14560
14561 arg = non_reference (TREE_VALUE (args));
14562 if (!is_std_init_list (type: arg))
14563 return false;
14564
14565 args = TREE_CHAIN (args);
14566
14567 if (args && args != void_list_node && !TREE_PURPOSE (args))
14568 /* There are more non-defaulted parms. */
14569 return false;
14570
14571 return true;
14572}
14573
14574/* We know that can_convert_arg_bad already said "no" when trying to convert
14575 FROM to TO with ARG and FLAGS. Try to figure out if it was because
14576 an explicit conversion function was skipped when looking for a way to
14577 perform the conversion. At this point we've already printed an error. */
14578
14579void
14580maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
14581{
14582 if (!(flags & LOOKUP_ONLYCONVERTING))
14583 return;
14584
14585 conversion_obstack_sentinel cos;
14586 conversion *c = implicit_conversion (to, from, expr: arg, /*c_cast_p=*/false,
14587 flags: flags & ~LOOKUP_ONLYCONVERTING, complain: tf_none);
14588 if (c && !c->bad_p && c->user_conv_p)
14589 /* Ay, the conversion would have worked in direct-init context. */
14590 for (; c; c = next_conversion (conv: c))
14591 if (c->kind == ck_user
14592 && DECL_P (c->cand->fn)
14593 && DECL_NONCONVERTING_P (c->cand->fn))
14594 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
14595 "function was not considered");
14596}
14597
14598/* We're converting EXPR to TYPE. If that conversion involves a conversion
14599 function and we're binding EXPR to a reference parameter of that function,
14600 return true. */
14601
14602bool
14603conv_binds_to_reference_parm_p (tree type, tree expr)
14604{
14605 conversion_obstack_sentinel cos;
14606 conversion *c = implicit_conversion (to: type, TREE_TYPE (expr), expr,
14607 /*c_cast_p=*/false, LOOKUP_NORMAL,
14608 complain: tf_none);
14609 if (c && !c->bad_p && c->user_conv_p)
14610 for (; c; c = next_conversion (conv: c))
14611 if (c->kind == ck_user)
14612 for (z_candidate *cand = c->cand; cand; cand = cand->next)
14613 if (cand->viable == 1)
14614 for (size_t i = 0; i < cand->num_convs; ++i)
14615 if (cand->convs[i]->kind == ck_ref_bind
14616 && conv_get_original_expr (c: cand->convs[i]) == expr)
14617 return true;
14618
14619 return false;
14620}
14621
14622#include "gt-cp-call.h"
14623

source code of gcc/cp/call.cc