]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/cp/call.cc
Update copyright years.
[thirdparty/gcc.git] / gcc / cp / call.cc
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
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
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
50 enum conversion_kind {
51 ck_identity,
52 ck_lvalue,
53 ck_fnptr,
54 ck_qual,
55 ck_std,
56 ck_ptr,
57 ck_pmem,
58 ck_base,
59 ck_ref_bind,
60 ck_user,
61 ck_ambig,
62 ck_list,
63 ck_aggr,
64 ck_rvalue,
65 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
66 this kind whenever we know the true conversion is either bad or outright
67 invalid, but we don't want to attempt to compute the bad conversion (for
68 sake of avoiding unnecessary instantiation). bad_p should always be set
69 for these. */
70 ck_deferred_bad,
71 };
72
73 /* The rank of the conversion. Order of the enumerals matters; better
74 conversions should come earlier in the list. */
75
76 enum conversion_rank {
77 cr_identity,
78 cr_exact,
79 cr_promotion,
80 cr_std,
81 cr_pbool,
82 cr_user,
83 cr_ellipsis,
84 cr_bad
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
91 struct conversion {
92 /* The kind of conversion represented by this step. */
93 conversion_kind kind;
94 /* The rank of this conversion. */
95 conversion_rank rank;
96 BOOL_BITFIELD user_conv_p : 1;
97 BOOL_BITFIELD ellipsis_p : 1;
98 BOOL_BITFIELD this_p : 1;
99 /* True if this conversion would be permitted with a bending of
100 language standards, e.g. disregarding pointer qualifiers or
101 converting integers to pointers. */
102 BOOL_BITFIELD bad_p : 1;
103 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
104 temporary should be created to hold the result of the
105 conversion. If KIND is ck_ambig or ck_user, true means force
106 copy-initialization. */
107 BOOL_BITFIELD need_temporary_p : 1;
108 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
109 from a pointer-to-derived to pointer-to-base is being performed. */
110 BOOL_BITFIELD base_p : 1;
111 /* If KIND is ck_ref_bind, true when either an lvalue reference is
112 being bound to an lvalue expression or an rvalue reference is
113 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
114 true when we are treating an lvalue as an rvalue (12.8p33). If
115 ck_identity, we will be binding a reference directly or decaying to
116 a pointer. */
117 BOOL_BITFIELD rvaluedness_matches_p: 1;
118 BOOL_BITFIELD check_narrowing: 1;
119 /* Whether check_narrowing should only check TREE_CONSTANTs; used
120 in build_converted_constant_expr. */
121 BOOL_BITFIELD check_narrowing_const_only: 1;
122 /* True if this conversion is taking place in a copy-initialization context
123 and we should only consider converting constructors. Only set in
124 ck_base and ck_rvalue. */
125 BOOL_BITFIELD copy_init_p : 1;
126 /* The type of the expression resulting from the conversion. */
127 tree type;
128 union {
129 /* The next conversion in the chain. Since the conversions are
130 arranged from outermost to innermost, the NEXT conversion will
131 actually be performed before this conversion. This variant is
132 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
133 ck_list. Please use the next_conversion function instead
134 of using this field directly. */
135 conversion *next;
136 /* The expression at the beginning of the conversion chain. This
137 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
138 You can use conv_get_original_expr to get this expression. */
139 tree expr;
140 /* The array of conversions for an initializer_list, so this
141 variant is used only when KIN D is ck_list. */
142 conversion **list;
143 } u;
144 /* The function candidate corresponding to this conversion
145 sequence. This field is only used if KIND is ck_user. */
146 struct z_candidate *cand;
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
160 static struct obstack conversion_obstack;
161 static bool conversion_obstack_initialized;
162 struct rejection_reason;
163
164 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
165 static int equal_functions (tree, tree);
166 static int joust (struct z_candidate *, struct z_candidate *, bool,
167 tsubst_flags_t);
168 static int compare_ics (conversion *, conversion *);
169 static void maybe_warn_class_memaccess (location_t, tree,
170 const vec<tree, va_gc> *);
171 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
172 static tree convert_like (conversion *, tree, tsubst_flags_t);
173 static tree convert_like_with_context (conversion *, tree, tree, int,
174 tsubst_flags_t);
175 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
176 tree, tree, tree, bool);
177 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
178 tsubst_flags_t);
179 static void print_z_candidate (location_t, const char *, struct z_candidate *);
180 static void print_z_candidates (location_t, struct z_candidate *,
181 tristate = tristate::unknown ());
182 static tree build_this (tree);
183 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
184 static bool any_strictly_viable (struct z_candidate *);
185 static struct z_candidate *add_template_candidate
186 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
187 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
188 static struct z_candidate *add_template_candidate_real
189 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
190 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
191 static bool is_complete (tree);
192 static struct z_candidate *add_conv_candidate
193 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
194 tree, tsubst_flags_t);
195 static struct z_candidate *add_function_candidate
196 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
197 tree, int, conversion**, bool, tsubst_flags_t);
198 static conversion *implicit_conversion (tree, tree, tree, bool, int,
199 tsubst_flags_t);
200 static conversion *reference_binding (tree, tree, tree, bool, int,
201 tsubst_flags_t);
202 static conversion *build_conv (conversion_kind, tree, conversion *);
203 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
204 static conversion *next_conversion (conversion *);
205 static bool is_subseq (conversion *, conversion *);
206 static conversion *maybe_handle_ref_bind (conversion **);
207 static void maybe_handle_implicit_object (conversion **);
208 static struct z_candidate *add_candidate
209 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
210 conversion **, tree, tree, int, struct rejection_reason *, int);
211 static tree source_type (conversion *);
212 static void add_warning (struct z_candidate *, struct z_candidate *);
213 static conversion *direct_reference_binding (tree, conversion *);
214 static bool promoted_arithmetic_type_p (tree);
215 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
216 static char *name_as_c_string (tree, tree, bool *);
217 static tree prep_operand (tree);
218 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
219 bool, tree, tree, int, struct z_candidate **,
220 tsubst_flags_t);
221 static conversion *merge_conversion_sequences (conversion *, conversion *);
222 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
223 static conversion *build_identity_conv (tree, tree);
224 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
225 static bool conv_is_prvalue (conversion *);
226 static tree prevent_lifetime_extension (tree);
227
228 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
229 NAME can take many forms... */
230
231 bool
232 check_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 (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, 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
277 tree
278 build_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
310 tree
311 build_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
332 void
333 set_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
360 tree
361 build_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, 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 (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
425 struct z_candidate;
426
427 struct candidate_warning {
428 z_candidate *loser;
429 candidate_warning *next;
430 };
431
432 /* Information for providing diagnostics about why overloading failed. */
433
434 enum rejection_reason_code {
435 rr_none,
436 rr_arity,
437 rr_explicit_conversion,
438 rr_template_conversion,
439 rr_arg_conversion,
440 rr_bad_arg_conversion,
441 rr_template_unification,
442 rr_invalid_copy,
443 rr_inherited_ctor,
444 rr_constraint_failure,
445 rr_ignored,
446 };
447
448 struct conversion_info {
449 /* The index of the argument, 0-based. */
450 int n_arg;
451 /* The actual argument or its type. */
452 tree from;
453 /* The type of the parameter. */
454 tree to_type;
455 /* The location of the argument. */
456 location_t loc;
457 };
458
459 struct rejection_reason {
460 enum rejection_reason_code code;
461 union {
462 /* Information about an arity mismatch. */
463 struct {
464 /* The expected number of arguments. */
465 int expected;
466 /* The actual number of arguments in the call. */
467 int actual;
468 /* Whether EXPECTED should be treated as a lower bound. */
469 bool least_p;
470 } arity;
471 /* Information about an argument conversion mismatch. */
472 struct conversion_info conversion;
473 /* Same, but for bad argument conversions. */
474 struct conversion_info bad_conversion;
475 /* Information about template unification failures. These are the
476 parameters passed to fn_type_unification. */
477 struct {
478 tree tmpl;
479 tree explicit_targs;
480 int num_targs;
481 const tree *args;
482 unsigned int nargs;
483 tree return_type;
484 unification_kind_t strict;
485 int flags;
486 } template_unification;
487 /* Information about template instantiation failures. These are the
488 parameters passed to instantiate_template. */
489 struct {
490 tree tmpl;
491 tree targs;
492 } template_instantiation;
493 } u;
494 };
495
496 struct z_candidate {
497 /* The FUNCTION_DECL that will be called if this candidate is
498 selected by overload resolution. */
499 tree fn;
500 /* If not NULL_TREE, the first argument to use when calling this
501 function. */
502 tree first_arg;
503 /* The rest of the arguments to use when calling this function. If
504 there are no further arguments this may be NULL or it may be an
505 empty vector. */
506 const vec<tree, va_gc> *args;
507 /* The implicit conversion sequences for each of the arguments to
508 FN. */
509 conversion **convs;
510 /* The number of implicit conversion sequences. */
511 size_t num_convs;
512 /* If FN is a user-defined conversion, the standard conversion
513 sequence from the type returned by FN to the desired destination
514 type. */
515 conversion *second_conv;
516 struct rejection_reason *reason;
517 /* If FN is a member function, the binfo indicating the path used to
518 qualify the name of FN at the call site. This path is used to
519 determine whether or not FN is accessible if it is selected by
520 overload resolution. The DECL_CONTEXT of FN will always be a
521 (possibly improper) base of this binfo. */
522 tree access_path;
523 /* If FN is a non-static member function, the binfo indicating the
524 subobject to which the `this' pointer should be converted if FN
525 is selected by overload resolution. The type pointed to by
526 the `this' pointer must correspond to the most derived class
527 indicated by the CONVERSION_PATH. */
528 tree conversion_path;
529 tree template_decl;
530 tree explicit_targs;
531 candidate_warning *warnings;
532 z_candidate *next;
533 int viable;
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
545 bool
546 null_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
582 bool
583 null_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
601 bool
602 sufficient_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
615 static void *
616 conversion_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 (p, 0, n);
626 return p;
627 }
628
629 /* RAII class to discard anything added to conversion_obstack. */
630
631 struct conversion_obstack_sentinel
632 {
633 void *p;
634 conversion_obstack_sentinel (): p (conversion_obstack_alloc (0)) {}
635 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
636 };
637
638 /* Allocate rejection reasons. */
639
640 static struct rejection_reason *
641 alloc_rejection (enum rejection_reason_code code)
642 {
643 struct rejection_reason *p;
644 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
645 p->code = code;
646 return p;
647 }
648
649 static struct rejection_reason *
650 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
651 {
652 struct rejection_reason *r = alloc_rejection (rr_arity);
653 int adjust = first_arg != NULL_TREE;
654 r->u.arity.expected = expected - adjust;
655 r->u.arity.actual = actual - adjust;
656 r->u.arity.least_p = least_p;
657 return r;
658 }
659
660 static struct rejection_reason *
661 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
662 location_t loc)
663 {
664 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
665 int adjust = first_arg != NULL_TREE;
666 r->u.conversion.n_arg = n_arg - adjust;
667 r->u.conversion.from = from;
668 r->u.conversion.to_type = to;
669 r->u.conversion.loc = loc;
670 return r;
671 }
672
673 static struct rejection_reason *
674 bad_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 (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
686 static struct rejection_reason *
687 explicit_conversion_rejection (tree from, tree to)
688 {
689 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
690 r->u.conversion.n_arg = 0;
691 r->u.conversion.from = from;
692 r->u.conversion.to_type = to;
693 r->u.conversion.loc = UNKNOWN_LOCATION;
694 return r;
695 }
696
697 static struct rejection_reason *
698 template_conversion_rejection (tree from, tree to)
699 {
700 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
701 r->u.conversion.n_arg = 0;
702 r->u.conversion.from = from;
703 r->u.conversion.to_type = to;
704 r->u.conversion.loc = UNKNOWN_LOCATION;
705 return r;
706 }
707
708 static struct rejection_reason *
709 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
710 const tree *args, unsigned int nargs,
711 tree return_type, unification_kind_t strict,
712 int flags)
713 {
714 size_t args_n_bytes = sizeof (*args) * nargs;
715 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
716 struct rejection_reason *r = alloc_rejection (rr_template_unification);
717 r->u.template_unification.tmpl = tmpl;
718 r->u.template_unification.explicit_targs = explicit_targs;
719 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
720 /* Copy args to our own storage. */
721 memcpy (args1, args, args_n_bytes);
722 r->u.template_unification.args = args1;
723 r->u.template_unification.nargs = nargs;
724 r->u.template_unification.return_type = return_type;
725 r->u.template_unification.strict = strict;
726 r->u.template_unification.flags = flags;
727 return r;
728 }
729
730 static struct rejection_reason *
731 template_unification_error_rejection (void)
732 {
733 return alloc_rejection (rr_template_unification);
734 }
735
736 static struct rejection_reason *
737 invalid_copy_with_fn_template_rejection (void)
738 {
739 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
740 return r;
741 }
742
743 static struct rejection_reason *
744 inherited_ctor_rejection (void)
745 {
746 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
747 return r;
748 }
749
750 /* Build a constraint failure record. */
751
752 static struct rejection_reason *
753 constraint_failure (void)
754 {
755 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
756 return r;
757 }
758
759 /* Dynamically allocate a conversion. */
760
761 static conversion *
762 alloc_conversion (conversion_kind kind)
763 {
764 conversion *c;
765 c = (conversion *) conversion_obstack_alloc (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
773 void
774 validate_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
783 static conversion **
784 alloc_conversions (size_t n)
785 {
786 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
787 }
788
789 /* True iff the active member of conversion::u for code CODE is NEXT. */
790
791 static inline bool
792 has_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
801 static conversion *
802 build_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 (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
846 static conversion *
847 build_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 (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 (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
902 static conversion *
903 next_conversion (conversion *conv)
904 {
905 if (conv == NULL
906 || !has_next (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
914 static conversion *
915 strip_standard_conversion (conversion *conv)
916 {
917 while (conv
918 && conv->kind != ck_user
919 && has_next (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
927 static bool
928 can_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 (elttype, val, flags, complain);
941 else
942 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
943 complain);
944 if (!ok)
945 return false;
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
962 static bool
963 field_in_pset (hash_set<tree, true> &pset, tree field)
964 {
965 if (pset.contains (field))
966 return true;
967 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
968 for (field = TYPE_FIELDS (TREE_TYPE (field));
969 field; field = DECL_CHAIN (field))
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
983 static conversion *
984 build_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 (ftype, 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 (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 (ftype, 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 (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
1087 static conversion *
1088 build_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 (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
1138 static conversion *
1139 build_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 (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
1182 static conversion *
1183 build_identity_conv (tree type, tree expr)
1184 {
1185 conversion *c;
1186
1187 c = alloc_conversion (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
1198 static conversion *
1199 build_ambiguous_conv (tree type, tree expr)
1200 {
1201 conversion *c;
1202
1203 c = alloc_conversion (ck_ambig);
1204 c->type = type;
1205 c->u.expr = expr;
1206
1207 return c;
1208 }
1209
1210 tree
1211 strip_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
1223 static conversion *
1224 standard_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 (to);
1240 from = strip_top_quals (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 (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 (ck_lvalue, 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 (bitfield_type);
1284 fcode = TREE_CODE (from);
1285 }
1286 }
1287 conv = build_conv (ck_rvalue, from, conv);
1288 /* If we're performing copy-initialization, remember to skip
1289 explicit constructors. */
1290 if (flags & LOOKUP_ONLYCONVERTING)
1291 conv->copy_init_p = true;
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 (part_conv->kind, to, 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 (expr))
1331 || NULLPTR_TYPE_P (from)))
1332 conv = build_conv (ck_std, to, conv);
1333 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1334 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1335 {
1336 /* For backwards brain damage compatibility, allow interconversion of
1337 pointers and integers with a pedwarn. */
1338 conv = build_conv (ck_std, to, conv);
1339 conv->bad_p = true;
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 (ck_std, to, 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 (ck_ptr, 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 (ck_pmem, 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 (ck_ptr, 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 (ck_qual, to, conv);
1437 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1438 conv = build_conv (ck_qual, to, conv);
1439 else if (expr && string_conv_p (to, expr, 0))
1440 /* converting from string constant to char *. */
1441 conv = build_conv (ck_qual, to, conv);
1442 else if (fnptr_conv_p (to, from))
1443 conv = build_conv (ck_fnptr, to, conv);
1444 /* Allow conversions among compatible ObjC pointer types (base
1445 conversions have been already handled above). */
1446 else if (c_dialect_objc ()
1447 && objc_compare_types (to, from, -4, NULL_TREE))
1448 conv = build_conv (ck_ptr, to, conv);
1449 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1450 {
1451 conv = build_conv (ck_ptr, to, 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 (fromfn);
1464 tree tbase = class_of_this_parm (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 (ck_pmem, from, conv);
1487 conv->base_p = true;
1488 }
1489 if (fnptr_conv_p (tstat, fstat))
1490 conv = build_conv (ck_fnptr, to, 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 (ck_std, to, conv);
1507 if (fcode == POINTER_TYPE
1508 || TYPE_PTRDATAMEM_P (from)
1509 || (TYPE_PTRMEMFUNC_P (from)
1510 && conv->rank < cr_pbool)
1511 || NULLPTR_TYPE_P (from))
1512 conv->rank = cr_pbool;
1513 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1514 conv->bad_p = true;
1515 if (flags & LOOKUP_NO_NARROWING)
1516 conv->check_narrowing = true;
1517 return conv;
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 (ck_std, to, 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 (from)
1567 || extended_float_type_p (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 (from, to, false))
1573 return build_conv (ck_std, to, conv);
1574 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1575 && is_properly_derived_from (from, to))
1576 {
1577 if (conv->kind == ck_rvalue)
1578 conv = next_conversion (conv);
1579 conv = build_conv (ck_base, to, conv);
1580 /* The derived-to-base conversion indicates the initialization
1581 of a parameter with base type from an object of a derived
1582 type. A temporary object is created to hold the result of
1583 the conversion unless we're binding directly to a reference. */
1584 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1585 /* If we're performing copy-initialization, remember to skip
1586 explicit constructors. */
1587 if (flags & LOOKUP_ONLYCONVERTING)
1588 conv->copy_init_p = true;
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 bool
1602 reference_related_p (tree t1, tree t2)
1603 {
1604 if (t1 == error_mark_node || t2 == error_mark_node)
1605 return false;
1606
1607 t1 = TYPE_MAIN_VARIANT (t1);
1608 t2 = TYPE_MAIN_VARIANT (t2);
1609
1610 /* [dcl.init.ref]
1611
1612 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1613 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1614 return (similar_type_p (t1, t2)
1615 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1616 && DERIVED_FROM_P (t1, t2)));
1617 }
1618
1619 /* Returns nonzero if T1 is reference-compatible with T2. */
1620
1621 bool
1622 reference_compatible_p (tree t1, tree t2)
1623 {
1624 /* [dcl.init.ref]
1625
1626 "cv1 T1" is reference compatible with "cv2 T2" if
1627 a prvalue of type "pointer to cv2 T2" can be converted to the type
1628 "pointer to cv1 T1" via a standard conversion sequence. */
1629 tree ptype1 = build_pointer_type (t1);
1630 tree ptype2 = build_pointer_type (t2);
1631 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1632 /*c_cast_p=*/false, 0, tf_none);
1633 if (!conv || conv->bad_p)
1634 return false;
1635 return true;
1636 }
1637
1638 /* Return true if converting FROM to TO would involve a qualification
1639 conversion. */
1640
1641 static bool
1642 involves_qualification_conversion_p (tree to, tree from)
1643 {
1644 /* If we're not convering a pointer to another one, we won't get
1645 a qualification conversion. */
1646 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1647 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1648 return false;
1649
1650 conversion *conv = standard_conversion (to, from, NULL_TREE,
1651 /*c_cast_p=*/false, 0, tf_none);
1652 for (conversion *t = conv; t; t = next_conversion (t))
1653 if (t->kind == ck_qual)
1654 return true;
1655
1656 return false;
1657 }
1658
1659 /* A reference of the indicated TYPE is being bound directly to the
1660 expression represented by the implicit conversion sequence CONV.
1661 Return a conversion sequence for this binding. */
1662
1663 static conversion *
1664 direct_reference_binding (tree type, conversion *conv)
1665 {
1666 tree t;
1667
1668 gcc_assert (TYPE_REF_P (type));
1669 gcc_assert (!TYPE_REF_P (conv->type));
1670
1671 t = TREE_TYPE (type);
1672
1673 if (conv->kind == ck_identity)
1674 /* Mark the identity conv as to not decay to rvalue. */
1675 conv->rvaluedness_matches_p = true;
1676
1677 /* [over.ics.rank]
1678
1679 When a parameter of reference type binds directly
1680 (_dcl.init.ref_) to an argument expression, the implicit
1681 conversion sequence is the identity conversion, unless the
1682 argument expression has a type that is a derived class of the
1683 parameter type, in which case the implicit conversion sequence is
1684 a derived-to-base Conversion.
1685
1686 If the parameter binds directly to the result of applying a
1687 conversion function to the argument expression, the implicit
1688 conversion sequence is a user-defined conversion sequence
1689 (_over.ics.user_), with the second standard conversion sequence
1690 either an identity conversion or, if the conversion function
1691 returns an entity of a type that is a derived class of the
1692 parameter type, a derived-to-base conversion. */
1693 if (is_properly_derived_from (conv->type, t))
1694 {
1695 /* Represent the derived-to-base conversion. */
1696 conv = build_conv (ck_base, t, conv);
1697 /* We will actually be binding to the base-class subobject in
1698 the derived class, so we mark this conversion appropriately.
1699 That way, convert_like knows not to generate a temporary. */
1700 conv->need_temporary_p = false;
1701 }
1702 else if (involves_qualification_conversion_p (t, conv->type))
1703 /* Represent the qualification conversion. After DR 2352
1704 #1 and #2 were indistinguishable conversion sequences:
1705
1706 void f(int*); // #1
1707 void f(const int* const &); // #2
1708 void g(int* p) { f(p); }
1709
1710 because the types "int *" and "const int *const" are
1711 reference-related and we were binding both directly and they
1712 had the same rank. To break it up, we add a ck_qual under the
1713 ck_ref_bind so that conversion sequence ranking chooses #1.
1714
1715 We strip_top_quals here which is also what standard_conversion
1716 does. Failure to do so would confuse comp_cv_qual_signature
1717 into thinking that in
1718
1719 void f(const int * const &); // #1
1720 void f(const int *); // #2
1721 int *x;
1722 f(x);
1723
1724 #2 is a better match than #1 even though they're ambiguous (97296). */
1725 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1726
1727 return build_conv (ck_ref_bind, type, conv);
1728 }
1729
1730 /* Returns the conversion path from type FROM to reference type TO for
1731 purposes of reference binding. For lvalue binding, either pass a
1732 reference type to FROM or an lvalue expression to EXPR. If the
1733 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1734 the conversion returned. If C_CAST_P is true, this
1735 conversion is coming from a C-style cast. */
1736
1737 static conversion *
1738 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1739 tsubst_flags_t complain)
1740 {
1741 conversion *conv = NULL;
1742 tree to = TREE_TYPE (rto);
1743 tree from = rfrom;
1744 tree tfrom;
1745 bool related_p;
1746 bool compatible_p;
1747 cp_lvalue_kind gl_kind;
1748 bool is_lvalue;
1749
1750 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1751 {
1752 expr = instantiate_type (to, expr, tf_none);
1753 if (expr == error_mark_node)
1754 return NULL;
1755 from = TREE_TYPE (expr);
1756 }
1757
1758 bool copy_list_init = false;
1759 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1760 {
1761 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1762 /* DR 1288: Otherwise, if the initializer list has a single element
1763 of type E and ... [T's] referenced type is reference-related to E,
1764 the object or reference is initialized from that element...
1765
1766 ??? With P0388R4, we should bind 't' directly to U{}:
1767 using U = A[2];
1768 A (&&t)[] = {U{}};
1769 because A[] and A[2] are reference-related. But we don't do it
1770 because grok_reference_init has deduced the array size (to 1), and
1771 A[1] and A[2] aren't reference-related. */
1772 if (CONSTRUCTOR_NELTS (expr) == 1
1773 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1774 {
1775 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1776 if (error_operand_p (elt))
1777 return NULL;
1778 tree etype = TREE_TYPE (elt);
1779 if (reference_related_p (to, etype))
1780 {
1781 expr = elt;
1782 from = etype;
1783 goto skip;
1784 }
1785 }
1786 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1787 referenced by T is copy-list-initialized, and the reference is bound
1788 to that temporary. */
1789 copy_list_init = true;
1790 skip:;
1791 }
1792
1793 if (TYPE_REF_P (from))
1794 {
1795 from = TREE_TYPE (from);
1796 if (!TYPE_REF_IS_RVALUE (rfrom)
1797 || TREE_CODE (from) == FUNCTION_TYPE)
1798 gl_kind = clk_ordinary;
1799 else
1800 gl_kind = clk_rvalueref;
1801 }
1802 else if (expr)
1803 gl_kind = lvalue_kind (expr);
1804 else if (CLASS_TYPE_P (from)
1805 || TREE_CODE (from) == ARRAY_TYPE)
1806 gl_kind = clk_class;
1807 else
1808 gl_kind = clk_none;
1809
1810 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1811 if ((flags & LOOKUP_NO_TEMP_BIND)
1812 && (gl_kind & clk_class))
1813 gl_kind = clk_none;
1814
1815 /* Same mask as real_lvalue_p. */
1816 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1817
1818 tfrom = from;
1819 if ((gl_kind & clk_bitfield) != 0)
1820 tfrom = unlowered_expr_type (expr);
1821
1822 /* Figure out whether or not the types are reference-related and
1823 reference compatible. We have to do this after stripping
1824 references from FROM. */
1825 related_p = reference_related_p (to, tfrom);
1826 /* If this is a C cast, first convert to an appropriately qualified
1827 type, so that we can later do a const_cast to the desired type. */
1828 if (related_p && c_cast_p
1829 && !at_least_as_qualified_p (to, tfrom))
1830 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1831 compatible_p = reference_compatible_p (to, tfrom);
1832
1833 /* Directly bind reference when target expression's type is compatible with
1834 the reference and expression is an lvalue. In DR391, the wording in
1835 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1836 const and rvalue references to rvalues of compatible class type.
1837 We should also do direct bindings for non-class xvalues. */
1838 if ((related_p || compatible_p) && gl_kind)
1839 {
1840 /* [dcl.init.ref]
1841
1842 If the initializer expression
1843
1844 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1845 is reference-compatible with "cv2 T2,"
1846
1847 the reference is bound directly to the initializer expression
1848 lvalue.
1849
1850 [...]
1851 If the initializer expression is an rvalue, with T2 a class type,
1852 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1853 is bound to the object represented by the rvalue or to a sub-object
1854 within that object. */
1855
1856 conv = build_identity_conv (tfrom, expr);
1857 conv = direct_reference_binding (rto, conv);
1858
1859 if (TYPE_REF_P (rfrom))
1860 /* Handle rvalue reference to function properly. */
1861 conv->rvaluedness_matches_p
1862 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1863 else
1864 conv->rvaluedness_matches_p
1865 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1866
1867 if ((gl_kind & clk_bitfield) != 0
1868 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1869 /* For the purposes of overload resolution, we ignore the fact
1870 this expression is a bitfield or packed field. (In particular,
1871 [over.ics.ref] says specifically that a function with a
1872 non-const reference parameter is viable even if the
1873 argument is a bitfield.)
1874
1875 However, when we actually call the function we must create
1876 a temporary to which to bind the reference. If the
1877 reference is volatile, or isn't const, then we cannot make
1878 a temporary, so we just issue an error when the conversion
1879 actually occurs. */
1880 conv->need_temporary_p = true;
1881
1882 /* Don't allow binding of lvalues (other than function lvalues) to
1883 rvalue references. */
1884 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1885 && TREE_CODE (to) != FUNCTION_TYPE)
1886 conv->bad_p = true;
1887
1888 /* Nor the reverse. */
1889 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1890 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1891 But in C++23, such an expression is just an xvalue, not a special
1892 lvalue, so the binding is once again ill-formed. */
1893 && !(cxx_dialect <= cxx20
1894 && (gl_kind & clk_implicit_rval))
1895 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1896 || (flags & LOOKUP_NO_RVAL_BIND))
1897 && TREE_CODE (to) != FUNCTION_TYPE)
1898 conv->bad_p = true;
1899
1900 if (!compatible_p)
1901 conv->bad_p = true;
1902
1903 return conv;
1904 }
1905 /* [class.conv.fct] A conversion function is never used to convert a
1906 (possibly cv-qualified) object to the (possibly cv-qualified) same
1907 object type (or a reference to it), to a (possibly cv-qualified) base
1908 class of that type (or a reference to it).... */
1909 else if (CLASS_TYPE_P (from) && !related_p
1910 && !(flags & LOOKUP_NO_CONVERSION))
1911 {
1912 /* [dcl.init.ref]
1913
1914 If the initializer expression
1915
1916 -- has a class type (i.e., T2 is a class type) can be
1917 implicitly converted to an lvalue of type "cv3 T3," where
1918 "cv1 T1" is reference-compatible with "cv3 T3". (this
1919 conversion is selected by enumerating the applicable
1920 conversion functions (_over.match.ref_) and choosing the
1921 best one through overload resolution. (_over.match_).
1922
1923 the reference is bound to the lvalue result of the conversion
1924 in the second case. */
1925 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1926 complain);
1927 if (cand)
1928 return cand->second_conv;
1929 }
1930
1931 /* From this point on, we conceptually need temporaries, even if we
1932 elide them. Only the cases above are "direct bindings". */
1933 if (flags & LOOKUP_NO_TEMP_BIND)
1934 return NULL;
1935
1936 /* [over.ics.rank]
1937
1938 When a parameter of reference type is not bound directly to an
1939 argument expression, the conversion sequence is the one required
1940 to convert the argument expression to the underlying type of the
1941 reference according to _over.best.ics_. Conceptually, this
1942 conversion sequence corresponds to copy-initializing a temporary
1943 of the underlying type with the argument expression. Any
1944 difference in top-level cv-qualification is subsumed by the
1945 initialization itself and does not constitute a conversion. */
1946
1947 bool maybe_valid_p = true;
1948
1949 /* [dcl.init.ref]
1950
1951 Otherwise, the reference shall be an lvalue reference to a
1952 non-volatile const type, or the reference shall be an rvalue
1953 reference. */
1954 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1955 maybe_valid_p = false;
1956
1957 /* [dcl.init.ref]
1958
1959 Otherwise, a temporary of type "cv1 T1" is created and
1960 initialized from the initializer expression using the rules for a
1961 non-reference copy initialization. If T1 is reference-related to
1962 T2, cv1 must be the same cv-qualification as, or greater
1963 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1964 if (related_p && !at_least_as_qualified_p (to, from))
1965 maybe_valid_p = false;
1966
1967 /* We try below to treat an invalid reference binding as a bad conversion
1968 to improve diagnostics, but doing so may cause otherwise unnecessary
1969 instantiations that can lead to a hard error. So during the first pass
1970 of overload resolution wherein we shortcut bad conversions, instead just
1971 produce a special conversion indicating a second pass is necessary if
1972 there's no strictly viable candidate. */
1973 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1974 {
1975 conv = alloc_conversion (ck_deferred_bad);
1976 conv->bad_p = true;
1977 return conv;
1978 }
1979
1980 /* We're generating a temporary now, but don't bind any more in the
1981 conversion (specifically, don't slice the temporary returned by a
1982 conversion operator). */
1983 flags |= LOOKUP_NO_TEMP_BIND;
1984
1985 /* Core issue 899: When [copy-]initializing a temporary to be bound
1986 to the first parameter of a copy constructor (12.8) called with
1987 a single argument in the context of direct-initialization,
1988 explicit conversion functions are also considered.
1989
1990 So don't set LOOKUP_ONLYCONVERTING in that case. */
1991 if (!(flags & LOOKUP_COPY_PARM))
1992 flags |= LOOKUP_ONLYCONVERTING;
1993
1994 if (!conv)
1995 conv = implicit_conversion (to, from, expr, c_cast_p,
1996 flags, complain);
1997 if (!conv)
1998 return NULL;
1999
2000 if (conv->user_conv_p)
2001 {
2002 if (copy_list_init)
2003 /* Remember this was copy-list-initialization. */
2004 conv->need_temporary_p = true;
2005
2006 /* If initializing the temporary used a conversion function,
2007 recalculate the second conversion sequence. */
2008 for (conversion *t = conv; t; t = next_conversion (t))
2009 if (t->kind == ck_user
2010 && DECL_CONV_FN_P (t->cand->fn))
2011 {
2012 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2013 /* A prvalue of non-class type is cv-unqualified. */
2014 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2015 ftype = cv_unqualified (ftype);
2016 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2017 conversion *new_second
2018 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2019 sflags, complain);
2020 if (!new_second)
2021 return NULL;
2022 conv = merge_conversion_sequences (t, new_second);
2023 gcc_assert (maybe_valid_p || conv->bad_p);
2024 return conv;
2025 }
2026 }
2027
2028 conv = build_conv (ck_ref_bind, rto, conv);
2029 /* This reference binding, unlike those above, requires the
2030 creation of a temporary. */
2031 conv->need_temporary_p = true;
2032 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2033 conv->bad_p |= !maybe_valid_p;
2034
2035 return conv;
2036 }
2037
2038 /* Returns the implicit conversion sequence (see [over.ics]) from type
2039 FROM to type TO. The optional expression EXPR may affect the
2040 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2041 true, this conversion is coming from a C-style cast. */
2042
2043 static conversion *
2044 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2045 int flags, tsubst_flags_t complain)
2046 {
2047 conversion *conv;
2048
2049 if (from == error_mark_node || to == error_mark_node
2050 || expr == error_mark_node)
2051 return NULL;
2052
2053 /* Other flags only apply to the primary function in overload
2054 resolution, or after we've chosen one. */
2055 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2056 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2057 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2058
2059 /* FIXME: actually we don't want warnings either, but we can't just
2060 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2061 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2062 We really ought not to issue that warning until we've committed
2063 to that conversion. */
2064 complain &= ~tf_error;
2065
2066 /* Call reshape_init early to remove redundant braces. */
2067 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2068 {
2069 to = complete_type (to);
2070 if (!COMPLETE_TYPE_P (to))
2071 return nullptr;
2072 if (!CLASSTYPE_NON_AGGREGATE (to))
2073 {
2074 expr = reshape_init (to, expr, complain);
2075 if (expr == error_mark_node)
2076 return nullptr;
2077 from = TREE_TYPE (expr);
2078 }
2079 }
2080
2081 if (TYPE_REF_P (to))
2082 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2083 else
2084 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2085
2086 if (conv)
2087 return conv;
2088
2089 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2090 {
2091 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2092 return build_list_conv (to, expr, flags, complain);
2093
2094 /* As an extension, allow list-initialization of _Complex. */
2095 if (TREE_CODE (to) == COMPLEX_TYPE
2096 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2097 {
2098 conv = build_complex_conv (to, expr, flags, complain);
2099 if (conv)
2100 return conv;
2101 }
2102
2103 /* Allow conversion from an initializer-list with one element to a
2104 scalar type. */
2105 if (SCALAR_TYPE_P (to))
2106 {
2107 int nelts = CONSTRUCTOR_NELTS (expr);
2108 tree elt;
2109
2110 if (nelts == 0)
2111 elt = build_value_init (to, tf_none);
2112 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2113 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2114 else
2115 elt = error_mark_node;
2116
2117 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2118 c_cast_p, flags, complain);
2119 if (conv)
2120 {
2121 conv->check_narrowing = true;
2122 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2123 /* Too many levels of braces, i.e. '{{1}}'. */
2124 conv->bad_p = true;
2125 return conv;
2126 }
2127 }
2128 else if (TREE_CODE (to) == ARRAY_TYPE)
2129 return build_array_conv (to, expr, flags, complain);
2130 }
2131
2132 if (expr != NULL_TREE
2133 && (MAYBE_CLASS_TYPE_P (from)
2134 || MAYBE_CLASS_TYPE_P (to))
2135 && (flags & LOOKUP_NO_CONVERSION) == 0)
2136 {
2137 struct z_candidate *cand;
2138
2139 if (CLASS_TYPE_P (to)
2140 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2141 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2142 return build_aggr_conv (to, expr, flags, complain);
2143
2144 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2145 if (cand)
2146 {
2147 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2148 && CONSTRUCTOR_NELTS (expr) == 1
2149 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2150 && !is_list_ctor (cand->fn))
2151 {
2152 /* "If C is not an initializer-list constructor and the
2153 initializer list has a single element of type cv U, where U is
2154 X or a class derived from X, the implicit conversion sequence
2155 has Exact Match rank if U is X, or Conversion rank if U is
2156 derived from X." */
2157 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2158 tree elttype = TREE_TYPE (elt);
2159 if (reference_related_p (to, elttype))
2160 return implicit_conversion (to, elttype, elt,
2161 c_cast_p, flags, complain);
2162 }
2163 conv = cand->second_conv;
2164 }
2165
2166 /* We used to try to bind a reference to a temporary here, but that
2167 is now handled after the recursive call to this function at the end
2168 of reference_binding. */
2169 return conv;
2170 }
2171
2172 return NULL;
2173 }
2174
2175 /* Like implicit_conversion, but return NULL if the conversion is bad.
2176
2177 This is not static so that check_non_deducible_conversion can call it within
2178 add_template_candidate_real as part of overload resolution; it should not be
2179 called outside of overload resolution. */
2180
2181 conversion *
2182 good_conversion (tree to, tree from, tree expr,
2183 int flags, tsubst_flags_t complain)
2184 {
2185 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2186 flags, complain);
2187 if (c && c->bad_p)
2188 c = NULL;
2189 return c;
2190 }
2191
2192 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2193 functions. ARGS will not be changed until a single candidate is
2194 selected. */
2195
2196 static struct z_candidate *
2197 add_candidate (struct z_candidate **candidates,
2198 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2199 size_t num_convs, conversion **convs,
2200 tree access_path, tree conversion_path,
2201 int viable, struct rejection_reason *reason,
2202 int flags)
2203 {
2204 struct z_candidate *cand = (struct z_candidate *)
2205 conversion_obstack_alloc (sizeof (struct z_candidate));
2206
2207 cand->fn = fn;
2208 cand->first_arg = first_arg;
2209 cand->args = args;
2210 cand->convs = convs;
2211 cand->num_convs = num_convs;
2212 cand->access_path = access_path;
2213 cand->conversion_path = conversion_path;
2214 cand->viable = viable;
2215 cand->reason = reason;
2216 cand->next = *candidates;
2217 cand->flags = flags;
2218 *candidates = cand;
2219
2220 if (convs && cand->reversed ())
2221 /* Swap the conversions for comparison in joust; we'll swap them back
2222 before build_over_call. */
2223 std::swap (convs[0], convs[1]);
2224
2225 return cand;
2226 }
2227
2228 /* FN is a function from the overload set that we outright didn't even
2229 consider (for some reason); add it to the list as an non-viable "ignored"
2230 candidate. */
2231
2232 static z_candidate *
2233 add_ignored_candidate (z_candidate **candidates, tree fn)
2234 {
2235 /* No need to dynamically allocate these. */
2236 static const rejection_reason reason_ignored = { rr_ignored, {} };
2237
2238 struct z_candidate *cand = (struct z_candidate *)
2239 conversion_obstack_alloc (sizeof (struct z_candidate));
2240
2241 cand->fn = fn;
2242 cand->reason = const_cast<rejection_reason *> (&reason_ignored);
2243 cand->next = *candidates;
2244 *candidates = cand;
2245
2246 return cand;
2247 }
2248
2249 /* True iff CAND is a candidate added by add_ignored_candidate. */
2250
2251 static bool
2252 ignored_candidate_p (const z_candidate *cand)
2253 {
2254 return cand->reason && cand->reason->code == rr_ignored;
2255 }
2256
2257 /* Return the number of remaining arguments in the parameter list
2258 beginning with ARG. */
2259
2260 int
2261 remaining_arguments (tree arg)
2262 {
2263 int n;
2264
2265 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2266 arg = TREE_CHAIN (arg))
2267 n++;
2268
2269 return n;
2270 }
2271
2272 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2273 to the first parameter of a constructor where the parameter is of type
2274 "reference to possibly cv-qualified T" and the constructor is called with a
2275 single argument in the context of direct-initialization of an object of type
2276 "cv2 T", explicit conversion functions are also considered.
2277
2278 So set LOOKUP_COPY_PARM to let reference_binding know that
2279 it's being called in that context. */
2280
2281 int
2282 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2283 {
2284 int lflags = flags;
2285 tree t;
2286 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2287 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2288 && (same_type_ignoring_top_level_qualifiers_p
2289 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2290 {
2291 if (!(flags & LOOKUP_ONLYCONVERTING))
2292 lflags |= LOOKUP_COPY_PARM;
2293 if ((flags & LOOKUP_LIST_INIT_CTOR)
2294 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2295 lflags |= LOOKUP_NO_CONVERSION;
2296 }
2297 else
2298 lflags |= LOOKUP_ONLYCONVERTING;
2299
2300 return lflags;
2301 }
2302
2303 /* Build an appropriate 'this' conversion for the method FN and class
2304 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2305 This function modifies PARMTYPE, ARGTYPE and ARG. */
2306
2307 static conversion *
2308 build_this_conversion (tree fn, tree ctype,
2309 tree& parmtype, tree& argtype, tree& arg,
2310 int flags, tsubst_flags_t complain)
2311 {
2312 gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2313 && !DECL_CONSTRUCTOR_P (fn));
2314
2315 /* The type of the implicit object parameter ('this') for
2316 overload resolution is not always the same as for the
2317 function itself; conversion functions are considered to
2318 be members of the class being converted, and functions
2319 introduced by a using-declaration are considered to be
2320 members of the class that uses them.
2321
2322 Since build_over_call ignores the ICS for the `this'
2323 parameter, we can just change the parm type. */
2324 parmtype = cp_build_qualified_type (ctype,
2325 cp_type_quals (TREE_TYPE (parmtype)));
2326 bool this_p = true;
2327 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2328 {
2329 /* If the function has a ref-qualifier, the implicit
2330 object parameter has reference type. */
2331 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2332 parmtype = cp_build_reference_type (parmtype, rv);
2333 /* The special handling of 'this' conversions in compare_ics
2334 does not apply if there is a ref-qualifier. */
2335 this_p = false;
2336 }
2337 else
2338 {
2339 parmtype = build_pointer_type (parmtype);
2340 /* We don't use build_this here because we don't want to
2341 capture the object argument until we've chosen a
2342 non-static member function. */
2343 arg = build_address (arg);
2344 argtype = lvalue_type (arg);
2345 }
2346 flags |= LOOKUP_ONLYCONVERTING;
2347 conversion *t = implicit_conversion (parmtype, argtype, arg,
2348 /*c_cast_p=*/false, flags, complain);
2349 t->this_p = this_p;
2350 return t;
2351 }
2352
2353 /* Create an overload candidate for the function or method FN called
2354 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2355 FLAGS is passed on to implicit_conversion.
2356
2357 This does not change ARGS.
2358
2359 CTYPE, if non-NULL, is the type we want to pretend this function
2360 comes from for purposes of overload resolution.
2361
2362 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2363 If true, we stop computing conversions upon seeing the first bad
2364 conversion. This is used by add_candidates to avoid computing
2365 more conversions than necessary in the presence of a strictly viable
2366 candidate, while preserving the defacto behavior of overload resolution
2367 when it turns out there are only non-strictly viable candidates. */
2368
2369 static struct z_candidate *
2370 add_function_candidate (struct z_candidate **candidates,
2371 tree fn, tree ctype, tree first_arg,
2372 const vec<tree, va_gc> *args, tree access_path,
2373 tree conversion_path, int flags,
2374 conversion **convs,
2375 bool shortcut_bad_convs,
2376 tsubst_flags_t complain)
2377 {
2378 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2379 int i, len;
2380 tree parmnode;
2381 tree orig_first_arg = first_arg;
2382 int skip;
2383 int viable = 1;
2384 struct rejection_reason *reason = NULL;
2385
2386 /* The `this', `in_chrg' and VTT arguments to constructors are not
2387 considered in overload resolution. */
2388 if (DECL_CONSTRUCTOR_P (fn))
2389 {
2390 if (ctor_omit_inherited_parms (fn))
2391 /* Bring back parameters omitted from an inherited ctor. */
2392 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2393 else
2394 parmlist = skip_artificial_parms_for (fn, parmlist);
2395 skip = num_artificial_parms_for (fn);
2396 if (skip > 0 && first_arg != NULL_TREE)
2397 {
2398 --skip;
2399 first_arg = NULL_TREE;
2400 }
2401 }
2402 else
2403 skip = 0;
2404
2405 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2406 if (!convs)
2407 convs = alloc_conversions (len);
2408
2409 /* 13.3.2 - Viable functions [over.match.viable]
2410 First, to be a viable function, a candidate function shall have enough
2411 parameters to agree in number with the arguments in the list.
2412
2413 We need to check this first; otherwise, checking the ICSes might cause
2414 us to produce an ill-formed template instantiation. */
2415
2416 parmnode = parmlist;
2417 for (i = 0; i < len; ++i)
2418 {
2419 if (parmnode == NULL_TREE || parmnode == void_list_node)
2420 break;
2421 parmnode = TREE_CHAIN (parmnode);
2422 }
2423
2424 if ((i < len && parmnode)
2425 || !sufficient_parms_p (parmnode))
2426 {
2427 int remaining = remaining_arguments (parmnode);
2428 viable = 0;
2429 reason = arity_rejection (first_arg, i + remaining, len);
2430 }
2431
2432 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2433 parameter of type "reference to cv C" (including such a constructor
2434 instantiated from a template) is excluded from the set of candidate
2435 functions when used to construct an object of type D with an argument list
2436 containing a single argument if C is reference-related to D. */
2437 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2438 && flag_new_inheriting_ctors
2439 && DECL_INHERITED_CTOR (fn))
2440 {
2441 tree ptype = non_reference (TREE_VALUE (parmlist));
2442 tree dtype = DECL_CONTEXT (fn);
2443 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2444 if (reference_related_p (ptype, dtype)
2445 && reference_related_p (btype, ptype))
2446 {
2447 viable = false;
2448 reason = inherited_ctor_rejection ();
2449 }
2450 }
2451
2452 /* Second, for a function to be viable, its constraints must be
2453 satisfied. */
2454 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2455 {
2456 reason = constraint_failure ();
2457 viable = false;
2458 }
2459
2460 /* When looking for a function from a subobject from an implicit
2461 copy/move constructor/operator=, don't consider anything that takes (a
2462 reference to) an unrelated type. See c++/44909 and core 1092. */
2463 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2464 {
2465 if (DECL_CONSTRUCTOR_P (fn))
2466 i = 1;
2467 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2468 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2469 i = 2;
2470 else
2471 i = 0;
2472 if (i && len == i)
2473 {
2474 parmnode = chain_index (i-1, parmlist);
2475 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2476 ctype))
2477 viable = 0;
2478 }
2479
2480 /* This only applies at the top level. */
2481 flags &= ~LOOKUP_DEFAULTED;
2482 }
2483
2484 if (! viable)
2485 goto out;
2486
2487 if (shortcut_bad_convs)
2488 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2489 else
2490 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2491
2492 /* Third, for F to be a viable function, there shall exist for each
2493 argument an implicit conversion sequence that converts that argument
2494 to the corresponding parameter of F. */
2495
2496 parmnode = parmlist;
2497
2498 for (i = 0; i < len; ++i)
2499 {
2500 tree argtype, to_type;
2501 tree arg;
2502
2503 if (parmnode == void_list_node)
2504 break;
2505
2506 if (convs[i])
2507 {
2508 /* Already set during deduction. */
2509 parmnode = TREE_CHAIN (parmnode);
2510 continue;
2511 }
2512
2513 if (i == 0 && first_arg != NULL_TREE)
2514 arg = first_arg;
2515 else
2516 arg = CONST_CAST_TREE (
2517 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2518 argtype = lvalue_type (arg);
2519
2520 conversion *t;
2521 if (parmnode)
2522 {
2523 tree parmtype = TREE_VALUE (parmnode);
2524 if (i == 0
2525 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2526 && !DECL_CONSTRUCTOR_P (fn))
2527 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2528 flags, complain);
2529 else
2530 {
2531 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2532 t = implicit_conversion (parmtype, argtype, arg,
2533 /*c_cast_p=*/false, lflags, complain);
2534 }
2535 to_type = parmtype;
2536 parmnode = TREE_CHAIN (parmnode);
2537 }
2538 else
2539 {
2540 t = build_identity_conv (argtype, arg);
2541 t->ellipsis_p = true;
2542 to_type = argtype;
2543 }
2544
2545 convs[i] = t;
2546 if (! t)
2547 {
2548 viable = 0;
2549 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2550 EXPR_LOCATION (arg));
2551 break;
2552 }
2553
2554 if (t->bad_p)
2555 {
2556 viable = -1;
2557 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2558 EXPR_LOCATION (arg));
2559 if (shortcut_bad_convs)
2560 break;
2561 }
2562 }
2563
2564 out:
2565 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2566 access_path, conversion_path, viable, reason, flags);
2567 }
2568
2569 /* Create an overload candidate for the conversion function FN which will
2570 be invoked for expression OBJ, producing a pointer-to-function which
2571 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2572 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2573 passed on to implicit_conversion.
2574
2575 Actually, we don't really care about FN; we care about the type it
2576 converts to. There may be multiple conversion functions that will
2577 convert to that type, and we rely on build_user_type_conversion_1 to
2578 choose the best one; so when we create our candidate, we record the type
2579 instead of the function. */
2580
2581 static struct z_candidate *
2582 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2583 const vec<tree, va_gc> *arglist,
2584 tree access_path, tree conversion_path,
2585 tsubst_flags_t complain)
2586 {
2587 tree totype = TREE_TYPE (TREE_TYPE (fn));
2588 int i, len, viable, flags;
2589 tree parmlist, parmnode;
2590 conversion **convs;
2591 struct rejection_reason *reason;
2592
2593 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2594 parmlist = TREE_TYPE (parmlist);
2595 parmlist = TYPE_ARG_TYPES (parmlist);
2596
2597 len = vec_safe_length (arglist) + 1;
2598 convs = alloc_conversions (len);
2599 parmnode = parmlist;
2600 viable = 1;
2601 flags = LOOKUP_IMPLICIT;
2602 reason = NULL;
2603
2604 /* Don't bother looking up the same type twice. */
2605 if (*candidates && (*candidates)->fn == totype)
2606 return NULL;
2607
2608 if (!constraints_satisfied_p (fn))
2609 {
2610 reason = constraint_failure ();
2611 viable = 0;
2612 return add_candidate (candidates, fn, obj, arglist, len, convs,
2613 access_path, conversion_path, viable, reason, flags);
2614 }
2615
2616 for (i = 0; i < len; ++i)
2617 {
2618 tree arg, argtype, convert_type = NULL_TREE;
2619 conversion *t;
2620
2621 if (i == 0)
2622 arg = obj;
2623 else
2624 arg = (*arglist)[i - 1];
2625 argtype = lvalue_type (arg);
2626
2627 if (i == 0)
2628 {
2629 t = build_identity_conv (argtype, NULL_TREE);
2630 t = build_conv (ck_user, totype, t);
2631 /* Leave the 'cand' field null; we'll figure out the conversion in
2632 convert_like if this candidate is chosen. */
2633 convert_type = totype;
2634 }
2635 else if (parmnode == void_list_node)
2636 break;
2637 else if (parmnode)
2638 {
2639 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2640 /*c_cast_p=*/false, flags, complain);
2641 convert_type = TREE_VALUE (parmnode);
2642 }
2643 else
2644 {
2645 t = build_identity_conv (argtype, arg);
2646 t->ellipsis_p = true;
2647 convert_type = argtype;
2648 }
2649
2650 convs[i] = t;
2651 if (! t)
2652 break;
2653
2654 if (t->bad_p)
2655 {
2656 viable = -1;
2657 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2658 EXPR_LOCATION (arg));
2659 }
2660
2661 if (i == 0)
2662 continue;
2663
2664 if (parmnode)
2665 parmnode = TREE_CHAIN (parmnode);
2666 }
2667
2668 if (i < len
2669 || ! sufficient_parms_p (parmnode))
2670 {
2671 int remaining = remaining_arguments (parmnode);
2672 viable = 0;
2673 reason = arity_rejection (NULL_TREE, i + remaining, len);
2674 }
2675
2676 return add_candidate (candidates, totype, obj, arglist, len, convs,
2677 access_path, conversion_path, viable, reason, flags);
2678 }
2679
2680 static void
2681 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2682 tree type1, tree type2, const vec<tree,va_gc> &args,
2683 tree *argtypes, int flags, tsubst_flags_t complain)
2684 {
2685 conversion *t;
2686 conversion **convs;
2687 size_t num_convs;
2688 int viable = 1;
2689 tree types[2];
2690 struct rejection_reason *reason = NULL;
2691
2692 types[0] = type1;
2693 types[1] = type2;
2694
2695 num_convs = args.length ();
2696 convs = alloc_conversions (num_convs);
2697
2698 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2699 conversion ops are allowed. We handle that here by just checking for
2700 boolean_type_node because other operators don't ask for it. COND_EXPR
2701 also does contextual conversion to bool for the first operand, but we
2702 handle that in build_conditional_expr, and type1 here is operand 2. */
2703 if (type1 != boolean_type_node)
2704 flags |= LOOKUP_ONLYCONVERTING;
2705
2706 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2707 {
2708 t = implicit_conversion (types[i], argtypes[i], args[i],
2709 /*c_cast_p=*/false, flags, complain);
2710 if (! t)
2711 {
2712 viable = 0;
2713 /* We need something for printing the candidate. */
2714 t = build_identity_conv (types[i], NULL_TREE);
2715 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2716 types[i], EXPR_LOCATION (args[i]));
2717 }
2718 else if (t->bad_p)
2719 {
2720 viable = 0;
2721 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2722 types[i],
2723 EXPR_LOCATION (args[i]));
2724 }
2725 convs[i] = t;
2726 }
2727
2728 /* For COND_EXPR we rearranged the arguments; undo that now. */
2729 if (num_convs == 3)
2730 {
2731 convs[2] = convs[1];
2732 convs[1] = convs[0];
2733 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2734 /*c_cast_p=*/false, flags,
2735 complain);
2736 if (t)
2737 convs[0] = t;
2738 else
2739 {
2740 viable = 0;
2741 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2742 boolean_type_node,
2743 EXPR_LOCATION (args[2]));
2744 }
2745 }
2746
2747 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2748 num_convs, convs,
2749 /*access_path=*/NULL_TREE,
2750 /*conversion_path=*/NULL_TREE,
2751 viable, reason, flags);
2752 }
2753
2754 static bool
2755 is_complete (tree t)
2756 {
2757 return COMPLETE_TYPE_P (complete_type (t));
2758 }
2759
2760 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2761
2762 static bool
2763 promoted_arithmetic_type_p (tree type)
2764 {
2765 /* [over.built]
2766
2767 In this section, the term promoted integral type is used to refer
2768 to those integral types which are preserved by integral promotion
2769 (including e.g. int and long but excluding e.g. char).
2770 Similarly, the term promoted arithmetic type refers to promoted
2771 integral types plus floating types. */
2772 return ((CP_INTEGRAL_TYPE_P (type)
2773 && same_type_p (type_promotes_to (type), type))
2774 || SCALAR_FLOAT_TYPE_P (type));
2775 }
2776
2777 /* Create any builtin operator overload candidates for the operator in
2778 question given the converted operand types TYPE1 and TYPE2. The other
2779 args are passed through from add_builtin_candidates to
2780 build_builtin_candidate.
2781
2782 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2783 If CODE is requires candidates operands of the same type of the kind
2784 of which TYPE1 and TYPE2 are, we add both candidates
2785 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2786
2787 static void
2788 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2789 enum tree_code code2, tree fnname, tree type1,
2790 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2791 int flags, tsubst_flags_t complain)
2792 {
2793 switch (code)
2794 {
2795 case POSTINCREMENT_EXPR:
2796 case POSTDECREMENT_EXPR:
2797 args[1] = integer_zero_node;
2798 type2 = integer_type_node;
2799 break;
2800 default:
2801 break;
2802 }
2803
2804 switch (code)
2805 {
2806
2807 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2808 and VQ is either volatile or empty, there exist candidate operator
2809 functions of the form
2810 VQ T& operator++(VQ T&);
2811 T operator++(VQ T&, int);
2812 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2813 and VQ is either volatile or empty, there exist candidate operator
2814 functions of the form
2815 VQ T& operator--(VQ T&);
2816 T operator--(VQ T&, int);
2817 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2818 type, and VQ is either volatile or empty, there exist candidate operator
2819 functions of the form
2820 T*VQ& operator++(T*VQ&);
2821 T*VQ& operator--(T*VQ&);
2822 T* operator++(T*VQ&, int);
2823 T* operator--(T*VQ&, int); */
2824
2825 case POSTDECREMENT_EXPR:
2826 case PREDECREMENT_EXPR:
2827 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2828 return;
2829 /* FALLTHRU */
2830 case POSTINCREMENT_EXPR:
2831 case PREINCREMENT_EXPR:
2832 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2833 to p4. */
2834 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2835 return;
2836 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2837 {
2838 type1 = build_reference_type (type1);
2839 break;
2840 }
2841 return;
2842
2843 /* 7 For every cv-qualified or cv-unqualified object type T, there
2844 exist candidate operator functions of the form
2845
2846 T& operator*(T*);
2847
2848
2849 8 For every function type T that does not have cv-qualifiers or
2850 a ref-qualifier, there exist candidate operator functions of the form
2851 T& operator*(T*); */
2852
2853 case INDIRECT_REF:
2854 if (TYPE_PTR_P (type1)
2855 && (TYPE_PTROB_P (type1)
2856 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2857 break;
2858 return;
2859
2860 /* 9 For every type T, there exist candidate operator functions of the form
2861 T* operator+(T*);
2862
2863 10 For every floating-point or promoted integral type T, there exist
2864 candidate operator functions of the form
2865 T operator+(T);
2866 T operator-(T); */
2867
2868 case UNARY_PLUS_EXPR: /* unary + */
2869 if (TYPE_PTR_P (type1))
2870 break;
2871 /* FALLTHRU */
2872 case NEGATE_EXPR:
2873 if (ARITHMETIC_TYPE_P (type1))
2874 break;
2875 return;
2876
2877 /* 11 For every promoted integral type T, there exist candidate operator
2878 functions of the form
2879 T operator~(T); */
2880
2881 case BIT_NOT_EXPR:
2882 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2883 break;
2884 return;
2885
2886 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2887 is the same type as C2 or is a derived class of C2, and T is an object
2888 type or a function type there exist candidate operator functions of the
2889 form
2890 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2891 where CV12 is the union of CV1 and CV2. */
2892
2893 case MEMBER_REF:
2894 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2895 {
2896 tree c1 = TREE_TYPE (type1);
2897 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2898
2899 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2900 && (TYPE_PTRMEMFUNC_P (type2)
2901 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2902 break;
2903 }
2904 return;
2905
2906 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2907 or promoted integral type, there exist candidate operator functions of the
2908 form
2909 LR operator*(L, R);
2910 LR operator/(L, R);
2911 LR operator+(L, R);
2912 LR operator-(L, R);
2913 bool operator<(L, R);
2914 bool operator>(L, R);
2915 bool operator<=(L, R);
2916 bool operator>=(L, R);
2917 bool operator==(L, R);
2918 bool operator!=(L, R);
2919 where LR is the result of the usual arithmetic conversions between
2920 types L and R.
2921
2922 14 For every integral type T there exists a candidate operator function of
2923 the form
2924
2925 std::strong_ordering operator<=>(T, T);
2926
2927 15 For every pair of floating-point types L and R, there exists a candidate
2928 operator function of the form
2929
2930 std::partial_ordering operator<=>(L, R);
2931
2932 16 For every cv-qualified or cv-unqualified object type T there exist
2933 candidate operator functions of the form
2934 T* operator+(T*, std::ptrdiff_t);
2935 T& operator[](T*, std::ptrdiff_t);
2936 T* operator-(T*, std::ptrdiff_t);
2937 T* operator+(std::ptrdiff_t, T*);
2938 T& operator[](std::ptrdiff_t, T*);
2939
2940 17 For every T, where T is a pointer to object type, there exist candidate
2941 operator functions of the form
2942 std::ptrdiff_t operator-(T, T);
2943
2944 18 For every T, where T is an enumeration type or a pointer type, there
2945 exist candidate operator functions of the form
2946 bool operator<(T, T);
2947 bool operator>(T, T);
2948 bool operator<=(T, T);
2949 bool operator>=(T, T);
2950 bool operator==(T, T);
2951 bool operator!=(T, T);
2952 R operator<=>(T, T);
2953
2954 where R is the result type specified in [expr.spaceship].
2955
2956 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2957 there exist candidate operator functions of the form
2958 bool operator==(T, T);
2959 bool operator!=(T, T); */
2960
2961 case MINUS_EXPR:
2962 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2963 break;
2964 if (TYPE_PTROB_P (type1)
2965 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2966 {
2967 type2 = ptrdiff_type_node;
2968 break;
2969 }
2970 /* FALLTHRU */
2971 case MULT_EXPR:
2972 case TRUNC_DIV_EXPR:
2973 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2974 break;
2975 return;
2976
2977 /* This isn't exactly what's specified above for operator<=>, but it's
2978 close enough. In particular, we don't care about the return type
2979 specified above; it doesn't participate in overload resolution and it
2980 doesn't affect the semantics of the built-in operator. */
2981 case SPACESHIP_EXPR:
2982 case EQ_EXPR:
2983 case NE_EXPR:
2984 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2985 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2986 break;
2987 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2988 break;
2989 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2990 {
2991 type2 = type1;
2992 break;
2993 }
2994 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2995 {
2996 type1 = type2;
2997 break;
2998 }
2999 /* Fall through. */
3000 case LT_EXPR:
3001 case GT_EXPR:
3002 case LE_EXPR:
3003 case GE_EXPR:
3004 case MAX_EXPR:
3005 case MIN_EXPR:
3006 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3007 break;
3008 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3009 break;
3010 if (TREE_CODE (type1) == ENUMERAL_TYPE
3011 && TREE_CODE (type2) == ENUMERAL_TYPE)
3012 break;
3013 if (TYPE_PTR_P (type1)
3014 && null_ptr_cst_p (args[1]))
3015 {
3016 type2 = type1;
3017 break;
3018 }
3019 if (null_ptr_cst_p (args[0])
3020 && TYPE_PTR_P (type2))
3021 {
3022 type1 = type2;
3023 break;
3024 }
3025 return;
3026
3027 case PLUS_EXPR:
3028 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3029 break;
3030 /* FALLTHRU */
3031 case ARRAY_REF:
3032 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3033 {
3034 type1 = ptrdiff_type_node;
3035 break;
3036 }
3037 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3038 {
3039 type2 = ptrdiff_type_node;
3040 break;
3041 }
3042 return;
3043
3044 /* 18For every pair of promoted integral types L and R, there exist candi-
3045 date operator functions of the form
3046 LR operator%(L, R);
3047 LR operator&(L, R);
3048 LR operator^(L, R);
3049 LR operator|(L, R);
3050 L operator<<(L, R);
3051 L operator>>(L, R);
3052 where LR is the result of the usual arithmetic conversions between
3053 types L and R. */
3054
3055 case TRUNC_MOD_EXPR:
3056 case BIT_AND_EXPR:
3057 case BIT_IOR_EXPR:
3058 case BIT_XOR_EXPR:
3059 case LSHIFT_EXPR:
3060 case RSHIFT_EXPR:
3061 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3062 break;
3063 return;
3064
3065 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3066 type, VQ is either volatile or empty, and R is a promoted arithmetic
3067 type, there exist candidate operator functions of the form
3068 VQ L& operator=(VQ L&, R);
3069 VQ L& operator*=(VQ L&, R);
3070 VQ L& operator/=(VQ L&, R);
3071 VQ L& operator+=(VQ L&, R);
3072 VQ L& operator-=(VQ L&, R);
3073
3074 20For every pair T, VQ), where T is any type and VQ is either volatile
3075 or empty, there exist candidate operator functions of the form
3076 T*VQ& operator=(T*VQ&, T*);
3077
3078 21For every pair T, VQ), where T is a pointer to member type and VQ is
3079 either volatile or empty, there exist candidate operator functions of
3080 the form
3081 VQ T& operator=(VQ T&, T);
3082
3083 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3084 unqualified complete object type, VQ is either volatile or empty, and
3085 I is a promoted integral type, there exist candidate operator func-
3086 tions of the form
3087 T*VQ& operator+=(T*VQ&, I);
3088 T*VQ& operator-=(T*VQ&, I);
3089
3090 23For every triple L, VQ, R), where L is an integral or enumeration
3091 type, VQ is either volatile or empty, and R is a promoted integral
3092 type, there exist candidate operator functions of the form
3093
3094 VQ L& operator%=(VQ L&, R);
3095 VQ L& operator<<=(VQ L&, R);
3096 VQ L& operator>>=(VQ L&, R);
3097 VQ L& operator&=(VQ L&, R);
3098 VQ L& operator^=(VQ L&, R);
3099 VQ L& operator|=(VQ L&, R); */
3100
3101 case MODIFY_EXPR:
3102 switch (code2)
3103 {
3104 case PLUS_EXPR:
3105 case MINUS_EXPR:
3106 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3107 {
3108 type2 = ptrdiff_type_node;
3109 break;
3110 }
3111 /* FALLTHRU */
3112 case MULT_EXPR:
3113 case TRUNC_DIV_EXPR:
3114 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3115 break;
3116 return;
3117
3118 case TRUNC_MOD_EXPR:
3119 case BIT_AND_EXPR:
3120 case BIT_IOR_EXPR:
3121 case BIT_XOR_EXPR:
3122 case LSHIFT_EXPR:
3123 case RSHIFT_EXPR:
3124 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3125 break;
3126 return;
3127
3128 case NOP_EXPR:
3129 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3130 break;
3131 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3132 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3133 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3134 || ((TYPE_PTRMEMFUNC_P (type1)
3135 || TYPE_PTR_P (type1))
3136 && null_ptr_cst_p (args[1])))
3137 {
3138 type2 = type1;
3139 break;
3140 }
3141 return;
3142
3143 default:
3144 gcc_unreachable ();
3145 }
3146 type1 = build_reference_type (type1);
3147 break;
3148
3149 case COND_EXPR:
3150 /* [over.built]
3151
3152 For every pair of promoted arithmetic types L and R, there
3153 exist candidate operator functions of the form
3154
3155 LR operator?(bool, L, R);
3156
3157 where LR is the result of the usual arithmetic conversions
3158 between types L and R.
3159
3160 For every type T, where T is a pointer or pointer-to-member
3161 type, there exist candidate operator functions of the form T
3162 operator?(bool, T, T); */
3163
3164 if (promoted_arithmetic_type_p (type1)
3165 && promoted_arithmetic_type_p (type2))
3166 /* That's OK. */
3167 break;
3168
3169 /* Otherwise, the types should be pointers. */
3170 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3171 return;
3172
3173 /* We don't check that the two types are the same; the logic
3174 below will actually create two candidates; one in which both
3175 parameter types are TYPE1, and one in which both parameter
3176 types are TYPE2. */
3177 break;
3178
3179 case REALPART_EXPR:
3180 case IMAGPART_EXPR:
3181 if (ARITHMETIC_TYPE_P (type1))
3182 break;
3183 return;
3184
3185 default:
3186 gcc_unreachable ();
3187 }
3188
3189 /* Make sure we don't create builtin candidates with dependent types. */
3190 bool u1 = uses_template_parms (type1);
3191 bool u2 = type2 ? uses_template_parms (type2) : false;
3192 if (u1 || u2)
3193 {
3194 /* Try to recover if one of the types is non-dependent. But if
3195 there's only one type, there's nothing we can do. */
3196 if (!type2)
3197 return;
3198 /* And we lose if both are dependent. */
3199 if (u1 && u2)
3200 return;
3201 /* Or if they have different forms. */
3202 if (TREE_CODE (type1) != TREE_CODE (type2))
3203 return;
3204
3205 if (u1 && !u2)
3206 type1 = type2;
3207 else if (u2 && !u1)
3208 type2 = type1;
3209 }
3210
3211 /* If we're dealing with two pointer types or two enumeral types,
3212 we need candidates for both of them. */
3213 if (type2 && !same_type_p (type1, type2)
3214 && TREE_CODE (type1) == TREE_CODE (type2)
3215 && (TYPE_REF_P (type1)
3216 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3217 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3218 || TYPE_PTRMEMFUNC_P (type1)
3219 || MAYBE_CLASS_TYPE_P (type1)
3220 || TREE_CODE (type1) == ENUMERAL_TYPE))
3221 {
3222 if (TYPE_PTR_OR_PTRMEM_P (type1))
3223 {
3224 tree cptype = composite_pointer_type (input_location,
3225 type1, type2,
3226 error_mark_node,
3227 error_mark_node,
3228 CPO_CONVERSION,
3229 tf_none);
3230 if (cptype != error_mark_node)
3231 {
3232 build_builtin_candidate
3233 (candidates, fnname, cptype, cptype, args, argtypes,
3234 flags, complain);
3235 return;
3236 }
3237 }
3238
3239 build_builtin_candidate
3240 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3241 build_builtin_candidate
3242 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3243 return;
3244 }
3245
3246 build_builtin_candidate
3247 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3248 }
3249
3250 tree
3251 type_decays_to (tree type)
3252 {
3253 if (TREE_CODE (type) == ARRAY_TYPE)
3254 return build_pointer_type (TREE_TYPE (type));
3255 if (TREE_CODE (type) == FUNCTION_TYPE)
3256 return build_pointer_type (type);
3257 return type;
3258 }
3259
3260 /* There are three conditions of builtin candidates:
3261
3262 1) bool-taking candidates. These are the same regardless of the input.
3263 2) pointer-pair taking candidates. These are generated for each type
3264 one of the input types converts to.
3265 3) arithmetic candidates. According to the standard, we should generate
3266 all of these, but I'm trying not to...
3267
3268 Here we generate a superset of the possible candidates for this particular
3269 case. That is a subset of the full set the standard defines, plus some
3270 other cases which the standard disallows. add_builtin_candidate will
3271 filter out the invalid set. */
3272
3273 static void
3274 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3275 enum tree_code code2, tree fnname,
3276 vec<tree, va_gc> *argv,
3277 int flags, tsubst_flags_t complain)
3278 {
3279 int ref1;
3280 int enum_p = 0;
3281 tree type, argtypes[3], t;
3282 /* TYPES[i] is the set of possible builtin-operator parameter types
3283 we will consider for the Ith argument. */
3284 vec<tree, va_gc> *types[2];
3285 unsigned ix;
3286 vec<tree, va_gc> &args = *argv;
3287 unsigned len = args.length ();
3288
3289 for (unsigned i = 0; i < len; ++i)
3290 {
3291 if (args[i])
3292 argtypes[i] = unlowered_expr_type (args[i]);
3293 else
3294 argtypes[i] = NULL_TREE;
3295 }
3296
3297 switch (code)
3298 {
3299 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3300 and VQ is either volatile or empty, there exist candidate operator
3301 functions of the form
3302 VQ T& operator++(VQ T&); */
3303
3304 case POSTINCREMENT_EXPR:
3305 case PREINCREMENT_EXPR:
3306 case POSTDECREMENT_EXPR:
3307 case PREDECREMENT_EXPR:
3308 case MODIFY_EXPR:
3309 ref1 = 1;
3310 break;
3311
3312 /* 24There also exist candidate operator functions of the form
3313 bool operator!(bool);
3314 bool operator&&(bool, bool);
3315 bool operator||(bool, bool); */
3316
3317 case TRUTH_NOT_EXPR:
3318 build_builtin_candidate
3319 (candidates, fnname, boolean_type_node,
3320 NULL_TREE, args, argtypes, flags, complain);
3321 return;
3322
3323 case TRUTH_ORIF_EXPR:
3324 case TRUTH_ANDIF_EXPR:
3325 build_builtin_candidate
3326 (candidates, fnname, boolean_type_node,
3327 boolean_type_node, args, argtypes, flags, complain);
3328 return;
3329
3330 case ADDR_EXPR:
3331 case COMPOUND_EXPR:
3332 case COMPONENT_REF:
3333 case CO_AWAIT_EXPR:
3334 return;
3335
3336 case COND_EXPR:
3337 case EQ_EXPR:
3338 case NE_EXPR:
3339 case LT_EXPR:
3340 case LE_EXPR:
3341 case GT_EXPR:
3342 case GE_EXPR:
3343 case SPACESHIP_EXPR:
3344 enum_p = 1;
3345 /* Fall through. */
3346
3347 default:
3348 ref1 = 0;
3349 }
3350
3351 types[0] = make_tree_vector ();
3352 types[1] = make_tree_vector ();
3353
3354 if (len == 3)
3355 len = 2;
3356 for (unsigned i = 0; i < len; ++i)
3357 {
3358 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3359 {
3360 tree convs;
3361
3362 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3363 return;
3364
3365 convs = lookup_conversions (argtypes[i]);
3366
3367 if (code == COND_EXPR)
3368 {
3369 if (lvalue_p (args[i]))
3370 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3371
3372 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3373 }
3374
3375 else if (! convs)
3376 return;
3377
3378 for (; convs; convs = TREE_CHAIN (convs))
3379 {
3380 type = TREE_TYPE (convs);
3381
3382 if (i == 0 && ref1
3383 && (!TYPE_REF_P (type)
3384 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3385 continue;
3386
3387 if (code == COND_EXPR && TYPE_REF_P (type))
3388 vec_safe_push (types[i], type);
3389
3390 type = non_reference (type);
3391 if (i != 0 || ! ref1)
3392 {
3393 type = cv_unqualified (type_decays_to (type));
3394 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3395 vec_safe_push (types[i], type);
3396 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3397 type = type_promotes_to (type);
3398 }
3399
3400 if (! vec_member (type, types[i]))
3401 vec_safe_push (types[i], type);
3402 }
3403 }
3404 else
3405 {
3406 if (code == COND_EXPR && lvalue_p (args[i]))
3407 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3408 type = non_reference (argtypes[i]);
3409 if (i != 0 || ! ref1)
3410 {
3411 type = cv_unqualified (type_decays_to (type));
3412 if (enum_p && UNSCOPED_ENUM_P (type))
3413 vec_safe_push (types[i], type);
3414 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3415 type = type_promotes_to (type);
3416 }
3417 vec_safe_push (types[i], type);
3418 }
3419 }
3420
3421 /* Run through the possible parameter types of both arguments,
3422 creating candidates with those parameter types. */
3423 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3424 {
3425 unsigned jx;
3426 tree u;
3427
3428 if (!types[1]->is_empty ())
3429 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3430 add_builtin_candidate
3431 (candidates, code, code2, fnname, t,
3432 u, args, argtypes, flags, complain);
3433 else
3434 add_builtin_candidate
3435 (candidates, code, code2, fnname, t,
3436 NULL_TREE, args, argtypes, flags, complain);
3437 }
3438
3439 release_tree_vector (types[0]);
3440 release_tree_vector (types[1]);
3441 }
3442
3443
3444 /* If TMPL can be successfully instantiated as indicated by
3445 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3446
3447 TMPL is the template. EXPLICIT_TARGS are any explicit template
3448 arguments. ARGLIST is the arguments provided at the call-site.
3449 This does not change ARGLIST. The RETURN_TYPE is the desired type
3450 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3451 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3452 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3453
3454 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3455
3456 static struct z_candidate*
3457 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3458 tree ctype, tree explicit_targs, tree first_arg,
3459 const vec<tree, va_gc> *arglist, tree return_type,
3460 tree access_path, tree conversion_path,
3461 int flags, tree obj, unification_kind_t strict,
3462 bool shortcut_bad_convs, tsubst_flags_t complain)
3463 {
3464 int ntparms = DECL_NTPARMS (tmpl);
3465 tree targs = make_tree_vec (ntparms);
3466 unsigned int len = vec_safe_length (arglist);
3467 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3468 unsigned int skip_without_in_chrg = 0;
3469 tree first_arg_without_in_chrg = first_arg;
3470 tree *args_without_in_chrg;
3471 unsigned int nargs_without_in_chrg;
3472 unsigned int ia, ix;
3473 tree arg;
3474 struct z_candidate *cand;
3475 tree fn;
3476 struct rejection_reason *reason = NULL;
3477 int errs;
3478 conversion **convs = NULL;
3479
3480 /* We don't do deduction on the in-charge parameter, the VTT
3481 parameter or 'this'. */
3482 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3483 {
3484 if (first_arg_without_in_chrg != NULL_TREE)
3485 first_arg_without_in_chrg = NULL_TREE;
3486 else if (return_type && strict == DEDUCE_CALL)
3487 /* We're deducing for a call to the result of a template conversion
3488 function, so the args don't contain 'this'; leave them alone. */;
3489 else
3490 ++skip_without_in_chrg;
3491 }
3492
3493 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3494 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3495 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3496 {
3497 if (first_arg_without_in_chrg != NULL_TREE)
3498 first_arg_without_in_chrg = NULL_TREE;
3499 else
3500 ++skip_without_in_chrg;
3501 }
3502
3503 if (len < skip_without_in_chrg)
3504 return add_ignored_candidate (candidates, tmpl);
3505
3506 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3507 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3508 TREE_TYPE ((*arglist)[0])))
3509 {
3510 /* 12.8/6 says, "A declaration of a constructor for a class X is
3511 ill-formed if its first parameter is of type (optionally cv-qualified)
3512 X and either there are no other parameters or else all other
3513 parameters have default arguments. A member function template is never
3514 instantiated to produce such a constructor signature."
3515
3516 So if we're trying to copy an object of the containing class, don't
3517 consider a template constructor that has a first parameter type that
3518 is just a template parameter, as we would deduce a signature that we
3519 would then reject in the code below. */
3520 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3521 {
3522 firstparm = TREE_VALUE (firstparm);
3523 if (PACK_EXPANSION_P (firstparm))
3524 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3525 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3526 {
3527 gcc_assert (!explicit_targs);
3528 reason = invalid_copy_with_fn_template_rejection ();
3529 goto fail;
3530 }
3531 }
3532 }
3533
3534 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3535 + (len - skip_without_in_chrg));
3536 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3537 ia = 0;
3538 if (first_arg_without_in_chrg != NULL_TREE)
3539 {
3540 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3541 ++ia;
3542 }
3543 for (ix = skip_without_in_chrg;
3544 vec_safe_iterate (arglist, ix, &arg);
3545 ++ix)
3546 {
3547 args_without_in_chrg[ia] = arg;
3548 ++ia;
3549 }
3550 gcc_assert (ia == nargs_without_in_chrg);
3551
3552 if (!obj)
3553 {
3554 /* Check that there's no obvious arity mismatch before proceeding with
3555 deduction. This avoids substituting explicit template arguments
3556 into the template or e.g. derived-to-base parm/arg unification
3557 (which could result in an error outside the immediate context) when
3558 the resulting candidate would be unviable anyway. */
3559 int min_arity = 0, max_arity = 0;
3560 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3561 parms = skip_artificial_parms_for (tmpl, parms);
3562 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3563 {
3564 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3565 {
3566 max_arity = -1;
3567 break;
3568 }
3569 if (TREE_PURPOSE (parms))
3570 /* A parameter with a default argument. */
3571 ++max_arity;
3572 else
3573 ++min_arity, ++max_arity;
3574 }
3575 if (ia < (unsigned)min_arity)
3576 {
3577 /* Too few arguments. */
3578 reason = arity_rejection (NULL_TREE, min_arity, ia,
3579 /*least_p=*/(max_arity == -1));
3580 goto fail;
3581 }
3582 else if (max_arity != -1 && ia > (unsigned)max_arity)
3583 {
3584 /* Too many arguments. */
3585 reason = arity_rejection (NULL_TREE, max_arity, ia);
3586 goto fail;
3587 }
3588
3589 convs = alloc_conversions (nargs);
3590
3591 if (shortcut_bad_convs
3592 && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3593 && !DECL_CONSTRUCTOR_P (tmpl))
3594 {
3595 /* Check the 'this' conversion before proceeding with deduction.
3596 This is effectively an extension of the DR 1391 resolution
3597 that we perform in check_non_deducible_conversions, though it's
3598 convenient to do this extra check here instead of there. */
3599 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3600 tree argtype = lvalue_type (first_arg);
3601 tree arg = first_arg;
3602 conversion *t = build_this_conversion (tmpl, ctype,
3603 parmtype, argtype, arg,
3604 flags, complain);
3605 convs[0] = t;
3606 if (t->bad_p)
3607 {
3608 reason = bad_arg_conversion_rejection (first_arg, 0,
3609 arg, parmtype,
3610 EXPR_LOCATION (arg));
3611 goto fail;
3612 }
3613 }
3614 }
3615
3616 errs = errorcount+sorrycount;
3617 fn = fn_type_unification (tmpl, explicit_targs, targs,
3618 args_without_in_chrg,
3619 nargs_without_in_chrg,
3620 return_type, strict, flags, convs,
3621 false, complain & tf_decltype);
3622
3623 if (fn == error_mark_node)
3624 {
3625 /* Don't repeat unification later if it already resulted in errors. */
3626 if (errorcount+sorrycount == errs)
3627 reason = template_unification_rejection (tmpl, explicit_targs,
3628 targs, args_without_in_chrg,
3629 nargs_without_in_chrg,
3630 return_type, strict, flags);
3631 else
3632 reason = template_unification_error_rejection ();
3633 goto fail;
3634 }
3635
3636 /* Now the explicit specifier might have been deduced; check if this
3637 declaration is explicit. If it is and we're ignoring non-converting
3638 constructors, don't add this function to the set of candidates. */
3639 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3640 == LOOKUP_ONLYCONVERTING)
3641 && DECL_NONCONVERTING_P (fn))
3642 return add_ignored_candidate (candidates, fn);
3643
3644 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3645 {
3646 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3647 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3648 ctype))
3649 {
3650 /* We're trying to produce a constructor with a prohibited signature,
3651 as discussed above; handle here any cases we didn't catch then,
3652 such as X(X<T>). */
3653 reason = invalid_copy_with_fn_template_rejection ();
3654 goto fail;
3655 }
3656 }
3657
3658 if (obj != NULL_TREE)
3659 /* Aha, this is a conversion function. */
3660 cand = add_conv_candidate (candidates, fn, obj, arglist,
3661 access_path, conversion_path, complain);
3662 else
3663 cand = add_function_candidate (candidates, fn, ctype,
3664 first_arg, arglist, access_path,
3665 conversion_path, flags, convs,
3666 shortcut_bad_convs, complain);
3667 if (DECL_TI_TEMPLATE (fn) != tmpl)
3668 /* This situation can occur if a member template of a template
3669 class is specialized. Then, instantiate_template might return
3670 an instantiation of the specialization, in which case the
3671 DECL_TI_TEMPLATE field will point at the original
3672 specialization. For example:
3673
3674 template <class T> struct S { template <class U> void f(U);
3675 template <> void f(int) {}; };
3676 S<double> sd;
3677 sd.f(3);
3678
3679 Here, TMPL will be template <class U> S<double>::f(U).
3680 And, instantiate template will give us the specialization
3681 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3682 for this will point at template <class T> template <> S<T>::f(int),
3683 so that we can find the definition. For the purposes of
3684 overload resolution, however, we want the original TMPL. */
3685 cand->template_decl = build_template_info (tmpl, targs);
3686 else
3687 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3688 cand->explicit_targs = explicit_targs;
3689
3690 return cand;
3691 fail:
3692 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3693 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3694 access_path, conversion_path, viable, reason, flags);
3695 }
3696
3697
3698 static struct z_candidate *
3699 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3700 tree explicit_targs, tree first_arg,
3701 const vec<tree, va_gc> *arglist, tree return_type,
3702 tree access_path, tree conversion_path, int flags,
3703 unification_kind_t strict, bool shortcut_bad_convs,
3704 tsubst_flags_t complain)
3705 {
3706 return
3707 add_template_candidate_real (candidates, tmpl, ctype,
3708 explicit_targs, first_arg, arglist,
3709 return_type, access_path, conversion_path,
3710 flags, NULL_TREE, strict, shortcut_bad_convs,
3711 complain);
3712 }
3713
3714 /* Create an overload candidate for the conversion function template TMPL,
3715 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3716 pointer-to-function which will in turn be called with the argument list
3717 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3718 passed on to implicit_conversion. */
3719
3720 static struct z_candidate *
3721 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3722 tree obj,
3723 const vec<tree, va_gc> *arglist,
3724 tree return_type, tree access_path,
3725 tree conversion_path, tsubst_flags_t complain)
3726 {
3727 return
3728 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3729 NULL_TREE, arglist, return_type, access_path,
3730 conversion_path, 0, obj, DEDUCE_CALL,
3731 /*shortcut_bad_convs=*/false, complain);
3732 }
3733
3734 /* The CANDS are the set of candidates that were considered for
3735 overload resolution. Sort CANDS so that the strictly viable
3736 candidates appear first, followed by non-strictly viable candidates,
3737 followed by non-viable candidates. Returns the first candidate
3738 in this sorted list. If any of the candidates were viable, set
3739 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3740 considered viable only if it is strictly viable when setting
3741 *ANY_VIABLE_P. */
3742
3743 static struct z_candidate*
3744 splice_viable (struct z_candidate *cands,
3745 bool strict_p,
3746 bool *any_viable_p)
3747 {
3748 z_candidate *strictly_viable = nullptr;
3749 z_candidate **strictly_viable_tail = &strictly_viable;
3750
3751 z_candidate *non_strictly_viable = nullptr;
3752 z_candidate **non_strictly_viable_tail = &non_strictly_viable;
3753
3754 z_candidate *non_viable = nullptr;
3755 z_candidate **non_viable_tail = &non_viable;
3756
3757 z_candidate *non_viable_ignored = nullptr;
3758 z_candidate **non_viable_ignored_tail = &non_viable_ignored;
3759
3760 /* Be strict inside templates, since build_over_call won't actually
3761 do the conversions to get pedwarns. */
3762 if (processing_template_decl)
3763 strict_p = true;
3764
3765 for (z_candidate *cand = cands; cand; cand = cand->next)
3766 {
3767 if (!strict_p
3768 && (cand->viable == 1 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
3769 /* Be strict in the presence of a viable candidate. Also if
3770 there are template candidates, so that we get deduction errors
3771 for them instead of silently preferring a bad conversion. */
3772 strict_p = true;
3773
3774 /* Move this candidate to the appropriate list according to
3775 its viability. */
3776 auto& tail = (cand->viable == 1 ? strictly_viable_tail
3777 : cand->viable == -1 ? non_strictly_viable_tail
3778 : ignored_candidate_p (cand) ? non_viable_ignored_tail
3779 : non_viable_tail);
3780 *tail = cand;
3781 tail = &cand->next;
3782 }
3783
3784 *any_viable_p = (strictly_viable != nullptr
3785 || (!strict_p && non_strictly_viable != nullptr));
3786
3787 /* Combine the lists. */
3788 *non_viable_ignored_tail = nullptr;
3789 *non_viable_tail = non_viable_ignored;
3790 *non_strictly_viable_tail = non_viable;
3791 *strictly_viable_tail = non_strictly_viable;
3792
3793 return strictly_viable;
3794 }
3795
3796 static bool
3797 any_strictly_viable (struct z_candidate *cands)
3798 {
3799 for (; cands; cands = cands->next)
3800 if (cands->viable == 1)
3801 return true;
3802 return false;
3803 }
3804
3805 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3806 words, it is about to become the "this" pointer for a member
3807 function call. Take the address of the object. */
3808
3809 static tree
3810 build_this (tree obj)
3811 {
3812 /* In a template, we are only concerned about the type of the
3813 expression, so we can take a shortcut. */
3814 if (processing_template_decl)
3815 return build_address (obj);
3816
3817 return cp_build_addr_expr (obj, tf_warning_or_error);
3818 }
3819
3820 /* Returns true iff functions are equivalent. Equivalent functions are
3821 not '==' only if one is a function-local extern function or if
3822 both are extern "C". */
3823
3824 static inline int
3825 equal_functions (tree fn1, tree fn2)
3826 {
3827 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3828 return 0;
3829 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3830 return fn1 == fn2;
3831 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3832 || DECL_EXTERN_C_FUNCTION_P (fn1))
3833 return decls_match (fn1, fn2);
3834 return fn1 == fn2;
3835 }
3836
3837 /* Print information about a candidate FN being rejected due to INFO. */
3838
3839 static void
3840 print_conversion_rejection (location_t loc, struct conversion_info *info,
3841 tree fn)
3842 {
3843 tree from = info->from;
3844 if (!TYPE_P (from))
3845 from = lvalue_type (from);
3846 if (info->n_arg == -1)
3847 {
3848 /* Conversion of implicit `this' argument failed. */
3849 if (!TYPE_P (info->from))
3850 /* A bad conversion for 'this' must be discarding cv-quals. */
3851 inform (loc, " passing %qT as %<this%> "
3852 "argument discards qualifiers",
3853 from);
3854 else
3855 inform (loc, " no known conversion for implicit "
3856 "%<this%> parameter from %qH to %qI",
3857 from, info->to_type);
3858 }
3859 else if (!TYPE_P (info->from))
3860 {
3861 if (info->n_arg >= 0)
3862 inform (loc, " conversion of argument %d would be ill-formed:",
3863 info->n_arg + 1);
3864 iloc_sentinel ils = loc;
3865 perform_implicit_conversion (info->to_type, info->from,
3866 tf_warning_or_error);
3867 }
3868 else if (info->n_arg == -2)
3869 /* Conversion of conversion function return value failed. */
3870 inform (loc, " no known conversion from %qH to %qI",
3871 from, info->to_type);
3872 else
3873 {
3874 if (TREE_CODE (fn) == FUNCTION_DECL)
3875 loc = get_fndecl_argument_location (fn, info->n_arg);
3876 inform (loc, " no known conversion for argument %d from %qH to %qI",
3877 info->n_arg + 1, from, info->to_type);
3878 }
3879 }
3880
3881 /* Print information about a candidate with WANT parameters and we found
3882 HAVE. */
3883
3884 static void
3885 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3886 bool least_p)
3887 {
3888 if (least_p)
3889 inform_n (loc, want,
3890 " candidate expects at least %d argument, %d provided",
3891 " candidate expects at least %d arguments, %d provided",
3892 want, have);
3893 else
3894 inform_n (loc, want,
3895 " candidate expects %d argument, %d provided",
3896 " candidate expects %d arguments, %d provided",
3897 want, have);
3898 }
3899
3900 /* Print information about one overload candidate CANDIDATE. MSGSTR
3901 is the text to print before the candidate itself.
3902
3903 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3904 to have been run through gettext by the caller. This wart makes
3905 life simpler in print_z_candidates and for the translators. */
3906
3907 static void
3908 print_z_candidate (location_t loc, const char *msgstr,
3909 struct z_candidate *candidate)
3910 {
3911 const char *msg = (msgstr == NULL
3912 ? ""
3913 : ACONCAT ((_(msgstr), " ", NULL)));
3914 tree fn = candidate->fn;
3915 if (flag_new_inheriting_ctors)
3916 fn = strip_inheriting_ctors (fn);
3917 location_t cloc = location_of (fn);
3918
3919 if (identifier_p (fn))
3920 {
3921 cloc = loc;
3922 if (candidate->num_convs == 3)
3923 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3924 candidate->convs[0]->type,
3925 candidate->convs[1]->type,
3926 candidate->convs[2]->type);
3927 else if (candidate->num_convs == 2)
3928 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3929 candidate->convs[0]->type,
3930 candidate->convs[1]->type);
3931 else
3932 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3933 candidate->convs[0]->type);
3934 }
3935 else if (TYPE_P (fn))
3936 inform (cloc, "%s%qT (conversion)", msg, fn);
3937 else if (candidate->viable == -1)
3938 inform (cloc, "%s%#qD (near match)", msg, fn);
3939 else if (ignored_candidate_p (candidate))
3940 inform (cloc, "%s%#qD (ignored)", msg, fn);
3941 else if (DECL_DELETED_FN (fn))
3942 inform (cloc, "%s%#qD (deleted)", msg, fn);
3943 else if (candidate->reversed ())
3944 inform (cloc, "%s%#qD (reversed)", msg, fn);
3945 else if (candidate->rewritten ())
3946 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3947 else
3948 inform (cloc, "%s%#qD", msg, fn);
3949 if (fn != candidate->fn)
3950 {
3951 cloc = location_of (candidate->fn);
3952 inform (cloc, " inherited here");
3953 }
3954 /* Give the user some information about why this candidate failed. */
3955 if (candidate->reason != NULL)
3956 {
3957 struct rejection_reason *r = candidate->reason;
3958
3959 switch (r->code)
3960 {
3961 case rr_arity:
3962 print_arity_information (cloc, r->u.arity.actual,
3963 r->u.arity.expected,
3964 r->u.arity.least_p);
3965 break;
3966 case rr_arg_conversion:
3967 print_conversion_rejection (cloc, &r->u.conversion, fn);
3968 break;
3969 case rr_bad_arg_conversion:
3970 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3971 break;
3972 case rr_explicit_conversion:
3973 inform (cloc, " return type %qT of explicit conversion function "
3974 "cannot be converted to %qT with a qualification "
3975 "conversion", r->u.conversion.from,
3976 r->u.conversion.to_type);
3977 break;
3978 case rr_template_conversion:
3979 inform (cloc, " conversion from return type %qT of template "
3980 "conversion function specialization to %qT is not an "
3981 "exact match", r->u.conversion.from,
3982 r->u.conversion.to_type);
3983 break;
3984 case rr_template_unification:
3985 /* We use template_unification_error_rejection if unification caused
3986 actual non-SFINAE errors, in which case we don't need to repeat
3987 them here. */
3988 if (r->u.template_unification.tmpl == NULL_TREE)
3989 {
3990 inform (cloc, " substitution of deduced template arguments "
3991 "resulted in errors seen above");
3992 break;
3993 }
3994 /* Re-run template unification with diagnostics. */
3995 inform (cloc, " template argument deduction/substitution failed:");
3996 fn_type_unification (r->u.template_unification.tmpl,
3997 r->u.template_unification.explicit_targs,
3998 (make_tree_vec
3999 (r->u.template_unification.num_targs)),
4000 r->u.template_unification.args,
4001 r->u.template_unification.nargs,
4002 r->u.template_unification.return_type,
4003 r->u.template_unification.strict,
4004 r->u.template_unification.flags,
4005 NULL, true, false);
4006 break;
4007 case rr_invalid_copy:
4008 inform (cloc,
4009 " a constructor taking a single argument of its own "
4010 "class type is invalid");
4011 break;
4012 case rr_constraint_failure:
4013 diagnose_constraints (cloc, fn, NULL_TREE);
4014 break;
4015 case rr_inherited_ctor:
4016 inform (cloc, " an inherited constructor is not a candidate for "
4017 "initialization from an expression of the same or derived "
4018 "type");
4019 break;
4020 case rr_ignored:
4021 break;
4022 case rr_none:
4023 default:
4024 /* This candidate didn't have any issues or we failed to
4025 handle a particular code. Either way... */
4026 gcc_unreachable ();
4027 }
4028 }
4029 }
4030
4031 /* Print information about each overload candidate in CANDIDATES,
4032 which is assumed to have gone through splice_viable and tourney
4033 (if splice_viable succeeded). */
4034
4035 static void
4036 print_z_candidates (location_t loc, struct z_candidate *candidates,
4037 tristate only_viable_p /* = tristate::unknown () */)
4038 {
4039 struct z_candidate *cand1;
4040 struct z_candidate **cand2;
4041
4042 if (!candidates)
4043 return;
4044
4045 /* Remove non-viable deleted candidates. */
4046 cand1 = candidates;
4047 for (cand2 = &cand1; *cand2; )
4048 {
4049 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4050 && !(*cand2)->viable
4051 && DECL_DELETED_FN ((*cand2)->fn))
4052 *cand2 = (*cand2)->next;
4053 else
4054 cand2 = &(*cand2)->next;
4055 }
4056 /* ...if there are any non-deleted ones. */
4057 if (cand1)
4058 candidates = cand1;
4059
4060 /* There may be duplicates in the set of candidates. We put off
4061 checking this condition as long as possible, since we have no way
4062 to eliminate duplicates from a set of functions in less than n^2
4063 time. Now we are about to emit an error message, so it is more
4064 permissible to go slowly. */
4065 for (cand1 = candidates; cand1; cand1 = cand1->next)
4066 {
4067 tree fn = cand1->fn;
4068 /* Skip builtin candidates and conversion functions. */
4069 if (!DECL_P (fn))
4070 continue;
4071 cand2 = &cand1->next;
4072 while (*cand2)
4073 {
4074 if (DECL_P ((*cand2)->fn)
4075 && equal_functions (fn, (*cand2)->fn))
4076 *cand2 = (*cand2)->next;
4077 else
4078 cand2 = &(*cand2)->next;
4079 }
4080 }
4081
4082 /* Unless otherwise specified, if there's a (strictly) viable candidate
4083 then we assume we're being called as part of diagnosing ambiguity, in
4084 which case we want to print only viable candidates since non-viable
4085 candidates couldn't have contributed to the ambiguity. */
4086 if (only_viable_p.is_unknown ())
4087 only_viable_p = candidates->viable == 1;
4088
4089 for (; candidates; candidates = candidates->next)
4090 {
4091 if (only_viable_p.is_true () && candidates->viable != 1)
4092 break;
4093 if (ignored_candidate_p (candidates) && !flag_diagnostics_all_candidates)
4094 {
4095 inform (loc, "some candidates omitted; "
4096 "use %<-fdiagnostics-all-candidates%> to display them");
4097 break;
4098 }
4099 print_z_candidate (loc, N_("candidate:"), candidates);
4100 }
4101 }
4102
4103 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4104 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4105 the result of the conversion function to convert it to the final
4106 desired type. Merge the two sequences into a single sequence,
4107 and return the merged sequence. */
4108
4109 static conversion *
4110 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4111 {
4112 conversion **t;
4113 bool bad = user_seq->bad_p;
4114
4115 gcc_assert (user_seq->kind == ck_user);
4116
4117 /* Find the end of the second conversion sequence. */
4118 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4119 {
4120 /* The entire sequence is a user-conversion sequence. */
4121 (*t)->user_conv_p = true;
4122 if (bad)
4123 (*t)->bad_p = true;
4124 }
4125
4126 if ((*t)->rvaluedness_matches_p)
4127 /* We're binding a reference directly to the result of the conversion.
4128 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4129 type, but we want it back. */
4130 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4131
4132 /* Replace the identity conversion with the user conversion
4133 sequence. */
4134 *t = user_seq;
4135
4136 return std_seq;
4137 }
4138
4139 /* Handle overload resolution for initializing an object of class type from
4140 an initializer list. First we look for a suitable constructor that
4141 takes a std::initializer_list; if we don't find one, we then look for a
4142 non-list constructor.
4143
4144 Parameters are as for add_candidates, except that the arguments are in
4145 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4146 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4147
4148 static void
4149 add_list_candidates (tree fns, tree first_arg,
4150 const vec<tree, va_gc> *args, tree totype,
4151 tree explicit_targs, bool template_only,
4152 tree conversion_path, tree access_path,
4153 int flags,
4154 struct z_candidate **candidates,
4155 tsubst_flags_t complain)
4156 {
4157 gcc_assert (*candidates == NULL);
4158
4159 /* We're looking for a ctor for list-initialization. */
4160 flags |= LOOKUP_LIST_INIT_CTOR;
4161 /* And we don't allow narrowing conversions. We also use this flag to
4162 avoid the copy constructor call for copy-list-initialization. */
4163 flags |= LOOKUP_NO_NARROWING;
4164
4165 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4166 tree init_list = (*args)[nart];
4167
4168 /* Always use the default constructor if the list is empty (DR 990). */
4169 if (CONSTRUCTOR_NELTS (init_list) == 0
4170 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4171 ;
4172 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4173 && !CP_AGGREGATE_TYPE_P (totype))
4174 {
4175 if (complain & tf_error)
4176 error ("designated initializers cannot be used with a "
4177 "non-aggregate type %qT", totype);
4178 return;
4179 }
4180 /* If the class has a list ctor, try passing the list as a single
4181 argument first, but only consider list ctors. */
4182 else if (TYPE_HAS_LIST_CTOR (totype))
4183 {
4184 flags |= LOOKUP_LIST_ONLY;
4185 add_candidates (fns, first_arg, args, NULL_TREE,
4186 explicit_targs, template_only, conversion_path,
4187 access_path, flags, candidates, complain);
4188 if (any_strictly_viable (*candidates))
4189 return;
4190 }
4191
4192 /* Expand the CONSTRUCTOR into a new argument vec. */
4193 vec<tree, va_gc> *new_args;
4194 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4195 for (unsigned i = 0; i < nart; ++i)
4196 new_args->quick_push ((*args)[i]);
4197 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4198 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4199
4200 /* We aren't looking for list-ctors anymore. */
4201 flags &= ~LOOKUP_LIST_ONLY;
4202 /* We allow more user-defined conversions within an init-list. */
4203 flags &= ~LOOKUP_NO_CONVERSION;
4204
4205 add_candidates (fns, first_arg, new_args, NULL_TREE,
4206 explicit_targs, template_only, conversion_path,
4207 access_path, flags, candidates, complain);
4208 }
4209
4210 /* Given C(std::initializer_list<A>), return A. */
4211
4212 static tree
4213 list_ctor_element_type (tree fn)
4214 {
4215 gcc_checking_assert (is_list_ctor (fn));
4216
4217 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4218 parm = non_reference (TREE_VALUE (parm));
4219 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4220 }
4221
4222 /* If EXPR is a braced-init-list where the elements all decay to the same type,
4223 return that type. */
4224
4225 static tree
4226 braced_init_element_type (tree expr)
4227 {
4228 if (TREE_CODE (expr) == CONSTRUCTOR
4229 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4230 return TREE_TYPE (TREE_TYPE (expr));
4231 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4232 return NULL_TREE;
4233
4234 tree elttype = NULL_TREE;
4235 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4236 {
4237 tree type = TREE_TYPE (e.value);
4238 type = type_decays_to (type);
4239 if (!elttype)
4240 elttype = type;
4241 else if (!same_type_p (type, elttype))
4242 return NULL_TREE;
4243 }
4244 return elttype;
4245 }
4246
4247 /* True iff EXPR contains any temporaries with non-trivial destruction.
4248
4249 ??? Also ignore classes with non-trivial but no-op destruction other than
4250 std::allocator? */
4251
4252 static bool
4253 has_non_trivial_temporaries (tree expr)
4254 {
4255 auto_vec<tree*> temps;
4256 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4257 for (tree *p : temps)
4258 {
4259 tree t = TREE_TYPE (*p);
4260 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4261 && !is_std_allocator (t))
4262 return true;
4263 }
4264 return false;
4265 }
4266
4267 /* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4268 return INIT as an array (of its own type) so the caller can initialize the
4269 target array in a loop. */
4270
4271 static tree
4272 maybe_init_list_as_array (tree elttype, tree init)
4273 {
4274 /* Only do this if the array can go in rodata but not once converted. */
4275 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4276 return NULL_TREE;
4277 tree init_elttype = braced_init_element_type (init);
4278 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4279 return NULL_TREE;
4280
4281 /* Check with a stub expression to weed out special cases, and check whether
4282 we call the same function for direct-init as copy-list-init. */
4283 conversion_obstack_sentinel cos;
4284 tree arg = build_stub_object (init_elttype);
4285 conversion *c = implicit_conversion (elttype, init_elttype, arg, false,
4286 LOOKUP_NORMAL, tf_none);
4287 if (c && c->kind == ck_rvalue)
4288 c = next_conversion (c);
4289 if (!c || c->kind != ck_user)
4290 return NULL_TREE;
4291
4292 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4293 conversion *fc = implicit_conversion (elttype, init_elttype, first, false,
4294 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4295 tf_none);
4296 if (fc && fc->kind == ck_rvalue)
4297 fc = next_conversion (fc);
4298 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4299 return NULL_TREE;
4300 first = convert_like (fc, first, tf_none);
4301 if (first == error_mark_node)
4302 /* Let the normal code give the error. */
4303 return NULL_TREE;
4304
4305 /* Don't do this if the conversion would be constant. */
4306 first = maybe_constant_init (first);
4307 if (TREE_CONSTANT (first))
4308 return NULL_TREE;
4309
4310 /* We can't do this if the conversion creates temporaries that need
4311 to live until the whole array is initialized. */
4312 if (has_non_trivial_temporaries (first))
4313 return NULL_TREE;
4314
4315 /* We can't do this if copying from the initializer_list would be
4316 ill-formed. */
4317 tree copy_argtypes = make_tree_vec (1);
4318 TREE_VEC_ELT (copy_argtypes, 0)
4319 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4320 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4321 return NULL_TREE;
4322
4323 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4324 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4325 arr = finish_compound_literal (arr, init, tf_none);
4326 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4327 return arr;
4328 }
4329
4330 /* If we were going to call e.g. vector(initializer_list<string>) starting
4331 with a list of string-literals (which is inefficient, see PR105838),
4332 instead build an array of const char* and pass it to the range constructor.
4333 But only do this for standard library types, where we can assume the
4334 transformation makes sense.
4335
4336 Really the container classes should have initializer_list<U> constructors to
4337 get the same effect more simply; this is working around that lack. */
4338
4339 static tree
4340 maybe_init_list_as_range (tree fn, tree expr)
4341 {
4342 if (!processing_template_decl
4343 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4344 && is_list_ctor (fn)
4345 && decl_in_std_namespace_p (fn))
4346 {
4347 tree to = list_ctor_element_type (fn);
4348 if (tree init = maybe_init_list_as_array (to, expr))
4349 {
4350 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4351 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4352 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4353 nelts, tf_none);
4354 begin = cp_build_compound_expr (init, begin, tf_none);
4355 return build_constructor_va (init_list_type_node, 2,
4356 NULL_TREE, begin, NULL_TREE, end);
4357 }
4358 }
4359
4360 return NULL_TREE;
4361 }
4362
4363 /* Returns the best overload candidate to perform the requested
4364 conversion. This function is used for three the overloading situations
4365 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4366 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4367 per [dcl.init.ref], so we ignore temporary bindings. */
4368
4369 static struct z_candidate *
4370 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4371 tsubst_flags_t complain)
4372 {
4373 struct z_candidate *candidates, *cand;
4374 tree fromtype;
4375 tree ctors = NULL_TREE;
4376 tree conv_fns = NULL_TREE;
4377 conversion *conv = NULL;
4378 tree first_arg = NULL_TREE;
4379 vec<tree, va_gc> *args = NULL;
4380 bool any_viable_p;
4381 int convflags;
4382
4383 if (!expr)
4384 return NULL;
4385
4386 fromtype = TREE_TYPE (expr);
4387
4388 /* We represent conversion within a hierarchy using RVALUE_CONV and
4389 BASE_CONV, as specified by [over.best.ics]; these become plain
4390 constructor calls, as specified in [dcl.init]. */
4391 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4392 || !DERIVED_FROM_P (totype, fromtype));
4393
4394 if (CLASS_TYPE_P (totype))
4395 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4396 creating a garbage BASELINK; constructors can't be inherited. */
4397 ctors = get_class_binding (totype, complete_ctor_identifier);
4398
4399 tree to_nonref = non_reference (totype);
4400 if (MAYBE_CLASS_TYPE_P (fromtype))
4401 {
4402 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4403 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4404 && DERIVED_FROM_P (to_nonref, fromtype)))
4405 {
4406 /* [class.conv.fct] A conversion function is never used to
4407 convert a (possibly cv-qualified) object to the (possibly
4408 cv-qualified) same object type (or a reference to it), to a
4409 (possibly cv-qualified) base class of that type (or a
4410 reference to it)... */
4411 }
4412 else
4413 conv_fns = lookup_conversions (fromtype);
4414 }
4415
4416 candidates = 0;
4417 flags |= LOOKUP_NO_CONVERSION;
4418 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4419 flags |= LOOKUP_NO_NARROWING;
4420 /* Prevent add_candidates from treating a non-strictly viable candidate
4421 as unviable. */
4422 complain |= tf_conv;
4423
4424 /* It's OK to bind a temporary for converting constructor arguments, but
4425 not in converting the return value of a conversion operator. */
4426 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4427 | (flags & LOOKUP_NO_NARROWING));
4428 flags &= ~LOOKUP_NO_TEMP_BIND;
4429
4430 if (ctors)
4431 {
4432 int ctorflags = flags;
4433
4434 first_arg = build_dummy_object (totype);
4435
4436 /* We should never try to call the abstract or base constructor
4437 from here. */
4438 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4439 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4440
4441 args = make_tree_vector_single (expr);
4442 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4443 {
4444 /* List-initialization. */
4445 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4446 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4447 ctorflags, &candidates, complain);
4448 }
4449 else
4450 {
4451 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4452 TYPE_BINFO (totype), TYPE_BINFO (totype),
4453 ctorflags, &candidates, complain);
4454 }
4455
4456 for (cand = candidates; cand; cand = cand->next)
4457 {
4458 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4459
4460 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4461 set, then this is copy-initialization. In that case, "The
4462 result of the call is then used to direct-initialize the
4463 object that is the destination of the copy-initialization."
4464 [dcl.init]
4465
4466 We represent this in the conversion sequence with an
4467 rvalue conversion, which means a constructor call. */
4468 if (!TYPE_REF_P (totype)
4469 && cxx_dialect < cxx17
4470 && (flags & LOOKUP_ONLYCONVERTING)
4471 && !(convflags & LOOKUP_NO_TEMP_BIND))
4472 cand->second_conv
4473 = build_conv (ck_rvalue, totype, cand->second_conv);
4474 }
4475 }
4476
4477 if (conv_fns)
4478 {
4479 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4480 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4481 else
4482 first_arg = expr;
4483 }
4484
4485 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4486 {
4487 tree conversion_path = TREE_PURPOSE (conv_fns);
4488 struct z_candidate *old_candidates;
4489
4490 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4491 would need an addional user-defined conversion, i.e. if the return
4492 type differs in class-ness from the desired type. So we avoid
4493 considering operator bool when calling a copy constructor.
4494
4495 This optimization avoids the failure in PR97600, and is allowed by
4496 [temp.inst]/9: "If the function selected by overload resolution can be
4497 determined without instantiating a class template definition, it is
4498 unspecified whether that instantiation actually takes place." */
4499 tree convtype = non_reference (TREE_TYPE (conv_fns));
4500 if ((flags & LOOKUP_NO_CONVERSION)
4501 && !WILDCARD_TYPE_P (convtype)
4502 && (CLASS_TYPE_P (to_nonref)
4503 != CLASS_TYPE_P (convtype)))
4504 continue;
4505
4506 /* If we are called to convert to a reference type, we are trying to
4507 find a direct binding, so don't even consider temporaries. If
4508 we don't find a direct binding, the caller will try again to
4509 look for a temporary binding. */
4510 if (TYPE_REF_P (totype))
4511 convflags |= LOOKUP_NO_TEMP_BIND;
4512
4513 old_candidates = candidates;
4514 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4515 NULL_TREE, false,
4516 conversion_path, TYPE_BINFO (fromtype),
4517 flags, &candidates, complain);
4518
4519 for (cand = candidates; cand != old_candidates; cand = cand->next)
4520 {
4521 if (cand->viable == 0)
4522 /* Already rejected, don't change to -1. */
4523 continue;
4524
4525 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4526 conversion *ics
4527 = implicit_conversion (totype,
4528 rettype,
4529 0,
4530 /*c_cast_p=*/false, convflags,
4531 complain);
4532
4533 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4534 copy-initialization. In that case, "The result of the
4535 call is then used to direct-initialize the object that is
4536 the destination of the copy-initialization." [dcl.init]
4537
4538 We represent this in the conversion sequence with an
4539 rvalue conversion, which means a constructor call. But
4540 don't add a second rvalue conversion if there's already
4541 one there. Which there really shouldn't be, but it's
4542 harmless since we'd add it here anyway. */
4543 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4544 && !(convflags & LOOKUP_NO_TEMP_BIND))
4545 ics = build_conv (ck_rvalue, totype, ics);
4546
4547 cand->second_conv = ics;
4548
4549 if (!ics)
4550 {
4551 cand->viable = 0;
4552 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4553 rettype, totype,
4554 EXPR_LOCATION (expr));
4555 }
4556 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4557 /* Limit this to non-templates for now (PR90546). */
4558 && !cand->template_decl
4559 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4560 {
4561 /* If we are called to convert to a reference type, we are trying
4562 to find a direct binding per [over.match.ref], so rvaluedness
4563 must match for non-functions. */
4564 cand->viable = 0;
4565 }
4566 else if (DECL_NONCONVERTING_P (cand->fn)
4567 && ics->rank > cr_exact)
4568 {
4569 /* 13.3.1.5: For direct-initialization, those explicit
4570 conversion functions that are not hidden within S and
4571 yield type T or a type that can be converted to type T
4572 with a qualification conversion (4.4) are also candidate
4573 functions. */
4574 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4575 I've raised this issue with the committee. --jason 9/2011 */
4576 cand->viable = -1;
4577 cand->reason = explicit_conversion_rejection (rettype, totype);
4578 }
4579 else if (cand->viable == 1 && ics->bad_p)
4580 {
4581 cand->viable = -1;
4582 cand->reason
4583 = bad_arg_conversion_rejection (NULL_TREE, -2,
4584 rettype, totype,
4585 EXPR_LOCATION (expr));
4586 }
4587 else if (primary_template_specialization_p (cand->fn)
4588 && ics->rank > cr_exact)
4589 {
4590 /* 13.3.3.1.2: If the user-defined conversion is specified by
4591 a specialization of a conversion function template, the
4592 second standard conversion sequence shall have exact match
4593 rank. */
4594 cand->viable = -1;
4595 cand->reason = template_conversion_rejection (rettype, totype);
4596 }
4597 }
4598 }
4599
4600 candidates = splice_viable (candidates, false, &any_viable_p);
4601 if (!any_viable_p)
4602 {
4603 if (args)
4604 release_tree_vector (args);
4605 return NULL;
4606 }
4607
4608 cand = tourney (candidates, complain);
4609 if (cand == NULL)
4610 {
4611 if (complain & tf_error)
4612 {
4613 auto_diagnostic_group d;
4614 error_at (cp_expr_loc_or_input_loc (expr),
4615 "conversion from %qH to %qI is ambiguous",
4616 fromtype, totype);
4617 print_z_candidates (location_of (expr), candidates);
4618 }
4619
4620 cand = candidates; /* any one will do */
4621 cand->second_conv = build_ambiguous_conv (totype, expr);
4622 cand->second_conv->user_conv_p = true;
4623 if (!any_strictly_viable (candidates))
4624 cand->second_conv->bad_p = true;
4625 if (flags & LOOKUP_ONLYCONVERTING)
4626 cand->second_conv->need_temporary_p = true;
4627 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4628 ambiguous conversion is no worse than another user-defined
4629 conversion. */
4630
4631 return cand;
4632 }
4633
4634 /* Maybe pass { } as iterators instead of an initializer_list. */
4635 if (tree iters = maybe_init_list_as_range (cand->fn, expr))
4636 if (z_candidate *cand2
4637 = build_user_type_conversion_1 (totype, iters, flags, tf_none))
4638 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4639 {
4640 cand = cand2;
4641 expr = iters;
4642 }
4643
4644 tree convtype;
4645 if (!DECL_CONSTRUCTOR_P (cand->fn))
4646 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4647 else if (cand->second_conv->kind == ck_rvalue)
4648 /* DR 5: [in the first step of copy-initialization]...if the function
4649 is a constructor, the call initializes a temporary of the
4650 cv-unqualified version of the destination type. */
4651 convtype = cv_unqualified (totype);
4652 else
4653 convtype = totype;
4654 /* Build the user conversion sequence. */
4655 conv = build_conv
4656 (ck_user,
4657 convtype,
4658 build_identity_conv (TREE_TYPE (expr), expr));
4659 conv->cand = cand;
4660 if (cand->viable == -1)
4661 conv->bad_p = true;
4662
4663 /* Remember that this was a list-initialization. */
4664 if (flags & LOOKUP_NO_NARROWING)
4665 conv->check_narrowing = true;
4666
4667 /* Combine it with the second conversion sequence. */
4668 cand->second_conv = merge_conversion_sequences (conv,
4669 cand->second_conv);
4670
4671 return cand;
4672 }
4673
4674 /* Wrapper for above. */
4675
4676 tree
4677 build_user_type_conversion (tree totype, tree expr, int flags,
4678 tsubst_flags_t complain)
4679 {
4680 struct z_candidate *cand;
4681 tree ret;
4682
4683 auto_cond_timevar tv (TV_OVERLOAD);
4684
4685 conversion_obstack_sentinel cos;
4686
4687 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4688
4689 if (cand)
4690 {
4691 if (cand->second_conv->kind == ck_ambig)
4692 ret = error_mark_node;
4693 else
4694 {
4695 expr = convert_like (cand->second_conv, expr, complain);
4696 ret = convert_from_reference (expr);
4697 }
4698 }
4699 else
4700 ret = NULL_TREE;
4701
4702 return ret;
4703 }
4704
4705 /* Give a helpful diagnostic when implicit_conversion fails. */
4706
4707 static void
4708 implicit_conversion_error (location_t loc, tree type, tree expr)
4709 {
4710 tsubst_flags_t complain = tf_warning_or_error;
4711
4712 /* If expr has unknown type, then it is an overloaded function.
4713 Call instantiate_type to get good error messages. */
4714 if (TREE_TYPE (expr) == unknown_type_node)
4715 instantiate_type (type, expr, complain);
4716 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4717 /* We gave an error. */;
4718 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4719 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4720 && !CP_AGGREGATE_TYPE_P (type))
4721 error_at (loc, "designated initializers cannot be used with a "
4722 "non-aggregate type %qT", type);
4723 else
4724 {
4725 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4726 gcc_rich_location rich_loc (loc, &label);
4727 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4728 expr, TREE_TYPE (expr), type);
4729 }
4730 }
4731
4732 /* Worker for build_converted_constant_expr. */
4733
4734 static tree
4735 build_converted_constant_expr_internal (tree type, tree expr,
4736 int flags, tsubst_flags_t complain)
4737 {
4738 conversion *conv;
4739 tree t;
4740 location_t loc = cp_expr_loc_or_input_loc (expr);
4741
4742 if (error_operand_p (expr))
4743 return error_mark_node;
4744
4745 conversion_obstack_sentinel cos;
4746
4747 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4748 /*c_cast_p=*/false, flags, complain);
4749
4750 /* A converted constant expression of type T is an expression, implicitly
4751 converted to type T, where the converted expression is a constant
4752 expression and the implicit conversion sequence contains only
4753
4754 * user-defined conversions,
4755 * lvalue-to-rvalue conversions (7.1),
4756 * array-to-pointer conversions (7.2),
4757 * function-to-pointer conversions (7.3),
4758 * qualification conversions (7.5),
4759 * integral promotions (7.6),
4760 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4761 * null pointer conversions (7.11) from std::nullptr_t,
4762 * null member pointer conversions (7.12) from std::nullptr_t, and
4763 * function pointer conversions (7.13),
4764
4765 and where the reference binding (if any) binds directly. */
4766
4767 for (conversion *c = conv;
4768 c && c->kind != ck_identity;
4769 c = next_conversion (c))
4770 {
4771 switch (c->kind)
4772 {
4773 /* A conversion function is OK. If it isn't constexpr, we'll
4774 complain later that the argument isn't constant. */
4775 case ck_user:
4776 /* List-initialization is OK. */
4777 case ck_aggr:
4778 /* The lvalue-to-rvalue conversion is OK. */
4779 case ck_rvalue:
4780 /* Array-to-pointer and function-to-pointer. */
4781 case ck_lvalue:
4782 /* Function pointer conversions. */
4783 case ck_fnptr:
4784 /* Qualification conversions. */
4785 case ck_qual:
4786 break;
4787
4788 case ck_ref_bind:
4789 if (c->need_temporary_p)
4790 {
4791 if (complain & tf_error)
4792 error_at (loc, "initializing %qH with %qI in converted "
4793 "constant expression does not bind directly",
4794 type, next_conversion (c)->type);
4795 conv = NULL;
4796 }
4797 break;
4798
4799 case ck_base:
4800 case ck_pmem:
4801 case ck_ptr:
4802 case ck_std:
4803 t = next_conversion (c)->type;
4804 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4805 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4806 /* Integral promotion or conversion. */
4807 break;
4808 if (NULLPTR_TYPE_P (t))
4809 /* Conversion from nullptr to pointer or pointer-to-member. */
4810 break;
4811
4812 if (complain & tf_error)
4813 error_at (loc, "conversion from %qH to %qI in a "
4814 "converted constant expression", t, type);
4815 /* fall through. */
4816
4817 default:
4818 conv = NULL;
4819 break;
4820 }
4821 }
4822
4823 /* Avoid confusing convert_nontype_argument by introducing
4824 a redundant conversion to the same reference type. */
4825 if (conv && conv->kind == ck_ref_bind
4826 && REFERENCE_REF_P (expr))
4827 {
4828 tree ref = TREE_OPERAND (expr, 0);
4829 if (same_type_p (type, TREE_TYPE (ref)))
4830 return ref;
4831 }
4832
4833 if (conv)
4834 {
4835 /* Don't copy a class in a template. */
4836 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4837 && processing_template_decl)
4838 conv = next_conversion (conv);
4839
4840 /* Issuing conversion warnings for value-dependent expressions is
4841 likely too noisy. */
4842 warning_sentinel w (warn_conversion);
4843 conv->check_narrowing = true;
4844 conv->check_narrowing_const_only = true;
4845 expr = convert_like (conv, expr, complain);
4846 }
4847 else
4848 {
4849 if (complain & tf_error)
4850 implicit_conversion_error (loc, type, expr);
4851 expr = error_mark_node;
4852 }
4853
4854 return expr;
4855 }
4856
4857 /* Subroutine of convert_nontype_argument.
4858
4859 EXPR is an expression used in a context that requires a converted
4860 constant-expression, such as a template non-type parameter. Do any
4861 necessary conversions (that are permitted for converted
4862 constant-expressions) to convert it to the desired type.
4863
4864 This function doesn't consider explicit conversion functions. If
4865 you mean to use "a contextually converted constant expression of type
4866 bool", use build_converted_constant_bool_expr.
4867
4868 If conversion is successful, returns the converted expression;
4869 otherwise, returns error_mark_node. */
4870
4871 tree
4872 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4873 {
4874 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4875 complain);
4876 }
4877
4878 /* Used to create "a contextually converted constant expression of type
4879 bool". This differs from build_converted_constant_expr in that it
4880 also considers explicit conversion functions. */
4881
4882 tree
4883 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4884 {
4885 return build_converted_constant_expr_internal (boolean_type_node, expr,
4886 LOOKUP_NORMAL, complain);
4887 }
4888
4889 /* Do any initial processing on the arguments to a function call. */
4890
4891 vec<tree, va_gc> *
4892 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4893 {
4894 unsigned int ix;
4895 tree arg;
4896
4897 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4898 {
4899 if (error_operand_p (arg))
4900 return NULL;
4901 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4902 {
4903 if (complain & tf_error)
4904 error_at (cp_expr_loc_or_input_loc (arg),
4905 "invalid use of void expression");
4906 return NULL;
4907 }
4908 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4909 return NULL;
4910
4911 /* Force auto deduction now. Omit tf_warning to avoid redundant
4912 deprecated warning on deprecated-14.C. */
4913 if (!mark_single_function (arg, complain & ~tf_warning))
4914 return NULL;
4915 }
4916 return args;
4917 }
4918
4919 /* Perform overload resolution on FN, which is called with the ARGS.
4920
4921 Return the candidate function selected by overload resolution, or
4922 NULL if the event that overload resolution failed. In the case
4923 that overload resolution fails, *CANDIDATES will be the set of
4924 candidates considered, and ANY_VIABLE_P will be set to true or
4925 false to indicate whether or not any of the candidates were
4926 viable.
4927
4928 The ARGS should already have gone through RESOLVE_ARGS before this
4929 function is called. */
4930
4931 static struct z_candidate *
4932 perform_overload_resolution (tree fn,
4933 const vec<tree, va_gc> *args,
4934 struct z_candidate **candidates,
4935 bool *any_viable_p, tsubst_flags_t complain)
4936 {
4937 struct z_candidate *cand;
4938 tree explicit_targs;
4939 int template_only;
4940
4941 auto_cond_timevar tv (TV_OVERLOAD);
4942
4943 explicit_targs = NULL_TREE;
4944 template_only = 0;
4945
4946 *candidates = NULL;
4947 *any_viable_p = true;
4948
4949 /* Check FN. */
4950 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4951
4952 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4953 {
4954 explicit_targs = TREE_OPERAND (fn, 1);
4955 fn = TREE_OPERAND (fn, 0);
4956 template_only = 1;
4957 }
4958
4959 /* Add the various candidate functions. */
4960 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4961 explicit_targs, template_only,
4962 /*conversion_path=*/NULL_TREE,
4963 /*access_path=*/NULL_TREE,
4964 LOOKUP_NORMAL,
4965 candidates, complain);
4966
4967 *candidates = splice_viable (*candidates, false, any_viable_p);
4968 if (*any_viable_p)
4969 cand = tourney (*candidates, complain);
4970 else
4971 cand = NULL;
4972
4973 return cand;
4974 }
4975
4976 /* Print an error message about being unable to build a call to FN with
4977 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4978 be located; CANDIDATES is a possibly empty list of such
4979 functions. */
4980
4981 static void
4982 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4983 struct z_candidate *candidates)
4984 {
4985 tree targs = NULL_TREE;
4986 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4987 {
4988 targs = TREE_OPERAND (fn, 1);
4989 fn = TREE_OPERAND (fn, 0);
4990 }
4991 tree name = OVL_NAME (fn);
4992 location_t loc = location_of (name);
4993 if (targs)
4994 name = lookup_template_function (name, targs);
4995
4996 auto_diagnostic_group d;
4997 if (!any_strictly_viable (candidates))
4998 error_at (loc, "no matching function for call to %<%D(%A)%>",
4999 name, build_tree_list_vec (args));
5000 else
5001 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
5002 name, build_tree_list_vec (args));
5003 if (candidates)
5004 print_z_candidates (loc, candidates);
5005 }
5006
5007 /* Perform overload resolution on the set of deduction guides DGUIDES
5008 using ARGS. Returns the selected deduction guide, or error_mark_node
5009 if overload resolution fails. */
5010
5011 tree
5012 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
5013 tsubst_flags_t complain)
5014 {
5015 z_candidate *candidates;
5016 bool any_viable_p;
5017 tree result;
5018
5019 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
5020
5021 conversion_obstack_sentinel cos;
5022
5023 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
5024 &any_viable_p, complain);
5025 if (!cand)
5026 {
5027 if (complain & tf_error)
5028 print_error_for_call_failure (dguides, args, candidates);
5029 result = error_mark_node;
5030 }
5031 else
5032 result = cand->fn;
5033
5034 return result;
5035 }
5036
5037 /* Return an expression for a call to FN (a namespace-scope function,
5038 or a static member function) with the ARGS. This may change
5039 ARGS. */
5040
5041 tree
5042 build_new_function_call (tree fn, vec<tree, va_gc> **args,
5043 tsubst_flags_t complain)
5044 {
5045 struct z_candidate *candidates, *cand;
5046 bool any_viable_p;
5047 tree result;
5048
5049 if (args != NULL && *args != NULL)
5050 {
5051 *args = resolve_args (*args, complain);
5052 if (*args == NULL)
5053 return error_mark_node;
5054 }
5055
5056 if (flag_tm)
5057 tm_malloc_replacement (fn);
5058
5059 conversion_obstack_sentinel cos;
5060
5061 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
5062 complain);
5063
5064 if (!cand)
5065 {
5066 if (complain & tf_error)
5067 {
5068 // If there is a single (non-viable) function candidate,
5069 // let the error be diagnosed by cp_build_function_call_vec.
5070 if (!any_viable_p && candidates && ! candidates->next
5071 && TREE_CODE (candidates->fn) == FUNCTION_DECL
5072 /* A template-id callee consisting of a single (ignored)
5073 non-template candidate needs to be diagnosed the
5074 ordinary way. */
5075 && (TREE_CODE (fn) != TEMPLATE_ID_EXPR
5076 || candidates->template_decl))
5077 return cp_build_function_call_vec (candidates->fn, args, complain);
5078
5079 // Otherwise, emit notes for non-viable candidates.
5080 print_error_for_call_failure (fn, *args, candidates);
5081 }
5082 result = error_mark_node;
5083 }
5084 else
5085 {
5086 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5087 }
5088
5089 if (flag_coroutines
5090 && result
5091 && TREE_CODE (result) == CALL_EXPR
5092 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5093 == BUILT_IN_NORMAL)
5094 result = coro_validate_builtin_call (result);
5095
5096 return result;
5097 }
5098
5099 /* Build a call to a global operator new. FNNAME is the name of the
5100 operator (either "operator new" or "operator new[]") and ARGS are
5101 the arguments provided. This may change ARGS. *SIZE points to the
5102 total number of bytes required by the allocation, and is updated if
5103 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5104 be used. If this function determines that no cookie should be
5105 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5106 is not NULL_TREE, it is evaluated before calculating the final
5107 array size, and if it fails, the array size is replaced with
5108 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5109 is non-NULL, it will be set, upon return, to the allocation
5110 function called. */
5111
5112 tree
5113 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5114 tree *size, tree *cookie_size,
5115 tree align_arg, tree size_check,
5116 tree *fn, tsubst_flags_t complain)
5117 {
5118 tree original_size = *size;
5119 tree fns;
5120 struct z_candidate *candidates;
5121 struct z_candidate *cand = NULL;
5122 bool any_viable_p;
5123
5124 if (fn)
5125 *fn = NULL_TREE;
5126 /* Set to (size_t)-1 if the size check fails. */
5127 if (size_check != NULL_TREE)
5128 {
5129 tree errval = TYPE_MAX_VALUE (sizetype);
5130 if (cxx_dialect >= cxx11 && flag_exceptions)
5131 errval = throw_bad_array_new_length ();
5132 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5133 original_size, errval);
5134 }
5135 vec_safe_insert (*args, 0, *size);
5136 *args = resolve_args (*args, complain);
5137 if (*args == NULL)
5138 return error_mark_node;
5139
5140 conversion_obstack_sentinel cos;
5141
5142 /* Based on:
5143
5144 [expr.new]
5145
5146 If this lookup fails to find the name, or if the allocated type
5147 is not a class type, the allocation function's name is looked
5148 up in the global scope.
5149
5150 we disregard block-scope declarations of "operator new". */
5151 fns = lookup_qualified_name (global_namespace, fnname);
5152
5153 if (align_arg)
5154 {
5155 vec<tree, va_gc>* align_args
5156 = vec_copy_and_insert (*args, align_arg, 1);
5157 cand = perform_overload_resolution (fns, align_args, &candidates,
5158 &any_viable_p, tf_none);
5159 if (cand)
5160 *args = align_args;
5161 /* If no aligned allocation function matches, try again without the
5162 alignment. */
5163 }
5164
5165 /* Figure out what function is being called. */
5166 if (!cand)
5167 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
5168 complain);
5169
5170 /* If no suitable function could be found, issue an error message
5171 and give up. */
5172 if (!cand)
5173 {
5174 if (complain & tf_error)
5175 print_error_for_call_failure (fns, *args, candidates);
5176 return error_mark_node;
5177 }
5178
5179 /* If a cookie is required, add some extra space. Whether
5180 or not a cookie is required cannot be determined until
5181 after we know which function was called. */
5182 if (*cookie_size)
5183 {
5184 bool use_cookie = true;
5185 tree arg_types;
5186
5187 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5188 /* Skip the size_t parameter. */
5189 arg_types = TREE_CHAIN (arg_types);
5190 /* Check the remaining parameters (if any). */
5191 if (arg_types
5192 && TREE_CHAIN (arg_types) == void_list_node
5193 && same_type_p (TREE_VALUE (arg_types),
5194 ptr_type_node))
5195 use_cookie = false;
5196 /* If we need a cookie, adjust the number of bytes allocated. */
5197 if (use_cookie)
5198 {
5199 /* Update the total size. */
5200 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5201 if (size_check)
5202 {
5203 /* Set to (size_t)-1 if the size check fails. */
5204 gcc_assert (size_check != NULL_TREE);
5205 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5206 *size, TYPE_MAX_VALUE (sizetype));
5207 }
5208 /* Update the argument list to reflect the adjusted size. */
5209 (**args)[0] = *size;
5210 }
5211 else
5212 *cookie_size = NULL_TREE;
5213 }
5214
5215 /* Tell our caller which function we decided to call. */
5216 if (fn)
5217 *fn = cand->fn;
5218
5219 /* Build the CALL_EXPR. */
5220 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5221
5222 /* Set this flag for all callers of this function. In addition to
5223 new-expressions, this is called for allocating coroutine state; treat
5224 that as an implicit new-expression. */
5225 tree call = extract_call_expr (ret);
5226 if (TREE_CODE (call) == CALL_EXPR)
5227 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5228
5229 return ret;
5230 }
5231
5232 /* Evaluate side-effects from OBJ before evaluating call
5233 to FN in RESULT expression.
5234 This is for expressions of the form `obj->fn(...)'
5235 where `fn' turns out to be a static member function and
5236 `obj' needs to be evaluated. `fn' could be also static operator[]
5237 or static operator(), in which cases the source expression
5238 would be `obj[...]' or `obj(...)'. */
5239
5240 tree
5241 keep_unused_object_arg (tree result, tree obj, tree fn)
5242 {
5243 if (result == NULL_TREE
5244 || result == error_mark_node
5245 || TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
5246 || !TREE_SIDE_EFFECTS (obj))
5247 return result;
5248
5249 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5250 volatile. */
5251 tree a = obj;
5252 if (TREE_THIS_VOLATILE (a))
5253 a = build_this (a);
5254 if (TREE_SIDE_EFFECTS (a))
5255 return cp_build_compound_expr (a, result, tf_error);
5256 return result;
5257 }
5258
5259 /* Build a new call to operator(). This may change ARGS. */
5260
5261 tree
5262 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5263 {
5264 struct z_candidate *candidates = 0, *cand;
5265 tree fns, convs, first_mem_arg = NULL_TREE;
5266 bool any_viable_p;
5267 tree result = NULL_TREE;
5268
5269 auto_cond_timevar tv (TV_OVERLOAD);
5270
5271 obj = mark_lvalue_use (obj);
5272
5273 if (error_operand_p (obj))
5274 return error_mark_node;
5275
5276 tree type = TREE_TYPE (obj);
5277
5278 obj = prep_operand (obj);
5279
5280 if (TYPE_PTRMEMFUNC_P (type))
5281 {
5282 if (complain & tf_error)
5283 /* It's no good looking for an overloaded operator() on a
5284 pointer-to-member-function. */
5285 error ("pointer-to-member function %qE cannot be called without "
5286 "an object; consider using %<.*%> or %<->*%>", obj);
5287 return error_mark_node;
5288 }
5289
5290 if (TYPE_BINFO (type))
5291 {
5292 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5293 if (fns == error_mark_node)
5294 return error_mark_node;
5295 }
5296 else
5297 fns = NULL_TREE;
5298
5299 if (args != NULL && *args != NULL)
5300 {
5301 *args = resolve_args (*args, complain);
5302 if (*args == NULL)
5303 return error_mark_node;
5304 }
5305
5306 conversion_obstack_sentinel cos;
5307
5308 if (fns)
5309 {
5310 first_mem_arg = obj;
5311
5312 add_candidates (BASELINK_FUNCTIONS (fns),
5313 first_mem_arg, *args, NULL_TREE,
5314 NULL_TREE, false,
5315 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5316 LOOKUP_NORMAL, &candidates, complain);
5317 }
5318
5319 bool any_call_ops = candidates != nullptr;
5320
5321 convs = lookup_conversions (type);
5322
5323 for (; convs; convs = TREE_CHAIN (convs))
5324 {
5325 tree totype = TREE_TYPE (convs);
5326
5327 if (TYPE_PTRFN_P (totype)
5328 || TYPE_REFFN_P (totype)
5329 || (TYPE_REF_P (totype)
5330 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5331 for (tree fn : ovl_range (TREE_VALUE (convs)))
5332 {
5333 if (DECL_NONCONVERTING_P (fn))
5334 continue;
5335
5336 if (TREE_CODE (fn) == TEMPLATE_DECL)
5337 {
5338 /* Making this work broke PR 71117 and 85118, so until the
5339 committee resolves core issue 2189, let's disable this
5340 candidate if there are any call operators. */
5341 if (any_call_ops)
5342 continue;
5343
5344 add_template_conv_candidate
5345 (&candidates, fn, obj, *args, totype,
5346 /*access_path=*/NULL_TREE,
5347 /*conversion_path=*/NULL_TREE, complain);
5348 }
5349 else
5350 add_conv_candidate (&candidates, fn, obj,
5351 *args, /*conversion_path=*/NULL_TREE,
5352 /*access_path=*/NULL_TREE, complain);
5353 }
5354 }
5355
5356 /* Be strict here because if we choose a bad conversion candidate, the
5357 errors we get won't mention the call context. */
5358 candidates = splice_viable (candidates, true, &any_viable_p);
5359 if (!any_viable_p)
5360 {
5361 if (complain & tf_error)
5362 {
5363 auto_diagnostic_group d;
5364 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5365 build_tree_list_vec (*args));
5366 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5367 }
5368 result = error_mark_node;
5369 }
5370 else
5371 {
5372 cand = tourney (candidates, complain);
5373 if (cand == 0)
5374 {
5375 if (complain & tf_error)
5376 {
5377 auto_diagnostic_group d;
5378 error ("call of %<(%T) (%A)%> is ambiguous",
5379 TREE_TYPE (obj), build_tree_list_vec (*args));
5380 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5381 }
5382 result = error_mark_node;
5383 }
5384 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5385 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5386 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5387 {
5388 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5389 /* In an expression of the form `a()' where cand->fn
5390 which is operator() turns out to be a static member function,
5391 `a' is none-the-less evaluated. */
5392 result = keep_unused_object_arg (result, obj, cand->fn);
5393 }
5394 else
5395 {
5396 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5397 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5398 -1, complain);
5399 else
5400 {
5401 gcc_checking_assert (TYPE_P (cand->fn));
5402 obj = convert_like (cand->convs[0], obj, complain);
5403 }
5404 obj = convert_from_reference (obj);
5405 result = cp_build_function_call_vec (obj, args, complain);
5406 }
5407 }
5408
5409 return result;
5410 }
5411
5412 /* Called by op_error to prepare format strings suitable for the error
5413 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5414 and a suffix (controlled by NTYPES). */
5415
5416 static const char *
5417 op_error_string (const char *errmsg, int ntypes, bool match)
5418 {
5419 const char *msg;
5420
5421 const char *msgp = concat (match ? G_("ambiguous overload for ")
5422 : G_("no match for "), errmsg, NULL);
5423
5424 if (ntypes == 3)
5425 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5426 else if (ntypes == 2)
5427 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5428 else
5429 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5430
5431 return msg;
5432 }
5433
5434 static void
5435 op_error (const op_location_t &loc,
5436 enum tree_code code, enum tree_code code2,
5437 tree arg1, tree arg2, tree arg3, bool match)
5438 {
5439 bool assop = code == MODIFY_EXPR;
5440 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5441
5442 switch (code)
5443 {
5444 case COND_EXPR:
5445 if (flag_diagnostics_show_caret)
5446 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5447 3, match),
5448 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5449 else
5450 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5451 "in %<%E ? %E : %E%>"), 3, match),
5452 arg1, arg2, arg3,
5453 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5454 break;
5455
5456 case POSTINCREMENT_EXPR:
5457 case POSTDECREMENT_EXPR:
5458 if (flag_diagnostics_show_caret)
5459 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5460 opname, TREE_TYPE (arg1));
5461 else
5462 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5463 1, match),
5464 opname, arg1, opname, TREE_TYPE (arg1));
5465 break;
5466
5467 case ARRAY_REF:
5468 if (flag_diagnostics_show_caret)
5469 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5470 TREE_TYPE (arg1), TREE_TYPE (arg2));
5471 else
5472 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5473 2, match),
5474 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5475 break;
5476
5477 case REALPART_EXPR:
5478 case IMAGPART_EXPR:
5479 if (flag_diagnostics_show_caret)
5480 error_at (loc, op_error_string (G_("%qs"), 1, match),
5481 opname, TREE_TYPE (arg1));
5482 else
5483 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5484 opname, opname, arg1, TREE_TYPE (arg1));
5485 break;
5486
5487 case CO_AWAIT_EXPR:
5488 if (flag_diagnostics_show_caret)
5489 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5490 opname, TREE_TYPE (arg1));
5491 else
5492 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5493 1, match),
5494 opname, opname, arg1, TREE_TYPE (arg1));
5495 break;
5496
5497 default:
5498 if (arg2)
5499 if (flag_diagnostics_show_caret)
5500 {
5501 binary_op_rich_location richloc (loc, arg1, arg2, true);
5502 error_at (&richloc,
5503 op_error_string (G_("%<operator%s%>"), 2, match),
5504 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5505 }
5506 else
5507 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5508 2, match),
5509 opname, arg1, opname, arg2,
5510 TREE_TYPE (arg1), TREE_TYPE (arg2));
5511 else
5512 if (flag_diagnostics_show_caret)
5513 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5514 opname, TREE_TYPE (arg1));
5515 else
5516 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5517 1, match),
5518 opname, opname, arg1, TREE_TYPE (arg1));
5519 break;
5520 }
5521 }
5522
5523 /* Return the implicit conversion sequence that could be used to
5524 convert E1 to E2 in [expr.cond]. */
5525
5526 static conversion *
5527 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5528 {
5529 tree t1 = non_reference (TREE_TYPE (e1));
5530 tree t2 = non_reference (TREE_TYPE (e2));
5531 conversion *conv;
5532 bool good_base;
5533
5534 /* [expr.cond]
5535
5536 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5537 implicitly converted (clause _conv_) to the type "lvalue reference to
5538 T2", subject to the constraint that in the conversion the
5539 reference must bind directly (_dcl.init.ref_) to an lvalue.
5540
5541 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5542 implicitly converted to the type "rvalue reference to T2", subject to
5543 the constraint that the reference must bind directly. */
5544 if (glvalue_p (e2))
5545 {
5546 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5547 conv = implicit_conversion (rtype,
5548 t1,
5549 e1,
5550 /*c_cast_p=*/false,
5551 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5552 |LOOKUP_ONLYCONVERTING,
5553 complain);
5554 if (conv && !conv->bad_p)
5555 return conv;
5556 }
5557
5558 /* If E2 is a prvalue or if neither of the conversions above can be done
5559 and at least one of the operands has (possibly cv-qualified) class
5560 type: */
5561 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5562 return NULL;
5563
5564 /* [expr.cond]
5565
5566 If E1 and E2 have class type, and the underlying class types are
5567 the same or one is a base class of the other: E1 can be converted
5568 to match E2 if the class of T2 is the same type as, or a base
5569 class of, the class of T1, and the cv-qualification of T2 is the
5570 same cv-qualification as, or a greater cv-qualification than, the
5571 cv-qualification of T1. If the conversion is applied, E1 is
5572 changed to an rvalue of type T2 that still refers to the original
5573 source class object (or the appropriate subobject thereof). */
5574 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5575 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5576 {
5577 if (good_base && at_least_as_qualified_p (t2, t1))
5578 {
5579 conv = build_identity_conv (t1, e1);
5580 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5581 TYPE_MAIN_VARIANT (t2)))
5582 conv = build_conv (ck_base, t2, conv);
5583 else
5584 conv = build_conv (ck_rvalue, t2, conv);
5585 return conv;
5586 }
5587 else
5588 return NULL;
5589 }
5590 else
5591 /* [expr.cond]
5592
5593 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5594 converted to the type that expression E2 would have if E2 were
5595 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5596 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5597 LOOKUP_IMPLICIT, complain);
5598 }
5599
5600 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5601 arguments to the conditional expression. */
5602
5603 tree
5604 build_conditional_expr (const op_location_t &loc,
5605 tree arg1, tree arg2, tree arg3,
5606 tsubst_flags_t complain)
5607 {
5608 tree arg2_type;
5609 tree arg3_type;
5610 tree result = NULL_TREE;
5611 tree result_type = NULL_TREE;
5612 tree semantic_result_type = NULL_TREE;
5613 bool is_glvalue = true;
5614 struct z_candidate *candidates = 0;
5615 struct z_candidate *cand;
5616 tree orig_arg2, orig_arg3;
5617
5618 auto_cond_timevar tv (TV_OVERLOAD);
5619
5620 /* As a G++ extension, the second argument to the conditional can be
5621 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5622 c'.) If the second operand is omitted, make sure it is
5623 calculated only once. */
5624 if (!arg2)
5625 {
5626 if (complain & tf_error)
5627 pedwarn (loc, OPT_Wpedantic,
5628 "ISO C++ forbids omitting the middle term of "
5629 "a %<?:%> expression");
5630
5631 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5632 warn_for_omitted_condop (loc, arg1);
5633
5634 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5635 if (glvalue_p (arg1))
5636 {
5637 arg1 = cp_stabilize_reference (arg1);
5638 arg2 = arg1 = prevent_lifetime_extension (arg1);
5639 }
5640 else if (TREE_CODE (arg1) == TARGET_EXPR)
5641 /* arg1 can't be a prvalue result of the conditional
5642 expression, since it needs to be materialized for the
5643 conversion to bool, so treat it as an xvalue in arg2. */
5644 arg2 = move (TARGET_EXPR_SLOT (arg1));
5645 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5646 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5647 cp_save_expr (TREE_OPERAND (arg1, 0)));
5648 else
5649 arg2 = arg1 = cp_save_expr (arg1);
5650 }
5651
5652 /* If something has already gone wrong, just pass that fact up the
5653 tree. */
5654 if (error_operand_p (arg1)
5655 || error_operand_p (arg2)
5656 || error_operand_p (arg3))
5657 return error_mark_node;
5658
5659 conversion_obstack_sentinel cos;
5660
5661 orig_arg2 = arg2;
5662 orig_arg3 = arg3;
5663
5664 if (gnu_vector_type_p (TREE_TYPE (arg1))
5665 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5666 {
5667 tree arg1_type = TREE_TYPE (arg1);
5668
5669 /* If arg1 is another cond_expr choosing between -1 and 0,
5670 then we can use its comparison. It may help to avoid
5671 additional comparison, produce more accurate diagnostics
5672 and enables folding. */
5673 if (TREE_CODE (arg1) == VEC_COND_EXPR
5674 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5675 && integer_zerop (TREE_OPERAND (arg1, 2)))
5676 arg1 = TREE_OPERAND (arg1, 0);
5677
5678 arg1 = force_rvalue (arg1, complain);
5679 arg2 = force_rvalue (arg2, complain);
5680 arg3 = force_rvalue (arg3, complain);
5681
5682 /* force_rvalue can return error_mark on valid arguments. */
5683 if (error_operand_p (arg1)
5684 || error_operand_p (arg2)
5685 || error_operand_p (arg3))
5686 return error_mark_node;
5687
5688 arg2_type = TREE_TYPE (arg2);
5689 arg3_type = TREE_TYPE (arg3);
5690
5691 if (!VECTOR_TYPE_P (arg2_type)
5692 && !VECTOR_TYPE_P (arg3_type))
5693 {
5694 /* Rely on the error messages of the scalar version. */
5695 tree scal = build_conditional_expr (loc, integer_one_node,
5696 orig_arg2, orig_arg3, complain);
5697 if (scal == error_mark_node)
5698 return error_mark_node;
5699 tree stype = TREE_TYPE (scal);
5700 tree ctype = TREE_TYPE (arg1_type);
5701 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5702 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5703 {
5704 if (complain & tf_error)
5705 error_at (loc, "inferred scalar type %qT is not an integer or "
5706 "floating-point type of the same size as %qT", stype,
5707 COMPARISON_CLASS_P (arg1)
5708 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5709 : ctype);
5710 return error_mark_node;
5711 }
5712
5713 tree vtype = build_opaque_vector_type (stype,
5714 TYPE_VECTOR_SUBPARTS (arg1_type));
5715 /* We could pass complain & tf_warning to unsafe_conversion_p,
5716 but the warnings (like Wsign-conversion) have already been
5717 given by the scalar build_conditional_expr_1. We still check
5718 unsafe_conversion_p to forbid truncating long long -> float. */
5719 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5720 {
5721 if (complain & tf_error)
5722 error_at (loc, "conversion of scalar %qH to vector %qI "
5723 "involves truncation", arg2_type, vtype);
5724 return error_mark_node;
5725 }
5726 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5727 {
5728 if (complain & tf_error)
5729 error_at (loc, "conversion of scalar %qH to vector %qI "
5730 "involves truncation", arg3_type, vtype);
5731 return error_mark_node;
5732 }
5733
5734 arg2 = cp_convert (stype, arg2, complain);
5735 arg2 = save_expr (arg2);
5736 arg2 = build_vector_from_val (vtype, arg2);
5737 arg2_type = vtype;
5738 arg3 = cp_convert (stype, arg3, complain);
5739 arg3 = save_expr (arg3);
5740 arg3 = build_vector_from_val (vtype, arg3);
5741 arg3_type = vtype;
5742 }
5743
5744 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5745 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5746 {
5747 enum stv_conv convert_flag =
5748 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5749 complain & tf_error);
5750
5751 switch (convert_flag)
5752 {
5753 case stv_error:
5754 return error_mark_node;
5755 case stv_firstarg:
5756 {
5757 arg2 = save_expr (arg2);
5758 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5759 arg2 = build_vector_from_val (arg3_type, arg2);
5760 arg2_type = TREE_TYPE (arg2);
5761 break;
5762 }
5763 case stv_secondarg:
5764 {
5765 arg3 = save_expr (arg3);
5766 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5767 arg3 = build_vector_from_val (arg2_type, arg3);
5768 arg3_type = TREE_TYPE (arg3);
5769 break;
5770 }
5771 default:
5772 break;
5773 }
5774 }
5775
5776 if (!gnu_vector_type_p (arg2_type)
5777 || !gnu_vector_type_p (arg3_type)
5778 || !same_type_p (arg2_type, arg3_type)
5779 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5780 TYPE_VECTOR_SUBPARTS (arg2_type))
5781 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5782 {
5783 if (complain & tf_error)
5784 error_at (loc,
5785 "incompatible vector types in conditional expression: "
5786 "%qT, %qT and %qT", TREE_TYPE (arg1),
5787 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5788 return error_mark_node;
5789 }
5790
5791 if (!COMPARISON_CLASS_P (arg1))
5792 {
5793 tree cmp_type = truth_type_for (arg1_type);
5794 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5795 }
5796 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5797 }
5798
5799 /* [expr.cond]
5800
5801 The first expression is implicitly converted to bool (clause
5802 _conv_). */
5803 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5804 LOOKUP_NORMAL);
5805 if (error_operand_p (arg1))
5806 return error_mark_node;
5807
5808 arg2_type = unlowered_expr_type (arg2);
5809 arg3_type = unlowered_expr_type (arg3);
5810
5811 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5812 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5813 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5814 || SCALAR_FLOAT_TYPE_P (arg2_type)
5815 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5816 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5817 || SCALAR_FLOAT_TYPE_P (arg3_type)
5818 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5819 {
5820 semantic_result_type
5821 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5822 if (semantic_result_type == error_mark_node)
5823 {
5824 tree t1 = arg2_type;
5825 tree t2 = arg3_type;
5826 if (TREE_CODE (t1) == COMPLEX_TYPE)
5827 t1 = TREE_TYPE (t1);
5828 if (TREE_CODE (t2) == COMPLEX_TYPE)
5829 t2 = TREE_TYPE (t2);
5830 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
5831 && SCALAR_FLOAT_TYPE_P (t2)
5832 && (extended_float_type_p (t1)
5833 || extended_float_type_p (t2))
5834 && cp_compare_floating_point_conversion_ranks
5835 (t1, t2) == 3);
5836 if (complain & tf_error)
5837 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5838 "have unordered conversion rank",
5839 arg2_type, arg3_type);
5840 return error_mark_node;
5841 }
5842 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5843 {
5844 arg2 = TREE_OPERAND (arg2, 0);
5845 arg2_type = TREE_TYPE (arg2);
5846 }
5847 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5848 {
5849 arg3 = TREE_OPERAND (arg3, 0);
5850 arg3_type = TREE_TYPE (arg3);
5851 }
5852 }
5853
5854 /* [expr.cond]
5855
5856 If either the second or the third operand has type (possibly
5857 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5858 array-to-pointer (_conv.array_), and function-to-pointer
5859 (_conv.func_) standard conversions are performed on the second
5860 and third operands. */
5861 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5862 {
5863 /* 'void' won't help in resolving an overloaded expression on the
5864 other side, so require it to resolve by itself. */
5865 if (arg2_type == unknown_type_node)
5866 {
5867 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5868 arg2_type = TREE_TYPE (arg2);
5869 }
5870 if (arg3_type == unknown_type_node)
5871 {
5872 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5873 arg3_type = TREE_TYPE (arg3);
5874 }
5875
5876 /* [expr.cond]
5877
5878 One of the following shall hold:
5879
5880 --The second or the third operand (but not both) is a
5881 throw-expression (_except.throw_); the result is of the type
5882 and value category of the other.
5883
5884 --Both the second and the third operands have type void; the
5885 result is of type void and is a prvalue. */
5886 if (TREE_CODE (arg2) == THROW_EXPR
5887 && TREE_CODE (arg3) != THROW_EXPR)
5888 {
5889 result_type = arg3_type;
5890 is_glvalue = glvalue_p (arg3);
5891 }
5892 else if (TREE_CODE (arg2) != THROW_EXPR
5893 && TREE_CODE (arg3) == THROW_EXPR)
5894 {
5895 result_type = arg2_type;
5896 is_glvalue = glvalue_p (arg2);
5897 }
5898 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5899 {
5900 result_type = void_type_node;
5901 is_glvalue = false;
5902 }
5903 else
5904 {
5905 if (complain & tf_error)
5906 {
5907 if (VOID_TYPE_P (arg2_type))
5908 error_at (cp_expr_loc_or_loc (arg3, loc),
5909 "second operand to the conditional operator "
5910 "is of type %<void%>, but the third operand is "
5911 "neither a throw-expression nor of type %<void%>");
5912 else
5913 error_at (cp_expr_loc_or_loc (arg2, loc),
5914 "third operand to the conditional operator "
5915 "is of type %<void%>, but the second operand is "
5916 "neither a throw-expression nor of type %<void%>");
5917 }
5918 return error_mark_node;
5919 }
5920
5921 goto valid_operands;
5922 }
5923 /* [expr.cond]
5924
5925 Otherwise, if the second and third operand have different types,
5926 and either has (possibly cv-qualified) class type, or if both are
5927 glvalues of the same value category and the same type except for
5928 cv-qualification, an attempt is made to convert each of those operands
5929 to the type of the other. */
5930 else if (!same_type_p (arg2_type, arg3_type)
5931 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5932 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5933 arg3_type)
5934 && glvalue_p (arg2) && glvalue_p (arg3)
5935 && lvalue_p (arg2) == lvalue_p (arg3))))
5936 {
5937 conversion *conv2;
5938 conversion *conv3;
5939 bool converted = false;
5940
5941 conv2 = conditional_conversion (arg2, arg3, complain);
5942 conv3 = conditional_conversion (arg3, arg2, complain);
5943
5944 /* [expr.cond]
5945
5946 If both can be converted, or one can be converted but the
5947 conversion is ambiguous, the program is ill-formed. If
5948 neither can be converted, the operands are left unchanged and
5949 further checking is performed as described below. If exactly
5950 one conversion is possible, that conversion is applied to the
5951 chosen operand and the converted operand is used in place of
5952 the original operand for the remainder of this section. */
5953 if ((conv2 && !conv2->bad_p
5954 && conv3 && !conv3->bad_p)
5955 || (conv2 && conv2->kind == ck_ambig)
5956 || (conv3 && conv3->kind == ck_ambig))
5957 {
5958 if (complain & tf_error)
5959 {
5960 error_at (loc, "operands to %<?:%> have different types "
5961 "%qT and %qT",
5962 arg2_type, arg3_type);
5963 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5964 inform (loc, " and each type can be converted to the other");
5965 else if (conv2 && conv2->kind == ck_ambig)
5966 convert_like (conv2, arg2, complain);
5967 else
5968 convert_like (conv3, arg3, complain);
5969 }
5970 result = error_mark_node;
5971 }
5972 else if (conv2 && !conv2->bad_p)
5973 {
5974 arg2 = convert_like (conv2, arg2, complain);
5975 arg2 = convert_from_reference (arg2);
5976 arg2_type = TREE_TYPE (arg2);
5977 /* Even if CONV2 is a valid conversion, the result of the
5978 conversion may be invalid. For example, if ARG3 has type
5979 "volatile X", and X does not have a copy constructor
5980 accepting a "volatile X&", then even if ARG2 can be
5981 converted to X, the conversion will fail. */
5982 if (error_operand_p (arg2))
5983 result = error_mark_node;
5984 converted = true;
5985 }
5986 else if (conv3 && !conv3->bad_p)
5987 {
5988 arg3 = convert_like (conv3, arg3, complain);
5989 arg3 = convert_from_reference (arg3);
5990 arg3_type = TREE_TYPE (arg3);
5991 if (error_operand_p (arg3))
5992 result = error_mark_node;
5993 converted = true;
5994 }
5995
5996 if (result)
5997 return result;
5998
5999 /* If, after the conversion, both operands have class type,
6000 treat the cv-qualification of both operands as if it were the
6001 union of the cv-qualification of the operands.
6002
6003 The standard is not clear about what to do in this
6004 circumstance. For example, if the first operand has type
6005 "const X" and the second operand has a user-defined
6006 conversion to "volatile X", what is the type of the second
6007 operand after this step? Making it be "const X" (matching
6008 the first operand) seems wrong, as that discards the
6009 qualification without actually performing a copy. Leaving it
6010 as "volatile X" seems wrong as that will result in the
6011 conditional expression failing altogether, even though,
6012 according to this step, the one operand could be converted to
6013 the type of the other. */
6014 if (converted
6015 && CLASS_TYPE_P (arg2_type)
6016 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
6017 arg2_type = arg3_type =
6018 cp_build_qualified_type (arg2_type,
6019 cp_type_quals (arg2_type)
6020 | cp_type_quals (arg3_type));
6021 }
6022
6023 /* [expr.cond]
6024
6025 If the second and third operands are glvalues of the same value
6026 category and have the same type, the result is of that type and
6027 value category. */
6028 if (((lvalue_p (arg2) && lvalue_p (arg3))
6029 || (xvalue_p (arg2) && xvalue_p (arg3)))
6030 && same_type_p (arg2_type, arg3_type))
6031 {
6032 result_type = arg2_type;
6033 goto valid_operands;
6034 }
6035
6036 /* [expr.cond]
6037
6038 Otherwise, the result is an rvalue. If the second and third
6039 operand do not have the same type, and either has (possibly
6040 cv-qualified) class type, overload resolution is used to
6041 determine the conversions (if any) to be applied to the operands
6042 (_over.match.oper_, _over.built_). */
6043 is_glvalue = false;
6044 if (!same_type_p (arg2_type, arg3_type)
6045 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6046 {
6047 releasing_vec args;
6048 conversion *conv;
6049 bool any_viable_p;
6050
6051 /* Rearrange the arguments so that add_builtin_candidate only has
6052 to know about two args. In build_builtin_candidate, the
6053 arguments are unscrambled. */
6054 args->quick_push (arg2);
6055 args->quick_push (arg3);
6056 args->quick_push (arg1);
6057 add_builtin_candidates (&candidates,
6058 COND_EXPR,
6059 NOP_EXPR,
6060 ovl_op_identifier (false, COND_EXPR),
6061 args,
6062 LOOKUP_NORMAL, complain);
6063
6064 /* [expr.cond]
6065
6066 If the overload resolution fails, the program is
6067 ill-formed. */
6068 candidates = splice_viable (candidates, false, &any_viable_p);
6069 if (!any_viable_p)
6070 {
6071 if (complain & tf_error)
6072 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6073 arg2_type, arg3_type);
6074 return error_mark_node;
6075 }
6076 cand = tourney (candidates, complain);
6077 if (!cand)
6078 {
6079 if (complain & tf_error)
6080 {
6081 auto_diagnostic_group d;
6082 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, false);
6083 print_z_candidates (loc, candidates);
6084 }
6085 return error_mark_node;
6086 }
6087
6088 /* [expr.cond]
6089
6090 Otherwise, the conversions thus determined are applied, and
6091 the converted operands are used in place of the original
6092 operands for the remainder of this section. */
6093 conv = cand->convs[0];
6094 arg1 = convert_like (conv, arg1, complain);
6095 conv = cand->convs[1];
6096 arg2 = convert_like (conv, arg2, complain);
6097 arg2_type = TREE_TYPE (arg2);
6098 conv = cand->convs[2];
6099 arg3 = convert_like (conv, arg3, complain);
6100 arg3_type = TREE_TYPE (arg3);
6101 }
6102
6103 /* [expr.cond]
6104
6105 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6106 and function-to-pointer (_conv.func_) standard conversions are
6107 performed on the second and third operands.
6108
6109 We need to force the lvalue-to-rvalue conversion here for class types,
6110 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6111 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6112 regions. */
6113
6114 arg2 = force_rvalue (arg2, complain);
6115 if (!CLASS_TYPE_P (arg2_type))
6116 arg2_type = TREE_TYPE (arg2);
6117
6118 arg3 = force_rvalue (arg3, complain);
6119 if (!CLASS_TYPE_P (arg3_type))
6120 arg3_type = TREE_TYPE (arg3);
6121
6122 if (arg2 == error_mark_node || arg3 == error_mark_node)
6123 return error_mark_node;
6124
6125 /* [expr.cond]
6126
6127 After those conversions, one of the following shall hold:
6128
6129 --The second and third operands have the same type; the result is of
6130 that type. */
6131 if (same_type_p (arg2_type, arg3_type))
6132 result_type = arg2_type;
6133 /* [expr.cond]
6134
6135 --The second and third operands have arithmetic or enumeration
6136 type; the usual arithmetic conversions are performed to bring
6137 them to a common type, and the result is of that type. */
6138 else if ((ARITHMETIC_TYPE_P (arg2_type)
6139 || UNSCOPED_ENUM_P (arg2_type))
6140 && (ARITHMETIC_TYPE_P (arg3_type)
6141 || UNSCOPED_ENUM_P (arg3_type)))
6142 {
6143 /* A conditional expression between a floating-point
6144 type and an integer type should convert the integer type to
6145 the evaluation format of the floating-point type, with
6146 possible excess precision. */
6147 tree eptype2 = arg2_type;
6148 tree eptype3 = arg3_type;
6149 tree eptype;
6150 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6151 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6152 {
6153 eptype3 = eptype;
6154 if (!semantic_result_type)
6155 semantic_result_type
6156 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6157 }
6158 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6159 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6160 {
6161 eptype2 = eptype;
6162 if (!semantic_result_type)
6163 semantic_result_type
6164 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6165 }
6166 result_type = type_after_usual_arithmetic_conversions (eptype2,
6167 eptype3);
6168 if (result_type == error_mark_node)
6169 {
6170 tree t1 = eptype2;
6171 tree t2 = eptype3;
6172 if (TREE_CODE (t1) == COMPLEX_TYPE)
6173 t1 = TREE_TYPE (t1);
6174 if (TREE_CODE (t2) == COMPLEX_TYPE)
6175 t2 = TREE_TYPE (t2);
6176 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6177 && SCALAR_FLOAT_TYPE_P (t2)
6178 && (extended_float_type_p (t1)
6179 || extended_float_type_p (t2))
6180 && cp_compare_floating_point_conversion_ranks
6181 (t1, t2) == 3);
6182 if (complain & tf_error)
6183 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6184 "have unordered conversion rank",
6185 eptype2, eptype3);
6186 return error_mark_node;
6187 }
6188 if (semantic_result_type == error_mark_node)
6189 {
6190 tree t1 = arg2_type;
6191 tree t2 = arg3_type;
6192 if (TREE_CODE (t1) == COMPLEX_TYPE)
6193 t1 = TREE_TYPE (t1);
6194 if (TREE_CODE (t2) == COMPLEX_TYPE)
6195 t2 = TREE_TYPE (t2);
6196 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6197 && SCALAR_FLOAT_TYPE_P (t2)
6198 && (extended_float_type_p (t1)
6199 || extended_float_type_p (t2))
6200 && cp_compare_floating_point_conversion_ranks
6201 (t1, t2) == 3);
6202 if (complain & tf_error)
6203 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6204 "have unordered conversion rank",
6205 arg2_type, arg3_type);
6206 return error_mark_node;
6207 }
6208
6209 if (complain & tf_warning)
6210 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6211 "implicit conversion from %qH to %qI to "
6212 "match other result of conditional",
6213 loc);
6214
6215 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6216 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6217 {
6218 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
6219 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
6220 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6221 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6222 && (DECL_CONTEXT (stripped_orig_arg2)
6223 == DECL_CONTEXT (stripped_orig_arg3)))
6224 /* Two enumerators from the same enumeration can have different
6225 types when the enumeration is still being defined. */;
6226 else if (complain & (cxx_dialect >= cxx26
6227 ? tf_warning_or_error : tf_warning))
6228 emit_diagnostic (cxx_dialect >= cxx26 ? DK_PEDWARN : DK_WARNING,
6229 loc, OPT_Wenum_compare, "enumerated mismatch "
6230 "in conditional expression: %qT vs %qT",
6231 arg2_type, arg3_type);
6232 else if (cxx_dialect >= cxx26)
6233 return error_mark_node;
6234 }
6235 else if ((((complain & (cxx_dialect >= cxx26
6236 ? tf_warning_or_error : tf_warning))
6237 && warn_deprecated_enum_float_conv)
6238 || (cxx_dialect >= cxx26
6239 && (complain & tf_warning_or_error) == 0))
6240 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6241 && SCALAR_FLOAT_TYPE_P (arg3_type))
6242 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6243 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6244 {
6245 if (cxx_dialect >= cxx26 && (complain & tf_warning_or_error) == 0)
6246 return error_mark_node;
6247 if (cxx_dialect >= cxx26 && TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6248 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6249 "conditional expression between enumeration type "
6250 "%qT and floating-point type %qT", arg2_type, arg3_type);
6251 else if (cxx_dialect >= cxx26)
6252 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6253 "conditional expression between floating-point type "
6254 "%qT and enumeration type %qT", arg2_type, arg3_type);
6255 else if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6256 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6257 "conditional expression between enumeration type "
6258 "%qT and floating-point type %qT is deprecated",
6259 arg2_type, arg3_type);
6260 else
6261 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6262 "conditional expression between floating-point "
6263 "type %qT and enumeration type %qT is deprecated",
6264 arg2_type, arg3_type);
6265 }
6266 else if ((extra_warnings || warn_enum_conversion)
6267 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6268 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6269 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6270 && !same_type_p (arg2_type,
6271 type_promotes_to (arg3_type)))))
6272 {
6273 if (complain & tf_warning)
6274 {
6275 enum opt_code opt = (warn_enum_conversion
6276 ? OPT_Wenum_conversion
6277 : OPT_Wextra);
6278 warning_at (loc, opt, "enumerated and "
6279 "non-enumerated type in conditional expression");
6280 }
6281 }
6282
6283 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6284 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6285 }
6286 /* [expr.cond]
6287
6288 --The second and third operands have pointer type, or one has
6289 pointer type and the other is a null pointer constant; pointer
6290 conversions (_conv.ptr_) and qualification conversions
6291 (_conv.qual_) are performed to bring them to their composite
6292 pointer type (_expr.rel_). The result is of the composite
6293 pointer type.
6294
6295 --The second and third operands have pointer to member type, or
6296 one has pointer to member type and the other is a null pointer
6297 constant; pointer to member conversions (_conv.mem_) and
6298 qualification conversions (_conv.qual_) are performed to bring
6299 them to a common type, whose cv-qualification shall match the
6300 cv-qualification of either the second or the third operand.
6301 The result is of the common type. */
6302 else if ((null_ptr_cst_p (arg2)
6303 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6304 || (null_ptr_cst_p (arg3)
6305 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6306 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6307 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6308 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6309 {
6310 result_type = composite_pointer_type (loc,
6311 arg2_type, arg3_type, arg2,
6312 arg3, CPO_CONDITIONAL_EXPR,
6313 complain);
6314 if (result_type == error_mark_node)
6315 return error_mark_node;
6316 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6317 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6318 }
6319
6320 if (!result_type)
6321 {
6322 if (complain & tf_error)
6323 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6324 arg2_type, arg3_type);
6325 return error_mark_node;
6326 }
6327
6328 if (arg2 == error_mark_node || arg3 == error_mark_node)
6329 return error_mark_node;
6330
6331 valid_operands:
6332 if (processing_template_decl && is_glvalue)
6333 {
6334 /* Let lvalue_kind know this was a glvalue. */
6335 tree arg = (result_type == arg2_type ? arg2 : arg3);
6336 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6337 }
6338
6339 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
6340
6341 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6342 warn here, because the COND_EXPR will be turned into ARG2. */
6343 if (warn_duplicated_branches
6344 && (complain & tf_warning)
6345 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6346 OEP_ADDRESS_OF_SAME_FIELD)))
6347 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6348 "this condition has identical branches");
6349
6350 /* We can't use result_type below, as fold might have returned a
6351 throw_expr. */
6352
6353 if (!is_glvalue)
6354 {
6355 /* Expand both sides into the same slot, hopefully the target of
6356 the ?: expression. We used to check for TARGET_EXPRs here,
6357 but now we sometimes wrap them in NOP_EXPRs so the test would
6358 fail. */
6359 if (CLASS_TYPE_P (TREE_TYPE (result)))
6360 {
6361 result = get_target_expr (result, complain);
6362 /* Tell gimplify_modify_expr_rhs not to strip this in
6363 assignment context: we want both arms to initialize
6364 the same temporary. */
6365 TARGET_EXPR_NO_ELIDE (result) = true;
6366 }
6367 /* If this expression is an rvalue, but might be mistaken for an
6368 lvalue, we must add a NON_LVALUE_EXPR. */
6369 result = rvalue (result);
6370 if (semantic_result_type)
6371 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6372 result);
6373 }
6374 else
6375 {
6376 result = force_paren_expr (result);
6377 gcc_assert (semantic_result_type == NULL_TREE);
6378 }
6379
6380 return result;
6381 }
6382
6383 /* OPERAND is an operand to an expression. Perform necessary steps
6384 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6385 returned. */
6386
6387 static tree
6388 prep_operand (tree operand)
6389 {
6390 if (operand)
6391 {
6392 if (CLASS_TYPE_P (TREE_TYPE (operand))
6393 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6394 /* Make sure the template type is instantiated now. */
6395 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6396 }
6397
6398 return operand;
6399 }
6400
6401 /* True iff CONV represents a conversion sequence which no other can be better
6402 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6403 type (including binding to a reference to the same type). This is stronger
6404 than the standard's "identity" category, which also includes reference
6405 bindings that add cv-qualifiers or change rvalueness. */
6406
6407 static bool
6408 perfect_conversion_p (conversion *conv)
6409 {
6410 if (CONVERSION_RANK (conv) != cr_identity)
6411 return false;
6412 if (conv->kind == ck_ref_bind)
6413 {
6414 if (!conv->rvaluedness_matches_p)
6415 return false;
6416 if (!same_type_p (TREE_TYPE (conv->type),
6417 next_conversion (conv)->type))
6418 return false;
6419 }
6420 if (conv->check_narrowing)
6421 /* Brace elision is imperfect. */
6422 return false;
6423 return true;
6424 }
6425
6426 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6427 other candidate can be a better match. Since the template/non-template
6428 tiebreaker comes immediately after the conversion comparison in
6429 [over.match.best], a perfect non-template candidate is better than all
6430 templates. */
6431
6432 static bool
6433 perfect_candidate_p (z_candidate *cand)
6434 {
6435 if (cand->viable < 1)
6436 return false;
6437 /* CWG1402 makes an implicitly deleted move op worse than other
6438 candidates. */
6439 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6440 && move_fn_p (cand->fn))
6441 return false;
6442 int len = cand->num_convs;
6443 for (int i = 0; i < len; ++i)
6444 if (!perfect_conversion_p (cand->convs[i]))
6445 return false;
6446 if (conversion *conv = cand->second_conv)
6447 if (!perfect_conversion_p (conv))
6448 return false;
6449 return true;
6450 }
6451
6452 /* True iff one of CAND's argument conversions is missing. */
6453
6454 static bool
6455 missing_conversion_p (const z_candidate *cand)
6456 {
6457 for (unsigned i = 0; i < cand->num_convs; ++i)
6458 {
6459 conversion *conv = cand->convs[i];
6460 if (!conv)
6461 return true;
6462 if (conv->kind == ck_deferred_bad)
6463 {
6464 /* We don't know whether this conversion is outright invalid or
6465 just bad, so conservatively assume it's missing. */
6466 gcc_checking_assert (conv->bad_p);
6467 return true;
6468 }
6469 }
6470 return false;
6471 }
6472
6473 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6474 OVERLOAD) to the CANDIDATES, returning an updated list of
6475 CANDIDATES. The ARGS are the arguments provided to the call;
6476 if FIRST_ARG is non-null it is the implicit object argument,
6477 otherwise the first element of ARGS is used if needed. The
6478 EXPLICIT_TARGS are explicit template arguments provided.
6479 TEMPLATE_ONLY is true if only template functions should be
6480 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6481 add_function_candidate. */
6482
6483 static void
6484 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6485 tree return_type,
6486 tree explicit_targs, bool template_only,
6487 tree conversion_path, tree access_path,
6488 int flags,
6489 struct z_candidate **candidates,
6490 tsubst_flags_t complain)
6491 {
6492 tree ctype;
6493 const vec<tree, va_gc> *non_static_args;
6494 bool check_list_ctor = false;
6495 bool check_converting = false;
6496 unification_kind_t strict;
6497 tree ne_fns = NULL_TREE;
6498
6499 if (!fns)
6500 return;
6501
6502 /* Precalculate special handling of constructors and conversion ops. */
6503 tree fn = OVL_FIRST (fns);
6504 if (DECL_CONV_FN_P (fn))
6505 {
6506 check_list_ctor = false;
6507 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6508 if (flags & LOOKUP_NO_CONVERSION)
6509 /* We're doing return_type(x). */
6510 strict = DEDUCE_CONV;
6511 else
6512 /* We're doing x.operator return_type(). */
6513 strict = DEDUCE_EXACT;
6514 /* [over.match.funcs] For conversion functions, the function
6515 is considered to be a member of the class of the implicit
6516 object argument for the purpose of defining the type of
6517 the implicit object parameter. */
6518 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6519 }
6520 else
6521 {
6522 if (DECL_CONSTRUCTOR_P (fn))
6523 {
6524 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6525 /* For list-initialization we consider explicit constructors
6526 and complain if one is chosen. */
6527 check_converting
6528 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6529 == LOOKUP_ONLYCONVERTING);
6530 }
6531 strict = DEDUCE_CALL;
6532 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6533 }
6534
6535 /* P2468: Check if operator== is a rewrite target with first operand
6536 (*args)[0]; for now just do the lookups. */
6537 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6538 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6539 {
6540 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6541 if (DECL_CLASS_SCOPE_P (fn))
6542 {
6543 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6544 1, tf_none);
6545 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6546 ne_fns = NULL_TREE;
6547 else
6548 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6549 }
6550 else
6551 {
6552 tree context = decl_namespace_context (fn);
6553 ne_fns = lookup_qualified_name (context, ne_name, LOOK_want::NORMAL,
6554 /*complain*/false);
6555 if (ne_fns == error_mark_node
6556 || !is_overloaded_fn (ne_fns))
6557 ne_fns = NULL_TREE;
6558 }
6559 }
6560
6561 if (first_arg)
6562 non_static_args = args;
6563 else
6564 /* Delay creating the implicit this parameter until it is needed. */
6565 non_static_args = NULL;
6566
6567 bool seen_strictly_viable = any_strictly_viable (*candidates);
6568 /* If there's a non-template perfect match, we don't need to consider
6569 templates. So check non-templates first. This optimization is only
6570 really needed for the defaulted copy constructor of tuple and the like
6571 (96926), but it seems like we might as well enable it more generally. */
6572 bool seen_perfect = false;
6573 enum { templates, non_templates, either } which = either;
6574 if (template_only)
6575 which = templates;
6576 else /*if (flags & LOOKUP_DEFAULTED)*/
6577 which = non_templates;
6578
6579 /* Template candidates that we'll potentially ignore if the
6580 perfect candidate optimization succeeds. */
6581 z_candidate *ignored_template_cands = nullptr;
6582
6583 /* During overload resolution, we first consider each function under the
6584 assumption that we'll eventually find a strictly viable candidate.
6585 This allows us to circumvent our defacto behavior when checking
6586 argument conversions and shortcut consideration of the candidate
6587 upon encountering the first bad conversion. If this assumption
6588 turns out to be false, and all candidates end up being non-strictly
6589 viable, then we reconsider such candidates under the defacto behavior.
6590 This trick is important for pruning member function overloads according
6591 to their const/ref-qualifiers (since all 'this' conversions are at
6592 worst bad) without breaking -fpermissive. */
6593 z_candidate *bad_cands = nullptr;
6594 bool shortcut_bad_convs = true;
6595
6596 again:
6597 for (tree fn : lkp_range (fns))
6598 {
6599 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6600 {
6601 if (template_only)
6602 add_ignored_candidate (candidates, fn);
6603 continue;
6604 }
6605 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6606 {
6607 add_ignored_candidate (&ignored_template_cands, fn);
6608 continue;
6609 }
6610 if ((check_converting && DECL_NONCONVERTING_P (fn))
6611 || (check_list_ctor && !is_list_ctor (fn)))
6612 {
6613 add_ignored_candidate (candidates, fn);
6614 continue;
6615 }
6616
6617 tree fn_first_arg = NULL_TREE;
6618 const vec<tree, va_gc> *fn_args = args;
6619
6620 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6621 {
6622 /* Figure out where the object arg comes from. If this
6623 function is a non-static member and we didn't get an
6624 implicit object argument, move it out of args. */
6625 if (first_arg == NULL_TREE)
6626 {
6627 unsigned int ix;
6628 tree arg;
6629 vec<tree, va_gc> *tempvec;
6630 vec_alloc (tempvec, args->length () - 1);
6631 for (ix = 1; args->iterate (ix, &arg); ++ix)
6632 tempvec->quick_push (arg);
6633 non_static_args = tempvec;
6634 first_arg = (*args)[0];
6635 }
6636
6637 fn_first_arg = first_arg;
6638 fn_args = non_static_args;
6639 }
6640
6641 /* Don't bother reversing an operator with two identical parameters. */
6642 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6643 {
6644 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6645 if (same_type_p (TREE_VALUE (parmlist),
6646 TREE_VALUE (TREE_CHAIN (parmlist))))
6647 continue;
6648 }
6649
6650 /* When considering reversed operator==, if there's a corresponding
6651 operator!= in the same scope, it's not a rewrite target. */
6652 if (ne_fns)
6653 {
6654 bool found = false;
6655 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6656 if (0 && !ne.using_p ()
6657 && DECL_NAMESPACE_SCOPE_P (fn)
6658 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6659 /* ??? This kludge excludes inline namespace members for the H
6660 test in spaceship-eq15.C, but I don't see why we would want
6661 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6662 else if (fns_correspond (fn, *ne))
6663 {
6664 found = true;
6665 break;
6666 }
6667 if (found)
6668 continue;
6669 }
6670
6671 if (TREE_CODE (fn) == TEMPLATE_DECL)
6672 add_template_candidate (candidates,
6673 fn,
6674 ctype,
6675 explicit_targs,
6676 fn_first_arg,
6677 fn_args,
6678 return_type,
6679 access_path,
6680 conversion_path,
6681 flags,
6682 strict,
6683 shortcut_bad_convs,
6684 complain);
6685 else
6686 {
6687 add_function_candidate (candidates,
6688 fn,
6689 ctype,
6690 fn_first_arg,
6691 fn_args,
6692 access_path,
6693 conversion_path,
6694 flags,
6695 NULL,
6696 shortcut_bad_convs,
6697 complain);
6698 if (perfect_candidate_p (*candidates))
6699 seen_perfect = true;
6700 }
6701
6702 z_candidate *cand = *candidates;
6703 if (cand->viable == 1)
6704 seen_strictly_viable = true;
6705
6706 if (cand->viable == -1
6707 && shortcut_bad_convs
6708 && missing_conversion_p (cand))
6709 {
6710 /* This candidate has been tentatively marked non-strictly viable,
6711 and we didn't compute all argument conversions for it (having
6712 stopped at the first bad conversion). Move it to BAD_CANDS to
6713 to fully reconsider later if we don't find any strictly viable
6714 candidates. */
6715 if (complain & (tf_error | tf_conv))
6716 {
6717 *candidates = cand->next;
6718 cand->next = bad_cands;
6719 bad_cands = cand;
6720 }
6721 else
6722 /* But if we're in a SFINAE context, just mark this candidate as
6723 unviable outright and avoid potentially reconsidering it.
6724 This is safe to do because in a SFINAE context, performing a bad
6725 conversion is always an error (even with -fpermissive), so a
6726 non-strictly viable candidate is effectively unviable anyway. */
6727 cand->viable = 0;
6728 }
6729 }
6730 if (which == non_templates && !seen_perfect)
6731 {
6732 which = templates;
6733 ignored_template_cands = nullptr;
6734 goto again;
6735 }
6736 else if (which == templates
6737 && !seen_strictly_viable
6738 && shortcut_bad_convs
6739 && bad_cands)
6740 {
6741 /* None of the candidates are strictly viable, so consider again those
6742 functions in BAD_CANDS, this time without shortcutting bad conversions
6743 so that all their argument conversions are computed. */
6744 which = either;
6745 fns = NULL_TREE;
6746 for (z_candidate *cand = bad_cands; cand; cand = cand->next)
6747 {
6748 tree fn = cand->fn;
6749 if (tree ti = cand->template_decl)
6750 fn = TI_TEMPLATE (ti);
6751 fns = ovl_make (fn, fns);
6752 }
6753 shortcut_bad_convs = false;
6754 bad_cands = nullptr;
6755 goto again;
6756 }
6757
6758 if (complain & tf_error)
6759 {
6760 /* Remember any omitted candidates; we may want to print all candidates
6761 as part of overload resolution failure diagnostics. */
6762 for (z_candidate *omitted_cands : { ignored_template_cands, bad_cands })
6763 {
6764 z_candidate **omitted_cands_tail = &omitted_cands;
6765 while (*omitted_cands_tail)
6766 omitted_cands_tail = &(*omitted_cands_tail)->next;
6767 *omitted_cands_tail = *candidates;
6768 *candidates = omitted_cands;
6769 }
6770 }
6771 }
6772
6773 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6774 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6775
6776 static int
6777 op_is_ordered (tree_code code)
6778 {
6779 switch (code)
6780 {
6781 // 5. b @= a
6782 case MODIFY_EXPR:
6783 return (flag_strong_eval_order > 1 ? -1 : 0);
6784
6785 // 6. a[b]
6786 case ARRAY_REF:
6787 return (flag_strong_eval_order > 1 ? 1 : 0);
6788
6789 // 1. a.b
6790 // Not overloadable (yet).
6791 // 2. a->b
6792 // Only one argument.
6793 // 3. a->*b
6794 case MEMBER_REF:
6795 // 7. a << b
6796 case LSHIFT_EXPR:
6797 // 8. a >> b
6798 case RSHIFT_EXPR:
6799 // a && b
6800 // Predates P0145R3.
6801 case TRUTH_ANDIF_EXPR:
6802 // a || b
6803 // Predates P0145R3.
6804 case TRUTH_ORIF_EXPR:
6805 // a , b
6806 // Predates P0145R3.
6807 case COMPOUND_EXPR:
6808 return (flag_strong_eval_order ? 1 : 0);
6809
6810 default:
6811 return 0;
6812 }
6813 }
6814
6815 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6816 operator indicated by CODE/CODE2. This function calls itself recursively to
6817 handle C++20 rewritten comparison operator candidates.
6818
6819 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6820 overloads to consider. This parameter is used when instantiating a
6821 dependent operator expression and has the same structure as
6822 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6823
6824 static tree
6825 add_operator_candidates (z_candidate **candidates,
6826 tree_code code, tree_code code2,
6827 vec<tree, va_gc> *arglist, tree lookups,
6828 int flags, tsubst_flags_t complain)
6829 {
6830 z_candidate *start_candidates = *candidates;
6831 bool ismodop = code2 != ERROR_MARK;
6832 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6833
6834 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6835 rewrite from, and also when we're looking for the e.g. < operator to use
6836 on the result of <=>. In the latter case, we don't want the flag set in
6837 the candidate, we just want to suppress looking for rewrites. */
6838 bool rewritten = (flags & LOOKUP_REWRITTEN);
6839 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6840 flags &= ~LOOKUP_REWRITTEN;
6841
6842 bool memonly = false;
6843 switch (code)
6844 {
6845 /* =, ->, [], () must be non-static member functions. */
6846 case MODIFY_EXPR:
6847 if (code2 != NOP_EXPR)
6848 break;
6849 /* FALLTHRU */
6850 case COMPONENT_REF:
6851 case ARRAY_REF:
6852 memonly = true;
6853 break;
6854
6855 default:
6856 break;
6857 }
6858
6859 /* Add namespace-scope operators to the list of functions to
6860 consider. */
6861 if (!memonly)
6862 {
6863 tree fns;
6864 if (!lookups)
6865 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6866 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6867 expression, and LOOKUPS is the result of stage 1 name lookup. */
6868 else if (tree found = purpose_member (fnname, lookups))
6869 fns = TREE_VALUE (found);
6870 else
6871 fns = NULL_TREE;
6872 fns = lookup_arg_dependent (fnname, fns, arglist);
6873 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6874 NULL_TREE, false, NULL_TREE, NULL_TREE,
6875 flags, candidates, complain);
6876 }
6877
6878 /* Add class-member operators to the candidate set. */
6879 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6880 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6881 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6882 if (CLASS_TYPE_P (arg1_type))
6883 {
6884 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6885 if (fns == error_mark_node)
6886 return error_mark_node;
6887 if (fns)
6888 {
6889 if (code == ARRAY_REF)
6890 {
6891 vec<tree,va_gc> *restlist = make_tree_vector ();
6892 for (unsigned i = 1; i < nargs; ++i)
6893 vec_safe_push (restlist, (*arglist)[i]);
6894 z_candidate *save_cand = *candidates;
6895 add_candidates (BASELINK_FUNCTIONS (fns),
6896 (*arglist)[0], restlist, NULL_TREE,
6897 NULL_TREE, false,
6898 BASELINK_BINFO (fns),
6899 BASELINK_ACCESS_BINFO (fns),
6900 flags, candidates, complain);
6901 /* Release the vec if we didn't add a candidate that uses it. */
6902 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6903 if (c->args == restlist)
6904 {
6905 restlist = NULL;
6906 break;
6907 }
6908 release_tree_vector (restlist);
6909 }
6910 else
6911 add_candidates (BASELINK_FUNCTIONS (fns),
6912 NULL_TREE, arglist, NULL_TREE,
6913 NULL_TREE, false,
6914 BASELINK_BINFO (fns),
6915 BASELINK_ACCESS_BINFO (fns),
6916 flags, candidates, complain);
6917 }
6918 }
6919 /* Per [over.match.oper]3.2, if no operand has a class type, then
6920 only non-member functions that have type T1 or reference to
6921 cv-qualified-opt T1 for the first argument, if the first argument
6922 has an enumeration type, or T2 or reference to cv-qualified-opt
6923 T2 for the second argument, if the second argument has an
6924 enumeration type. Filter out those that don't match. */
6925 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6926 {
6927 struct z_candidate **candp, **next;
6928
6929 for (candp = candidates; *candp != start_candidates; candp = next)
6930 {
6931 unsigned i;
6932 z_candidate *cand = *candp;
6933 next = &cand->next;
6934
6935 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6936
6937 for (i = 0; i < nargs; ++i)
6938 {
6939 tree parmtype = TREE_VALUE (parmlist);
6940 tree argtype = unlowered_expr_type ((*arglist)[i]);
6941
6942 if (TYPE_REF_P (parmtype))
6943 parmtype = TREE_TYPE (parmtype);
6944 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6945 && (same_type_ignoring_top_level_qualifiers_p
6946 (argtype, parmtype)))
6947 break;
6948
6949 parmlist = TREE_CHAIN (parmlist);
6950 }
6951
6952 /* No argument has an appropriate type, so remove this
6953 candidate function from the list. */
6954 if (i == nargs)
6955 {
6956 *candp = cand->next;
6957 next = candp;
6958 }
6959 }
6960 }
6961
6962 if (!rewritten)
6963 {
6964 /* The standard says to rewrite built-in candidates, too,
6965 but there's no point. */
6966 add_builtin_candidates (candidates, code, code2, fnname, arglist,
6967 flags, complain);
6968
6969 /* Maybe add C++20 rewritten comparison candidates. */
6970 tree_code rewrite_code = ERROR_MARK;
6971 if (cxx_dialect >= cxx20
6972 && nargs == 2
6973 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6974 switch (code)
6975 {
6976 case LT_EXPR:
6977 case LE_EXPR:
6978 case GT_EXPR:
6979 case GE_EXPR:
6980 case SPACESHIP_EXPR:
6981 rewrite_code = SPACESHIP_EXPR;
6982 break;
6983
6984 case NE_EXPR:
6985 case EQ_EXPR:
6986 rewrite_code = EQ_EXPR;
6987 break;
6988
6989 default:;
6990 }
6991
6992 if (rewrite_code)
6993 {
6994 flags |= LOOKUP_REWRITTEN;
6995 if (rewrite_code != code)
6996 /* Add rewritten candidates in same order. */
6997 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6998 arglist, lookups, flags, complain);
6999
7000 z_candidate *save_cand = *candidates;
7001
7002 /* Add rewritten candidates in reverse order. */
7003 flags |= LOOKUP_REVERSED;
7004 vec<tree,va_gc> *revlist = make_tree_vector ();
7005 revlist->quick_push ((*arglist)[1]);
7006 revlist->quick_push ((*arglist)[0]);
7007 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7008 revlist, lookups, flags, complain);
7009
7010 /* Release the vec if we didn't add a candidate that uses it. */
7011 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7012 if (c->args == revlist)
7013 {
7014 revlist = NULL;
7015 break;
7016 }
7017 release_tree_vector (revlist);
7018 }
7019 }
7020
7021 return NULL_TREE;
7022 }
7023
7024 tree
7025 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
7026 tree arg1, tree arg2, tree arg3, tree lookups,
7027 tree *overload, tsubst_flags_t complain)
7028 {
7029 struct z_candidate *candidates = 0, *cand;
7030 releasing_vec arglist;
7031 tree result = NULL_TREE;
7032 bool result_valid_p = false;
7033 enum tree_code code2 = ERROR_MARK;
7034 enum tree_code code_orig_arg1 = ERROR_MARK;
7035 enum tree_code code_orig_arg2 = ERROR_MARK;
7036 bool strict_p;
7037 bool any_viable_p;
7038
7039 auto_cond_timevar tv (TV_OVERLOAD);
7040
7041 if (error_operand_p (arg1)
7042 || error_operand_p (arg2)
7043 || error_operand_p (arg3))
7044 return error_mark_node;
7045
7046 conversion_obstack_sentinel cos;
7047
7048 bool ismodop = code == MODIFY_EXPR;
7049 if (ismodop)
7050 {
7051 code2 = TREE_CODE (arg3);
7052 arg3 = NULL_TREE;
7053 }
7054
7055 tree arg1_type = unlowered_expr_type (arg1);
7056 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
7057
7058 arg1 = prep_operand (arg1);
7059
7060 switch (code)
7061 {
7062 case NEW_EXPR:
7063 case VEC_NEW_EXPR:
7064 case VEC_DELETE_EXPR:
7065 case DELETE_EXPR:
7066 /* Use build_operator_new_call and build_op_delete_call instead. */
7067 gcc_unreachable ();
7068
7069 case CALL_EXPR:
7070 /* Use build_op_call instead. */
7071 gcc_unreachable ();
7072
7073 case TRUTH_ORIF_EXPR:
7074 case TRUTH_ANDIF_EXPR:
7075 case TRUTH_AND_EXPR:
7076 case TRUTH_OR_EXPR:
7077 /* These are saved for the sake of warn_logical_operator. */
7078 code_orig_arg1 = TREE_CODE (arg1);
7079 code_orig_arg2 = TREE_CODE (arg2);
7080 break;
7081 case GT_EXPR:
7082 case LT_EXPR:
7083 case GE_EXPR:
7084 case LE_EXPR:
7085 case EQ_EXPR:
7086 case NE_EXPR:
7087 /* These are saved for the sake of maybe_warn_bool_compare. */
7088 code_orig_arg1 = TREE_CODE (arg1_type);
7089 code_orig_arg2 = TREE_CODE (arg2_type);
7090 break;
7091
7092 default:
7093 break;
7094 }
7095
7096 arg2 = prep_operand (arg2);
7097 arg3 = prep_operand (arg3);
7098
7099 if (code == COND_EXPR)
7100 /* Use build_conditional_expr instead. */
7101 gcc_unreachable ();
7102 else if (! OVERLOAD_TYPE_P (arg1_type)
7103 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7104 goto builtin;
7105
7106 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7107 {
7108 arg2 = integer_zero_node;
7109 arg2_type = integer_type_node;
7110 }
7111
7112 arglist->quick_push (arg1);
7113 if (arg2 != NULL_TREE)
7114 arglist->quick_push (arg2);
7115 if (arg3 != NULL_TREE)
7116 arglist->quick_push (arg3);
7117
7118 result = add_operator_candidates (&candidates, code, code2, arglist,
7119 lookups, flags, complain);
7120 if (result == error_mark_node)
7121 return error_mark_node;
7122
7123 switch (code)
7124 {
7125 case COMPOUND_EXPR:
7126 case ADDR_EXPR:
7127 /* For these, the built-in candidates set is empty
7128 [over.match.oper]/3. We don't want non-strict matches
7129 because exact matches are always possible with built-in
7130 operators. The built-in candidate set for COMPONENT_REF
7131 would be empty too, but since there are no such built-in
7132 operators, we accept non-strict matches for them. */
7133 strict_p = true;
7134 break;
7135
7136 default:
7137 strict_p = false;
7138 break;
7139 }
7140
7141 candidates = splice_viable (candidates, strict_p, &any_viable_p);
7142 if (!any_viable_p)
7143 {
7144 switch (code)
7145 {
7146 case POSTINCREMENT_EXPR:
7147 case POSTDECREMENT_EXPR:
7148 /* Don't try anything fancy if we're not allowed to produce
7149 errors. */
7150 if (!(complain & tf_error))
7151 return error_mark_node;
7152
7153 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7154 distinguish between prefix and postfix ++ and
7155 operator++() was used for both, so we allow this with
7156 -fpermissive. */
7157 else
7158 {
7159 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7160 const char *msg = (flag_permissive)
7161 ? G_("no %<%D(int)%> declared for postfix %qs,"
7162 " trying prefix operator instead")
7163 : G_("no %<%D(int)%> declared for postfix %qs");
7164 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7165 }
7166
7167 if (!flag_permissive)
7168 return error_mark_node;
7169
7170 if (code == POSTINCREMENT_EXPR)
7171 code = PREINCREMENT_EXPR;
7172 else
7173 code = PREDECREMENT_EXPR;
7174 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7175 NULL_TREE, lookups, overload, complain);
7176 break;
7177
7178 /* The caller will deal with these. */
7179 case ADDR_EXPR:
7180 case COMPOUND_EXPR:
7181 case COMPONENT_REF:
7182 case CO_AWAIT_EXPR:
7183 result = NULL_TREE;
7184 result_valid_p = true;
7185 break;
7186
7187 default:
7188 if (complain & tf_error)
7189 {
7190 /* If one of the arguments of the operator represents
7191 an invalid use of member function pointer, try to report
7192 a meaningful error ... */
7193 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7194 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7195 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7196 /* We displayed the error message. */;
7197 else
7198 {
7199 /* ... Otherwise, report the more generic
7200 "no matching operator found" error */
7201 auto_diagnostic_group d;
7202 op_error (loc, code, code2, arg1, arg2, arg3, false);
7203 print_z_candidates (loc, candidates);
7204 }
7205 }
7206 result = error_mark_node;
7207 break;
7208 }
7209 }
7210 else
7211 {
7212 cand = tourney (candidates, complain);
7213 if (cand == 0)
7214 {
7215 if (complain & tf_error)
7216 {
7217 auto_diagnostic_group d;
7218 op_error (loc, code, code2, arg1, arg2, arg3, true);
7219 print_z_candidates (loc, candidates);
7220 }
7221 result = error_mark_node;
7222 if (overload)
7223 *overload = error_mark_node;
7224 }
7225 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7226 {
7227 if (overload)
7228 *overload = cand->fn;
7229
7230 if (resolve_args (arglist, complain) == NULL)
7231 result = error_mark_node;
7232 else
7233 {
7234 tsubst_flags_t ocomplain = complain;
7235 if (cand->rewritten ())
7236 /* We'll wrap this call in another one. */
7237 ocomplain &= ~tf_decltype;
7238 if (cand->reversed ())
7239 {
7240 /* We swapped these in add_candidate, swap them back now. */
7241 std::swap (cand->convs[0], cand->convs[1]);
7242 if (cand->fn == current_function_decl)
7243 warning_at (loc, 0, "in C++20 this comparison calls the "
7244 "current function recursively with reversed "
7245 "arguments");
7246 }
7247 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7248 }
7249
7250 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7251 /* There won't be a CALL_EXPR. */;
7252 else if (result && result != error_mark_node)
7253 {
7254 tree call = extract_call_expr (result);
7255 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7256
7257 /* Specify evaluation order as per P0145R2. */
7258 CALL_EXPR_ORDERED_ARGS (call) = false;
7259 switch (op_is_ordered (code))
7260 {
7261 case -1:
7262 CALL_EXPR_REVERSE_ARGS (call) = true;
7263 break;
7264
7265 case 1:
7266 CALL_EXPR_ORDERED_ARGS (call) = true;
7267 break;
7268
7269 default:
7270 break;
7271 }
7272 }
7273
7274 /* If this was a C++20 rewritten comparison, adjust the result. */
7275 if (cand->rewritten ())
7276 {
7277 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7278 if (overload)
7279 *overload = NULL_TREE;
7280 switch (code)
7281 {
7282 case EQ_EXPR:
7283 gcc_checking_assert (cand->reversed ());
7284 gcc_fallthrough ();
7285 case NE_EXPR:
7286 if (result == error_mark_node)
7287 ;
7288 /* If a rewritten operator== candidate is selected by
7289 overload resolution for an operator @, its return type
7290 shall be cv bool.... */
7291 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7292 {
7293 if (complain & tf_error)
7294 {
7295 auto_diagnostic_group d;
7296 error_at (loc, "return type of %qD is not %qs",
7297 cand->fn, "bool");
7298 inform (loc, "used as rewritten candidate for "
7299 "comparison of %qT and %qT",
7300 arg1_type, arg2_type);
7301 }
7302 result = error_mark_node;
7303 }
7304 else if (code == NE_EXPR)
7305 /* !(y == x) or !(x == y) */
7306 result = build1_loc (loc, TRUTH_NOT_EXPR,
7307 boolean_type_node, result);
7308 break;
7309
7310 /* If a rewritten operator<=> candidate is selected by
7311 overload resolution for an operator @, x @ y is
7312 interpreted as 0 @ (y <=> x) if the selected candidate is
7313 a synthesized candidate with reversed order of parameters,
7314 or (x <=> y) @ 0 otherwise, using the selected rewritten
7315 operator<=> candidate. */
7316 case SPACESHIP_EXPR:
7317 if (!cand->reversed ())
7318 /* We're in the build_new_op call below for an outer
7319 reversed call; we don't need to do anything more. */
7320 break;
7321 gcc_fallthrough ();
7322 case LT_EXPR:
7323 case LE_EXPR:
7324 case GT_EXPR:
7325 case GE_EXPR:
7326 {
7327 tree lhs = result;
7328 tree rhs = integer_zero_node;
7329 if (cand->reversed ())
7330 std::swap (lhs, rhs);
7331 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7332 result = build_new_op (loc, code,
7333 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7334 lhs, rhs, NULL_TREE, lookups,
7335 NULL, complain);
7336 }
7337 break;
7338
7339 default:
7340 gcc_unreachable ();
7341 }
7342 }
7343
7344 /* In an expression of the form `a[]' where cand->fn
7345 which is operator[] turns out to be a static member function,
7346 `a' is none-the-less evaluated. */
7347 if (code == ARRAY_REF)
7348 result = keep_unused_object_arg (result, arg1, cand->fn);
7349 }
7350 else
7351 {
7352 /* Give any warnings we noticed during overload resolution. */
7353 if (cand->warnings && (complain & tf_warning))
7354 {
7355 struct candidate_warning *w;
7356 for (w = cand->warnings; w; w = w->next)
7357 joust (cand, w->loser, 1, complain);
7358 }
7359
7360 /* Check for comparison of different enum types. */
7361 switch (code)
7362 {
7363 case GT_EXPR:
7364 case LT_EXPR:
7365 case GE_EXPR:
7366 case LE_EXPR:
7367 case EQ_EXPR:
7368 case NE_EXPR:
7369 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7370 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7371 && (TYPE_MAIN_VARIANT (arg1_type)
7372 != TYPE_MAIN_VARIANT (arg2_type)))
7373 {
7374 if (cxx_dialect >= cxx26
7375 && (complain & tf_warning_or_error) == 0)
7376 result = error_mark_node;
7377 else if (cxx_dialect >= cxx26 || (complain & tf_warning))
7378 emit_diagnostic (cxx_dialect >= cxx26
7379 ? DK_PEDWARN : DK_WARNING,
7380 loc, OPT_Wenum_compare,
7381 "comparison between %q#T and %q#T",
7382 arg1_type, arg2_type);
7383 }
7384 break;
7385 default:
7386 break;
7387 }
7388
7389 /* "If a built-in candidate is selected by overload resolution, the
7390 operands of class type are converted to the types of the
7391 corresponding parameters of the selected operation function,
7392 except that the second standard conversion sequence of a
7393 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7394 conversion *conv = cand->convs[0];
7395 if (conv->user_conv_p)
7396 {
7397 conv = strip_standard_conversion (conv);
7398 arg1 = convert_like (conv, arg1, complain);
7399 }
7400
7401 if (arg2)
7402 {
7403 conv = cand->convs[1];
7404 if (conv->user_conv_p)
7405 {
7406 conv = strip_standard_conversion (conv);
7407 arg2 = convert_like (conv, arg2, complain);
7408 }
7409 }
7410
7411 if (arg3)
7412 {
7413 conv = cand->convs[2];
7414 if (conv->user_conv_p)
7415 {
7416 conv = strip_standard_conversion (conv);
7417 arg3 = convert_like (conv, arg3, complain);
7418 }
7419 }
7420 }
7421 }
7422
7423 if (result || result_valid_p)
7424 return result;
7425
7426 builtin:
7427 switch (code)
7428 {
7429 case MODIFY_EXPR:
7430 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7431
7432 case INDIRECT_REF:
7433 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7434
7435 case TRUTH_ANDIF_EXPR:
7436 case TRUTH_ORIF_EXPR:
7437 case TRUTH_AND_EXPR:
7438 case TRUTH_OR_EXPR:
7439 if ((complain & tf_warning) && !processing_template_decl)
7440 warn_logical_operator (loc, code, boolean_type_node,
7441 code_orig_arg1, arg1,
7442 code_orig_arg2, arg2);
7443 /* Fall through. */
7444 case GT_EXPR:
7445 case LT_EXPR:
7446 case GE_EXPR:
7447 case LE_EXPR:
7448 case EQ_EXPR:
7449 case NE_EXPR:
7450 if ((complain & tf_warning)
7451 && ((code_orig_arg1 == BOOLEAN_TYPE)
7452 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7453 maybe_warn_bool_compare (loc, code, arg1, arg2);
7454 if (complain & tf_warning && warn_tautological_compare)
7455 warn_tautological_cmp (loc, code, arg1, arg2);
7456 /* Fall through. */
7457 case SPACESHIP_EXPR:
7458 case PLUS_EXPR:
7459 case MINUS_EXPR:
7460 case MULT_EXPR:
7461 case TRUNC_DIV_EXPR:
7462 case MAX_EXPR:
7463 case MIN_EXPR:
7464 case LSHIFT_EXPR:
7465 case RSHIFT_EXPR:
7466 case TRUNC_MOD_EXPR:
7467 case BIT_AND_EXPR:
7468 case BIT_IOR_EXPR:
7469 case BIT_XOR_EXPR:
7470 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7471
7472 case UNARY_PLUS_EXPR:
7473 case NEGATE_EXPR:
7474 case BIT_NOT_EXPR:
7475 case TRUTH_NOT_EXPR:
7476 case PREINCREMENT_EXPR:
7477 case POSTINCREMENT_EXPR:
7478 case PREDECREMENT_EXPR:
7479 case POSTDECREMENT_EXPR:
7480 case REALPART_EXPR:
7481 case IMAGPART_EXPR:
7482 case ABS_EXPR:
7483 case CO_AWAIT_EXPR:
7484 return cp_build_unary_op (code, arg1, false, complain);
7485
7486 case ARRAY_REF:
7487 return cp_build_array_ref (input_location, arg1, arg2, complain);
7488
7489 case MEMBER_REF:
7490 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7491 RO_ARROW_STAR,
7492 complain),
7493 arg2, complain);
7494
7495 /* The caller will deal with these. */
7496 case ADDR_EXPR:
7497 case COMPONENT_REF:
7498 case COMPOUND_EXPR:
7499 return NULL_TREE;
7500
7501 default:
7502 gcc_unreachable ();
7503 }
7504 return NULL_TREE;
7505 }
7506
7507 /* Build a new call to operator[]. This may change ARGS. */
7508
7509 tree
7510 build_op_subscript (const op_location_t &loc, tree obj,
7511 vec<tree, va_gc> **args, tree *overload,
7512 tsubst_flags_t complain)
7513 {
7514 struct z_candidate *candidates = 0, *cand;
7515 tree fns, first_mem_arg = NULL_TREE;
7516 bool any_viable_p;
7517 tree result = NULL_TREE;
7518
7519 auto_cond_timevar tv (TV_OVERLOAD);
7520
7521 obj = mark_lvalue_use (obj);
7522
7523 if (error_operand_p (obj))
7524 return error_mark_node;
7525
7526 tree type = TREE_TYPE (obj);
7527
7528 obj = prep_operand (obj);
7529
7530 if (TYPE_BINFO (type))
7531 {
7532 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7533 1, complain);
7534 if (fns == error_mark_node)
7535 return error_mark_node;
7536 }
7537 else
7538 fns = NULL_TREE;
7539
7540 if (args != NULL && *args != NULL)
7541 {
7542 *args = resolve_args (*args, complain);
7543 if (*args == NULL)
7544 return error_mark_node;
7545 }
7546
7547 conversion_obstack_sentinel cos;
7548
7549 if (fns)
7550 {
7551 first_mem_arg = obj;
7552
7553 add_candidates (BASELINK_FUNCTIONS (fns),
7554 first_mem_arg, *args, NULL_TREE,
7555 NULL_TREE, false,
7556 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7557 LOOKUP_NORMAL, &candidates, complain);
7558 }
7559
7560 /* Be strict here because if we choose a bad conversion candidate, the
7561 errors we get won't mention the call context. */
7562 candidates = splice_viable (candidates, true, &any_viable_p);
7563 if (!any_viable_p)
7564 {
7565 if (complain & tf_error)
7566 {
7567 auto_diagnostic_group d;
7568 error ("no match for call to %<%T::operator[] (%A)%>",
7569 TREE_TYPE (obj), build_tree_list_vec (*args));
7570 print_z_candidates (loc, candidates);
7571 }
7572 result = error_mark_node;
7573 }
7574 else
7575 {
7576 cand = tourney (candidates, complain);
7577 if (cand == 0)
7578 {
7579 if (complain & tf_error)
7580 {
7581 auto_diagnostic_group d;
7582 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7583 TREE_TYPE (obj), build_tree_list_vec (*args));
7584 print_z_candidates (loc, candidates);
7585 }
7586 result = error_mark_node;
7587 }
7588 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7589 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7590 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7591 {
7592 if (overload)
7593 *overload = cand->fn;
7594 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7595 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7596 /* There won't be a CALL_EXPR. */;
7597 else if (result && result != error_mark_node)
7598 {
7599 tree call = extract_call_expr (result);
7600 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7601
7602 /* Specify evaluation order as per P0145R2. */
7603 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7604 }
7605
7606 /* In an expression of the form `a[]' where cand->fn
7607 which is operator[] turns out to be a static member function,
7608 `a' is none-the-less evaluated. */
7609 result = keep_unused_object_arg (result, obj, cand->fn);
7610 }
7611 else
7612 gcc_unreachable ();
7613 }
7614
7615 return result;
7616 }
7617
7618 /* CALL was returned by some call-building function; extract the actual
7619 CALL_EXPR from any bits that have been tacked on, e.g. by
7620 convert_from_reference. */
7621
7622 tree
7623 extract_call_expr (tree call)
7624 {
7625 while (TREE_CODE (call) == COMPOUND_EXPR)
7626 call = TREE_OPERAND (call, 1);
7627 if (REFERENCE_REF_P (call))
7628 call = TREE_OPERAND (call, 0);
7629 if (TREE_CODE (call) == TARGET_EXPR)
7630 call = TARGET_EXPR_INITIAL (call);
7631 if (cxx_dialect >= cxx20)
7632 switch (TREE_CODE (call))
7633 {
7634 /* C++20 rewritten comparison operators. */
7635 case TRUTH_NOT_EXPR:
7636 call = TREE_OPERAND (call, 0);
7637 break;
7638 case LT_EXPR:
7639 case LE_EXPR:
7640 case GT_EXPR:
7641 case GE_EXPR:
7642 case SPACESHIP_EXPR:
7643 {
7644 tree op0 = TREE_OPERAND (call, 0);
7645 if (integer_zerop (op0))
7646 call = TREE_OPERAND (call, 1);
7647 else
7648 call = op0;
7649 }
7650 break;
7651 default:;
7652 }
7653
7654 if (TREE_CODE (call) != CALL_EXPR
7655 && TREE_CODE (call) != AGGR_INIT_EXPR
7656 && call != error_mark_node)
7657 return NULL_TREE;
7658 return call;
7659 }
7660
7661 /* Returns true if FN has two parameters, of which the second has type
7662 size_t. */
7663
7664 static bool
7665 second_parm_is_size_t (tree fn)
7666 {
7667 tree t = FUNCTION_ARG_CHAIN (fn);
7668 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7669 return false;
7670 t = TREE_CHAIN (t);
7671 if (t == void_list_node)
7672 return true;
7673 return false;
7674 }
7675
7676 /* True if T, an allocation function, has std::align_val_t as its second
7677 argument. */
7678
7679 bool
7680 aligned_allocation_fn_p (tree t)
7681 {
7682 if (!aligned_new_threshold)
7683 return false;
7684
7685 tree a = FUNCTION_ARG_CHAIN (t);
7686 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7687 }
7688
7689 /* True if T is std::destroying_delete_t. */
7690
7691 static bool
7692 std_destroying_delete_t_p (tree t)
7693 {
7694 return (TYPE_CONTEXT (t) == std_node
7695 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7696 }
7697
7698 /* A deallocation function with at least two parameters whose second parameter
7699 type is of type std::destroying_delete_t is a destroying operator delete. A
7700 destroying operator delete shall be a class member function named operator
7701 delete. [ Note: Array deletion cannot use a destroying operator
7702 delete. --end note ] */
7703
7704 tree
7705 destroying_delete_p (tree t)
7706 {
7707 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7708 if (!a || !TREE_CHAIN (a))
7709 return NULL_TREE;
7710 tree type = TREE_VALUE (TREE_CHAIN (a));
7711 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7712 }
7713
7714 struct dealloc_info
7715 {
7716 bool sized;
7717 bool aligned;
7718 tree destroying;
7719 };
7720
7721 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7722 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7723 non-null, also set *DI. */
7724
7725 static bool
7726 usual_deallocation_fn_p (tree t, dealloc_info *di)
7727 {
7728 if (di) *di = dealloc_info();
7729
7730 /* A template instance is never a usual deallocation function,
7731 regardless of its signature. */
7732 if (TREE_CODE (t) == TEMPLATE_DECL
7733 || primary_template_specialization_p (t))
7734 return false;
7735
7736 /* A usual deallocation function is a deallocation function whose parameters
7737 after the first are
7738 - optionally, a parameter of type std::destroying_delete_t, then
7739 - optionally, a parameter of type std::size_t, then
7740 - optionally, a parameter of type std::align_val_t. */
7741 bool global = DECL_NAMESPACE_SCOPE_P (t);
7742 tree chain = FUNCTION_ARG_CHAIN (t);
7743 if (chain && destroying_delete_p (t))
7744 {
7745 if (di) di->destroying = TREE_VALUE (chain);
7746 chain = TREE_CHAIN (chain);
7747 }
7748 if (chain
7749 && (!global || flag_sized_deallocation)
7750 && same_type_p (TREE_VALUE (chain), size_type_node))
7751 {
7752 if (di) di->sized = true;
7753 chain = TREE_CHAIN (chain);
7754 }
7755 if (chain && aligned_new_threshold
7756 && same_type_p (TREE_VALUE (chain), align_type_node))
7757 {
7758 if (di) di->aligned = true;
7759 chain = TREE_CHAIN (chain);
7760 }
7761 return (chain == void_list_node);
7762 }
7763
7764 /* Just return whether FN is a usual deallocation function. */
7765
7766 bool
7767 usual_deallocation_fn_p (tree fn)
7768 {
7769 return usual_deallocation_fn_p (fn, NULL);
7770 }
7771
7772 /* Build a call to operator delete. This has to be handled very specially,
7773 because the restrictions on what signatures match are different from all
7774 other call instances. For a normal delete, only a delete taking (void *)
7775 or (void *, size_t) is accepted. For a placement delete, only an exact
7776 match with the placement new is accepted.
7777
7778 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7779 ADDR is the pointer to be deleted.
7780 SIZE is the size of the memory block to be deleted.
7781 GLOBAL_P is true if the delete-expression should not consider
7782 class-specific delete operators.
7783 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7784
7785 If this call to "operator delete" is being generated as part to
7786 deallocate memory allocated via a new-expression (as per [expr.new]
7787 which requires that if the initialization throws an exception then
7788 we call a deallocation function), then ALLOC_FN is the allocation
7789 function. */
7790
7791 tree
7792 build_op_delete_call (enum tree_code code, tree addr, tree size,
7793 bool global_p, tree placement,
7794 tree alloc_fn, tsubst_flags_t complain)
7795 {
7796 tree fn = NULL_TREE;
7797 tree fns, fnname, type, t;
7798 dealloc_info di_fn = { };
7799
7800 if (addr == error_mark_node)
7801 return error_mark_node;
7802
7803 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7804
7805 fnname = ovl_op_identifier (false, code);
7806
7807 if (CLASS_TYPE_P (type)
7808 && COMPLETE_TYPE_P (complete_type (type))
7809 && !global_p)
7810 /* In [class.free]
7811
7812 If the result of the lookup is ambiguous or inaccessible, or if
7813 the lookup selects a placement deallocation function, the
7814 program is ill-formed.
7815
7816 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7817 {
7818 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7819 if (fns == error_mark_node)
7820 return error_mark_node;
7821 }
7822 else
7823 fns = NULL_TREE;
7824
7825 if (fns == NULL_TREE)
7826 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7827
7828 /* Strip const and volatile from addr. */
7829 tree oaddr = addr;
7830 addr = cp_convert (ptr_type_node, addr, complain);
7831
7832 tree excluded_destroying = NULL_TREE;
7833
7834 if (placement)
7835 {
7836 /* "A declaration of a placement deallocation function matches the
7837 declaration of a placement allocation function if it has the same
7838 number of parameters and, after parameter transformations (8.3.5),
7839 all parameter types except the first are identical."
7840
7841 So we build up the function type we want and ask instantiate_type
7842 to get it for us. */
7843 t = FUNCTION_ARG_CHAIN (alloc_fn);
7844 t = tree_cons (NULL_TREE, ptr_type_node, t);
7845 t = build_function_type (void_type_node, t);
7846
7847 fn = instantiate_type (t, fns, tf_none);
7848 if (fn == error_mark_node)
7849 return NULL_TREE;
7850
7851 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7852
7853 /* "If the lookup finds the two-parameter form of a usual deallocation
7854 function (3.7.4.2) and that function, considered as a placement
7855 deallocation function, would have been selected as a match for the
7856 allocation function, the program is ill-formed." */
7857 if (second_parm_is_size_t (fn))
7858 {
7859 const char *const msg1
7860 = G_("exception cleanup for this placement new selects "
7861 "non-placement %<operator delete%>");
7862 const char *const msg2
7863 = G_("%qD is a usual (non-placement) deallocation "
7864 "function in C++14 (or with %<-fsized-deallocation%>)");
7865
7866 /* But if the class has an operator delete (void *), then that is
7867 the usual deallocation function, so we shouldn't complain
7868 about using the operator delete (void *, size_t). */
7869 if (DECL_CLASS_SCOPE_P (fn))
7870 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7871 {
7872 if (usual_deallocation_fn_p (elt)
7873 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7874 goto ok;
7875 }
7876 /* Before C++14 a two-parameter global deallocation function is
7877 always a placement deallocation function, but warn if
7878 -Wc++14-compat. */
7879 else if (!flag_sized_deallocation)
7880 {
7881 if (complain & tf_warning)
7882 {
7883 auto_diagnostic_group d;
7884 if (warning (OPT_Wc__14_compat, msg1))
7885 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7886 }
7887 goto ok;
7888 }
7889
7890 if (complain & tf_warning_or_error)
7891 {
7892 auto_diagnostic_group d;
7893 if (permerror (input_location, msg1))
7894 {
7895 /* Only mention C++14 for namespace-scope delete. */
7896 if (DECL_NAMESPACE_SCOPE_P (fn))
7897 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7898 else
7899 inform (DECL_SOURCE_LOCATION (fn),
7900 "%qD is a usual (non-placement) deallocation "
7901 "function", fn);
7902 }
7903 }
7904 else
7905 return error_mark_node;
7906 ok:;
7907 }
7908 }
7909 else
7910 /* "Any non-placement deallocation function matches a non-placement
7911 allocation function. If the lookup finds a single matching
7912 deallocation function, that function will be called; otherwise, no
7913 deallocation function will be called." */
7914 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7915 {
7916 dealloc_info di_elt;
7917 if (usual_deallocation_fn_p (elt, &di_elt))
7918 {
7919 /* If we're called for an EH cleanup in a new-expression, we can't
7920 use a destroying delete; the exception was thrown before the
7921 object was constructed. */
7922 if (alloc_fn && di_elt.destroying)
7923 {
7924 excluded_destroying = elt;
7925 continue;
7926 }
7927
7928 if (!fn)
7929 {
7930 fn = elt;
7931 di_fn = di_elt;
7932 continue;
7933 }
7934
7935 /* -- If any of the deallocation functions is a destroying
7936 operator delete, all deallocation functions that are not
7937 destroying operator deletes are eliminated from further
7938 consideration. */
7939 if (di_elt.destroying != di_fn.destroying)
7940 {
7941 if (di_elt.destroying)
7942 {
7943 fn = elt;
7944 di_fn = di_elt;
7945 }
7946 continue;
7947 }
7948
7949 /* -- If the type has new-extended alignment, a function with a
7950 parameter of type std::align_val_t is preferred; otherwise a
7951 function without such a parameter is preferred. If exactly one
7952 preferred function is found, that function is selected and the
7953 selection process terminates. If more than one preferred
7954 function is found, all non-preferred functions are eliminated
7955 from further consideration. */
7956 if (aligned_new_threshold)
7957 {
7958 bool want_align = type_has_new_extended_alignment (type);
7959 if (di_elt.aligned != di_fn.aligned)
7960 {
7961 if (want_align == di_elt.aligned)
7962 {
7963 fn = elt;
7964 di_fn = di_elt;
7965 }
7966 continue;
7967 }
7968 }
7969
7970 /* -- If the deallocation functions have class scope, the one
7971 without a parameter of type std::size_t is selected. */
7972 bool want_size;
7973 if (DECL_CLASS_SCOPE_P (fn))
7974 want_size = false;
7975
7976 /* -- If the type is complete and if, for the second alternative
7977 (delete array) only, the operand is a pointer to a class type
7978 with a non-trivial destructor or a (possibly multi-dimensional)
7979 array thereof, the function with a parameter of type std::size_t
7980 is selected.
7981
7982 -- Otherwise, it is unspecified whether a deallocation function
7983 with a parameter of type std::size_t is selected. */
7984 else
7985 {
7986 want_size = COMPLETE_TYPE_P (type);
7987 if (code == VEC_DELETE_EXPR
7988 && !TYPE_VEC_NEW_USES_COOKIE (type))
7989 /* We need a cookie to determine the array size. */
7990 want_size = false;
7991 }
7992 gcc_assert (di_fn.sized != di_elt.sized);
7993 if (want_size == di_elt.sized)
7994 {
7995 fn = elt;
7996 di_fn = di_elt;
7997 }
7998 }
7999 }
8000
8001 /* If we have a matching function, call it. */
8002 if (fn)
8003 {
8004 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8005
8006 /* If the FN is a member function, make sure that it is
8007 accessible. */
8008 if (BASELINK_P (fns))
8009 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
8010 complain);
8011
8012 /* Core issue 901: It's ok to new a type with deleted delete. */
8013 if (DECL_DELETED_FN (fn) && alloc_fn)
8014 return NULL_TREE;
8015
8016 tree ret;
8017 if (placement)
8018 {
8019 /* The placement args might not be suitable for overload
8020 resolution at this point, so build the call directly. */
8021 int nargs = call_expr_nargs (placement);
8022 tree *argarray = XALLOCAVEC (tree, nargs);
8023 int i;
8024 argarray[0] = addr;
8025 for (i = 1; i < nargs; i++)
8026 argarray[i] = CALL_EXPR_ARG (placement, i);
8027 if (!mark_used (fn, complain) && !(complain & tf_error))
8028 return error_mark_node;
8029 ret = build_cxx_call (fn, nargs, argarray, complain);
8030 }
8031 else
8032 {
8033 tree destroying = di_fn.destroying;
8034 if (destroying)
8035 {
8036 /* Strip const and volatile from addr but retain the type of the
8037 object. */
8038 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
8039 rtype = cv_unqualified (rtype);
8040 rtype = TYPE_POINTER_TO (rtype);
8041 addr = cp_convert (rtype, oaddr, complain);
8042 destroying = build_functional_cast (input_location,
8043 destroying, NULL_TREE,
8044 complain);
8045 }
8046
8047 releasing_vec args;
8048 args->quick_push (addr);
8049 if (destroying)
8050 args->quick_push (destroying);
8051 if (di_fn.sized)
8052 args->quick_push (size);
8053 if (di_fn.aligned)
8054 {
8055 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
8056 args->quick_push (al);
8057 }
8058 ret = cp_build_function_call_vec (fn, &args, complain);
8059 }
8060
8061 /* Set this flag for all callers of this function. In addition to
8062 delete-expressions, this is called for deallocating coroutine state;
8063 treat that as an implicit delete-expression. This is also called for
8064 the delete if the constructor throws in a new-expression, and for a
8065 deleting destructor (which implements a delete-expression). */
8066 /* But leave this flag off for destroying delete to avoid wrong
8067 assumptions in the optimizers. */
8068 tree call = extract_call_expr (ret);
8069 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
8070 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
8071
8072 return ret;
8073 }
8074
8075 /* If there's only a destroying delete that we can't use because the
8076 object isn't constructed yet, and we used global new, use global
8077 delete as well. */
8078 if (excluded_destroying
8079 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
8080 return build_op_delete_call (code, addr, size, true, placement,
8081 alloc_fn, complain);
8082
8083 /* [expr.new]
8084
8085 If no unambiguous matching deallocation function can be found,
8086 propagating the exception does not cause the object's memory to
8087 be freed. */
8088 if (alloc_fn)
8089 {
8090 if ((complain & tf_warning)
8091 && !placement)
8092 {
8093 bool w = warning (0,
8094 "no corresponding deallocation function for %qD",
8095 alloc_fn);
8096 if (w && excluded_destroying)
8097 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8098 "delete %qD cannot be used to release the allocated memory"
8099 " if the initialization throws because the object is not "
8100 "constructed yet", excluded_destroying);
8101 }
8102 return NULL_TREE;
8103 }
8104
8105 if (complain & tf_error)
8106 error ("no suitable %<operator %s%> for %qT",
8107 OVL_OP_INFO (false, code)->name, type);
8108 return error_mark_node;
8109 }
8110
8111 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8112 in the diagnostics.
8113
8114 If ISSUE_ERROR is true, then issue an error about the access, followed
8115 by a note showing the declaration. Otherwise, just show the note.
8116
8117 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8118 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8119 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8120 would be because DECL was private). If not using NO_ACCESS_REASON,
8121 then it must be ak_none, and the access failure reason will be
8122 figured out by looking at the protection of DECL. */
8123
8124 void
8125 complain_about_access (tree decl, tree diag_decl, tree diag_location,
8126 bool issue_error, access_kind no_access_reason)
8127 {
8128 /* If we have not already figured out why DECL is inaccessible... */
8129 if (no_access_reason == ak_none)
8130 {
8131 /* Examine the access of DECL to find out why. */
8132 if (TREE_PRIVATE (decl))
8133 no_access_reason = ak_private;
8134 else if (TREE_PROTECTED (decl))
8135 no_access_reason = ak_protected;
8136 }
8137
8138 /* Now generate an error message depending on calculated access. */
8139 if (no_access_reason == ak_private)
8140 {
8141 if (issue_error)
8142 error ("%q#D is private within this context", diag_decl);
8143 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8144 }
8145 else if (no_access_reason == ak_protected)
8146 {
8147 if (issue_error)
8148 error ("%q#D is protected within this context", diag_decl);
8149 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8150 }
8151 /* Couldn't figure out why DECL is inaccesible, so just say it's
8152 inaccessible. */
8153 else
8154 {
8155 if (issue_error)
8156 error ("%q#D is inaccessible within this context", diag_decl);
8157 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8158 }
8159 }
8160
8161 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8162 bitwise or of LOOKUP_* values. If any errors are warnings are
8163 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8164 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8165 to NULL. */
8166
8167 static tree
8168 build_temp (tree expr, tree type, int flags,
8169 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8170 {
8171 int savew, savee;
8172
8173 *diagnostic_kind = DK_UNSPECIFIED;
8174
8175 /* If the source is a packed field, calling the copy constructor will require
8176 binding the field to the reference parameter to the copy constructor, and
8177 we'll end up with an infinite loop. If we can use a bitwise copy, then
8178 do that now. */
8179 if ((lvalue_kind (expr) & clk_packed)
8180 && CLASS_TYPE_P (TREE_TYPE (expr))
8181 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8182 return get_target_expr (expr, complain);
8183
8184 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8185 But it turns out to be a subexpression, so perform temporary
8186 materialization now. */
8187 if (TREE_CODE (expr) == CALL_EXPR
8188 && CLASS_TYPE_P (type)
8189 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8190 expr = build_cplus_new (type, expr, complain);
8191
8192 savew = warningcount + werrorcount, savee = errorcount;
8193 releasing_vec args (make_tree_vector_single (expr));
8194 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8195 &args, type, flags, complain);
8196 if (warningcount + werrorcount > savew)
8197 *diagnostic_kind = DK_WARNING;
8198 else if (errorcount > savee)
8199 *diagnostic_kind = DK_ERROR;
8200 return expr;
8201 }
8202
8203 /* Get any location for EXPR, falling back to input_location.
8204
8205 If the result is in a system header and is the virtual location for
8206 a token coming from the expansion of a macro, unwind it to the
8207 location of the expansion point of the macro (e.g. to avoid the
8208 diagnostic being suppressed for expansions of NULL where "NULL" is
8209 in a system header). */
8210
8211 static location_t
8212 get_location_for_expr_unwinding_for_system_header (tree expr)
8213 {
8214 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8215 loc = expansion_point_location_if_in_system_header (loc);
8216 return loc;
8217 }
8218
8219 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
8220 Also handle a subset of zero as null warnings.
8221 EXPR is implicitly converted to type TOTYPE.
8222 FN and ARGNUM are used for diagnostics. */
8223
8224 static void
8225 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8226 {
8227 /* Issue warnings about peculiar, but valid, uses of NULL. */
8228 if (TREE_CODE (totype) != BOOLEAN_TYPE
8229 && ARITHMETIC_TYPE_P (totype)
8230 && null_node_p (expr))
8231 {
8232 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8233 if (fn)
8234 {
8235 auto_diagnostic_group d;
8236 if (warning_at (loc, OPT_Wconversion_null,
8237 "passing NULL to non-pointer argument %P of %qD",
8238 argnum, fn))
8239 inform (get_fndecl_argument_location (fn, argnum),
8240 " declared here");
8241 }
8242 else
8243 warning_at (loc, OPT_Wconversion_null,
8244 "converting to non-pointer type %qT from NULL", totype);
8245 }
8246
8247 /* Issue warnings if "false" is converted to a NULL pointer */
8248 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8249 && TYPE_PTR_P (totype))
8250 {
8251 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8252 if (fn)
8253 {
8254 auto_diagnostic_group d;
8255 if (warning_at (loc, OPT_Wconversion_null,
8256 "converting %<false%> to pointer type for argument "
8257 "%P of %qD", argnum, fn))
8258 inform (get_fndecl_argument_location (fn, argnum),
8259 " declared here");
8260 }
8261 else
8262 warning_at (loc, OPT_Wconversion_null,
8263 "converting %<false%> to pointer type %qT", totype);
8264 }
8265 /* Handle zero as null pointer warnings for cases other
8266 than EQ_EXPR and NE_EXPR */
8267 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8268 && null_ptr_cst_p (expr))
8269 {
8270 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8271 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8272 }
8273 }
8274
8275 /* We gave a diagnostic during a conversion. If this was in the second
8276 standard conversion sequence of a user-defined conversion sequence, say
8277 which user-defined conversion. */
8278
8279 static void
8280 maybe_print_user_conv_context (conversion *convs)
8281 {
8282 if (convs->user_conv_p)
8283 for (conversion *t = convs; t; t = next_conversion (t))
8284 if (t->kind == ck_user)
8285 {
8286 print_z_candidate (0, N_(" after user-defined conversion:"),
8287 t->cand);
8288 break;
8289 }
8290 }
8291
8292 /* Locate the parameter with the given index within FNDECL.
8293 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8294 Return the location of the FNDECL itself if there are problems. */
8295
8296 location_t
8297 get_fndecl_argument_location (tree fndecl, int argnum)
8298 {
8299 /* The locations of implicitly-declared functions are likely to be
8300 more meaningful than those of their parameters. */
8301 if (DECL_ARTIFICIAL (fndecl))
8302 return DECL_SOURCE_LOCATION (fndecl);
8303
8304 int i;
8305 tree param;
8306
8307 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8308 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8309 i < argnum && param;
8310 i++, param = TREE_CHAIN (param))
8311 ;
8312
8313 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8314 return the location of FNDECL. */
8315 if (param == NULL)
8316 return DECL_SOURCE_LOCATION (fndecl);
8317
8318 return DECL_SOURCE_LOCATION (param);
8319 }
8320
8321 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8322 within its declaration (or the fndecl itself if something went
8323 wrong). */
8324
8325 void
8326 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
8327 {
8328 if (fn)
8329 inform (get_fndecl_argument_location (fn, argnum),
8330 " initializing argument %P of %qD", argnum, fn);
8331 }
8332
8333 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8334 the conversion, EXPR is the expression we're converting. */
8335
8336 static void
8337 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8338 {
8339 if (cxx_dialect >= cxx20)
8340 return;
8341
8342 tree type = TREE_TYPE (expr);
8343 type = strip_pointer_operator (type);
8344
8345 if (TREE_CODE (type) != ARRAY_TYPE
8346 || TYPE_DOMAIN (type) == NULL_TREE)
8347 return;
8348
8349 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8350 pedwarn (loc, OPT_Wc__20_extensions,
8351 "conversions to arrays of unknown bound "
8352 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8353 }
8354
8355 /* We call this recursively in convert_like_internal. */
8356 static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8357 tsubst_flags_t);
8358
8359 /* Perform the conversions in CONVS on the expression EXPR. FN and
8360 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8361 indicates the `this' argument of a method. INNER is nonzero when
8362 being called to continue a conversion chain. It is negative when a
8363 reference binding will be applied, positive otherwise. If
8364 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8365 conversions will be emitted if appropriate. If C_CAST_P is true,
8366 this conversion is coming from a C-style cast; in that case,
8367 conversions to inaccessible bases are permitted. */
8368
8369 static tree
8370 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8371 bool issue_conversion_warnings, bool c_cast_p,
8372 bool nested_p, tsubst_flags_t complain)
8373 {
8374 tree totype = convs->type;
8375 diagnostic_t diag_kind;
8376 int flags;
8377 location_t loc = cp_expr_loc_or_input_loc (expr);
8378
8379 if (convs->bad_p && !(complain & tf_error))
8380 return error_mark_node;
8381
8382 if (convs->bad_p
8383 && convs->kind != ck_user
8384 && convs->kind != ck_list
8385 && convs->kind != ck_ambig
8386 && (convs->kind != ck_ref_bind
8387 || (convs->user_conv_p && next_conversion (convs)->bad_p))
8388 && (convs->kind != ck_rvalue
8389 || SCALAR_TYPE_P (totype))
8390 && convs->kind != ck_base)
8391 {
8392 int complained = 0;
8393 conversion *t = convs;
8394
8395 /* Give a helpful error if this is bad because of excess braces. */
8396 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8397 && SCALAR_TYPE_P (totype)
8398 && CONSTRUCTOR_NELTS (expr) > 0
8399 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8400 {
8401 complained = permerror (loc, "too many braces around initializer "
8402 "for %qT", totype);
8403 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8404 && CONSTRUCTOR_NELTS (expr) == 1)
8405 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8406 }
8407
8408 /* Give a helpful error if this is bad because a conversion to bool
8409 from std::nullptr_t requires direct-initialization. */
8410 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8411 && TREE_CODE (totype) == BOOLEAN_TYPE)
8412 complained = permerror (loc, "converting to %qH from %qI requires "
8413 "direct-initialization",
8414 totype, TREE_TYPE (expr));
8415
8416 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8417 && SCALAR_FLOAT_TYPE_P (totype)
8418 && (extended_float_type_p (TREE_TYPE (expr))
8419 || extended_float_type_p (totype)))
8420 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8421 totype))
8422 {
8423 case 2:
8424 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8425 "converting to %qH from %qI with greater "
8426 "conversion rank", totype, TREE_TYPE (expr)))
8427 complained = 1;
8428 else if (!complained)
8429 complained = -1;
8430 break;
8431 case 3:
8432 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8433 "converting to %qH from %qI with unordered "
8434 "conversion rank", totype, TREE_TYPE (expr)))
8435 complained = 1;
8436 else if (!complained)
8437 complained = -1;
8438 break;
8439 default:
8440 break;
8441 }
8442
8443 for (; t ; t = next_conversion (t))
8444 {
8445 if (t->kind == ck_user && t->cand->reason)
8446 {
8447 auto_diagnostic_group d;
8448 complained = permerror (loc, "invalid user-defined conversion "
8449 "from %qH to %qI", TREE_TYPE (expr),
8450 totype);
8451 if (complained)
8452 print_z_candidate (loc, N_("candidate is:"), t->cand);
8453 expr = convert_like (t, expr, fn, argnum,
8454 /*issue_conversion_warnings=*/false,
8455 /*c_cast_p=*/false, /*nested_p=*/true,
8456 complain);
8457 }
8458 else if (t->kind == ck_user || !t->bad_p)
8459 {
8460 expr = convert_like (t, expr, fn, argnum,
8461 /*issue_conversion_warnings=*/false,
8462 /*c_cast_p=*/false, /*nested_p=*/true,
8463 complain);
8464 if (t->bad_p)
8465 complained = 1;
8466 break;
8467 }
8468 else if (t->kind == ck_ambig)
8469 return convert_like (t, expr, fn, argnum,
8470 /*issue_conversion_warnings=*/false,
8471 /*c_cast_p=*/false, /*nested_p=*/true,
8472 complain);
8473 else if (t->kind == ck_identity)
8474 break;
8475 }
8476 if (!complained && expr != error_mark_node)
8477 {
8478 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8479 gcc_rich_location richloc (loc, &label);
8480 complained = permerror (&richloc,
8481 "invalid conversion from %qH to %qI",
8482 TREE_TYPE (expr), totype);
8483 }
8484 if (convs->kind == ck_ref_bind)
8485 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8486 LOOKUP_NORMAL, NULL_TREE,
8487 complain);
8488 else
8489 expr = cp_convert (totype, expr, complain);
8490 if (complained == 1)
8491 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8492 return expr;
8493 }
8494
8495 if (issue_conversion_warnings && (complain & tf_warning))
8496 conversion_null_warnings (totype, expr, fn, argnum);
8497
8498 switch (convs->kind)
8499 {
8500 case ck_user:
8501 {
8502 struct z_candidate *cand = convs->cand;
8503
8504 if (cand == NULL)
8505 /* We chose the surrogate function from add_conv_candidate, now we
8506 actually need to build the conversion. */
8507 cand = build_user_type_conversion_1 (totype, expr,
8508 LOOKUP_NO_CONVERSION, complain);
8509
8510 tree convfn = cand->fn;
8511
8512 /* When converting from an init list we consider explicit
8513 constructors, but actually trying to call one is an error. */
8514 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8515 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8516 /* Unless this is for direct-list-initialization. */
8517 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8518 /* And in C++98 a default constructor can't be explicit. */
8519 && cxx_dialect >= cxx11)
8520 {
8521 if (!(complain & tf_error))
8522 return error_mark_node;
8523 location_t loc = location_of (expr);
8524 if (CONSTRUCTOR_NELTS (expr) == 0
8525 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8526 {
8527 auto_diagnostic_group d;
8528 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8529 "would use explicit constructor %qD",
8530 totype, convfn))
8531 {
8532 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8533 convfn);
8534 inform (loc, "in C++11 and above a default constructor "
8535 "can be explicit");
8536 }
8537 }
8538 else
8539 {
8540 auto_diagnostic_group d;
8541 error ("converting to %qT from initializer list would use "
8542 "explicit constructor %qD", totype, convfn);
8543 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8544 convfn);
8545 }
8546 }
8547
8548 /* If we're initializing from {}, it's value-initialization. */
8549 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8550 && CONSTRUCTOR_NELTS (expr) == 0
8551 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8552 && !processing_template_decl)
8553 {
8554 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8555 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8556 return error_mark_node;
8557 expr = build_value_init (totype, complain);
8558 expr = get_target_expr (expr, complain);
8559 if (expr != error_mark_node)
8560 {
8561 TARGET_EXPR_LIST_INIT_P (expr) = true;
8562 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8563 }
8564 return expr;
8565 }
8566
8567 /* We don't know here whether EXPR is being used as an lvalue or
8568 rvalue, but we know it's read. */
8569 mark_exp_read (expr);
8570
8571 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8572 any more UDCs. */
8573 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8574 complain);
8575
8576 /* If this is a constructor or a function returning an aggr type,
8577 we need to build up a TARGET_EXPR. */
8578 if (DECL_CONSTRUCTOR_P (convfn))
8579 {
8580 expr = build_cplus_new (totype, expr, complain);
8581
8582 /* Remember that this was list-initialization. */
8583 if (convs->check_narrowing && expr != error_mark_node)
8584 TARGET_EXPR_LIST_INIT_P (expr) = true;
8585 }
8586
8587 return expr;
8588 }
8589 case ck_identity:
8590 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8591 {
8592 int nelts = CONSTRUCTOR_NELTS (expr);
8593 if (nelts == 0)
8594 expr = build_value_init (totype, complain);
8595 else if (nelts == 1)
8596 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8597 else
8598 gcc_unreachable ();
8599 }
8600 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8601 /*read_p=*/true, UNKNOWN_LOCATION,
8602 /*reject_builtin=*/true);
8603
8604 if (type_unknown_p (expr))
8605 expr = instantiate_type (totype, expr, complain);
8606 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8607 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8608 if (expr == null_node
8609 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8610 /* If __null has been converted to an integer type, we do not want to
8611 continue to warn about uses of EXPR as an integer, rather than as a
8612 pointer. */
8613 expr = build_int_cst (totype, 0);
8614 return expr;
8615 case ck_ambig:
8616 /* We leave bad_p off ck_ambig because overload resolution considers
8617 it valid, it just fails when we try to perform it. So we need to
8618 check complain here, too. */
8619 if (complain & tf_error)
8620 {
8621 /* Call build_user_type_conversion again for the error. */
8622 int flags = (convs->need_temporary_p
8623 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8624 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8625 gcc_assert (seen_error ());
8626 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8627 }
8628 return error_mark_node;
8629
8630 case ck_list:
8631 {
8632 /* Conversion to std::initializer_list<T>. */
8633 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8634 unsigned len = CONSTRUCTOR_NELTS (expr);
8635 tree array;
8636
8637 if (tree init = maybe_init_list_as_array (elttype, expr))
8638 {
8639 elttype = cp_build_qualified_type
8640 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8641 array = build_array_of_n_type (elttype, len);
8642 array = build_vec_init_expr (array, init, complain);
8643 array = get_target_expr (array);
8644 array = cp_build_addr_expr (array, complain);
8645 }
8646 else if (len)
8647 {
8648 tree val; unsigned ix;
8649
8650 tree new_ctor = build_constructor (init_list_type_node, NULL);
8651
8652 /* Convert all the elements. */
8653 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8654 {
8655 tree sub = convert_like (convs->u.list[ix], val, fn,
8656 argnum, false, false,
8657 /*nested_p=*/true, complain);
8658 if (sub == error_mark_node)
8659 return sub;
8660 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8661 && !check_narrowing (TREE_TYPE (sub), val, complain))
8662 return error_mark_node;
8663 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8664 NULL_TREE, sub);
8665 if (!TREE_CONSTANT (sub))
8666 TREE_CONSTANT (new_ctor) = false;
8667 }
8668 /* Build up the array. */
8669 elttype = cp_build_qualified_type
8670 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8671 array = build_array_of_n_type (elttype, len);
8672 array = finish_compound_literal (array, new_ctor, complain);
8673 /* This is dubious now, should be blessed by P2752. */
8674 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
8675 array = cp_build_addr_expr (array, complain);
8676 }
8677 else
8678 array = nullptr_node;
8679
8680 array = cp_convert (build_pointer_type (elttype), array, complain);
8681 if (array == error_mark_node)
8682 return error_mark_node;
8683
8684 /* Build up the initializer_list object. Note: fail gracefully
8685 if the object cannot be completed because, for example, no
8686 definition is provided (c++/80956). */
8687 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8688 if (!totype)
8689 return error_mark_node;
8690 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8691 vec<constructor_elt, va_gc> *vec = NULL;
8692 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8693 field = next_aggregate_field (DECL_CHAIN (field));
8694 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8695 tree new_ctor = build_constructor (totype, vec);
8696 return get_target_expr (new_ctor, complain);
8697 }
8698
8699 case ck_aggr:
8700 if (TREE_CODE (totype) == COMPLEX_TYPE)
8701 {
8702 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8703 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8704 real = perform_implicit_conversion (TREE_TYPE (totype),
8705 real, complain);
8706 imag = perform_implicit_conversion (TREE_TYPE (totype),
8707 imag, complain);
8708 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8709 return expr;
8710 }
8711 expr = reshape_init (totype, expr, complain);
8712 expr = get_target_expr (digest_init (totype, expr, complain),
8713 complain);
8714 if (expr != error_mark_node)
8715 TARGET_EXPR_LIST_INIT_P (expr) = true;
8716 return expr;
8717
8718 default:
8719 break;
8720 };
8721
8722 expr = convert_like (next_conversion (convs), expr, fn, argnum,
8723 convs->kind == ck_ref_bind
8724 ? issue_conversion_warnings : false,
8725 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8726 if (expr == error_mark_node)
8727 return error_mark_node;
8728
8729 switch (convs->kind)
8730 {
8731 case ck_rvalue:
8732 expr = decay_conversion (expr, complain);
8733 if (expr == error_mark_node)
8734 {
8735 if (complain & tf_error)
8736 {
8737 auto_diagnostic_group d;
8738 maybe_print_user_conv_context (convs);
8739 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8740 }
8741 return error_mark_node;
8742 }
8743
8744 if (! MAYBE_CLASS_TYPE_P (totype))
8745 return expr;
8746
8747 /* Don't introduce copies when passing arguments along to the inherited
8748 constructor. */
8749 if (current_function_decl
8750 && flag_new_inheriting_ctors
8751 && DECL_INHERITED_CTOR (current_function_decl))
8752 return expr;
8753
8754 if (TREE_CODE (expr) == TARGET_EXPR
8755 && TARGET_EXPR_LIST_INIT_P (expr))
8756 /* Copy-list-initialization doesn't actually involve a copy. */
8757 return expr;
8758
8759 /* Fall through. */
8760 case ck_base:
8761 if (convs->kind == ck_base && !convs->need_temporary_p)
8762 {
8763 /* We are going to bind a reference directly to a base-class
8764 subobject of EXPR. */
8765 /* Build an expression for `*((base*) &expr)'. */
8766 expr = convert_to_base (expr, totype,
8767 !c_cast_p, /*nonnull=*/true, complain);
8768 return expr;
8769 }
8770
8771 /* Copy-initialization where the cv-unqualified version of the source
8772 type is the same class as, or a derived class of, the class of the
8773 destination [is treated as direct-initialization]. [dcl.init] */
8774 flags = LOOKUP_NORMAL;
8775 /* This conversion is being done in the context of a user-defined
8776 conversion (i.e. the second step of copy-initialization), so
8777 don't allow any more. */
8778 if (convs->user_conv_p)
8779 flags |= LOOKUP_NO_CONVERSION;
8780 /* We might be performing a conversion of the argument
8781 to the user-defined conversion, i.e., not a conversion of the
8782 result of the user-defined conversion. In which case we skip
8783 explicit constructors. */
8784 if (convs->copy_init_p)
8785 flags |= LOOKUP_ONLYCONVERTING;
8786 expr = build_temp (expr, totype, flags, &diag_kind, complain);
8787 if (diag_kind && complain)
8788 {
8789 auto_diagnostic_group d;
8790 maybe_print_user_conv_context (convs);
8791 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8792 }
8793
8794 return build_cplus_new (totype, expr, complain);
8795
8796 case ck_ref_bind:
8797 {
8798 tree ref_type = totype;
8799
8800 /* direct_reference_binding might have inserted a ck_qual under
8801 this ck_ref_bind for the benefit of conversion sequence ranking.
8802 Ignore the conversion; we'll create our own below. */
8803 if (next_conversion (convs)->kind == ck_qual
8804 && !convs->need_temporary_p)
8805 {
8806 gcc_assert (same_type_p (TREE_TYPE (expr),
8807 next_conversion (convs)->type));
8808 /* Strip the cast created by the ck_qual; cp_build_addr_expr
8809 below expects an lvalue. */
8810 STRIP_NOPS (expr);
8811 }
8812
8813 if (convs->bad_p && !next_conversion (convs)->bad_p)
8814 {
8815 tree extype = TREE_TYPE (expr);
8816 auto_diagnostic_group d;
8817 if (TYPE_REF_IS_RVALUE (ref_type)
8818 && lvalue_p (expr))
8819 error_at (loc, "cannot bind rvalue reference of type %qH to "
8820 "lvalue of type %qI", totype, extype);
8821 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8822 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8823 {
8824 conversion *next = next_conversion (convs);
8825 if (next->kind == ck_std)
8826 {
8827 next = next_conversion (next);
8828 error_at (loc, "cannot bind non-const lvalue reference of "
8829 "type %qH to a value of type %qI",
8830 totype, next->type);
8831 }
8832 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8833 error_at (loc, "cannot bind non-const lvalue reference of "
8834 "type %qH to an rvalue of type %qI", totype, extype);
8835 else // extype is volatile
8836 error_at (loc, "cannot bind lvalue reference of type "
8837 "%qH to an rvalue of type %qI", totype,
8838 extype);
8839 }
8840 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8841 {
8842 /* If we're converting from T[] to T[N], don't talk
8843 about discarding qualifiers. (Converting from T[N] to
8844 T[] is allowed by P0388R4.) */
8845 if (TREE_CODE (extype) == ARRAY_TYPE
8846 && TYPE_DOMAIN (extype) == NULL_TREE
8847 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8848 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8849 error_at (loc, "cannot bind reference of type %qH to %qI "
8850 "due to different array bounds", totype, extype);
8851 else
8852 error_at (loc, "binding reference of type %qH to %qI "
8853 "discards qualifiers", totype, extype);
8854 }
8855 else
8856 gcc_unreachable ();
8857 maybe_print_user_conv_context (convs);
8858 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8859
8860 return error_mark_node;
8861 }
8862 else if (complain & tf_warning)
8863 maybe_warn_array_conv (loc, convs, expr);
8864
8865 /* If necessary, create a temporary.
8866
8867 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8868 that need temporaries, even when their types are reference
8869 compatible with the type of reference being bound, so the
8870 upcoming call to cp_build_addr_expr doesn't fail. */
8871 if (convs->need_temporary_p
8872 || TREE_CODE (expr) == CONSTRUCTOR
8873 || TREE_CODE (expr) == VA_ARG_EXPR)
8874 {
8875 /* Otherwise, a temporary of type "cv1 T1" is created and
8876 initialized from the initializer expression using the rules
8877 for a non-reference copy-initialization (8.5). */
8878
8879 tree type = TREE_TYPE (ref_type);
8880 cp_lvalue_kind lvalue = lvalue_kind (expr);
8881
8882 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8883 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8884 && !TYPE_REF_IS_RVALUE (ref_type))
8885 {
8886 /* If the reference is volatile or non-const, we
8887 cannot create a temporary. */
8888 if (complain & tf_error)
8889 {
8890 if (lvalue & clk_bitfield)
8891 error_at (loc, "cannot bind bit-field %qE to %qT",
8892 expr, ref_type);
8893 else if (lvalue & clk_packed)
8894 error_at (loc, "cannot bind packed field %qE to %qT",
8895 expr, ref_type);
8896 else
8897 error_at (loc, "cannot bind rvalue %qE to %qT",
8898 expr, ref_type);
8899 }
8900 return error_mark_node;
8901 }
8902 /* If the source is a packed field, and we must use a copy
8903 constructor, then building the target expr will require
8904 binding the field to the reference parameter to the
8905 copy constructor, and we'll end up with an infinite
8906 loop. If we can use a bitwise copy, then we'll be
8907 OK. */
8908 if ((lvalue & clk_packed)
8909 && CLASS_TYPE_P (type)
8910 && type_has_nontrivial_copy_init (type))
8911 {
8912 error_at (loc, "cannot bind packed field %qE to %qT",
8913 expr, ref_type);
8914 return error_mark_node;
8915 }
8916 if (lvalue & clk_bitfield)
8917 {
8918 expr = convert_bitfield_to_declared_type (expr);
8919 expr = fold_convert (type, expr);
8920 }
8921
8922 /* Creating &TARGET_EXPR<> in a template would break when
8923 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8924 instead. This can happen even when there's no class
8925 involved, e.g., when converting an integer to a reference
8926 type. */
8927 if (processing_template_decl)
8928 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8929 expr = build_target_expr_with_type (expr, type, complain);
8930 }
8931
8932 /* Take the address of the thing to which we will bind the
8933 reference. */
8934 expr = cp_build_addr_expr (expr, complain);
8935 if (expr == error_mark_node)
8936 return error_mark_node;
8937
8938 /* Convert it to a pointer to the type referred to by the
8939 reference. This will adjust the pointer if a derived to
8940 base conversion is being performed. */
8941 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8942 expr, complain);
8943 /* Convert the pointer to the desired reference type. */
8944 return build_nop (ref_type, expr);
8945 }
8946
8947 case ck_lvalue:
8948 return decay_conversion (expr, complain);
8949
8950 case ck_fnptr:
8951 /* ??? Should the address of a transaction-safe pointer point to the TM
8952 clone, and this conversion look up the primary function? */
8953 return build_nop (totype, expr);
8954
8955 case ck_qual:
8956 /* Warn about deprecated conversion if appropriate. */
8957 if (complain & tf_warning)
8958 {
8959 string_conv_p (totype, expr, 1);
8960 maybe_warn_array_conv (loc, convs, expr);
8961 }
8962 break;
8963
8964 case ck_ptr:
8965 if (convs->base_p)
8966 expr = convert_to_base (expr, totype, !c_cast_p,
8967 /*nonnull=*/false, complain);
8968 return build_nop (totype, expr);
8969
8970 case ck_pmem:
8971 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8972 c_cast_p, complain);
8973
8974 default:
8975 break;
8976 }
8977
8978 if (convs->check_narrowing
8979 && !check_narrowing (totype, expr, complain,
8980 convs->check_narrowing_const_only))
8981 return error_mark_node;
8982
8983 warning_sentinel w (warn_zero_as_null_pointer_constant);
8984 if (issue_conversion_warnings)
8985 expr = cp_convert_and_check (totype, expr, complain);
8986 else
8987 {
8988 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8989 expr = TREE_OPERAND (expr, 0);
8990 expr = cp_convert (totype, expr, complain);
8991 }
8992
8993 return expr;
8994 }
8995
8996 /* Return true if converting FROM to TO is unsafe in a template. */
8997
8998 static bool
8999 conv_unsafe_in_template_p (tree to, tree from)
9000 {
9001 /* Converting classes involves TARGET_EXPR. */
9002 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
9003 return true;
9004
9005 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
9006 doesn't handle. */
9007 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
9008 return true;
9009
9010 /* Converting integer to real isn't a trivial conversion, either. */
9011 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
9012 return true;
9013
9014 return false;
9015 }
9016
9017 /* Wrapper for convert_like_internal that handles creating
9018 IMPLICIT_CONV_EXPR. */
9019
9020 static tree
9021 convert_like (conversion *convs, tree expr, tree fn, int argnum,
9022 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
9023 tsubst_flags_t complain)
9024 {
9025 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
9026 and creating a CALL_EXPR in a template breaks in finish_call_expr
9027 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
9028 created such codes e.g. when calling a user-defined conversion
9029 function. */
9030 tree conv_expr = NULL_TREE;
9031 if (processing_template_decl
9032 && convs->kind != ck_identity
9033 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
9034 {
9035 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
9036 if (convs->kind != ck_ref_bind)
9037 conv_expr = convert_from_reference (conv_expr);
9038 if (!convs->bad_p)
9039 return conv_expr;
9040 /* Do the normal processing to give the bad_p errors. But we still
9041 need to return the IMPLICIT_CONV_EXPR, unless we're returning
9042 error_mark_node. */
9043 }
9044 expr = convert_like_internal (convs, expr, fn, argnum,
9045 issue_conversion_warnings, c_cast_p,
9046 nested_p, complain);
9047 if (expr == error_mark_node)
9048 return error_mark_node;
9049 return conv_expr ? conv_expr : expr;
9050 }
9051
9052 /* Convenience wrapper for convert_like. */
9053
9054 static inline tree
9055 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
9056 {
9057 return convert_like (convs, expr, NULL_TREE, 0,
9058 /*issue_conversion_warnings=*/true,
9059 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9060 }
9061
9062 /* Convenience wrapper for convert_like. */
9063
9064 static inline tree
9065 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
9066 tsubst_flags_t complain)
9067 {
9068 return convert_like (convs, expr, fn, argnum,
9069 /*issue_conversion_warnings=*/true,
9070 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9071 }
9072
9073 /* ARG is being passed to a varargs function. Perform any conversions
9074 required. Return the converted value. */
9075
9076 tree
9077 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
9078 {
9079 tree arg_type = TREE_TYPE (arg);
9080 location_t loc = cp_expr_loc_or_input_loc (arg);
9081
9082 /* [expr.call]
9083
9084 If the argument has integral or enumeration type that is subject
9085 to the integral promotions (_conv.prom_), or a floating-point
9086 type that is subject to the floating-point promotion
9087 (_conv.fpprom_), the value of the argument is converted to the
9088 promoted type before the call. */
9089 if (SCALAR_FLOAT_TYPE_P (arg_type)
9090 && (TYPE_PRECISION (arg_type)
9091 < TYPE_PRECISION (double_type_node))
9092 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
9093 && !extended_float_type_p (arg_type))
9094 {
9095 if ((complain & tf_warning)
9096 && warn_double_promotion && !c_inhibit_evaluation_warnings)
9097 warning_at (loc, OPT_Wdouble_promotion,
9098 "implicit conversion from %qH to %qI when passing "
9099 "argument to function",
9100 arg_type, double_type_node);
9101 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
9102 arg = TREE_OPERAND (arg, 0);
9103 arg = mark_rvalue_use (arg);
9104 arg = convert_to_real_nofold (double_type_node, arg);
9105 }
9106 else if (NULLPTR_TYPE_P (arg_type))
9107 {
9108 arg = mark_rvalue_use (arg);
9109 if (TREE_SIDE_EFFECTS (arg))
9110 {
9111 warning_sentinel w(warn_unused_result);
9112 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9113 }
9114 else
9115 arg = null_pointer_node;
9116 }
9117 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9118 {
9119 if (SCOPED_ENUM_P (arg_type))
9120 {
9121 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9122 complain);
9123 prom = cp_perform_integral_promotions (prom, complain);
9124 if (abi_version_crosses (6)
9125 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9126 && (complain & tf_warning))
9127 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9128 " as %qT before %<-fabi-version=6%>, %qT after",
9129 arg_type,
9130 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9131 if (!abi_version_at_least (6))
9132 arg = prom;
9133 }
9134 else
9135 arg = cp_perform_integral_promotions (arg, complain);
9136 }
9137 else
9138 /* [expr.call]
9139
9140 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9141 standard conversions are performed. */
9142 arg = decay_conversion (arg, complain);
9143
9144 arg = require_complete_type (arg, complain);
9145 arg_type = TREE_TYPE (arg);
9146
9147 if (arg != error_mark_node
9148 /* In a template (or ill-formed code), we can have an incomplete type
9149 even after require_complete_type, in which case we don't know
9150 whether it has trivial copy or not. */
9151 && COMPLETE_TYPE_P (arg_type)
9152 && !cp_unevaluated_operand)
9153 {
9154 /* [expr.call] 5.2.2/7:
9155 Passing a potentially-evaluated argument of class type (Clause 9)
9156 with a non-trivial copy constructor or a non-trivial destructor
9157 with no corresponding parameter is conditionally-supported, with
9158 implementation-defined semantics.
9159
9160 We support it as pass-by-invisible-reference, just like a normal
9161 value parameter.
9162
9163 If the call appears in the context of a sizeof expression,
9164 it is not potentially-evaluated. */
9165 if (type_has_nontrivial_copy_init (arg_type)
9166 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9167 {
9168 arg = force_rvalue (arg, complain);
9169 if (complain & tf_warning)
9170 warning (OPT_Wconditionally_supported,
9171 "passing objects of non-trivially-copyable "
9172 "type %q#T through %<...%> is conditionally supported",
9173 arg_type);
9174 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9175 }
9176 /* Build up a real lvalue-to-rvalue conversion in case the
9177 copy constructor is trivial but not callable. */
9178 else if (CLASS_TYPE_P (arg_type))
9179 force_rvalue (arg, complain);
9180
9181 }
9182
9183 return arg;
9184 }
9185
9186 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9187
9188 tree
9189 build_x_va_arg (location_t loc, tree expr, tree type)
9190 {
9191 if (processing_template_decl)
9192 {
9193 tree r = build_min (VA_ARG_EXPR, type, expr);
9194 SET_EXPR_LOCATION (r, loc);
9195 return r;
9196 }
9197
9198 type = complete_type_or_else (type, NULL_TREE);
9199
9200 if (expr == error_mark_node || !type)
9201 return error_mark_node;
9202
9203 expr = mark_lvalue_use (expr);
9204
9205 if (TYPE_REF_P (type))
9206 {
9207 error ("cannot receive reference type %qT through %<...%>", type);
9208 return error_mark_node;
9209 }
9210
9211 if (type_has_nontrivial_copy_init (type)
9212 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9213 {
9214 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9215 it as pass by invisible reference. */
9216 warning_at (loc, OPT_Wconditionally_supported,
9217 "receiving objects of non-trivially-copyable type %q#T "
9218 "through %<...%> is conditionally-supported", type);
9219
9220 tree ref = cp_build_reference_type (type, false);
9221 expr = build_va_arg (loc, expr, ref);
9222 return convert_from_reference (expr);
9223 }
9224
9225 tree ret = build_va_arg (loc, expr, type);
9226 if (CLASS_TYPE_P (type))
9227 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9228 know how to handle it. */
9229 ret = get_target_expr (ret);
9230 return ret;
9231 }
9232
9233 /* TYPE has been given to va_arg. Apply the default conversions which
9234 would have happened when passed via ellipsis. Return the promoted
9235 type, or the passed type if there is no change. */
9236
9237 tree
9238 cxx_type_promotes_to (tree type)
9239 {
9240 tree promote;
9241
9242 /* Perform the array-to-pointer and function-to-pointer
9243 conversions. */
9244 type = type_decays_to (type);
9245
9246 promote = type_promotes_to (type);
9247 if (same_type_p (type, promote))
9248 promote = type;
9249
9250 return promote;
9251 }
9252
9253 /* ARG is a default argument expression being passed to a parameter of
9254 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9255 zero-based argument number. Do any required conversions. Return
9256 the converted value. */
9257
9258 static GTY(()) vec<tree, va_gc> *default_arg_context;
9259 void
9260 push_defarg_context (tree fn)
9261 { vec_safe_push (default_arg_context, fn); }
9262
9263 void
9264 pop_defarg_context (void)
9265 { default_arg_context->pop (); }
9266
9267 tree
9268 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9269 tsubst_flags_t complain)
9270 {
9271 int i;
9272 tree t;
9273
9274 /* See through clones. */
9275 fn = DECL_ORIGIN (fn);
9276 /* And inheriting ctors. */
9277 if (flag_new_inheriting_ctors)
9278 fn = strip_inheriting_ctors (fn);
9279
9280 /* Detect recursion. */
9281 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9282 if (t == fn)
9283 {
9284 if (complain & tf_error)
9285 error ("recursive evaluation of default argument for %q#D", fn);
9286 return error_mark_node;
9287 }
9288
9289 /* If the ARG is an unparsed default argument expression, the
9290 conversion cannot be performed. */
9291 if (TREE_CODE (arg) == DEFERRED_PARSE)
9292 {
9293 if (complain & tf_error)
9294 error ("call to %qD uses the default argument for parameter %P, which "
9295 "is not yet defined", fn, parmnum);
9296 return error_mark_node;
9297 }
9298
9299 push_defarg_context (fn);
9300
9301 if (fn && DECL_TEMPLATE_INFO (fn))
9302 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9303
9304 /* Due to:
9305
9306 [dcl.fct.default]
9307
9308 The names in the expression are bound, and the semantic
9309 constraints are checked, at the point where the default
9310 expressions appears.
9311
9312 we must not perform access checks here. */
9313 push_deferring_access_checks (dk_no_check);
9314 /* We must make a copy of ARG, in case subsequent processing
9315 alters any part of it. */
9316 arg = break_out_target_exprs (arg, /*clear location*/true);
9317
9318 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9319 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9320 complain);
9321 arg = convert_for_arg_passing (type, arg, complain);
9322 pop_deferring_access_checks();
9323
9324 pop_defarg_context ();
9325
9326 return arg;
9327 }
9328
9329 /* Returns the type which will really be used for passing an argument of
9330 type TYPE. */
9331
9332 tree
9333 type_passed_as (tree type)
9334 {
9335 /* Pass classes with copy ctors by invisible reference. */
9336 if (TREE_ADDRESSABLE (type))
9337 type = build_reference_type (type);
9338 else if (targetm.calls.promote_prototypes (NULL_TREE)
9339 && INTEGRAL_TYPE_P (type)
9340 && COMPLETE_TYPE_P (type)
9341 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9342 type = integer_type_node;
9343
9344 return type;
9345 }
9346
9347 /* Actually perform the appropriate conversion. */
9348
9349 tree
9350 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9351 {
9352 tree bitfield_type;
9353
9354 /* If VAL is a bitfield, then -- since it has already been converted
9355 to TYPE -- it cannot have a precision greater than TYPE.
9356
9357 If it has a smaller precision, we must widen it here. For
9358 example, passing "int f:3;" to a function expecting an "int" will
9359 not result in any conversion before this point.
9360
9361 If the precision is the same we must not risk widening. For
9362 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9363 often have type "int", even though the C++ type for the field is
9364 "long long". If the value is being passed to a function
9365 expecting an "int", then no conversions will be required. But,
9366 if we call convert_bitfield_to_declared_type, the bitfield will
9367 be converted to "long long". */
9368 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9369 if (bitfield_type
9370 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9371 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
9372
9373 if (val == error_mark_node)
9374 ;
9375 /* Pass classes with copy ctors by invisible reference. */
9376 else if (TREE_ADDRESSABLE (type))
9377 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9378 else if (targetm.calls.promote_prototypes (NULL_TREE)
9379 && INTEGRAL_TYPE_P (type)
9380 && COMPLETE_TYPE_P (type)
9381 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9382 val = cp_perform_integral_promotions (val, complain);
9383 if (complain & tf_warning)
9384 {
9385 if (warn_suggest_attribute_format)
9386 {
9387 tree rhstype = TREE_TYPE (val);
9388 const enum tree_code coder = TREE_CODE (rhstype);
9389 const enum tree_code codel = TREE_CODE (type);
9390 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9391 && coder == codel
9392 && check_missing_format_attribute (type, rhstype))
9393 warning (OPT_Wsuggest_attribute_format,
9394 "argument of function call might be a candidate "
9395 "for a format attribute");
9396 }
9397 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
9398 }
9399
9400 if (complain & tf_warning)
9401 warn_for_address_of_packed_member (type, val);
9402
9403 return val;
9404 }
9405
9406 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9407 which just decay_conversion or no conversions at all should be done.
9408 This is true for some builtins which don't act like normal functions.
9409 Return 2 if just decay_conversion and removal of excess precision should
9410 be done, 1 if just decay_conversion. Return 3 for special treatment of
9411 the 3rd argument for __builtin_*_overflow_p. Return 4 for special
9412 treatment of the 1st argument for
9413 __builtin_{clz,ctz,clrsb,ffs,parity,popcount}g. */
9414
9415 int
9416 magic_varargs_p (tree fn)
9417 {
9418 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9419 switch (DECL_FUNCTION_CODE (fn))
9420 {
9421 case BUILT_IN_CLASSIFY_TYPE:
9422 case BUILT_IN_CONSTANT_P:
9423 case BUILT_IN_NEXT_ARG:
9424 case BUILT_IN_VA_START:
9425 return 1;
9426
9427 case BUILT_IN_ADD_OVERFLOW_P:
9428 case BUILT_IN_SUB_OVERFLOW_P:
9429 case BUILT_IN_MUL_OVERFLOW_P:
9430 return 3;
9431
9432 case BUILT_IN_ISFINITE:
9433 case BUILT_IN_ISINF:
9434 case BUILT_IN_ISINF_SIGN:
9435 case BUILT_IN_ISNAN:
9436 case BUILT_IN_ISNORMAL:
9437 case BUILT_IN_FPCLASSIFY:
9438 return 2;
9439
9440 case BUILT_IN_CLZG:
9441 case BUILT_IN_CTZG:
9442 case BUILT_IN_CLRSBG:
9443 case BUILT_IN_FFSG:
9444 case BUILT_IN_PARITYG:
9445 case BUILT_IN_POPCOUNTG:
9446 return 4;
9447
9448 default:
9449 return lookup_attribute ("type generic",
9450 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9451 }
9452
9453 return 0;
9454 }
9455
9456 /* Returns the decl of the dispatcher function if FN is a function version. */
9457
9458 tree
9459 get_function_version_dispatcher (tree fn)
9460 {
9461 tree dispatcher_decl = NULL;
9462
9463 if (DECL_LOCAL_DECL_P (fn))
9464 fn = DECL_LOCAL_DECL_ALIAS (fn);
9465
9466 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9467 && DECL_FUNCTION_VERSIONED (fn));
9468
9469 gcc_assert (targetm.get_function_versions_dispatcher);
9470 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9471
9472 if (dispatcher_decl == NULL)
9473 {
9474 error_at (input_location, "use of multiversioned function "
9475 "without a default");
9476 return NULL;
9477 }
9478
9479 retrofit_lang_decl (dispatcher_decl);
9480 gcc_assert (dispatcher_decl != NULL);
9481 return dispatcher_decl;
9482 }
9483
9484 /* fn is a function version dispatcher that is marked used. Mark all the
9485 semantically identical function versions it will dispatch as used. */
9486
9487 void
9488 mark_versions_used (tree fn)
9489 {
9490 struct cgraph_node *node;
9491 struct cgraph_function_version_info *node_v;
9492 struct cgraph_function_version_info *it_v;
9493
9494 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9495
9496 node = cgraph_node::get (fn);
9497 if (node == NULL)
9498 return;
9499
9500 gcc_assert (node->dispatcher_function);
9501
9502 node_v = node->function_version ();
9503 if (node_v == NULL)
9504 return;
9505
9506 /* All semantically identical versions are chained. Traverse and mark each
9507 one of them as used. */
9508 it_v = node_v->next;
9509 while (it_v != NULL)
9510 {
9511 mark_used (it_v->this_node->decl);
9512 it_v = it_v->next;
9513 }
9514 }
9515
9516 /* Build a call to "the copy constructor" for the type of A, even if it
9517 wouldn't be selected by normal overload resolution. Used for
9518 diagnostics. */
9519
9520 static tree
9521 call_copy_ctor (tree a, tsubst_flags_t complain)
9522 {
9523 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9524 tree binfo = TYPE_BINFO (ctype);
9525 tree copy = get_copy_ctor (ctype, complain);
9526 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9527 tree ob = build_dummy_object (ctype);
9528 releasing_vec args (make_tree_vector_single (a));
9529 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9530 LOOKUP_NORMAL, NULL, complain);
9531 return r;
9532 }
9533
9534 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9535
9536 static tree
9537 base_ctor_for (tree complete_ctor)
9538 {
9539 tree clone;
9540 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9541 if (DECL_BASE_CONSTRUCTOR_P (clone))
9542 return clone;
9543 return NULL_TREE;
9544 }
9545
9546 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9547 and return whether we were successful. EXP must have already been cleared
9548 by unsafe_copy_elision_p{,_opt}. */
9549
9550 static bool
9551 make_base_init_ok (tree exp)
9552 {
9553 if (TREE_CODE (exp) == TARGET_EXPR)
9554 exp = TARGET_EXPR_INITIAL (exp);
9555 while (TREE_CODE (exp) == COMPOUND_EXPR)
9556 exp = TREE_OPERAND (exp, 1);
9557 if (TREE_CODE (exp) == COND_EXPR)
9558 {
9559 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9560 if (tree op1 = TREE_OPERAND (exp, 1))
9561 {
9562 bool r1 = make_base_init_ok (op1);
9563 /* If unsafe_copy_elision_p was false, the arms should match. */
9564 gcc_assert (r1 == ret);
9565 }
9566 return ret;
9567 }
9568 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9569 /* A trivial copy is OK. */
9570 return true;
9571 if (!AGGR_INIT_VIA_CTOR_P (exp))
9572 /* unsafe_copy_elision_p_opt must have said this is OK. */
9573 return true;
9574 tree fn = cp_get_callee_fndecl_nofold (exp);
9575 if (DECL_BASE_CONSTRUCTOR_P (fn))
9576 return true;
9577 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9578 fn = base_ctor_for (fn);
9579 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9580 /* The base constructor has more parameters, so we can't just change the
9581 call target. It would be possible to splice in the appropriate
9582 arguments, but probably not worth the complexity. */
9583 return false;
9584 mark_used (fn);
9585 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9586 return true;
9587 }
9588
9589 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9590 neither of which can be used for return by invisible reference. We avoid
9591 doing C++17 mandatory copy elision for either of these cases.
9592
9593 This returns non-zero even if the type of T has no tail padding that other
9594 data could be allocated into, because that depends on the particular ABI.
9595 unsafe_copy_elision_p_opt does consider whether there is padding. */
9596
9597 int
9598 unsafe_return_slot_p (tree t)
9599 {
9600 /* Check empty bases separately, they don't have fields. */
9601 if (is_empty_base_ref (t))
9602 return 2;
9603
9604 /* A delegating constructor might be used to initialize a base. */
9605 if (current_function_decl
9606 && DECL_CONSTRUCTOR_P (current_function_decl)
9607 && (t == current_class_ref
9608 || tree_strip_nop_conversions (t) == current_class_ptr))
9609 return 2;
9610
9611 STRIP_NOPS (t);
9612 if (TREE_CODE (t) == ADDR_EXPR)
9613 t = TREE_OPERAND (t, 0);
9614 if (TREE_CODE (t) == COMPONENT_REF)
9615 t = TREE_OPERAND (t, 1);
9616 if (TREE_CODE (t) != FIELD_DECL)
9617 return false;
9618 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9619 /* The middle-end will do the right thing for scalar types. */
9620 return false;
9621 if (DECL_FIELD_IS_BASE (t))
9622 return 2;
9623 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9624 return 1;
9625 return 0;
9626 }
9627
9628 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9629
9630 static bool
9631 init_by_return_slot_p (tree exp)
9632 {
9633 /* Copy elision only happens with a TARGET_EXPR. */
9634 if (TREE_CODE (exp) != TARGET_EXPR)
9635 return false;
9636 tree init = TARGET_EXPR_INITIAL (exp);
9637 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9638 while (TREE_CODE (init) == COMPOUND_EXPR)
9639 init = TREE_OPERAND (init, 1);
9640 if (TREE_CODE (init) == COND_EXPR)
9641 {
9642 /* We'll end up copying from each of the arms of the COND_EXPR directly
9643 into the target, so look at them. */
9644 if (tree op = TREE_OPERAND (init, 1))
9645 if (init_by_return_slot_p (op))
9646 return true;
9647 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9648 }
9649 return (TREE_CODE (init) == AGGR_INIT_EXPR
9650 && !AGGR_INIT_VIA_CTOR_P (init));
9651 }
9652
9653 /* We can't elide a copy from a function returning by value to a
9654 potentially-overlapping subobject, as the callee might clobber tail padding.
9655 Return true iff this could be that case.
9656
9657 Places that use this function (or _opt) to decide to elide a copy should
9658 probably use make_safe_copy_elision instead. */
9659
9660 bool
9661 unsafe_copy_elision_p (tree target, tree exp)
9662 {
9663 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9664 }
9665
9666 /* As above, but for optimization allow more cases that are actually safe. */
9667
9668 static bool
9669 unsafe_copy_elision_p_opt (tree target, tree exp)
9670 {
9671 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9672 /* It's safe to elide the copy for a class with no tail padding. */
9673 if (!is_empty_class (type)
9674 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9675 return false;
9676 return unsafe_copy_elision_p (target, exp);
9677 }
9678
9679 /* Try to make EXP suitable to be used as the initializer for TARGET,
9680 and return whether we were successful. */
9681
9682 bool
9683 make_safe_copy_elision (tree target, tree exp)
9684 {
9685 int uns = unsafe_return_slot_p (target);
9686 if (!uns)
9687 return true;
9688 if (init_by_return_slot_p (exp))
9689 return false;
9690 if (uns == 1)
9691 return true;
9692 return make_base_init_ok (exp);
9693 }
9694
9695 /* True IFF the result of the conversion C is a prvalue. */
9696
9697 static bool
9698 conv_is_prvalue (conversion *c)
9699 {
9700 if (c->kind == ck_rvalue)
9701 return true;
9702 if (c->kind == ck_base && c->need_temporary_p)
9703 return true;
9704 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9705 return true;
9706 if (c->kind == ck_identity && c->u.expr
9707 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9708 return true;
9709
9710 return false;
9711 }
9712
9713 /* True iff C is a conversion that binds a reference to a prvalue. */
9714
9715 static bool
9716 conv_binds_ref_to_prvalue (conversion *c)
9717 {
9718 if (c->kind != ck_ref_bind)
9719 return false;
9720 if (c->need_temporary_p)
9721 return true;
9722
9723 return conv_is_prvalue (next_conversion (c));
9724 }
9725
9726 /* True iff EXPR represents a (subobject of a) temporary. */
9727
9728 static bool
9729 expr_represents_temporary_p (tree expr)
9730 {
9731 while (handled_component_p (expr))
9732 expr = TREE_OPERAND (expr, 0);
9733 return TREE_CODE (expr) == TARGET_EXPR;
9734 }
9735
9736 /* True iff C is a conversion that binds a reference to a temporary.
9737 This is a superset of conv_binds_ref_to_prvalue: here we're also
9738 interested in xvalues. */
9739
9740 static bool
9741 conv_binds_ref_to_temporary (conversion *c)
9742 {
9743 if (conv_binds_ref_to_prvalue (c))
9744 return true;
9745 if (c->kind != ck_ref_bind)
9746 return false;
9747 c = next_conversion (c);
9748 /* This is the case for
9749 struct Base {};
9750 struct Derived : Base {};
9751 const Base& b(Derived{});
9752 where we bind 'b' to the Base subobject of a temporary object of type
9753 Derived. The subobject is an xvalue; the whole object is a prvalue.
9754
9755 The ck_base doesn't have to be present for cases like X{}.m. */
9756 if (c->kind == ck_base)
9757 c = next_conversion (c);
9758 if (c->kind == ck_identity && c->u.expr
9759 && expr_represents_temporary_p (c->u.expr))
9760 return true;
9761 return false;
9762 }
9763
9764 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9765 the reference to a temporary. Return tristate::TS_FALSE if converting
9766 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9767 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9768 says whether the conversion should be done in direct- or copy-initialization
9769 context. */
9770
9771 tristate
9772 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9773 {
9774 gcc_assert (TYPE_REF_P (type));
9775
9776 conversion_obstack_sentinel cos;
9777
9778 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9779 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9780 /*c_cast_p=*/false, flags, tf_none);
9781 tristate ret (tristate::TS_UNKNOWN);
9782 if (conv && !conv->bad_p)
9783 ret = tristate (conv_binds_ref_to_temporary (conv));
9784
9785 return ret;
9786 }
9787
9788 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9789 class type or a pointer to class type. If NO_PTR_DEREF is true and
9790 INSTANCE has pointer type, clobber the pointer rather than what it points
9791 to. */
9792
9793 tree
9794 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9795 {
9796 gcc_assert (!is_dummy_object (instance));
9797
9798 if (!flag_lifetime_dse)
9799 {
9800 no_clobber:
9801 return fold_convert (void_type_node, instance);
9802 }
9803
9804 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9805 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9806 {
9807 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9808 goto no_clobber;
9809 instance = cp_build_fold_indirect_ref (instance);
9810 }
9811
9812 /* A trivial destructor should still clobber the object. */
9813 tree clobber = build_clobber (TREE_TYPE (instance), CLOBBER_OBJECT_END);
9814 return build2 (MODIFY_EXPR, void_type_node,
9815 instance, clobber);
9816 }
9817
9818 /* Return true if in an immediate function context, or an unevaluated operand,
9819 or a default argument/member initializer, or a subexpression of an immediate
9820 invocation. */
9821
9822 bool
9823 in_immediate_context ()
9824 {
9825 return (cp_unevaluated_operand != 0
9826 || (current_function_decl != NULL_TREE
9827 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9828 /* DR 2631: default args and DMI aren't immediately evaluated.
9829 Return true here so immediate_invocation_p returns false. */
9830 || current_binding_level->kind == sk_function_parms
9831 || current_binding_level->kind == sk_template_parms
9832 || parsing_nsdmi ()
9833 || in_consteval_if_p);
9834 }
9835
9836 /* Return true if a call to FN with number of arguments NARGS
9837 is an immediate invocation. */
9838
9839 bool
9840 immediate_invocation_p (tree fn)
9841 {
9842 return (TREE_CODE (fn) == FUNCTION_DECL
9843 && DECL_IMMEDIATE_FUNCTION_P (fn)
9844 && !in_immediate_context ());
9845 }
9846
9847 /* Subroutine of the various build_*_call functions. Overload resolution
9848 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9849 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9850 bitmask of various LOOKUP_* flags which apply to the call itself. */
9851
9852 static tree
9853 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9854 {
9855 tree fn = cand->fn;
9856 const vec<tree, va_gc> *args = cand->args;
9857 tree first_arg = cand->first_arg;
9858 conversion **convs = cand->convs;
9859 conversion *conv;
9860 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9861 int parmlen;
9862 tree val;
9863 int i = 0;
9864 int j = 0;
9865 unsigned int arg_index = 0;
9866 int is_method = 0;
9867 int nargs;
9868 tree *argarray;
9869 bool already_used = false;
9870
9871 /* In a template, there is no need to perform all of the work that
9872 is normally done. We are only interested in the type of the call
9873 expression, i.e., the return type of the function. Any semantic
9874 errors will be deferred until the template is instantiated. */
9875 if (processing_template_decl)
9876 {
9877 if (undeduced_auto_decl (fn))
9878 mark_used (fn, complain);
9879 else
9880 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9881 See PR80598. */
9882 TREE_USED (fn) = 1;
9883
9884 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9885 tree callee;
9886 if (first_arg == NULL_TREE)
9887 {
9888 callee = build_addr_func (fn, complain);
9889 if (callee == error_mark_node)
9890 return error_mark_node;
9891 }
9892 else
9893 {
9894 callee = build_baselink (cand->conversion_path, cand->access_path,
9895 fn, NULL_TREE);
9896 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9897 first_arg, callee, NULL_TREE);
9898 }
9899
9900 tree expr = build_call_vec (return_type, callee, args);
9901 SET_EXPR_LOCATION (expr, input_location);
9902 if (TREE_THIS_VOLATILE (fn) && cfun)
9903 current_function_returns_abnormally = 1;
9904 if (immediate_invocation_p (fn))
9905 {
9906 tree obj_arg = NULL_TREE, exprimm = expr;
9907 if (DECL_CONSTRUCTOR_P (fn))
9908 obj_arg = first_arg;
9909 if (obj_arg
9910 && is_dummy_object (obj_arg)
9911 && !type_dependent_expression_p (obj_arg))
9912 {
9913 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9914 obj_arg = NULL_TREE;
9915 }
9916 /* Look through *(const T *)&obj. */
9917 else if (obj_arg && INDIRECT_REF_P (obj_arg))
9918 {
9919 tree addr = TREE_OPERAND (obj_arg, 0);
9920 STRIP_NOPS (addr);
9921 if (TREE_CODE (addr) == ADDR_EXPR)
9922 {
9923 tree typeo = TREE_TYPE (obj_arg);
9924 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9925 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9926 obj_arg = TREE_OPERAND (addr, 0);
9927 }
9928 }
9929 fold_non_dependent_expr (exprimm, complain,
9930 /*manifestly_const_eval=*/true,
9931 obj_arg);
9932 }
9933 return convert_from_reference (expr);
9934 }
9935
9936 /* Give any warnings we noticed during overload resolution. */
9937 if (cand->warnings && (complain & tf_warning))
9938 {
9939 struct candidate_warning *w;
9940 for (w = cand->warnings; w; w = w->next)
9941 joust (cand, w->loser, 1, complain);
9942 }
9943
9944 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9945 argument to the copy constructor ends up being a prvalue after
9946 conversion. Let's do the normal processing, but pretend we aren't
9947 actually using the copy constructor. */
9948 bool force_elide = false;
9949 if (cxx_dialect >= cxx17
9950 && cand->num_convs == 1
9951 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9952 && (DECL_COPY_CONSTRUCTOR_P (fn)
9953 || DECL_MOVE_CONSTRUCTOR_P (fn))
9954 && !unsafe_return_slot_p (first_arg)
9955 && conv_binds_ref_to_prvalue (convs[0]))
9956 {
9957 force_elide = true;
9958 goto not_really_used;
9959 }
9960
9961 /* OK, we're actually calling this inherited constructor; set its deletedness
9962 appropriately. We can get away with doing this here because calling is
9963 the only way to refer to a constructor. */
9964 if (DECL_INHERITED_CTOR (fn)
9965 && !deduce_inheriting_ctor (fn))
9966 {
9967 if (complain & tf_error)
9968 mark_used (fn);
9969 return error_mark_node;
9970 }
9971
9972 /* Make =delete work with SFINAE. */
9973 if (DECL_DELETED_FN (fn))
9974 {
9975 if (complain & tf_error)
9976 {
9977 mark_used (fn);
9978 if (cand->next)
9979 {
9980 if (flag_diagnostics_all_candidates)
9981 print_z_candidates (input_location, cand, /*only_viable_p=*/false);
9982 else
9983 inform (input_location,
9984 "use %<-fdiagnostics-all-candidates%> to display "
9985 "considered candidates");
9986 }
9987 }
9988 return error_mark_node;
9989 }
9990
9991 if (DECL_FUNCTION_MEMBER_P (fn))
9992 {
9993 tree access_fn;
9994 /* If FN is a template function, two cases must be considered.
9995 For example:
9996
9997 struct A {
9998 protected:
9999 template <class T> void f();
10000 };
10001 template <class T> struct B {
10002 protected:
10003 void g();
10004 };
10005 struct C : A, B<int> {
10006 using A::f; // #1
10007 using B<int>::g; // #2
10008 };
10009
10010 In case #1 where `A::f' is a member template, DECL_ACCESS is
10011 recorded in the primary template but not in its specialization.
10012 We check access of FN using its primary template.
10013
10014 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
10015 because it is a member of class template B, DECL_ACCESS is
10016 recorded in the specialization `B<int>::g'. We cannot use its
10017 primary template because `B<T>::g' and `B<int>::g' may have
10018 different access. */
10019 if (DECL_TEMPLATE_INFO (fn)
10020 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
10021 access_fn = DECL_TI_TEMPLATE (fn);
10022 else
10023 access_fn = fn;
10024 if (!perform_or_defer_access_check (cand->access_path, access_fn,
10025 fn, complain))
10026 return error_mark_node;
10027 }
10028
10029 /* If we're checking for implicit delete, don't bother with argument
10030 conversions. */
10031 if (flags & LOOKUP_SPECULATIVE)
10032 {
10033 if (cand->viable == 1)
10034 return fn;
10035 else if (!(complain & tf_error))
10036 /* Reject bad conversions now. */
10037 return error_mark_node;
10038 /* else continue to get conversion error. */
10039 }
10040
10041 not_really_used:
10042
10043 /* N3276 magic doesn't apply to nested calls. */
10044 tsubst_flags_t decltype_flag = (complain & tf_decltype);
10045 complain &= ~tf_decltype;
10046 /* No-Cleanup doesn't apply to nested calls either. */
10047 tsubst_flags_t no_cleanup_complain = complain;
10048 complain &= ~tf_no_cleanup;
10049
10050 /* Find maximum size of vector to hold converted arguments. */
10051 parmlen = list_length (parm);
10052 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
10053 if (parmlen > nargs)
10054 nargs = parmlen;
10055 argarray = XALLOCAVEC (tree, nargs);
10056
10057 in_consteval_if_p_temp_override icip;
10058 /* If the call is immediate function invocation, make sure
10059 taking address of immediate functions is allowed in its arguments. */
10060 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
10061 in_consteval_if_p = true;
10062
10063 /* The implicit parameters to a constructor are not considered by overload
10064 resolution, and must be of the proper type. */
10065 if (DECL_CONSTRUCTOR_P (fn))
10066 {
10067 tree object_arg;
10068 if (first_arg != NULL_TREE)
10069 {
10070 object_arg = first_arg;
10071 first_arg = NULL_TREE;
10072 }
10073 else
10074 {
10075 object_arg = (*args)[arg_index];
10076 ++arg_index;
10077 }
10078 argarray[j++] = build_this (object_arg);
10079 parm = TREE_CHAIN (parm);
10080 /* We should never try to call the abstract constructor. */
10081 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
10082
10083 if (DECL_HAS_VTT_PARM_P (fn))
10084 {
10085 argarray[j++] = (*args)[arg_index];
10086 ++arg_index;
10087 parm = TREE_CHAIN (parm);
10088 }
10089 }
10090 /* Bypass access control for 'this' parameter. */
10091 else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
10092 {
10093 tree arg = build_this (first_arg != NULL_TREE
10094 ? first_arg
10095 : (*args)[arg_index]);
10096 tree argtype = TREE_TYPE (arg);
10097
10098 if (arg == error_mark_node)
10099 return error_mark_node;
10100
10101 if (convs[i]->bad_p)
10102 {
10103 if (complain & tf_error)
10104 {
10105 auto_diagnostic_group d;
10106 if (permerror (input_location, "passing %qT as %<this%> "
10107 "argument discards qualifiers",
10108 TREE_TYPE (argtype)))
10109 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
10110 }
10111 else
10112 return error_mark_node;
10113 }
10114
10115 /* The class where FN is defined. */
10116 tree ctx = DECL_CONTEXT (fn);
10117
10118 /* See if the function member or the whole class type is declared
10119 final and the call can be devirtualized. */
10120 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
10121 flags |= LOOKUP_NONVIRTUAL;
10122
10123 /* [class.mfct.non-static]: If a non-static member function of a class
10124 X is called for an object that is not of type X, or of a type
10125 derived from X, the behavior is undefined.
10126
10127 So we can assume that anything passed as 'this' is non-null, and
10128 optimize accordingly. */
10129 /* Check that the base class is accessible. */
10130 if (!accessible_base_p (TREE_TYPE (argtype),
10131 BINFO_TYPE (cand->conversion_path), true))
10132 {
10133 if (complain & tf_error)
10134 error ("%qT is not an accessible base of %qT",
10135 BINFO_TYPE (cand->conversion_path),
10136 TREE_TYPE (argtype));
10137 else
10138 return error_mark_node;
10139 }
10140 /* If fn was found by a using declaration, the conversion path
10141 will be to the derived class, not the base declaring fn. We
10142 must convert to the base. */
10143 tree base_binfo = cand->conversion_path;
10144 if (BINFO_TYPE (base_binfo) != ctx)
10145 {
10146 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10147 if (base_binfo == error_mark_node)
10148 return error_mark_node;
10149 }
10150
10151 /* If we know the dynamic type of the object, look up the final overrider
10152 in the BINFO. */
10153 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10154 && resolves_to_fixed_type_p (arg))
10155 {
10156 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10157
10158 /* And unwind base_binfo to match. If we don't find the type we're
10159 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10160 inheritance; for now do a normal virtual call in that case. */
10161 tree octx = DECL_CONTEXT (ov);
10162 tree obinfo = base_binfo;
10163 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10164 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10165 if (obinfo)
10166 {
10167 fn = ov;
10168 base_binfo = obinfo;
10169 flags |= LOOKUP_NONVIRTUAL;
10170 }
10171 }
10172
10173 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10174 base_binfo, 1, complain);
10175
10176 argarray[j++] = converted_arg;
10177 parm = TREE_CHAIN (parm);
10178 if (first_arg != NULL_TREE)
10179 first_arg = NULL_TREE;
10180 else
10181 ++arg_index;
10182 ++i;
10183 is_method = 1;
10184 }
10185
10186 gcc_assert (first_arg == NULL_TREE);
10187 for (; arg_index < vec_safe_length (args) && parm;
10188 parm = TREE_CHAIN (parm), ++arg_index, ++i)
10189 {
10190 tree type = TREE_VALUE (parm);
10191 tree arg = (*args)[arg_index];
10192 bool conversion_warning = true;
10193
10194 conv = convs[i];
10195
10196 /* If the argument is NULL and used to (implicitly) instantiate a
10197 template function (and bind one of the template arguments to
10198 the type of 'long int'), we don't want to warn about passing NULL
10199 to non-pointer argument.
10200 For example, if we have this template function:
10201
10202 template<typename T> void func(T x) {}
10203
10204 we want to warn (when -Wconversion is enabled) in this case:
10205
10206 void foo() {
10207 func<int>(NULL);
10208 }
10209
10210 but not in this case:
10211
10212 void foo() {
10213 func(NULL);
10214 }
10215 */
10216 if (null_node_p (arg)
10217 && DECL_TEMPLATE_INFO (fn)
10218 && cand->template_decl
10219 && !cand->explicit_targs)
10220 conversion_warning = false;
10221
10222 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10223 knows not to allow any more UDCs. This needs to happen after we
10224 process cand->warnings. */
10225 if (flags & LOOKUP_NO_CONVERSION)
10226 conv->user_conv_p = true;
10227
10228 tsubst_flags_t arg_complain = complain;
10229 if (!conversion_warning)
10230 arg_complain &= ~tf_warning;
10231
10232 if (arg_complain & tf_warning)
10233 maybe_warn_pessimizing_move (arg, type, /*return_p*/false);
10234
10235 val = convert_like_with_context (conv, arg, fn, i - is_method,
10236 arg_complain);
10237 val = convert_for_arg_passing (type, val, arg_complain);
10238
10239 if (val == error_mark_node)
10240 return error_mark_node;
10241 else
10242 argarray[j++] = val;
10243 }
10244
10245 /* Default arguments */
10246 for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
10247 {
10248 if (TREE_VALUE (parm) == error_mark_node)
10249 return error_mark_node;
10250 val = convert_default_arg (TREE_VALUE (parm),
10251 TREE_PURPOSE (parm),
10252 fn, i - is_method,
10253 complain);
10254 if (val == error_mark_node)
10255 return error_mark_node;
10256 argarray[j++] = val;
10257 }
10258
10259 /* Ellipsis */
10260 int magic = magic_varargs_p (fn);
10261 for (; arg_index < vec_safe_length (args); ++arg_index)
10262 {
10263 tree a = (*args)[arg_index];
10264 if ((magic == 3 && arg_index == 2) || (magic == 4 && arg_index == 0))
10265 {
10266 /* Do no conversions for certain magic varargs. */
10267 a = mark_type_use (a);
10268 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10269 return error_mark_node;
10270 }
10271 else if (magic != 0)
10272 {
10273 /* Don't truncate excess precision to the semantic type. */
10274 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10275 a = TREE_OPERAND (a, 0);
10276 /* For other magic varargs only do decay_conversion. */
10277 a = decay_conversion (a, complain);
10278 }
10279 else if (DECL_CONSTRUCTOR_P (fn)
10280 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10281 TREE_TYPE (a)))
10282 {
10283 /* Avoid infinite recursion trying to call A(...). */
10284 if (complain & tf_error)
10285 /* Try to call the actual copy constructor for a good error. */
10286 call_copy_ctor (a, complain);
10287 return error_mark_node;
10288 }
10289 else
10290 a = convert_arg_to_ellipsis (a, complain);
10291 if (a == error_mark_node)
10292 return error_mark_node;
10293 argarray[j++] = a;
10294 }
10295
10296 gcc_assert (j <= nargs);
10297 nargs = j;
10298 icip.reset ();
10299
10300 /* Avoid performing argument transformation if warnings are disabled.
10301 When tf_warning is set and at least one of the warnings is active
10302 the check_function_arguments function might warn about something. */
10303
10304 bool warned_p = false;
10305 if ((complain & tf_warning)
10306 && (warn_nonnull
10307 || warn_format
10308 || warn_suggest_attribute_format
10309 || warn_restrict))
10310 {
10311 tree *fargs = (!nargs ? argarray
10312 : (tree *) alloca (nargs * sizeof (tree)));
10313 for (j = 0; j < nargs; j++)
10314 {
10315 /* For -Wformat undo the implicit passing by hidden reference
10316 done by convert_arg_to_ellipsis. */
10317 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10318 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10319 fargs[j] = TREE_OPERAND (argarray[j], 0);
10320 else
10321 fargs[j] = argarray[j];
10322 }
10323
10324 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
10325 nargs, fargs, NULL);
10326 }
10327
10328 if (DECL_INHERITED_CTOR (fn))
10329 {
10330 /* Check for passing ellipsis arguments to an inherited constructor. We
10331 could handle this by open-coding the inherited constructor rather than
10332 defining it, but let's not bother now. */
10333 if (!cp_unevaluated_operand
10334 && cand->num_convs
10335 && cand->convs[cand->num_convs-1]->ellipsis_p)
10336 {
10337 if (complain & tf_error)
10338 {
10339 sorry ("passing arguments to ellipsis of inherited constructor "
10340 "%qD", cand->fn);
10341 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10342 }
10343 return error_mark_node;
10344 }
10345
10346 /* A base constructor inheriting from a virtual base doesn't get the
10347 inherited arguments, just this and __vtt. */
10348 if (ctor_omit_inherited_parms (fn))
10349 nargs = 2;
10350 }
10351
10352 /* Avoid actually calling copy constructors and copy assignment operators,
10353 if possible. */
10354
10355 if (!force_elide
10356 && (!flag_elide_constructors
10357 /* It's unsafe to elide the operation when handling
10358 a noexcept-expression, it may evaluate to the wrong
10359 value (c++/53025, c++/96090). */
10360 || cp_noexcept_operand != 0))
10361 /* Do things the hard way. */;
10362 else if (cand->num_convs == 1
10363 && (DECL_COPY_CONSTRUCTOR_P (fn)
10364 || DECL_MOVE_CONSTRUCTOR_P (fn)))
10365 {
10366 tree targ;
10367 tree arg = argarray[num_artificial_parms_for (fn)];
10368 tree fa = argarray[0];
10369 bool trivial = trivial_fn_p (fn);
10370
10371 /* Pull out the real argument, disregarding const-correctness. */
10372 targ = arg;
10373 /* Strip the reference binding for the constructor parameter. */
10374 if (CONVERT_EXPR_P (targ)
10375 && TYPE_REF_P (TREE_TYPE (targ)))
10376 targ = TREE_OPERAND (targ, 0);
10377 /* But don't strip any other reference bindings; binding a temporary to a
10378 reference prevents copy elision. */
10379 while ((CONVERT_EXPR_P (targ)
10380 && !TYPE_REF_P (TREE_TYPE (targ)))
10381 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10382 targ = TREE_OPERAND (targ, 0);
10383 if (TREE_CODE (targ) == ADDR_EXPR)
10384 {
10385 targ = TREE_OPERAND (targ, 0);
10386 if (!same_type_ignoring_top_level_qualifiers_p
10387 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10388 targ = NULL_TREE;
10389 }
10390 else
10391 targ = NULL_TREE;
10392
10393 if (targ)
10394 arg = targ;
10395 else
10396 arg = cp_build_fold_indirect_ref (arg);
10397
10398 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10399 potentially-overlapping subobject. */
10400 if (CHECKING_P && cxx_dialect >= cxx17)
10401 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10402 || force_elide
10403 /* It's from binding the ref parm to a packed field. */
10404 || convs[0]->need_temporary_p
10405 || seen_error ()
10406 /* See unsafe_copy_elision_p. */
10407 || unsafe_return_slot_p (fa));
10408
10409 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
10410 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10411
10412 /* [class.copy]: the copy constructor is implicitly defined even if the
10413 implementation elided its use. But don't warn about deprecation when
10414 eliding a temporary, as then no copy is actually performed. */
10415 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10416 if (force_elide)
10417 /* The language says this isn't called. */;
10418 else if (!trivial)
10419 {
10420 if (!mark_used (fn, complain) && !(complain & tf_error))
10421 return error_mark_node;
10422 already_used = true;
10423 }
10424 else
10425 cp_handle_deprecated_or_unavailable (fn, complain);
10426
10427 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10428 && !make_base_init_ok (arg))
10429 unsafe = true;
10430
10431 /* If we're creating a temp and we already have one, don't create a
10432 new one. If we're not creating a temp but we get one, use
10433 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10434 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10435 temp or an INIT_EXPR otherwise. */
10436 if (is_dummy_object (fa))
10437 {
10438 if (TREE_CODE (arg) == TARGET_EXPR)
10439 return arg;
10440 else if (trivial)
10441 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10442 }
10443 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10444 && !unsafe)
10445 {
10446 tree to = cp_build_fold_indirect_ref (fa);
10447 val = cp_build_init_expr (to, arg);
10448 return val;
10449 }
10450 }
10451 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10452 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10453 && trivial_fn_p (fn))
10454 {
10455 tree to = cp_build_fold_indirect_ref (argarray[0]);
10456 tree type = TREE_TYPE (to);
10457 tree as_base = CLASSTYPE_AS_BASE (type);
10458 tree arg = argarray[1];
10459 location_t loc = cp_expr_loc_or_input_loc (arg);
10460
10461 if (is_really_empty_class (type, /*ignore_vptr*/true))
10462 {
10463 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10464 if the object argument isn't one. This isn't needed in other cases
10465 since MODIFY_EXPR is always considered an lvalue. */
10466 to = cp_build_addr_expr (to, tf_none);
10467 to = cp_build_indirect_ref (input_location, to, RO_ARROW, complain);
10468 val = build2 (COMPOUND_EXPR, type, arg, to);
10469 suppress_warning (val, OPT_Wunused);
10470 }
10471 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10472 {
10473 if (is_std_init_list (type)
10474 && conv_binds_ref_to_prvalue (convs[1]))
10475 warning_at (loc, OPT_Winit_list_lifetime,
10476 "assignment from temporary %<initializer_list%> does "
10477 "not extend the lifetime of the underlying array");
10478 arg = cp_build_fold_indirect_ref (arg);
10479 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10480 }
10481 else
10482 {
10483 /* We must only copy the non-tail padding parts. */
10484 tree arg0, arg2, t;
10485 tree array_type, alias_set;
10486
10487 arg2 = TYPE_SIZE_UNIT (as_base);
10488 to = cp_stabilize_reference (to);
10489 arg0 = cp_build_addr_expr (to, complain);
10490
10491 array_type = build_array_type (unsigned_char_type_node,
10492 build_index_type
10493 (size_binop (MINUS_EXPR,
10494 arg2, size_int (1))));
10495 alias_set = build_int_cst (build_pointer_type (type), 0);
10496 t = build2 (MODIFY_EXPR, void_type_node,
10497 build2 (MEM_REF, array_type, arg0, alias_set),
10498 build2 (MEM_REF, array_type, arg, alias_set));
10499 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10500 suppress_warning (val, OPT_Wunused);
10501 }
10502
10503 cp_handle_deprecated_or_unavailable (fn, complain);
10504
10505 return val;
10506 }
10507 else if (trivial_fn_p (fn))
10508 {
10509 if (DECL_DESTRUCTOR_P (fn))
10510 return build_trivial_dtor_call (argarray[0]);
10511 else if (default_ctor_p (fn))
10512 {
10513 if (is_dummy_object (argarray[0]))
10514 return force_target_expr (DECL_CONTEXT (fn), void_node,
10515 no_cleanup_complain);
10516 else
10517 return cp_build_fold_indirect_ref (argarray[0]);
10518 }
10519 }
10520
10521 gcc_assert (!force_elide);
10522
10523 if (!already_used
10524 && !mark_used (fn, complain))
10525 return error_mark_node;
10526
10527 /* Warn if the built-in writes to an object of a non-trivial type. */
10528 if (warn_class_memaccess
10529 && vec_safe_length (args) >= 2
10530 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10531 maybe_warn_class_memaccess (input_location, fn, args);
10532
10533 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10534 {
10535 tree t;
10536 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10537 DECL_CONTEXT (fn),
10538 ba_any, NULL, complain);
10539 gcc_assert (binfo && binfo != error_mark_node);
10540
10541 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10542 complain);
10543 if (TREE_SIDE_EFFECTS (argarray[0]))
10544 argarray[0] = save_expr (argarray[0]);
10545 t = build_pointer_type (TREE_TYPE (fn));
10546 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10547 TREE_TYPE (fn) = t;
10548 }
10549 else
10550 {
10551 /* If FN is marked deprecated or unavailable, then we've already
10552 issued a diagnostic from mark_used above, so avoid redundantly
10553 issuing another one from build_addr_func. */
10554 auto w = make_temp_override (deprecated_state,
10555 UNAVAILABLE_DEPRECATED_SUPPRESS);
10556
10557 fn = build_addr_func (fn, complain);
10558 if (fn == error_mark_node)
10559 return error_mark_node;
10560
10561 /* We're actually invoking the function. (Immediate functions get an
10562 & when invoking it even though the user didn't use &.) */
10563 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
10564 }
10565
10566 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10567 if (call == error_mark_node)
10568 return call;
10569 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10570 {
10571 tree c = extract_call_expr (call);
10572 /* build_new_op will clear this when appropriate. */
10573 CALL_EXPR_ORDERED_ARGS (c) = true;
10574 }
10575 if (warned_p)
10576 {
10577 tree c = extract_call_expr (call);
10578 if (TREE_CODE (c) == CALL_EXPR)
10579 suppress_warning (c /* Suppress all warnings. */);
10580 }
10581
10582 return call;
10583 }
10584
10585 namespace
10586 {
10587
10588 /* Return the DECL of the first non-static subobject of class TYPE
10589 that satisfies the predicate PRED or null if none can be found. */
10590
10591 template <class Predicate>
10592 tree
10593 first_non_static_field (tree type, Predicate pred)
10594 {
10595 if (!type || !CLASS_TYPE_P (type))
10596 return NULL_TREE;
10597
10598 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10599 {
10600 if (TREE_CODE (field) != FIELD_DECL)
10601 continue;
10602 if (TREE_STATIC (field))
10603 continue;
10604 if (pred (field))
10605 return field;
10606 }
10607
10608 int i = 0;
10609
10610 for (tree base_binfo, binfo = TYPE_BINFO (type);
10611 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10612 {
10613 tree base = TREE_TYPE (base_binfo);
10614 if (pred (base))
10615 return base;
10616 if (tree field = first_non_static_field (base, pred))
10617 return field;
10618 }
10619
10620 return NULL_TREE;
10621 }
10622
10623 struct NonPublicField
10624 {
10625 bool operator() (const_tree t) const
10626 {
10627 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10628 }
10629 };
10630
10631 /* Return the DECL of the first non-public subobject of class TYPE
10632 or null if none can be found. */
10633
10634 static inline tree
10635 first_non_public_field (tree type)
10636 {
10637 return first_non_static_field (type, NonPublicField ());
10638 }
10639
10640 struct NonTrivialField
10641 {
10642 bool operator() (const_tree t) const
10643 {
10644 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10645 }
10646 };
10647
10648 /* Return the DECL of the first non-trivial subobject of class TYPE
10649 or null if none can be found. */
10650
10651 static inline tree
10652 first_non_trivial_field (tree type)
10653 {
10654 return first_non_static_field (type, NonTrivialField ());
10655 }
10656
10657 } /* unnamed namespace */
10658
10659 /* Return true if all copy and move assignment operator overloads for
10660 class TYPE are trivial and at least one of them is not deleted and,
10661 when ACCESS is set, accessible. Return false otherwise. Set
10662 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10663 copy or move assignment. */
10664
10665 static bool
10666 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10667 {
10668 tree fns = get_class_binding (type, assign_op_identifier);
10669 bool all_trivial = true;
10670
10671 /* Iterate over overloads of the assignment operator, checking
10672 accessible copy assignments for triviality. */
10673
10674 for (tree f : ovl_range (fns))
10675 {
10676 /* Skip operators that aren't copy assignments. */
10677 if (!copy_fn_p (f))
10678 continue;
10679
10680 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10681 || accessible_p (TYPE_BINFO (type), f, true));
10682
10683 /* Skip template assignment operators and deleted functions. */
10684 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10685 continue;
10686
10687 if (accessible)
10688 *hasassign = true;
10689
10690 if (!accessible || !trivial_fn_p (f))
10691 all_trivial = false;
10692
10693 /* Break early when both properties have been determined. */
10694 if (*hasassign && !all_trivial)
10695 break;
10696 }
10697
10698 /* Return true if they're all trivial and one of the expressions
10699 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10700 tree ref = cp_build_reference_type (type, false);
10701 return (all_trivial
10702 && (is_trivially_xible (MODIFY_EXPR, type, type)
10703 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10704 }
10705
10706 /* Return true if all copy and move ctor overloads for class TYPE are
10707 trivial and at least one of them is not deleted and, when ACCESS is
10708 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10709 to true when the TYPE has a (not necessarily trivial) default and copy
10710 (or move) ctor, respectively. */
10711
10712 static bool
10713 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10714 {
10715 tree fns = get_class_binding (type, complete_ctor_identifier);
10716 bool all_trivial = true;
10717
10718 for (tree f : ovl_range (fns))
10719 {
10720 /* Skip template constructors. */
10721 if (TREE_CODE (f) != FUNCTION_DECL)
10722 continue;
10723
10724 bool cpy_or_move_ctor_p = copy_fn_p (f);
10725
10726 /* Skip ctors other than default, copy, and move. */
10727 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10728 continue;
10729
10730 if (DECL_DELETED_FN (f))
10731 continue;
10732
10733 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10734 || accessible_p (TYPE_BINFO (type), f, true));
10735
10736 if (accessible)
10737 hasctor[cpy_or_move_ctor_p] = true;
10738
10739 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10740 all_trivial = false;
10741
10742 /* Break early when both properties have been determined. */
10743 if (hasctor[0] && hasctor[1] && !all_trivial)
10744 break;
10745 }
10746
10747 return all_trivial;
10748 }
10749
10750 /* Issue a warning on a call to the built-in function FNDECL if it is
10751 a raw memory write whose destination is not an object of (something
10752 like) trivial or standard layout type with a non-deleted assignment
10753 and copy ctor. Detects const correctness violations, corrupting
10754 references, virtual table pointers, and bypassing non-trivial
10755 assignments. */
10756
10757 static void
10758 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10759 const vec<tree, va_gc> *args)
10760 {
10761 /* Except for bcopy where it's second, the destination pointer is
10762 the first argument for all functions handled here. Compute
10763 the index of the destination and source arguments. */
10764 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10765 unsigned srcidx = !dstidx;
10766
10767 tree dest = (*args)[dstidx];
10768 if (!TREE_TYPE (dest)
10769 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10770 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10771 return;
10772
10773 tree srctype = NULL_TREE;
10774
10775 /* Determine the type of the pointed-to object and whether it's
10776 a complete class type. */
10777 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10778
10779 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10780 return;
10781
10782 /* Check to see if the raw memory call is made by a non-static member
10783 function with THIS as the destination argument for the destination
10784 type. If so, and if the class has no non-trivial bases or members,
10785 be more permissive. */
10786 if (current_function_decl
10787 && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10788 && is_this_parameter (tree_strip_nop_conversions (dest)))
10789 {
10790 tree ctx = DECL_CONTEXT (current_function_decl);
10791 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10792 tree binfo = TYPE_BINFO (ctx);
10793
10794 if (special
10795 && !BINFO_VTABLE (binfo)
10796 && !first_non_trivial_field (desttype))
10797 return;
10798 }
10799
10800 /* True if the class is trivial. */
10801 bool trivial = trivial_type_p (desttype);
10802
10803 /* Set to true if DESTYPE has an accessible copy assignment. */
10804 bool hasassign = false;
10805 /* True if all of the class' overloaded copy assignment operators
10806 are all trivial (and not deleted) and at least one of them is
10807 accessible. */
10808 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10809
10810 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10811 respectively. */
10812 bool hasctors[2] = { false, false };
10813
10814 /* True if all of the class' overloaded copy constructors are all
10815 trivial (and not deleted) and at least one of them is accessible. */
10816 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10817
10818 /* Set FLD to the first private/protected member of the class. */
10819 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10820
10821 /* The warning format string. */
10822 const char *warnfmt = NULL;
10823 /* A suggested alternative to offer instead of the raw memory call.
10824 Empty string when none can be come up with. */
10825 const char *suggest = "";
10826 bool warned = false;
10827
10828 switch (DECL_FUNCTION_CODE (fndecl))
10829 {
10830 case BUILT_IN_MEMSET:
10831 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10832 {
10833 /* Diagnose setting non-copy-assignable or non-trivial types,
10834 or types with a private member, to (potentially) non-zero
10835 bytes. Since the value of the bytes being written is unknown,
10836 suggest using assignment instead (if one exists). Also warn
10837 for writes into objects for which zero-initialization doesn't
10838 mean all bits clear (pointer-to-member data, where null is all
10839 bits set). Since the value being written is (most likely)
10840 non-zero, simply suggest assignment (but not copy assignment). */
10841 suggest = "; use assignment instead";
10842 if (!trivassign)
10843 warnfmt = G_("%qD writing to an object of type %#qT with "
10844 "no trivial copy-assignment");
10845 else if (!trivial)
10846 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10847 else if (fld)
10848 {
10849 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10850 warned = warning_at (loc, OPT_Wclass_memaccess,
10851 "%qD writing to an object of type %#qT with "
10852 "%qs member %qD",
10853 fndecl, desttype, access, fld);
10854 }
10855 else if (!zero_init_p (desttype))
10856 warnfmt = G_("%qD writing to an object of type %#qT containing "
10857 "a pointer to data member%s");
10858
10859 break;
10860 }
10861 /* Fall through. */
10862
10863 case BUILT_IN_BZERO:
10864 /* Similarly to the above, diagnose clearing non-trivial or non-
10865 standard layout objects, or objects of types with no assignmenmt.
10866 Since the value being written is known to be zero, suggest either
10867 copy assignment, copy ctor, or default ctor as an alternative,
10868 depending on what's available. */
10869
10870 if (hasassign && hasctors[0])
10871 suggest = G_("; use assignment or value-initialization instead");
10872 else if (hasassign)
10873 suggest = G_("; use assignment instead");
10874 else if (hasctors[0])
10875 suggest = G_("; use value-initialization instead");
10876
10877 if (!trivassign)
10878 warnfmt = G_("%qD clearing an object of type %#qT with "
10879 "no trivial copy-assignment%s");
10880 else if (!trivial)
10881 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10882 else if (!zero_init_p (desttype))
10883 warnfmt = G_("%qD clearing an object of type %#qT containing "
10884 "a pointer-to-member%s");
10885 break;
10886
10887 case BUILT_IN_BCOPY:
10888 case BUILT_IN_MEMCPY:
10889 case BUILT_IN_MEMMOVE:
10890 case BUILT_IN_MEMPCPY:
10891 /* Determine the type of the source object. */
10892 srctype = TREE_TYPE ((*args)[srcidx]);
10893 if (!srctype || !INDIRECT_TYPE_P (srctype))
10894 srctype = void_type_node;
10895 else
10896 srctype = TREE_TYPE (srctype);
10897
10898 /* Since it's impossible to determine wheter the byte copy is
10899 being used in place of assignment to an existing object or
10900 as a substitute for initialization, assume it's the former.
10901 Determine the best alternative to use instead depending on
10902 what's not deleted. */
10903 if (hasassign && hasctors[1])
10904 suggest = G_("; use copy-assignment or copy-initialization instead");
10905 else if (hasassign)
10906 suggest = G_("; use copy-assignment instead");
10907 else if (hasctors[1])
10908 suggest = G_("; use copy-initialization instead");
10909
10910 if (!trivassign)
10911 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10912 "copy-assignment%s");
10913 else if (!trivially_copyable_p (desttype))
10914 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10915 "type %#qT%s");
10916 else if (!trivcopy)
10917 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10918
10919 else if (!trivial
10920 && !VOID_TYPE_P (srctype)
10921 && !is_byte_access_type (srctype)
10922 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10923 srctype))
10924 {
10925 /* Warn when copying into a non-trivial object from an object
10926 of a different type other than void or char. */
10927 warned = warning_at (loc, OPT_Wclass_memaccess,
10928 "%qD copying an object of non-trivial type "
10929 "%#qT from an array of %#qT",
10930 fndecl, desttype, srctype);
10931 }
10932 else if (fld
10933 && !VOID_TYPE_P (srctype)
10934 && !is_byte_access_type (srctype)
10935 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10936 srctype))
10937 {
10938 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10939 warned = warning_at (loc, OPT_Wclass_memaccess,
10940 "%qD copying an object of type %#qT with "
10941 "%qs member %qD from an array of %#qT; use "
10942 "assignment or copy-initialization instead",
10943 fndecl, desttype, access, fld, srctype);
10944 }
10945 else if (!trivial && vec_safe_length (args) > 2)
10946 {
10947 tree sz = maybe_constant_value ((*args)[2]);
10948 if (!tree_fits_uhwi_p (sz))
10949 break;
10950
10951 /* Finally, warn on partial copies. */
10952 unsigned HOST_WIDE_INT typesize
10953 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10954 if (typesize == 0)
10955 break;
10956 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10957 warned = warning_at (loc, OPT_Wclass_memaccess,
10958 (typesize - partial > 1
10959 ? G_("%qD writing to an object of "
10960 "a non-trivial type %#qT leaves %wu "
10961 "bytes unchanged")
10962 : G_("%qD writing to an object of "
10963 "a non-trivial type %#qT leaves %wu "
10964 "byte unchanged")),
10965 fndecl, desttype, typesize - partial);
10966 }
10967 break;
10968
10969 case BUILT_IN_REALLOC:
10970
10971 if (!trivially_copyable_p (desttype))
10972 warnfmt = G_("%qD moving an object of non-trivially copyable type "
10973 "%#qT; use %<new%> and %<delete%> instead");
10974 else if (!trivcopy)
10975 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10976 "constructor; use %<new%> and %<delete%> instead");
10977 else if (!get_dtor (desttype, tf_none))
10978 warnfmt = G_("%qD moving an object of type %#qT with deleted "
10979 "destructor");
10980 else if (!trivial)
10981 {
10982 tree sz = maybe_constant_value ((*args)[1]);
10983 if (TREE_CODE (sz) == INTEGER_CST
10984 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10985 /* Finally, warn on reallocation into insufficient space. */
10986 warned = warning_at (loc, OPT_Wclass_memaccess,
10987 "%qD moving an object of non-trivial type "
10988 "%#qT and size %E into a region of size %E",
10989 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10990 sz);
10991 }
10992 break;
10993
10994 default:
10995 return;
10996 }
10997
10998 if (warnfmt)
10999 {
11000 if (suggest)
11001 warned = warning_at (loc, OPT_Wclass_memaccess,
11002 warnfmt, fndecl, desttype, suggest);
11003 else
11004 warned = warning_at (loc, OPT_Wclass_memaccess,
11005 warnfmt, fndecl, desttype);
11006 }
11007
11008 if (warned)
11009 inform (location_of (desttype), "%#qT declared here", desttype);
11010 }
11011
11012 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
11013 If FN is the result of resolving an overloaded target built-in,
11014 ORIG_FNDECL is the original function decl, otherwise it is null.
11015 This function performs no overload resolution, conversion, or other
11016 high-level operations. */
11017
11018 tree
11019 build_cxx_call (tree fn, int nargs, tree *argarray,
11020 tsubst_flags_t complain, tree orig_fndecl)
11021 {
11022 tree fndecl;
11023
11024 /* Remember roughly where this call is. */
11025 location_t loc = cp_expr_loc_or_input_loc (fn);
11026 fn = build_call_a (fn, nargs, argarray);
11027 SET_EXPR_LOCATION (fn, loc);
11028
11029 fndecl = get_callee_fndecl (fn);
11030 if (!orig_fndecl)
11031 orig_fndecl = fndecl;
11032
11033 /* Check that arguments to builtin functions match the expectations. */
11034 if (fndecl
11035 && !processing_template_decl
11036 && fndecl_built_in_p (fndecl))
11037 {
11038 int i;
11039
11040 /* We need to take care that values to BUILT_IN_NORMAL
11041 are reduced. */
11042 for (i = 0; i < nargs; i++)
11043 argarray[i] = maybe_constant_value (argarray[i]);
11044
11045 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
11046 orig_fndecl, nargs, argarray))
11047 return error_mark_node;
11048 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
11049 {
11050 tree arg0 = argarray[0];
11051 STRIP_NOPS (arg0);
11052 if (TREE_CODE (arg0) == ADDR_EXPR
11053 && DECL_P (TREE_OPERAND (arg0, 0))
11054 && same_type_ignoring_top_level_qualifiers_p
11055 (TREE_TYPE (TREE_TYPE (argarray[0])),
11056 TREE_TYPE (TREE_TYPE (arg0))))
11057 /* For __builtin_clear_padding (&var) we know the type
11058 is for a complete object, so there is no risk in clearing
11059 padding that is reused in some derived class member. */;
11060 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
11061 {
11062 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
11063 "argument %u in call to function %qE "
11064 "has pointer to a non-trivially-copyable type (%qT)",
11065 1, fndecl, TREE_TYPE (argarray[0]));
11066 return error_mark_node;
11067 }
11068 }
11069 }
11070
11071 if (VOID_TYPE_P (TREE_TYPE (fn)))
11072 return fn;
11073
11074 /* 5.2.2/11: If a function call is a prvalue of object type: if the
11075 function call is either the operand of a decltype-specifier or the
11076 right operand of a comma operator that is the operand of a
11077 decltype-specifier, a temporary object is not introduced for the
11078 prvalue. The type of the prvalue may be incomplete. */
11079 if (!(complain & tf_decltype))
11080 {
11081 fn = require_complete_type (fn, complain);
11082 if (fn == error_mark_node)
11083 return error_mark_node;
11084
11085 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
11086 {
11087 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
11088 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
11089 }
11090 }
11091 return convert_from_reference (fn);
11092 }
11093
11094 /* Returns the value to use for the in-charge parameter when making a
11095 call to a function with the indicated NAME.
11096
11097 FIXME:Can't we find a neater way to do this mapping? */
11098
11099 tree
11100 in_charge_arg_for_name (tree name)
11101 {
11102 if (IDENTIFIER_CTOR_P (name))
11103 {
11104 if (name == complete_ctor_identifier)
11105 return integer_one_node;
11106 gcc_checking_assert (name == base_ctor_identifier);
11107 }
11108 else
11109 {
11110 if (name == complete_dtor_identifier)
11111 return integer_two_node;
11112 else if (name == deleting_dtor_identifier)
11113 return integer_three_node;
11114 gcc_checking_assert (name == base_dtor_identifier);
11115 }
11116
11117 return integer_zero_node;
11118 }
11119
11120 /* We've built up a constructor call RET. Complain if it delegates to the
11121 constructor we're currently compiling. */
11122
11123 static void
11124 check_self_delegation (tree ret)
11125 {
11126 if (TREE_CODE (ret) == TARGET_EXPR)
11127 ret = TARGET_EXPR_INITIAL (ret);
11128 tree fn = cp_get_callee_fndecl_nofold (ret);
11129 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11130 error ("constructor delegates to itself");
11131 }
11132
11133 /* Build a call to a constructor, destructor, or an assignment
11134 operator for INSTANCE, an expression with class type. NAME
11135 indicates the special member function to call; *ARGS are the
11136 arguments. ARGS may be NULL. This may change ARGS. BINFO
11137 indicates the base of INSTANCE that is to be passed as the `this'
11138 parameter to the member function called.
11139
11140 FLAGS are the LOOKUP_* flags to use when processing the call.
11141
11142 If NAME indicates a complete object constructor, INSTANCE may be
11143 NULL_TREE. In this case, the caller will call build_cplus_new to
11144 store the newly constructed object into a VAR_DECL. */
11145
11146 tree
11147 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11148 tree binfo, int flags, tsubst_flags_t complain)
11149 {
11150 tree fns;
11151 /* The type of the subobject to be constructed or destroyed. */
11152 tree class_type;
11153 vec<tree, va_gc> *allocated = NULL;
11154 tree ret;
11155
11156 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11157
11158 if (error_operand_p (instance))
11159 return error_mark_node;
11160
11161 if (IDENTIFIER_DTOR_P (name))
11162 {
11163 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11164 if (!type_build_dtor_call (TREE_TYPE (instance)))
11165 /* Shortcut to avoid lazy destructor declaration. */
11166 return build_trivial_dtor_call (instance);
11167 }
11168
11169 if (TYPE_P (binfo))
11170 {
11171 /* Resolve the name. */
11172 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11173 return error_mark_node;
11174
11175 binfo = TYPE_BINFO (binfo);
11176 }
11177
11178 gcc_assert (binfo != NULL_TREE);
11179
11180 class_type = BINFO_TYPE (binfo);
11181
11182 /* Handle the special case where INSTANCE is NULL_TREE. */
11183 if (name == complete_ctor_identifier && !instance)
11184 instance = build_dummy_object (class_type);
11185 else
11186 {
11187 /* Convert to the base class, if necessary. */
11188 if (!same_type_ignoring_top_level_qualifiers_p
11189 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11190 {
11191 if (IDENTIFIER_CDTOR_P (name))
11192 /* For constructors and destructors, either the base is
11193 non-virtual, or it is virtual but we are doing the
11194 conversion from a constructor or destructor for the
11195 complete object. In either case, we can convert
11196 statically. */
11197 instance = convert_to_base_statically (instance, binfo);
11198 else
11199 {
11200 /* However, for assignment operators, we must convert
11201 dynamically if the base is virtual. */
11202 gcc_checking_assert (name == assign_op_identifier);
11203 instance = build_base_path (PLUS_EXPR, instance,
11204 binfo, /*nonnull=*/1, complain);
11205 }
11206 }
11207 }
11208
11209 gcc_assert (instance != NULL_TREE);
11210
11211 /* In C++17, "If the initializer expression is a prvalue and the
11212 cv-unqualified version of the source type is the same class as the class
11213 of the destination, the initializer expression is used to initialize the
11214 destination object." Handle that here to avoid doing overload
11215 resolution. */
11216 if (cxx_dialect >= cxx17
11217 && args && vec_safe_length (*args) == 1
11218 && !unsafe_return_slot_p (instance))
11219 {
11220 tree arg = (**args)[0];
11221
11222 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11223 && !TYPE_HAS_LIST_CTOR (class_type)
11224 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11225 && CONSTRUCTOR_NELTS (arg) == 1)
11226 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11227
11228 if ((TREE_CODE (arg) == TARGET_EXPR
11229 || TREE_CODE (arg) == CONSTRUCTOR)
11230 && (same_type_ignoring_top_level_qualifiers_p
11231 (class_type, TREE_TYPE (arg))))
11232 {
11233 if (is_dummy_object (instance))
11234 return arg;
11235 else if (TREE_CODE (arg) == TARGET_EXPR)
11236 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11237
11238 if ((complain & tf_error)
11239 && (flags & LOOKUP_DELEGATING_CONS))
11240 check_self_delegation (arg);
11241 /* Avoid change of behavior on Wunused-var-2.C. */
11242 instance = mark_lvalue_use (instance);
11243 return cp_build_init_expr (instance, arg);
11244 }
11245 }
11246
11247 fns = lookup_fnfields (binfo, name, 1, complain);
11248
11249 /* When making a call to a constructor or destructor for a subobject
11250 that uses virtual base classes, pass down a pointer to a VTT for
11251 the subobject. */
11252 if ((name == base_ctor_identifier
11253 || name == base_dtor_identifier)
11254 && CLASSTYPE_VBASECLASSES (class_type))
11255 {
11256 tree vtt;
11257 tree sub_vtt;
11258
11259 /* If the current function is a complete object constructor
11260 or destructor, then we fetch the VTT directly.
11261 Otherwise, we look it up using the VTT we were given. */
11262 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11263 vtt = decay_conversion (vtt, complain);
11264 if (vtt == error_mark_node)
11265 return error_mark_node;
11266 vtt = build_if_in_charge (vtt, current_vtt_parm);
11267 if (BINFO_SUBVTT_INDEX (binfo))
11268 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11269 else
11270 sub_vtt = vtt;
11271
11272 if (args == NULL)
11273 {
11274 allocated = make_tree_vector ();
11275 args = &allocated;
11276 }
11277
11278 vec_safe_insert (*args, 0, sub_vtt);
11279 }
11280
11281 ret = build_new_method_call (instance, fns, args,
11282 TYPE_BINFO (BINFO_TYPE (binfo)),
11283 flags, /*fn=*/NULL,
11284 complain);
11285
11286 if (allocated != NULL)
11287 release_tree_vector (allocated);
11288
11289 if ((complain & tf_error)
11290 && (flags & LOOKUP_DELEGATING_CONS)
11291 && name == complete_ctor_identifier)
11292 check_self_delegation (ret);
11293
11294 return ret;
11295 }
11296
11297 /* Return the NAME, as a C string. The NAME indicates a function that
11298 is a member of TYPE. *FREE_P is set to true if the caller must
11299 free the memory returned.
11300
11301 Rather than go through all of this, we should simply set the names
11302 of constructors and destructors appropriately, and dispense with
11303 ctor_identifier, dtor_identifier, etc. */
11304
11305 static char *
11306 name_as_c_string (tree name, tree type, bool *free_p)
11307 {
11308 const char *pretty_name;
11309
11310 /* Assume that we will not allocate memory. */
11311 *free_p = false;
11312 /* Constructors and destructors are special. */
11313 if (IDENTIFIER_CDTOR_P (name))
11314 {
11315 pretty_name
11316 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11317 /* For a destructor, add the '~'. */
11318 if (IDENTIFIER_DTOR_P (name))
11319 {
11320 pretty_name = concat ("~", pretty_name, NULL);
11321 /* Remember that we need to free the memory allocated. */
11322 *free_p = true;
11323 }
11324 }
11325 else if (IDENTIFIER_CONV_OP_P (name))
11326 {
11327 pretty_name = concat ("operator ",
11328 type_as_string_translate (TREE_TYPE (name),
11329 TFF_PLAIN_IDENTIFIER),
11330 NULL);
11331 /* Remember that we need to free the memory allocated. */
11332 *free_p = true;
11333 }
11334 else
11335 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11336
11337 return CONST_CAST (char *, pretty_name);
11338 }
11339
11340 /* If CANDIDATES contains exactly one candidate, return it, otherwise
11341 return NULL. */
11342
11343 static z_candidate *
11344 single_z_candidate (z_candidate *candidates)
11345 {
11346 if (candidates == NULL)
11347 return NULL;
11348
11349 if (candidates->next)
11350 return NULL;
11351
11352 return candidates;
11353 }
11354
11355 /* If CANDIDATE is invalid due to a bad argument type, return the
11356 pertinent conversion_info.
11357
11358 Otherwise, return NULL. */
11359
11360 static const conversion_info *
11361 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11362 {
11363 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11364 rejection_reason *r = candidate->reason;
11365
11366 if (r == NULL)
11367 return NULL;
11368
11369 switch (r->code)
11370 {
11371 default:
11372 return NULL;
11373
11374 case rr_arg_conversion:
11375 return &r->u.conversion;
11376
11377 case rr_bad_arg_conversion:
11378 return &r->u.bad_conversion;
11379 }
11380 }
11381
11382 /* Issue an error and note complaining about a bad argument type at a
11383 callsite with a single candidate FNDECL.
11384
11385 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11386 case input_location is used).
11387 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11388 the formal parameter. */
11389
11390 void
11391 complain_about_bad_argument (location_t arg_loc,
11392 tree from_type, tree to_type,
11393 tree fndecl, int parmnum)
11394 {
11395 auto_diagnostic_group d;
11396 range_label_for_type_mismatch rhs_label (from_type, to_type);
11397 range_label *label = &rhs_label;
11398 if (arg_loc == UNKNOWN_LOCATION)
11399 {
11400 arg_loc = input_location;
11401 label = NULL;
11402 }
11403 gcc_rich_location richloc (arg_loc, label);
11404 error_at (&richloc,
11405 "cannot convert %qH to %qI",
11406 from_type, to_type);
11407 maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
11408 parmnum);
11409 }
11410
11411 /* Subroutine of build_new_method_call_1, for where there are no viable
11412 candidates for the call. */
11413
11414 static void
11415 complain_about_no_candidates_for_method_call (tree instance,
11416 z_candidate *candidates,
11417 tree explicit_targs,
11418 tree basetype,
11419 tree optype, tree name,
11420 bool skip_first_for_error,
11421 vec<tree, va_gc> *user_args)
11422 {
11423 auto_diagnostic_group d;
11424 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11425 cxx_incomplete_type_error (instance, basetype);
11426 else if (optype)
11427 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11428 basetype, optype, build_tree_list_vec (user_args),
11429 TREE_TYPE (instance));
11430 else
11431 {
11432 /* Special-case for when there's a single candidate that's failing
11433 due to a bad argument type. */
11434 if (z_candidate *candidate = single_z_candidate (candidates))
11435 if (const conversion_info *conv
11436 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11437 {
11438 tree from_type = conv->from;
11439 if (!TYPE_P (conv->from))
11440 from_type = lvalue_type (conv->from);
11441 complain_about_bad_argument (conv->loc,
11442 from_type, conv->to_type,
11443 candidate->fn, conv->n_arg);
11444 return;
11445 }
11446
11447 tree arglist = build_tree_list_vec (user_args);
11448 tree errname = name;
11449 bool twiddle = false;
11450 if (IDENTIFIER_CDTOR_P (errname))
11451 {
11452 twiddle = IDENTIFIER_DTOR_P (errname);
11453 errname = constructor_name (basetype);
11454 }
11455 if (explicit_targs)
11456 errname = lookup_template_function (errname, explicit_targs);
11457 if (skip_first_for_error)
11458 arglist = TREE_CHAIN (arglist);
11459 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11460 basetype, &"~"[!twiddle], errname, arglist,
11461 TREE_TYPE (instance));
11462 }
11463 print_z_candidates (location_of (name), candidates);
11464 }
11465
11466 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11467 be set, upon return, to the function called. ARGS may be NULL.
11468 This may change ARGS. */
11469
11470 tree
11471 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11472 tree conversion_path, int flags,
11473 tree *fn_p, tsubst_flags_t complain)
11474 {
11475 struct z_candidate *candidates = 0, *cand;
11476 tree explicit_targs = NULL_TREE;
11477 tree basetype = NULL_TREE;
11478 tree access_binfo;
11479 tree optype;
11480 tree first_mem_arg = NULL_TREE;
11481 tree name;
11482 bool skip_first_for_error;
11483 vec<tree, va_gc> *user_args;
11484 tree call;
11485 tree fn;
11486 int template_only = 0;
11487 bool any_viable_p;
11488 tree orig_instance;
11489 tree orig_fns;
11490 vec<tree, va_gc> *orig_args = NULL;
11491
11492 auto_cond_timevar tv (TV_OVERLOAD);
11493
11494 gcc_assert (instance != NULL_TREE);
11495
11496 /* We don't know what function we're going to call, yet. */
11497 if (fn_p)
11498 *fn_p = NULL_TREE;
11499
11500 if (error_operand_p (instance)
11501 || !fns || error_operand_p (fns))
11502 return error_mark_node;
11503
11504 if (!BASELINK_P (fns))
11505 {
11506 if (complain & tf_error)
11507 error ("call to non-function %qD", fns);
11508 return error_mark_node;
11509 }
11510
11511 orig_instance = instance;
11512 orig_fns = fns;
11513
11514 /* Dismantle the baselink to collect all the information we need. */
11515 if (!conversion_path)
11516 conversion_path = BASELINK_BINFO (fns);
11517 access_binfo = BASELINK_ACCESS_BINFO (fns);
11518 optype = BASELINK_OPTYPE (fns);
11519 fns = BASELINK_FUNCTIONS (fns);
11520 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11521 {
11522 explicit_targs = TREE_OPERAND (fns, 1);
11523 fns = TREE_OPERAND (fns, 0);
11524 template_only = 1;
11525 }
11526 gcc_assert (OVL_P (fns));
11527 fn = OVL_FIRST (fns);
11528 name = DECL_NAME (fn);
11529
11530 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11531 gcc_assert (CLASS_TYPE_P (basetype));
11532
11533 user_args = args == NULL ? NULL : *args;
11534 /* Under DR 147 A::A() is an invalid constructor call,
11535 not a functional cast. */
11536 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11537 {
11538 if (! (complain & tf_error))
11539 return error_mark_node;
11540
11541 basetype = DECL_CONTEXT (fn);
11542 name = constructor_name (basetype);
11543 auto_diagnostic_group d;
11544 if (permerror (input_location,
11545 "cannot call constructor %<%T::%D%> directly",
11546 basetype, name))
11547 inform (input_location, "for a function-style cast, remove the "
11548 "redundant %<::%D%>", name);
11549 call = build_functional_cast (input_location, basetype,
11550 build_tree_list_vec (user_args),
11551 complain);
11552 return call;
11553 }
11554
11555 if (processing_template_decl)
11556 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11557
11558 /* Process the argument list. */
11559 if (args != NULL && *args != NULL)
11560 {
11561 *args = resolve_args (*args, complain);
11562 if (*args == NULL)
11563 return error_mark_node;
11564 user_args = *args;
11565 }
11566
11567 /* Consider the object argument to be used even if we end up selecting a
11568 static member function. */
11569 instance = mark_type_use (instance);
11570
11571 /* Figure out whether to skip the first argument for the error
11572 message we will display to users if an error occurs. We don't
11573 want to display any compiler-generated arguments. The "this"
11574 pointer hasn't been added yet. However, we must remove the VTT
11575 pointer if this is a call to a base-class constructor or
11576 destructor. */
11577 skip_first_for_error = false;
11578 if (IDENTIFIER_CDTOR_P (name))
11579 {
11580 /* Callers should explicitly indicate whether they want to ctor
11581 the complete object or just the part without virtual bases. */
11582 gcc_assert (name != ctor_identifier);
11583
11584 /* Remove the VTT pointer, if present. */
11585 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11586 && CLASSTYPE_VBASECLASSES (basetype))
11587 skip_first_for_error = true;
11588
11589 /* It's OK to call destructors and constructors on cv-qualified
11590 objects. Therefore, convert the INSTANCE to the unqualified
11591 type, if necessary. */
11592 if (!same_type_p (basetype, TREE_TYPE (instance)))
11593 {
11594 instance = build_this (instance);
11595 instance = build_nop (build_pointer_type (basetype), instance);
11596 instance = build_fold_indirect_ref (instance);
11597 }
11598 }
11599 else
11600 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11601
11602 /* For the overload resolution we need to find the actual `this`
11603 that would be captured if the call turns out to be to a
11604 non-static member function. Do not actually capture it at this
11605 point. */
11606 if (DECL_CONSTRUCTOR_P (fn))
11607 /* Constructors don't use the enclosing 'this'. */
11608 first_mem_arg = instance;
11609 else
11610 first_mem_arg = maybe_resolve_dummy (instance, false);
11611
11612 conversion_obstack_sentinel cos;
11613
11614 /* The number of arguments artificial parms in ARGS; we subtract one because
11615 there's no 'this' in ARGS. */
11616 unsigned skip = num_artificial_parms_for (fn) - 1;
11617
11618 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11619 initializer, not T({ }). */
11620 if (DECL_CONSTRUCTOR_P (fn)
11621 && vec_safe_length (user_args) > skip
11622 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11623 {
11624 tree init_list = (*user_args)[skip];
11625 tree init = NULL_TREE;
11626
11627 gcc_assert (user_args->length () == skip + 1
11628 && !(flags & LOOKUP_ONLYCONVERTING));
11629
11630 /* If the initializer list has no elements and T is a class type with
11631 a default constructor, the object is value-initialized. Handle
11632 this here so we don't need to handle it wherever we use
11633 build_special_member_call. */
11634 if (CONSTRUCTOR_NELTS (init_list) == 0
11635 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11636 /* For a user-provided default constructor, use the normal
11637 mechanisms so that protected access works. */
11638 && type_has_non_user_provided_default_constructor (basetype)
11639 && !processing_template_decl)
11640 init = build_value_init (basetype, complain);
11641
11642 /* If BASETYPE is an aggregate, we need to do aggregate
11643 initialization. */
11644 else if (CP_AGGREGATE_TYPE_P (basetype))
11645 {
11646 init = reshape_init (basetype, init_list, complain);
11647 init = digest_init (basetype, init, complain);
11648 }
11649
11650 if (init)
11651 {
11652 if (is_dummy_object (instance))
11653 return get_target_expr (init, complain);
11654 return cp_build_init_expr (instance, init);
11655 }
11656
11657 /* Otherwise go ahead with overload resolution. */
11658 add_list_candidates (fns, first_mem_arg, user_args,
11659 basetype, explicit_targs, template_only,
11660 conversion_path, access_binfo, flags,
11661 &candidates, complain);
11662 }
11663 else
11664 add_candidates (fns, first_mem_arg, user_args, optype,
11665 explicit_targs, template_only, conversion_path,
11666 access_binfo, flags, &candidates, complain);
11667
11668 any_viable_p = false;
11669 candidates = splice_viable (candidates, false, &any_viable_p);
11670
11671 if (!any_viable_p)
11672 {
11673 /* [dcl.init], 17.6.2.2:
11674
11675 Otherwise, if no constructor is viable, the destination type is
11676 a (possibly cv-qualified) aggregate class A, and the initializer
11677 is a parenthesized expression-list, the object is initialized as
11678 follows...
11679
11680 We achieve this by building up a CONSTRUCTOR, as for list-init,
11681 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11682 the two. */
11683 if (DECL_CONSTRUCTOR_P (fn)
11684 && !(flags & LOOKUP_ONLYCONVERTING)
11685 && cxx_dialect >= cxx20
11686 && CP_AGGREGATE_TYPE_P (basetype)
11687 && !vec_safe_is_empty (user_args))
11688 {
11689 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11690 tree ctor = build_constructor_from_vec (init_list_type_node,
11691 user_args);
11692 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11693 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11694 if (is_dummy_object (instance))
11695 return ctor;
11696 else
11697 {
11698 ctor = digest_init (basetype, ctor, complain);
11699 if (ctor == error_mark_node)
11700 return error_mark_node;
11701 return cp_build_init_expr (instance, ctor);
11702 }
11703 }
11704 if (complain & tf_error)
11705 complain_about_no_candidates_for_method_call (instance, candidates,
11706 explicit_targs, basetype,
11707 optype, name,
11708 skip_first_for_error,
11709 user_args);
11710 call = error_mark_node;
11711 }
11712 else
11713 {
11714 cand = tourney (candidates, complain);
11715 if (cand == 0)
11716 {
11717 char *pretty_name;
11718 bool free_p;
11719 tree arglist;
11720
11721 if (complain & tf_error)
11722 {
11723 pretty_name = name_as_c_string (name, basetype, &free_p);
11724 arglist = build_tree_list_vec (user_args);
11725 if (skip_first_for_error)
11726 arglist = TREE_CHAIN (arglist);
11727 auto_diagnostic_group d;
11728 if (!any_strictly_viable (candidates))
11729 error ("no matching function for call to %<%s(%A)%>",
11730 pretty_name, arglist);
11731 else
11732 error ("call of overloaded %<%s(%A)%> is ambiguous",
11733 pretty_name, arglist);
11734 print_z_candidates (location_of (name), candidates);
11735 if (free_p)
11736 free (pretty_name);
11737 }
11738 call = error_mark_node;
11739 if (fn_p)
11740 *fn_p = error_mark_node;
11741 }
11742 else
11743 {
11744 fn = cand->fn;
11745 call = NULL_TREE;
11746
11747 if (!(flags & LOOKUP_NONVIRTUAL)
11748 && DECL_PURE_VIRTUAL_P (fn)
11749 && instance == current_class_ref
11750 && (complain & tf_warning))
11751 {
11752 /* This is not an error, it is runtime undefined
11753 behavior. */
11754 if (!current_function_decl)
11755 warning (0, "pure virtual %q#D called from "
11756 "non-static data member initializer", fn);
11757 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11758 || DECL_DESTRUCTOR_P (current_function_decl))
11759 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11760 ? G_("pure virtual %q#D called from constructor")
11761 : G_("pure virtual %q#D called from destructor")),
11762 fn);
11763 }
11764
11765 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11766 && !DECL_CONSTRUCTOR_P (fn)
11767 && is_dummy_object (instance))
11768 {
11769 instance = maybe_resolve_dummy (instance, true);
11770 if (instance == error_mark_node)
11771 call = error_mark_node;
11772 else if (!is_dummy_object (instance))
11773 {
11774 /* We captured 'this' in the current lambda now that
11775 we know we really need it. */
11776 cand->first_arg = instance;
11777 }
11778 else if (current_class_ptr && any_dependent_bases_p ())
11779 /* We can't tell until instantiation time whether we can use
11780 *this as the implicit object argument. */;
11781 else
11782 {
11783 if (complain & tf_error)
11784 error ("cannot call member function %qD without object",
11785 fn);
11786 call = error_mark_node;
11787 }
11788 }
11789
11790 if (call != error_mark_node)
11791 {
11792 /* Now we know what function is being called. */
11793 if (fn_p)
11794 *fn_p = fn;
11795 /* Build the actual CALL_EXPR. */
11796 call = build_over_call (cand, flags, complain);
11797
11798 /* Suppress warnings for if (my_struct.operator= (x)) where
11799 my_struct is implicitly converted to bool. */
11800 if (TREE_CODE (call) == MODIFY_EXPR)
11801 suppress_warning (call, OPT_Wparentheses);
11802
11803 /* In an expression of the form `a->f()' where `f' turns
11804 out to be a static member function, `a' is
11805 none-the-less evaluated. */
11806 if (!is_dummy_object (instance))
11807 call = keep_unused_object_arg (call, instance, fn);
11808 if (call != error_mark_node
11809 && DECL_DESTRUCTOR_P (cand->fn)
11810 && !VOID_TYPE_P (TREE_TYPE (call)))
11811 /* An explicit call of the form "x->~X()" has type
11812 "void". However, on platforms where destructors
11813 return "this" (i.e., those where
11814 targetm.cxx.cdtor_returns_this is true), such calls
11815 will appear to have a return value of pointer type
11816 to the low-level call machinery. We do not want to
11817 change the low-level machinery, since we want to be
11818 able to optimize "delete f()" on such platforms as
11819 "operator delete(~X(f()))" (rather than generating
11820 "t = f(), ~X(t), operator delete (t)"). */
11821 call = build_nop (void_type_node, call);
11822 }
11823 }
11824 }
11825
11826 if (processing_template_decl && call != error_mark_node)
11827 {
11828 bool cast_to_void = false;
11829
11830 if (TREE_CODE (call) == COMPOUND_EXPR)
11831 call = TREE_OPERAND (call, 1);
11832 else if (TREE_CODE (call) == NOP_EXPR)
11833 {
11834 cast_to_void = true;
11835 call = TREE_OPERAND (call, 0);
11836 }
11837 if (INDIRECT_REF_P (call))
11838 call = TREE_OPERAND (call, 0);
11839
11840 /* Prune all but the selected function from the original overload
11841 set so that we can avoid some duplicate work at instantiation time. */
11842 if (really_overloaded_fn (fns))
11843 {
11844 if (DECL_TEMPLATE_INFO (fn)
11845 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11846 {
11847 /* Use the selected template, not the specialization, so that
11848 this looks like an actual lookup result for sake of
11849 filter_memfn_lookup. */
11850
11851 if (OVL_SINGLE_P (fns))
11852 /* If the original overload set consists of a single function
11853 template, this isn't beneficial. */
11854 goto skip_prune;
11855
11856 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11857 if (template_only)
11858 fn = lookup_template_function (fn, explicit_targs);
11859 }
11860 orig_fns = copy_node (orig_fns);
11861 BASELINK_FUNCTIONS (orig_fns) = fn;
11862 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11863 }
11864
11865 skip_prune:
11866 call = (build_min_non_dep_call_vec
11867 (call,
11868 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11869 orig_instance, orig_fns, NULL_TREE),
11870 orig_args));
11871 SET_EXPR_LOCATION (call, input_location);
11872 call = convert_from_reference (call);
11873 if (cast_to_void)
11874 call = build_nop (void_type_node, call);
11875 }
11876
11877 if (orig_args != NULL)
11878 release_tree_vector (orig_args);
11879
11880 return call;
11881 }
11882
11883 /* Returns true iff standard conversion sequence ICS1 is a proper
11884 subsequence of ICS2. */
11885
11886 static bool
11887 is_subseq (conversion *ics1, conversion *ics2)
11888 {
11889 /* We can assume that a conversion of the same code
11890 between the same types indicates a subsequence since we only get
11891 here if the types we are converting from are the same. */
11892
11893 while (ics1->kind == ck_rvalue
11894 || ics1->kind == ck_lvalue)
11895 ics1 = next_conversion (ics1);
11896
11897 while (1)
11898 {
11899 while (ics2->kind == ck_rvalue
11900 || ics2->kind == ck_lvalue)
11901 ics2 = next_conversion (ics2);
11902
11903 if (ics2->kind == ck_user
11904 || !has_next (ics2->kind))
11905 /* At this point, ICS1 cannot be a proper subsequence of
11906 ICS2. We can get a USER_CONV when we are comparing the
11907 second standard conversion sequence of two user conversion
11908 sequences. */
11909 return false;
11910
11911 ics2 = next_conversion (ics2);
11912
11913 while (ics2->kind == ck_rvalue
11914 || ics2->kind == ck_lvalue)
11915 ics2 = next_conversion (ics2);
11916
11917 if (ics2->kind == ics1->kind
11918 && same_type_p (ics2->type, ics1->type)
11919 && (ics1->kind == ck_identity
11920 || same_type_p (next_conversion (ics2)->type,
11921 next_conversion (ics1)->type)))
11922 return true;
11923 }
11924 }
11925
11926 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11927 be any _TYPE nodes. */
11928
11929 bool
11930 is_properly_derived_from (tree derived, tree base)
11931 {
11932 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11933 return false;
11934
11935 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11936 considers every class derived from itself. */
11937 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11938 && DERIVED_FROM_P (base, derived));
11939 }
11940
11941 /* We build the ICS for an implicit object parameter as a pointer
11942 conversion sequence. However, such a sequence should be compared
11943 as if it were a reference conversion sequence. If ICS is the
11944 implicit conversion sequence for an implicit object parameter,
11945 modify it accordingly. */
11946
11947 static void
11948 maybe_handle_implicit_object (conversion **ics)
11949 {
11950 if ((*ics)->this_p)
11951 {
11952 /* [over.match.funcs]
11953
11954 For non-static member functions, the type of the
11955 implicit object parameter is "reference to cv X"
11956 where X is the class of which the function is a
11957 member and cv is the cv-qualification on the member
11958 function declaration. */
11959 conversion *t = *ics;
11960 tree reference_type;
11961
11962 /* The `this' parameter is a pointer to a class type. Make the
11963 implicit conversion talk about a reference to that same class
11964 type. */
11965 reference_type = TREE_TYPE (t->type);
11966 reference_type = build_reference_type (reference_type);
11967
11968 if (t->kind == ck_qual)
11969 t = next_conversion (t);
11970 if (t->kind == ck_ptr)
11971 t = next_conversion (t);
11972 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11973 t = direct_reference_binding (reference_type, t);
11974 t->this_p = 1;
11975 t->rvaluedness_matches_p = 0;
11976 *ics = t;
11977 }
11978 }
11979
11980 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11981 and return the initial reference binding conversion. Otherwise,
11982 leave *ICS unchanged and return NULL. */
11983
11984 static conversion *
11985 maybe_handle_ref_bind (conversion **ics)
11986 {
11987 if ((*ics)->kind == ck_ref_bind)
11988 {
11989 conversion *old_ics = *ics;
11990 *ics = next_conversion (old_ics);
11991 (*ics)->user_conv_p = old_ics->user_conv_p;
11992 return old_ics;
11993 }
11994
11995 return NULL;
11996 }
11997
11998 /* Get the expression at the beginning of the conversion chain C. */
11999
12000 static tree
12001 conv_get_original_expr (conversion *c)
12002 {
12003 for (; c; c = next_conversion (c))
12004 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
12005 return c->u.expr;
12006 return NULL_TREE;
12007 }
12008
12009 /* Return a tree representing the number of elements initialized by the
12010 list-initialization C. The caller must check that C converts to an
12011 array type. */
12012
12013 static tree
12014 nelts_initialized_by_list_init (conversion *c)
12015 {
12016 /* If the array we're converting to has a dimension, we'll use that. */
12017 if (TYPE_DOMAIN (c->type))
12018 return array_type_nelts_top (c->type);
12019 else
12020 {
12021 /* Otherwise, we look at how many elements the constructor we're
12022 initializing from has. */
12023 tree ctor = conv_get_original_expr (c);
12024 return size_int (CONSTRUCTOR_NELTS (ctor));
12025 }
12026 }
12027
12028 /* True iff C is a conversion that binds a reference or a pointer to
12029 an array of unknown bound. */
12030
12031 static inline bool
12032 conv_binds_to_array_of_unknown_bound (conversion *c)
12033 {
12034 /* ck_ref_bind won't have the reference stripped. */
12035 tree type = non_reference (c->type);
12036 /* ck_qual won't have the pointer stripped. */
12037 type = strip_pointer_operator (type);
12038 return (TREE_CODE (type) == ARRAY_TYPE
12039 && TYPE_DOMAIN (type) == NULL_TREE);
12040 }
12041
12042 /* Compare two implicit conversion sequences according to the rules set out in
12043 [over.ics.rank]. Return values:
12044
12045 1: ics1 is better than ics2
12046 -1: ics2 is better than ics1
12047 0: ics1 and ics2 are indistinguishable */
12048
12049 static int
12050 compare_ics (conversion *ics1, conversion *ics2)
12051 {
12052 tree from_type1;
12053 tree from_type2;
12054 tree to_type1;
12055 tree to_type2;
12056 tree deref_from_type1 = NULL_TREE;
12057 tree deref_from_type2 = NULL_TREE;
12058 tree deref_to_type1 = NULL_TREE;
12059 tree deref_to_type2 = NULL_TREE;
12060 conversion_rank rank1, rank2;
12061
12062 /* REF_BINDING is nonzero if the result of the conversion sequence
12063 is a reference type. In that case REF_CONV is the reference
12064 binding conversion. */
12065 conversion *ref_conv1;
12066 conversion *ref_conv2;
12067
12068 /* Compare badness before stripping the reference conversion. */
12069 if (ics1->bad_p > ics2->bad_p)
12070 return -1;
12071 else if (ics1->bad_p < ics2->bad_p)
12072 return 1;
12073
12074 /* Handle implicit object parameters. */
12075 maybe_handle_implicit_object (&ics1);
12076 maybe_handle_implicit_object (&ics2);
12077
12078 /* Handle reference parameters. */
12079 ref_conv1 = maybe_handle_ref_bind (&ics1);
12080 ref_conv2 = maybe_handle_ref_bind (&ics2);
12081
12082 /* List-initialization sequence L1 is a better conversion sequence than
12083 list-initialization sequence L2 if L1 converts to
12084 std::initializer_list<X> for some X and L2 does not. */
12085 if (ics1->kind == ck_list && ics2->kind != ck_list)
12086 return 1;
12087 if (ics2->kind == ck_list && ics1->kind != ck_list)
12088 return -1;
12089
12090 /* [over.ics.rank]
12091
12092 When comparing the basic forms of implicit conversion sequences (as
12093 defined in _over.best.ics_)
12094
12095 --a standard conversion sequence (_over.ics.scs_) is a better
12096 conversion sequence than a user-defined conversion sequence
12097 or an ellipsis conversion sequence, and
12098
12099 --a user-defined conversion sequence (_over.ics.user_) is a
12100 better conversion sequence than an ellipsis conversion sequence
12101 (_over.ics.ellipsis_). */
12102 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12103 mismatch. If both ICS are bad, we try to make a decision based on
12104 what would have happened if they'd been good. This is not an
12105 extension, we'll still give an error when we build up the call; this
12106 just helps us give a more helpful error message. */
12107 rank1 = BAD_CONVERSION_RANK (ics1);
12108 rank2 = BAD_CONVERSION_RANK (ics2);
12109
12110 if (rank1 > rank2)
12111 return -1;
12112 else if (rank1 < rank2)
12113 return 1;
12114
12115 if (ics1->ellipsis_p)
12116 /* Both conversions are ellipsis conversions. */
12117 return 0;
12118
12119 /* User-defined conversion sequence U1 is a better conversion sequence
12120 than another user-defined conversion sequence U2 if they contain the
12121 same user-defined conversion operator or constructor and if the sec-
12122 ond standard conversion sequence of U1 is better than the second
12123 standard conversion sequence of U2. */
12124
12125 /* Handle list-conversion with the same code even though it isn't always
12126 ranked as a user-defined conversion and it doesn't have a second
12127 standard conversion sequence; it will still have the desired effect.
12128 Specifically, we need to do the reference binding comparison at the
12129 end of this function. */
12130
12131 if (ics1->user_conv_p || ics1->kind == ck_list
12132 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12133 {
12134 conversion *t1 = strip_standard_conversion (ics1);
12135 conversion *t2 = strip_standard_conversion (ics2);
12136
12137 if (!t1 || !t2 || t1->kind != t2->kind)
12138 return 0;
12139 else if (t1->kind == ck_user)
12140 {
12141 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12142 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12143 if (f1 != f2)
12144 return 0;
12145 }
12146 /* List-initialization sequence L1 is a better conversion sequence than
12147 list-initialization sequence L2 if
12148
12149 -- L1 and L2 convert to arrays of the same element type, and either
12150 the number of elements n1 initialized by L1 is less than the number
12151 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12152 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12153 P0388R4.) */
12154 else if (t1->kind == ck_aggr
12155 && TREE_CODE (t1->type) == ARRAY_TYPE
12156 && TREE_CODE (t2->type) == ARRAY_TYPE
12157 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12158 {
12159 tree n1 = nelts_initialized_by_list_init (t1);
12160 tree n2 = nelts_initialized_by_list_init (t2);
12161 if (tree_int_cst_lt (n1, n2))
12162 return 1;
12163 else if (tree_int_cst_lt (n2, n1))
12164 return -1;
12165 /* The n1 == n2 case. */
12166 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
12167 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
12168 if (c1 && !c2)
12169 return -1;
12170 else if (!c1 && c2)
12171 return 1;
12172 else
12173 return 0;
12174 }
12175 else
12176 {
12177 /* For ambiguous or aggregate conversions, use the target type as
12178 a proxy for the conversion function. */
12179 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12180 return 0;
12181 }
12182
12183 /* We can just fall through here, after setting up
12184 FROM_TYPE1 and FROM_TYPE2. */
12185 from_type1 = t1->type;
12186 from_type2 = t2->type;
12187 }
12188 else
12189 {
12190 conversion *t1;
12191 conversion *t2;
12192
12193 /* We're dealing with two standard conversion sequences.
12194
12195 [over.ics.rank]
12196
12197 Standard conversion sequence S1 is a better conversion
12198 sequence than standard conversion sequence S2 if
12199
12200 --S1 is a proper subsequence of S2 (comparing the conversion
12201 sequences in the canonical form defined by _over.ics.scs_,
12202 excluding any Lvalue Transformation; the identity
12203 conversion sequence is considered to be a subsequence of
12204 any non-identity conversion sequence */
12205
12206 t1 = ics1;
12207 while (t1->kind != ck_identity)
12208 t1 = next_conversion (t1);
12209 from_type1 = t1->type;
12210
12211 t2 = ics2;
12212 while (t2->kind != ck_identity)
12213 t2 = next_conversion (t2);
12214 from_type2 = t2->type;
12215 }
12216
12217 /* One sequence can only be a subsequence of the other if they start with
12218 the same type. They can start with different types when comparing the
12219 second standard conversion sequence in two user-defined conversion
12220 sequences. */
12221 if (same_type_p (from_type1, from_type2))
12222 {
12223 if (is_subseq (ics1, ics2))
12224 return 1;
12225 if (is_subseq (ics2, ics1))
12226 return -1;
12227 }
12228
12229 /* [over.ics.rank]
12230
12231 Or, if not that,
12232
12233 --the rank of S1 is better than the rank of S2 (by the rules
12234 defined below):
12235
12236 Standard conversion sequences are ordered by their ranks: an Exact
12237 Match is a better conversion than a Promotion, which is a better
12238 conversion than a Conversion.
12239
12240 Two conversion sequences with the same rank are indistinguishable
12241 unless one of the following rules applies:
12242
12243 --A conversion that does not a convert a pointer, pointer to member,
12244 or std::nullptr_t to bool is better than one that does.
12245
12246 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12247 so that we do not have to check it explicitly. */
12248 if (ics1->rank < ics2->rank)
12249 return 1;
12250 else if (ics2->rank < ics1->rank)
12251 return -1;
12252
12253 to_type1 = ics1->type;
12254 to_type2 = ics2->type;
12255
12256 /* A conversion from scalar arithmetic type to complex is worse than a
12257 conversion between scalar arithmetic types. */
12258 if (same_type_p (from_type1, from_type2)
12259 && ARITHMETIC_TYPE_P (from_type1)
12260 && ARITHMETIC_TYPE_P (to_type1)
12261 && ARITHMETIC_TYPE_P (to_type2)
12262 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12263 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12264 {
12265 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12266 return -1;
12267 else
12268 return 1;
12269 }
12270
12271 {
12272 /* A conversion in either direction between floating-point type FP1 and
12273 floating-point type FP2 is better than a conversion in the same
12274 direction between FP1 and arithmetic type T3 if
12275 - the floating-point conversion rank of FP1 is equal to the rank of
12276 FP2, and
12277 - T3 is not a floating-point type, or T3 is a floating-point type
12278 whose rank is not equal to the rank of FP1, or the floating-point
12279 conversion subrank of FP2 is greater than the subrank of T3. */
12280 tree fp1 = from_type1;
12281 tree fp2 = to_type1;
12282 tree fp3 = from_type2;
12283 tree t3 = to_type2;
12284 int ret = 1;
12285 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12286 {
12287 std::swap (fp1, fp2);
12288 std::swap (fp3, t3);
12289 }
12290 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12291 && SCALAR_FLOAT_TYPE_P (fp1)
12292 /* Only apply this rule if at least one of the 3 types is
12293 extended floating-point type, otherwise keep them as
12294 before for compatibility reasons with types like __float128.
12295 float, double and long double alone have different conversion
12296 ranks and so when just those 3 types are involved, this
12297 rule doesn't trigger. */
12298 && (extended_float_type_p (fp1)
12299 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (fp2))
12300 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (t3))))
12301 {
12302 if (TREE_CODE (fp2) != REAL_TYPE)
12303 {
12304 ret = -ret;
12305 std::swap (fp2, t3);
12306 }
12307 if (SCALAR_FLOAT_TYPE_P (fp2))
12308 {
12309 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12310 if the conversion rank is equal (-1 or 1 if the subrank is
12311 different). */
12312 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12313 fp2),
12314 -1, 1))
12315 {
12316 /* Conversion ranks of FP1 and FP2 are equal. */
12317 if (TREE_CODE (t3) != REAL_TYPE
12318 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12319 (fp1, t3),
12320 -1, 1))
12321 /* FP1 <-> FP2 conversion is better. */
12322 return ret;
12323 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12324 gcc_assert (IN_RANGE (c, -1, 1));
12325 if (c == 1)
12326 /* Conversion subrank of FP2 is greater than subrank of T3.
12327 FP1 <-> FP2 conversion is better. */
12328 return ret;
12329 else if (c == -1)
12330 /* Conversion subrank of FP2 is less than subrank of T3.
12331 FP1 <-> T3 conversion is better. */
12332 return -ret;
12333 }
12334 else if (SCALAR_FLOAT_TYPE_P (t3)
12335 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12336 (fp1, t3),
12337 -1, 1))
12338 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12339 ranks of FP1 and T3 are equal.
12340 FP1 <-> T3 conversion is better. */
12341 return -ret;
12342 }
12343 }
12344 }
12345
12346 if (TYPE_PTR_P (from_type1)
12347 && TYPE_PTR_P (from_type2)
12348 && TYPE_PTR_P (to_type1)
12349 && TYPE_PTR_P (to_type2))
12350 {
12351 deref_from_type1 = TREE_TYPE (from_type1);
12352 deref_from_type2 = TREE_TYPE (from_type2);
12353 deref_to_type1 = TREE_TYPE (to_type1);
12354 deref_to_type2 = TREE_TYPE (to_type2);
12355 }
12356 /* The rules for pointers to members A::* are just like the rules
12357 for pointers A*, except opposite: if B is derived from A then
12358 A::* converts to B::*, not vice versa. For that reason, we
12359 switch the from_ and to_ variables here. */
12360 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12361 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12362 || (TYPE_PTRMEMFUNC_P (from_type1)
12363 && TYPE_PTRMEMFUNC_P (from_type2)
12364 && TYPE_PTRMEMFUNC_P (to_type1)
12365 && TYPE_PTRMEMFUNC_P (to_type2)))
12366 {
12367 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12368 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12369 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12370 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12371 }
12372
12373 if (deref_from_type1 != NULL_TREE
12374 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12375 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12376 {
12377 /* This was one of the pointer or pointer-like conversions.
12378
12379 [over.ics.rank]
12380
12381 --If class B is derived directly or indirectly from class A,
12382 conversion of B* to A* is better than conversion of B* to
12383 void*, and conversion of A* to void* is better than
12384 conversion of B* to void*. */
12385 if (VOID_TYPE_P (deref_to_type1)
12386 && VOID_TYPE_P (deref_to_type2))
12387 {
12388 if (is_properly_derived_from (deref_from_type1,
12389 deref_from_type2))
12390 return -1;
12391 else if (is_properly_derived_from (deref_from_type2,
12392 deref_from_type1))
12393 return 1;
12394 }
12395 else if (VOID_TYPE_P (deref_to_type1)
12396 || VOID_TYPE_P (deref_to_type2))
12397 {
12398 if (same_type_p (deref_from_type1, deref_from_type2))
12399 {
12400 if (VOID_TYPE_P (deref_to_type2))
12401 {
12402 if (is_properly_derived_from (deref_from_type1,
12403 deref_to_type1))
12404 return 1;
12405 }
12406 /* We know that DEREF_TO_TYPE1 is `void' here. */
12407 else if (is_properly_derived_from (deref_from_type1,
12408 deref_to_type2))
12409 return -1;
12410 }
12411 }
12412 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12413 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12414 {
12415 /* [over.ics.rank]
12416
12417 --If class B is derived directly or indirectly from class A
12418 and class C is derived directly or indirectly from B,
12419
12420 --conversion of C* to B* is better than conversion of C* to
12421 A*,
12422
12423 --conversion of B* to A* is better than conversion of C* to
12424 A* */
12425 if (same_type_p (deref_from_type1, deref_from_type2))
12426 {
12427 if (is_properly_derived_from (deref_to_type1,
12428 deref_to_type2))
12429 return 1;
12430 else if (is_properly_derived_from (deref_to_type2,
12431 deref_to_type1))
12432 return -1;
12433 }
12434 else if (same_type_p (deref_to_type1, deref_to_type2))
12435 {
12436 if (is_properly_derived_from (deref_from_type2,
12437 deref_from_type1))
12438 return 1;
12439 else if (is_properly_derived_from (deref_from_type1,
12440 deref_from_type2))
12441 return -1;
12442 }
12443 }
12444 }
12445 else if (CLASS_TYPE_P (non_reference (from_type1))
12446 && same_type_p (from_type1, from_type2))
12447 {
12448 tree from = non_reference (from_type1);
12449
12450 /* [over.ics.rank]
12451
12452 --binding of an expression of type C to a reference of type
12453 B& is better than binding an expression of type C to a
12454 reference of type A&
12455
12456 --conversion of C to B is better than conversion of C to A, */
12457 if (is_properly_derived_from (from, to_type1)
12458 && is_properly_derived_from (from, to_type2))
12459 {
12460 if (is_properly_derived_from (to_type1, to_type2))
12461 return 1;
12462 else if (is_properly_derived_from (to_type2, to_type1))
12463 return -1;
12464 }
12465 }
12466 else if (CLASS_TYPE_P (non_reference (to_type1))
12467 && same_type_p (to_type1, to_type2))
12468 {
12469 tree to = non_reference (to_type1);
12470
12471 /* [over.ics.rank]
12472
12473 --binding of an expression of type B to a reference of type
12474 A& is better than binding an expression of type C to a
12475 reference of type A&,
12476
12477 --conversion of B to A is better than conversion of C to A */
12478 if (is_properly_derived_from (from_type1, to)
12479 && is_properly_derived_from (from_type2, to))
12480 {
12481 if (is_properly_derived_from (from_type2, from_type1))
12482 return 1;
12483 else if (is_properly_derived_from (from_type1, from_type2))
12484 return -1;
12485 }
12486 }
12487
12488 /* [over.ics.rank]
12489
12490 --S1 and S2 differ only in their qualification conversion and yield
12491 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12492 qualification signature of type T1 is a proper subset of the cv-
12493 qualification signature of type T2 */
12494 if (ics1->kind == ck_qual
12495 && ics2->kind == ck_qual
12496 && same_type_p (from_type1, from_type2))
12497 {
12498 int result = comp_cv_qual_signature (to_type1, to_type2);
12499 if (result != 0)
12500 return result;
12501 }
12502
12503 /* [over.ics.rank]
12504
12505 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12506 to an implicit object parameter of a non-static member function
12507 declared without a ref-qualifier, and either S1 binds an lvalue
12508 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12509 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12510 draft standard, 13.3.3.2)
12511
12512 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12513 types to which the references refer are the same type except for
12514 top-level cv-qualifiers, and the type to which the reference
12515 initialized by S2 refers is more cv-qualified than the type to
12516 which the reference initialized by S1 refers.
12517
12518 DR 1328 [over.match.best]: the context is an initialization by
12519 conversion function for direct reference binding (13.3.1.6) of a
12520 reference to function type, the return type of F1 is the same kind of
12521 reference (i.e. lvalue or rvalue) as the reference being initialized,
12522 and the return type of F2 is not. */
12523
12524 if (ref_conv1 && ref_conv2)
12525 {
12526 if (!ref_conv1->this_p && !ref_conv2->this_p
12527 && (ref_conv1->rvaluedness_matches_p
12528 != ref_conv2->rvaluedness_matches_p)
12529 && (same_type_p (ref_conv1->type, ref_conv2->type)
12530 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12531 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12532 {
12533 if (ref_conv1->bad_p
12534 && !same_type_p (TREE_TYPE (ref_conv1->type),
12535 TREE_TYPE (ref_conv2->type)))
12536 /* Don't prefer a bad conversion that drops cv-quals to a bad
12537 conversion with the wrong rvalueness. */
12538 return 0;
12539 return (ref_conv1->rvaluedness_matches_p
12540 - ref_conv2->rvaluedness_matches_p);
12541 }
12542
12543 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12544 {
12545 /* Per P0388R4:
12546
12547 void f (int(&)[]), // (1)
12548 f (int(&)[1]), // (2)
12549 f (int*); // (3)
12550
12551 (2) is better than (1), but (3) should be equal to (1) and to
12552 (2). For that reason we don't use ck_qual for (1) which would
12553 give it the cr_exact rank while (3) remains ck_identity.
12554 Therefore we compare (1) and (2) here. For (1) we'll have
12555
12556 ck_ref_bind <- ck_identity
12557 int[] & int[1]
12558
12559 so to handle this we must look at ref_conv. */
12560 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12561 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12562 if (c1 && !c2)
12563 return -1;
12564 else if (!c1 && c2)
12565 return 1;
12566
12567 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12568 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12569 if (ref_conv1->bad_p)
12570 {
12571 /* Prefer the one that drops fewer cv-quals. */
12572 tree ftype = next_conversion (ref_conv1)->type;
12573 int fquals = cp_type_quals (ftype);
12574 q1 ^= fquals;
12575 q2 ^= fquals;
12576 }
12577 return comp_cv_qualification (q2, q1);
12578 }
12579 }
12580
12581 /* [over.ics.rank]
12582
12583 Per CWG 1601:
12584 -- A conversion that promotes an enumeration whose underlying type
12585 is fixed to its underlying type is better than one that promotes to
12586 the promoted underlying type, if the two are different. */
12587 if (ics1->rank == cr_promotion
12588 && ics2->rank == cr_promotion
12589 && UNSCOPED_ENUM_P (from_type1)
12590 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12591 && same_type_p (from_type1, from_type2))
12592 {
12593 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12594 tree prom = type_promotes_to (from_type1);
12595 if (!same_type_p (utype, prom))
12596 {
12597 if (same_type_p (to_type1, utype)
12598 && same_type_p (to_type2, prom))
12599 return 1;
12600 else if (same_type_p (to_type2, utype)
12601 && same_type_p (to_type1, prom))
12602 return -1;
12603 }
12604 }
12605
12606 /* Neither conversion sequence is better than the other. */
12607 return 0;
12608 }
12609
12610 /* The source type for this standard conversion sequence. */
12611
12612 static tree
12613 source_type (conversion *t)
12614 {
12615 return strip_standard_conversion (t)->type;
12616 }
12617
12618 /* Note a warning about preferring WINNER to LOSER. We do this by storing
12619 a pointer to LOSER and re-running joust to produce the warning if WINNER
12620 is actually used. */
12621
12622 static void
12623 add_warning (struct z_candidate *winner, struct z_candidate *loser)
12624 {
12625 candidate_warning *cw = (candidate_warning *)
12626 conversion_obstack_alloc (sizeof (candidate_warning));
12627 cw->loser = loser;
12628 cw->next = winner->warnings;
12629 winner->warnings = cw;
12630 }
12631
12632 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12633 prvalue returned from a conversion function, return true. Otherwise, return
12634 false. */
12635
12636 static bool
12637 joust_maybe_elide_copy (z_candidate *cand)
12638 {
12639 tree fn = cand->fn;
12640 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12641 return false;
12642 conversion *conv = cand->convs[0];
12643 if (conv->kind == ck_ambig)
12644 return false;
12645 gcc_checking_assert (conv->kind == ck_ref_bind);
12646 conv = next_conversion (conv);
12647 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12648 {
12649 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12650 (conv->type, DECL_CONTEXT (fn)));
12651 z_candidate *uc = conv->cand;
12652 if (DECL_CONV_FN_P (uc->fn))
12653 return true;
12654 }
12655 return false;
12656 }
12657
12658 /* True if the defining declarations of the two candidates have equivalent
12659 parameters. */
12660
12661 static bool
12662 cand_parms_match (z_candidate *c1, z_candidate *c2)
12663 {
12664 tree fn1 = c1->fn;
12665 tree fn2 = c2->fn;
12666 if (fn1 == fn2)
12667 return true;
12668 if (identifier_p (fn1) || identifier_p (fn2))
12669 return false;
12670 /* We don't look at c1->template_decl because that's only set for primary
12671 templates, not e.g. non-template member functions of class templates. */
12672 tree t1 = most_general_template (fn1);
12673 tree t2 = most_general_template (fn2);
12674 if (t1 || t2)
12675 {
12676 if (!t1 || !t2)
12677 return false;
12678 if (t1 == t2)
12679 return true;
12680 fn1 = DECL_TEMPLATE_RESULT (t1);
12681 fn2 = DECL_TEMPLATE_RESULT (t2);
12682 }
12683 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12684 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12685 if (DECL_FUNCTION_MEMBER_P (fn1)
12686 && DECL_FUNCTION_MEMBER_P (fn2)
12687 && (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn1)
12688 != DECL_NONSTATIC_MEMBER_FUNCTION_P (fn2)))
12689 {
12690 /* Ignore 'this' when comparing the parameters of a static member
12691 function with those of a non-static one. */
12692 parms1 = skip_artificial_parms_for (fn1, parms1);
12693 parms2 = skip_artificial_parms_for (fn2, parms2);
12694 }
12695 return compparms (parms1, parms2);
12696 }
12697
12698 /* True iff FN is a copy or move constructor or assignment operator. */
12699
12700 static bool
12701 sfk_copy_or_move (tree fn)
12702 {
12703 if (TREE_CODE (fn) != FUNCTION_DECL)
12704 return false;
12705 special_function_kind sfk = special_function_p (fn);
12706 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
12707 }
12708
12709 /* Compare two candidates for overloading as described in
12710 [over.match.best]. Return values:
12711
12712 1: cand1 is better than cand2
12713 -1: cand2 is better than cand1
12714 0: cand1 and cand2 are indistinguishable */
12715
12716 static int
12717 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12718 tsubst_flags_t complain)
12719 {
12720 int winner = 0;
12721 int off1 = 0, off2 = 0;
12722 size_t i;
12723 size_t len;
12724
12725 /* Candidates that involve bad conversions are always worse than those
12726 that don't. */
12727 if (cand1->viable > cand2->viable)
12728 return 1;
12729 if (cand1->viable < cand2->viable)
12730 return -1;
12731
12732 /* If we have two pseudo-candidates for conversions to the same type,
12733 or two candidates for the same function, arbitrarily pick one. */
12734 if (cand1->fn == cand2->fn
12735 && cand1->reversed () == cand2->reversed ()
12736 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12737 return 1;
12738
12739 /* Prefer a non-deleted function over an implicitly deleted move
12740 constructor or assignment operator. This differs slightly from the
12741 wording for issue 1402 (which says the move op is ignored by overload
12742 resolution), but this way produces better error messages. */
12743 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12744 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12745 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12746 {
12747 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12748 && move_fn_p (cand1->fn))
12749 return -1;
12750 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12751 && move_fn_p (cand2->fn))
12752 return 1;
12753 }
12754
12755 /* a viable function F1
12756 is defined to be a better function than another viable function F2 if
12757 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12758 ICSi(F2), and then */
12759
12760 /* for some argument j, ICSj(F1) is a better conversion sequence than
12761 ICSj(F2) */
12762
12763 /* For comparing static and non-static member functions, we ignore
12764 the implicit object parameter of the non-static function. The
12765 standard says to pretend that the static function has an object
12766 parm, but that won't work with operator overloading. */
12767 len = cand1->num_convs;
12768 if (len != cand2->num_convs)
12769 {
12770 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12771 && DECL_STATIC_FUNCTION_P (cand1->fn));
12772 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12773 && DECL_STATIC_FUNCTION_P (cand2->fn));
12774
12775 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12776 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12777 && DECL_CONSTRUCTOR_P (cand1->fn)
12778 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12779 /* We're comparing a near-match list constructor and a near-match
12780 non-list constructor. Just treat them as unordered. */
12781 return 0;
12782
12783 gcc_assert (static_1 != static_2);
12784
12785 if (static_1)
12786 {
12787 /* C++23 [over.best.ics.general] says:
12788 When the parameter is the implicit object parameter of a static
12789 member function, the implicit conversion sequence is a standard
12790 conversion sequence that is neither better nor worse than any
12791 other standard conversion sequence. */
12792 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12793 winner = 1;
12794 off2 = 1;
12795 }
12796 else
12797 {
12798 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12799 winner = -1;
12800 off1 = 1;
12801 --len;
12802 }
12803 }
12804
12805 for (i = 0; i < len; ++i)
12806 {
12807 conversion *t1 = cand1->convs[i + off1];
12808 conversion *t2 = cand2->convs[i + off2];
12809 int comp = compare_ics (t1, t2);
12810
12811 if (comp != 0)
12812 {
12813 if ((complain & tf_warning)
12814 && warn_sign_promo
12815 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12816 == cr_std + cr_promotion)
12817 && t1->kind == ck_std
12818 && t2->kind == ck_std
12819 && TREE_CODE (t1->type) == INTEGER_TYPE
12820 && TREE_CODE (t2->type) == INTEGER_TYPE
12821 && (TYPE_PRECISION (t1->type)
12822 == TYPE_PRECISION (t2->type))
12823 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12824 || (TREE_CODE (next_conversion (t1)->type)
12825 == ENUMERAL_TYPE)))
12826 {
12827 tree type = next_conversion (t1)->type;
12828 tree type1, type2;
12829 struct z_candidate *w, *l;
12830 if (comp > 0)
12831 type1 = t1->type, type2 = t2->type,
12832 w = cand1, l = cand2;
12833 else
12834 type1 = t2->type, type2 = t1->type,
12835 w = cand2, l = cand1;
12836
12837 if (warn)
12838 {
12839 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12840 type, type1, type2);
12841 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12842 }
12843 else
12844 add_warning (w, l);
12845 }
12846
12847 if (winner && comp != winner)
12848 {
12849 /* Ambiguity between normal and reversed comparison operators
12850 with the same parameter types. P2468 decided not to go with
12851 this approach to resolving the ambiguity, so pedwarn. */
12852 if ((complain & tf_warning_or_error)
12853 && (cand1->reversed () != cand2->reversed ())
12854 && cand_parms_match (cand1, cand2))
12855 {
12856 struct z_candidate *w, *l;
12857 if (cand2->reversed ())
12858 winner = 1, w = cand1, l = cand2;
12859 else
12860 winner = -1, w = cand2, l = cand1;
12861 if (warn)
12862 {
12863 auto_diagnostic_group d;
12864 if (pedwarn (input_location, 0,
12865 "C++20 says that these are ambiguous, "
12866 "even though the second is reversed:"))
12867 {
12868 print_z_candidate (input_location,
12869 N_("candidate 1:"), w);
12870 print_z_candidate (input_location,
12871 N_("candidate 2:"), l);
12872 if (w->fn == l->fn
12873 && DECL_NONSTATIC_MEMBER_FUNCTION_P (w->fn)
12874 && (type_memfn_quals (TREE_TYPE (w->fn))
12875 & TYPE_QUAL_CONST) == 0)
12876 {
12877 /* Suggest adding const to
12878 struct A { bool operator==(const A&); }; */
12879 tree parmtype
12880 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
12881 parmtype = TREE_VALUE (parmtype);
12882 if (TYPE_REF_P (parmtype)
12883 && TYPE_READONLY (TREE_TYPE (parmtype))
12884 && (same_type_ignoring_top_level_qualifiers_p
12885 (TREE_TYPE (parmtype),
12886 DECL_CONTEXT (w->fn))))
12887 inform (DECL_SOURCE_LOCATION (w->fn),
12888 "try making the operator a %<const%> "
12889 "member function");
12890 }
12891 }
12892 }
12893 else
12894 add_warning (w, l);
12895 return winner;
12896 }
12897
12898 winner = 0;
12899 goto tweak;
12900 }
12901 winner = comp;
12902 }
12903 }
12904
12905 /* warn about confusing overload resolution for user-defined conversions,
12906 either between a constructor and a conversion op, or between two
12907 conversion ops. */
12908 if ((complain & tf_warning)
12909 /* In C++17, the constructor might have been elided, which means that
12910 an originally null ->second_conv could become non-null. */
12911 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12912 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12913 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
12914 {
12915 struct z_candidate *w, *l;
12916 bool give_warning = false;
12917
12918 if (winner == 1)
12919 w = cand1, l = cand2;
12920 else
12921 w = cand2, l = cand1;
12922
12923 /* We don't want to complain about `X::operator T1 ()'
12924 beating `X::operator T2 () const', when T2 is a no less
12925 cv-qualified version of T1. */
12926 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12927 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12928 {
12929 tree t = TREE_TYPE (TREE_TYPE (l->fn));
12930 tree f = TREE_TYPE (TREE_TYPE (w->fn));
12931
12932 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12933 {
12934 t = TREE_TYPE (t);
12935 f = TREE_TYPE (f);
12936 }
12937 if (!comp_ptr_ttypes (t, f))
12938 give_warning = true;
12939 }
12940 else
12941 give_warning = true;
12942
12943 if (!give_warning)
12944 /*NOP*/;
12945 else if (warn)
12946 {
12947 tree source = source_type (w->convs[0]);
12948 if (INDIRECT_TYPE_P (source))
12949 source = TREE_TYPE (source);
12950 auto_diagnostic_group d;
12951 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12952 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
12953 source, w->second_conv->type))
12954 {
12955 inform (input_location, " because conversion sequence "
12956 "for the argument is better");
12957 }
12958 }
12959 else
12960 add_warning (w, l);
12961 }
12962
12963 if (winner)
12964 return winner;
12965
12966 /* DR 495 moved this tiebreaker above the template ones. */
12967 /* or, if not that,
12968 the context is an initialization by user-defined conversion (see
12969 _dcl.init_ and _over.match.user_) and the standard conversion
12970 sequence from the return type of F1 to the destination type (i.e.,
12971 the type of the entity being initialized) is a better conversion
12972 sequence than the standard conversion sequence from the return type
12973 of F2 to the destination type. */
12974
12975 if (cand1->second_conv)
12976 {
12977 winner = compare_ics (cand1->second_conv, cand2->second_conv);
12978 if (winner)
12979 return winner;
12980 }
12981
12982 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
12983 explicit conversion (due to list-initialization) is worse. */
12984 {
12985 z_candidate *sp = nullptr;
12986 if (sfk_copy_or_move (cand1->fn))
12987 sp = cand1;
12988 if (sfk_copy_or_move (cand2->fn))
12989 sp = sp ? nullptr : cand2;
12990 if (sp)
12991 {
12992 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
12993 if (conv->user_conv_p)
12994 for (; conv; conv = next_conversion (conv))
12995 if (conv->kind == ck_user
12996 && DECL_P (conv->cand->fn)
12997 && DECL_NONCONVERTING_P (conv->cand->fn))
12998 return (sp == cand1) ? -1 : 1;
12999 }
13000 }
13001
13002 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
13003 The standard currently says that only constructors are candidates, but if
13004 one copies a prvalue returned by a conversion function we prefer that.
13005
13006 Clang does something similar, as discussed at
13007 http://lists.isocpp.org/core/2017/10/3166.php
13008 http://lists.isocpp.org/core/2019/03/5721.php */
13009 if (len == 1 && cxx_dialect >= cxx17
13010 && DECL_P (cand1->fn)
13011 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
13012 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
13013 {
13014 bool elided1 = joust_maybe_elide_copy (cand1);
13015 bool elided2 = joust_maybe_elide_copy (cand2);
13016 winner = elided1 - elided2;
13017 if (winner)
13018 return winner;
13019 }
13020
13021 /* or, if not that,
13022 F1 is a non-template function and F2 is a template function
13023 specialization. */
13024
13025 if (!cand1->template_decl && cand2->template_decl)
13026 return 1;
13027 else if (cand1->template_decl && !cand2->template_decl)
13028 return -1;
13029
13030 /* or, if not that,
13031 F1 and F2 are template functions and the function template for F1 is
13032 more specialized than the template for F2 according to the partial
13033 ordering rules. */
13034
13035 if (cand1->template_decl && cand2->template_decl)
13036 {
13037 winner = more_specialized_fn
13038 (TI_TEMPLATE (cand1->template_decl),
13039 TI_TEMPLATE (cand2->template_decl),
13040 /* [temp.func.order]: The presence of unused ellipsis and default
13041 arguments has no effect on the partial ordering of function
13042 templates. add_function_candidate() will not have
13043 counted the "this" argument for constructors. */
13044 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
13045 if (winner)
13046 return winner;
13047 }
13048
13049 /* Concepts: F1 and F2 are non-template functions with the same
13050 parameter-type-lists, and F1 is more constrained than F2 according to the
13051 partial ordering of constraints described in 13.5.4. */
13052
13053 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
13054 && !cand1->template_decl && !cand2->template_decl
13055 && cand_parms_match (cand1, cand2))
13056 {
13057 winner = more_constrained (cand1->fn, cand2->fn);
13058 if (winner)
13059 return winner;
13060 }
13061
13062 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
13063 rewritten candidates, and F2 is a synthesized candidate with reversed
13064 order of parameters and F1 is not. */
13065 if (cand1->rewritten ())
13066 {
13067 if (!cand2->rewritten ())
13068 return -1;
13069 if (!cand1->reversed () && cand2->reversed ())
13070 return 1;
13071 if (cand1->reversed () && !cand2->reversed ())
13072 return -1;
13073 }
13074 else if (cand2->rewritten ())
13075 return 1;
13076
13077 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
13078 if (deduction_guide_p (cand1->fn))
13079 {
13080 gcc_assert (deduction_guide_p (cand2->fn));
13081 /* We distinguish between candidates from an explicit deduction guide and
13082 candidates built from a constructor based on DECL_ARTIFICIAL. */
13083 int art1 = DECL_ARTIFICIAL (cand1->fn);
13084 int art2 = DECL_ARTIFICIAL (cand2->fn);
13085 if (art1 != art2)
13086 return art2 - art1;
13087
13088 if (art1)
13089 {
13090 /* Prefer the special copy guide over a declared copy/move
13091 constructor. */
13092 if (copy_guide_p (cand1->fn))
13093 return 1;
13094 if (copy_guide_p (cand2->fn))
13095 return -1;
13096
13097 /* Prefer a candidate generated from a non-template constructor. */
13098 int tg1 = template_guide_p (cand1->fn);
13099 int tg2 = template_guide_p (cand2->fn);
13100 if (tg1 != tg2)
13101 return tg2 - tg1;
13102 }
13103 }
13104
13105 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
13106 for all arguments the corresponding parameters of F1 and F2 have the same
13107 type (CWG 2273/2277). */
13108 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
13109 && !DECL_CONV_FN_P (cand1->fn)
13110 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
13111 && !DECL_CONV_FN_P (cand2->fn))
13112 {
13113 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13114 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13115
13116 bool used1 = false;
13117 bool used2 = false;
13118 if (base1 == base2)
13119 /* No difference. */;
13120 else if (DERIVED_FROM_P (base1, base2))
13121 used1 = true;
13122 else if (DERIVED_FROM_P (base2, base1))
13123 used2 = true;
13124
13125 if (int diff = used2 - used1)
13126 {
13127 for (i = 0; i < len; ++i)
13128 {
13129 conversion *t1 = cand1->convs[i + off1];
13130 conversion *t2 = cand2->convs[i + off2];
13131 if (!same_type_p (t1->type, t2->type))
13132 break;
13133 }
13134 if (i == len)
13135 return diff;
13136 }
13137 }
13138
13139 /* Check whether we can discard a builtin candidate, either because we
13140 have two identical ones or matching builtin and non-builtin candidates.
13141
13142 (Pedantically in the latter case the builtin which matched the user
13143 function should not be added to the overload set, but we spot it here.
13144
13145 [over.match.oper]
13146 ... the builtin candidates include ...
13147 - do not have the same parameter type list as any non-template
13148 non-member candidate. */
13149
13150 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
13151 {
13152 for (i = 0; i < len; ++i)
13153 if (!same_type_p (cand1->convs[i]->type,
13154 cand2->convs[i]->type))
13155 break;
13156 if (i == cand1->num_convs)
13157 {
13158 if (cand1->fn == cand2->fn)
13159 /* Two built-in candidates; arbitrarily pick one. */
13160 return 1;
13161 else if (identifier_p (cand1->fn))
13162 /* cand1 is built-in; prefer cand2. */
13163 return -1;
13164 else
13165 /* cand2 is built-in; prefer cand1. */
13166 return 1;
13167 }
13168 }
13169
13170 /* For candidates of a multi-versioned function, make the version with
13171 the highest priority win. This version will be checked for dispatching
13172 first. If this version can be inlined into the caller, the front-end
13173 will simply make a direct call to this function. */
13174
13175 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13176 && DECL_FUNCTION_VERSIONED (cand1->fn)
13177 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13178 && DECL_FUNCTION_VERSIONED (cand2->fn))
13179 {
13180 tree f1 = TREE_TYPE (cand1->fn);
13181 tree f2 = TREE_TYPE (cand2->fn);
13182 tree p1 = TYPE_ARG_TYPES (f1);
13183 tree p2 = TYPE_ARG_TYPES (f2);
13184
13185 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13186 is possible that cand1->fn and cand2->fn are function versions but of
13187 different functions. Check types to see if they are versions of the same
13188 function. */
13189 if (compparms (p1, p2)
13190 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13191 {
13192 /* Always make the version with the higher priority, more
13193 specialized, win. */
13194 gcc_assert (targetm.compare_version_priority);
13195 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13196 return 1;
13197 else
13198 return -1;
13199 }
13200 }
13201
13202 /* If the two function declarations represent the same function (this can
13203 happen with declarations in multiple scopes and arg-dependent lookup),
13204 arbitrarily choose one. But first make sure the default args we're
13205 using match. */
13206 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13207 && equal_functions (cand1->fn, cand2->fn))
13208 {
13209 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13210 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13211
13212 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13213
13214 for (i = 0; i < len; ++i)
13215 {
13216 /* Don't crash if the fn is variadic. */
13217 if (!parms1)
13218 break;
13219 parms1 = TREE_CHAIN (parms1);
13220 parms2 = TREE_CHAIN (parms2);
13221 }
13222
13223 if (off1)
13224 parms1 = TREE_CHAIN (parms1);
13225 else if (off2)
13226 parms2 = TREE_CHAIN (parms2);
13227
13228 for (; parms1; ++i)
13229 {
13230 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13231 TREE_PURPOSE (parms2)))
13232 {
13233 if (warn)
13234 {
13235 if (complain & tf_error)
13236 {
13237 auto_diagnostic_group d;
13238 if (permerror (input_location,
13239 "default argument mismatch in "
13240 "overload resolution"))
13241 {
13242 inform (DECL_SOURCE_LOCATION (cand1->fn),
13243 " candidate 1: %q#F", cand1->fn);
13244 inform (DECL_SOURCE_LOCATION (cand2->fn),
13245 " candidate 2: %q#F", cand2->fn);
13246 }
13247 }
13248 else
13249 return 0;
13250 }
13251 else
13252 add_warning (cand1, cand2);
13253 break;
13254 }
13255 parms1 = TREE_CHAIN (parms1);
13256 parms2 = TREE_CHAIN (parms2);
13257 }
13258
13259 return 1;
13260 }
13261
13262 tweak:
13263
13264 /* Extension: If the worst conversion for one candidate is better than the
13265 worst conversion for the other, take the first. */
13266 if (!pedantic && (complain & tf_warning_or_error))
13267 {
13268 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13269 struct z_candidate *w = 0, *l = 0;
13270
13271 for (i = 0; i < len; ++i)
13272 {
13273 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13274 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13275 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13276 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13277 }
13278 if (rank1 < rank2)
13279 winner = 1, w = cand1, l = cand2;
13280 if (rank1 > rank2)
13281 winner = -1, w = cand2, l = cand1;
13282 if (winner)
13283 {
13284 /* Don't choose a deleted function over ambiguity. */
13285 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13286 return 0;
13287 if (warn)
13288 {
13289 auto_diagnostic_group d;
13290 if (pedwarn (input_location, 0,
13291 "ISO C++ says that these are ambiguous, even "
13292 "though the worst conversion for the first is "
13293 "better than the worst conversion for the second:"))
13294 {
13295 print_z_candidate (input_location, N_("candidate 1:"), w);
13296 print_z_candidate (input_location, N_("candidate 2:"), l);
13297 }
13298 }
13299 else
13300 add_warning (w, l);
13301 return winner;
13302 }
13303 }
13304
13305 gcc_assert (!winner);
13306 return 0;
13307 }
13308
13309 /* Given a list of candidates for overloading, find the best one, if any.
13310 This algorithm has a worst case of O(2n) (winner is last), and a best
13311 case of O(n/2) (totally ambiguous); much better than a sorting
13312 algorithm. The candidates list is assumed to be sorted according
13313 to viability (via splice_viable). */
13314
13315 static struct z_candidate *
13316 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13317 {
13318 struct z_candidate **champ = &candidates, **challenger;
13319 int fate;
13320 struct z_candidate *previous_worse_champ = nullptr;
13321
13322 /* Walk through the list once, comparing each current champ to the next
13323 candidate, knocking out a candidate or two with each comparison. */
13324
13325 for (challenger = &candidates->next; *challenger && (*challenger)->viable; )
13326 {
13327 fate = joust (*champ, *challenger, 0, complain);
13328 if (fate == 1)
13329 challenger = &(*challenger)->next;
13330 else if (fate == -1)
13331 {
13332 previous_worse_champ = *champ;
13333 champ = challenger;
13334 challenger = &(*challenger)->next;
13335 }
13336 else
13337 {
13338 previous_worse_champ = nullptr;
13339 champ = &(*challenger)->next;
13340 if (!*champ || !(*champ)->viable)
13341 {
13342 champ = nullptr;
13343 break;
13344 }
13345 challenger = &(*champ)->next;
13346 }
13347 }
13348
13349 /* Make sure the champ is better than all the candidates it hasn't yet
13350 been compared to. */
13351
13352 if (champ)
13353 for (challenger = &candidates;
13354 challenger != champ;
13355 challenger = &(*challenger)->next)
13356 {
13357 if (*challenger == previous_worse_champ)
13358 /* We already know this candidate is worse than the champ. */
13359 continue;
13360 fate = joust (*champ, *challenger, 0, complain);
13361 if (fate != 1)
13362 {
13363 champ = nullptr;
13364 break;
13365 }
13366 }
13367
13368 if (!champ)
13369 return nullptr;
13370
13371 /* Move the champ to the front of the candidate list. */
13372
13373 if (champ != &candidates)
13374 {
13375 z_candidate *saved_champ = *champ;
13376 *champ = saved_champ->next;
13377 saved_champ->next = candidates;
13378 candidates = saved_champ;
13379 }
13380
13381 return candidates;
13382 }
13383
13384 /* Returns nonzero if things of type FROM can be converted to TO. */
13385
13386 bool
13387 can_convert (tree to, tree from, tsubst_flags_t complain)
13388 {
13389 tree arg = NULL_TREE;
13390 /* implicit_conversion only considers user-defined conversions
13391 if it has an expression for the call argument list. */
13392 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13393 arg = build_stub_object (from);
13394 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13395 }
13396
13397 /* Returns nonzero if things of type FROM can be converted to TO with a
13398 standard conversion. */
13399
13400 bool
13401 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13402 {
13403 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13404 }
13405
13406 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13407
13408 bool
13409 can_convert_arg (tree to, tree from, tree arg, int flags,
13410 tsubst_flags_t complain)
13411 {
13412 conversion *t;
13413 bool ok_p;
13414
13415 conversion_obstack_sentinel cos;
13416 /* We want to discard any access checks done for this test,
13417 as we might not be in the appropriate access context and
13418 we'll do the check again when we actually perform the
13419 conversion. */
13420 push_deferring_access_checks (dk_deferred);
13421
13422 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13423 flags, complain);
13424 ok_p = (t && !t->bad_p);
13425
13426 /* Discard the access checks now. */
13427 pop_deferring_access_checks ();
13428
13429 return ok_p;
13430 }
13431
13432 /* Like can_convert_arg, but allows dubious conversions as well. */
13433
13434 bool
13435 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13436 tsubst_flags_t complain)
13437 {
13438 conversion *t;
13439
13440 conversion_obstack_sentinel cos;
13441 /* Try to perform the conversion. */
13442 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13443 flags, complain);
13444
13445 return t != NULL;
13446 }
13447
13448 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13449 resolution FLAGS. */
13450
13451 tree
13452 build_implicit_conv_flags (tree type, tree expr, int flags)
13453 {
13454 /* In a template, we are only concerned about determining the
13455 type of non-dependent expressions, so we do not have to
13456 perform the actual conversion. But for initializers, we
13457 need to be able to perform it at instantiation
13458 (or instantiate_non_dependent_expr) time. */
13459 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13460 if (!(flags & LOOKUP_ONLYCONVERTING))
13461 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13462 if (flags & LOOKUP_NO_NARROWING)
13463 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13464 return expr;
13465 }
13466
13467 /* Convert EXPR to TYPE. Return the converted expression.
13468
13469 Note that we allow bad conversions here because by the time we get to
13470 this point we are committed to doing the conversion. If we end up
13471 doing a bad conversion, convert_like will complain. */
13472
13473 tree
13474 perform_implicit_conversion_flags (tree type, tree expr,
13475 tsubst_flags_t complain, int flags)
13476 {
13477 conversion *conv;
13478 location_t loc = cp_expr_loc_or_input_loc (expr);
13479
13480 if (TYPE_REF_P (type))
13481 expr = mark_lvalue_use (expr);
13482 else
13483 expr = mark_rvalue_use (expr);
13484
13485 if (error_operand_p (expr))
13486 return error_mark_node;
13487
13488 conversion_obstack_sentinel cos;
13489
13490 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13491 /*c_cast_p=*/false,
13492 flags, complain);
13493
13494 if (!conv)
13495 {
13496 if (complain & tf_error)
13497 implicit_conversion_error (loc, type, expr);
13498 expr = error_mark_node;
13499 }
13500 else if (processing_template_decl && conv->kind != ck_identity)
13501 expr = build_implicit_conv_flags (type, expr, flags);
13502 else
13503 {
13504 /* Give a conversion call the same location as expr. */
13505 iloc_sentinel il (loc);
13506 expr = convert_like (conv, expr, complain);
13507 }
13508
13509 return expr;
13510 }
13511
13512 tree
13513 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13514 {
13515 return perform_implicit_conversion_flags (type, expr, complain,
13516 LOOKUP_IMPLICIT);
13517 }
13518
13519 /* Convert EXPR to TYPE (as a direct-initialization) if that is
13520 permitted. If the conversion is valid, the converted expression is
13521 returned. Otherwise, NULL_TREE is returned, except in the case
13522 that TYPE is a class type; in that case, an error is issued. If
13523 C_CAST_P is true, then this direct-initialization is taking
13524 place as part of a static_cast being attempted as part of a C-style
13525 cast. */
13526
13527 tree
13528 perform_direct_initialization_if_possible (tree type,
13529 tree expr,
13530 bool c_cast_p,
13531 tsubst_flags_t complain)
13532 {
13533 conversion *conv;
13534
13535 if (type == error_mark_node || error_operand_p (expr))
13536 return error_mark_node;
13537 /* [dcl.init]
13538
13539 If the destination type is a (possibly cv-qualified) class type:
13540
13541 -- If the initialization is direct-initialization ...,
13542 constructors are considered.
13543
13544 -- If overload resolution is successful, the selected constructor
13545 is called to initialize the object, with the initializer expression
13546 or expression-list as its argument(s).
13547
13548 -- Otherwise, if no constructor is viable, the destination type is
13549 a (possibly cv-qualified) aggregate class A, and the initializer is
13550 a parenthesized expression-list, the object is initialized as
13551 follows... */
13552 if (CLASS_TYPE_P (type))
13553 {
13554 releasing_vec args (make_tree_vector_single (expr));
13555 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13556 &args, type, LOOKUP_NORMAL, complain);
13557 return build_cplus_new (type, expr, complain);
13558 }
13559
13560 conversion_obstack_sentinel cos;
13561
13562 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13563 c_cast_p,
13564 LOOKUP_NORMAL, complain);
13565 if (!conv || conv->bad_p)
13566 expr = NULL_TREE;
13567 else if (processing_template_decl && conv->kind != ck_identity)
13568 {
13569 /* In a template, we are only concerned about determining the
13570 type of non-dependent expressions, so we do not have to
13571 perform the actual conversion. But for initializers, we
13572 need to be able to perform it at instantiation
13573 (or instantiate_non_dependent_expr) time. */
13574 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13575 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13576 }
13577 else
13578 expr = convert_like (conv, expr, NULL_TREE, 0,
13579 /*issue_conversion_warnings=*/false,
13580 c_cast_p, /*nested_p=*/false, complain);
13581
13582 return expr;
13583 }
13584
13585 /* When initializing a reference that lasts longer than a full-expression,
13586 this special rule applies:
13587
13588 [class.temporary]
13589
13590 The temporary to which the reference is bound or the temporary
13591 that is the complete object to which the reference is bound
13592 persists for the lifetime of the reference.
13593
13594 The temporaries created during the evaluation of the expression
13595 initializing the reference, except the temporary to which the
13596 reference is bound, are destroyed at the end of the
13597 full-expression in which they are created.
13598
13599 In that case, we store the converted expression into a new
13600 VAR_DECL in a new scope.
13601
13602 However, we want to be careful not to create temporaries when
13603 they are not required. For example, given:
13604
13605 struct B {};
13606 struct D : public B {};
13607 D f();
13608 const B& b = f();
13609
13610 there is no need to copy the return value from "f"; we can just
13611 extend its lifetime. Similarly, given:
13612
13613 struct S {};
13614 struct T { operator S(); };
13615 T t;
13616 const S& s = t;
13617
13618 we can extend the lifetime of the return value of the conversion
13619 operator.
13620
13621 The next several functions are involved in this lifetime extension. */
13622
13623 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13624 reference is being bound to a temporary. Create and return a new
13625 VAR_DECL with the indicated TYPE; this variable will store the value to
13626 which the reference is bound. */
13627
13628 tree
13629 make_temporary_var_for_ref_to_temp (tree decl, tree type)
13630 {
13631 tree var = create_temporary_var (type);
13632
13633 /* Register the variable. */
13634 if (VAR_P (decl)
13635 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13636 {
13637 /* Namespace-scope or local static; give it a mangled name. */
13638
13639 /* If an initializer is visible to multiple translation units, those
13640 translation units must agree on the addresses of the
13641 temporaries. Therefore the temporaries must be given a consistent name
13642 and vague linkage. The mangled name of a temporary is the name of the
13643 non-temporary object in whose initializer they appear, prefixed with
13644 GR and suffixed with a sequence number mangled using the usual rules
13645 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13646 left-to-right walk of the complete initializer. */
13647 copy_linkage (var, decl);
13648
13649 tree name = mangle_ref_init_variable (decl);
13650 DECL_NAME (var) = name;
13651 SET_DECL_ASSEMBLER_NAME (var, name);
13652 }
13653 else
13654 /* Create a new cleanup level if necessary. */
13655 maybe_push_cleanup_level (type);
13656
13657 return pushdecl (var);
13658 }
13659
13660 /* EXPR is the initializer for a variable DECL of reference or
13661 std::initializer_list type. Create, push and return a new VAR_DECL
13662 for the initializer so that it will live as long as DECL. Any
13663 cleanup for the new variable is returned through CLEANUP, and the
13664 code to initialize the new variable is returned through INITP. */
13665
13666 static tree
13667 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13668 tree *initp, tree *cond_guard)
13669 {
13670 tree init;
13671 tree type;
13672 tree var;
13673
13674 /* Create the temporary variable. */
13675 type = TREE_TYPE (expr);
13676 var = make_temporary_var_for_ref_to_temp (decl, type);
13677 layout_decl (var, 0);
13678 /* If the rvalue is the result of a function call it will be
13679 a TARGET_EXPR. If it is some other construct (such as a
13680 member access expression where the underlying object is
13681 itself the result of a function call), turn it into a
13682 TARGET_EXPR here. It is important that EXPR be a
13683 TARGET_EXPR below since otherwise the INIT_EXPR will
13684 attempt to make a bitwise copy of EXPR to initialize
13685 VAR. */
13686 if (TREE_CODE (expr) != TARGET_EXPR)
13687 expr = get_target_expr (expr);
13688 else
13689 {
13690 if (TREE_ADDRESSABLE (expr))
13691 TREE_ADDRESSABLE (var) = 1;
13692 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
13693 DECL_MERGEABLE (var) = true;
13694 }
13695
13696 if (TREE_CODE (decl) == FIELD_DECL
13697 && extra_warnings && !warning_suppressed_p (decl))
13698 {
13699 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13700 "until the constructor exits", decl);
13701 suppress_warning (decl);
13702 }
13703
13704 /* Recursively extend temps in this initializer. */
13705 TARGET_EXPR_INITIAL (expr)
13706 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13707 cond_guard);
13708
13709 /* Any reference temp has a non-trivial initializer. */
13710 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13711
13712 /* If the initializer is constant, put it in DECL_INITIAL so we get
13713 static initialization and use in constant expressions. */
13714 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13715 /* As in store_init_value. */
13716 init = cp_fully_fold (init);
13717 if (TREE_CONSTANT (init))
13718 {
13719 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13720 {
13721 /* 5.19 says that a constant expression can include an
13722 lvalue-rvalue conversion applied to "a glvalue of literal type
13723 that refers to a non-volatile temporary object initialized
13724 with a constant expression". Rather than try to communicate
13725 that this VAR_DECL is a temporary, just mark it constexpr. */
13726 DECL_DECLARED_CONSTEXPR_P (var) = true;
13727 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13728 TREE_CONSTANT (var) = true;
13729 TREE_READONLY (var) = true;
13730 }
13731 DECL_INITIAL (var) = init;
13732 init = NULL_TREE;
13733 }
13734 else
13735 /* Create the INIT_EXPR that will initialize the temporary
13736 variable. */
13737 init = split_nonconstant_init (var, expr);
13738 if (at_function_scope_p ())
13739 {
13740 add_decl_expr (var);
13741
13742 if (TREE_STATIC (var))
13743 init = add_stmt_to_compound (init, register_dtor_fn (var));
13744 else
13745 {
13746 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13747 if (cleanup)
13748 {
13749 if (cond_guard && cleanup != error_mark_node)
13750 {
13751 if (*cond_guard == NULL_TREE)
13752 {
13753 *cond_guard = build_local_temp (boolean_type_node);
13754 add_decl_expr (*cond_guard);
13755 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13756 *cond_guard, NOP_EXPR,
13757 boolean_false_node,
13758 tf_warning_or_error);
13759 finish_expr_stmt (set);
13760 }
13761 cleanup = build3 (COND_EXPR, void_type_node,
13762 *cond_guard, cleanup, NULL_TREE);
13763 }
13764 vec_safe_push (*cleanups, cleanup);
13765 }
13766 }
13767
13768 /* We must be careful to destroy the temporary only
13769 after its initialization has taken place. If the
13770 initialization throws an exception, then the
13771 destructor should not be run. We cannot simply
13772 transform INIT into something like:
13773
13774 (INIT, ({ CLEANUP_STMT; }))
13775
13776 because emit_local_var always treats the
13777 initializer as a full-expression. Thus, the
13778 destructor would run too early; it would run at the
13779 end of initializing the reference variable, rather
13780 than at the end of the block enclosing the
13781 reference variable.
13782
13783 The solution is to pass back a cleanup expression
13784 which the caller is responsible for attaching to
13785 the statement tree. */
13786 }
13787 else
13788 {
13789 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13790 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13791 {
13792 if (CP_DECL_THREAD_LOCAL_P (var))
13793 tls_aggregates = tree_cons (NULL_TREE, var,
13794 tls_aggregates);
13795 else
13796 static_aggregates = tree_cons (NULL_TREE, var,
13797 static_aggregates);
13798 }
13799 else
13800 /* Check whether the dtor is callable. */
13801 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13802 }
13803 /* Avoid -Wunused-variable warning (c++/38958). */
13804 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13805 && VAR_P (decl))
13806 TREE_USED (decl) = DECL_READ_P (decl) = true;
13807
13808 *initp = init;
13809 return var;
13810 }
13811
13812 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
13813 initializing a variable of that TYPE. */
13814
13815 tree
13816 initialize_reference (tree type, tree expr,
13817 int flags, tsubst_flags_t complain)
13818 {
13819 conversion *conv;
13820 location_t loc = cp_expr_loc_or_input_loc (expr);
13821
13822 if (type == error_mark_node || error_operand_p (expr))
13823 return error_mark_node;
13824
13825 conversion_obstack_sentinel cos;
13826
13827 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13828 flags, complain);
13829 /* If this conversion failed, we're in C++20, and we have something like
13830 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13831 if ((!conv || conv->bad_p)
13832 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13833 {
13834 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13835 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13836 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13837 conversion *c = reference_binding (type, TREE_TYPE (e), e,
13838 /*c_cast_p=*/false, flags, complain);
13839 /* If this worked, use it. */
13840 if (c && !c->bad_p)
13841 expr = e, conv = c;
13842 }
13843 if (!conv || conv->bad_p)
13844 {
13845 if (complain & tf_error)
13846 {
13847 if (conv)
13848 convert_like (conv, expr, complain);
13849 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13850 && !TYPE_REF_IS_RVALUE (type)
13851 && !lvalue_p (expr))
13852 error_at (loc, "invalid initialization of non-const reference of "
13853 "type %qH from an rvalue of type %qI",
13854 type, TREE_TYPE (expr));
13855 else
13856 error_at (loc, "invalid initialization of reference of type "
13857 "%qH from expression of type %qI", type,
13858 TREE_TYPE (expr));
13859 }
13860 return error_mark_node;
13861 }
13862
13863 if (conv->kind == ck_ref_bind)
13864 /* Perform the conversion. */
13865 expr = convert_like (conv, expr, complain);
13866 else if (conv->kind == ck_ambig)
13867 /* We gave an error in build_user_type_conversion_1. */
13868 expr = error_mark_node;
13869 else
13870 gcc_unreachable ();
13871
13872 return expr;
13873 }
13874
13875 /* Return true if T is std::pair<const T&, const T&>. */
13876
13877 static bool
13878 std_pair_ref_ref_p (tree t)
13879 {
13880 /* First, check if we have std::pair. */
13881 if (!NON_UNION_CLASS_TYPE_P (t)
13882 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
13883 return false;
13884 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
13885 if (!decl_in_std_namespace_p (tdecl))
13886 return false;
13887 tree name = DECL_NAME (tdecl);
13888 if (!name || !id_equal (name, "pair"))
13889 return false;
13890
13891 /* Now see if the template arguments are both const T&. */
13892 tree args = CLASSTYPE_TI_ARGS (t);
13893 if (TREE_VEC_LENGTH (args) != 2)
13894 return false;
13895 for (int i = 0; i < 2; i++)
13896 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
13897 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
13898 return false;
13899
13900 return true;
13901 }
13902
13903 /* Return true if a class CTYPE is either std::reference_wrapper or
13904 std::ref_view, or a reference wrapper class. We consider a class
13905 a reference wrapper class if it has a reference member. We no
13906 longer check that it has a constructor taking the same reference type
13907 since that approach still generated too many false positives. */
13908
13909 static bool
13910 class_has_reference_member_p (tree t)
13911 {
13912 for (tree fields = TYPE_FIELDS (t);
13913 fields;
13914 fields = DECL_CHAIN (fields))
13915 if (TREE_CODE (fields) == FIELD_DECL
13916 && !DECL_ARTIFICIAL (fields)
13917 && TYPE_REF_P (TREE_TYPE (fields)))
13918 return true;
13919 return false;
13920 }
13921
13922 /* A wrapper for the above suitable as a callback for dfs_walk_once. */
13923
13924 static tree
13925 class_has_reference_member_p_r (tree binfo, void *)
13926 {
13927 return (class_has_reference_member_p (BINFO_TYPE (binfo))
13928 ? integer_one_node : NULL_TREE);
13929 }
13930
13931 static bool
13932 reference_like_class_p (tree ctype)
13933 {
13934 if (!CLASS_TYPE_P (ctype))
13935 return false;
13936
13937 /* Also accept a std::pair<const T&, const T&>. */
13938 if (std_pair_ref_ref_p (ctype))
13939 return true;
13940
13941 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
13942 if (decl_in_std_namespace_p (tdecl))
13943 {
13944 tree name = DECL_NAME (tdecl);
13945 if (name
13946 && (id_equal (name, "reference_wrapper")
13947 || id_equal (name, "span")
13948 || id_equal (name, "ref_view")))
13949 return true;
13950 }
13951
13952 /* Some classes, such as std::tuple, have the reference member in its
13953 (non-direct) base class. */
13954 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
13955 nullptr, nullptr))
13956 return true;
13957
13958 return false;
13959 }
13960
13961 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
13962 that initializes the LHS (and at least one of its arguments represents
13963 a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
13964 if none found. For instance:
13965
13966 const S& s = S().self(); // S::self (&TARGET_EXPR <...>)
13967 const int& r = (42, f(1)); // f(1)
13968 const int& t = b ? f(1) : f(2); // f(1)
13969 const int& u = b ? f(1) : f(g); // f(1)
13970 const int& v = b ? f(g) : f(2); // f(2)
13971 const int& w = b ? f(g) : f(g); // NULL_TREE
13972 const int& y = (f(1), 42); // NULL_TREE
13973 const int& z = f(f(1)); // f(f(1))
13974
13975 EXPR is the initializer. If ARG_P is true, we're processing an argument
13976 to a function; the point is to distinguish between, for example,
13977
13978 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
13979
13980 where we shouldn't warn, and
13981
13982 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
13983
13984 where we should warn (Ref is a reference_like_class_p so we see through
13985 it. */
13986
13987 static tree
13988 do_warn_dangling_reference (tree expr, bool arg_p)
13989 {
13990 STRIP_NOPS (expr);
13991
13992 if (arg_p && expr_represents_temporary_p (expr))
13993 {
13994 /* An attempt to reduce the number of -Wdangling-reference
13995 false positives concerning reference wrappers (c++/107532).
13996 When we encounter a reference_like_class_p, we don't warn
13997 just yet; instead, we keep recursing to see if there were
13998 any temporaries behind the reference-wrapper class. */
13999 tree e = expr;
14000 while (handled_component_p (e))
14001 e = TREE_OPERAND (e, 0);
14002 if (!reference_like_class_p (TREE_TYPE (e)))
14003 return expr;
14004 }
14005
14006 switch (TREE_CODE (expr))
14007 {
14008 case CALL_EXPR:
14009 {
14010 tree fndecl = cp_get_callee_fndecl_nofold (expr);
14011 if (!fndecl
14012 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
14013 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
14014 OPT_Wdangling_reference)
14015 /* Don't emit a false positive for:
14016 std::vector<int> v = ...;
14017 std::vector<int>::const_iterator it = v.begin();
14018 const int &r = *it++;
14019 because R refers to one of the int elements of V, not to
14020 a temporary object. Member operator* may return a reference
14021 but probably not to one of its arguments. */
14022 || (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
14023 && DECL_OVERLOADED_OPERATOR_P (fndecl)
14024 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF)))
14025 return NULL_TREE;
14026
14027 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
14028 /* If the function doesn't return a reference, don't warn. This
14029 can be e.g.
14030 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
14031 which doesn't dangle: std::min here returns an int.
14032
14033 If the function returns a std::pair<const T&, const T&>, we
14034 warn, to detect e.g.
14035 std::pair<const int&, const int&> v = std::minmax(1, 2);
14036 which also creates a dangling reference, because std::minmax
14037 returns std::pair<const T&, const T&>(b, a). */
14038 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
14039 return NULL_TREE;
14040
14041 /* Here we're looking to see if any of the arguments is a temporary
14042 initializing a reference parameter. */
14043 for (int i = 0; i < call_expr_nargs (expr); ++i)
14044 {
14045 tree arg = CALL_EXPR_ARG (expr, i);
14046 /* Check that this argument initializes a reference, except for
14047 the argument initializing the object of a member function. */
14048 if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
14049 && !TYPE_REF_P (TREE_TYPE (arg)))
14050 continue;
14051 STRIP_NOPS (arg);
14052 if (TREE_CODE (arg) == ADDR_EXPR)
14053 arg = TREE_OPERAND (arg, 0);
14054 /* Recurse to see if the argument is a temporary. It could also
14055 be another call taking a temporary and returning it and
14056 initializing this reference parameter. */
14057 if (do_warn_dangling_reference (arg, /*arg_p=*/true))
14058 return expr;
14059 /* Don't warn about member function like:
14060 std::any a(...);
14061 S& s = a.emplace<S>({0}, 0);
14062 which constructs a new object and returns a reference to it, but
14063 we still want to detect:
14064 struct S { const S& self () { return *this; } };
14065 const S& s = S().self();
14066 where 's' dangles. If we've gotten here, the object this function
14067 is invoked on is not a temporary. */
14068 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl))
14069 break;
14070 }
14071 return NULL_TREE;
14072 }
14073 case COMPOUND_EXPR:
14074 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
14075 case COND_EXPR:
14076 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
14077 return t;
14078 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
14079 case PAREN_EXPR:
14080 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
14081 case TARGET_EXPR:
14082 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
14083 default:
14084 return NULL_TREE;
14085 }
14086 }
14087
14088 /* Implement -Wdangling-reference, to detect cases like
14089
14090 int n = 1;
14091 const int& r = std::max(n - 1, n + 1); // r is dangling
14092
14093 This creates temporaries from the arguments, returns a reference to
14094 one of the temporaries, but both temporaries are destroyed at the end
14095 of the full expression.
14096
14097 This works by checking if a reference is initialized with a function
14098 that returns a reference, and at least one parameter of the function
14099 is a reference that is bound to a temporary. It assumes that such a
14100 function actually returns one of its arguments.
14101
14102 DECL is the reference being initialized, INIT is the initializer. */
14103
14104 static void
14105 maybe_warn_dangling_reference (const_tree decl, tree init)
14106 {
14107 if (!warn_dangling_reference)
14108 return;
14109 tree type = TREE_TYPE (decl);
14110 /* Only warn if what we're initializing has type T&& or const T&, or
14111 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14112 bind to a temporary.) */
14113 if (!((TYPE_REF_OBJ_P (type)
14114 && (TYPE_REF_IS_RVALUE (type)
14115 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14116 || std_pair_ref_ref_p (type)))
14117 return;
14118 /* Don't suppress the diagnostic just because the call comes from
14119 a system header. If the DECL is not in a system header, or if
14120 -Wsystem-headers was provided, warn. */
14121 auto wsh
14122 = make_temp_override (global_dc->m_warn_system_headers,
14123 (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14124 || global_dc->m_warn_system_headers));
14125 if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
14126 {
14127 auto_diagnostic_group d;
14128 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14129 "possibly dangling reference to a temporary"))
14130 inform (EXPR_LOCATION (call), "the temporary was destroyed at "
14131 "the end of the full expression %qE", call);
14132 }
14133 }
14134
14135 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
14136 gets used to initialize a reference. */
14137
14138 static tree
14139 prevent_lifetime_extension (tree t)
14140 {
14141 tree *p = &t;
14142 while (TREE_CODE (*p) == COMPOUND_EXPR)
14143 p = &TREE_OPERAND (*p, 1);
14144 while (handled_component_p (*p))
14145 p = &TREE_OPERAND (*p, 0);
14146 /* Change a TARGET_EXPR from prvalue to xvalue. */
14147 if (TREE_CODE (*p) == TARGET_EXPR)
14148 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14149 move (TARGET_EXPR_SLOT (*p)));
14150 return t;
14151 }
14152
14153 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14154 which is bound either to a reference or a std::initializer_list. */
14155
14156 static tree
14157 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14158 tree *cond_guard)
14159 {
14160 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14161 the temporary object that is the complete object of a subobject to which
14162 the reference is bound persists for the lifetime of the reference if the
14163 glvalue to which the reference is bound was obtained through one of the
14164 following:
14165 - a temporary materialization conversion ([conv.rval]),
14166 - ( expression ), where expression is one of these expressions,
14167 - subscripting ([expr.sub]) of an array operand, where that operand is one
14168 of these expressions,
14169 - a class member access ([expr.ref]) using the . operator where the left
14170 operand is one of these expressions and the right operand designates a
14171 non-static data member of non-reference type,
14172 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14173 where the left operand is one of these expressions and the right operand
14174 is a pointer to data member of non-reference type,
14175 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14176 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14177 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14178 a glvalue operand that is one of these expressions to a glvalue that
14179 refers to the object designated by the operand, or to its complete
14180 object or a subobject thereof,
14181 - a conditional expression ([expr.cond]) that is a glvalue where the
14182 second or third operand is one of these expressions, or
14183 - a comma expression ([expr.comma]) that is a glvalue where the right
14184 operand is one of these expressions. */
14185
14186 /* FIXME several cases are still handled wrong (101572, 81420). */
14187
14188 tree sub = init;
14189 tree *p;
14190 STRIP_NOPS (sub);
14191 if (TREE_CODE (sub) == COMPOUND_EXPR)
14192 {
14193 TREE_OPERAND (sub, 1)
14194 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14195 cond_guard);
14196 return init;
14197 }
14198 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14199 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14200 (TREE_OPERAND (sub, 1)))))
14201 {
14202 /* A pointer-to-member operation. */
14203 TREE_OPERAND (sub, 0)
14204 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14205 cond_guard);
14206 return init;
14207 }
14208 if (TREE_CODE (sub) == COND_EXPR)
14209 {
14210 tree cur_cond_guard = NULL_TREE;
14211 if (TREE_OPERAND (sub, 1))
14212 TREE_OPERAND (sub, 1)
14213 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14214 &cur_cond_guard);
14215 if (cur_cond_guard)
14216 {
14217 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14218 NOP_EXPR, boolean_true_node,
14219 tf_warning_or_error);
14220 TREE_OPERAND (sub, 1)
14221 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14222 tf_warning_or_error);
14223 }
14224 cur_cond_guard = NULL_TREE;
14225 if (TREE_OPERAND (sub, 2))
14226 TREE_OPERAND (sub, 2)
14227 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14228 &cur_cond_guard);
14229 if (cur_cond_guard)
14230 {
14231 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14232 NOP_EXPR, boolean_true_node,
14233 tf_warning_or_error);
14234 TREE_OPERAND (sub, 2)
14235 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14236 tf_warning_or_error);
14237 }
14238 return init;
14239 }
14240 if (TREE_CODE (sub) != ADDR_EXPR)
14241 return init;
14242 /* Deal with binding to a subobject. */
14243 for (p = &TREE_OPERAND (sub, 0);
14244 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14245 p = &TREE_OPERAND (*p, 0);
14246 if (TREE_CODE (*p) == TARGET_EXPR)
14247 {
14248 tree subinit = NULL_TREE;
14249 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
14250 recompute_tree_invariant_for_addr_expr (sub);
14251 if (init != sub)
14252 init = fold_convert (TREE_TYPE (init), sub);
14253 if (subinit)
14254 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14255 }
14256 return init;
14257 }
14258
14259 /* INIT is part of the initializer for DECL. If there are any
14260 reference or initializer lists being initialized, extend their
14261 lifetime to match that of DECL. */
14262
14263 tree
14264 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14265 tree *cond_guard)
14266 {
14267 tree type = TREE_TYPE (init);
14268 if (processing_template_decl)
14269 return init;
14270
14271 maybe_warn_dangling_reference (decl, init);
14272
14273 if (TYPE_REF_P (type))
14274 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14275 else
14276 {
14277 tree ctor = init;
14278 if (TREE_CODE (ctor) == TARGET_EXPR)
14279 ctor = TARGET_EXPR_INITIAL (ctor);
14280 if (TREE_CODE (ctor) == CONSTRUCTOR)
14281 {
14282 /* [dcl.init] When initializing an aggregate from a parenthesized list
14283 of values... a temporary object bound to a reference does not have
14284 its lifetime extended. */
14285 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14286 return init;
14287
14288 if (is_std_init_list (type))
14289 {
14290 /* The temporary array underlying a std::initializer_list
14291 is handled like a reference temporary. */
14292 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14293 array = extend_ref_init_temps_1 (decl, array, cleanups,
14294 cond_guard);
14295 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14296 }
14297 else
14298 {
14299 unsigned i;
14300 constructor_elt *p;
14301 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14302 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14303 p->value = extend_ref_init_temps (decl, p->value, cleanups,
14304 cond_guard);
14305 }
14306 recompute_constructor_flags (ctor);
14307 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14308 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14309 }
14310 }
14311
14312 return init;
14313 }
14314
14315 /* Returns true iff an initializer for TYPE could contain temporaries that
14316 need to be extended because they are bound to references or
14317 std::initializer_list. */
14318
14319 bool
14320 type_has_extended_temps (tree type)
14321 {
14322 type = strip_array_types (type);
14323 if (TYPE_REF_P (type))
14324 return true;
14325 if (CLASS_TYPE_P (type))
14326 {
14327 if (is_std_init_list (type))
14328 return true;
14329 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14330 f; f = next_aggregate_field (DECL_CHAIN (f)))
14331 if (type_has_extended_temps (TREE_TYPE (f)))
14332 return true;
14333 }
14334 return false;
14335 }
14336
14337 /* Returns true iff TYPE is some variant of std::initializer_list. */
14338
14339 bool
14340 is_std_init_list (tree type)
14341 {
14342 if (!TYPE_P (type))
14343 return false;
14344 if (cxx_dialect == cxx98)
14345 return false;
14346 /* Look through typedefs. */
14347 type = TYPE_MAIN_VARIANT (type);
14348 return (CLASS_TYPE_P (type)
14349 && CP_TYPE_CONTEXT (type) == std_node
14350 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14351 }
14352
14353 /* Returns true iff DECL is a list constructor: i.e. a constructor which
14354 will accept an argument list of a single std::initializer_list<T>. */
14355
14356 bool
14357 is_list_ctor (tree decl)
14358 {
14359 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14360 tree arg;
14361
14362 if (!args || args == void_list_node)
14363 return false;
14364
14365 arg = non_reference (TREE_VALUE (args));
14366 if (!is_std_init_list (arg))
14367 return false;
14368
14369 args = TREE_CHAIN (args);
14370
14371 if (args && args != void_list_node && !TREE_PURPOSE (args))
14372 /* There are more non-defaulted parms. */
14373 return false;
14374
14375 return true;
14376 }
14377
14378 /* We know that can_convert_arg_bad already said "no" when trying to convert
14379 FROM to TO with ARG and FLAGS. Try to figure out if it was because
14380 an explicit conversion function was skipped when looking for a way to
14381 perform the conversion. At this point we've already printed an error. */
14382
14383 void
14384 maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
14385 {
14386 if (!(flags & LOOKUP_ONLYCONVERTING))
14387 return;
14388
14389 conversion_obstack_sentinel cos;
14390 conversion *c = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
14391 flags & ~LOOKUP_ONLYCONVERTING, tf_none);
14392 if (c && !c->bad_p && c->user_conv_p)
14393 /* Ay, the conversion would have worked in direct-init context. */
14394 for (; c; c = next_conversion (c))
14395 if (c->kind == ck_user
14396 && DECL_P (c->cand->fn)
14397 && DECL_NONCONVERTING_P (c->cand->fn))
14398 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
14399 "function was not considered");
14400 }
14401
14402 #include "gt-cp-call.h"