c++: look for empty base at specific offset [PR109678]
[official-gcc.git] / gcc / cp / call.cc
blob2a06520c0c107e5b66f2caef514d445c3f66f914
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2023 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com) and
4 modified by Brendan Kehoe (brendan@cygnus.com).
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
23 /* High-level class interface. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "target.h"
29 #include "cp-tree.h"
30 #include "timevar.h"
31 #include "stringpool.h"
32 #include "cgraph.h"
33 #include "stor-layout.h"
34 #include "trans-mem.h"
35 #include "flags.h"
36 #include "toplev.h"
37 #include "intl.h"
38 #include "convert.h"
39 #include "langhooks.h"
40 #include "c-family/c-objc.h"
41 #include "internal-fn.h"
42 #include "stringpool.h"
43 #include "attribs.h"
44 #include "decl.h"
45 #include "gcc-rich-location.h"
47 /* The various kinds of conversion. */
49 enum conversion_kind {
50 ck_identity,
51 ck_lvalue,
52 ck_fnptr,
53 ck_qual,
54 ck_std,
55 ck_ptr,
56 ck_pmem,
57 ck_base,
58 ck_ref_bind,
59 ck_user,
60 ck_ambig,
61 ck_list,
62 ck_aggr,
63 ck_rvalue,
64 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
65 this kind whenever we know the true conversion is either bad or outright
66 invalid, but we don't want to attempt to compute the bad conversion (for
67 sake of avoiding unnecessary instantiation). bad_p should always be set
68 for these. */
69 ck_deferred_bad,
72 /* The rank of the conversion. Order of the enumerals matters; better
73 conversions should come earlier in the list. */
75 enum conversion_rank {
76 cr_identity,
77 cr_exact,
78 cr_promotion,
79 cr_std,
80 cr_pbool,
81 cr_user,
82 cr_ellipsis,
83 cr_bad
86 /* An implicit conversion sequence, in the sense of [over.best.ics].
87 The first conversion to be performed is at the end of the chain.
88 That conversion is always a cr_identity conversion. */
90 struct conversion {
91 /* The kind of conversion represented by this step. */
92 conversion_kind kind;
93 /* The rank of this conversion. */
94 conversion_rank rank;
95 BOOL_BITFIELD user_conv_p : 1;
96 BOOL_BITFIELD ellipsis_p : 1;
97 BOOL_BITFIELD this_p : 1;
98 /* True if this conversion would be permitted with a bending of
99 language standards, e.g. disregarding pointer qualifiers or
100 converting integers to pointers. */
101 BOOL_BITFIELD bad_p : 1;
102 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
103 temporary should be created to hold the result of the
104 conversion. If KIND is ck_ambig or ck_user, true means force
105 copy-initialization. */
106 BOOL_BITFIELD need_temporary_p : 1;
107 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
108 from a pointer-to-derived to pointer-to-base is being performed. */
109 BOOL_BITFIELD base_p : 1;
110 /* If KIND is ck_ref_bind, true when either an lvalue reference is
111 being bound to an lvalue expression or an rvalue reference is
112 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
113 true when we are treating an lvalue as an rvalue (12.8p33). If
114 ck_identity, we will be binding a reference directly or decaying to
115 a pointer. */
116 BOOL_BITFIELD rvaluedness_matches_p: 1;
117 BOOL_BITFIELD check_narrowing: 1;
118 /* Whether check_narrowing should only check TREE_CONSTANTs; used
119 in build_converted_constant_expr. */
120 BOOL_BITFIELD check_narrowing_const_only: 1;
121 /* True if this conversion is taking place in a copy-initialization context
122 and we should only consider converting constructors. Only set in
123 ck_base and ck_rvalue. */
124 BOOL_BITFIELD copy_init_p : 1;
125 /* The type of the expression resulting from the conversion. */
126 tree type;
127 union {
128 /* The next conversion in the chain. Since the conversions are
129 arranged from outermost to innermost, the NEXT conversion will
130 actually be performed before this conversion. This variant is
131 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
132 ck_list. Please use the next_conversion function instead
133 of using this field directly. */
134 conversion *next;
135 /* The expression at the beginning of the conversion chain. This
136 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
137 You can use conv_get_original_expr to get this expression. */
138 tree expr;
139 /* The array of conversions for an initializer_list, so this
140 variant is used only when KIN D is ck_list. */
141 conversion **list;
142 } u;
143 /* The function candidate corresponding to this conversion
144 sequence. This field is only used if KIND is ck_user. */
145 struct z_candidate *cand;
148 #define CONVERSION_RANK(NODE) \
149 ((NODE)->bad_p ? cr_bad \
150 : (NODE)->ellipsis_p ? cr_ellipsis \
151 : (NODE)->user_conv_p ? cr_user \
152 : (NODE)->rank)
154 #define BAD_CONVERSION_RANK(NODE) \
155 ((NODE)->ellipsis_p ? cr_ellipsis \
156 : (NODE)->user_conv_p ? cr_user \
157 : (NODE)->rank)
159 static struct obstack conversion_obstack;
160 static bool conversion_obstack_initialized;
161 struct rejection_reason;
163 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
164 static int equal_functions (tree, tree);
165 static int joust (struct z_candidate *, struct z_candidate *, bool,
166 tsubst_flags_t);
167 static int compare_ics (conversion *, conversion *);
168 static void maybe_warn_class_memaccess (location_t, tree,
169 const vec<tree, va_gc> *);
170 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
171 static tree convert_like (conversion *, tree, tsubst_flags_t);
172 static tree convert_like_with_context (conversion *, tree, tree, int,
173 tsubst_flags_t);
174 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
175 tree, tree, tree, bool);
176 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
177 tsubst_flags_t);
178 static void print_z_candidate (location_t, const char *, struct z_candidate *);
179 static void print_z_candidates (location_t, struct z_candidate *);
180 static tree build_this (tree);
181 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
182 static bool any_strictly_viable (struct z_candidate *);
183 static struct z_candidate *add_template_candidate
184 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
185 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
186 static struct z_candidate *add_template_candidate_real
187 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
188 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
189 static bool is_complete (tree);
190 static struct z_candidate *add_conv_candidate
191 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
192 tree, tsubst_flags_t);
193 static struct z_candidate *add_function_candidate
194 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
195 tree, int, conversion**, bool, tsubst_flags_t);
196 static conversion *implicit_conversion (tree, tree, tree, bool, int,
197 tsubst_flags_t);
198 static conversion *reference_binding (tree, tree, tree, bool, int,
199 tsubst_flags_t);
200 static conversion *build_conv (conversion_kind, tree, conversion *);
201 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
202 static conversion *next_conversion (conversion *);
203 static bool is_subseq (conversion *, conversion *);
204 static conversion *maybe_handle_ref_bind (conversion **);
205 static void maybe_handle_implicit_object (conversion **);
206 static struct z_candidate *add_candidate
207 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
208 conversion **, tree, tree, int, struct rejection_reason *, int);
209 static tree source_type (conversion *);
210 static void add_warning (struct z_candidate *, struct z_candidate *);
211 static conversion *direct_reference_binding (tree, conversion *);
212 static bool promoted_arithmetic_type_p (tree);
213 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
214 static char *name_as_c_string (tree, tree, bool *);
215 static tree prep_operand (tree);
216 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
217 bool, tree, tree, int, struct z_candidate **,
218 tsubst_flags_t);
219 static conversion *merge_conversion_sequences (conversion *, conversion *);
220 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
221 static conversion *build_identity_conv (tree, tree);
222 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
223 static bool conv_is_prvalue (conversion *);
224 static tree prevent_lifetime_extension (tree);
226 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
227 NAME can take many forms... */
229 bool
230 check_dtor_name (tree basetype, tree name)
232 /* Just accept something we've already complained about. */
233 if (name == error_mark_node)
234 return true;
236 if (TREE_CODE (name) == TYPE_DECL)
237 name = TREE_TYPE (name);
238 else if (TYPE_P (name))
239 /* OK */;
240 else if (identifier_p (name))
242 if ((MAYBE_CLASS_TYPE_P (basetype)
243 || TREE_CODE (basetype) == ENUMERAL_TYPE)
244 && name == constructor_name (basetype))
245 return true;
247 /* Otherwise lookup the name, it could be an unrelated typedef
248 of the correct type. */
249 name = lookup_name (name, LOOK_want::TYPE);
250 if (!name)
251 return false;
252 name = TREE_TYPE (name);
253 if (name == error_mark_node)
254 return false;
256 else
258 /* In the case of:
260 template <class T> struct S { ~S(); };
261 int i;
262 i.~S();
264 NAME will be a class template. */
265 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
266 return false;
269 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
272 /* We want the address of a function or method. We avoid creating a
273 pointer-to-member function. */
275 tree
276 build_addr_func (tree function, tsubst_flags_t complain)
278 tree type = TREE_TYPE (function);
280 /* We have to do these by hand to avoid real pointer to member
281 functions. */
282 if (TREE_CODE (type) == METHOD_TYPE)
284 if (TREE_CODE (function) == OFFSET_REF)
286 tree object = build_address (TREE_OPERAND (function, 0));
287 return get_member_function_from_ptrfunc (&object,
288 TREE_OPERAND (function, 1),
289 complain);
291 function = build_address (function);
293 else if (TREE_CODE (function) == FUNCTION_DECL
294 && DECL_IMMEDIATE_FUNCTION_P (function))
295 function = build_address (function);
296 else
297 function = decay_conversion (function, complain, /*reject_builtin=*/false);
299 return function;
302 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
303 POINTER_TYPE to those. Note, pointer to member function types
304 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
305 two variants. build_call_a is the primitive taking an array of
306 arguments, while build_call_n is a wrapper that handles varargs. */
308 tree
309 build_call_n (tree function, int n, ...)
311 if (n == 0)
312 return build_call_a (function, 0, NULL);
313 else
315 tree *argarray = XALLOCAVEC (tree, n);
316 va_list ap;
317 int i;
319 va_start (ap, n);
320 for (i = 0; i < n; i++)
321 argarray[i] = va_arg (ap, tree);
322 va_end (ap);
323 return build_call_a (function, n, argarray);
327 /* Update various flags in cfun and the call itself based on what is being
328 called. Split out of build_call_a so that bot_manip can use it too. */
330 void
331 set_flags_from_callee (tree call)
333 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
334 tree decl = cp_get_callee_fndecl_nofold (call);
336 /* We check both the decl and the type; a function may be known not to
337 throw without being declared throw(). */
338 bool nothrow = decl && TREE_NOTHROW (decl);
339 tree callee = cp_get_callee (call);
340 if (callee)
341 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
342 else if (TREE_CODE (call) == CALL_EXPR
343 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
344 nothrow = true;
346 if (cfun && cp_function_chain && !cp_unevaluated_operand)
348 if (!nothrow && at_function_scope_p ())
349 cp_function_chain->can_throw = 1;
351 if (decl && TREE_THIS_VOLATILE (decl))
352 current_function_returns_abnormally = 1;
355 TREE_NOTHROW (call) = nothrow;
358 tree
359 build_call_a (tree function, int n, tree *argarray)
361 tree decl;
362 tree result_type;
363 tree fntype;
364 int i;
366 function = build_addr_func (function, tf_warning_or_error);
368 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
369 fntype = TREE_TYPE (TREE_TYPE (function));
370 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
371 result_type = TREE_TYPE (fntype);
372 /* An rvalue has no cv-qualifiers. */
373 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
374 result_type = cv_unqualified (result_type);
376 function = build_call_array_loc (input_location,
377 result_type, function, n, argarray);
378 set_flags_from_callee (function);
380 decl = get_callee_fndecl (function);
382 if (decl && !TREE_USED (decl))
384 /* We invoke build_call directly for several library
385 functions. These may have been declared normally if
386 we're building libgcc, so we can't just check
387 DECL_ARTIFICIAL. */
388 gcc_assert (DECL_ARTIFICIAL (decl)
389 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
390 "__", 2));
391 mark_used (decl);
394 require_complete_eh_spec_types (fntype, decl);
396 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
398 /* Don't pass empty class objects by value. This is useful
399 for tags in STL, which are used to control overload resolution.
400 We don't need to handle other cases of copying empty classes. */
401 if (!decl || !fndecl_built_in_p (decl))
402 for (i = 0; i < n; i++)
404 tree arg = CALL_EXPR_ARG (function, i);
405 if (is_empty_class (TREE_TYPE (arg))
406 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
408 while (TREE_CODE (arg) == TARGET_EXPR)
409 /* We're disconnecting the initializer from its target,
410 don't create a temporary. */
411 arg = TARGET_EXPR_INITIAL (arg);
412 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
413 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
414 CALL_EXPR_ARG (function, i) = arg;
418 return function;
421 /* New overloading code. */
423 struct z_candidate;
425 struct candidate_warning {
426 z_candidate *loser;
427 candidate_warning *next;
430 /* Information for providing diagnostics about why overloading failed. */
432 enum rejection_reason_code {
433 rr_none,
434 rr_arity,
435 rr_explicit_conversion,
436 rr_template_conversion,
437 rr_arg_conversion,
438 rr_bad_arg_conversion,
439 rr_template_unification,
440 rr_invalid_copy,
441 rr_inherited_ctor,
442 rr_constraint_failure
445 struct conversion_info {
446 /* The index of the argument, 0-based. */
447 int n_arg;
448 /* The actual argument or its type. */
449 tree from;
450 /* The type of the parameter. */
451 tree to_type;
452 /* The location of the argument. */
453 location_t loc;
456 struct rejection_reason {
457 enum rejection_reason_code code;
458 union {
459 /* Information about an arity mismatch. */
460 struct {
461 /* The expected number of arguments. */
462 int expected;
463 /* The actual number of arguments in the call. */
464 int actual;
465 /* Whether EXPECTED should be treated as a lower bound. */
466 bool least_p;
467 } arity;
468 /* Information about an argument conversion mismatch. */
469 struct conversion_info conversion;
470 /* Same, but for bad argument conversions. */
471 struct conversion_info bad_conversion;
472 /* Information about template unification failures. These are the
473 parameters passed to fn_type_unification. */
474 struct {
475 tree tmpl;
476 tree explicit_targs;
477 int num_targs;
478 const tree *args;
479 unsigned int nargs;
480 tree return_type;
481 unification_kind_t strict;
482 int flags;
483 } template_unification;
484 /* Information about template instantiation failures. These are the
485 parameters passed to instantiate_template. */
486 struct {
487 tree tmpl;
488 tree targs;
489 } template_instantiation;
490 } u;
493 struct z_candidate {
494 /* The FUNCTION_DECL that will be called if this candidate is
495 selected by overload resolution. */
496 tree fn;
497 /* If not NULL_TREE, the first argument to use when calling this
498 function. */
499 tree first_arg;
500 /* The rest of the arguments to use when calling this function. If
501 there are no further arguments this may be NULL or it may be an
502 empty vector. */
503 const vec<tree, va_gc> *args;
504 /* The implicit conversion sequences for each of the arguments to
505 FN. */
506 conversion **convs;
507 /* The number of implicit conversion sequences. */
508 size_t num_convs;
509 /* If FN is a user-defined conversion, the standard conversion
510 sequence from the type returned by FN to the desired destination
511 type. */
512 conversion *second_conv;
513 struct rejection_reason *reason;
514 /* If FN is a member function, the binfo indicating the path used to
515 qualify the name of FN at the call site. This path is used to
516 determine whether or not FN is accessible if it is selected by
517 overload resolution. The DECL_CONTEXT of FN will always be a
518 (possibly improper) base of this binfo. */
519 tree access_path;
520 /* If FN is a non-static member function, the binfo indicating the
521 subobject to which the `this' pointer should be converted if FN
522 is selected by overload resolution. The type pointed to by
523 the `this' pointer must correspond to the most derived class
524 indicated by the CONVERSION_PATH. */
525 tree conversion_path;
526 tree template_decl;
527 tree explicit_targs;
528 candidate_warning *warnings;
529 z_candidate *next;
530 int viable;
532 /* The flags active in add_candidate. */
533 int flags;
535 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
536 bool reversed () const { return (flags & LOOKUP_REVERSED); }
539 /* Returns true iff T is a null pointer constant in the sense of
540 [conv.ptr]. */
542 bool
543 null_ptr_cst_p (tree t)
545 tree type = TREE_TYPE (t);
547 /* [conv.ptr]
549 A null pointer constant is an integer literal ([lex.icon]) with value
550 zero or a prvalue of type std::nullptr_t. */
551 if (NULLPTR_TYPE_P (type))
552 return true;
554 if (cxx_dialect >= cxx11)
556 STRIP_ANY_LOCATION_WRAPPER (t);
558 /* Core issue 903 says only literal 0 is a null pointer constant. */
559 if (TREE_CODE (t) == INTEGER_CST
560 && !TREE_OVERFLOW (t)
561 && TREE_CODE (type) == INTEGER_TYPE
562 && integer_zerop (t)
563 && !char_type_p (type))
564 return true;
566 else if (CP_INTEGRAL_TYPE_P (type))
568 t = fold_non_dependent_expr (t, tf_none);
569 STRIP_NOPS (t);
570 if (integer_zerop (t) && !TREE_OVERFLOW (t))
571 return true;
574 return false;
577 /* Returns true iff T is a null member pointer value (4.11). */
579 bool
580 null_member_pointer_value_p (tree t)
582 tree type = TREE_TYPE (t);
583 if (!type)
584 return false;
585 else if (TYPE_PTRMEMFUNC_P (type))
586 return (TREE_CODE (t) == CONSTRUCTOR
587 && CONSTRUCTOR_NELTS (t)
588 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
589 else if (TYPE_PTRDATAMEM_P (type))
590 return integer_all_onesp (t);
591 else
592 return false;
595 /* Returns nonzero if PARMLIST consists of only default parms,
596 ellipsis, and/or undeduced parameter packs. */
598 bool
599 sufficient_parms_p (const_tree parmlist)
601 for (; parmlist && parmlist != void_list_node;
602 parmlist = TREE_CHAIN (parmlist))
603 if (!TREE_PURPOSE (parmlist)
604 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
605 return false;
606 return true;
609 /* Allocate N bytes of memory from the conversion obstack. The memory
610 is zeroed before being returned. */
612 static void *
613 conversion_obstack_alloc (size_t n)
615 void *p;
616 if (!conversion_obstack_initialized)
618 gcc_obstack_init (&conversion_obstack);
619 conversion_obstack_initialized = true;
621 p = obstack_alloc (&conversion_obstack, n);
622 memset (p, 0, n);
623 return p;
626 /* RAII class to discard anything added to conversion_obstack. */
628 struct conversion_obstack_sentinel
630 void *p;
631 conversion_obstack_sentinel (): p (conversion_obstack_alloc (0)) {}
632 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
635 /* Allocate rejection reasons. */
637 static struct rejection_reason *
638 alloc_rejection (enum rejection_reason_code code)
640 struct rejection_reason *p;
641 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
642 p->code = code;
643 return p;
646 static struct rejection_reason *
647 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
649 struct rejection_reason *r = alloc_rejection (rr_arity);
650 int adjust = first_arg != NULL_TREE;
651 r->u.arity.expected = expected - adjust;
652 r->u.arity.actual = actual - adjust;
653 r->u.arity.least_p = least_p;
654 return r;
657 static struct rejection_reason *
658 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
659 location_t loc)
661 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
662 int adjust = first_arg != NULL_TREE;
663 r->u.conversion.n_arg = n_arg - adjust;
664 r->u.conversion.from = from;
665 r->u.conversion.to_type = to;
666 r->u.conversion.loc = loc;
667 return r;
670 static struct rejection_reason *
671 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
672 location_t loc)
674 struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
675 int adjust = first_arg != NULL_TREE;
676 r->u.bad_conversion.n_arg = n_arg - adjust;
677 r->u.bad_conversion.from = from;
678 r->u.bad_conversion.to_type = to;
679 r->u.bad_conversion.loc = loc;
680 return r;
683 static struct rejection_reason *
684 explicit_conversion_rejection (tree from, tree to)
686 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
687 r->u.conversion.n_arg = 0;
688 r->u.conversion.from = from;
689 r->u.conversion.to_type = to;
690 r->u.conversion.loc = UNKNOWN_LOCATION;
691 return r;
694 static struct rejection_reason *
695 template_conversion_rejection (tree from, tree to)
697 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
698 r->u.conversion.n_arg = 0;
699 r->u.conversion.from = from;
700 r->u.conversion.to_type = to;
701 r->u.conversion.loc = UNKNOWN_LOCATION;
702 return r;
705 static struct rejection_reason *
706 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
707 const tree *args, unsigned int nargs,
708 tree return_type, unification_kind_t strict,
709 int flags)
711 size_t args_n_bytes = sizeof (*args) * nargs;
712 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
713 struct rejection_reason *r = alloc_rejection (rr_template_unification);
714 r->u.template_unification.tmpl = tmpl;
715 r->u.template_unification.explicit_targs = explicit_targs;
716 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
717 /* Copy args to our own storage. */
718 memcpy (args1, args, args_n_bytes);
719 r->u.template_unification.args = args1;
720 r->u.template_unification.nargs = nargs;
721 r->u.template_unification.return_type = return_type;
722 r->u.template_unification.strict = strict;
723 r->u.template_unification.flags = flags;
724 return r;
727 static struct rejection_reason *
728 template_unification_error_rejection (void)
730 return alloc_rejection (rr_template_unification);
733 static struct rejection_reason *
734 invalid_copy_with_fn_template_rejection (void)
736 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
737 return r;
740 static struct rejection_reason *
741 inherited_ctor_rejection (void)
743 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
744 return r;
747 /* Build a constraint failure record. */
749 static struct rejection_reason *
750 constraint_failure (void)
752 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
753 return r;
756 /* Dynamically allocate a conversion. */
758 static conversion *
759 alloc_conversion (conversion_kind kind)
761 conversion *c;
762 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
763 c->kind = kind;
764 return c;
767 /* Make sure that all memory on the conversion obstack has been
768 freed. */
770 void
771 validate_conversion_obstack (void)
773 if (conversion_obstack_initialized)
774 gcc_assert ((obstack_next_free (&conversion_obstack)
775 == obstack_base (&conversion_obstack)));
778 /* Dynamically allocate an array of N conversions. */
780 static conversion **
781 alloc_conversions (size_t n)
783 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
786 /* True iff the active member of conversion::u for code CODE is NEXT. */
788 static inline bool
789 has_next (conversion_kind code)
791 return !(code == ck_identity
792 || code == ck_ambig
793 || code == ck_list
794 || code == ck_aggr
795 || code == ck_deferred_bad);
798 static conversion *
799 build_conv (conversion_kind code, tree type, conversion *from)
801 conversion *t;
802 conversion_rank rank = CONVERSION_RANK (from);
804 /* Only call this function for conversions that use u.next. */
805 gcc_assert (from == NULL || has_next (code));
807 /* Note that the caller is responsible for filling in t->cand for
808 user-defined conversions. */
809 t = alloc_conversion (code);
810 t->type = type;
811 t->u.next = from;
813 switch (code)
815 case ck_ptr:
816 case ck_pmem:
817 case ck_base:
818 case ck_std:
819 if (rank < cr_std)
820 rank = cr_std;
821 break;
823 case ck_qual:
824 case ck_fnptr:
825 if (rank < cr_exact)
826 rank = cr_exact;
827 break;
829 default:
830 break;
832 t->rank = rank;
833 t->user_conv_p = (code == ck_user || from->user_conv_p);
834 t->bad_p = from->bad_p;
835 t->base_p = false;
836 return t;
839 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
840 specialization of std::initializer_list<T>, if such a conversion is
841 possible. */
843 static conversion *
844 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
846 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
847 unsigned len = CONSTRUCTOR_NELTS (ctor);
848 conversion **subconvs = alloc_conversions (len);
849 conversion *t;
850 unsigned i;
851 tree val;
853 /* Within a list-initialization we can have more user-defined
854 conversions. */
855 flags &= ~LOOKUP_NO_CONVERSION;
856 /* But no narrowing conversions. */
857 flags |= LOOKUP_NO_NARROWING;
859 /* Can't make an array of these types. */
860 if (TYPE_REF_P (elttype)
861 || TREE_CODE (elttype) == FUNCTION_TYPE
862 || VOID_TYPE_P (elttype))
863 return NULL;
865 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
867 conversion *sub
868 = implicit_conversion (elttype, TREE_TYPE (val), val,
869 false, flags, complain);
870 if (sub == NULL)
871 return NULL;
873 subconvs[i] = sub;
876 t = alloc_conversion (ck_list);
877 t->type = type;
878 t->u.list = subconvs;
879 t->rank = cr_exact;
881 for (i = 0; i < len; ++i)
883 conversion *sub = subconvs[i];
884 if (sub->rank > t->rank)
885 t->rank = sub->rank;
886 if (sub->user_conv_p)
887 t->user_conv_p = true;
888 if (sub->bad_p)
889 t->bad_p = true;
892 return t;
895 /* Return the next conversion of the conversion chain (if applicable),
896 or NULL otherwise. Please use this function instead of directly
897 accessing fields of struct conversion. */
899 static conversion *
900 next_conversion (conversion *conv)
902 if (conv == NULL
903 || !has_next (conv->kind))
904 return NULL;
905 return conv->u.next;
908 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
909 encountered. */
911 static conversion *
912 strip_standard_conversion (conversion *conv)
914 while (conv
915 && conv->kind != ck_user
916 && has_next (conv->kind))
917 conv = next_conversion (conv);
918 return conv;
921 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
922 initializer for array type ATYPE. */
924 static bool
925 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
927 tree elttype = TREE_TYPE (atype);
928 unsigned i;
930 if (TREE_CODE (from) == CONSTRUCTOR)
932 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
934 tree val = CONSTRUCTOR_ELT (from, i)->value;
935 bool ok;
936 if (TREE_CODE (elttype) == ARRAY_TYPE)
937 ok = can_convert_array (elttype, val, flags, complain);
938 else
939 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
940 complain);
941 if (!ok)
942 return false;
944 return true;
947 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
948 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
949 return array_string_literal_compatible_p (atype, from);
951 /* No other valid way to aggregate initialize an array. */
952 return false;
955 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
956 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
957 is in PSET. */
959 static bool
960 field_in_pset (hash_set<tree, true> &pset, tree field)
962 if (pset.contains (field))
963 return true;
964 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
965 for (field = TYPE_FIELDS (TREE_TYPE (field));
966 field; field = DECL_CHAIN (field))
968 field = next_aggregate_field (field);
969 if (field == NULL_TREE)
970 break;
971 if (field_in_pset (pset, field))
972 return true;
974 return false;
977 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
978 aggregate class, if such a conversion is possible. */
980 static conversion *
981 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
983 unsigned HOST_WIDE_INT i = 0;
984 conversion *c;
985 tree field = next_aggregate_field (TYPE_FIELDS (type));
986 tree empty_ctor = NULL_TREE;
987 hash_set<tree, true> pset;
989 /* We already called reshape_init in implicit_conversion, but it might not
990 have done anything in the case of parenthesized aggr init. */
992 /* The conversions within the init-list aren't affected by the enclosing
993 context; they're always simple copy-initialization. */
994 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
996 /* For designated initializers, verify that each initializer is convertible
997 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
998 visited. In the following loop then ignore already visited
999 FIELD_DECLs. */
1000 tree idx, val;
1001 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1003 if (!idx)
1004 break;
1006 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1008 tree ftype = TREE_TYPE (idx);
1009 bool ok;
1011 if (TREE_CODE (ftype) == ARRAY_TYPE)
1012 ok = can_convert_array (ftype, val, flags, complain);
1013 else
1014 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1015 complain);
1017 if (!ok)
1018 return NULL;
1020 /* For unions, there should be just one initializer. */
1021 if (TREE_CODE (type) == UNION_TYPE)
1023 field = NULL_TREE;
1024 i = 1;
1025 break;
1027 pset.add (idx);
1030 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1032 tree ftype = TREE_TYPE (field);
1033 bool ok;
1035 if (!pset.is_empty () && field_in_pset (pset, field))
1036 continue;
1037 if (i < CONSTRUCTOR_NELTS (ctor))
1039 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1040 gcc_checking_assert (!ce->index);
1041 val = ce->value;
1042 ++i;
1044 else if (DECL_INITIAL (field))
1045 val = get_nsdmi (field, /*ctor*/false, complain);
1046 else if (TYPE_REF_P (ftype))
1047 /* Value-initialization of reference is ill-formed. */
1048 return NULL;
1049 else
1051 if (empty_ctor == NULL_TREE)
1052 empty_ctor = build_constructor (init_list_type_node, NULL);
1053 val = empty_ctor;
1056 if (TREE_CODE (ftype) == ARRAY_TYPE)
1057 ok = can_convert_array (ftype, val, flags, complain);
1058 else
1059 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1060 complain);
1062 if (!ok)
1063 return NULL;
1065 if (TREE_CODE (type) == UNION_TYPE)
1066 break;
1069 if (i < CONSTRUCTOR_NELTS (ctor))
1070 return NULL;
1072 c = alloc_conversion (ck_aggr);
1073 c->type = type;
1074 c->rank = cr_exact;
1075 c->user_conv_p = true;
1076 c->check_narrowing = true;
1077 c->u.expr = ctor;
1078 return c;
1081 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1082 array type, if such a conversion is possible. */
1084 static conversion *
1085 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1087 conversion *c;
1088 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1089 tree elttype = TREE_TYPE (type);
1090 bool bad = false;
1091 bool user = false;
1092 enum conversion_rank rank = cr_exact;
1094 /* We might need to propagate the size from the element to the array. */
1095 complete_type (type);
1097 if (TYPE_DOMAIN (type)
1098 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1100 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1101 if (alen < len)
1102 return NULL;
1105 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1107 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1109 conversion *sub
1110 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1111 false, flags, complain);
1112 if (sub == NULL)
1113 return NULL;
1115 if (sub->rank > rank)
1116 rank = sub->rank;
1117 if (sub->user_conv_p)
1118 user = true;
1119 if (sub->bad_p)
1120 bad = true;
1123 c = alloc_conversion (ck_aggr);
1124 c->type = type;
1125 c->rank = rank;
1126 c->user_conv_p = user;
1127 c->bad_p = bad;
1128 c->u.expr = ctor;
1129 return c;
1132 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1133 complex type, if such a conversion is possible. */
1135 static conversion *
1136 build_complex_conv (tree type, tree ctor, int flags,
1137 tsubst_flags_t complain)
1139 conversion *c;
1140 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1141 tree elttype = TREE_TYPE (type);
1142 bool bad = false;
1143 bool user = false;
1144 enum conversion_rank rank = cr_exact;
1146 if (len != 2)
1147 return NULL;
1149 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1151 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1153 conversion *sub
1154 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1155 false, flags, complain);
1156 if (sub == NULL)
1157 return NULL;
1159 if (sub->rank > rank)
1160 rank = sub->rank;
1161 if (sub->user_conv_p)
1162 user = true;
1163 if (sub->bad_p)
1164 bad = true;
1167 c = alloc_conversion (ck_aggr);
1168 c->type = type;
1169 c->rank = rank;
1170 c->user_conv_p = user;
1171 c->bad_p = bad;
1172 c->u.expr = ctor;
1173 return c;
1176 /* Build a representation of the identity conversion from EXPR to
1177 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1179 static conversion *
1180 build_identity_conv (tree type, tree expr)
1182 conversion *c;
1184 c = alloc_conversion (ck_identity);
1185 c->type = type;
1186 c->u.expr = expr;
1188 return c;
1191 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1192 were multiple user-defined conversions to accomplish the job.
1193 Build a conversion that indicates that ambiguity. */
1195 static conversion *
1196 build_ambiguous_conv (tree type, tree expr)
1198 conversion *c;
1200 c = alloc_conversion (ck_ambig);
1201 c->type = type;
1202 c->u.expr = expr;
1204 return c;
1207 tree
1208 strip_top_quals (tree t)
1210 if (TREE_CODE (t) == ARRAY_TYPE)
1211 return t;
1212 return cp_build_qualified_type (t, 0);
1215 /* Returns the standard conversion path (see [conv]) from type FROM to type
1216 TO, if any. For proper handling of null pointer constants, you must
1217 also pass the expression EXPR to convert from. If C_CAST_P is true,
1218 this conversion is coming from a C-style cast. */
1220 static conversion *
1221 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1222 int flags, tsubst_flags_t complain)
1224 enum tree_code fcode, tcode;
1225 conversion *conv;
1226 bool fromref = false;
1227 tree qualified_to;
1229 to = non_reference (to);
1230 if (TYPE_REF_P (from))
1232 fromref = true;
1233 from = TREE_TYPE (from);
1235 qualified_to = to;
1236 to = strip_top_quals (to);
1237 from = strip_top_quals (from);
1239 if (expr && type_unknown_p (expr))
1241 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1243 tsubst_flags_t tflags = tf_conv;
1244 expr = instantiate_type (to, expr, tflags);
1245 if (expr == error_mark_node)
1246 return NULL;
1247 from = TREE_TYPE (expr);
1249 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1251 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1252 expr = resolve_nondeduced_context (expr, complain);
1253 from = TREE_TYPE (expr);
1257 fcode = TREE_CODE (from);
1258 tcode = TREE_CODE (to);
1260 conv = build_identity_conv (from, expr);
1261 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1263 from = type_decays_to (from);
1264 fcode = TREE_CODE (from);
1265 /* Tell convert_like that we're using the address. */
1266 conv->rvaluedness_matches_p = true;
1267 conv = build_conv (ck_lvalue, from, conv);
1269 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1270 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1271 express the copy constructor call required by copy-initialization. */
1272 else if (fromref || (expr && obvalue_p (expr)))
1274 if (expr)
1276 tree bitfield_type;
1277 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1278 if (bitfield_type)
1280 from = strip_top_quals (bitfield_type);
1281 fcode = TREE_CODE (from);
1284 conv = build_conv (ck_rvalue, from, conv);
1285 /* If we're performing copy-initialization, remember to skip
1286 explicit constructors. */
1287 if (flags & LOOKUP_ONLYCONVERTING)
1288 conv->copy_init_p = true;
1291 /* Allow conversion between `__complex__' data types. */
1292 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1294 /* The standard conversion sequence to convert FROM to TO is
1295 the standard conversion sequence to perform componentwise
1296 conversion. */
1297 conversion *part_conv = standard_conversion
1298 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1299 complain);
1301 if (!part_conv)
1302 conv = NULL;
1303 else if (part_conv->kind == ck_identity)
1304 /* Leave conv alone. */;
1305 else
1307 conv = build_conv (part_conv->kind, to, conv);
1308 conv->rank = part_conv->rank;
1311 return conv;
1314 if (same_type_p (from, to))
1316 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1317 conv->type = qualified_to;
1318 return conv;
1321 /* [conv.ptr]
1322 A null pointer constant can be converted to a pointer type; ... A
1323 null pointer constant of integral type can be converted to an
1324 rvalue of type std::nullptr_t. */
1325 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1326 || NULLPTR_TYPE_P (to))
1327 && ((expr && null_ptr_cst_p (expr))
1328 || NULLPTR_TYPE_P (from)))
1329 conv = build_conv (ck_std, to, conv);
1330 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1331 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1333 /* For backwards brain damage compatibility, allow interconversion of
1334 pointers and integers with a pedwarn. */
1335 conv = build_conv (ck_std, to, conv);
1336 conv->bad_p = true;
1338 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1340 /* For backwards brain damage compatibility, allow interconversion of
1341 enums and integers with a pedwarn. */
1342 conv = build_conv (ck_std, to, conv);
1343 conv->bad_p = true;
1345 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1346 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1348 tree to_pointee;
1349 tree from_pointee;
1351 if (tcode == POINTER_TYPE)
1353 to_pointee = TREE_TYPE (to);
1354 from_pointee = TREE_TYPE (from);
1356 /* Since this is the target of a pointer, it can't have function
1357 qualifiers, so any TYPE_QUALS must be for attributes const or
1358 noreturn. Strip them. */
1359 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1360 && TYPE_QUALS (to_pointee))
1361 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1362 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1363 && TYPE_QUALS (from_pointee))
1364 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1366 else
1368 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1369 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1372 if (tcode == POINTER_TYPE
1373 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1374 to_pointee))
1376 else if (VOID_TYPE_P (to_pointee)
1377 && !TYPE_PTRDATAMEM_P (from)
1378 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1380 tree nfrom = TREE_TYPE (from);
1381 /* Don't try to apply restrict to void. */
1382 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1383 from_pointee = cp_build_qualified_type (void_type_node, quals);
1384 from = build_pointer_type (from_pointee);
1385 conv = build_conv (ck_ptr, from, conv);
1387 else if (TYPE_PTRDATAMEM_P (from))
1389 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1390 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1392 if (same_type_p (fbase, tbase))
1393 /* No base conversion needed. */;
1394 else if (DERIVED_FROM_P (fbase, tbase)
1395 && (same_type_ignoring_top_level_qualifiers_p
1396 (from_pointee, to_pointee)))
1398 from = build_ptrmem_type (tbase, from_pointee);
1399 conv = build_conv (ck_pmem, from, conv);
1401 else
1402 return NULL;
1404 else if (CLASS_TYPE_P (from_pointee)
1405 && CLASS_TYPE_P (to_pointee)
1406 /* [conv.ptr]
1408 An rvalue of type "pointer to cv D," where D is a
1409 class type, can be converted to an rvalue of type
1410 "pointer to cv B," where B is a base class (clause
1411 _class.derived_) of D. If B is an inaccessible
1412 (clause _class.access_) or ambiguous
1413 (_class.member.lookup_) base class of D, a program
1414 that necessitates this conversion is ill-formed.
1415 Therefore, we use DERIVED_FROM_P, and do not check
1416 access or uniqueness. */
1417 && DERIVED_FROM_P (to_pointee, from_pointee))
1419 from_pointee
1420 = cp_build_qualified_type (to_pointee,
1421 cp_type_quals (from_pointee));
1422 from = build_pointer_type (from_pointee);
1423 conv = build_conv (ck_ptr, from, conv);
1424 conv->base_p = true;
1427 if (same_type_p (from, to))
1428 /* OK */;
1429 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1430 /* In a C-style cast, we ignore CV-qualification because we
1431 are allowed to perform a static_cast followed by a
1432 const_cast. */
1433 conv = build_conv (ck_qual, to, conv);
1434 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1435 conv = build_conv (ck_qual, to, conv);
1436 else if (expr && string_conv_p (to, expr, 0))
1437 /* converting from string constant to char *. */
1438 conv = build_conv (ck_qual, to, conv);
1439 else if (fnptr_conv_p (to, from))
1440 conv = build_conv (ck_fnptr, to, conv);
1441 /* Allow conversions among compatible ObjC pointer types (base
1442 conversions have been already handled above). */
1443 else if (c_dialect_objc ()
1444 && objc_compare_types (to, from, -4, NULL_TREE))
1445 conv = build_conv (ck_ptr, to, conv);
1446 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1448 conv = build_conv (ck_ptr, to, conv);
1449 conv->bad_p = true;
1451 else
1452 return NULL;
1454 from = to;
1456 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1458 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1459 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1460 tree fbase = class_of_this_parm (fromfn);
1461 tree tbase = class_of_this_parm (tofn);
1463 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1464 yields false. But a pointer to member of incomplete class is OK. */
1465 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1466 return NULL;
1468 tree fstat = static_fn_type (fromfn);
1469 tree tstat = static_fn_type (tofn);
1470 if (same_type_p (tstat, fstat)
1471 || fnptr_conv_p (tstat, fstat))
1472 /* OK */;
1473 else
1474 return NULL;
1476 if (!same_type_p (fbase, tbase))
1478 from = build_memfn_type (fstat,
1479 tbase,
1480 cp_type_quals (tbase),
1481 type_memfn_rqual (tofn));
1482 from = build_ptrmemfunc_type (build_pointer_type (from));
1483 conv = build_conv (ck_pmem, from, conv);
1484 conv->base_p = true;
1486 if (fnptr_conv_p (tstat, fstat))
1487 conv = build_conv (ck_fnptr, to, conv);
1489 else if (tcode == BOOLEAN_TYPE)
1491 /* [conv.bool]
1493 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1494 to member type can be converted to a prvalue of type bool. ...
1495 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1496 std::nullptr_t can be converted to a prvalue of type bool; */
1497 if (ARITHMETIC_TYPE_P (from)
1498 || UNSCOPED_ENUM_P (from)
1499 || fcode == POINTER_TYPE
1500 || TYPE_PTRMEM_P (from)
1501 || NULLPTR_TYPE_P (from))
1503 conv = build_conv (ck_std, to, conv);
1504 if (fcode == POINTER_TYPE
1505 || TYPE_PTRDATAMEM_P (from)
1506 || (TYPE_PTRMEMFUNC_P (from)
1507 && conv->rank < cr_pbool)
1508 || NULLPTR_TYPE_P (from))
1509 conv->rank = cr_pbool;
1510 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1511 conv->bad_p = true;
1512 if (flags & LOOKUP_NO_NARROWING)
1513 conv->check_narrowing = true;
1514 return conv;
1517 return NULL;
1519 /* We don't check for ENUMERAL_TYPE here because there are no standard
1520 conversions to enum type. */
1521 /* As an extension, allow conversion to complex type. */
1522 else if (ARITHMETIC_TYPE_P (to))
1524 if (! (INTEGRAL_CODE_P (fcode)
1525 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1526 || SCOPED_ENUM_P (from))
1527 return NULL;
1529 /* If we're parsing an enum with no fixed underlying type, we're
1530 dealing with an incomplete type, which renders the conversion
1531 ill-formed. */
1532 if (!COMPLETE_TYPE_P (from))
1533 return NULL;
1535 conv = build_conv (ck_std, to, conv);
1537 tree underlying_type = NULL_TREE;
1538 if (TREE_CODE (from) == ENUMERAL_TYPE
1539 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1540 underlying_type = ENUM_UNDERLYING_TYPE (from);
1542 /* Give this a better rank if it's a promotion.
1544 To handle CWG 1601, also bump the rank if we are converting
1545 an enumeration with a fixed underlying type to the underlying
1546 type. */
1547 if ((same_type_p (to, type_promotes_to (from))
1548 || (underlying_type && same_type_p (to, underlying_type)))
1549 && next_conversion (conv)->rank <= cr_promotion)
1550 conv->rank = cr_promotion;
1552 /* A prvalue of floating-point type can be converted to a prvalue of
1553 another floating-point type with a greater or equal conversion
1554 rank ([conv.rank]). A prvalue of standard floating-point type can
1555 be converted to a prvalue of another standard floating-point type.
1556 For backwards compatibility with handling __float128 and other
1557 non-standard floating point types, allow all implicit floating
1558 point conversions if neither type is extended floating-point
1559 type and if at least one of them is, fail if they have unordered
1560 conversion rank or from has higher conversion rank. */
1561 if (fcode == REAL_TYPE
1562 && tcode == REAL_TYPE
1563 && (extended_float_type_p (from)
1564 || extended_float_type_p (to))
1565 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1566 conv->bad_p = true;
1568 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1569 && vector_types_convertible_p (from, to, false))
1570 return build_conv (ck_std, to, conv);
1571 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1572 && is_properly_derived_from (from, to))
1574 if (conv->kind == ck_rvalue)
1575 conv = next_conversion (conv);
1576 conv = build_conv (ck_base, to, conv);
1577 /* The derived-to-base conversion indicates the initialization
1578 of a parameter with base type from an object of a derived
1579 type. A temporary object is created to hold the result of
1580 the conversion unless we're binding directly to a reference. */
1581 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1582 /* If we're performing copy-initialization, remember to skip
1583 explicit constructors. */
1584 if (flags & LOOKUP_ONLYCONVERTING)
1585 conv->copy_init_p = true;
1587 else
1588 return NULL;
1590 if (flags & LOOKUP_NO_NARROWING)
1591 conv->check_narrowing = true;
1593 return conv;
1596 /* Returns nonzero if T1 is reference-related to T2. */
1598 bool
1599 reference_related_p (tree t1, tree t2)
1601 if (t1 == error_mark_node || t2 == error_mark_node)
1602 return false;
1604 t1 = TYPE_MAIN_VARIANT (t1);
1605 t2 = TYPE_MAIN_VARIANT (t2);
1607 /* [dcl.init.ref]
1609 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1610 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1611 return (similar_type_p (t1, t2)
1612 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1613 && DERIVED_FROM_P (t1, t2)));
1616 /* Returns nonzero if T1 is reference-compatible with T2. */
1618 bool
1619 reference_compatible_p (tree t1, tree t2)
1621 /* [dcl.init.ref]
1623 "cv1 T1" is reference compatible with "cv2 T2" if
1624 a prvalue of type "pointer to cv2 T2" can be converted to the type
1625 "pointer to cv1 T1" via a standard conversion sequence. */
1626 tree ptype1 = build_pointer_type (t1);
1627 tree ptype2 = build_pointer_type (t2);
1628 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1629 /*c_cast_p=*/false, 0, tf_none);
1630 if (!conv || conv->bad_p)
1631 return false;
1632 return true;
1635 /* Return true if converting FROM to TO would involve a qualification
1636 conversion. */
1638 static bool
1639 involves_qualification_conversion_p (tree to, tree from)
1641 /* If we're not convering a pointer to another one, we won't get
1642 a qualification conversion. */
1643 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1644 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1645 return false;
1647 conversion *conv = standard_conversion (to, from, NULL_TREE,
1648 /*c_cast_p=*/false, 0, tf_none);
1649 for (conversion *t = conv; t; t = next_conversion (t))
1650 if (t->kind == ck_qual)
1651 return true;
1653 return false;
1656 /* A reference of the indicated TYPE is being bound directly to the
1657 expression represented by the implicit conversion sequence CONV.
1658 Return a conversion sequence for this binding. */
1660 static conversion *
1661 direct_reference_binding (tree type, conversion *conv)
1663 tree t;
1665 gcc_assert (TYPE_REF_P (type));
1666 gcc_assert (!TYPE_REF_P (conv->type));
1668 t = TREE_TYPE (type);
1670 if (conv->kind == ck_identity)
1671 /* Mark the identity conv as to not decay to rvalue. */
1672 conv->rvaluedness_matches_p = true;
1674 /* [over.ics.rank]
1676 When a parameter of reference type binds directly
1677 (_dcl.init.ref_) to an argument expression, the implicit
1678 conversion sequence is the identity conversion, unless the
1679 argument expression has a type that is a derived class of the
1680 parameter type, in which case the implicit conversion sequence is
1681 a derived-to-base Conversion.
1683 If the parameter binds directly to the result of applying a
1684 conversion function to the argument expression, the implicit
1685 conversion sequence is a user-defined conversion sequence
1686 (_over.ics.user_), with the second standard conversion sequence
1687 either an identity conversion or, if the conversion function
1688 returns an entity of a type that is a derived class of the
1689 parameter type, a derived-to-base conversion. */
1690 if (is_properly_derived_from (conv->type, t))
1692 /* Represent the derived-to-base conversion. */
1693 conv = build_conv (ck_base, t, conv);
1694 /* We will actually be binding to the base-class subobject in
1695 the derived class, so we mark this conversion appropriately.
1696 That way, convert_like knows not to generate a temporary. */
1697 conv->need_temporary_p = false;
1699 else if (involves_qualification_conversion_p (t, conv->type))
1700 /* Represent the qualification conversion. After DR 2352
1701 #1 and #2 were indistinguishable conversion sequences:
1703 void f(int*); // #1
1704 void f(const int* const &); // #2
1705 void g(int* p) { f(p); }
1707 because the types "int *" and "const int *const" are
1708 reference-related and we were binding both directly and they
1709 had the same rank. To break it up, we add a ck_qual under the
1710 ck_ref_bind so that conversion sequence ranking chooses #1.
1712 We strip_top_quals here which is also what standard_conversion
1713 does. Failure to do so would confuse comp_cv_qual_signature
1714 into thinking that in
1716 void f(const int * const &); // #1
1717 void f(const int *); // #2
1718 int *x;
1719 f(x);
1721 #2 is a better match than #1 even though they're ambiguous (97296). */
1722 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1724 return build_conv (ck_ref_bind, type, conv);
1727 /* Returns the conversion path from type FROM to reference type TO for
1728 purposes of reference binding. For lvalue binding, either pass a
1729 reference type to FROM or an lvalue expression to EXPR. If the
1730 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1731 the conversion returned. If C_CAST_P is true, this
1732 conversion is coming from a C-style cast. */
1734 static conversion *
1735 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1736 tsubst_flags_t complain)
1738 conversion *conv = NULL;
1739 tree to = TREE_TYPE (rto);
1740 tree from = rfrom;
1741 tree tfrom;
1742 bool related_p;
1743 bool compatible_p;
1744 cp_lvalue_kind gl_kind;
1745 bool is_lvalue;
1747 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1749 expr = instantiate_type (to, expr, tf_none);
1750 if (expr == error_mark_node)
1751 return NULL;
1752 from = TREE_TYPE (expr);
1755 bool copy_list_init = false;
1756 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1758 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1759 /* DR 1288: Otherwise, if the initializer list has a single element
1760 of type E and ... [T's] referenced type is reference-related to E,
1761 the object or reference is initialized from that element...
1763 ??? With P0388R4, we should bind 't' directly to U{}:
1764 using U = A[2];
1765 A (&&t)[] = {U{}};
1766 because A[] and A[2] are reference-related. But we don't do it
1767 because grok_reference_init has deduced the array size (to 1), and
1768 A[1] and A[2] aren't reference-related. */
1769 if (CONSTRUCTOR_NELTS (expr) == 1
1770 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1772 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1773 if (error_operand_p (elt))
1774 return NULL;
1775 tree etype = TREE_TYPE (elt);
1776 if (reference_related_p (to, etype))
1778 expr = elt;
1779 from = etype;
1780 goto skip;
1783 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1784 referenced by T is copy-list-initialized, and the reference is bound
1785 to that temporary. */
1786 copy_list_init = true;
1787 skip:;
1790 if (TYPE_REF_P (from))
1792 from = TREE_TYPE (from);
1793 if (!TYPE_REF_IS_RVALUE (rfrom)
1794 || TREE_CODE (from) == FUNCTION_TYPE)
1795 gl_kind = clk_ordinary;
1796 else
1797 gl_kind = clk_rvalueref;
1799 else if (expr)
1800 gl_kind = lvalue_kind (expr);
1801 else if (CLASS_TYPE_P (from)
1802 || TREE_CODE (from) == ARRAY_TYPE)
1803 gl_kind = clk_class;
1804 else
1805 gl_kind = clk_none;
1807 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1808 if ((flags & LOOKUP_NO_TEMP_BIND)
1809 && (gl_kind & clk_class))
1810 gl_kind = clk_none;
1812 /* Same mask as real_lvalue_p. */
1813 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1815 tfrom = from;
1816 if ((gl_kind & clk_bitfield) != 0)
1817 tfrom = unlowered_expr_type (expr);
1819 /* Figure out whether or not the types are reference-related and
1820 reference compatible. We have to do this after stripping
1821 references from FROM. */
1822 related_p = reference_related_p (to, tfrom);
1823 /* If this is a C cast, first convert to an appropriately qualified
1824 type, so that we can later do a const_cast to the desired type. */
1825 if (related_p && c_cast_p
1826 && !at_least_as_qualified_p (to, tfrom))
1827 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1828 compatible_p = reference_compatible_p (to, tfrom);
1830 /* Directly bind reference when target expression's type is compatible with
1831 the reference and expression is an lvalue. In DR391, the wording in
1832 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1833 const and rvalue references to rvalues of compatible class type.
1834 We should also do direct bindings for non-class xvalues. */
1835 if ((related_p || compatible_p) && gl_kind)
1837 /* [dcl.init.ref]
1839 If the initializer expression
1841 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1842 is reference-compatible with "cv2 T2,"
1844 the reference is bound directly to the initializer expression
1845 lvalue.
1847 [...]
1848 If the initializer expression is an rvalue, with T2 a class type,
1849 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1850 is bound to the object represented by the rvalue or to a sub-object
1851 within that object. */
1853 conv = build_identity_conv (tfrom, expr);
1854 conv = direct_reference_binding (rto, conv);
1856 if (TYPE_REF_P (rfrom))
1857 /* Handle rvalue reference to function properly. */
1858 conv->rvaluedness_matches_p
1859 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1860 else
1861 conv->rvaluedness_matches_p
1862 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1864 if ((gl_kind & clk_bitfield) != 0
1865 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1866 /* For the purposes of overload resolution, we ignore the fact
1867 this expression is a bitfield or packed field. (In particular,
1868 [over.ics.ref] says specifically that a function with a
1869 non-const reference parameter is viable even if the
1870 argument is a bitfield.)
1872 However, when we actually call the function we must create
1873 a temporary to which to bind the reference. If the
1874 reference is volatile, or isn't const, then we cannot make
1875 a temporary, so we just issue an error when the conversion
1876 actually occurs. */
1877 conv->need_temporary_p = true;
1879 /* Don't allow binding of lvalues (other than function lvalues) to
1880 rvalue references. */
1881 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1882 && TREE_CODE (to) != FUNCTION_TYPE)
1883 conv->bad_p = true;
1885 /* Nor the reverse. */
1886 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1887 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1888 But in C++23, such an expression is just an xvalue, not a special
1889 lvalue, so the binding is once again ill-formed. */
1890 && !(cxx_dialect <= cxx20
1891 && (gl_kind & clk_implicit_rval))
1892 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1893 || (flags & LOOKUP_NO_RVAL_BIND))
1894 && TREE_CODE (to) != FUNCTION_TYPE)
1895 conv->bad_p = true;
1897 if (!compatible_p)
1898 conv->bad_p = true;
1900 return conv;
1902 /* [class.conv.fct] A conversion function is never used to convert a
1903 (possibly cv-qualified) object to the (possibly cv-qualified) same
1904 object type (or a reference to it), to a (possibly cv-qualified) base
1905 class of that type (or a reference to it).... */
1906 else if (CLASS_TYPE_P (from) && !related_p
1907 && !(flags & LOOKUP_NO_CONVERSION))
1909 /* [dcl.init.ref]
1911 If the initializer expression
1913 -- has a class type (i.e., T2 is a class type) can be
1914 implicitly converted to an lvalue of type "cv3 T3," where
1915 "cv1 T1" is reference-compatible with "cv3 T3". (this
1916 conversion is selected by enumerating the applicable
1917 conversion functions (_over.match.ref_) and choosing the
1918 best one through overload resolution. (_over.match_).
1920 the reference is bound to the lvalue result of the conversion
1921 in the second case. */
1922 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1923 complain);
1924 if (cand)
1925 return cand->second_conv;
1928 /* From this point on, we conceptually need temporaries, even if we
1929 elide them. Only the cases above are "direct bindings". */
1930 if (flags & LOOKUP_NO_TEMP_BIND)
1931 return NULL;
1933 /* [over.ics.rank]
1935 When a parameter of reference type is not bound directly to an
1936 argument expression, the conversion sequence is the one required
1937 to convert the argument expression to the underlying type of the
1938 reference according to _over.best.ics_. Conceptually, this
1939 conversion sequence corresponds to copy-initializing a temporary
1940 of the underlying type with the argument expression. Any
1941 difference in top-level cv-qualification is subsumed by the
1942 initialization itself and does not constitute a conversion. */
1944 bool maybe_valid_p = true;
1946 /* [dcl.init.ref]
1948 Otherwise, the reference shall be an lvalue reference to a
1949 non-volatile const type, or the reference shall be an rvalue
1950 reference. */
1951 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1952 maybe_valid_p = false;
1954 /* [dcl.init.ref]
1956 Otherwise, a temporary of type "cv1 T1" is created and
1957 initialized from the initializer expression using the rules for a
1958 non-reference copy initialization. If T1 is reference-related to
1959 T2, cv1 must be the same cv-qualification as, or greater
1960 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1961 if (related_p && !at_least_as_qualified_p (to, from))
1962 maybe_valid_p = false;
1964 /* We try below to treat an invalid reference binding as a bad conversion
1965 to improve diagnostics, but doing so may cause otherwise unnecessary
1966 instantiations that can lead to a hard error. So during the first pass
1967 of overload resolution wherein we shortcut bad conversions, instead just
1968 produce a special conversion indicating a second pass is necessary if
1969 there's no strictly viable candidate. */
1970 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1972 conv = alloc_conversion (ck_deferred_bad);
1973 conv->bad_p = true;
1974 return conv;
1977 /* We're generating a temporary now, but don't bind any more in the
1978 conversion (specifically, don't slice the temporary returned by a
1979 conversion operator). */
1980 flags |= LOOKUP_NO_TEMP_BIND;
1982 /* Core issue 899: When [copy-]initializing a temporary to be bound
1983 to the first parameter of a copy constructor (12.8) called with
1984 a single argument in the context of direct-initialization,
1985 explicit conversion functions are also considered.
1987 So don't set LOOKUP_ONLYCONVERTING in that case. */
1988 if (!(flags & LOOKUP_COPY_PARM))
1989 flags |= LOOKUP_ONLYCONVERTING;
1991 if (!conv)
1992 conv = implicit_conversion (to, from, expr, c_cast_p,
1993 flags, complain);
1994 if (!conv)
1995 return NULL;
1997 if (conv->user_conv_p)
1999 if (copy_list_init)
2000 /* Remember this was copy-list-initialization. */
2001 conv->need_temporary_p = true;
2003 /* If initializing the temporary used a conversion function,
2004 recalculate the second conversion sequence. */
2005 for (conversion *t = conv; t; t = next_conversion (t))
2006 if (t->kind == ck_user
2007 && DECL_CONV_FN_P (t->cand->fn))
2009 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2010 /* A prvalue of non-class type is cv-unqualified. */
2011 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2012 ftype = cv_unqualified (ftype);
2013 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2014 conversion *new_second
2015 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2016 sflags, complain);
2017 if (!new_second)
2018 return NULL;
2019 conv = merge_conversion_sequences (t, new_second);
2020 gcc_assert (maybe_valid_p || conv->bad_p);
2021 return conv;
2025 conv = build_conv (ck_ref_bind, rto, conv);
2026 /* This reference binding, unlike those above, requires the
2027 creation of a temporary. */
2028 conv->need_temporary_p = true;
2029 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2030 conv->bad_p |= !maybe_valid_p;
2032 return conv;
2035 /* Most of the implementation of implicit_conversion, with the same
2036 parameters. */
2038 static conversion *
2039 implicit_conversion_1 (tree to, tree from, tree expr, bool c_cast_p,
2040 int flags, tsubst_flags_t complain)
2042 conversion *conv;
2044 if (from == error_mark_node || to == error_mark_node
2045 || expr == error_mark_node)
2046 return NULL;
2048 /* Other flags only apply to the primary function in overload
2049 resolution, or after we've chosen one. */
2050 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2051 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2052 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2054 /* FIXME: actually we don't want warnings either, but we can't just
2055 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2056 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2057 We really ought not to issue that warning until we've committed
2058 to that conversion. */
2059 complain &= ~tf_error;
2061 /* Call reshape_init early to remove redundant braces. */
2062 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr)
2063 && CLASS_TYPE_P (to)
2064 && COMPLETE_TYPE_P (complete_type (to))
2065 && !CLASSTYPE_NON_AGGREGATE (to))
2067 expr = reshape_init (to, expr, complain);
2068 if (expr == error_mark_node)
2069 return NULL;
2070 from = TREE_TYPE (expr);
2073 if (TYPE_REF_P (to))
2074 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2075 else
2076 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2078 if (conv)
2079 return conv;
2081 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2083 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2084 return build_list_conv (to, expr, flags, complain);
2086 /* As an extension, allow list-initialization of _Complex. */
2087 if (TREE_CODE (to) == COMPLEX_TYPE
2088 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2090 conv = build_complex_conv (to, expr, flags, complain);
2091 if (conv)
2092 return conv;
2095 /* Allow conversion from an initializer-list with one element to a
2096 scalar type. */
2097 if (SCALAR_TYPE_P (to))
2099 int nelts = CONSTRUCTOR_NELTS (expr);
2100 tree elt;
2102 if (nelts == 0)
2103 elt = build_value_init (to, tf_none);
2104 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2105 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2106 else
2107 elt = error_mark_node;
2109 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2110 c_cast_p, flags, complain);
2111 if (conv)
2113 conv->check_narrowing = true;
2114 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2115 /* Too many levels of braces, i.e. '{{1}}'. */
2116 conv->bad_p = true;
2117 return conv;
2120 else if (TREE_CODE (to) == ARRAY_TYPE)
2121 return build_array_conv (to, expr, flags, complain);
2124 if (expr != NULL_TREE
2125 && (MAYBE_CLASS_TYPE_P (from)
2126 || MAYBE_CLASS_TYPE_P (to))
2127 && (flags & LOOKUP_NO_CONVERSION) == 0)
2129 struct z_candidate *cand;
2131 if (CLASS_TYPE_P (to)
2132 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2133 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2134 return build_aggr_conv (to, expr, flags, complain);
2136 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2137 if (cand)
2139 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2140 && CONSTRUCTOR_NELTS (expr) == 1
2141 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2142 && !is_list_ctor (cand->fn))
2144 /* "If C is not an initializer-list constructor and the
2145 initializer list has a single element of type cv U, where U is
2146 X or a class derived from X, the implicit conversion sequence
2147 has Exact Match rank if U is X, or Conversion rank if U is
2148 derived from X." */
2149 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2150 tree elttype = TREE_TYPE (elt);
2151 if (reference_related_p (to, elttype))
2152 return implicit_conversion (to, elttype, elt,
2153 c_cast_p, flags, complain);
2155 conv = cand->second_conv;
2158 /* We used to try to bind a reference to a temporary here, but that
2159 is now handled after the recursive call to this function at the end
2160 of reference_binding. */
2161 return conv;
2164 return NULL;
2167 /* Returns the implicit conversion sequence (see [over.ics]) from type
2168 FROM to type TO. The optional expression EXPR may affect the
2169 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2170 true, this conversion is coming from a C-style cast. */
2172 static conversion *
2173 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2174 int flags, tsubst_flags_t complain)
2176 conversion *conv = implicit_conversion_1 (to, from, expr, c_cast_p,
2177 flags, complain);
2178 if (!conv || conv->bad_p)
2179 return conv;
2180 if (conv_is_prvalue (conv)
2181 && CLASS_TYPE_P (conv->type)
2182 && CLASSTYPE_PURE_VIRTUALS (conv->type))
2183 conv->bad_p = true;
2184 return conv;
2187 /* Like implicit_conversion, but return NULL if the conversion is bad.
2189 This is not static so that check_non_deducible_conversion can call it within
2190 add_template_candidate_real as part of overload resolution; it should not be
2191 called outside of overload resolution. */
2193 conversion *
2194 good_conversion (tree to, tree from, tree expr,
2195 int flags, tsubst_flags_t complain)
2197 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2198 flags, complain);
2199 if (c && c->bad_p)
2200 c = NULL;
2201 return c;
2204 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2205 functions. ARGS will not be changed until a single candidate is
2206 selected. */
2208 static struct z_candidate *
2209 add_candidate (struct z_candidate **candidates,
2210 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2211 size_t num_convs, conversion **convs,
2212 tree access_path, tree conversion_path,
2213 int viable, struct rejection_reason *reason,
2214 int flags)
2216 struct z_candidate *cand = (struct z_candidate *)
2217 conversion_obstack_alloc (sizeof (struct z_candidate));
2219 cand->fn = fn;
2220 cand->first_arg = first_arg;
2221 cand->args = args;
2222 cand->convs = convs;
2223 cand->num_convs = num_convs;
2224 cand->access_path = access_path;
2225 cand->conversion_path = conversion_path;
2226 cand->viable = viable;
2227 cand->reason = reason;
2228 cand->next = *candidates;
2229 cand->flags = flags;
2230 *candidates = cand;
2232 if (convs && cand->reversed ())
2233 /* Swap the conversions for comparison in joust; we'll swap them back
2234 before build_over_call. */
2235 std::swap (convs[0], convs[1]);
2237 return cand;
2240 /* Return the number of remaining arguments in the parameter list
2241 beginning with ARG. */
2244 remaining_arguments (tree arg)
2246 int n;
2248 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2249 arg = TREE_CHAIN (arg))
2250 n++;
2252 return n;
2255 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2256 to the first parameter of a constructor where the parameter is of type
2257 "reference to possibly cv-qualified T" and the constructor is called with a
2258 single argument in the context of direct-initialization of an object of type
2259 "cv2 T", explicit conversion functions are also considered.
2261 So set LOOKUP_COPY_PARM to let reference_binding know that
2262 it's being called in that context. */
2265 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2267 int lflags = flags;
2268 tree t;
2269 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2270 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2271 && (same_type_ignoring_top_level_qualifiers_p
2272 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2274 if (!(flags & LOOKUP_ONLYCONVERTING))
2275 lflags |= LOOKUP_COPY_PARM;
2276 if ((flags & LOOKUP_LIST_INIT_CTOR)
2277 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2278 lflags |= LOOKUP_NO_CONVERSION;
2280 else
2281 lflags |= LOOKUP_ONLYCONVERTING;
2283 return lflags;
2286 /* Build an appropriate 'this' conversion for the method FN and class
2287 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2288 This function modifies PARMTYPE, ARGTYPE and ARG. */
2290 static conversion *
2291 build_this_conversion (tree fn, tree ctype,
2292 tree& parmtype, tree& argtype, tree& arg,
2293 int flags, tsubst_flags_t complain)
2295 gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2296 && !DECL_CONSTRUCTOR_P (fn));
2298 /* The type of the implicit object parameter ('this') for
2299 overload resolution is not always the same as for the
2300 function itself; conversion functions are considered to
2301 be members of the class being converted, and functions
2302 introduced by a using-declaration are considered to be
2303 members of the class that uses them.
2305 Since build_over_call ignores the ICS for the `this'
2306 parameter, we can just change the parm type. */
2307 parmtype = cp_build_qualified_type (ctype,
2308 cp_type_quals (TREE_TYPE (parmtype)));
2309 bool this_p = true;
2310 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2312 /* If the function has a ref-qualifier, the implicit
2313 object parameter has reference type. */
2314 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2315 parmtype = cp_build_reference_type (parmtype, rv);
2316 /* The special handling of 'this' conversions in compare_ics
2317 does not apply if there is a ref-qualifier. */
2318 this_p = false;
2320 else
2322 parmtype = build_pointer_type (parmtype);
2323 /* We don't use build_this here because we don't want to
2324 capture the object argument until we've chosen a
2325 non-static member function. */
2326 arg = build_address (arg);
2327 argtype = lvalue_type (arg);
2329 flags |= LOOKUP_ONLYCONVERTING;
2330 conversion *t = implicit_conversion (parmtype, argtype, arg,
2331 /*c_cast_p=*/false, flags, complain);
2332 t->this_p = this_p;
2333 return t;
2336 /* Create an overload candidate for the function or method FN called
2337 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2338 FLAGS is passed on to implicit_conversion.
2340 This does not change ARGS.
2342 CTYPE, if non-NULL, is the type we want to pretend this function
2343 comes from for purposes of overload resolution.
2345 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2346 If true, we stop computing conversions upon seeing the first bad
2347 conversion. This is used by add_candidates to avoid computing
2348 more conversions than necessary in the presence of a strictly viable
2349 candidate, while preserving the defacto behavior of overload resolution
2350 when it turns out there are only non-strictly viable candidates. */
2352 static struct z_candidate *
2353 add_function_candidate (struct z_candidate **candidates,
2354 tree fn, tree ctype, tree first_arg,
2355 const vec<tree, va_gc> *args, tree access_path,
2356 tree conversion_path, int flags,
2357 conversion **convs,
2358 bool shortcut_bad_convs,
2359 tsubst_flags_t complain)
2361 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2362 int i, len;
2363 tree parmnode;
2364 tree orig_first_arg = first_arg;
2365 int skip;
2366 int viable = 1;
2367 struct rejection_reason *reason = NULL;
2369 /* The `this', `in_chrg' and VTT arguments to constructors are not
2370 considered in overload resolution. */
2371 if (DECL_CONSTRUCTOR_P (fn))
2373 if (ctor_omit_inherited_parms (fn))
2374 /* Bring back parameters omitted from an inherited ctor. */
2375 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2376 else
2377 parmlist = skip_artificial_parms_for (fn, parmlist);
2378 skip = num_artificial_parms_for (fn);
2379 if (skip > 0 && first_arg != NULL_TREE)
2381 --skip;
2382 first_arg = NULL_TREE;
2385 else
2386 skip = 0;
2388 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2389 if (!convs)
2390 convs = alloc_conversions (len);
2392 /* 13.3.2 - Viable functions [over.match.viable]
2393 First, to be a viable function, a candidate function shall have enough
2394 parameters to agree in number with the arguments in the list.
2396 We need to check this first; otherwise, checking the ICSes might cause
2397 us to produce an ill-formed template instantiation. */
2399 parmnode = parmlist;
2400 for (i = 0; i < len; ++i)
2402 if (parmnode == NULL_TREE || parmnode == void_list_node)
2403 break;
2404 parmnode = TREE_CHAIN (parmnode);
2407 if ((i < len && parmnode)
2408 || !sufficient_parms_p (parmnode))
2410 int remaining = remaining_arguments (parmnode);
2411 viable = 0;
2412 reason = arity_rejection (first_arg, i + remaining, len);
2415 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2416 parameter of type "reference to cv C" (including such a constructor
2417 instantiated from a template) is excluded from the set of candidate
2418 functions when used to construct an object of type D with an argument list
2419 containing a single argument if C is reference-related to D. */
2420 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2421 && flag_new_inheriting_ctors
2422 && DECL_INHERITED_CTOR (fn))
2424 tree ptype = non_reference (TREE_VALUE (parmlist));
2425 tree dtype = DECL_CONTEXT (fn);
2426 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2427 if (reference_related_p (ptype, dtype)
2428 && reference_related_p (btype, ptype))
2430 viable = false;
2431 reason = inherited_ctor_rejection ();
2435 /* Second, for a function to be viable, its constraints must be
2436 satisfied. */
2437 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2439 reason = constraint_failure ();
2440 viable = false;
2443 /* When looking for a function from a subobject from an implicit
2444 copy/move constructor/operator=, don't consider anything that takes (a
2445 reference to) an unrelated type. See c++/44909 and core 1092. */
2446 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2448 if (DECL_CONSTRUCTOR_P (fn))
2449 i = 1;
2450 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2451 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2452 i = 2;
2453 else
2454 i = 0;
2455 if (i && len == i)
2457 parmnode = chain_index (i-1, parmlist);
2458 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2459 ctype))
2460 viable = 0;
2463 /* This only applies at the top level. */
2464 flags &= ~LOOKUP_DEFAULTED;
2467 if (! viable)
2468 goto out;
2470 if (shortcut_bad_convs)
2471 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2472 else
2473 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2475 /* Third, for F to be a viable function, there shall exist for each
2476 argument an implicit conversion sequence that converts that argument
2477 to the corresponding parameter of F. */
2479 parmnode = parmlist;
2481 for (i = 0; i < len; ++i)
2483 tree argtype, to_type;
2484 tree arg;
2486 if (parmnode == void_list_node)
2487 break;
2489 if (convs[i])
2491 /* Already set during deduction. */
2492 parmnode = TREE_CHAIN (parmnode);
2493 continue;
2496 if (i == 0 && first_arg != NULL_TREE)
2497 arg = first_arg;
2498 else
2499 arg = CONST_CAST_TREE (
2500 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2501 argtype = lvalue_type (arg);
2503 conversion *t;
2504 if (parmnode)
2506 tree parmtype = TREE_VALUE (parmnode);
2507 if (i == 0
2508 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2509 && !DECL_CONSTRUCTOR_P (fn))
2510 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2511 flags, complain);
2512 else
2514 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2515 t = implicit_conversion (parmtype, argtype, arg,
2516 /*c_cast_p=*/false, lflags, complain);
2518 to_type = parmtype;
2519 parmnode = TREE_CHAIN (parmnode);
2521 else
2523 t = build_identity_conv (argtype, arg);
2524 t->ellipsis_p = true;
2525 to_type = argtype;
2528 convs[i] = t;
2529 if (! t)
2531 viable = 0;
2532 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2533 EXPR_LOCATION (arg));
2534 break;
2537 if (t->bad_p)
2539 viable = -1;
2540 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2541 EXPR_LOCATION (arg));
2542 if (shortcut_bad_convs)
2543 break;
2547 out:
2548 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2549 access_path, conversion_path, viable, reason, flags);
2552 /* Create an overload candidate for the conversion function FN which will
2553 be invoked for expression OBJ, producing a pointer-to-function which
2554 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2555 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2556 passed on to implicit_conversion.
2558 Actually, we don't really care about FN; we care about the type it
2559 converts to. There may be multiple conversion functions that will
2560 convert to that type, and we rely on build_user_type_conversion_1 to
2561 choose the best one; so when we create our candidate, we record the type
2562 instead of the function. */
2564 static struct z_candidate *
2565 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2566 const vec<tree, va_gc> *arglist,
2567 tree access_path, tree conversion_path,
2568 tsubst_flags_t complain)
2570 tree totype = TREE_TYPE (TREE_TYPE (fn));
2571 int i, len, viable, flags;
2572 tree parmlist, parmnode;
2573 conversion **convs;
2574 struct rejection_reason *reason;
2576 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2577 parmlist = TREE_TYPE (parmlist);
2578 parmlist = TYPE_ARG_TYPES (parmlist);
2580 len = vec_safe_length (arglist) + 1;
2581 convs = alloc_conversions (len);
2582 parmnode = parmlist;
2583 viable = 1;
2584 flags = LOOKUP_IMPLICIT;
2585 reason = NULL;
2587 /* Don't bother looking up the same type twice. */
2588 if (*candidates && (*candidates)->fn == totype)
2589 return NULL;
2591 for (i = 0; i < len; ++i)
2593 tree arg, argtype, convert_type = NULL_TREE;
2594 conversion *t;
2596 if (i == 0)
2597 arg = obj;
2598 else
2599 arg = (*arglist)[i - 1];
2600 argtype = lvalue_type (arg);
2602 if (i == 0)
2604 t = build_identity_conv (argtype, NULL_TREE);
2605 t = build_conv (ck_user, totype, t);
2606 /* Leave the 'cand' field null; we'll figure out the conversion in
2607 convert_like if this candidate is chosen. */
2608 convert_type = totype;
2610 else if (parmnode == void_list_node)
2611 break;
2612 else if (parmnode)
2614 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2615 /*c_cast_p=*/false, flags, complain);
2616 convert_type = TREE_VALUE (parmnode);
2618 else
2620 t = build_identity_conv (argtype, arg);
2621 t->ellipsis_p = true;
2622 convert_type = argtype;
2625 convs[i] = t;
2626 if (! t)
2627 break;
2629 if (t->bad_p)
2631 viable = -1;
2632 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2633 EXPR_LOCATION (arg));
2636 if (i == 0)
2637 continue;
2639 if (parmnode)
2640 parmnode = TREE_CHAIN (parmnode);
2643 if (i < len
2644 || ! sufficient_parms_p (parmnode))
2646 int remaining = remaining_arguments (parmnode);
2647 viable = 0;
2648 reason = arity_rejection (NULL_TREE, i + remaining, len);
2651 return add_candidate (candidates, totype, obj, arglist, len, convs,
2652 access_path, conversion_path, viable, reason, flags);
2655 static void
2656 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2657 tree type1, tree type2, const vec<tree,va_gc> &args,
2658 tree *argtypes, int flags, tsubst_flags_t complain)
2660 conversion *t;
2661 conversion **convs;
2662 size_t num_convs;
2663 int viable = 1;
2664 tree types[2];
2665 struct rejection_reason *reason = NULL;
2667 types[0] = type1;
2668 types[1] = type2;
2670 num_convs = args.length ();
2671 convs = alloc_conversions (num_convs);
2673 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2674 conversion ops are allowed. We handle that here by just checking for
2675 boolean_type_node because other operators don't ask for it. COND_EXPR
2676 also does contextual conversion to bool for the first operand, but we
2677 handle that in build_conditional_expr, and type1 here is operand 2. */
2678 if (type1 != boolean_type_node)
2679 flags |= LOOKUP_ONLYCONVERTING;
2681 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2683 t = implicit_conversion (types[i], argtypes[i], args[i],
2684 /*c_cast_p=*/false, flags, complain);
2685 if (! t)
2687 viable = 0;
2688 /* We need something for printing the candidate. */
2689 t = build_identity_conv (types[i], NULL_TREE);
2690 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2691 types[i], EXPR_LOCATION (args[i]));
2693 else if (t->bad_p)
2695 viable = 0;
2696 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2697 types[i],
2698 EXPR_LOCATION (args[i]));
2700 convs[i] = t;
2703 /* For COND_EXPR we rearranged the arguments; undo that now. */
2704 if (num_convs == 3)
2706 convs[2] = convs[1];
2707 convs[1] = convs[0];
2708 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2709 /*c_cast_p=*/false, flags,
2710 complain);
2711 if (t)
2712 convs[0] = t;
2713 else
2715 viable = 0;
2716 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2717 boolean_type_node,
2718 EXPR_LOCATION (args[2]));
2722 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2723 num_convs, convs,
2724 /*access_path=*/NULL_TREE,
2725 /*conversion_path=*/NULL_TREE,
2726 viable, reason, flags);
2729 static bool
2730 is_complete (tree t)
2732 return COMPLETE_TYPE_P (complete_type (t));
2735 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2737 static bool
2738 promoted_arithmetic_type_p (tree type)
2740 /* [over.built]
2742 In this section, the term promoted integral type is used to refer
2743 to those integral types which are preserved by integral promotion
2744 (including e.g. int and long but excluding e.g. char).
2745 Similarly, the term promoted arithmetic type refers to promoted
2746 integral types plus floating types. */
2747 return ((CP_INTEGRAL_TYPE_P (type)
2748 && same_type_p (type_promotes_to (type), type))
2749 || TREE_CODE (type) == REAL_TYPE);
2752 /* Create any builtin operator overload candidates for the operator in
2753 question given the converted operand types TYPE1 and TYPE2. The other
2754 args are passed through from add_builtin_candidates to
2755 build_builtin_candidate.
2757 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2758 If CODE is requires candidates operands of the same type of the kind
2759 of which TYPE1 and TYPE2 are, we add both candidates
2760 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2762 static void
2763 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2764 enum tree_code code2, tree fnname, tree type1,
2765 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2766 int flags, tsubst_flags_t complain)
2768 switch (code)
2770 case POSTINCREMENT_EXPR:
2771 case POSTDECREMENT_EXPR:
2772 args[1] = integer_zero_node;
2773 type2 = integer_type_node;
2774 break;
2775 default:
2776 break;
2779 switch (code)
2782 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2783 and VQ is either volatile or empty, there exist candidate operator
2784 functions of the form
2785 VQ T& operator++(VQ T&);
2786 T operator++(VQ T&, int);
2787 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2788 and VQ is either volatile or empty, there exist candidate operator
2789 functions of the form
2790 VQ T& operator--(VQ T&);
2791 T operator--(VQ T&, int);
2792 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2793 type, and VQ is either volatile or empty, there exist candidate operator
2794 functions of the form
2795 T*VQ& operator++(T*VQ&);
2796 T*VQ& operator--(T*VQ&);
2797 T* operator++(T*VQ&, int);
2798 T* operator--(T*VQ&, int); */
2800 case POSTDECREMENT_EXPR:
2801 case PREDECREMENT_EXPR:
2802 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2803 return;
2804 /* FALLTHRU */
2805 case POSTINCREMENT_EXPR:
2806 case PREINCREMENT_EXPR:
2807 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2808 to p4. */
2809 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2810 return;
2811 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2813 type1 = build_reference_type (type1);
2814 break;
2816 return;
2818 /* 7 For every cv-qualified or cv-unqualified object type T, there
2819 exist candidate operator functions of the form
2821 T& operator*(T*);
2824 8 For every function type T that does not have cv-qualifiers or
2825 a ref-qualifier, there exist candidate operator functions of the form
2826 T& operator*(T*); */
2828 case INDIRECT_REF:
2829 if (TYPE_PTR_P (type1)
2830 && (TYPE_PTROB_P (type1)
2831 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2832 break;
2833 return;
2835 /* 9 For every type T, there exist candidate operator functions of the form
2836 T* operator+(T*);
2838 10 For every floating-point or promoted integral type T, there exist
2839 candidate operator functions of the form
2840 T operator+(T);
2841 T operator-(T); */
2843 case UNARY_PLUS_EXPR: /* unary + */
2844 if (TYPE_PTR_P (type1))
2845 break;
2846 /* FALLTHRU */
2847 case NEGATE_EXPR:
2848 if (ARITHMETIC_TYPE_P (type1))
2849 break;
2850 return;
2852 /* 11 For every promoted integral type T, there exist candidate operator
2853 functions of the form
2854 T operator~(T); */
2856 case BIT_NOT_EXPR:
2857 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2858 break;
2859 return;
2861 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2862 is the same type as C2 or is a derived class of C2, and T is an object
2863 type or a function type there exist candidate operator functions of the
2864 form
2865 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2866 where CV12 is the union of CV1 and CV2. */
2868 case MEMBER_REF:
2869 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2871 tree c1 = TREE_TYPE (type1);
2872 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2874 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2875 && (TYPE_PTRMEMFUNC_P (type2)
2876 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2877 break;
2879 return;
2881 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2882 or promoted integral type, there exist candidate operator functions of the
2883 form
2884 LR operator*(L, R);
2885 LR operator/(L, R);
2886 LR operator+(L, R);
2887 LR operator-(L, R);
2888 bool operator<(L, R);
2889 bool operator>(L, R);
2890 bool operator<=(L, R);
2891 bool operator>=(L, R);
2892 bool operator==(L, R);
2893 bool operator!=(L, R);
2894 where LR is the result of the usual arithmetic conversions between
2895 types L and R.
2897 14 For every integral type T there exists a candidate operator function of
2898 the form
2900 std::strong_ordering operator<=>(T, T);
2902 15 For every pair of floating-point types L and R, there exists a candidate
2903 operator function of the form
2905 std::partial_ordering operator<=>(L, R);
2907 16 For every cv-qualified or cv-unqualified object type T there exist
2908 candidate operator functions of the form
2909 T* operator+(T*, std::ptrdiff_t);
2910 T& operator[](T*, std::ptrdiff_t);
2911 T* operator-(T*, std::ptrdiff_t);
2912 T* operator+(std::ptrdiff_t, T*);
2913 T& operator[](std::ptrdiff_t, T*);
2915 17 For every T, where T is a pointer to object type, there exist candidate
2916 operator functions of the form
2917 std::ptrdiff_t operator-(T, T);
2919 18 For every T, where T is an enumeration type or a pointer type, there
2920 exist candidate operator functions of the form
2921 bool operator<(T, T);
2922 bool operator>(T, T);
2923 bool operator<=(T, T);
2924 bool operator>=(T, T);
2925 bool operator==(T, T);
2926 bool operator!=(T, T);
2927 R operator<=>(T, T);
2929 where R is the result type specified in [expr.spaceship].
2931 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2932 there exist candidate operator functions of the form
2933 bool operator==(T, T);
2934 bool operator!=(T, T); */
2936 case MINUS_EXPR:
2937 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2938 break;
2939 if (TYPE_PTROB_P (type1)
2940 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2942 type2 = ptrdiff_type_node;
2943 break;
2945 /* FALLTHRU */
2946 case MULT_EXPR:
2947 case TRUNC_DIV_EXPR:
2948 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2949 break;
2950 return;
2952 /* This isn't exactly what's specified above for operator<=>, but it's
2953 close enough. In particular, we don't care about the return type
2954 specified above; it doesn't participate in overload resolution and it
2955 doesn't affect the semantics of the built-in operator. */
2956 case SPACESHIP_EXPR:
2957 case EQ_EXPR:
2958 case NE_EXPR:
2959 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2960 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2961 break;
2962 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2963 break;
2964 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2966 type2 = type1;
2967 break;
2969 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2971 type1 = type2;
2972 break;
2974 /* Fall through. */
2975 case LT_EXPR:
2976 case GT_EXPR:
2977 case LE_EXPR:
2978 case GE_EXPR:
2979 case MAX_EXPR:
2980 case MIN_EXPR:
2981 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2982 break;
2983 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2984 break;
2985 if (TREE_CODE (type1) == ENUMERAL_TYPE
2986 && TREE_CODE (type2) == ENUMERAL_TYPE)
2987 break;
2988 if (TYPE_PTR_P (type1)
2989 && null_ptr_cst_p (args[1]))
2991 type2 = type1;
2992 break;
2994 if (null_ptr_cst_p (args[0])
2995 && TYPE_PTR_P (type2))
2997 type1 = type2;
2998 break;
3000 return;
3002 case PLUS_EXPR:
3003 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3004 break;
3005 /* FALLTHRU */
3006 case ARRAY_REF:
3007 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3009 type1 = ptrdiff_type_node;
3010 break;
3012 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3014 type2 = ptrdiff_type_node;
3015 break;
3017 return;
3019 /* 18For every pair of promoted integral types L and R, there exist candi-
3020 date operator functions of the form
3021 LR operator%(L, R);
3022 LR operator&(L, R);
3023 LR operator^(L, R);
3024 LR operator|(L, R);
3025 L operator<<(L, R);
3026 L operator>>(L, R);
3027 where LR is the result of the usual arithmetic conversions between
3028 types L and R. */
3030 case TRUNC_MOD_EXPR:
3031 case BIT_AND_EXPR:
3032 case BIT_IOR_EXPR:
3033 case BIT_XOR_EXPR:
3034 case LSHIFT_EXPR:
3035 case RSHIFT_EXPR:
3036 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3037 break;
3038 return;
3040 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3041 type, VQ is either volatile or empty, and R is a promoted arithmetic
3042 type, there exist candidate operator functions of the form
3043 VQ L& operator=(VQ L&, R);
3044 VQ L& operator*=(VQ L&, R);
3045 VQ L& operator/=(VQ L&, R);
3046 VQ L& operator+=(VQ L&, R);
3047 VQ L& operator-=(VQ L&, R);
3049 20For every pair T, VQ), where T is any type and VQ is either volatile
3050 or empty, there exist candidate operator functions of the form
3051 T*VQ& operator=(T*VQ&, T*);
3053 21For every pair T, VQ), where T is a pointer to member type and VQ is
3054 either volatile or empty, there exist candidate operator functions of
3055 the form
3056 VQ T& operator=(VQ T&, T);
3058 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3059 unqualified complete object type, VQ is either volatile or empty, and
3060 I is a promoted integral type, there exist candidate operator func-
3061 tions of the form
3062 T*VQ& operator+=(T*VQ&, I);
3063 T*VQ& operator-=(T*VQ&, I);
3065 23For every triple L, VQ, R), where L is an integral or enumeration
3066 type, VQ is either volatile or empty, and R is a promoted integral
3067 type, there exist candidate operator functions of the form
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 VQ L& operator^=(VQ L&, R);
3074 VQ L& operator|=(VQ L&, R); */
3076 case MODIFY_EXPR:
3077 switch (code2)
3079 case PLUS_EXPR:
3080 case MINUS_EXPR:
3081 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3083 type2 = ptrdiff_type_node;
3084 break;
3086 /* FALLTHRU */
3087 case MULT_EXPR:
3088 case TRUNC_DIV_EXPR:
3089 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3090 break;
3091 return;
3093 case TRUNC_MOD_EXPR:
3094 case BIT_AND_EXPR:
3095 case BIT_IOR_EXPR:
3096 case BIT_XOR_EXPR:
3097 case LSHIFT_EXPR:
3098 case RSHIFT_EXPR:
3099 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3100 break;
3101 return;
3103 case NOP_EXPR:
3104 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3105 break;
3106 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3107 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3108 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3109 || ((TYPE_PTRMEMFUNC_P (type1)
3110 || TYPE_PTR_P (type1))
3111 && null_ptr_cst_p (args[1])))
3113 type2 = type1;
3114 break;
3116 return;
3118 default:
3119 gcc_unreachable ();
3121 type1 = build_reference_type (type1);
3122 break;
3124 case COND_EXPR:
3125 /* [over.built]
3127 For every pair of promoted arithmetic types L and R, there
3128 exist candidate operator functions of the form
3130 LR operator?(bool, L, R);
3132 where LR is the result of the usual arithmetic conversions
3133 between types L and R.
3135 For every type T, where T is a pointer or pointer-to-member
3136 type, there exist candidate operator functions of the form T
3137 operator?(bool, T, T); */
3139 if (promoted_arithmetic_type_p (type1)
3140 && promoted_arithmetic_type_p (type2))
3141 /* That's OK. */
3142 break;
3144 /* Otherwise, the types should be pointers. */
3145 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3146 return;
3148 /* We don't check that the two types are the same; the logic
3149 below will actually create two candidates; one in which both
3150 parameter types are TYPE1, and one in which both parameter
3151 types are TYPE2. */
3152 break;
3154 case REALPART_EXPR:
3155 case IMAGPART_EXPR:
3156 if (ARITHMETIC_TYPE_P (type1))
3157 break;
3158 return;
3160 default:
3161 gcc_unreachable ();
3164 /* Make sure we don't create builtin candidates with dependent types. */
3165 bool u1 = uses_template_parms (type1);
3166 bool u2 = type2 ? uses_template_parms (type2) : false;
3167 if (u1 || u2)
3169 /* Try to recover if one of the types is non-dependent. But if
3170 there's only one type, there's nothing we can do. */
3171 if (!type2)
3172 return;
3173 /* And we lose if both are dependent. */
3174 if (u1 && u2)
3175 return;
3176 /* Or if they have different forms. */
3177 if (TREE_CODE (type1) != TREE_CODE (type2))
3178 return;
3180 if (u1 && !u2)
3181 type1 = type2;
3182 else if (u2 && !u1)
3183 type2 = type1;
3186 /* If we're dealing with two pointer types or two enumeral types,
3187 we need candidates for both of them. */
3188 if (type2 && !same_type_p (type1, type2)
3189 && TREE_CODE (type1) == TREE_CODE (type2)
3190 && (TYPE_REF_P (type1)
3191 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3192 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3193 || TYPE_PTRMEMFUNC_P (type1)
3194 || MAYBE_CLASS_TYPE_P (type1)
3195 || TREE_CODE (type1) == ENUMERAL_TYPE))
3197 if (TYPE_PTR_OR_PTRMEM_P (type1))
3199 tree cptype = composite_pointer_type (input_location,
3200 type1, type2,
3201 error_mark_node,
3202 error_mark_node,
3203 CPO_CONVERSION,
3204 tf_none);
3205 if (cptype != error_mark_node)
3207 build_builtin_candidate
3208 (candidates, fnname, cptype, cptype, args, argtypes,
3209 flags, complain);
3210 return;
3214 build_builtin_candidate
3215 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3216 build_builtin_candidate
3217 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3218 return;
3221 build_builtin_candidate
3222 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3225 tree
3226 type_decays_to (tree type)
3228 if (TREE_CODE (type) == ARRAY_TYPE)
3229 return build_pointer_type (TREE_TYPE (type));
3230 if (TREE_CODE (type) == FUNCTION_TYPE)
3231 return build_pointer_type (type);
3232 return type;
3235 /* There are three conditions of builtin candidates:
3237 1) bool-taking candidates. These are the same regardless of the input.
3238 2) pointer-pair taking candidates. These are generated for each type
3239 one of the input types converts to.
3240 3) arithmetic candidates. According to the standard, we should generate
3241 all of these, but I'm trying not to...
3243 Here we generate a superset of the possible candidates for this particular
3244 case. That is a subset of the full set the standard defines, plus some
3245 other cases which the standard disallows. add_builtin_candidate will
3246 filter out the invalid set. */
3248 static void
3249 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3250 enum tree_code code2, tree fnname,
3251 vec<tree, va_gc> *argv,
3252 int flags, tsubst_flags_t complain)
3254 int ref1;
3255 int enum_p = 0;
3256 tree type, argtypes[3], t;
3257 /* TYPES[i] is the set of possible builtin-operator parameter types
3258 we will consider for the Ith argument. */
3259 vec<tree, va_gc> *types[2];
3260 unsigned ix;
3261 vec<tree, va_gc> &args = *argv;
3262 unsigned len = args.length ();
3264 for (unsigned i = 0; i < len; ++i)
3266 if (args[i])
3267 argtypes[i] = unlowered_expr_type (args[i]);
3268 else
3269 argtypes[i] = NULL_TREE;
3272 switch (code)
3274 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3275 and VQ is either volatile or empty, there exist candidate operator
3276 functions of the form
3277 VQ T& operator++(VQ T&); */
3279 case POSTINCREMENT_EXPR:
3280 case PREINCREMENT_EXPR:
3281 case POSTDECREMENT_EXPR:
3282 case PREDECREMENT_EXPR:
3283 case MODIFY_EXPR:
3284 ref1 = 1;
3285 break;
3287 /* 24There also exist candidate operator functions of the form
3288 bool operator!(bool);
3289 bool operator&&(bool, bool);
3290 bool operator||(bool, bool); */
3292 case TRUTH_NOT_EXPR:
3293 build_builtin_candidate
3294 (candidates, fnname, boolean_type_node,
3295 NULL_TREE, args, argtypes, flags, complain);
3296 return;
3298 case TRUTH_ORIF_EXPR:
3299 case TRUTH_ANDIF_EXPR:
3300 build_builtin_candidate
3301 (candidates, fnname, boolean_type_node,
3302 boolean_type_node, args, argtypes, flags, complain);
3303 return;
3305 case ADDR_EXPR:
3306 case COMPOUND_EXPR:
3307 case COMPONENT_REF:
3308 case CO_AWAIT_EXPR:
3309 return;
3311 case COND_EXPR:
3312 case EQ_EXPR:
3313 case NE_EXPR:
3314 case LT_EXPR:
3315 case LE_EXPR:
3316 case GT_EXPR:
3317 case GE_EXPR:
3318 case SPACESHIP_EXPR:
3319 enum_p = 1;
3320 /* Fall through. */
3322 default:
3323 ref1 = 0;
3326 types[0] = make_tree_vector ();
3327 types[1] = make_tree_vector ();
3329 if (len == 3)
3330 len = 2;
3331 for (unsigned i = 0; i < len; ++i)
3333 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3335 tree convs;
3337 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3338 return;
3340 convs = lookup_conversions (argtypes[i]);
3342 if (code == COND_EXPR)
3344 if (lvalue_p (args[i]))
3345 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3347 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3350 else if (! convs)
3351 return;
3353 for (; convs; convs = TREE_CHAIN (convs))
3355 type = TREE_TYPE (convs);
3357 if (i == 0 && ref1
3358 && (!TYPE_REF_P (type)
3359 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3360 continue;
3362 if (code == COND_EXPR && TYPE_REF_P (type))
3363 vec_safe_push (types[i], type);
3365 type = non_reference (type);
3366 if (i != 0 || ! ref1)
3368 type = cv_unqualified (type_decays_to (type));
3369 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3370 vec_safe_push (types[i], type);
3371 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3372 type = type_promotes_to (type);
3375 if (! vec_member (type, types[i]))
3376 vec_safe_push (types[i], type);
3379 else
3381 if (code == COND_EXPR && lvalue_p (args[i]))
3382 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3383 type = non_reference (argtypes[i]);
3384 if (i != 0 || ! ref1)
3386 type = cv_unqualified (type_decays_to (type));
3387 if (enum_p && UNSCOPED_ENUM_P (type))
3388 vec_safe_push (types[i], type);
3389 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3390 type = type_promotes_to (type);
3392 vec_safe_push (types[i], type);
3396 /* Run through the possible parameter types of both arguments,
3397 creating candidates with those parameter types. */
3398 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3400 unsigned jx;
3401 tree u;
3403 if (!types[1]->is_empty ())
3404 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3405 add_builtin_candidate
3406 (candidates, code, code2, fnname, t,
3407 u, args, argtypes, flags, complain);
3408 else
3409 add_builtin_candidate
3410 (candidates, code, code2, fnname, t,
3411 NULL_TREE, args, argtypes, flags, complain);
3414 release_tree_vector (types[0]);
3415 release_tree_vector (types[1]);
3419 /* If TMPL can be successfully instantiated as indicated by
3420 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3422 TMPL is the template. EXPLICIT_TARGS are any explicit template
3423 arguments. ARGLIST is the arguments provided at the call-site.
3424 This does not change ARGLIST. The RETURN_TYPE is the desired type
3425 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3426 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3427 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3429 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3431 static struct z_candidate*
3432 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3433 tree ctype, tree explicit_targs, tree first_arg,
3434 const vec<tree, va_gc> *arglist, tree return_type,
3435 tree access_path, tree conversion_path,
3436 int flags, tree obj, unification_kind_t strict,
3437 bool shortcut_bad_convs, tsubst_flags_t complain)
3439 int ntparms = DECL_NTPARMS (tmpl);
3440 tree targs = make_tree_vec (ntparms);
3441 unsigned int len = vec_safe_length (arglist);
3442 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3443 unsigned int skip_without_in_chrg = 0;
3444 tree first_arg_without_in_chrg = first_arg;
3445 tree *args_without_in_chrg;
3446 unsigned int nargs_without_in_chrg;
3447 unsigned int ia, ix;
3448 tree arg;
3449 struct z_candidate *cand;
3450 tree fn;
3451 struct rejection_reason *reason = NULL;
3452 int errs;
3453 conversion **convs = NULL;
3455 /* We don't do deduction on the in-charge parameter, the VTT
3456 parameter or 'this'. */
3457 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3459 if (first_arg_without_in_chrg != NULL_TREE)
3460 first_arg_without_in_chrg = NULL_TREE;
3461 else if (return_type && strict == DEDUCE_CALL)
3462 /* We're deducing for a call to the result of a template conversion
3463 function, so the args don't contain 'this'; leave them alone. */;
3464 else
3465 ++skip_without_in_chrg;
3468 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3469 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3470 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3472 if (first_arg_without_in_chrg != NULL_TREE)
3473 first_arg_without_in_chrg = NULL_TREE;
3474 else
3475 ++skip_without_in_chrg;
3478 if (len < skip_without_in_chrg)
3479 return NULL;
3481 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3482 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3483 TREE_TYPE ((*arglist)[0])))
3485 /* 12.8/6 says, "A declaration of a constructor for a class X is
3486 ill-formed if its first parameter is of type (optionally cv-qualified)
3487 X and either there are no other parameters or else all other
3488 parameters have default arguments. A member function template is never
3489 instantiated to produce such a constructor signature."
3491 So if we're trying to copy an object of the containing class, don't
3492 consider a template constructor that has a first parameter type that
3493 is just a template parameter, as we would deduce a signature that we
3494 would then reject in the code below. */
3495 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3497 firstparm = TREE_VALUE (firstparm);
3498 if (PACK_EXPANSION_P (firstparm))
3499 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3500 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3502 gcc_assert (!explicit_targs);
3503 reason = invalid_copy_with_fn_template_rejection ();
3504 goto fail;
3509 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3510 + (len - skip_without_in_chrg));
3511 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3512 ia = 0;
3513 if (first_arg_without_in_chrg != NULL_TREE)
3515 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3516 ++ia;
3518 for (ix = skip_without_in_chrg;
3519 vec_safe_iterate (arglist, ix, &arg);
3520 ++ix)
3522 args_without_in_chrg[ia] = arg;
3523 ++ia;
3525 gcc_assert (ia == nargs_without_in_chrg);
3527 if (!obj && explicit_targs)
3529 /* Check that there's no obvious arity mismatch before proceeding with
3530 deduction. This avoids substituting explicit template arguments
3531 into the template (which could result in an error outside the
3532 immediate context) when the resulting candidate would be unviable
3533 anyway. */
3534 int min_arity = 0, max_arity = 0;
3535 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3536 parms = skip_artificial_parms_for (tmpl, parms);
3537 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3539 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3541 max_arity = -1;
3542 break;
3544 if (TREE_PURPOSE (parms))
3545 /* A parameter with a default argument. */
3546 ++max_arity;
3547 else
3548 ++min_arity, ++max_arity;
3550 if (ia < (unsigned)min_arity)
3552 /* Too few arguments. */
3553 reason = arity_rejection (NULL_TREE, min_arity, ia,
3554 /*least_p=*/(max_arity == -1));
3555 goto fail;
3557 else if (max_arity != -1 && ia > (unsigned)max_arity)
3559 /* Too many arguments. */
3560 reason = arity_rejection (NULL_TREE, max_arity, ia);
3561 goto fail;
3565 errs = errorcount+sorrycount;
3566 if (!obj)
3568 convs = alloc_conversions (nargs);
3570 if (shortcut_bad_convs
3571 && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3572 && !DECL_CONSTRUCTOR_P (tmpl))
3574 /* Check the 'this' conversion before proceeding with deduction.
3575 This is effectively an extension of the DR 1391 resolution
3576 that we perform in check_non_deducible_conversions, though it's
3577 convenient to do this extra check here instead of there. */
3578 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3579 tree argtype = lvalue_type (first_arg);
3580 tree arg = first_arg;
3581 conversion *t = build_this_conversion (tmpl, ctype,
3582 parmtype, argtype, arg,
3583 flags, complain);
3584 convs[0] = t;
3585 if (t->bad_p)
3587 reason = bad_arg_conversion_rejection (first_arg, 0,
3588 arg, parmtype,
3589 EXPR_LOCATION (arg));
3590 goto fail;
3594 fn = fn_type_unification (tmpl, explicit_targs, targs,
3595 args_without_in_chrg,
3596 nargs_without_in_chrg,
3597 return_type, strict, flags, convs,
3598 false, complain & tf_decltype);
3600 if (fn == error_mark_node)
3602 /* Don't repeat unification later if it already resulted in errors. */
3603 if (errorcount+sorrycount == errs)
3604 reason = template_unification_rejection (tmpl, explicit_targs,
3605 targs, args_without_in_chrg,
3606 nargs_without_in_chrg,
3607 return_type, strict, flags);
3608 else
3609 reason = template_unification_error_rejection ();
3610 goto fail;
3613 /* Now the explicit specifier might have been deduced; check if this
3614 declaration is explicit. If it is and we're ignoring non-converting
3615 constructors, don't add this function to the set of candidates. */
3616 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3617 == LOOKUP_ONLYCONVERTING)
3618 && DECL_NONCONVERTING_P (fn))
3619 return NULL;
3621 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3623 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3624 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3625 ctype))
3627 /* We're trying to produce a constructor with a prohibited signature,
3628 as discussed above; handle here any cases we didn't catch then,
3629 such as X(X<T>). */
3630 reason = invalid_copy_with_fn_template_rejection ();
3631 goto fail;
3635 if (obj != NULL_TREE)
3636 /* Aha, this is a conversion function. */
3637 cand = add_conv_candidate (candidates, fn, obj, arglist,
3638 access_path, conversion_path, complain);
3639 else
3640 cand = add_function_candidate (candidates, fn, ctype,
3641 first_arg, arglist, access_path,
3642 conversion_path, flags, convs,
3643 shortcut_bad_convs, complain);
3644 if (DECL_TI_TEMPLATE (fn) != tmpl)
3645 /* This situation can occur if a member template of a template
3646 class is specialized. Then, instantiate_template might return
3647 an instantiation of the specialization, in which case the
3648 DECL_TI_TEMPLATE field will point at the original
3649 specialization. For example:
3651 template <class T> struct S { template <class U> void f(U);
3652 template <> void f(int) {}; };
3653 S<double> sd;
3654 sd.f(3);
3656 Here, TMPL will be template <class U> S<double>::f(U).
3657 And, instantiate template will give us the specialization
3658 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3659 for this will point at template <class T> template <> S<T>::f(int),
3660 so that we can find the definition. For the purposes of
3661 overload resolution, however, we want the original TMPL. */
3662 cand->template_decl = build_template_info (tmpl, targs);
3663 else
3664 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3665 cand->explicit_targs = explicit_targs;
3667 return cand;
3668 fail:
3669 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3670 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3671 access_path, conversion_path, viable, reason, flags);
3675 static struct z_candidate *
3676 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3677 tree explicit_targs, tree first_arg,
3678 const vec<tree, va_gc> *arglist, tree return_type,
3679 tree access_path, tree conversion_path, int flags,
3680 unification_kind_t strict, bool shortcut_bad_convs,
3681 tsubst_flags_t complain)
3683 return
3684 add_template_candidate_real (candidates, tmpl, ctype,
3685 explicit_targs, first_arg, arglist,
3686 return_type, access_path, conversion_path,
3687 flags, NULL_TREE, strict, shortcut_bad_convs,
3688 complain);
3691 /* Create an overload candidate for the conversion function template TMPL,
3692 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3693 pointer-to-function which will in turn be called with the argument list
3694 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3695 passed on to implicit_conversion. */
3697 static struct z_candidate *
3698 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3699 tree obj,
3700 const vec<tree, va_gc> *arglist,
3701 tree return_type, tree access_path,
3702 tree conversion_path, tsubst_flags_t complain)
3704 /* Making this work broke PR 71117 and 85118, so until the committee resolves
3705 core issue 2189, let's disable this candidate if there are any call
3706 operators. */
3707 if (*candidates)
3708 return NULL;
3710 return
3711 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3712 NULL_TREE, arglist, return_type, access_path,
3713 conversion_path, 0, obj, DEDUCE_CALL,
3714 /*shortcut_bad_convs=*/false, complain);
3717 /* The CANDS are the set of candidates that were considered for
3718 overload resolution. Return the set of viable candidates, or CANDS
3719 if none are viable. If any of the candidates were viable, set
3720 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3721 considered viable only if it is strictly viable. */
3723 static struct z_candidate*
3724 splice_viable (struct z_candidate *cands,
3725 bool strict_p,
3726 bool *any_viable_p)
3728 struct z_candidate *viable;
3729 struct z_candidate **last_viable;
3730 struct z_candidate **cand;
3731 bool found_strictly_viable = false;
3733 /* Be strict inside templates, since build_over_call won't actually
3734 do the conversions to get pedwarns. */
3735 if (processing_template_decl)
3736 strict_p = true;
3738 viable = NULL;
3739 last_viable = &viable;
3740 *any_viable_p = false;
3742 cand = &cands;
3743 while (*cand)
3745 struct z_candidate *c = *cand;
3746 if (!strict_p
3747 && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3749 /* Be strict in the presence of a viable candidate. Also if
3750 there are template candidates, so that we get deduction errors
3751 for them instead of silently preferring a bad conversion. */
3752 strict_p = true;
3753 if (viable && !found_strictly_viable)
3755 /* Put any spliced near matches back onto the main list so
3756 that we see them if there is no strict match. */
3757 *any_viable_p = false;
3758 *last_viable = cands;
3759 cands = viable;
3760 viable = NULL;
3761 last_viable = &viable;
3765 if (strict_p ? c->viable == 1 : c->viable)
3767 *last_viable = c;
3768 *cand = c->next;
3769 c->next = NULL;
3770 last_viable = &c->next;
3771 *any_viable_p = true;
3772 if (c->viable == 1)
3773 found_strictly_viable = true;
3775 else
3776 cand = &c->next;
3779 return viable ? viable : cands;
3782 static bool
3783 any_strictly_viable (struct z_candidate *cands)
3785 for (; cands; cands = cands->next)
3786 if (cands->viable == 1)
3787 return true;
3788 return false;
3791 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3792 words, it is about to become the "this" pointer for a member
3793 function call. Take the address of the object. */
3795 static tree
3796 build_this (tree obj)
3798 /* In a template, we are only concerned about the type of the
3799 expression, so we can take a shortcut. */
3800 if (processing_template_decl)
3801 return build_address (obj);
3803 return cp_build_addr_expr (obj, tf_warning_or_error);
3806 /* Returns true iff functions are equivalent. Equivalent functions are
3807 not '==' only if one is a function-local extern function or if
3808 both are extern "C". */
3810 static inline int
3811 equal_functions (tree fn1, tree fn2)
3813 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3814 return 0;
3815 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3816 return fn1 == fn2;
3817 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3818 || DECL_EXTERN_C_FUNCTION_P (fn1))
3819 return decls_match (fn1, fn2);
3820 return fn1 == fn2;
3823 /* Print information about a candidate FN being rejected due to INFO. */
3825 static void
3826 print_conversion_rejection (location_t loc, struct conversion_info *info,
3827 tree fn)
3829 tree from = info->from;
3830 if (!TYPE_P (from))
3831 from = lvalue_type (from);
3832 if (info->n_arg == -1)
3834 /* Conversion of implicit `this' argument failed. */
3835 if (!TYPE_P (info->from))
3836 /* A bad conversion for 'this' must be discarding cv-quals. */
3837 inform (loc, " passing %qT as %<this%> "
3838 "argument discards qualifiers",
3839 from);
3840 else
3841 inform (loc, " no known conversion for implicit "
3842 "%<this%> parameter from %qH to %qI",
3843 from, info->to_type);
3845 else if (!TYPE_P (info->from))
3847 if (info->n_arg >= 0)
3848 inform (loc, " conversion of argument %d would be ill-formed:",
3849 info->n_arg + 1);
3850 iloc_sentinel ils = loc;
3851 perform_implicit_conversion (info->to_type, info->from,
3852 tf_warning_or_error);
3854 else if (info->n_arg == -2)
3855 /* Conversion of conversion function return value failed. */
3856 inform (loc, " no known conversion from %qH to %qI",
3857 from, info->to_type);
3858 else
3860 if (TREE_CODE (fn) == FUNCTION_DECL)
3861 loc = get_fndecl_argument_location (fn, info->n_arg);
3862 inform (loc, " no known conversion for argument %d from %qH to %qI",
3863 info->n_arg + 1, from, info->to_type);
3867 /* Print information about a candidate with WANT parameters and we found
3868 HAVE. */
3870 static void
3871 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3872 bool least_p)
3874 if (least_p)
3875 inform_n (loc, want,
3876 " candidate expects at least %d argument, %d provided",
3877 " candidate expects at least %d arguments, %d provided",
3878 want, have);
3879 else
3880 inform_n (loc, want,
3881 " candidate expects %d argument, %d provided",
3882 " candidate expects %d arguments, %d provided",
3883 want, have);
3886 /* Print information about one overload candidate CANDIDATE. MSGSTR
3887 is the text to print before the candidate itself.
3889 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3890 to have been run through gettext by the caller. This wart makes
3891 life simpler in print_z_candidates and for the translators. */
3893 static void
3894 print_z_candidate (location_t loc, const char *msgstr,
3895 struct z_candidate *candidate)
3897 const char *msg = (msgstr == NULL
3898 ? ""
3899 : ACONCAT ((_(msgstr), " ", NULL)));
3900 tree fn = candidate->fn;
3901 if (flag_new_inheriting_ctors)
3902 fn = strip_inheriting_ctors (fn);
3903 location_t cloc = location_of (fn);
3905 if (identifier_p (fn))
3907 cloc = loc;
3908 if (candidate->num_convs == 3)
3909 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3910 candidate->convs[0]->type,
3911 candidate->convs[1]->type,
3912 candidate->convs[2]->type);
3913 else if (candidate->num_convs == 2)
3914 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3915 candidate->convs[0]->type,
3916 candidate->convs[1]->type);
3917 else
3918 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3919 candidate->convs[0]->type);
3921 else if (TYPE_P (fn))
3922 inform (cloc, "%s%qT (conversion)", msg, fn);
3923 else if (candidate->viable == -1)
3924 inform (cloc, "%s%#qD (near match)", msg, fn);
3925 else if (DECL_DELETED_FN (fn))
3926 inform (cloc, "%s%#qD (deleted)", msg, fn);
3927 else if (candidate->reversed ())
3928 inform (cloc, "%s%#qD (reversed)", msg, fn);
3929 else if (candidate->rewritten ())
3930 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3931 else
3932 inform (cloc, "%s%#qD", msg, fn);
3933 if (fn != candidate->fn)
3935 cloc = location_of (candidate->fn);
3936 inform (cloc, " inherited here");
3938 /* Give the user some information about why this candidate failed. */
3939 if (candidate->reason != NULL)
3941 struct rejection_reason *r = candidate->reason;
3943 switch (r->code)
3945 case rr_arity:
3946 print_arity_information (cloc, r->u.arity.actual,
3947 r->u.arity.expected,
3948 r->u.arity.least_p);
3949 break;
3950 case rr_arg_conversion:
3951 print_conversion_rejection (cloc, &r->u.conversion, fn);
3952 break;
3953 case rr_bad_arg_conversion:
3954 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3955 break;
3956 case rr_explicit_conversion:
3957 inform (cloc, " return type %qT of explicit conversion function "
3958 "cannot be converted to %qT with a qualification "
3959 "conversion", r->u.conversion.from,
3960 r->u.conversion.to_type);
3961 break;
3962 case rr_template_conversion:
3963 inform (cloc, " conversion from return type %qT of template "
3964 "conversion function specialization to %qT is not an "
3965 "exact match", r->u.conversion.from,
3966 r->u.conversion.to_type);
3967 break;
3968 case rr_template_unification:
3969 /* We use template_unification_error_rejection if unification caused
3970 actual non-SFINAE errors, in which case we don't need to repeat
3971 them here. */
3972 if (r->u.template_unification.tmpl == NULL_TREE)
3974 inform (cloc, " substitution of deduced template arguments "
3975 "resulted in errors seen above");
3976 break;
3978 /* Re-run template unification with diagnostics. */
3979 inform (cloc, " template argument deduction/substitution failed:");
3980 fn_type_unification (r->u.template_unification.tmpl,
3981 r->u.template_unification.explicit_targs,
3982 (make_tree_vec
3983 (r->u.template_unification.num_targs)),
3984 r->u.template_unification.args,
3985 r->u.template_unification.nargs,
3986 r->u.template_unification.return_type,
3987 r->u.template_unification.strict,
3988 r->u.template_unification.flags,
3989 NULL, true, false);
3990 break;
3991 case rr_invalid_copy:
3992 inform (cloc,
3993 " a constructor taking a single argument of its own "
3994 "class type is invalid");
3995 break;
3996 case rr_constraint_failure:
3997 diagnose_constraints (cloc, fn, NULL_TREE);
3998 break;
3999 case rr_inherited_ctor:
4000 inform (cloc, " an inherited constructor is not a candidate for "
4001 "initialization from an expression of the same or derived "
4002 "type");
4003 break;
4004 case rr_none:
4005 default:
4006 /* This candidate didn't have any issues or we failed to
4007 handle a particular code. Either way... */
4008 gcc_unreachable ();
4013 static void
4014 print_z_candidates (location_t loc, struct z_candidate *candidates)
4016 struct z_candidate *cand1;
4017 struct z_candidate **cand2;
4019 if (!candidates)
4020 return;
4022 /* Remove non-viable deleted candidates. */
4023 cand1 = candidates;
4024 for (cand2 = &cand1; *cand2; )
4026 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4027 && !(*cand2)->viable
4028 && DECL_DELETED_FN ((*cand2)->fn))
4029 *cand2 = (*cand2)->next;
4030 else
4031 cand2 = &(*cand2)->next;
4033 /* ...if there are any non-deleted ones. */
4034 if (cand1)
4035 candidates = cand1;
4037 /* There may be duplicates in the set of candidates. We put off
4038 checking this condition as long as possible, since we have no way
4039 to eliminate duplicates from a set of functions in less than n^2
4040 time. Now we are about to emit an error message, so it is more
4041 permissible to go slowly. */
4042 for (cand1 = candidates; cand1; cand1 = cand1->next)
4044 tree fn = cand1->fn;
4045 /* Skip builtin candidates and conversion functions. */
4046 if (!DECL_P (fn))
4047 continue;
4048 cand2 = &cand1->next;
4049 while (*cand2)
4051 if (DECL_P ((*cand2)->fn)
4052 && equal_functions (fn, (*cand2)->fn))
4053 *cand2 = (*cand2)->next;
4054 else
4055 cand2 = &(*cand2)->next;
4059 for (; candidates; candidates = candidates->next)
4060 print_z_candidate (loc, N_("candidate:"), candidates);
4063 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4064 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4065 the result of the conversion function to convert it to the final
4066 desired type. Merge the two sequences into a single sequence,
4067 and return the merged sequence. */
4069 static conversion *
4070 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4072 conversion **t;
4073 bool bad = user_seq->bad_p;
4075 gcc_assert (user_seq->kind == ck_user);
4077 /* Find the end of the second conversion sequence. */
4078 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4080 /* The entire sequence is a user-conversion sequence. */
4081 (*t)->user_conv_p = true;
4082 if (bad)
4083 (*t)->bad_p = true;
4086 if ((*t)->rvaluedness_matches_p)
4087 /* We're binding a reference directly to the result of the conversion.
4088 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4089 type, but we want it back. */
4090 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4092 /* Replace the identity conversion with the user conversion
4093 sequence. */
4094 *t = user_seq;
4096 return std_seq;
4099 /* Handle overload resolution for initializing an object of class type from
4100 an initializer list. First we look for a suitable constructor that
4101 takes a std::initializer_list; if we don't find one, we then look for a
4102 non-list constructor.
4104 Parameters are as for add_candidates, except that the arguments are in
4105 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4106 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4108 static void
4109 add_list_candidates (tree fns, tree first_arg,
4110 const vec<tree, va_gc> *args, tree totype,
4111 tree explicit_targs, bool template_only,
4112 tree conversion_path, tree access_path,
4113 int flags,
4114 struct z_candidate **candidates,
4115 tsubst_flags_t complain)
4117 gcc_assert (*candidates == NULL);
4119 /* We're looking for a ctor for list-initialization. */
4120 flags |= LOOKUP_LIST_INIT_CTOR;
4121 /* And we don't allow narrowing conversions. We also use this flag to
4122 avoid the copy constructor call for copy-list-initialization. */
4123 flags |= LOOKUP_NO_NARROWING;
4125 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4126 tree init_list = (*args)[nart];
4128 /* Always use the default constructor if the list is empty (DR 990). */
4129 if (CONSTRUCTOR_NELTS (init_list) == 0
4130 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4132 /* If the class has a list ctor, try passing the list as a single
4133 argument first, but only consider list ctors. */
4134 else if (TYPE_HAS_LIST_CTOR (totype))
4136 flags |= LOOKUP_LIST_ONLY;
4137 add_candidates (fns, first_arg, args, NULL_TREE,
4138 explicit_targs, template_only, conversion_path,
4139 access_path, flags, candidates, complain);
4140 if (any_strictly_viable (*candidates))
4141 return;
4143 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4144 && !CP_AGGREGATE_TYPE_P (totype))
4146 if (complain & tf_error)
4147 error ("designated initializers cannot be used with a "
4148 "non-aggregate type %qT", totype);
4149 return;
4152 /* Expand the CONSTRUCTOR into a new argument vec. */
4153 vec<tree, va_gc> *new_args;
4154 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4155 for (unsigned i = 0; i < nart; ++i)
4156 new_args->quick_push ((*args)[i]);
4157 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4158 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4160 /* We aren't looking for list-ctors anymore. */
4161 flags &= ~LOOKUP_LIST_ONLY;
4162 /* We allow more user-defined conversions within an init-list. */
4163 flags &= ~LOOKUP_NO_CONVERSION;
4165 add_candidates (fns, first_arg, new_args, NULL_TREE,
4166 explicit_targs, template_only, conversion_path,
4167 access_path, flags, candidates, complain);
4170 /* Given C(std::initializer_list<A>), return A. */
4172 static tree
4173 list_ctor_element_type (tree fn)
4175 gcc_checking_assert (is_list_ctor (fn));
4177 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4178 parm = non_reference (TREE_VALUE (parm));
4179 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4182 /* If EXPR is a braced-init-list where the elements all decay to the same type,
4183 return that type. */
4185 static tree
4186 braced_init_element_type (tree expr)
4188 if (TREE_CODE (expr) == CONSTRUCTOR
4189 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4190 return TREE_TYPE (TREE_TYPE (expr));
4191 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4192 return NULL_TREE;
4194 tree elttype = NULL_TREE;
4195 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4197 tree type = TREE_TYPE (e.value);
4198 type = type_decays_to (type);
4199 if (!elttype)
4200 elttype = type;
4201 else if (!same_type_p (type, elttype))
4202 return NULL_TREE;
4204 return elttype;
4207 /* True iff EXPR contains any temporaries with non-trivial destruction.
4209 ??? Also ignore classes with non-trivial but no-op destruction other than
4210 std::allocator? */
4212 static bool
4213 has_non_trivial_temporaries (tree expr)
4215 auto_vec<tree*> temps;
4216 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4217 for (tree *p : temps)
4219 tree t = TREE_TYPE (*p);
4220 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4221 && !is_std_allocator (t))
4222 return true;
4224 return false;
4227 /* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4228 return INIT as an array (of its own type) so the caller can initialize the
4229 target array in a loop. */
4231 static tree
4232 maybe_init_list_as_array (tree elttype, tree init)
4234 /* Only do this if the array can go in rodata but not once converted. */
4235 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4236 return NULL_TREE;
4237 tree init_elttype = braced_init_element_type (init);
4238 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4239 return NULL_TREE;
4241 /* Check with a stub expression to weed out special cases, and check whether
4242 we call the same function for direct-init as copy-list-init. */
4243 conversion_obstack_sentinel cos;
4244 tree arg = build_stub_object (init_elttype);
4245 conversion *c = implicit_conversion (elttype, init_elttype, arg, false,
4246 LOOKUP_NORMAL, tf_none);
4247 if (c && c->kind == ck_rvalue)
4248 c = next_conversion (c);
4249 if (!c || c->kind != ck_user)
4250 return NULL_TREE;
4252 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4253 conversion *fc = implicit_conversion (elttype, init_elttype, first, false,
4254 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4255 tf_none);
4256 if (fc && fc->kind == ck_rvalue)
4257 fc = next_conversion (fc);
4258 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4259 return NULL_TREE;
4260 first = convert_like (fc, first, tf_none);
4261 if (first == error_mark_node)
4262 /* Let the normal code give the error. */
4263 return NULL_TREE;
4265 /* Don't do this if the conversion would be constant. */
4266 first = maybe_constant_init (first);
4267 if (TREE_CONSTANT (first))
4268 return NULL_TREE;
4270 /* We can't do this if the conversion creates temporaries that need
4271 to live until the whole array is initialized. */
4272 if (has_non_trivial_temporaries (first))
4273 return NULL_TREE;
4275 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4276 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4277 return finish_compound_literal (arr, init, tf_none);
4280 /* If we were going to call e.g. vector(initializer_list<string>) starting
4281 with a list of string-literals (which is inefficient, see PR105838),
4282 instead build an array of const char* and pass it to the range constructor.
4283 But only do this for standard library types, where we can assume the
4284 transformation makes sense.
4286 Really the container classes should have initializer_list<U> constructors to
4287 get the same effect more simply; this is working around that lack. */
4289 static tree
4290 maybe_init_list_as_range (tree fn, tree expr)
4292 if (!processing_template_decl
4293 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4294 && is_list_ctor (fn)
4295 && decl_in_std_namespace_p (fn))
4297 tree to = list_ctor_element_type (fn);
4298 if (tree init = maybe_init_list_as_array (to, expr))
4300 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4301 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4302 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4303 nelts, tf_none);
4304 begin = cp_build_compound_expr (init, begin, tf_none);
4305 return build_constructor_va (init_list_type_node, 2,
4306 NULL_TREE, begin, NULL_TREE, end);
4310 return NULL_TREE;
4313 /* Returns the best overload candidate to perform the requested
4314 conversion. This function is used for three the overloading situations
4315 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4316 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4317 per [dcl.init.ref], so we ignore temporary bindings. */
4319 static struct z_candidate *
4320 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4321 tsubst_flags_t complain)
4323 struct z_candidate *candidates, *cand;
4324 tree fromtype;
4325 tree ctors = NULL_TREE;
4326 tree conv_fns = NULL_TREE;
4327 conversion *conv = NULL;
4328 tree first_arg = NULL_TREE;
4329 vec<tree, va_gc> *args = NULL;
4330 bool any_viable_p;
4331 int convflags;
4333 if (!expr)
4334 return NULL;
4336 fromtype = TREE_TYPE (expr);
4338 /* We represent conversion within a hierarchy using RVALUE_CONV and
4339 BASE_CONV, as specified by [over.best.ics]; these become plain
4340 constructor calls, as specified in [dcl.init]. */
4341 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4342 || !DERIVED_FROM_P (totype, fromtype));
4344 if (CLASS_TYPE_P (totype))
4345 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4346 creating a garbage BASELINK; constructors can't be inherited. */
4347 ctors = get_class_binding (totype, complete_ctor_identifier);
4349 tree to_nonref = non_reference (totype);
4350 if (MAYBE_CLASS_TYPE_P (fromtype))
4352 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4353 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4354 && DERIVED_FROM_P (to_nonref, fromtype)))
4356 /* [class.conv.fct] A conversion function is never used to
4357 convert a (possibly cv-qualified) object to the (possibly
4358 cv-qualified) same object type (or a reference to it), to a
4359 (possibly cv-qualified) base class of that type (or a
4360 reference to it)... */
4362 else
4363 conv_fns = lookup_conversions (fromtype);
4366 candidates = 0;
4367 flags |= LOOKUP_NO_CONVERSION;
4368 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4369 flags |= LOOKUP_NO_NARROWING;
4370 /* Prevent add_candidates from treating a non-strictly viable candidate
4371 as unviable. */
4372 complain |= tf_conv;
4374 /* It's OK to bind a temporary for converting constructor arguments, but
4375 not in converting the return value of a conversion operator. */
4376 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4377 | (flags & LOOKUP_NO_NARROWING));
4378 flags &= ~LOOKUP_NO_TEMP_BIND;
4380 if (ctors)
4382 int ctorflags = flags;
4384 first_arg = build_dummy_object (totype);
4386 /* We should never try to call the abstract or base constructor
4387 from here. */
4388 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4389 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4391 args = make_tree_vector_single (expr);
4392 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4394 /* List-initialization. */
4395 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4396 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4397 ctorflags, &candidates, complain);
4399 else
4401 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4402 TYPE_BINFO (totype), TYPE_BINFO (totype),
4403 ctorflags, &candidates, complain);
4406 for (cand = candidates; cand; cand = cand->next)
4408 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4410 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4411 set, then this is copy-initialization. In that case, "The
4412 result of the call is then used to direct-initialize the
4413 object that is the destination of the copy-initialization."
4414 [dcl.init]
4416 We represent this in the conversion sequence with an
4417 rvalue conversion, which means a constructor call. */
4418 if (!TYPE_REF_P (totype)
4419 && cxx_dialect < cxx17
4420 && (flags & LOOKUP_ONLYCONVERTING)
4421 && !(convflags & LOOKUP_NO_TEMP_BIND))
4422 cand->second_conv
4423 = build_conv (ck_rvalue, totype, cand->second_conv);
4427 if (conv_fns)
4429 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4430 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4431 else
4432 first_arg = expr;
4435 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4437 tree conversion_path = TREE_PURPOSE (conv_fns);
4438 struct z_candidate *old_candidates;
4440 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4441 would need an addional user-defined conversion, i.e. if the return
4442 type differs in class-ness from the desired type. So we avoid
4443 considering operator bool when calling a copy constructor.
4445 This optimization avoids the failure in PR97600, and is allowed by
4446 [temp.inst]/9: "If the function selected by overload resolution can be
4447 determined without instantiating a class template definition, it is
4448 unspecified whether that instantiation actually takes place." */
4449 tree convtype = non_reference (TREE_TYPE (conv_fns));
4450 if ((flags & LOOKUP_NO_CONVERSION)
4451 && !WILDCARD_TYPE_P (convtype)
4452 && (CLASS_TYPE_P (to_nonref)
4453 != CLASS_TYPE_P (convtype)))
4454 continue;
4456 /* If we are called to convert to a reference type, we are trying to
4457 find a direct binding, so don't even consider temporaries. If
4458 we don't find a direct binding, the caller will try again to
4459 look for a temporary binding. */
4460 if (TYPE_REF_P (totype))
4461 convflags |= LOOKUP_NO_TEMP_BIND;
4463 old_candidates = candidates;
4464 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4465 NULL_TREE, false,
4466 conversion_path, TYPE_BINFO (fromtype),
4467 flags, &candidates, complain);
4469 for (cand = candidates; cand != old_candidates; cand = cand->next)
4471 if (cand->viable == 0)
4472 /* Already rejected, don't change to -1. */
4473 continue;
4475 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4476 conversion *ics
4477 = implicit_conversion (totype,
4478 rettype,
4480 /*c_cast_p=*/false, convflags,
4481 complain);
4483 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4484 copy-initialization. In that case, "The result of the
4485 call is then used to direct-initialize the object that is
4486 the destination of the copy-initialization." [dcl.init]
4488 We represent this in the conversion sequence with an
4489 rvalue conversion, which means a constructor call. But
4490 don't add a second rvalue conversion if there's already
4491 one there. Which there really shouldn't be, but it's
4492 harmless since we'd add it here anyway. */
4493 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4494 && !(convflags & LOOKUP_NO_TEMP_BIND))
4495 ics = build_conv (ck_rvalue, totype, ics);
4497 cand->second_conv = ics;
4499 if (!ics)
4501 cand->viable = 0;
4502 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4503 rettype, totype,
4504 EXPR_LOCATION (expr));
4506 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4507 /* Limit this to non-templates for now (PR90546). */
4508 && !cand->template_decl
4509 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4511 /* If we are called to convert to a reference type, we are trying
4512 to find a direct binding per [over.match.ref], so rvaluedness
4513 must match for non-functions. */
4514 cand->viable = 0;
4516 else if (DECL_NONCONVERTING_P (cand->fn)
4517 && ics->rank > cr_exact)
4519 /* 13.3.1.5: For direct-initialization, those explicit
4520 conversion functions that are not hidden within S and
4521 yield type T or a type that can be converted to type T
4522 with a qualification conversion (4.4) are also candidate
4523 functions. */
4524 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4525 I've raised this issue with the committee. --jason 9/2011 */
4526 cand->viable = -1;
4527 cand->reason = explicit_conversion_rejection (rettype, totype);
4529 else if (cand->viable == 1 && ics->bad_p)
4531 cand->viable = -1;
4532 cand->reason
4533 = bad_arg_conversion_rejection (NULL_TREE, -2,
4534 rettype, totype,
4535 EXPR_LOCATION (expr));
4537 else if (primary_template_specialization_p (cand->fn)
4538 && ics->rank > cr_exact)
4540 /* 13.3.3.1.2: If the user-defined conversion is specified by
4541 a specialization of a conversion function template, the
4542 second standard conversion sequence shall have exact match
4543 rank. */
4544 cand->viable = -1;
4545 cand->reason = template_conversion_rejection (rettype, totype);
4550 candidates = splice_viable (candidates, false, &any_viable_p);
4551 if (!any_viable_p)
4553 if (args)
4554 release_tree_vector (args);
4555 return NULL;
4558 cand = tourney (candidates, complain);
4559 if (cand == NULL)
4561 if (complain & tf_error)
4563 auto_diagnostic_group d;
4564 error_at (cp_expr_loc_or_input_loc (expr),
4565 "conversion from %qH to %qI is ambiguous",
4566 fromtype, totype);
4567 print_z_candidates (location_of (expr), candidates);
4570 cand = candidates; /* any one will do */
4571 cand->second_conv = build_ambiguous_conv (totype, expr);
4572 cand->second_conv->user_conv_p = true;
4573 if (!any_strictly_viable (candidates))
4574 cand->second_conv->bad_p = true;
4575 if (flags & LOOKUP_ONLYCONVERTING)
4576 cand->second_conv->need_temporary_p = true;
4577 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4578 ambiguous conversion is no worse than another user-defined
4579 conversion. */
4581 return cand;
4584 /* Maybe pass { } as iterators instead of an initializer_list. */
4585 if (tree iters = maybe_init_list_as_range (cand->fn, expr))
4586 if (z_candidate *cand2
4587 = build_user_type_conversion_1 (totype, iters, flags, tf_none))
4588 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4590 cand = cand2;
4591 expr = iters;
4594 tree convtype;
4595 if (!DECL_CONSTRUCTOR_P (cand->fn))
4596 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4597 else if (cand->second_conv->kind == ck_rvalue)
4598 /* DR 5: [in the first step of copy-initialization]...if the function
4599 is a constructor, the call initializes a temporary of the
4600 cv-unqualified version of the destination type. */
4601 convtype = cv_unqualified (totype);
4602 else
4603 convtype = totype;
4604 /* Build the user conversion sequence. */
4605 conv = build_conv
4606 (ck_user,
4607 convtype,
4608 build_identity_conv (TREE_TYPE (expr), expr));
4609 conv->cand = cand;
4610 if (cand->viable == -1)
4611 conv->bad_p = true;
4613 /* Remember that this was a list-initialization. */
4614 if (flags & LOOKUP_NO_NARROWING)
4615 conv->check_narrowing = true;
4617 /* Combine it with the second conversion sequence. */
4618 cand->second_conv = merge_conversion_sequences (conv,
4619 cand->second_conv);
4621 return cand;
4624 /* Wrapper for above. */
4626 tree
4627 build_user_type_conversion (tree totype, tree expr, int flags,
4628 tsubst_flags_t complain)
4630 struct z_candidate *cand;
4631 tree ret;
4633 auto_cond_timevar tv (TV_OVERLOAD);
4634 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4636 if (cand)
4638 if (cand->second_conv->kind == ck_ambig)
4639 ret = error_mark_node;
4640 else
4642 expr = convert_like (cand->second_conv, expr, complain);
4643 ret = convert_from_reference (expr);
4646 else
4647 ret = NULL_TREE;
4649 return ret;
4652 /* Give a helpful diagnostic when implicit_conversion fails. */
4654 static void
4655 implicit_conversion_error (location_t loc, tree type, tree expr)
4657 tsubst_flags_t complain = tf_warning_or_error;
4659 /* If expr has unknown type, then it is an overloaded function.
4660 Call instantiate_type to get good error messages. */
4661 if (TREE_TYPE (expr) == unknown_type_node)
4662 instantiate_type (type, expr, complain);
4663 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4664 /* We gave an error. */;
4665 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4666 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4667 && !CP_AGGREGATE_TYPE_P (type))
4668 error_at (loc, "designated initializers cannot be used with a "
4669 "non-aggregate type %qT", type);
4670 else
4672 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4673 gcc_rich_location rich_loc (loc, &label);
4674 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4675 expr, TREE_TYPE (expr), type);
4679 /* Worker for build_converted_constant_expr. */
4681 static tree
4682 build_converted_constant_expr_internal (tree type, tree expr,
4683 int flags, tsubst_flags_t complain)
4685 conversion *conv;
4686 void *p;
4687 tree t;
4688 location_t loc = cp_expr_loc_or_input_loc (expr);
4690 if (error_operand_p (expr))
4691 return error_mark_node;
4693 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4694 p = conversion_obstack_alloc (0);
4696 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4697 /*c_cast_p=*/false, flags, complain);
4699 /* A converted constant expression of type T is an expression, implicitly
4700 converted to type T, where the converted expression is a constant
4701 expression and the implicit conversion sequence contains only
4703 * user-defined conversions,
4704 * lvalue-to-rvalue conversions (7.1),
4705 * array-to-pointer conversions (7.2),
4706 * function-to-pointer conversions (7.3),
4707 * qualification conversions (7.5),
4708 * integral promotions (7.6),
4709 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4710 * null pointer conversions (7.11) from std::nullptr_t,
4711 * null member pointer conversions (7.12) from std::nullptr_t, and
4712 * function pointer conversions (7.13),
4714 and where the reference binding (if any) binds directly. */
4716 for (conversion *c = conv;
4717 c && c->kind != ck_identity;
4718 c = next_conversion (c))
4720 switch (c->kind)
4722 /* A conversion function is OK. If it isn't constexpr, we'll
4723 complain later that the argument isn't constant. */
4724 case ck_user:
4725 /* List-initialization is OK. */
4726 case ck_aggr:
4727 /* The lvalue-to-rvalue conversion is OK. */
4728 case ck_rvalue:
4729 /* Array-to-pointer and function-to-pointer. */
4730 case ck_lvalue:
4731 /* Function pointer conversions. */
4732 case ck_fnptr:
4733 /* Qualification conversions. */
4734 case ck_qual:
4735 break;
4737 case ck_ref_bind:
4738 if (c->need_temporary_p)
4740 if (complain & tf_error)
4741 error_at (loc, "initializing %qH with %qI in converted "
4742 "constant expression does not bind directly",
4743 type, next_conversion (c)->type);
4744 conv = NULL;
4746 break;
4748 case ck_base:
4749 case ck_pmem:
4750 case ck_ptr:
4751 case ck_std:
4752 t = next_conversion (c)->type;
4753 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4754 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4755 /* Integral promotion or conversion. */
4756 break;
4757 if (NULLPTR_TYPE_P (t))
4758 /* Conversion from nullptr to pointer or pointer-to-member. */
4759 break;
4761 if (complain & tf_error)
4762 error_at (loc, "conversion from %qH to %qI in a "
4763 "converted constant expression", t, type);
4764 /* fall through. */
4766 default:
4767 conv = NULL;
4768 break;
4772 /* Avoid confusing convert_nontype_argument by introducing
4773 a redundant conversion to the same reference type. */
4774 if (conv && conv->kind == ck_ref_bind
4775 && REFERENCE_REF_P (expr))
4777 tree ref = TREE_OPERAND (expr, 0);
4778 if (same_type_p (type, TREE_TYPE (ref)))
4779 return ref;
4782 if (conv)
4784 /* Don't copy a class in a template. */
4785 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4786 && processing_template_decl)
4787 conv = next_conversion (conv);
4789 /* Issuing conversion warnings for value-dependent expressions is
4790 likely too noisy. */
4791 warning_sentinel w (warn_conversion);
4792 conv->check_narrowing = true;
4793 conv->check_narrowing_const_only = true;
4794 expr = convert_like (conv, expr, complain);
4796 else
4798 if (complain & tf_error)
4799 implicit_conversion_error (loc, type, expr);
4800 expr = error_mark_node;
4803 /* Free all the conversions we allocated. */
4804 obstack_free (&conversion_obstack, p);
4806 return expr;
4809 /* Subroutine of convert_nontype_argument.
4811 EXPR is an expression used in a context that requires a converted
4812 constant-expression, such as a template non-type parameter. Do any
4813 necessary conversions (that are permitted for converted
4814 constant-expressions) to convert it to the desired type.
4816 This function doesn't consider explicit conversion functions. If
4817 you mean to use "a contextually converted constant expression of type
4818 bool", use build_converted_constant_bool_expr.
4820 If conversion is successful, returns the converted expression;
4821 otherwise, returns error_mark_node. */
4823 tree
4824 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4826 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4827 complain);
4830 /* Used to create "a contextually converted constant expression of type
4831 bool". This differs from build_converted_constant_expr in that it
4832 also considers explicit conversion functions. */
4834 tree
4835 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4837 return build_converted_constant_expr_internal (boolean_type_node, expr,
4838 LOOKUP_NORMAL, complain);
4841 /* Do any initial processing on the arguments to a function call. */
4843 vec<tree, va_gc> *
4844 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4846 unsigned int ix;
4847 tree arg;
4849 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4851 if (error_operand_p (arg))
4852 return NULL;
4853 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4855 if (complain & tf_error)
4856 error_at (cp_expr_loc_or_input_loc (arg),
4857 "invalid use of void expression");
4858 return NULL;
4860 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4861 return NULL;
4863 /* Force auto deduction now. Omit tf_warning to avoid redundant
4864 deprecated warning on deprecated-14.C. */
4865 if (!mark_single_function (arg, complain & ~tf_warning))
4866 return NULL;
4868 return args;
4871 /* Perform overload resolution on FN, which is called with the ARGS.
4873 Return the candidate function selected by overload resolution, or
4874 NULL if the event that overload resolution failed. In the case
4875 that overload resolution fails, *CANDIDATES will be the set of
4876 candidates considered, and ANY_VIABLE_P will be set to true or
4877 false to indicate whether or not any of the candidates were
4878 viable.
4880 The ARGS should already have gone through RESOLVE_ARGS before this
4881 function is called. */
4883 static struct z_candidate *
4884 perform_overload_resolution (tree fn,
4885 const vec<tree, va_gc> *args,
4886 struct z_candidate **candidates,
4887 bool *any_viable_p, tsubst_flags_t complain)
4889 struct z_candidate *cand;
4890 tree explicit_targs;
4891 int template_only;
4893 auto_cond_timevar tv (TV_OVERLOAD);
4895 explicit_targs = NULL_TREE;
4896 template_only = 0;
4898 *candidates = NULL;
4899 *any_viable_p = true;
4901 /* Check FN. */
4902 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4904 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4906 explicit_targs = TREE_OPERAND (fn, 1);
4907 fn = TREE_OPERAND (fn, 0);
4908 template_only = 1;
4911 /* Add the various candidate functions. */
4912 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4913 explicit_targs, template_only,
4914 /*conversion_path=*/NULL_TREE,
4915 /*access_path=*/NULL_TREE,
4916 LOOKUP_NORMAL,
4917 candidates, complain);
4919 *candidates = splice_viable (*candidates, false, any_viable_p);
4920 if (*any_viable_p)
4921 cand = tourney (*candidates, complain);
4922 else
4923 cand = NULL;
4925 return cand;
4928 /* Print an error message about being unable to build a call to FN with
4929 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4930 be located; CANDIDATES is a possibly empty list of such
4931 functions. */
4933 static void
4934 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4935 struct z_candidate *candidates)
4937 tree targs = NULL_TREE;
4938 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4940 targs = TREE_OPERAND (fn, 1);
4941 fn = TREE_OPERAND (fn, 0);
4943 tree name = OVL_NAME (fn);
4944 location_t loc = location_of (name);
4945 if (targs)
4946 name = lookup_template_function (name, targs);
4948 auto_diagnostic_group d;
4949 if (!any_strictly_viable (candidates))
4950 error_at (loc, "no matching function for call to %<%D(%A)%>",
4951 name, build_tree_list_vec (args));
4952 else
4953 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4954 name, build_tree_list_vec (args));
4955 if (candidates)
4956 print_z_candidates (loc, candidates);
4959 /* Perform overload resolution on the set of deduction guides DGUIDES
4960 using ARGS. Returns the selected deduction guide, or error_mark_node
4961 if overload resolution fails. */
4963 tree
4964 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4965 tsubst_flags_t complain)
4967 z_candidate *candidates;
4968 bool any_viable_p;
4969 tree result;
4971 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4973 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4974 void *p = conversion_obstack_alloc (0);
4976 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
4977 &any_viable_p, complain);
4978 if (!cand)
4980 if (complain & tf_error)
4981 print_error_for_call_failure (dguides, args, candidates);
4982 result = error_mark_node;
4984 else
4985 result = cand->fn;
4987 /* Free all the conversions we allocated. */
4988 obstack_free (&conversion_obstack, p);
4990 return result;
4993 /* Return an expression for a call to FN (a namespace-scope function,
4994 or a static member function) with the ARGS. This may change
4995 ARGS. */
4997 tree
4998 build_new_function_call (tree fn, vec<tree, va_gc> **args,
4999 tsubst_flags_t complain)
5001 struct z_candidate *candidates, *cand;
5002 bool any_viable_p;
5003 void *p;
5004 tree result;
5006 if (args != NULL && *args != NULL)
5008 *args = resolve_args (*args, complain);
5009 if (*args == NULL)
5010 return error_mark_node;
5013 if (flag_tm)
5014 tm_malloc_replacement (fn);
5016 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5017 p = conversion_obstack_alloc (0);
5019 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
5020 complain);
5022 if (!cand)
5024 if (complain & tf_error)
5026 // If there is a single (non-viable) function candidate,
5027 // let the error be diagnosed by cp_build_function_call_vec.
5028 if (!any_viable_p && candidates && ! candidates->next
5029 && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
5030 return cp_build_function_call_vec (candidates->fn, args, complain);
5032 // Otherwise, emit notes for non-viable candidates.
5033 print_error_for_call_failure (fn, *args, candidates);
5035 result = error_mark_node;
5037 else
5039 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5042 if (flag_coroutines
5043 && result
5044 && TREE_CODE (result) == CALL_EXPR
5045 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5046 == BUILT_IN_NORMAL)
5047 result = coro_validate_builtin_call (result);
5049 /* Free all the conversions we allocated. */
5050 obstack_free (&conversion_obstack, p);
5052 return result;
5055 /* Build a call to a global operator new. FNNAME is the name of the
5056 operator (either "operator new" or "operator new[]") and ARGS are
5057 the arguments provided. This may change ARGS. *SIZE points to the
5058 total number of bytes required by the allocation, and is updated if
5059 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5060 be used. If this function determines that no cookie should be
5061 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5062 is not NULL_TREE, it is evaluated before calculating the final
5063 array size, and if it fails, the array size is replaced with
5064 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5065 is non-NULL, it will be set, upon return, to the allocation
5066 function called. */
5068 tree
5069 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5070 tree *size, tree *cookie_size,
5071 tree align_arg, tree size_check,
5072 tree *fn, tsubst_flags_t complain)
5074 tree original_size = *size;
5075 tree fns;
5076 struct z_candidate *candidates;
5077 struct z_candidate *cand = NULL;
5078 bool any_viable_p;
5080 if (fn)
5081 *fn = NULL_TREE;
5082 /* Set to (size_t)-1 if the size check fails. */
5083 if (size_check != NULL_TREE)
5085 tree errval = TYPE_MAX_VALUE (sizetype);
5086 if (cxx_dialect >= cxx11 && flag_exceptions)
5087 errval = throw_bad_array_new_length ();
5088 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5089 original_size, errval);
5091 vec_safe_insert (*args, 0, *size);
5092 *args = resolve_args (*args, complain);
5093 if (*args == NULL)
5094 return error_mark_node;
5096 /* Based on:
5098 [expr.new]
5100 If this lookup fails to find the name, or if the allocated type
5101 is not a class type, the allocation function's name is looked
5102 up in the global scope.
5104 we disregard block-scope declarations of "operator new". */
5105 fns = lookup_qualified_name (global_namespace, fnname);
5107 if (align_arg)
5109 vec<tree, va_gc>* align_args
5110 = vec_copy_and_insert (*args, align_arg, 1);
5111 cand = perform_overload_resolution (fns, align_args, &candidates,
5112 &any_viable_p, tf_none);
5113 if (cand)
5114 *args = align_args;
5115 /* If no aligned allocation function matches, try again without the
5116 alignment. */
5119 /* Figure out what function is being called. */
5120 if (!cand)
5121 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
5122 complain);
5124 /* If no suitable function could be found, issue an error message
5125 and give up. */
5126 if (!cand)
5128 if (complain & tf_error)
5129 print_error_for_call_failure (fns, *args, candidates);
5130 return error_mark_node;
5133 /* If a cookie is required, add some extra space. Whether
5134 or not a cookie is required cannot be determined until
5135 after we know which function was called. */
5136 if (*cookie_size)
5138 bool use_cookie = true;
5139 tree arg_types;
5141 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5142 /* Skip the size_t parameter. */
5143 arg_types = TREE_CHAIN (arg_types);
5144 /* Check the remaining parameters (if any). */
5145 if (arg_types
5146 && TREE_CHAIN (arg_types) == void_list_node
5147 && same_type_p (TREE_VALUE (arg_types),
5148 ptr_type_node))
5149 use_cookie = false;
5150 /* If we need a cookie, adjust the number of bytes allocated. */
5151 if (use_cookie)
5153 /* Update the total size. */
5154 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5155 if (size_check)
5157 /* Set to (size_t)-1 if the size check fails. */
5158 gcc_assert (size_check != NULL_TREE);
5159 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5160 *size, TYPE_MAX_VALUE (sizetype));
5162 /* Update the argument list to reflect the adjusted size. */
5163 (**args)[0] = *size;
5165 else
5166 *cookie_size = NULL_TREE;
5169 /* Tell our caller which function we decided to call. */
5170 if (fn)
5171 *fn = cand->fn;
5173 /* Build the CALL_EXPR. */
5174 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5176 /* Set this flag for all callers of this function. In addition to
5177 new-expressions, this is called for allocating coroutine state; treat
5178 that as an implicit new-expression. */
5179 tree call = extract_call_expr (ret);
5180 if (TREE_CODE (call) == CALL_EXPR)
5181 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5183 return ret;
5186 /* Evaluate side-effects from OBJ before evaluating call
5187 to FN in RESULT expression.
5188 This is for expressions of the form `obj->fn(...)'
5189 where `fn' turns out to be a static member function and
5190 `obj' needs to be evaluated. `fn' could be also static operator[]
5191 or static operator(), in which cases the source expression
5192 would be `obj[...]' or `obj(...)'. */
5194 tree
5195 keep_unused_object_arg (tree result, tree obj, tree fn)
5197 if (result == NULL_TREE
5198 || result == error_mark_node
5199 || TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
5200 || !TREE_SIDE_EFFECTS (obj))
5201 return result;
5203 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5204 volatile. */
5205 tree a = obj;
5206 if (TREE_THIS_VOLATILE (a))
5207 a = build_this (a);
5208 if (TREE_SIDE_EFFECTS (a))
5209 return build2 (COMPOUND_EXPR, TREE_TYPE (result), a, result);
5210 return result;
5213 /* Build a new call to operator(). This may change ARGS. */
5215 tree
5216 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5218 struct z_candidate *candidates = 0, *cand;
5219 tree fns, convs, first_mem_arg = NULL_TREE;
5220 bool any_viable_p;
5221 tree result = NULL_TREE;
5222 void *p;
5224 auto_cond_timevar tv (TV_OVERLOAD);
5226 obj = mark_lvalue_use (obj);
5228 if (error_operand_p (obj))
5229 return error_mark_node;
5231 tree type = TREE_TYPE (obj);
5233 obj = prep_operand (obj);
5235 if (TYPE_PTRMEMFUNC_P (type))
5237 if (complain & tf_error)
5238 /* It's no good looking for an overloaded operator() on a
5239 pointer-to-member-function. */
5240 error ("pointer-to-member function %qE cannot be called without "
5241 "an object; consider using %<.*%> or %<->*%>", obj);
5242 return error_mark_node;
5245 if (TYPE_BINFO (type))
5247 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5248 if (fns == error_mark_node)
5249 return error_mark_node;
5251 else
5252 fns = NULL_TREE;
5254 if (args != NULL && *args != NULL)
5256 *args = resolve_args (*args, complain);
5257 if (*args == NULL)
5258 return error_mark_node;
5261 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5262 p = conversion_obstack_alloc (0);
5264 if (fns)
5266 first_mem_arg = obj;
5268 add_candidates (BASELINK_FUNCTIONS (fns),
5269 first_mem_arg, *args, NULL_TREE,
5270 NULL_TREE, false,
5271 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5272 LOOKUP_NORMAL, &candidates, complain);
5275 convs = lookup_conversions (type);
5277 for (; convs; convs = TREE_CHAIN (convs))
5279 tree totype = TREE_TYPE (convs);
5281 if (TYPE_PTRFN_P (totype)
5282 || TYPE_REFFN_P (totype)
5283 || (TYPE_REF_P (totype)
5284 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5285 for (tree fn : ovl_range (TREE_VALUE (convs)))
5287 if (DECL_NONCONVERTING_P (fn))
5288 continue;
5290 if (TREE_CODE (fn) == TEMPLATE_DECL)
5291 add_template_conv_candidate
5292 (&candidates, fn, obj, *args, totype,
5293 /*access_path=*/NULL_TREE,
5294 /*conversion_path=*/NULL_TREE, complain);
5295 else
5296 add_conv_candidate (&candidates, fn, obj,
5297 *args, /*conversion_path=*/NULL_TREE,
5298 /*access_path=*/NULL_TREE, complain);
5302 /* Be strict here because if we choose a bad conversion candidate, the
5303 errors we get won't mention the call context. */
5304 candidates = splice_viable (candidates, true, &any_viable_p);
5305 if (!any_viable_p)
5307 if (complain & tf_error)
5309 auto_diagnostic_group d;
5310 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5311 build_tree_list_vec (*args));
5312 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5314 result = error_mark_node;
5316 else
5318 cand = tourney (candidates, complain);
5319 if (cand == 0)
5321 if (complain & tf_error)
5323 auto_diagnostic_group d;
5324 error ("call of %<(%T) (%A)%> is ambiguous",
5325 TREE_TYPE (obj), build_tree_list_vec (*args));
5326 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5328 result = error_mark_node;
5330 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5331 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5332 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5334 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5335 /* In an expression of the form `a()' where cand->fn
5336 which is operator() turns out to be a static member function,
5337 `a' is none-the-less evaluated. */
5338 result = keep_unused_object_arg (result, obj, cand->fn);
5340 else
5342 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5343 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5344 -1, complain);
5345 else
5347 gcc_checking_assert (TYPE_P (cand->fn));
5348 obj = convert_like (cand->convs[0], obj, complain);
5350 obj = convert_from_reference (obj);
5351 result = cp_build_function_call_vec (obj, args, complain);
5355 /* Free all the conversions we allocated. */
5356 obstack_free (&conversion_obstack, p);
5358 return result;
5361 /* Called by op_error to prepare format strings suitable for the error
5362 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5363 and a suffix (controlled by NTYPES). */
5365 static const char *
5366 op_error_string (const char *errmsg, int ntypes, bool match)
5368 const char *msg;
5370 const char *msgp = concat (match ? G_("ambiguous overload for ")
5371 : G_("no match for "), errmsg, NULL);
5373 if (ntypes == 3)
5374 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5375 else if (ntypes == 2)
5376 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5377 else
5378 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5380 return msg;
5383 static void
5384 op_error (const op_location_t &loc,
5385 enum tree_code code, enum tree_code code2,
5386 tree arg1, tree arg2, tree arg3, bool match)
5388 bool assop = code == MODIFY_EXPR;
5389 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5391 switch (code)
5393 case COND_EXPR:
5394 if (flag_diagnostics_show_caret)
5395 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5396 3, match),
5397 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5398 else
5399 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5400 "in %<%E ? %E : %E%>"), 3, match),
5401 arg1, arg2, arg3,
5402 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5403 break;
5405 case POSTINCREMENT_EXPR:
5406 case POSTDECREMENT_EXPR:
5407 if (flag_diagnostics_show_caret)
5408 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5409 opname, TREE_TYPE (arg1));
5410 else
5411 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5412 1, match),
5413 opname, arg1, opname, TREE_TYPE (arg1));
5414 break;
5416 case ARRAY_REF:
5417 if (flag_diagnostics_show_caret)
5418 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5419 TREE_TYPE (arg1), TREE_TYPE (arg2));
5420 else
5421 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5422 2, match),
5423 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5424 break;
5426 case REALPART_EXPR:
5427 case IMAGPART_EXPR:
5428 if (flag_diagnostics_show_caret)
5429 error_at (loc, op_error_string (G_("%qs"), 1, match),
5430 opname, TREE_TYPE (arg1));
5431 else
5432 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5433 opname, opname, arg1, TREE_TYPE (arg1));
5434 break;
5436 case CO_AWAIT_EXPR:
5437 if (flag_diagnostics_show_caret)
5438 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5439 opname, TREE_TYPE (arg1));
5440 else
5441 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5442 1, match),
5443 opname, opname, arg1, TREE_TYPE (arg1));
5444 break;
5446 default:
5447 if (arg2)
5448 if (flag_diagnostics_show_caret)
5450 binary_op_rich_location richloc (loc, arg1, arg2, true);
5451 error_at (&richloc,
5452 op_error_string (G_("%<operator%s%>"), 2, match),
5453 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5455 else
5456 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5457 2, match),
5458 opname, arg1, opname, arg2,
5459 TREE_TYPE (arg1), TREE_TYPE (arg2));
5460 else
5461 if (flag_diagnostics_show_caret)
5462 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5463 opname, TREE_TYPE (arg1));
5464 else
5465 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5466 1, match),
5467 opname, opname, arg1, TREE_TYPE (arg1));
5468 break;
5472 /* Return the implicit conversion sequence that could be used to
5473 convert E1 to E2 in [expr.cond]. */
5475 static conversion *
5476 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5478 tree t1 = non_reference (TREE_TYPE (e1));
5479 tree t2 = non_reference (TREE_TYPE (e2));
5480 conversion *conv;
5481 bool good_base;
5483 /* [expr.cond]
5485 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5486 implicitly converted (clause _conv_) to the type "lvalue reference to
5487 T2", subject to the constraint that in the conversion the
5488 reference must bind directly (_dcl.init.ref_) to an lvalue.
5490 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5491 implicitly converted to the type "rvalue reference to T2", subject to
5492 the constraint that the reference must bind directly. */
5493 if (glvalue_p (e2))
5495 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5496 conv = implicit_conversion (rtype,
5499 /*c_cast_p=*/false,
5500 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5501 |LOOKUP_ONLYCONVERTING,
5502 complain);
5503 if (conv && !conv->bad_p)
5504 return conv;
5507 /* If E2 is a prvalue or if neither of the conversions above can be done
5508 and at least one of the operands has (possibly cv-qualified) class
5509 type: */
5510 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5511 return NULL;
5513 /* [expr.cond]
5515 If E1 and E2 have class type, and the underlying class types are
5516 the same or one is a base class of the other: E1 can be converted
5517 to match E2 if the class of T2 is the same type as, or a base
5518 class of, the class of T1, and the cv-qualification of T2 is the
5519 same cv-qualification as, or a greater cv-qualification than, the
5520 cv-qualification of T1. If the conversion is applied, E1 is
5521 changed to an rvalue of type T2 that still refers to the original
5522 source class object (or the appropriate subobject thereof). */
5523 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5524 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5526 if (good_base && at_least_as_qualified_p (t2, t1))
5528 conv = build_identity_conv (t1, e1);
5529 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5530 TYPE_MAIN_VARIANT (t2)))
5531 conv = build_conv (ck_base, t2, conv);
5532 else
5533 conv = build_conv (ck_rvalue, t2, conv);
5534 return conv;
5536 else
5537 return NULL;
5539 else
5540 /* [expr.cond]
5542 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5543 converted to the type that expression E2 would have if E2 were
5544 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5545 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5546 LOOKUP_IMPLICIT, complain);
5549 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5550 arguments to the conditional expression. */
5552 tree
5553 build_conditional_expr (const op_location_t &loc,
5554 tree arg1, tree arg2, tree arg3,
5555 tsubst_flags_t complain)
5557 tree arg2_type;
5558 tree arg3_type;
5559 tree result = NULL_TREE;
5560 tree result_type = NULL_TREE;
5561 tree semantic_result_type = NULL_TREE;
5562 bool is_glvalue = true;
5563 struct z_candidate *candidates = 0;
5564 struct z_candidate *cand;
5565 void *p;
5566 tree orig_arg2, orig_arg3;
5568 auto_cond_timevar tv (TV_OVERLOAD);
5570 /* As a G++ extension, the second argument to the conditional can be
5571 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5572 c'.) If the second operand is omitted, make sure it is
5573 calculated only once. */
5574 if (!arg2)
5576 if (complain & tf_error)
5577 pedwarn (loc, OPT_Wpedantic,
5578 "ISO C++ forbids omitting the middle term of "
5579 "a %<?:%> expression");
5581 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5582 warn_for_omitted_condop (loc, arg1);
5584 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5585 if (glvalue_p (arg1))
5587 arg1 = cp_stabilize_reference (arg1);
5588 arg2 = arg1 = prevent_lifetime_extension (arg1);
5590 else if (TREE_CODE (arg1) == TARGET_EXPR)
5591 /* arg1 can't be a prvalue result of the conditional
5592 expression, since it needs to be materialized for the
5593 conversion to bool, so treat it as an xvalue in arg2. */
5594 arg2 = move (TARGET_EXPR_SLOT (arg1));
5595 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5596 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5597 cp_save_expr (TREE_OPERAND (arg1, 0)));
5598 else
5599 arg2 = arg1 = cp_save_expr (arg1);
5602 /* If something has already gone wrong, just pass that fact up the
5603 tree. */
5604 if (error_operand_p (arg1)
5605 || error_operand_p (arg2)
5606 || error_operand_p (arg3))
5607 return error_mark_node;
5609 orig_arg2 = arg2;
5610 orig_arg3 = arg3;
5612 if (gnu_vector_type_p (TREE_TYPE (arg1))
5613 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5615 tree arg1_type = TREE_TYPE (arg1);
5617 /* If arg1 is another cond_expr choosing between -1 and 0,
5618 then we can use its comparison. It may help to avoid
5619 additional comparison, produce more accurate diagnostics
5620 and enables folding. */
5621 if (TREE_CODE (arg1) == VEC_COND_EXPR
5622 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5623 && integer_zerop (TREE_OPERAND (arg1, 2)))
5624 arg1 = TREE_OPERAND (arg1, 0);
5626 arg1 = force_rvalue (arg1, complain);
5627 arg2 = force_rvalue (arg2, complain);
5628 arg3 = force_rvalue (arg3, complain);
5630 /* force_rvalue can return error_mark on valid arguments. */
5631 if (error_operand_p (arg1)
5632 || error_operand_p (arg2)
5633 || error_operand_p (arg3))
5634 return error_mark_node;
5636 arg2_type = TREE_TYPE (arg2);
5637 arg3_type = TREE_TYPE (arg3);
5639 if (!VECTOR_TYPE_P (arg2_type)
5640 && !VECTOR_TYPE_P (arg3_type))
5642 /* Rely on the error messages of the scalar version. */
5643 tree scal = build_conditional_expr (loc, integer_one_node,
5644 orig_arg2, orig_arg3, complain);
5645 if (scal == error_mark_node)
5646 return error_mark_node;
5647 tree stype = TREE_TYPE (scal);
5648 tree ctype = TREE_TYPE (arg1_type);
5649 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5650 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5652 if (complain & tf_error)
5653 error_at (loc, "inferred scalar type %qT is not an integer or "
5654 "floating-point type of the same size as %qT", stype,
5655 COMPARISON_CLASS_P (arg1)
5656 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5657 : ctype);
5658 return error_mark_node;
5661 tree vtype = build_opaque_vector_type (stype,
5662 TYPE_VECTOR_SUBPARTS (arg1_type));
5663 /* We could pass complain & tf_warning to unsafe_conversion_p,
5664 but the warnings (like Wsign-conversion) have already been
5665 given by the scalar build_conditional_expr_1. We still check
5666 unsafe_conversion_p to forbid truncating long long -> float. */
5667 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5669 if (complain & tf_error)
5670 error_at (loc, "conversion of scalar %qH to vector %qI "
5671 "involves truncation", arg2_type, vtype);
5672 return error_mark_node;
5674 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5676 if (complain & tf_error)
5677 error_at (loc, "conversion of scalar %qH to vector %qI "
5678 "involves truncation", arg3_type, vtype);
5679 return error_mark_node;
5682 arg2 = cp_convert (stype, arg2, complain);
5683 arg2 = save_expr (arg2);
5684 arg2 = build_vector_from_val (vtype, arg2);
5685 arg2_type = vtype;
5686 arg3 = cp_convert (stype, arg3, complain);
5687 arg3 = save_expr (arg3);
5688 arg3 = build_vector_from_val (vtype, arg3);
5689 arg3_type = vtype;
5692 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5693 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5695 enum stv_conv convert_flag =
5696 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5697 complain & tf_error);
5699 switch (convert_flag)
5701 case stv_error:
5702 return error_mark_node;
5703 case stv_firstarg:
5705 arg2 = save_expr (arg2);
5706 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5707 arg2 = build_vector_from_val (arg3_type, arg2);
5708 arg2_type = TREE_TYPE (arg2);
5709 break;
5711 case stv_secondarg:
5713 arg3 = save_expr (arg3);
5714 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5715 arg3 = build_vector_from_val (arg2_type, arg3);
5716 arg3_type = TREE_TYPE (arg3);
5717 break;
5719 default:
5720 break;
5724 if (!gnu_vector_type_p (arg2_type)
5725 || !gnu_vector_type_p (arg3_type)
5726 || !same_type_p (arg2_type, arg3_type)
5727 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5728 TYPE_VECTOR_SUBPARTS (arg2_type))
5729 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5731 if (complain & tf_error)
5732 error_at (loc,
5733 "incompatible vector types in conditional expression: "
5734 "%qT, %qT and %qT", TREE_TYPE (arg1),
5735 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5736 return error_mark_node;
5739 if (!COMPARISON_CLASS_P (arg1))
5741 tree cmp_type = truth_type_for (arg1_type);
5742 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5744 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5747 /* [expr.cond]
5749 The first expression is implicitly converted to bool (clause
5750 _conv_). */
5751 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5752 LOOKUP_NORMAL);
5753 if (error_operand_p (arg1))
5754 return error_mark_node;
5756 arg2_type = unlowered_expr_type (arg2);
5757 arg3_type = unlowered_expr_type (arg3);
5759 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5760 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5761 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5762 || TREE_CODE (arg2_type) == REAL_TYPE
5763 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5764 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5765 || TREE_CODE (arg3_type) == REAL_TYPE
5766 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5768 semantic_result_type
5769 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5770 if (semantic_result_type == error_mark_node)
5772 tree t1 = arg2_type;
5773 tree t2 = arg3_type;
5774 if (TREE_CODE (t1) == COMPLEX_TYPE)
5775 t1 = TREE_TYPE (t1);
5776 if (TREE_CODE (t2) == COMPLEX_TYPE)
5777 t2 = TREE_TYPE (t2);
5778 gcc_checking_assert (TREE_CODE (t1) == REAL_TYPE
5779 && TREE_CODE (t2) == REAL_TYPE
5780 && (extended_float_type_p (t1)
5781 || extended_float_type_p (t2))
5782 && cp_compare_floating_point_conversion_ranks
5783 (t1, t2) == 3);
5784 if (complain & tf_error)
5785 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5786 "have unordered conversion rank",
5787 arg2_type, arg3_type);
5788 return error_mark_node;
5790 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5792 arg2 = TREE_OPERAND (arg2, 0);
5793 arg2_type = TREE_TYPE (arg2);
5795 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5797 arg3 = TREE_OPERAND (arg3, 0);
5798 arg3_type = TREE_TYPE (arg3);
5802 /* [expr.cond]
5804 If either the second or the third operand has type (possibly
5805 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5806 array-to-pointer (_conv.array_), and function-to-pointer
5807 (_conv.func_) standard conversions are performed on the second
5808 and third operands. */
5809 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5811 /* 'void' won't help in resolving an overloaded expression on the
5812 other side, so require it to resolve by itself. */
5813 if (arg2_type == unknown_type_node)
5815 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5816 arg2_type = TREE_TYPE (arg2);
5818 if (arg3_type == unknown_type_node)
5820 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5821 arg3_type = TREE_TYPE (arg3);
5824 /* [expr.cond]
5826 One of the following shall hold:
5828 --The second or the third operand (but not both) is a
5829 throw-expression (_except.throw_); the result is of the type
5830 and value category of the other.
5832 --Both the second and the third operands have type void; the
5833 result is of type void and is a prvalue. */
5834 if (TREE_CODE (arg2) == THROW_EXPR
5835 && TREE_CODE (arg3) != THROW_EXPR)
5837 result_type = arg3_type;
5838 is_glvalue = glvalue_p (arg3);
5840 else if (TREE_CODE (arg2) != THROW_EXPR
5841 && TREE_CODE (arg3) == THROW_EXPR)
5843 result_type = arg2_type;
5844 is_glvalue = glvalue_p (arg2);
5846 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5848 result_type = void_type_node;
5849 is_glvalue = false;
5851 else
5853 if (complain & tf_error)
5855 if (VOID_TYPE_P (arg2_type))
5856 error_at (cp_expr_loc_or_loc (arg3, loc),
5857 "second operand to the conditional operator "
5858 "is of type %<void%>, but the third operand is "
5859 "neither a throw-expression nor of type %<void%>");
5860 else
5861 error_at (cp_expr_loc_or_loc (arg2, loc),
5862 "third operand to the conditional operator "
5863 "is of type %<void%>, but the second operand is "
5864 "neither a throw-expression nor of type %<void%>");
5866 return error_mark_node;
5869 goto valid_operands;
5871 /* [expr.cond]
5873 Otherwise, if the second and third operand have different types,
5874 and either has (possibly cv-qualified) class type, or if both are
5875 glvalues of the same value category and the same type except for
5876 cv-qualification, an attempt is made to convert each of those operands
5877 to the type of the other. */
5878 else if (!same_type_p (arg2_type, arg3_type)
5879 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5880 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5881 arg3_type)
5882 && glvalue_p (arg2) && glvalue_p (arg3)
5883 && lvalue_p (arg2) == lvalue_p (arg3))))
5885 conversion *conv2;
5886 conversion *conv3;
5887 bool converted = false;
5889 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5890 p = conversion_obstack_alloc (0);
5892 conv2 = conditional_conversion (arg2, arg3, complain);
5893 conv3 = conditional_conversion (arg3, arg2, complain);
5895 /* [expr.cond]
5897 If both can be converted, or one can be converted but the
5898 conversion is ambiguous, the program is ill-formed. If
5899 neither can be converted, the operands are left unchanged and
5900 further checking is performed as described below. If exactly
5901 one conversion is possible, that conversion is applied to the
5902 chosen operand and the converted operand is used in place of
5903 the original operand for the remainder of this section. */
5904 if ((conv2 && !conv2->bad_p
5905 && conv3 && !conv3->bad_p)
5906 || (conv2 && conv2->kind == ck_ambig)
5907 || (conv3 && conv3->kind == ck_ambig))
5909 if (complain & tf_error)
5911 error_at (loc, "operands to %<?:%> have different types "
5912 "%qT and %qT",
5913 arg2_type, arg3_type);
5914 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5915 inform (loc, " and each type can be converted to the other");
5916 else if (conv2 && conv2->kind == ck_ambig)
5917 convert_like (conv2, arg2, complain);
5918 else
5919 convert_like (conv3, arg3, complain);
5921 result = error_mark_node;
5923 else if (conv2 && !conv2->bad_p)
5925 arg2 = convert_like (conv2, arg2, complain);
5926 arg2 = convert_from_reference (arg2);
5927 arg2_type = TREE_TYPE (arg2);
5928 /* Even if CONV2 is a valid conversion, the result of the
5929 conversion may be invalid. For example, if ARG3 has type
5930 "volatile X", and X does not have a copy constructor
5931 accepting a "volatile X&", then even if ARG2 can be
5932 converted to X, the conversion will fail. */
5933 if (error_operand_p (arg2))
5934 result = error_mark_node;
5935 converted = true;
5937 else if (conv3 && !conv3->bad_p)
5939 arg3 = convert_like (conv3, arg3, complain);
5940 arg3 = convert_from_reference (arg3);
5941 arg3_type = TREE_TYPE (arg3);
5942 if (error_operand_p (arg3))
5943 result = error_mark_node;
5944 converted = true;
5947 /* Free all the conversions we allocated. */
5948 obstack_free (&conversion_obstack, p);
5950 if (result)
5951 return result;
5953 /* If, after the conversion, both operands have class type,
5954 treat the cv-qualification of both operands as if it were the
5955 union of the cv-qualification of the operands.
5957 The standard is not clear about what to do in this
5958 circumstance. For example, if the first operand has type
5959 "const X" and the second operand has a user-defined
5960 conversion to "volatile X", what is the type of the second
5961 operand after this step? Making it be "const X" (matching
5962 the first operand) seems wrong, as that discards the
5963 qualification without actually performing a copy. Leaving it
5964 as "volatile X" seems wrong as that will result in the
5965 conditional expression failing altogether, even though,
5966 according to this step, the one operand could be converted to
5967 the type of the other. */
5968 if (converted
5969 && CLASS_TYPE_P (arg2_type)
5970 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5971 arg2_type = arg3_type =
5972 cp_build_qualified_type (arg2_type,
5973 cp_type_quals (arg2_type)
5974 | cp_type_quals (arg3_type));
5977 /* [expr.cond]
5979 If the second and third operands are glvalues of the same value
5980 category and have the same type, the result is of that type and
5981 value category. */
5982 if (((lvalue_p (arg2) && lvalue_p (arg3))
5983 || (xvalue_p (arg2) && xvalue_p (arg3)))
5984 && same_type_p (arg2_type, arg3_type))
5986 result_type = arg2_type;
5987 goto valid_operands;
5990 /* [expr.cond]
5992 Otherwise, the result is an rvalue. If the second and third
5993 operand do not have the same type, and either has (possibly
5994 cv-qualified) class type, overload resolution is used to
5995 determine the conversions (if any) to be applied to the operands
5996 (_over.match.oper_, _over.built_). */
5997 is_glvalue = false;
5998 if (!same_type_p (arg2_type, arg3_type)
5999 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6001 releasing_vec args;
6002 conversion *conv;
6003 bool any_viable_p;
6005 /* Rearrange the arguments so that add_builtin_candidate only has
6006 to know about two args. In build_builtin_candidate, the
6007 arguments are unscrambled. */
6008 args->quick_push (arg2);
6009 args->quick_push (arg3);
6010 args->quick_push (arg1);
6011 add_builtin_candidates (&candidates,
6012 COND_EXPR,
6013 NOP_EXPR,
6014 ovl_op_identifier (false, COND_EXPR),
6015 args,
6016 LOOKUP_NORMAL, complain);
6018 /* [expr.cond]
6020 If the overload resolution fails, the program is
6021 ill-formed. */
6022 candidates = splice_viable (candidates, false, &any_viable_p);
6023 if (!any_viable_p)
6025 if (complain & tf_error)
6026 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6027 arg2_type, arg3_type);
6028 return error_mark_node;
6030 cand = tourney (candidates, complain);
6031 if (!cand)
6033 if (complain & tf_error)
6035 auto_diagnostic_group d;
6036 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
6037 print_z_candidates (loc, candidates);
6039 return error_mark_node;
6042 /* [expr.cond]
6044 Otherwise, the conversions thus determined are applied, and
6045 the converted operands are used in place of the original
6046 operands for the remainder of this section. */
6047 conv = cand->convs[0];
6048 arg1 = convert_like (conv, arg1, complain);
6049 conv = cand->convs[1];
6050 arg2 = convert_like (conv, arg2, complain);
6051 arg2_type = TREE_TYPE (arg2);
6052 conv = cand->convs[2];
6053 arg3 = convert_like (conv, arg3, complain);
6054 arg3_type = TREE_TYPE (arg3);
6057 /* [expr.cond]
6059 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6060 and function-to-pointer (_conv.func_) standard conversions are
6061 performed on the second and third operands.
6063 We need to force the lvalue-to-rvalue conversion here for class types,
6064 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6065 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6066 regions. */
6068 arg2 = force_rvalue (arg2, complain);
6069 if (!CLASS_TYPE_P (arg2_type))
6070 arg2_type = TREE_TYPE (arg2);
6072 arg3 = force_rvalue (arg3, complain);
6073 if (!CLASS_TYPE_P (arg3_type))
6074 arg3_type = TREE_TYPE (arg3);
6076 if (arg2 == error_mark_node || arg3 == error_mark_node)
6077 return error_mark_node;
6079 /* [expr.cond]
6081 After those conversions, one of the following shall hold:
6083 --The second and third operands have the same type; the result is of
6084 that type. */
6085 if (same_type_p (arg2_type, arg3_type))
6086 result_type = arg2_type;
6087 /* [expr.cond]
6089 --The second and third operands have arithmetic or enumeration
6090 type; the usual arithmetic conversions are performed to bring
6091 them to a common type, and the result is of that type. */
6092 else if ((ARITHMETIC_TYPE_P (arg2_type)
6093 || UNSCOPED_ENUM_P (arg2_type))
6094 && (ARITHMETIC_TYPE_P (arg3_type)
6095 || UNSCOPED_ENUM_P (arg3_type)))
6097 /* A conditional expression between a floating-point
6098 type and an integer type should convert the integer type to
6099 the evaluation format of the floating-point type, with
6100 possible excess precision. */
6101 tree eptype2 = arg2_type;
6102 tree eptype3 = arg3_type;
6103 tree eptype;
6104 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6105 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6107 eptype3 = eptype;
6108 if (!semantic_result_type)
6109 semantic_result_type
6110 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6112 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6113 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6115 eptype2 = eptype;
6116 if (!semantic_result_type)
6117 semantic_result_type
6118 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6120 result_type = type_after_usual_arithmetic_conversions (eptype2,
6121 eptype3);
6122 if (result_type == error_mark_node)
6124 tree t1 = eptype2;
6125 tree t2 = eptype3;
6126 if (TREE_CODE (t1) == COMPLEX_TYPE)
6127 t1 = TREE_TYPE (t1);
6128 if (TREE_CODE (t2) == COMPLEX_TYPE)
6129 t2 = TREE_TYPE (t2);
6130 gcc_checking_assert (TREE_CODE (t1) == REAL_TYPE
6131 && TREE_CODE (t2) == REAL_TYPE
6132 && (extended_float_type_p (t1)
6133 || extended_float_type_p (t2))
6134 && cp_compare_floating_point_conversion_ranks
6135 (t1, t2) == 3);
6136 if (complain & tf_error)
6137 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6138 "have unordered conversion rank",
6139 eptype2, eptype3);
6140 return error_mark_node;
6142 if (semantic_result_type == error_mark_node)
6144 tree t1 = arg2_type;
6145 tree t2 = arg3_type;
6146 if (TREE_CODE (t1) == COMPLEX_TYPE)
6147 t1 = TREE_TYPE (t1);
6148 if (TREE_CODE (t2) == COMPLEX_TYPE)
6149 t2 = TREE_TYPE (t2);
6150 gcc_checking_assert (TREE_CODE (t1) == REAL_TYPE
6151 && TREE_CODE (t2) == REAL_TYPE
6152 && (extended_float_type_p (t1)
6153 || extended_float_type_p (t2))
6154 && cp_compare_floating_point_conversion_ranks
6155 (t1, t2) == 3);
6156 if (complain & tf_error)
6157 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6158 "have unordered conversion rank",
6159 arg2_type, arg3_type);
6160 return error_mark_node;
6163 if (complain & tf_warning)
6164 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6165 "implicit conversion from %qH to %qI to "
6166 "match other result of conditional",
6167 loc);
6169 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6170 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6172 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
6173 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
6174 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6175 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6176 && (DECL_CONTEXT (stripped_orig_arg2)
6177 == DECL_CONTEXT (stripped_orig_arg3)))
6178 /* Two enumerators from the same enumeration can have different
6179 types when the enumeration is still being defined. */;
6180 else if (complain & tf_warning)
6181 warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
6182 "in conditional expression: %qT vs %qT",
6183 arg2_type, arg3_type);
6185 else if ((complain & tf_warning)
6186 && warn_deprecated_enum_float_conv
6187 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6188 && TREE_CODE (arg3_type) == REAL_TYPE)
6189 || (TREE_CODE (arg2_type) == REAL_TYPE
6190 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6192 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6193 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6194 "conditional expression between enumeration type "
6195 "%qT and floating-point type %qT is deprecated",
6196 arg2_type, arg3_type);
6197 else
6198 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6199 "conditional expression between floating-point "
6200 "type %qT and enumeration type %qT is deprecated",
6201 arg2_type, arg3_type);
6203 else if ((extra_warnings || warn_enum_conversion)
6204 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6205 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6206 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6207 && !same_type_p (arg2_type,
6208 type_promotes_to (arg3_type)))))
6210 if (complain & tf_warning)
6212 enum opt_code opt = (warn_enum_conversion
6213 ? OPT_Wenum_conversion
6214 : OPT_Wextra);
6215 warning_at (loc, opt, "enumerated and "
6216 "non-enumerated type in conditional expression");
6220 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6221 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6223 /* [expr.cond]
6225 --The second and third operands have pointer type, or one has
6226 pointer type and the other is a null pointer constant; pointer
6227 conversions (_conv.ptr_) and qualification conversions
6228 (_conv.qual_) are performed to bring them to their composite
6229 pointer type (_expr.rel_). The result is of the composite
6230 pointer type.
6232 --The second and third operands have pointer to member type, or
6233 one has pointer to member type and the other is a null pointer
6234 constant; pointer to member conversions (_conv.mem_) and
6235 qualification conversions (_conv.qual_) are performed to bring
6236 them to a common type, whose cv-qualification shall match the
6237 cv-qualification of either the second or the third operand.
6238 The result is of the common type. */
6239 else if ((null_ptr_cst_p (arg2)
6240 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6241 || (null_ptr_cst_p (arg3)
6242 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6243 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6244 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6245 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6247 result_type = composite_pointer_type (loc,
6248 arg2_type, arg3_type, arg2,
6249 arg3, CPO_CONDITIONAL_EXPR,
6250 complain);
6251 if (result_type == error_mark_node)
6252 return error_mark_node;
6253 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6254 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6257 if (!result_type)
6259 if (complain & tf_error)
6260 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6261 arg2_type, arg3_type);
6262 return error_mark_node;
6265 if (arg2 == error_mark_node || arg3 == error_mark_node)
6266 return error_mark_node;
6268 valid_operands:
6269 if (processing_template_decl && is_glvalue)
6271 /* Let lvalue_kind know this was a glvalue. */
6272 tree arg = (result_type == arg2_type ? arg2 : arg3);
6273 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6276 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
6278 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6279 warn here, because the COND_EXPR will be turned into ARG2. */
6280 if (warn_duplicated_branches
6281 && (complain & tf_warning)
6282 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6283 OEP_ADDRESS_OF_SAME_FIELD)))
6284 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6285 "this condition has identical branches");
6287 /* We can't use result_type below, as fold might have returned a
6288 throw_expr. */
6290 if (!is_glvalue)
6292 /* Expand both sides into the same slot, hopefully the target of
6293 the ?: expression. We used to check for TARGET_EXPRs here,
6294 but now we sometimes wrap them in NOP_EXPRs so the test would
6295 fail. */
6296 if (CLASS_TYPE_P (TREE_TYPE (result)))
6298 result = get_target_expr (result, complain);
6299 /* Tell gimplify_modify_expr_rhs not to strip this in
6300 assignment context: we want both arms to initialize
6301 the same temporary. */
6302 TARGET_EXPR_NO_ELIDE (result) = true;
6304 /* If this expression is an rvalue, but might be mistaken for an
6305 lvalue, we must add a NON_LVALUE_EXPR. */
6306 result = rvalue (result);
6307 if (semantic_result_type)
6308 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6309 result);
6311 else
6313 result = force_paren_expr (result);
6314 gcc_assert (semantic_result_type == NULL_TREE);
6317 return result;
6320 /* OPERAND is an operand to an expression. Perform necessary steps
6321 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6322 returned. */
6324 static tree
6325 prep_operand (tree operand)
6327 if (operand)
6329 if (CLASS_TYPE_P (TREE_TYPE (operand))
6330 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6331 /* Make sure the template type is instantiated now. */
6332 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6335 return operand;
6338 /* True iff CONV represents a conversion sequence which no other can be better
6339 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6340 type (including binding to a reference to the same type). This is stronger
6341 than the standard's "identity" category, which also includes reference
6342 bindings that add cv-qualifiers or change rvalueness. */
6344 static bool
6345 perfect_conversion_p (conversion *conv)
6347 if (CONVERSION_RANK (conv) != cr_identity)
6348 return false;
6349 if (conv->kind == ck_ref_bind)
6351 if (!conv->rvaluedness_matches_p)
6352 return false;
6353 if (!same_type_p (TREE_TYPE (conv->type),
6354 next_conversion (conv)->type))
6355 return false;
6357 if (conv->check_narrowing)
6358 /* Brace elision is imperfect. */
6359 return false;
6360 return true;
6363 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6364 other candidate can be a better match. Since the template/non-template
6365 tiebreaker comes immediately after the conversion comparison in
6366 [over.match.best], a perfect non-template candidate is better than all
6367 templates. */
6369 static bool
6370 perfect_candidate_p (z_candidate *cand)
6372 if (cand->viable < 1)
6373 return false;
6374 /* CWG1402 makes an implicitly deleted move op worse than other
6375 candidates. */
6376 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6377 && move_fn_p (cand->fn))
6378 return false;
6379 int len = cand->num_convs;
6380 for (int i = 0; i < len; ++i)
6381 if (!perfect_conversion_p (cand->convs[i]))
6382 return false;
6383 if (conversion *conv = cand->second_conv)
6384 if (!perfect_conversion_p (conv))
6385 return false;
6386 return true;
6389 /* True iff one of CAND's argument conversions is missing. */
6391 static bool
6392 missing_conversion_p (const z_candidate *cand)
6394 for (unsigned i = 0; i < cand->num_convs; ++i)
6396 conversion *conv = cand->convs[i];
6397 if (!conv)
6398 return true;
6399 if (conv->kind == ck_deferred_bad)
6401 /* We don't know whether this conversion is outright invalid or
6402 just bad, so conservatively assume it's missing. */
6403 gcc_checking_assert (conv->bad_p);
6404 return true;
6407 return false;
6410 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6411 OVERLOAD) to the CANDIDATES, returning an updated list of
6412 CANDIDATES. The ARGS are the arguments provided to the call;
6413 if FIRST_ARG is non-null it is the implicit object argument,
6414 otherwise the first element of ARGS is used if needed. The
6415 EXPLICIT_TARGS are explicit template arguments provided.
6416 TEMPLATE_ONLY is true if only template functions should be
6417 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6418 add_function_candidate. */
6420 static void
6421 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6422 tree return_type,
6423 tree explicit_targs, bool template_only,
6424 tree conversion_path, tree access_path,
6425 int flags,
6426 struct z_candidate **candidates,
6427 tsubst_flags_t complain)
6429 tree ctype;
6430 const vec<tree, va_gc> *non_static_args;
6431 bool check_list_ctor = false;
6432 bool check_converting = false;
6433 unification_kind_t strict;
6434 tree ne_fns = NULL_TREE;
6436 if (!fns)
6437 return;
6439 /* Precalculate special handling of constructors and conversion ops. */
6440 tree fn = OVL_FIRST (fns);
6441 if (DECL_CONV_FN_P (fn))
6443 check_list_ctor = false;
6444 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6445 if (flags & LOOKUP_NO_CONVERSION)
6446 /* We're doing return_type(x). */
6447 strict = DEDUCE_CONV;
6448 else
6449 /* We're doing x.operator return_type(). */
6450 strict = DEDUCE_EXACT;
6451 /* [over.match.funcs] For conversion functions, the function
6452 is considered to be a member of the class of the implicit
6453 object argument for the purpose of defining the type of
6454 the implicit object parameter. */
6455 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6457 else
6459 if (DECL_CONSTRUCTOR_P (fn))
6461 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6462 /* For list-initialization we consider explicit constructors
6463 and complain if one is chosen. */
6464 check_converting
6465 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6466 == LOOKUP_ONLYCONVERTING);
6468 strict = DEDUCE_CALL;
6469 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6472 /* P2468: Check if operator== is a rewrite target with first operand
6473 (*args)[0]; for now just do the lookups. */
6474 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6475 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6477 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6478 if (DECL_CLASS_SCOPE_P (fn))
6480 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6481 1, tf_none);
6482 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6483 ne_fns = NULL_TREE;
6484 else
6485 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6487 else
6489 tree context = decl_namespace_context (fn);
6490 ne_fns = lookup_qualified_name (context, ne_name, LOOK_want::NORMAL,
6491 /*complain*/false);
6492 if (ne_fns == error_mark_node
6493 || !is_overloaded_fn (ne_fns))
6494 ne_fns = NULL_TREE;
6498 if (first_arg)
6499 non_static_args = args;
6500 else
6501 /* Delay creating the implicit this parameter until it is needed. */
6502 non_static_args = NULL;
6504 bool seen_strictly_viable = any_strictly_viable (*candidates);
6505 /* If there's a non-template perfect match, we don't need to consider
6506 templates. So check non-templates first. This optimization is only
6507 really needed for the defaulted copy constructor of tuple and the like
6508 (96926), but it seems like we might as well enable it more generally. */
6509 bool seen_perfect = false;
6510 enum { templates, non_templates, either } which = either;
6511 if (template_only)
6512 which = templates;
6513 else /*if (flags & LOOKUP_DEFAULTED)*/
6514 which = non_templates;
6516 /* During overload resolution, we first consider each function under the
6517 assumption that we'll eventually find a strictly viable candidate.
6518 This allows us to circumvent our defacto behavior when checking
6519 argument conversions and shortcut consideration of the candidate
6520 upon encountering the first bad conversion. If this assumption
6521 turns out to be false, and all candidates end up being non-strictly
6522 viable, then we reconsider such candidates under the defacto behavior.
6523 This trick is important for pruning member function overloads according
6524 to their const/ref-qualifiers (since all 'this' conversions are at
6525 worst bad) without breaking -fpermissive. */
6526 tree bad_fns = NULL_TREE;
6527 bool shortcut_bad_convs = true;
6529 again:
6530 for (tree fn : lkp_range (fns))
6532 if (check_converting && DECL_NONCONVERTING_P (fn))
6533 continue;
6534 if (check_list_ctor && !is_list_ctor (fn))
6535 continue;
6536 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6537 continue;
6538 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6539 continue;
6541 tree fn_first_arg = NULL_TREE;
6542 const vec<tree, va_gc> *fn_args = args;
6544 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6546 /* Figure out where the object arg comes from. If this
6547 function is a non-static member and we didn't get an
6548 implicit object argument, move it out of args. */
6549 if (first_arg == NULL_TREE)
6551 unsigned int ix;
6552 tree arg;
6553 vec<tree, va_gc> *tempvec;
6554 vec_alloc (tempvec, args->length () - 1);
6555 for (ix = 1; args->iterate (ix, &arg); ++ix)
6556 tempvec->quick_push (arg);
6557 non_static_args = tempvec;
6558 first_arg = (*args)[0];
6561 fn_first_arg = first_arg;
6562 fn_args = non_static_args;
6565 /* Don't bother reversing an operator with two identical parameters. */
6566 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6568 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6569 if (same_type_p (TREE_VALUE (parmlist),
6570 TREE_VALUE (TREE_CHAIN (parmlist))))
6571 continue;
6574 /* When considering reversed operator==, if there's a corresponding
6575 operator!= in the same scope, it's not a rewrite target. */
6576 if (ne_fns)
6578 bool found = false;
6579 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6580 if (0 && !ne.using_p ()
6581 && DECL_NAMESPACE_SCOPE_P (fn)
6582 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6583 /* ??? This kludge excludes inline namespace members for the H
6584 test in spaceship-eq15.C, but I don't see why we would want
6585 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6586 else if (fns_correspond (fn, *ne))
6588 found = true;
6589 break;
6591 if (found)
6592 continue;
6595 if (TREE_CODE (fn) == TEMPLATE_DECL)
6597 if (!add_template_candidate (candidates,
6599 ctype,
6600 explicit_targs,
6601 fn_first_arg,
6602 fn_args,
6603 return_type,
6604 access_path,
6605 conversion_path,
6606 flags,
6607 strict,
6608 shortcut_bad_convs,
6609 complain))
6610 continue;
6612 else
6614 add_function_candidate (candidates,
6616 ctype,
6617 fn_first_arg,
6618 fn_args,
6619 access_path,
6620 conversion_path,
6621 flags,
6622 NULL,
6623 shortcut_bad_convs,
6624 complain);
6625 if (perfect_candidate_p (*candidates))
6626 seen_perfect = true;
6629 z_candidate *cand = *candidates;
6630 if (cand->viable == 1)
6631 seen_strictly_viable = true;
6633 if (cand->viable == -1
6634 && shortcut_bad_convs
6635 && missing_conversion_p (cand))
6637 /* This candidate has been tentatively marked non-strictly viable,
6638 and we didn't compute all argument conversions for it (having
6639 stopped at the first bad conversion). Add the function to BAD_FNS
6640 to fully reconsider later if we don't find any strictly viable
6641 candidates. */
6642 if (complain & (tf_error | tf_conv))
6644 bad_fns = lookup_add (fn, bad_fns);
6645 *candidates = (*candidates)->next;
6647 else
6648 /* But if we're in a SFINAE context, just mark this candidate as
6649 unviable outright and avoid potentially reconsidering it.
6650 This is safe to do because in a SFINAE context, performing a bad
6651 conversion is always an error (even with -fpermissive), so a
6652 non-strictly viable candidate is effectively unviable anyway. */
6653 cand->viable = 0;
6656 if (which == non_templates && !seen_perfect)
6658 which = templates;
6659 goto again;
6661 else if (which == templates
6662 && !seen_strictly_viable
6663 && shortcut_bad_convs
6664 && bad_fns)
6666 /* None of the candidates are strictly viable, so consider again those
6667 functions in BAD_FNS, this time without shortcutting bad conversions
6668 so that all their argument conversions are computed. */
6669 which = either;
6670 fns = bad_fns;
6671 shortcut_bad_convs = false;
6672 goto again;
6676 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6677 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6679 static int
6680 op_is_ordered (tree_code code)
6682 switch (code)
6684 // 5. b @= a
6685 case MODIFY_EXPR:
6686 return (flag_strong_eval_order > 1 ? -1 : 0);
6688 // 6. a[b]
6689 case ARRAY_REF:
6690 return (flag_strong_eval_order > 1 ? 1 : 0);
6692 // 1. a.b
6693 // Not overloadable (yet).
6694 // 2. a->b
6695 // Only one argument.
6696 // 3. a->*b
6697 case MEMBER_REF:
6698 // 7. a << b
6699 case LSHIFT_EXPR:
6700 // 8. a >> b
6701 case RSHIFT_EXPR:
6702 // a && b
6703 // Predates P0145R3.
6704 case TRUTH_ANDIF_EXPR:
6705 // a || b
6706 // Predates P0145R3.
6707 case TRUTH_ORIF_EXPR:
6708 // a , b
6709 // Predates P0145R3.
6710 case COMPOUND_EXPR:
6711 return (flag_strong_eval_order ? 1 : 0);
6713 default:
6714 return 0;
6718 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6719 operator indicated by CODE/CODE2. This function calls itself recursively to
6720 handle C++20 rewritten comparison operator candidates.
6722 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6723 overloads to consider. This parameter is used when instantiating a
6724 dependent operator expression and has the same structure as
6725 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6727 static tree
6728 add_operator_candidates (z_candidate **candidates,
6729 tree_code code, tree_code code2,
6730 vec<tree, va_gc> *arglist, tree lookups,
6731 int flags, tsubst_flags_t complain)
6733 z_candidate *start_candidates = *candidates;
6734 bool ismodop = code2 != ERROR_MARK;
6735 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6737 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6738 rewrite from, and also when we're looking for the e.g. < operator to use
6739 on the result of <=>. In the latter case, we don't want the flag set in
6740 the candidate, we just want to suppress looking for rewrites. */
6741 bool rewritten = (flags & LOOKUP_REWRITTEN);
6742 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6743 flags &= ~LOOKUP_REWRITTEN;
6745 bool memonly = false;
6746 switch (code)
6748 /* =, ->, [], () must be non-static member functions. */
6749 case MODIFY_EXPR:
6750 if (code2 != NOP_EXPR)
6751 break;
6752 /* FALLTHRU */
6753 case COMPONENT_REF:
6754 case ARRAY_REF:
6755 memonly = true;
6756 break;
6758 default:
6759 break;
6762 /* Add namespace-scope operators to the list of functions to
6763 consider. */
6764 if (!memonly)
6766 tree fns;
6767 if (!lookups)
6768 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6769 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6770 expression, and LOOKUPS is the result of stage 1 name lookup. */
6771 else if (tree found = purpose_member (fnname, lookups))
6772 fns = TREE_VALUE (found);
6773 else
6774 fns = NULL_TREE;
6775 fns = lookup_arg_dependent (fnname, fns, arglist);
6776 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6777 NULL_TREE, false, NULL_TREE, NULL_TREE,
6778 flags, candidates, complain);
6781 /* Add class-member operators to the candidate set. */
6782 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6783 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6784 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6785 if (CLASS_TYPE_P (arg1_type))
6787 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6788 if (fns == error_mark_node)
6789 return error_mark_node;
6790 if (fns)
6792 if (code == ARRAY_REF)
6794 vec<tree,va_gc> *restlist = make_tree_vector ();
6795 for (unsigned i = 1; i < nargs; ++i)
6796 vec_safe_push (restlist, (*arglist)[i]);
6797 z_candidate *save_cand = *candidates;
6798 add_candidates (BASELINK_FUNCTIONS (fns),
6799 (*arglist)[0], restlist, NULL_TREE,
6800 NULL_TREE, false,
6801 BASELINK_BINFO (fns),
6802 BASELINK_ACCESS_BINFO (fns),
6803 flags, candidates, complain);
6804 /* Release the vec if we didn't add a candidate that uses it. */
6805 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6806 if (c->args == restlist)
6808 restlist = NULL;
6809 break;
6811 release_tree_vector (restlist);
6813 else
6814 add_candidates (BASELINK_FUNCTIONS (fns),
6815 NULL_TREE, arglist, NULL_TREE,
6816 NULL_TREE, false,
6817 BASELINK_BINFO (fns),
6818 BASELINK_ACCESS_BINFO (fns),
6819 flags, candidates, complain);
6822 /* Per [over.match.oper]3.2, if no operand has a class type, then
6823 only non-member functions that have type T1 or reference to
6824 cv-qualified-opt T1 for the first argument, if the first argument
6825 has an enumeration type, or T2 or reference to cv-qualified-opt
6826 T2 for the second argument, if the second argument has an
6827 enumeration type. Filter out those that don't match. */
6828 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6830 struct z_candidate **candp, **next;
6832 for (candp = candidates; *candp != start_candidates; candp = next)
6834 unsigned i;
6835 z_candidate *cand = *candp;
6836 next = &cand->next;
6838 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6840 for (i = 0; i < nargs; ++i)
6842 tree parmtype = TREE_VALUE (parmlist);
6843 tree argtype = unlowered_expr_type ((*arglist)[i]);
6845 if (TYPE_REF_P (parmtype))
6846 parmtype = TREE_TYPE (parmtype);
6847 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6848 && (same_type_ignoring_top_level_qualifiers_p
6849 (argtype, parmtype)))
6850 break;
6852 parmlist = TREE_CHAIN (parmlist);
6855 /* No argument has an appropriate type, so remove this
6856 candidate function from the list. */
6857 if (i == nargs)
6859 *candp = cand->next;
6860 next = candp;
6865 if (!rewritten)
6867 /* The standard says to rewrite built-in candidates, too,
6868 but there's no point. */
6869 add_builtin_candidates (candidates, code, code2, fnname, arglist,
6870 flags, complain);
6872 /* Maybe add C++20 rewritten comparison candidates. */
6873 tree_code rewrite_code = ERROR_MARK;
6874 if (cxx_dialect >= cxx20
6875 && nargs == 2
6876 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6877 switch (code)
6879 case LT_EXPR:
6880 case LE_EXPR:
6881 case GT_EXPR:
6882 case GE_EXPR:
6883 case SPACESHIP_EXPR:
6884 rewrite_code = SPACESHIP_EXPR;
6885 break;
6887 case NE_EXPR:
6888 case EQ_EXPR:
6889 rewrite_code = EQ_EXPR;
6890 break;
6892 default:;
6895 if (rewrite_code)
6897 flags |= LOOKUP_REWRITTEN;
6898 if (rewrite_code != code)
6899 /* Add rewritten candidates in same order. */
6900 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6901 arglist, lookups, flags, complain);
6903 z_candidate *save_cand = *candidates;
6905 /* Add rewritten candidates in reverse order. */
6906 flags |= LOOKUP_REVERSED;
6907 vec<tree,va_gc> *revlist = make_tree_vector ();
6908 revlist->quick_push ((*arglist)[1]);
6909 revlist->quick_push ((*arglist)[0]);
6910 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6911 revlist, lookups, flags, complain);
6913 /* Release the vec if we didn't add a candidate that uses it. */
6914 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6915 if (c->args == revlist)
6917 revlist = NULL;
6918 break;
6920 release_tree_vector (revlist);
6924 return NULL_TREE;
6927 tree
6928 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6929 tree arg1, tree arg2, tree arg3, tree lookups,
6930 tree *overload, tsubst_flags_t complain)
6932 struct z_candidate *candidates = 0, *cand;
6933 releasing_vec arglist;
6934 tree result = NULL_TREE;
6935 bool result_valid_p = false;
6936 enum tree_code code2 = ERROR_MARK;
6937 enum tree_code code_orig_arg1 = ERROR_MARK;
6938 enum tree_code code_orig_arg2 = ERROR_MARK;
6939 void *p;
6940 bool strict_p;
6941 bool any_viable_p;
6943 auto_cond_timevar tv (TV_OVERLOAD);
6945 if (error_operand_p (arg1)
6946 || error_operand_p (arg2)
6947 || error_operand_p (arg3))
6948 return error_mark_node;
6950 bool ismodop = code == MODIFY_EXPR;
6951 if (ismodop)
6953 code2 = TREE_CODE (arg3);
6954 arg3 = NULL_TREE;
6957 tree arg1_type = unlowered_expr_type (arg1);
6958 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6960 arg1 = prep_operand (arg1);
6962 switch (code)
6964 case NEW_EXPR:
6965 case VEC_NEW_EXPR:
6966 case VEC_DELETE_EXPR:
6967 case DELETE_EXPR:
6968 /* Use build_operator_new_call and build_op_delete_call instead. */
6969 gcc_unreachable ();
6971 case CALL_EXPR:
6972 /* Use build_op_call instead. */
6973 gcc_unreachable ();
6975 case TRUTH_ORIF_EXPR:
6976 case TRUTH_ANDIF_EXPR:
6977 case TRUTH_AND_EXPR:
6978 case TRUTH_OR_EXPR:
6979 /* These are saved for the sake of warn_logical_operator. */
6980 code_orig_arg1 = TREE_CODE (arg1);
6981 code_orig_arg2 = TREE_CODE (arg2);
6982 break;
6983 case GT_EXPR:
6984 case LT_EXPR:
6985 case GE_EXPR:
6986 case LE_EXPR:
6987 case EQ_EXPR:
6988 case NE_EXPR:
6989 /* These are saved for the sake of maybe_warn_bool_compare. */
6990 code_orig_arg1 = TREE_CODE (arg1_type);
6991 code_orig_arg2 = TREE_CODE (arg2_type);
6992 break;
6994 default:
6995 break;
6998 arg2 = prep_operand (arg2);
6999 arg3 = prep_operand (arg3);
7001 if (code == COND_EXPR)
7002 /* Use build_conditional_expr instead. */
7003 gcc_unreachable ();
7004 else if (! OVERLOAD_TYPE_P (arg1_type)
7005 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7006 goto builtin;
7008 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7010 arg2 = integer_zero_node;
7011 arg2_type = integer_type_node;
7014 arglist->quick_push (arg1);
7015 if (arg2 != NULL_TREE)
7016 arglist->quick_push (arg2);
7017 if (arg3 != NULL_TREE)
7018 arglist->quick_push (arg3);
7020 /* Get the high-water mark for the CONVERSION_OBSTACK. */
7021 p = conversion_obstack_alloc (0);
7023 result = add_operator_candidates (&candidates, code, code2, arglist,
7024 lookups, flags, complain);
7025 if (result == error_mark_node)
7026 goto user_defined_result_ready;
7028 switch (code)
7030 case COMPOUND_EXPR:
7031 case ADDR_EXPR:
7032 /* For these, the built-in candidates set is empty
7033 [over.match.oper]/3. We don't want non-strict matches
7034 because exact matches are always possible with built-in
7035 operators. The built-in candidate set for COMPONENT_REF
7036 would be empty too, but since there are no such built-in
7037 operators, we accept non-strict matches for them. */
7038 strict_p = true;
7039 break;
7041 default:
7042 strict_p = false;
7043 break;
7046 candidates = splice_viable (candidates, strict_p, &any_viable_p);
7047 if (!any_viable_p)
7049 switch (code)
7051 case POSTINCREMENT_EXPR:
7052 case POSTDECREMENT_EXPR:
7053 /* Don't try anything fancy if we're not allowed to produce
7054 errors. */
7055 if (!(complain & tf_error))
7056 return error_mark_node;
7058 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7059 distinguish between prefix and postfix ++ and
7060 operator++() was used for both, so we allow this with
7061 -fpermissive. */
7062 else
7064 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7065 const char *msg = (flag_permissive)
7066 ? G_("no %<%D(int)%> declared for postfix %qs,"
7067 " trying prefix operator instead")
7068 : G_("no %<%D(int)%> declared for postfix %qs");
7069 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7072 if (!flag_permissive)
7073 return error_mark_node;
7075 if (code == POSTINCREMENT_EXPR)
7076 code = PREINCREMENT_EXPR;
7077 else
7078 code = PREDECREMENT_EXPR;
7079 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7080 NULL_TREE, lookups, overload, complain);
7081 break;
7083 /* The caller will deal with these. */
7084 case ADDR_EXPR:
7085 case COMPOUND_EXPR:
7086 case COMPONENT_REF:
7087 case CO_AWAIT_EXPR:
7088 result = NULL_TREE;
7089 result_valid_p = true;
7090 break;
7092 default:
7093 if (complain & tf_error)
7095 /* If one of the arguments of the operator represents
7096 an invalid use of member function pointer, try to report
7097 a meaningful error ... */
7098 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7099 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7100 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7101 /* We displayed the error message. */;
7102 else
7104 /* ... Otherwise, report the more generic
7105 "no matching operator found" error */
7106 auto_diagnostic_group d;
7107 op_error (loc, code, code2, arg1, arg2, arg3, FALSE);
7108 print_z_candidates (loc, candidates);
7111 result = error_mark_node;
7112 break;
7115 else
7117 cand = tourney (candidates, complain);
7118 if (cand == 0)
7120 if (complain & tf_error)
7122 auto_diagnostic_group d;
7123 op_error (loc, code, code2, arg1, arg2, arg3, TRUE);
7124 print_z_candidates (loc, candidates);
7126 result = error_mark_node;
7127 if (overload)
7128 *overload = error_mark_node;
7130 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7132 if (overload)
7133 *overload = cand->fn;
7135 if (resolve_args (arglist, complain) == NULL)
7136 result = error_mark_node;
7137 else
7139 tsubst_flags_t ocomplain = complain;
7140 if (cand->rewritten ())
7141 /* We'll wrap this call in another one. */
7142 ocomplain &= ~tf_decltype;
7143 if (cand->reversed ())
7145 /* We swapped these in add_candidate, swap them back now. */
7146 std::swap (cand->convs[0], cand->convs[1]);
7147 if (cand->fn == current_function_decl)
7148 warning_at (loc, 0, "in C++20 this comparison calls the "
7149 "current function recursively with reversed "
7150 "arguments");
7152 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7155 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7156 /* There won't be a CALL_EXPR. */;
7157 else if (result && result != error_mark_node)
7159 tree call = extract_call_expr (result);
7160 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7162 /* Specify evaluation order as per P0145R2. */
7163 CALL_EXPR_ORDERED_ARGS (call) = false;
7164 switch (op_is_ordered (code))
7166 case -1:
7167 CALL_EXPR_REVERSE_ARGS (call) = true;
7168 break;
7170 case 1:
7171 CALL_EXPR_ORDERED_ARGS (call) = true;
7172 break;
7174 default:
7175 break;
7179 /* If this was a C++20 rewritten comparison, adjust the result. */
7180 if (cand->rewritten ())
7182 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7183 if (overload)
7184 *overload = NULL_TREE;
7185 switch (code)
7187 case EQ_EXPR:
7188 gcc_checking_assert (cand->reversed ());
7189 gcc_fallthrough ();
7190 case NE_EXPR:
7191 if (result == error_mark_node)
7193 /* If a rewritten operator== candidate is selected by
7194 overload resolution for an operator @, its return type
7195 shall be cv bool.... */
7196 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7198 if (complain & tf_error)
7200 auto_diagnostic_group d;
7201 error_at (loc, "return type of %qD is not %qs",
7202 cand->fn, "bool");
7203 inform (loc, "used as rewritten candidate for "
7204 "comparison of %qT and %qT",
7205 arg1_type, arg2_type);
7207 result = error_mark_node;
7209 else if (code == NE_EXPR)
7210 /* !(y == x) or !(x == y) */
7211 result = build1_loc (loc, TRUTH_NOT_EXPR,
7212 boolean_type_node, result);
7213 break;
7215 /* If a rewritten operator<=> candidate is selected by
7216 overload resolution for an operator @, x @ y is
7217 interpreted as 0 @ (y <=> x) if the selected candidate is
7218 a synthesized candidate with reversed order of parameters,
7219 or (x <=> y) @ 0 otherwise, using the selected rewritten
7220 operator<=> candidate. */
7221 case SPACESHIP_EXPR:
7222 if (!cand->reversed ())
7223 /* We're in the build_new_op call below for an outer
7224 reversed call; we don't need to do anything more. */
7225 break;
7226 gcc_fallthrough ();
7227 case LT_EXPR:
7228 case LE_EXPR:
7229 case GT_EXPR:
7230 case GE_EXPR:
7232 tree lhs = result;
7233 tree rhs = integer_zero_node;
7234 if (cand->reversed ())
7235 std::swap (lhs, rhs);
7236 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7237 result = build_new_op (loc, code,
7238 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7239 lhs, rhs, NULL_TREE, lookups,
7240 NULL, complain);
7242 break;
7244 default:
7245 gcc_unreachable ();
7249 /* In an expression of the form `a[]' where cand->fn
7250 which is operator[] turns out to be a static member function,
7251 `a' is none-the-less evaluated. */
7252 if (code == ARRAY_REF)
7253 result = keep_unused_object_arg (result, arg1, cand->fn);
7255 else
7257 /* Give any warnings we noticed during overload resolution. */
7258 if (cand->warnings && (complain & tf_warning))
7260 struct candidate_warning *w;
7261 for (w = cand->warnings; w; w = w->next)
7262 joust (cand, w->loser, 1, complain);
7265 /* Check for comparison of different enum types. */
7266 switch (code)
7268 case GT_EXPR:
7269 case LT_EXPR:
7270 case GE_EXPR:
7271 case LE_EXPR:
7272 case EQ_EXPR:
7273 case NE_EXPR:
7274 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7275 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7276 && (TYPE_MAIN_VARIANT (arg1_type)
7277 != TYPE_MAIN_VARIANT (arg2_type))
7278 && (complain & tf_warning))
7279 warning_at (loc, OPT_Wenum_compare,
7280 "comparison between %q#T and %q#T",
7281 arg1_type, arg2_type);
7282 break;
7283 default:
7284 break;
7287 /* "If a built-in candidate is selected by overload resolution, the
7288 operands of class type are converted to the types of the
7289 corresponding parameters of the selected operation function,
7290 except that the second standard conversion sequence of a
7291 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7292 conversion *conv = cand->convs[0];
7293 if (conv->user_conv_p)
7295 conv = strip_standard_conversion (conv);
7296 arg1 = convert_like (conv, arg1, complain);
7299 if (arg2)
7301 conv = cand->convs[1];
7302 if (conv->user_conv_p)
7304 conv = strip_standard_conversion (conv);
7305 arg2 = convert_like (conv, arg2, complain);
7309 if (arg3)
7311 conv = cand->convs[2];
7312 if (conv->user_conv_p)
7314 conv = strip_standard_conversion (conv);
7315 arg3 = convert_like (conv, arg3, complain);
7321 user_defined_result_ready:
7323 /* Free all the conversions we allocated. */
7324 obstack_free (&conversion_obstack, p);
7326 if (result || result_valid_p)
7327 return result;
7329 builtin:
7330 switch (code)
7332 case MODIFY_EXPR:
7333 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7335 case INDIRECT_REF:
7336 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7338 case TRUTH_ANDIF_EXPR:
7339 case TRUTH_ORIF_EXPR:
7340 case TRUTH_AND_EXPR:
7341 case TRUTH_OR_EXPR:
7342 if ((complain & tf_warning) && !processing_template_decl)
7343 warn_logical_operator (loc, code, boolean_type_node,
7344 code_orig_arg1, arg1,
7345 code_orig_arg2, arg2);
7346 /* Fall through. */
7347 case GT_EXPR:
7348 case LT_EXPR:
7349 case GE_EXPR:
7350 case LE_EXPR:
7351 case EQ_EXPR:
7352 case NE_EXPR:
7353 if ((complain & tf_warning)
7354 && ((code_orig_arg1 == BOOLEAN_TYPE)
7355 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7356 maybe_warn_bool_compare (loc, code, arg1, arg2);
7357 if (complain & tf_warning && warn_tautological_compare)
7358 warn_tautological_cmp (loc, code, arg1, arg2);
7359 /* Fall through. */
7360 case SPACESHIP_EXPR:
7361 case PLUS_EXPR:
7362 case MINUS_EXPR:
7363 case MULT_EXPR:
7364 case TRUNC_DIV_EXPR:
7365 case MAX_EXPR:
7366 case MIN_EXPR:
7367 case LSHIFT_EXPR:
7368 case RSHIFT_EXPR:
7369 case TRUNC_MOD_EXPR:
7370 case BIT_AND_EXPR:
7371 case BIT_IOR_EXPR:
7372 case BIT_XOR_EXPR:
7373 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7375 case UNARY_PLUS_EXPR:
7376 case NEGATE_EXPR:
7377 case BIT_NOT_EXPR:
7378 case TRUTH_NOT_EXPR:
7379 case PREINCREMENT_EXPR:
7380 case POSTINCREMENT_EXPR:
7381 case PREDECREMENT_EXPR:
7382 case POSTDECREMENT_EXPR:
7383 case REALPART_EXPR:
7384 case IMAGPART_EXPR:
7385 case ABS_EXPR:
7386 case CO_AWAIT_EXPR:
7387 return cp_build_unary_op (code, arg1, false, complain);
7389 case ARRAY_REF:
7390 return cp_build_array_ref (input_location, arg1, arg2, complain);
7392 case MEMBER_REF:
7393 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7394 RO_ARROW_STAR,
7395 complain),
7396 arg2, complain);
7398 /* The caller will deal with these. */
7399 case ADDR_EXPR:
7400 case COMPONENT_REF:
7401 case COMPOUND_EXPR:
7402 return NULL_TREE;
7404 default:
7405 gcc_unreachable ();
7407 return NULL_TREE;
7410 /* Build a new call to operator[]. This may change ARGS. */
7412 tree
7413 build_op_subscript (const op_location_t &loc, tree obj,
7414 vec<tree, va_gc> **args, tree *overload,
7415 tsubst_flags_t complain)
7417 struct z_candidate *candidates = 0, *cand;
7418 tree fns, first_mem_arg = NULL_TREE;
7419 bool any_viable_p;
7420 tree result = NULL_TREE;
7421 void *p;
7423 auto_cond_timevar tv (TV_OVERLOAD);
7425 obj = mark_lvalue_use (obj);
7427 if (error_operand_p (obj))
7428 return error_mark_node;
7430 tree type = TREE_TYPE (obj);
7432 obj = prep_operand (obj);
7434 if (TYPE_BINFO (type))
7436 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7437 1, complain);
7438 if (fns == error_mark_node)
7439 return error_mark_node;
7441 else
7442 fns = NULL_TREE;
7444 if (args != NULL && *args != NULL)
7446 *args = resolve_args (*args, complain);
7447 if (*args == NULL)
7448 return error_mark_node;
7451 /* Get the high-water mark for the CONVERSION_OBSTACK. */
7452 p = conversion_obstack_alloc (0);
7454 if (fns)
7456 first_mem_arg = obj;
7458 add_candidates (BASELINK_FUNCTIONS (fns),
7459 first_mem_arg, *args, NULL_TREE,
7460 NULL_TREE, false,
7461 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7462 LOOKUP_NORMAL, &candidates, complain);
7465 /* Be strict here because if we choose a bad conversion candidate, the
7466 errors we get won't mention the call context. */
7467 candidates = splice_viable (candidates, true, &any_viable_p);
7468 if (!any_viable_p)
7470 if (complain & tf_error)
7472 auto_diagnostic_group d;
7473 error ("no match for call to %<%T::operator[] (%A)%>",
7474 TREE_TYPE (obj), build_tree_list_vec (*args));
7475 print_z_candidates (loc, candidates);
7477 result = error_mark_node;
7479 else
7481 cand = tourney (candidates, complain);
7482 if (cand == 0)
7484 if (complain & tf_error)
7486 auto_diagnostic_group d;
7487 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7488 TREE_TYPE (obj), build_tree_list_vec (*args));
7489 print_z_candidates (loc, candidates);
7491 result = error_mark_node;
7493 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7494 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7495 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7497 if (overload)
7498 *overload = cand->fn;
7499 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7500 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7501 /* There won't be a CALL_EXPR. */;
7502 else if (result && result != error_mark_node)
7504 tree call = extract_call_expr (result);
7505 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7507 /* Specify evaluation order as per P0145R2. */
7508 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7511 /* In an expression of the form `a[]' where cand->fn
7512 which is operator[] turns out to be a static member function,
7513 `a' is none-the-less evaluated. */
7514 result = keep_unused_object_arg (result, obj, cand->fn);
7516 else
7517 gcc_unreachable ();
7520 /* Free all the conversions we allocated. */
7521 obstack_free (&conversion_obstack, p);
7523 return result;
7526 /* CALL was returned by some call-building function; extract the actual
7527 CALL_EXPR from any bits that have been tacked on, e.g. by
7528 convert_from_reference. */
7530 tree
7531 extract_call_expr (tree call)
7533 while (TREE_CODE (call) == COMPOUND_EXPR)
7534 call = TREE_OPERAND (call, 1);
7535 if (REFERENCE_REF_P (call))
7536 call = TREE_OPERAND (call, 0);
7537 if (TREE_CODE (call) == TARGET_EXPR)
7538 call = TARGET_EXPR_INITIAL (call);
7539 if (cxx_dialect >= cxx20)
7540 switch (TREE_CODE (call))
7542 /* C++20 rewritten comparison operators. */
7543 case TRUTH_NOT_EXPR:
7544 call = TREE_OPERAND (call, 0);
7545 break;
7546 case LT_EXPR:
7547 case LE_EXPR:
7548 case GT_EXPR:
7549 case GE_EXPR:
7550 case SPACESHIP_EXPR:
7552 tree op0 = TREE_OPERAND (call, 0);
7553 if (integer_zerop (op0))
7554 call = TREE_OPERAND (call, 1);
7555 else
7556 call = op0;
7558 break;
7559 default:;
7562 if (TREE_CODE (call) != CALL_EXPR
7563 && TREE_CODE (call) != AGGR_INIT_EXPR
7564 && call != error_mark_node)
7565 return NULL_TREE;
7566 return call;
7569 /* Returns true if FN has two parameters, of which the second has type
7570 size_t. */
7572 static bool
7573 second_parm_is_size_t (tree fn)
7575 tree t = FUNCTION_ARG_CHAIN (fn);
7576 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7577 return false;
7578 t = TREE_CHAIN (t);
7579 if (t == void_list_node)
7580 return true;
7581 return false;
7584 /* True if T, an allocation function, has std::align_val_t as its second
7585 argument. */
7587 bool
7588 aligned_allocation_fn_p (tree t)
7590 if (!aligned_new_threshold)
7591 return false;
7593 tree a = FUNCTION_ARG_CHAIN (t);
7594 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7597 /* True if T is std::destroying_delete_t. */
7599 static bool
7600 std_destroying_delete_t_p (tree t)
7602 return (TYPE_CONTEXT (t) == std_node
7603 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7606 /* A deallocation function with at least two parameters whose second parameter
7607 type is of type std::destroying_delete_t is a destroying operator delete. A
7608 destroying operator delete shall be a class member function named operator
7609 delete. [ Note: Array deletion cannot use a destroying operator
7610 delete. --end note ] */
7612 tree
7613 destroying_delete_p (tree t)
7615 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7616 if (!a || !TREE_CHAIN (a))
7617 return NULL_TREE;
7618 tree type = TREE_VALUE (TREE_CHAIN (a));
7619 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7622 struct dealloc_info
7624 bool sized;
7625 bool aligned;
7626 tree destroying;
7629 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7630 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7631 non-null, also set *DI. */
7633 static bool
7634 usual_deallocation_fn_p (tree t, dealloc_info *di)
7636 if (di) *di = dealloc_info();
7638 /* A template instance is never a usual deallocation function,
7639 regardless of its signature. */
7640 if (TREE_CODE (t) == TEMPLATE_DECL
7641 || primary_template_specialization_p (t))
7642 return false;
7644 /* A usual deallocation function is a deallocation function whose parameters
7645 after the first are
7646 - optionally, a parameter of type std::destroying_delete_t, then
7647 - optionally, a parameter of type std::size_t, then
7648 - optionally, a parameter of type std::align_val_t. */
7649 bool global = DECL_NAMESPACE_SCOPE_P (t);
7650 tree chain = FUNCTION_ARG_CHAIN (t);
7651 if (chain && destroying_delete_p (t))
7653 if (di) di->destroying = TREE_VALUE (chain);
7654 chain = TREE_CHAIN (chain);
7656 if (chain
7657 && (!global || flag_sized_deallocation)
7658 && same_type_p (TREE_VALUE (chain), size_type_node))
7660 if (di) di->sized = true;
7661 chain = TREE_CHAIN (chain);
7663 if (chain && aligned_new_threshold
7664 && same_type_p (TREE_VALUE (chain), align_type_node))
7666 if (di) di->aligned = true;
7667 chain = TREE_CHAIN (chain);
7669 return (chain == void_list_node);
7672 /* Just return whether FN is a usual deallocation function. */
7674 bool
7675 usual_deallocation_fn_p (tree fn)
7677 return usual_deallocation_fn_p (fn, NULL);
7680 /* Build a call to operator delete. This has to be handled very specially,
7681 because the restrictions on what signatures match are different from all
7682 other call instances. For a normal delete, only a delete taking (void *)
7683 or (void *, size_t) is accepted. For a placement delete, only an exact
7684 match with the placement new is accepted.
7686 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7687 ADDR is the pointer to be deleted.
7688 SIZE is the size of the memory block to be deleted.
7689 GLOBAL_P is true if the delete-expression should not consider
7690 class-specific delete operators.
7691 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7693 If this call to "operator delete" is being generated as part to
7694 deallocate memory allocated via a new-expression (as per [expr.new]
7695 which requires that if the initialization throws an exception then
7696 we call a deallocation function), then ALLOC_FN is the allocation
7697 function. */
7699 tree
7700 build_op_delete_call (enum tree_code code, tree addr, tree size,
7701 bool global_p, tree placement,
7702 tree alloc_fn, tsubst_flags_t complain)
7704 tree fn = NULL_TREE;
7705 tree fns, fnname, type, t;
7706 dealloc_info di_fn = { };
7708 if (addr == error_mark_node)
7709 return error_mark_node;
7711 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7713 fnname = ovl_op_identifier (false, code);
7715 if (CLASS_TYPE_P (type)
7716 && COMPLETE_TYPE_P (complete_type (type))
7717 && !global_p)
7718 /* In [class.free]
7720 If the result of the lookup is ambiguous or inaccessible, or if
7721 the lookup selects a placement deallocation function, the
7722 program is ill-formed.
7724 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7726 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7727 if (fns == error_mark_node)
7728 return error_mark_node;
7730 else
7731 fns = NULL_TREE;
7733 if (fns == NULL_TREE)
7734 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7736 /* Strip const and volatile from addr. */
7737 tree oaddr = addr;
7738 addr = cp_convert (ptr_type_node, addr, complain);
7740 tree excluded_destroying = NULL_TREE;
7742 if (placement)
7744 /* "A declaration of a placement deallocation function matches the
7745 declaration of a placement allocation function if it has the same
7746 number of parameters and, after parameter transformations (8.3.5),
7747 all parameter types except the first are identical."
7749 So we build up the function type we want and ask instantiate_type
7750 to get it for us. */
7751 t = FUNCTION_ARG_CHAIN (alloc_fn);
7752 t = tree_cons (NULL_TREE, ptr_type_node, t);
7753 t = build_function_type (void_type_node, t);
7755 fn = instantiate_type (t, fns, tf_none);
7756 if (fn == error_mark_node)
7757 return NULL_TREE;
7759 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7761 /* "If the lookup finds the two-parameter form of a usual deallocation
7762 function (3.7.4.2) and that function, considered as a placement
7763 deallocation function, would have been selected as a match for the
7764 allocation function, the program is ill-formed." */
7765 if (second_parm_is_size_t (fn))
7767 const char *const msg1
7768 = G_("exception cleanup for this placement new selects "
7769 "non-placement %<operator delete%>");
7770 const char *const msg2
7771 = G_("%qD is a usual (non-placement) deallocation "
7772 "function in C++14 (or with %<-fsized-deallocation%>)");
7774 /* But if the class has an operator delete (void *), then that is
7775 the usual deallocation function, so we shouldn't complain
7776 about using the operator delete (void *, size_t). */
7777 if (DECL_CLASS_SCOPE_P (fn))
7778 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7780 if (usual_deallocation_fn_p (elt)
7781 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7782 goto ok;
7784 /* Before C++14 a two-parameter global deallocation function is
7785 always a placement deallocation function, but warn if
7786 -Wc++14-compat. */
7787 else if (!flag_sized_deallocation)
7789 if (complain & tf_warning)
7791 auto_diagnostic_group d;
7792 if (warning (OPT_Wc__14_compat, msg1))
7793 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7795 goto ok;
7798 if (complain & tf_warning_or_error)
7800 auto_diagnostic_group d;
7801 if (permerror (input_location, msg1))
7803 /* Only mention C++14 for namespace-scope delete. */
7804 if (DECL_NAMESPACE_SCOPE_P (fn))
7805 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7806 else
7807 inform (DECL_SOURCE_LOCATION (fn),
7808 "%qD is a usual (non-placement) deallocation "
7809 "function", fn);
7812 else
7813 return error_mark_node;
7814 ok:;
7817 else
7818 /* "Any non-placement deallocation function matches a non-placement
7819 allocation function. If the lookup finds a single matching
7820 deallocation function, that function will be called; otherwise, no
7821 deallocation function will be called." */
7822 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7824 dealloc_info di_elt;
7825 if (usual_deallocation_fn_p (elt, &di_elt))
7827 /* If we're called for an EH cleanup in a new-expression, we can't
7828 use a destroying delete; the exception was thrown before the
7829 object was constructed. */
7830 if (alloc_fn && di_elt.destroying)
7832 excluded_destroying = elt;
7833 continue;
7836 if (!fn)
7838 fn = elt;
7839 di_fn = di_elt;
7840 continue;
7843 /* -- If any of the deallocation functions is a destroying
7844 operator delete, all deallocation functions that are not
7845 destroying operator deletes are eliminated from further
7846 consideration. */
7847 if (di_elt.destroying != di_fn.destroying)
7849 if (di_elt.destroying)
7851 fn = elt;
7852 di_fn = di_elt;
7854 continue;
7857 /* -- If the type has new-extended alignment, a function with a
7858 parameter of type std::align_val_t is preferred; otherwise a
7859 function without such a parameter is preferred. If exactly one
7860 preferred function is found, that function is selected and the
7861 selection process terminates. If more than one preferred
7862 function is found, all non-preferred functions are eliminated
7863 from further consideration. */
7864 if (aligned_new_threshold)
7866 bool want_align = type_has_new_extended_alignment (type);
7867 if (di_elt.aligned != di_fn.aligned)
7869 if (want_align == di_elt.aligned)
7871 fn = elt;
7872 di_fn = di_elt;
7874 continue;
7878 /* -- If the deallocation functions have class scope, the one
7879 without a parameter of type std::size_t is selected. */
7880 bool want_size;
7881 if (DECL_CLASS_SCOPE_P (fn))
7882 want_size = false;
7884 /* -- If the type is complete and if, for the second alternative
7885 (delete array) only, the operand is a pointer to a class type
7886 with a non-trivial destructor or a (possibly multi-dimensional)
7887 array thereof, the function with a parameter of type std::size_t
7888 is selected.
7890 -- Otherwise, it is unspecified whether a deallocation function
7891 with a parameter of type std::size_t is selected. */
7892 else
7894 want_size = COMPLETE_TYPE_P (type);
7895 if (code == VEC_DELETE_EXPR
7896 && !TYPE_VEC_NEW_USES_COOKIE (type))
7897 /* We need a cookie to determine the array size. */
7898 want_size = false;
7900 gcc_assert (di_fn.sized != di_elt.sized);
7901 if (want_size == di_elt.sized)
7903 fn = elt;
7904 di_fn = di_elt;
7909 /* If we have a matching function, call it. */
7910 if (fn)
7912 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7914 /* If the FN is a member function, make sure that it is
7915 accessible. */
7916 if (BASELINK_P (fns))
7917 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7918 complain);
7920 /* Core issue 901: It's ok to new a type with deleted delete. */
7921 if (DECL_DELETED_FN (fn) && alloc_fn)
7922 return NULL_TREE;
7924 tree ret;
7925 if (placement)
7927 /* The placement args might not be suitable for overload
7928 resolution at this point, so build the call directly. */
7929 int nargs = call_expr_nargs (placement);
7930 tree *argarray = XALLOCAVEC (tree, nargs);
7931 int i;
7932 argarray[0] = addr;
7933 for (i = 1; i < nargs; i++)
7934 argarray[i] = CALL_EXPR_ARG (placement, i);
7935 if (!mark_used (fn, complain) && !(complain & tf_error))
7936 return error_mark_node;
7937 ret = build_cxx_call (fn, nargs, argarray, complain);
7939 else
7941 tree destroying = di_fn.destroying;
7942 if (destroying)
7944 /* Strip const and volatile from addr but retain the type of the
7945 object. */
7946 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7947 rtype = cv_unqualified (rtype);
7948 rtype = TYPE_POINTER_TO (rtype);
7949 addr = cp_convert (rtype, oaddr, complain);
7950 destroying = build_functional_cast (input_location,
7951 destroying, NULL_TREE,
7952 complain);
7955 releasing_vec args;
7956 args->quick_push (addr);
7957 if (destroying)
7958 args->quick_push (destroying);
7959 if (di_fn.sized)
7960 args->quick_push (size);
7961 if (di_fn.aligned)
7963 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7964 args->quick_push (al);
7966 ret = cp_build_function_call_vec (fn, &args, complain);
7969 /* Set this flag for all callers of this function. In addition to
7970 delete-expressions, this is called for deallocating coroutine state;
7971 treat that as an implicit delete-expression. This is also called for
7972 the delete if the constructor throws in a new-expression, and for a
7973 deleting destructor (which implements a delete-expression). */
7974 /* But leave this flag off for destroying delete to avoid wrong
7975 assumptions in the optimizers. */
7976 tree call = extract_call_expr (ret);
7977 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
7978 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7980 return ret;
7983 /* If there's only a destroying delete that we can't use because the
7984 object isn't constructed yet, and we used global new, use global
7985 delete as well. */
7986 if (excluded_destroying
7987 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
7988 return build_op_delete_call (code, addr, size, true, placement,
7989 alloc_fn, complain);
7991 /* [expr.new]
7993 If no unambiguous matching deallocation function can be found,
7994 propagating the exception does not cause the object's memory to
7995 be freed. */
7996 if (alloc_fn)
7998 if ((complain & tf_warning)
7999 && !placement)
8001 bool w = warning (0,
8002 "no corresponding deallocation function for %qD",
8003 alloc_fn);
8004 if (w && excluded_destroying)
8005 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8006 "delete %qD cannot be used to release the allocated memory"
8007 " if the initialization throws because the object is not "
8008 "constructed yet", excluded_destroying);
8010 return NULL_TREE;
8013 if (complain & tf_error)
8014 error ("no suitable %<operator %s%> for %qT",
8015 OVL_OP_INFO (false, code)->name, type);
8016 return error_mark_node;
8019 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8020 in the diagnostics.
8022 If ISSUE_ERROR is true, then issue an error about the access, followed
8023 by a note showing the declaration. Otherwise, just show the note.
8025 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8026 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8027 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8028 would be because DECL was private). If not using NO_ACCESS_REASON,
8029 then it must be ak_none, and the access failure reason will be
8030 figured out by looking at the protection of DECL. */
8032 void
8033 complain_about_access (tree decl, tree diag_decl, tree diag_location,
8034 bool issue_error, access_kind no_access_reason)
8036 /* If we have not already figured out why DECL is inaccessible... */
8037 if (no_access_reason == ak_none)
8039 /* Examine the access of DECL to find out why. */
8040 if (TREE_PRIVATE (decl))
8041 no_access_reason = ak_private;
8042 else if (TREE_PROTECTED (decl))
8043 no_access_reason = ak_protected;
8046 /* Now generate an error message depending on calculated access. */
8047 if (no_access_reason == ak_private)
8049 if (issue_error)
8050 error ("%q#D is private within this context", diag_decl);
8051 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8053 else if (no_access_reason == ak_protected)
8055 if (issue_error)
8056 error ("%q#D is protected within this context", diag_decl);
8057 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8059 /* Couldn't figure out why DECL is inaccesible, so just say it's
8060 inaccessible. */
8061 else
8063 if (issue_error)
8064 error ("%q#D is inaccessible within this context", diag_decl);
8065 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8069 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8070 bitwise or of LOOKUP_* values. If any errors are warnings are
8071 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8072 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8073 to NULL. */
8075 static tree
8076 build_temp (tree expr, tree type, int flags,
8077 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8079 int savew, savee;
8081 *diagnostic_kind = DK_UNSPECIFIED;
8083 /* If the source is a packed field, calling the copy constructor will require
8084 binding the field to the reference parameter to the copy constructor, and
8085 we'll end up with an infinite loop. If we can use a bitwise copy, then
8086 do that now. */
8087 if ((lvalue_kind (expr) & clk_packed)
8088 && CLASS_TYPE_P (TREE_TYPE (expr))
8089 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8090 return get_target_expr (expr, complain);
8092 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8093 But it turns out to be a subexpression, so perform temporary
8094 materialization now. */
8095 if (TREE_CODE (expr) == CALL_EXPR
8096 && CLASS_TYPE_P (type)
8097 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8098 expr = build_cplus_new (type, expr, complain);
8100 savew = warningcount + werrorcount, savee = errorcount;
8101 releasing_vec args (make_tree_vector_single (expr));
8102 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8103 &args, type, flags, complain);
8104 if (warningcount + werrorcount > savew)
8105 *diagnostic_kind = DK_WARNING;
8106 else if (errorcount > savee)
8107 *diagnostic_kind = DK_ERROR;
8108 return expr;
8111 /* Get any location for EXPR, falling back to input_location.
8113 If the result is in a system header and is the virtual location for
8114 a token coming from the expansion of a macro, unwind it to the
8115 location of the expansion point of the macro (e.g. to avoid the
8116 diagnostic being suppressed for expansions of NULL where "NULL" is
8117 in a system header). */
8119 static location_t
8120 get_location_for_expr_unwinding_for_system_header (tree expr)
8122 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8123 loc = expansion_point_location_if_in_system_header (loc);
8124 return loc;
8127 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
8128 Also handle a subset of zero as null warnings.
8129 EXPR is implicitly converted to type TOTYPE.
8130 FN and ARGNUM are used for diagnostics. */
8132 static void
8133 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8135 /* Issue warnings about peculiar, but valid, uses of NULL. */
8136 if (TREE_CODE (totype) != BOOLEAN_TYPE
8137 && ARITHMETIC_TYPE_P (totype)
8138 && null_node_p (expr))
8140 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8141 if (fn)
8143 auto_diagnostic_group d;
8144 if (warning_at (loc, OPT_Wconversion_null,
8145 "passing NULL to non-pointer argument %P of %qD",
8146 argnum, fn))
8147 inform (get_fndecl_argument_location (fn, argnum),
8148 " declared here");
8150 else
8151 warning_at (loc, OPT_Wconversion_null,
8152 "converting to non-pointer type %qT from NULL", totype);
8155 /* Issue warnings if "false" is converted to a NULL pointer */
8156 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8157 && TYPE_PTR_P (totype))
8159 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8160 if (fn)
8162 auto_diagnostic_group d;
8163 if (warning_at (loc, OPT_Wconversion_null,
8164 "converting %<false%> to pointer type for argument "
8165 "%P of %qD", argnum, fn))
8166 inform (get_fndecl_argument_location (fn, argnum),
8167 " declared here");
8169 else
8170 warning_at (loc, OPT_Wconversion_null,
8171 "converting %<false%> to pointer type %qT", totype);
8173 /* Handle zero as null pointer warnings for cases other
8174 than EQ_EXPR and NE_EXPR */
8175 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8176 && null_ptr_cst_p (expr))
8178 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8179 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8183 /* We gave a diagnostic during a conversion. If this was in the second
8184 standard conversion sequence of a user-defined conversion sequence, say
8185 which user-defined conversion. */
8187 static void
8188 maybe_print_user_conv_context (conversion *convs)
8190 if (convs->user_conv_p)
8191 for (conversion *t = convs; t; t = next_conversion (t))
8192 if (t->kind == ck_user)
8194 print_z_candidate (0, N_(" after user-defined conversion:"),
8195 t->cand);
8196 break;
8200 /* Locate the parameter with the given index within FNDECL.
8201 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8202 Return the location of the FNDECL itself if there are problems. */
8204 location_t
8205 get_fndecl_argument_location (tree fndecl, int argnum)
8207 /* The locations of implicitly-declared functions are likely to be
8208 more meaningful than those of their parameters. */
8209 if (DECL_ARTIFICIAL (fndecl))
8210 return DECL_SOURCE_LOCATION (fndecl);
8212 int i;
8213 tree param;
8215 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8216 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8217 i < argnum && param;
8218 i++, param = TREE_CHAIN (param))
8221 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8222 return the location of FNDECL. */
8223 if (param == NULL)
8224 return DECL_SOURCE_LOCATION (fndecl);
8226 return DECL_SOURCE_LOCATION (param);
8229 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8230 within its declaration (or the fndecl itself if something went
8231 wrong). */
8233 void
8234 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
8236 if (fn)
8237 inform (get_fndecl_argument_location (fn, argnum),
8238 " initializing argument %P of %qD", argnum, fn);
8241 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8242 the conversion, EXPR is the expression we're converting. */
8244 static void
8245 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8247 if (cxx_dialect >= cxx20)
8248 return;
8250 tree type = TREE_TYPE (expr);
8251 type = strip_pointer_operator (type);
8253 if (TREE_CODE (type) != ARRAY_TYPE
8254 || TYPE_DOMAIN (type) == NULL_TREE)
8255 return;
8257 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8258 pedwarn (loc, OPT_Wc__20_extensions,
8259 "conversions to arrays of unknown bound "
8260 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8263 /* We call this recursively in convert_like_internal. */
8264 static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8265 tsubst_flags_t);
8267 /* Perform the conversions in CONVS on the expression EXPR. FN and
8268 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8269 indicates the `this' argument of a method. INNER is nonzero when
8270 being called to continue a conversion chain. It is negative when a
8271 reference binding will be applied, positive otherwise. If
8272 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8273 conversions will be emitted if appropriate. If C_CAST_P is true,
8274 this conversion is coming from a C-style cast; in that case,
8275 conversions to inaccessible bases are permitted. */
8277 static tree
8278 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8279 bool issue_conversion_warnings, bool c_cast_p,
8280 bool nested_p, tsubst_flags_t complain)
8282 tree totype = convs->type;
8283 diagnostic_t diag_kind;
8284 int flags;
8285 location_t loc = cp_expr_loc_or_input_loc (expr);
8287 if (convs->bad_p && !(complain & tf_error))
8288 return error_mark_node;
8290 if (convs->bad_p
8291 && convs->kind != ck_user
8292 && convs->kind != ck_list
8293 && convs->kind != ck_ambig
8294 && (convs->kind != ck_ref_bind
8295 || (convs->user_conv_p && next_conversion (convs)->bad_p))
8296 && (convs->kind != ck_rvalue
8297 || SCALAR_TYPE_P (totype))
8298 && convs->kind != ck_base)
8300 int complained = 0;
8301 conversion *t = convs;
8303 /* Give a helpful error if this is bad because of excess braces. */
8304 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8305 && SCALAR_TYPE_P (totype)
8306 && CONSTRUCTOR_NELTS (expr) > 0
8307 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8309 complained = permerror (loc, "too many braces around initializer "
8310 "for %qT", totype);
8311 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8312 && CONSTRUCTOR_NELTS (expr) == 1)
8313 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8316 /* Give a helpful error if this is bad because a conversion to bool
8317 from std::nullptr_t requires direct-initialization. */
8318 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8319 && TREE_CODE (totype) == BOOLEAN_TYPE)
8320 complained = permerror (loc, "converting to %qH from %qI requires "
8321 "direct-initialization",
8322 totype, TREE_TYPE (expr));
8324 if (TREE_CODE (TREE_TYPE (expr)) == REAL_TYPE
8325 && TREE_CODE (totype) == REAL_TYPE
8326 && (extended_float_type_p (TREE_TYPE (expr))
8327 || extended_float_type_p (totype)))
8328 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8329 totype))
8331 case 2:
8332 if (pedwarn (loc, 0, "converting to %qH from %qI with greater "
8333 "conversion rank", totype, TREE_TYPE (expr)))
8334 complained = 1;
8335 else if (!complained)
8336 complained = -1;
8337 break;
8338 case 3:
8339 if (pedwarn (loc, 0, "converting to %qH from %qI with unordered "
8340 "conversion ranks", totype, TREE_TYPE (expr)))
8341 complained = 1;
8342 else if (!complained)
8343 complained = -1;
8344 break;
8345 default:
8346 break;
8349 for (; t ; t = next_conversion (t))
8351 if (t->kind == ck_user && t->cand->reason)
8353 auto_diagnostic_group d;
8354 complained = permerror (loc, "invalid user-defined conversion "
8355 "from %qH to %qI", TREE_TYPE (expr),
8356 totype);
8357 if (complained)
8358 print_z_candidate (loc, N_("candidate is:"), t->cand);
8359 expr = convert_like (t, expr, fn, argnum,
8360 /*issue_conversion_warnings=*/false,
8361 /*c_cast_p=*/false, /*nested_p=*/true,
8362 complain);
8363 if (convs->kind == ck_ref_bind)
8364 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8365 LOOKUP_NORMAL, NULL_TREE,
8366 complain);
8367 else
8368 expr = cp_convert (totype, expr, complain);
8369 if (complained)
8370 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8371 return expr;
8373 else if (t->kind == ck_user || !t->bad_p)
8375 expr = convert_like (t, expr, fn, argnum,
8376 /*issue_conversion_warnings=*/false,
8377 /*c_cast_p=*/false, /*nested_p=*/true,
8378 complain);
8379 break;
8381 else if (t->kind == ck_ambig)
8382 return convert_like (t, expr, fn, argnum,
8383 /*issue_conversion_warnings=*/false,
8384 /*c_cast_p=*/false, /*nested_p=*/true,
8385 complain);
8386 else if (t->kind == ck_identity)
8387 break;
8389 if (!complained && expr != error_mark_node)
8391 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8392 gcc_rich_location richloc (loc, &label);
8393 complained = permerror (&richloc,
8394 "invalid conversion from %qH to %qI",
8395 TREE_TYPE (expr), totype);
8397 if (complained == 1)
8398 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8400 return cp_convert (totype, expr, complain);
8403 if (issue_conversion_warnings && (complain & tf_warning))
8404 conversion_null_warnings (totype, expr, fn, argnum);
8406 switch (convs->kind)
8408 case ck_user:
8410 struct z_candidate *cand = convs->cand;
8412 if (cand == NULL)
8413 /* We chose the surrogate function from add_conv_candidate, now we
8414 actually need to build the conversion. */
8415 cand = build_user_type_conversion_1 (totype, expr,
8416 LOOKUP_NO_CONVERSION, complain);
8418 tree convfn = cand->fn;
8420 /* When converting from an init list we consider explicit
8421 constructors, but actually trying to call one is an error. */
8422 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8423 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8424 /* Unless this is for direct-list-initialization. */
8425 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8426 /* And in C++98 a default constructor can't be explicit. */
8427 && cxx_dialect >= cxx11)
8429 if (!(complain & tf_error))
8430 return error_mark_node;
8431 location_t loc = location_of (expr);
8432 if (CONSTRUCTOR_NELTS (expr) == 0
8433 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8435 auto_diagnostic_group d;
8436 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8437 "would use explicit constructor %qD",
8438 totype, convfn))
8439 inform (loc, "in C++11 and above a default constructor "
8440 "can be explicit");
8442 else
8443 error ("converting to %qT from initializer list would use "
8444 "explicit constructor %qD", totype, convfn);
8447 /* If we're initializing from {}, it's value-initialization. */
8448 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8449 && CONSTRUCTOR_NELTS (expr) == 0
8450 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8451 && !processing_template_decl)
8453 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8454 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8455 return error_mark_node;
8456 expr = build_value_init (totype, complain);
8457 expr = get_target_expr (expr, complain);
8458 if (expr != error_mark_node)
8460 TARGET_EXPR_LIST_INIT_P (expr) = true;
8461 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8463 return expr;
8466 /* We don't know here whether EXPR is being used as an lvalue or
8467 rvalue, but we know it's read. */
8468 mark_exp_read (expr);
8470 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8471 any more UDCs. */
8472 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8473 complain);
8475 /* If this is a constructor or a function returning an aggr type,
8476 we need to build up a TARGET_EXPR. */
8477 if (DECL_CONSTRUCTOR_P (convfn))
8479 expr = build_cplus_new (totype, expr, complain);
8481 /* Remember that this was list-initialization. */
8482 if (convs->check_narrowing && expr != error_mark_node)
8483 TARGET_EXPR_LIST_INIT_P (expr) = true;
8486 return expr;
8488 case ck_identity:
8489 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8491 int nelts = CONSTRUCTOR_NELTS (expr);
8492 if (nelts == 0)
8493 expr = build_value_init (totype, complain);
8494 else if (nelts == 1)
8495 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8496 else
8497 gcc_unreachable ();
8499 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8500 /*read_p=*/true, UNKNOWN_LOCATION,
8501 /*reject_builtin=*/true);
8503 if (type_unknown_p (expr))
8504 expr = instantiate_type (totype, expr, complain);
8505 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8506 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8507 if (expr == null_node
8508 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8509 /* If __null has been converted to an integer type, we do not want to
8510 continue to warn about uses of EXPR as an integer, rather than as a
8511 pointer. */
8512 expr = build_int_cst (totype, 0);
8513 return expr;
8514 case ck_ambig:
8515 /* We leave bad_p off ck_ambig because overload resolution considers
8516 it valid, it just fails when we try to perform it. So we need to
8517 check complain here, too. */
8518 if (complain & tf_error)
8520 /* Call build_user_type_conversion again for the error. */
8521 int flags = (convs->need_temporary_p
8522 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8523 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8524 gcc_assert (seen_error ());
8525 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8527 return error_mark_node;
8529 case ck_list:
8531 /* Conversion to std::initializer_list<T>. */
8532 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8533 unsigned len = CONSTRUCTOR_NELTS (expr);
8534 tree array;
8536 if (len)
8538 tree val; unsigned ix;
8540 tree new_ctor = build_constructor (init_list_type_node, NULL);
8542 /* Convert all the elements. */
8543 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8545 tree sub = convert_like (convs->u.list[ix], val, fn,
8546 argnum, false, false,
8547 /*nested_p=*/true, complain);
8548 if (sub == error_mark_node)
8549 return sub;
8550 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8551 && !check_narrowing (TREE_TYPE (sub), val, complain))
8552 return error_mark_node;
8553 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8554 NULL_TREE, sub);
8555 if (!TREE_CONSTANT (sub))
8556 TREE_CONSTANT (new_ctor) = false;
8558 /* Build up the array. */
8559 elttype = cp_build_qualified_type
8560 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8561 array = build_array_of_n_type (elttype, len);
8562 array = finish_compound_literal (array, new_ctor, complain);
8563 /* Take the address explicitly rather than via decay_conversion
8564 to avoid the error about taking the address of a temporary. */
8565 array = cp_build_addr_expr (array, complain);
8567 else
8568 array = nullptr_node;
8570 array = cp_convert (build_pointer_type (elttype), array, complain);
8571 if (array == error_mark_node)
8572 return error_mark_node;
8574 /* Build up the initializer_list object. Note: fail gracefully
8575 if the object cannot be completed because, for example, no
8576 definition is provided (c++/80956). */
8577 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8578 if (!totype)
8579 return error_mark_node;
8580 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8581 vec<constructor_elt, va_gc> *vec = NULL;
8582 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8583 field = next_aggregate_field (DECL_CHAIN (field));
8584 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8585 tree new_ctor = build_constructor (totype, vec);
8586 return get_target_expr (new_ctor, complain);
8589 case ck_aggr:
8590 if (TREE_CODE (totype) == COMPLEX_TYPE)
8592 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8593 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8594 real = perform_implicit_conversion (TREE_TYPE (totype),
8595 real, complain);
8596 imag = perform_implicit_conversion (TREE_TYPE (totype),
8597 imag, complain);
8598 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8599 return expr;
8601 expr = reshape_init (totype, expr, complain);
8602 expr = get_target_expr (digest_init (totype, expr, complain),
8603 complain);
8604 if (expr != error_mark_node)
8605 TARGET_EXPR_LIST_INIT_P (expr) = true;
8606 return expr;
8608 default:
8609 break;
8612 expr = convert_like (next_conversion (convs), expr, fn, argnum,
8613 convs->kind == ck_ref_bind
8614 ? issue_conversion_warnings : false,
8615 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8616 if (expr == error_mark_node)
8617 return error_mark_node;
8619 switch (convs->kind)
8621 case ck_rvalue:
8622 expr = decay_conversion (expr, complain);
8623 if (expr == error_mark_node)
8625 if (complain & tf_error)
8627 auto_diagnostic_group d;
8628 maybe_print_user_conv_context (convs);
8629 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8631 return error_mark_node;
8634 if (! MAYBE_CLASS_TYPE_P (totype))
8635 return expr;
8637 /* Don't introduce copies when passing arguments along to the inherited
8638 constructor. */
8639 if (current_function_decl
8640 && flag_new_inheriting_ctors
8641 && DECL_INHERITED_CTOR (current_function_decl))
8642 return expr;
8644 if (TREE_CODE (expr) == TARGET_EXPR
8645 && TARGET_EXPR_LIST_INIT_P (expr))
8646 /* Copy-list-initialization doesn't actually involve a copy. */
8647 return expr;
8649 /* Fall through. */
8650 case ck_base:
8651 if (convs->kind == ck_base && !convs->need_temporary_p)
8653 /* We are going to bind a reference directly to a base-class
8654 subobject of EXPR. */
8655 /* Build an expression for `*((base*) &expr)'. */
8656 expr = convert_to_base (expr, totype,
8657 !c_cast_p, /*nonnull=*/true, complain);
8658 return expr;
8661 /* Copy-initialization where the cv-unqualified version of the source
8662 type is the same class as, or a derived class of, the class of the
8663 destination [is treated as direct-initialization]. [dcl.init] */
8664 flags = LOOKUP_NORMAL;
8665 /* This conversion is being done in the context of a user-defined
8666 conversion (i.e. the second step of copy-initialization), so
8667 don't allow any more. */
8668 if (convs->user_conv_p)
8669 flags |= LOOKUP_NO_CONVERSION;
8670 /* We might be performing a conversion of the argument
8671 to the user-defined conversion, i.e., not a conversion of the
8672 result of the user-defined conversion. In which case we skip
8673 explicit constructors. */
8674 if (convs->copy_init_p)
8675 flags |= LOOKUP_ONLYCONVERTING;
8676 expr = build_temp (expr, totype, flags, &diag_kind, complain);
8677 if (diag_kind && complain)
8679 auto_diagnostic_group d;
8680 maybe_print_user_conv_context (convs);
8681 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8684 return build_cplus_new (totype, expr, complain);
8686 case ck_ref_bind:
8688 tree ref_type = totype;
8690 /* direct_reference_binding might have inserted a ck_qual under
8691 this ck_ref_bind for the benefit of conversion sequence ranking.
8692 Ignore the conversion; we'll create our own below. */
8693 if (next_conversion (convs)->kind == ck_qual
8694 && !convs->need_temporary_p)
8696 gcc_assert (same_type_p (TREE_TYPE (expr),
8697 next_conversion (convs)->type));
8698 /* Strip the cast created by the ck_qual; cp_build_addr_expr
8699 below expects an lvalue. */
8700 STRIP_NOPS (expr);
8703 if (convs->bad_p && !next_conversion (convs)->bad_p)
8705 tree extype = TREE_TYPE (expr);
8706 auto_diagnostic_group d;
8707 if (TYPE_REF_IS_RVALUE (ref_type)
8708 && lvalue_p (expr))
8709 error_at (loc, "cannot bind rvalue reference of type %qH to "
8710 "lvalue of type %qI", totype, extype);
8711 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8712 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8714 conversion *next = next_conversion (convs);
8715 if (next->kind == ck_std)
8717 next = next_conversion (next);
8718 error_at (loc, "cannot bind non-const lvalue reference of "
8719 "type %qH to a value of type %qI",
8720 totype, next->type);
8722 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8723 error_at (loc, "cannot bind non-const lvalue reference of "
8724 "type %qH to an rvalue of type %qI", totype, extype);
8725 else // extype is volatile
8726 error_at (loc, "cannot bind lvalue reference of type "
8727 "%qH to an rvalue of type %qI", totype,
8728 extype);
8730 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8732 /* If we're converting from T[] to T[N], don't talk
8733 about discarding qualifiers. (Converting from T[N] to
8734 T[] is allowed by P0388R4.) */
8735 if (TREE_CODE (extype) == ARRAY_TYPE
8736 && TYPE_DOMAIN (extype) == NULL_TREE
8737 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8738 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8739 error_at (loc, "cannot bind reference of type %qH to %qI "
8740 "due to different array bounds", totype, extype);
8741 else
8742 error_at (loc, "binding reference of type %qH to %qI "
8743 "discards qualifiers", totype, extype);
8745 else
8746 gcc_unreachable ();
8747 maybe_print_user_conv_context (convs);
8748 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8750 return error_mark_node;
8752 else if (complain & tf_warning)
8753 maybe_warn_array_conv (loc, convs, expr);
8755 /* If necessary, create a temporary.
8757 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8758 that need temporaries, even when their types are reference
8759 compatible with the type of reference being bound, so the
8760 upcoming call to cp_build_addr_expr doesn't fail. */
8761 if (convs->need_temporary_p
8762 || TREE_CODE (expr) == CONSTRUCTOR
8763 || TREE_CODE (expr) == VA_ARG_EXPR)
8765 /* Otherwise, a temporary of type "cv1 T1" is created and
8766 initialized from the initializer expression using the rules
8767 for a non-reference copy-initialization (8.5). */
8769 tree type = TREE_TYPE (ref_type);
8770 cp_lvalue_kind lvalue = lvalue_kind (expr);
8772 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8773 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8774 && !TYPE_REF_IS_RVALUE (ref_type))
8776 /* If the reference is volatile or non-const, we
8777 cannot create a temporary. */
8778 if (complain & tf_error)
8780 if (lvalue & clk_bitfield)
8781 error_at (loc, "cannot bind bit-field %qE to %qT",
8782 expr, ref_type);
8783 else if (lvalue & clk_packed)
8784 error_at (loc, "cannot bind packed field %qE to %qT",
8785 expr, ref_type);
8786 else
8787 error_at (loc, "cannot bind rvalue %qE to %qT",
8788 expr, ref_type);
8790 return error_mark_node;
8792 /* If the source is a packed field, and we must use a copy
8793 constructor, then building the target expr will require
8794 binding the field to the reference parameter to the
8795 copy constructor, and we'll end up with an infinite
8796 loop. If we can use a bitwise copy, then we'll be
8797 OK. */
8798 if ((lvalue & clk_packed)
8799 && CLASS_TYPE_P (type)
8800 && type_has_nontrivial_copy_init (type))
8802 error_at (loc, "cannot bind packed field %qE to %qT",
8803 expr, ref_type);
8804 return error_mark_node;
8806 if (lvalue & clk_bitfield)
8808 expr = convert_bitfield_to_declared_type (expr);
8809 expr = fold_convert (type, expr);
8812 /* Creating &TARGET_EXPR<> in a template would break when
8813 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8814 instead. This can happen even when there's no class
8815 involved, e.g., when converting an integer to a reference
8816 type. */
8817 if (processing_template_decl)
8818 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8819 expr = build_target_expr_with_type (expr, type, complain);
8822 /* Take the address of the thing to which we will bind the
8823 reference. */
8824 expr = cp_build_addr_expr (expr, complain);
8825 if (expr == error_mark_node)
8826 return error_mark_node;
8828 /* Convert it to a pointer to the type referred to by the
8829 reference. This will adjust the pointer if a derived to
8830 base conversion is being performed. */
8831 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8832 expr, complain);
8833 /* Convert the pointer to the desired reference type. */
8834 return build_nop (ref_type, expr);
8837 case ck_lvalue:
8838 return decay_conversion (expr, complain);
8840 case ck_fnptr:
8841 /* ??? Should the address of a transaction-safe pointer point to the TM
8842 clone, and this conversion look up the primary function? */
8843 return build_nop (totype, expr);
8845 case ck_qual:
8846 /* Warn about deprecated conversion if appropriate. */
8847 if (complain & tf_warning)
8849 string_conv_p (totype, expr, 1);
8850 maybe_warn_array_conv (loc, convs, expr);
8852 break;
8854 case ck_ptr:
8855 if (convs->base_p)
8856 expr = convert_to_base (expr, totype, !c_cast_p,
8857 /*nonnull=*/false, complain);
8858 return build_nop (totype, expr);
8860 case ck_pmem:
8861 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8862 c_cast_p, complain);
8864 default:
8865 break;
8868 if (convs->check_narrowing
8869 && !check_narrowing (totype, expr, complain,
8870 convs->check_narrowing_const_only))
8871 return error_mark_node;
8873 warning_sentinel w (warn_zero_as_null_pointer_constant);
8874 if (issue_conversion_warnings)
8875 expr = cp_convert_and_check (totype, expr, complain);
8876 else
8878 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8879 expr = TREE_OPERAND (expr, 0);
8880 expr = cp_convert (totype, expr, complain);
8883 return expr;
8886 /* Return true if converting FROM to TO is unsafe in a template. */
8888 static bool
8889 conv_unsafe_in_template_p (tree to, tree from)
8891 /* Converting classes involves TARGET_EXPR. */
8892 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8893 return true;
8895 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8896 doesn't handle. */
8897 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8898 return true;
8900 /* Converting integer to real isn't a trivial conversion, either. */
8901 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8902 return true;
8904 return false;
8907 /* Wrapper for convert_like_internal that handles creating
8908 IMPLICIT_CONV_EXPR. */
8910 static tree
8911 convert_like (conversion *convs, tree expr, tree fn, int argnum,
8912 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
8913 tsubst_flags_t complain)
8915 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8916 and creating a CALL_EXPR in a template breaks in finish_call_expr
8917 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
8918 created such codes e.g. when calling a user-defined conversion
8919 function. */
8920 tree conv_expr = NULL_TREE;
8921 if (processing_template_decl
8922 && convs->kind != ck_identity
8923 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
8925 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8926 if (convs->kind != ck_ref_bind)
8927 conv_expr = convert_from_reference (conv_expr);
8928 if (!convs->bad_p)
8929 return conv_expr;
8930 /* Do the normal processing to give the bad_p errors. But we still
8931 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8932 error_mark_node. */
8934 expr = convert_like_internal (convs, expr, fn, argnum,
8935 issue_conversion_warnings, c_cast_p,
8936 nested_p, complain);
8937 if (expr == error_mark_node)
8938 return error_mark_node;
8939 return conv_expr ? conv_expr : expr;
8942 /* Convenience wrapper for convert_like. */
8944 static inline tree
8945 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8947 return convert_like (convs, expr, NULL_TREE, 0,
8948 /*issue_conversion_warnings=*/true,
8949 /*c_cast_p=*/false, /*nested_p=*/false, complain);
8952 /* Convenience wrapper for convert_like. */
8954 static inline tree
8955 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8956 tsubst_flags_t complain)
8958 return convert_like (convs, expr, fn, argnum,
8959 /*issue_conversion_warnings=*/true,
8960 /*c_cast_p=*/false, /*nested_p=*/false, complain);
8963 /* ARG is being passed to a varargs function. Perform any conversions
8964 required. Return the converted value. */
8966 tree
8967 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8969 tree arg_type = TREE_TYPE (arg);
8970 location_t loc = cp_expr_loc_or_input_loc (arg);
8972 /* [expr.call]
8974 If the argument has integral or enumeration type that is subject
8975 to the integral promotions (_conv.prom_), or a floating-point
8976 type that is subject to the floating-point promotion
8977 (_conv.fpprom_), the value of the argument is converted to the
8978 promoted type before the call. */
8979 if (TREE_CODE (arg_type) == REAL_TYPE
8980 && (TYPE_PRECISION (arg_type)
8981 < TYPE_PRECISION (double_type_node))
8982 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
8983 && !extended_float_type_p (arg_type))
8985 if ((complain & tf_warning)
8986 && warn_double_promotion && !c_inhibit_evaluation_warnings)
8987 warning_at (loc, OPT_Wdouble_promotion,
8988 "implicit conversion from %qH to %qI when passing "
8989 "argument to function",
8990 arg_type, double_type_node);
8991 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
8992 arg = TREE_OPERAND (arg, 0);
8993 arg = mark_rvalue_use (arg);
8994 arg = convert_to_real_nofold (double_type_node, arg);
8996 else if (NULLPTR_TYPE_P (arg_type))
8998 arg = mark_rvalue_use (arg);
8999 if (TREE_SIDE_EFFECTS (arg))
9001 warning_sentinel w(warn_unused_result);
9002 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9004 else
9005 arg = null_pointer_node;
9007 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9009 if (SCOPED_ENUM_P (arg_type))
9011 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9012 complain);
9013 prom = cp_perform_integral_promotions (prom, complain);
9014 if (abi_version_crosses (6)
9015 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9016 && (complain & tf_warning))
9017 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9018 " as %qT before %<-fabi-version=6%>, %qT after",
9019 arg_type,
9020 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9021 if (!abi_version_at_least (6))
9022 arg = prom;
9024 else
9025 arg = cp_perform_integral_promotions (arg, complain);
9027 else
9028 /* [expr.call]
9030 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9031 standard conversions are performed. */
9032 arg = decay_conversion (arg, complain);
9034 arg = require_complete_type (arg, complain);
9035 arg_type = TREE_TYPE (arg);
9037 if (arg != error_mark_node
9038 /* In a template (or ill-formed code), we can have an incomplete type
9039 even after require_complete_type, in which case we don't know
9040 whether it has trivial copy or not. */
9041 && COMPLETE_TYPE_P (arg_type)
9042 && !cp_unevaluated_operand)
9044 /* [expr.call] 5.2.2/7:
9045 Passing a potentially-evaluated argument of class type (Clause 9)
9046 with a non-trivial copy constructor or a non-trivial destructor
9047 with no corresponding parameter is conditionally-supported, with
9048 implementation-defined semantics.
9050 We support it as pass-by-invisible-reference, just like a normal
9051 value parameter.
9053 If the call appears in the context of a sizeof expression,
9054 it is not potentially-evaluated. */
9055 if (type_has_nontrivial_copy_init (arg_type)
9056 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9058 arg = force_rvalue (arg, complain);
9059 if (complain & tf_warning)
9060 warning (OPT_Wconditionally_supported,
9061 "passing objects of non-trivially-copyable "
9062 "type %q#T through %<...%> is conditionally supported",
9063 arg_type);
9064 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9066 /* Build up a real lvalue-to-rvalue conversion in case the
9067 copy constructor is trivial but not callable. */
9068 else if (CLASS_TYPE_P (arg_type))
9069 force_rvalue (arg, complain);
9073 return arg;
9076 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9078 tree
9079 build_x_va_arg (location_t loc, tree expr, tree type)
9081 if (processing_template_decl)
9083 tree r = build_min (VA_ARG_EXPR, type, expr);
9084 SET_EXPR_LOCATION (r, loc);
9085 return r;
9088 type = complete_type_or_else (type, NULL_TREE);
9090 if (expr == error_mark_node || !type)
9091 return error_mark_node;
9093 expr = mark_lvalue_use (expr);
9095 if (TYPE_REF_P (type))
9097 error ("cannot receive reference type %qT through %<...%>", type);
9098 return error_mark_node;
9101 if (type_has_nontrivial_copy_init (type)
9102 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9104 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9105 it as pass by invisible reference. */
9106 warning_at (loc, OPT_Wconditionally_supported,
9107 "receiving objects of non-trivially-copyable type %q#T "
9108 "through %<...%> is conditionally-supported", type);
9110 tree ref = cp_build_reference_type (type, false);
9111 expr = build_va_arg (loc, expr, ref);
9112 return convert_from_reference (expr);
9115 tree ret = build_va_arg (loc, expr, type);
9116 if (CLASS_TYPE_P (type))
9117 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9118 know how to handle it. */
9119 ret = get_target_expr (ret);
9120 return ret;
9123 /* TYPE has been given to va_arg. Apply the default conversions which
9124 would have happened when passed via ellipsis. Return the promoted
9125 type, or the passed type if there is no change. */
9127 tree
9128 cxx_type_promotes_to (tree type)
9130 tree promote;
9132 /* Perform the array-to-pointer and function-to-pointer
9133 conversions. */
9134 type = type_decays_to (type);
9136 promote = type_promotes_to (type);
9137 if (same_type_p (type, promote))
9138 promote = type;
9140 return promote;
9143 /* ARG is a default argument expression being passed to a parameter of
9144 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9145 zero-based argument number. Do any required conversions. Return
9146 the converted value. */
9148 static GTY(()) vec<tree, va_gc> *default_arg_context;
9149 void
9150 push_defarg_context (tree fn)
9151 { vec_safe_push (default_arg_context, fn); }
9153 void
9154 pop_defarg_context (void)
9155 { default_arg_context->pop (); }
9157 tree
9158 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9159 tsubst_flags_t complain)
9161 int i;
9162 tree t;
9164 /* See through clones. */
9165 fn = DECL_ORIGIN (fn);
9166 /* And inheriting ctors. */
9167 if (flag_new_inheriting_ctors)
9168 fn = strip_inheriting_ctors (fn);
9170 /* Detect recursion. */
9171 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9172 if (t == fn)
9174 if (complain & tf_error)
9175 error ("recursive evaluation of default argument for %q#D", fn);
9176 return error_mark_node;
9179 /* If the ARG is an unparsed default argument expression, the
9180 conversion cannot be performed. */
9181 if (TREE_CODE (arg) == DEFERRED_PARSE)
9183 if (complain & tf_error)
9184 error ("call to %qD uses the default argument for parameter %P, which "
9185 "is not yet defined", fn, parmnum);
9186 return error_mark_node;
9189 push_defarg_context (fn);
9191 if (fn && DECL_TEMPLATE_INFO (fn))
9192 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9194 /* Due to:
9196 [dcl.fct.default]
9198 The names in the expression are bound, and the semantic
9199 constraints are checked, at the point where the default
9200 expressions appears.
9202 we must not perform access checks here. */
9203 push_deferring_access_checks (dk_no_check);
9204 /* We must make a copy of ARG, in case subsequent processing
9205 alters any part of it. */
9206 arg = break_out_target_exprs (arg, /*clear location*/true);
9208 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9209 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9210 complain);
9211 arg = convert_for_arg_passing (type, arg, complain);
9212 pop_deferring_access_checks();
9214 pop_defarg_context ();
9216 return arg;
9219 /* Returns the type which will really be used for passing an argument of
9220 type TYPE. */
9222 tree
9223 type_passed_as (tree type)
9225 /* Pass classes with copy ctors by invisible reference. */
9226 if (TREE_ADDRESSABLE (type))
9227 type = build_reference_type (type);
9228 else if (targetm.calls.promote_prototypes (NULL_TREE)
9229 && INTEGRAL_TYPE_P (type)
9230 && COMPLETE_TYPE_P (type)
9231 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9232 type = integer_type_node;
9234 return type;
9237 /* Actually perform the appropriate conversion. */
9239 tree
9240 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9242 tree bitfield_type;
9244 /* If VAL is a bitfield, then -- since it has already been converted
9245 to TYPE -- it cannot have a precision greater than TYPE.
9247 If it has a smaller precision, we must widen it here. For
9248 example, passing "int f:3;" to a function expecting an "int" will
9249 not result in any conversion before this point.
9251 If the precision is the same we must not risk widening. For
9252 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9253 often have type "int", even though the C++ type for the field is
9254 "long long". If the value is being passed to a function
9255 expecting an "int", then no conversions will be required. But,
9256 if we call convert_bitfield_to_declared_type, the bitfield will
9257 be converted to "long long". */
9258 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9259 if (bitfield_type
9260 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9261 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
9263 if (val == error_mark_node)
9265 /* Pass classes with copy ctors by invisible reference. */
9266 else if (TREE_ADDRESSABLE (type))
9267 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9268 else if (targetm.calls.promote_prototypes (NULL_TREE)
9269 && INTEGRAL_TYPE_P (type)
9270 && COMPLETE_TYPE_P (type)
9271 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9272 val = cp_perform_integral_promotions (val, complain);
9273 if (complain & tf_warning)
9275 if (warn_suggest_attribute_format)
9277 tree rhstype = TREE_TYPE (val);
9278 const enum tree_code coder = TREE_CODE (rhstype);
9279 const enum tree_code codel = TREE_CODE (type);
9280 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9281 && coder == codel
9282 && check_missing_format_attribute (type, rhstype))
9283 warning (OPT_Wsuggest_attribute_format,
9284 "argument of function call might be a candidate "
9285 "for a format attribute");
9287 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
9290 if (complain & tf_warning)
9291 warn_for_address_or_pointer_of_packed_member (type, val);
9293 return val;
9296 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9297 which just decay_conversion or no conversions at all should be done.
9298 This is true for some builtins which don't act like normal functions.
9299 Return 2 if just decay_conversion and removal of excess precision should
9300 be done, 1 if just decay_conversion. Return 3 for special treatment of
9301 the 3rd argument for __builtin_*_overflow_p. */
9304 magic_varargs_p (tree fn)
9306 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9307 switch (DECL_FUNCTION_CODE (fn))
9309 case BUILT_IN_CLASSIFY_TYPE:
9310 case BUILT_IN_CONSTANT_P:
9311 case BUILT_IN_NEXT_ARG:
9312 case BUILT_IN_VA_START:
9313 return 1;
9315 case BUILT_IN_ADD_OVERFLOW_P:
9316 case BUILT_IN_SUB_OVERFLOW_P:
9317 case BUILT_IN_MUL_OVERFLOW_P:
9318 return 3;
9320 case BUILT_IN_ISFINITE:
9321 case BUILT_IN_ISINF:
9322 case BUILT_IN_ISINF_SIGN:
9323 case BUILT_IN_ISNAN:
9324 case BUILT_IN_ISNORMAL:
9325 case BUILT_IN_FPCLASSIFY:
9326 return 2;
9328 default:
9329 return lookup_attribute ("type generic",
9330 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9333 return 0;
9336 /* Returns the decl of the dispatcher function if FN is a function version. */
9338 tree
9339 get_function_version_dispatcher (tree fn)
9341 tree dispatcher_decl = NULL;
9343 if (DECL_LOCAL_DECL_P (fn))
9344 fn = DECL_LOCAL_DECL_ALIAS (fn);
9346 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9347 && DECL_FUNCTION_VERSIONED (fn));
9349 gcc_assert (targetm.get_function_versions_dispatcher);
9350 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9352 if (dispatcher_decl == NULL)
9354 error_at (input_location, "use of multiversioned function "
9355 "without a default");
9356 return NULL;
9359 retrofit_lang_decl (dispatcher_decl);
9360 gcc_assert (dispatcher_decl != NULL);
9361 return dispatcher_decl;
9364 /* fn is a function version dispatcher that is marked used. Mark all the
9365 semantically identical function versions it will dispatch as used. */
9367 void
9368 mark_versions_used (tree fn)
9370 struct cgraph_node *node;
9371 struct cgraph_function_version_info *node_v;
9372 struct cgraph_function_version_info *it_v;
9374 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9376 node = cgraph_node::get (fn);
9377 if (node == NULL)
9378 return;
9380 gcc_assert (node->dispatcher_function);
9382 node_v = node->function_version ();
9383 if (node_v == NULL)
9384 return;
9386 /* All semantically identical versions are chained. Traverse and mark each
9387 one of them as used. */
9388 it_v = node_v->next;
9389 while (it_v != NULL)
9391 mark_used (it_v->this_node->decl);
9392 it_v = it_v->next;
9396 /* Build a call to "the copy constructor" for the type of A, even if it
9397 wouldn't be selected by normal overload resolution. Used for
9398 diagnostics. */
9400 static tree
9401 call_copy_ctor (tree a, tsubst_flags_t complain)
9403 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9404 tree binfo = TYPE_BINFO (ctype);
9405 tree copy = get_copy_ctor (ctype, complain);
9406 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9407 tree ob = build_dummy_object (ctype);
9408 releasing_vec args (make_tree_vector_single (a));
9409 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9410 LOOKUP_NORMAL, NULL, complain);
9411 return r;
9414 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9416 static tree
9417 base_ctor_for (tree complete_ctor)
9419 tree clone;
9420 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9421 if (DECL_BASE_CONSTRUCTOR_P (clone))
9422 return clone;
9423 return NULL_TREE;
9426 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9427 and return whether we were successful. EXP must have already been cleared
9428 by unsafe_copy_elision_p{,_opt}. */
9430 static bool
9431 make_base_init_ok (tree exp)
9433 if (TREE_CODE (exp) == TARGET_EXPR)
9434 exp = TARGET_EXPR_INITIAL (exp);
9435 while (TREE_CODE (exp) == COMPOUND_EXPR)
9436 exp = TREE_OPERAND (exp, 1);
9437 if (TREE_CODE (exp) == COND_EXPR)
9439 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9440 if (tree op1 = TREE_OPERAND (exp, 1))
9442 bool r1 = make_base_init_ok (op1);
9443 /* If unsafe_copy_elision_p was false, the arms should match. */
9444 gcc_assert (r1 == ret);
9446 return ret;
9448 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9449 /* A trivial copy is OK. */
9450 return true;
9451 if (!AGGR_INIT_VIA_CTOR_P (exp))
9452 /* unsafe_copy_elision_p_opt must have said this is OK. */
9453 return true;
9454 tree fn = cp_get_callee_fndecl_nofold (exp);
9455 if (DECL_BASE_CONSTRUCTOR_P (fn))
9456 return true;
9457 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9458 fn = base_ctor_for (fn);
9459 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9460 /* The base constructor has more parameters, so we can't just change the
9461 call target. It would be possible to splice in the appropriate
9462 arguments, but probably not worth the complexity. */
9463 return false;
9464 mark_used (fn);
9465 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9466 return true;
9469 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9470 neither of which can be used for return by invisible reference. We avoid
9471 doing C++17 mandatory copy elision for either of these cases.
9473 This returns non-zero even if the type of T has no tail padding that other
9474 data could be allocated into, because that depends on the particular ABI.
9475 unsafe_copy_elision_p_opt does consider whether there is padding. */
9478 unsafe_return_slot_p (tree t)
9480 /* Check empty bases separately, they don't have fields. */
9481 if (is_empty_base_ref (t))
9482 return 2;
9484 /* A delegating constructor might be used to initialize a base. */
9485 if (current_function_decl
9486 && DECL_CONSTRUCTOR_P (current_function_decl)
9487 && (t == current_class_ref
9488 || tree_strip_nop_conversions (t) == current_class_ptr))
9489 return 2;
9491 STRIP_NOPS (t);
9492 if (TREE_CODE (t) == ADDR_EXPR)
9493 t = TREE_OPERAND (t, 0);
9494 if (TREE_CODE (t) == COMPONENT_REF)
9495 t = TREE_OPERAND (t, 1);
9496 if (TREE_CODE (t) != FIELD_DECL)
9497 return false;
9498 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9499 /* The middle-end will do the right thing for scalar types. */
9500 return false;
9501 if (DECL_FIELD_IS_BASE (t))
9502 return 2;
9503 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9504 return 1;
9505 return 0;
9508 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9510 static bool
9511 init_by_return_slot_p (tree exp)
9513 /* Copy elision only happens with a TARGET_EXPR. */
9514 if (TREE_CODE (exp) != TARGET_EXPR)
9515 return false;
9516 tree init = TARGET_EXPR_INITIAL (exp);
9517 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9518 while (TREE_CODE (init) == COMPOUND_EXPR)
9519 init = TREE_OPERAND (init, 1);
9520 if (TREE_CODE (init) == COND_EXPR)
9522 /* We'll end up copying from each of the arms of the COND_EXPR directly
9523 into the target, so look at them. */
9524 if (tree op = TREE_OPERAND (init, 1))
9525 if (init_by_return_slot_p (op))
9526 return true;
9527 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9529 return (TREE_CODE (init) == AGGR_INIT_EXPR
9530 && !AGGR_INIT_VIA_CTOR_P (init));
9533 /* We can't elide a copy from a function returning by value to a
9534 potentially-overlapping subobject, as the callee might clobber tail padding.
9535 Return true iff this could be that case.
9537 Places that use this function (or _opt) to decide to elide a copy should
9538 probably use make_safe_copy_elision instead. */
9540 bool
9541 unsafe_copy_elision_p (tree target, tree exp)
9543 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9546 /* As above, but for optimization allow more cases that are actually safe. */
9548 static bool
9549 unsafe_copy_elision_p_opt (tree target, tree exp)
9551 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9552 /* It's safe to elide the copy for a class with no tail padding. */
9553 if (!is_empty_class (type)
9554 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9555 return false;
9556 return unsafe_copy_elision_p (target, exp);
9559 /* Try to make EXP suitable to be used as the initializer for TARGET,
9560 and return whether we were successful. */
9562 bool
9563 make_safe_copy_elision (tree target, tree exp)
9565 int uns = unsafe_return_slot_p (target);
9566 if (!uns)
9567 return true;
9568 if (init_by_return_slot_p (exp))
9569 return false;
9570 if (uns == 1)
9571 return true;
9572 return make_base_init_ok (exp);
9575 /* True IFF the result of the conversion C is a prvalue. */
9577 static bool
9578 conv_is_prvalue (conversion *c)
9580 if (c->kind == ck_rvalue)
9581 return true;
9582 if (c->kind == ck_base && c->need_temporary_p)
9583 return true;
9584 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9585 return true;
9586 if (c->kind == ck_identity && c->u.expr
9587 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9588 return true;
9590 return false;
9593 /* True iff C is a conversion that binds a reference to a prvalue. */
9595 static bool
9596 conv_binds_ref_to_prvalue (conversion *c)
9598 if (c->kind != ck_ref_bind)
9599 return false;
9600 if (c->need_temporary_p)
9601 return true;
9603 return conv_is_prvalue (next_conversion (c));
9606 /* True iff EXPR represents a (subobject of a) temporary. */
9608 static bool
9609 expr_represents_temporary_p (tree expr)
9611 while (handled_component_p (expr))
9612 expr = TREE_OPERAND (expr, 0);
9613 return TREE_CODE (expr) == TARGET_EXPR;
9616 /* True iff C is a conversion that binds a reference to a temporary.
9617 This is a superset of conv_binds_ref_to_prvalue: here we're also
9618 interested in xvalues. */
9620 static bool
9621 conv_binds_ref_to_temporary (conversion *c)
9623 if (conv_binds_ref_to_prvalue (c))
9624 return true;
9625 if (c->kind != ck_ref_bind)
9626 return false;
9627 c = next_conversion (c);
9628 /* This is the case for
9629 struct Base {};
9630 struct Derived : Base {};
9631 const Base& b(Derived{});
9632 where we bind 'b' to the Base subobject of a temporary object of type
9633 Derived. The subobject is an xvalue; the whole object is a prvalue.
9635 The ck_base doesn't have to be present for cases like X{}.m. */
9636 if (c->kind == ck_base)
9637 c = next_conversion (c);
9638 if (c->kind == ck_identity && c->u.expr
9639 && expr_represents_temporary_p (c->u.expr))
9640 return true;
9641 return false;
9644 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9645 the reference to a temporary. Return tristate::TS_FALSE if converting
9646 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9647 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9648 says whether the conversion should be done in direct- or copy-initialization
9649 context. */
9651 tristate
9652 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9654 gcc_assert (TYPE_REF_P (type));
9656 /* Get the high-water mark for the CONVERSION_OBSTACK. */
9657 void *p = conversion_obstack_alloc (0);
9659 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9660 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9661 /*c_cast_p=*/false, flags, tf_none);
9662 tristate ret (tristate::TS_UNKNOWN);
9663 if (conv && !conv->bad_p)
9664 ret = tristate (conv_binds_ref_to_temporary (conv));
9666 /* Free all the conversions we allocated. */
9667 obstack_free (&conversion_obstack, p);
9669 return ret;
9672 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9673 class type or a pointer to class type. If NO_PTR_DEREF is true and
9674 INSTANCE has pointer type, clobber the pointer rather than what it points
9675 to. */
9677 tree
9678 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9680 gcc_assert (!is_dummy_object (instance));
9682 if (!flag_lifetime_dse)
9684 no_clobber:
9685 return fold_convert (void_type_node, instance);
9688 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9689 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9691 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9692 goto no_clobber;
9693 instance = cp_build_fold_indirect_ref (instance);
9696 /* A trivial destructor should still clobber the object. */
9697 tree clobber = build_clobber (TREE_TYPE (instance));
9698 return build2 (MODIFY_EXPR, void_type_node,
9699 instance, clobber);
9702 /* Return true if in an immediate function context, or an unevaluated operand,
9703 or a default argument/member initializer, or a subexpression of an immediate
9704 invocation. */
9706 bool
9707 in_immediate_context ()
9709 return (cp_unevaluated_operand != 0
9710 || (current_function_decl != NULL_TREE
9711 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9712 /* DR 2631: default args and DMI aren't immediately evaluated.
9713 Return true here so immediate_invocation_p returns false. */
9714 || current_binding_level->kind == sk_function_parms
9715 || current_binding_level->kind == sk_template_parms
9716 || parsing_nsdmi ()
9717 || in_consteval_if_p);
9720 /* Return true if a call to FN with number of arguments NARGS
9721 is an immediate invocation. */
9723 static bool
9724 immediate_invocation_p (tree fn)
9726 return (TREE_CODE (fn) == FUNCTION_DECL
9727 && DECL_IMMEDIATE_FUNCTION_P (fn)
9728 && !in_immediate_context ());
9731 /* Subroutine of the various build_*_call functions. Overload resolution
9732 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9733 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9734 bitmask of various LOOKUP_* flags which apply to the call itself. */
9736 static tree
9737 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9739 tree fn = cand->fn;
9740 const vec<tree, va_gc> *args = cand->args;
9741 tree first_arg = cand->first_arg;
9742 conversion **convs = cand->convs;
9743 conversion *conv;
9744 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9745 int parmlen;
9746 tree val;
9747 int i = 0;
9748 int j = 0;
9749 unsigned int arg_index = 0;
9750 int is_method = 0;
9751 int nargs;
9752 tree *argarray;
9753 bool already_used = false;
9755 /* In a template, there is no need to perform all of the work that
9756 is normally done. We are only interested in the type of the call
9757 expression, i.e., the return type of the function. Any semantic
9758 errors will be deferred until the template is instantiated. */
9759 if (processing_template_decl)
9761 if (undeduced_auto_decl (fn))
9762 mark_used (fn, complain);
9763 else
9764 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9765 See PR80598. */
9766 TREE_USED (fn) = 1;
9768 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9769 tree callee;
9770 if (first_arg == NULL_TREE)
9772 callee = build_addr_func (fn, complain);
9773 if (callee == error_mark_node)
9774 return error_mark_node;
9776 else
9778 callee = build_baselink (cand->conversion_path, cand->access_path,
9779 fn, NULL_TREE);
9780 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9781 first_arg, callee, NULL_TREE);
9784 tree expr = build_call_vec (return_type, callee, args);
9785 SET_EXPR_LOCATION (expr, input_location);
9786 if (TREE_THIS_VOLATILE (fn) && cfun)
9787 current_function_returns_abnormally = 1;
9788 if (immediate_invocation_p (fn))
9790 tree obj_arg = NULL_TREE, exprimm = expr;
9791 if (DECL_CONSTRUCTOR_P (fn))
9792 obj_arg = first_arg;
9793 if (obj_arg
9794 && is_dummy_object (obj_arg)
9795 && !type_dependent_expression_p (obj_arg))
9797 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9798 obj_arg = NULL_TREE;
9800 /* Look through *(const T *)&obj. */
9801 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9803 tree addr = TREE_OPERAND (obj_arg, 0);
9804 STRIP_NOPS (addr);
9805 if (TREE_CODE (addr) == ADDR_EXPR)
9807 tree typeo = TREE_TYPE (obj_arg);
9808 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9809 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9810 obj_arg = TREE_OPERAND (addr, 0);
9813 fold_non_dependent_expr (exprimm, complain,
9814 /*manifestly_const_eval=*/true,
9815 obj_arg);
9817 return convert_from_reference (expr);
9820 /* Give any warnings we noticed during overload resolution. */
9821 if (cand->warnings && (complain & tf_warning))
9823 struct candidate_warning *w;
9824 for (w = cand->warnings; w; w = w->next)
9825 joust (cand, w->loser, 1, complain);
9828 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9829 argument to the copy constructor ends up being a prvalue after
9830 conversion. Let's do the normal processing, but pretend we aren't
9831 actually using the copy constructor. */
9832 bool force_elide = false;
9833 if (cxx_dialect >= cxx17
9834 && cand->num_convs == 1
9835 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9836 && (DECL_COPY_CONSTRUCTOR_P (fn)
9837 || DECL_MOVE_CONSTRUCTOR_P (fn))
9838 && !unsafe_return_slot_p (first_arg)
9839 && conv_binds_ref_to_prvalue (convs[0]))
9841 force_elide = true;
9842 goto not_really_used;
9845 /* OK, we're actually calling this inherited constructor; set its deletedness
9846 appropriately. We can get away with doing this here because calling is
9847 the only way to refer to a constructor. */
9848 if (DECL_INHERITED_CTOR (fn)
9849 && !deduce_inheriting_ctor (fn))
9851 if (complain & tf_error)
9852 mark_used (fn);
9853 return error_mark_node;
9856 /* Make =delete work with SFINAE. */
9857 if (DECL_DELETED_FN (fn))
9859 if (complain & tf_error)
9860 mark_used (fn);
9861 return error_mark_node;
9864 if (DECL_FUNCTION_MEMBER_P (fn))
9866 tree access_fn;
9867 /* If FN is a template function, two cases must be considered.
9868 For example:
9870 struct A {
9871 protected:
9872 template <class T> void f();
9874 template <class T> struct B {
9875 protected:
9876 void g();
9878 struct C : A, B<int> {
9879 using A::f; // #1
9880 using B<int>::g; // #2
9883 In case #1 where `A::f' is a member template, DECL_ACCESS is
9884 recorded in the primary template but not in its specialization.
9885 We check access of FN using its primary template.
9887 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9888 because it is a member of class template B, DECL_ACCESS is
9889 recorded in the specialization `B<int>::g'. We cannot use its
9890 primary template because `B<T>::g' and `B<int>::g' may have
9891 different access. */
9892 if (DECL_TEMPLATE_INFO (fn)
9893 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9894 access_fn = DECL_TI_TEMPLATE (fn);
9895 else
9896 access_fn = fn;
9897 if (!perform_or_defer_access_check (cand->access_path, access_fn,
9898 fn, complain))
9899 return error_mark_node;
9902 /* If we're checking for implicit delete, don't bother with argument
9903 conversions. */
9904 if (flags & LOOKUP_SPECULATIVE)
9906 if (cand->viable == 1)
9907 return fn;
9908 else if (!(complain & tf_error))
9909 /* Reject bad conversions now. */
9910 return error_mark_node;
9911 /* else continue to get conversion error. */
9914 not_really_used:
9916 /* N3276 magic doesn't apply to nested calls. */
9917 tsubst_flags_t decltype_flag = (complain & tf_decltype);
9918 complain &= ~tf_decltype;
9919 /* No-Cleanup doesn't apply to nested calls either. */
9920 tsubst_flags_t no_cleanup_complain = complain;
9921 complain &= ~tf_no_cleanup;
9923 /* Find maximum size of vector to hold converted arguments. */
9924 parmlen = list_length (parm);
9925 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
9926 if (parmlen > nargs)
9927 nargs = parmlen;
9928 argarray = XALLOCAVEC (tree, nargs);
9930 in_consteval_if_p_temp_override icip;
9931 /* If the call is immediate function invocation, make sure
9932 taking address of immediate functions is allowed in its arguments. */
9933 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
9934 in_consteval_if_p = true;
9936 /* The implicit parameters to a constructor are not considered by overload
9937 resolution, and must be of the proper type. */
9938 if (DECL_CONSTRUCTOR_P (fn))
9940 tree object_arg;
9941 if (first_arg != NULL_TREE)
9943 object_arg = first_arg;
9944 first_arg = NULL_TREE;
9946 else
9948 object_arg = (*args)[arg_index];
9949 ++arg_index;
9951 argarray[j++] = build_this (object_arg);
9952 parm = TREE_CHAIN (parm);
9953 /* We should never try to call the abstract constructor. */
9954 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9956 if (DECL_HAS_VTT_PARM_P (fn))
9958 argarray[j++] = (*args)[arg_index];
9959 ++arg_index;
9960 parm = TREE_CHAIN (parm);
9963 /* Bypass access control for 'this' parameter. */
9964 else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9966 tree arg = build_this (first_arg != NULL_TREE
9967 ? first_arg
9968 : (*args)[arg_index]);
9969 tree argtype = TREE_TYPE (arg);
9971 if (arg == error_mark_node)
9972 return error_mark_node;
9974 if (convs[i]->bad_p)
9976 if (complain & tf_error)
9978 auto_diagnostic_group d;
9979 if (permerror (input_location, "passing %qT as %<this%> "
9980 "argument discards qualifiers",
9981 TREE_TYPE (argtype)))
9982 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
9984 else
9985 return error_mark_node;
9988 /* The class where FN is defined. */
9989 tree ctx = DECL_CONTEXT (fn);
9991 /* See if the function member or the whole class type is declared
9992 final and the call can be devirtualized. */
9993 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9994 flags |= LOOKUP_NONVIRTUAL;
9996 /* [class.mfct.non-static]: If a non-static member function of a class
9997 X is called for an object that is not of type X, or of a type
9998 derived from X, the behavior is undefined.
10000 So we can assume that anything passed as 'this' is non-null, and
10001 optimize accordingly. */
10002 /* Check that the base class is accessible. */
10003 if (!accessible_base_p (TREE_TYPE (argtype),
10004 BINFO_TYPE (cand->conversion_path), true))
10006 if (complain & tf_error)
10007 error ("%qT is not an accessible base of %qT",
10008 BINFO_TYPE (cand->conversion_path),
10009 TREE_TYPE (argtype));
10010 else
10011 return error_mark_node;
10013 /* If fn was found by a using declaration, the conversion path
10014 will be to the derived class, not the base declaring fn. We
10015 must convert to the base. */
10016 tree base_binfo = cand->conversion_path;
10017 if (BINFO_TYPE (base_binfo) != ctx)
10019 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10020 if (base_binfo == error_mark_node)
10021 return error_mark_node;
10024 /* If we know the dynamic type of the object, look up the final overrider
10025 in the BINFO. */
10026 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10027 && resolves_to_fixed_type_p (arg))
10029 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10031 /* And unwind base_binfo to match. If we don't find the type we're
10032 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10033 inheritance; for now do a normal virtual call in that case. */
10034 tree octx = DECL_CONTEXT (ov);
10035 tree obinfo = base_binfo;
10036 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10037 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10038 if (obinfo)
10040 fn = ov;
10041 base_binfo = obinfo;
10042 flags |= LOOKUP_NONVIRTUAL;
10046 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10047 base_binfo, 1, complain);
10049 argarray[j++] = converted_arg;
10050 parm = TREE_CHAIN (parm);
10051 if (first_arg != NULL_TREE)
10052 first_arg = NULL_TREE;
10053 else
10054 ++arg_index;
10055 ++i;
10056 is_method = 1;
10059 gcc_assert (first_arg == NULL_TREE);
10060 for (; arg_index < vec_safe_length (args) && parm;
10061 parm = TREE_CHAIN (parm), ++arg_index, ++i)
10063 tree type = TREE_VALUE (parm);
10064 tree arg = (*args)[arg_index];
10065 bool conversion_warning = true;
10067 conv = convs[i];
10069 /* If the argument is NULL and used to (implicitly) instantiate a
10070 template function (and bind one of the template arguments to
10071 the type of 'long int'), we don't want to warn about passing NULL
10072 to non-pointer argument.
10073 For example, if we have this template function:
10075 template<typename T> void func(T x) {}
10077 we want to warn (when -Wconversion is enabled) in this case:
10079 void foo() {
10080 func<int>(NULL);
10083 but not in this case:
10085 void foo() {
10086 func(NULL);
10089 if (null_node_p (arg)
10090 && DECL_TEMPLATE_INFO (fn)
10091 && cand->template_decl
10092 && !cand->explicit_targs)
10093 conversion_warning = false;
10095 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10096 knows not to allow any more UDCs. This needs to happen after we
10097 process cand->warnings. */
10098 if (flags & LOOKUP_NO_CONVERSION)
10099 conv->user_conv_p = true;
10101 tsubst_flags_t arg_complain = complain;
10102 if (!conversion_warning)
10103 arg_complain &= ~tf_warning;
10105 if (arg_complain & tf_warning)
10106 maybe_warn_pessimizing_move (arg, type, /*return_p*/false);
10108 val = convert_like_with_context (conv, arg, fn, i - is_method,
10109 arg_complain);
10110 val = convert_for_arg_passing (type, val, arg_complain);
10112 if (val == error_mark_node)
10113 return error_mark_node;
10114 else
10115 argarray[j++] = val;
10118 /* Default arguments */
10119 for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
10121 if (TREE_VALUE (parm) == error_mark_node)
10122 return error_mark_node;
10123 val = convert_default_arg (TREE_VALUE (parm),
10124 TREE_PURPOSE (parm),
10125 fn, i - is_method,
10126 complain);
10127 if (val == error_mark_node)
10128 return error_mark_node;
10129 argarray[j++] = val;
10132 /* Ellipsis */
10133 int magic = magic_varargs_p (fn);
10134 for (; arg_index < vec_safe_length (args); ++arg_index)
10136 tree a = (*args)[arg_index];
10137 if (magic == 3 && arg_index == 2)
10139 /* Do no conversions for certain magic varargs. */
10140 a = mark_type_use (a);
10141 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10142 return error_mark_node;
10144 else if (magic != 0)
10146 /* Don't truncate excess precision to the semantic type. */
10147 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10148 a = TREE_OPERAND (a, 0);
10149 /* For other magic varargs only do decay_conversion. */
10150 a = decay_conversion (a, complain);
10152 else if (DECL_CONSTRUCTOR_P (fn)
10153 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10154 TREE_TYPE (a)))
10156 /* Avoid infinite recursion trying to call A(...). */
10157 if (complain & tf_error)
10158 /* Try to call the actual copy constructor for a good error. */
10159 call_copy_ctor (a, complain);
10160 return error_mark_node;
10162 else
10163 a = convert_arg_to_ellipsis (a, complain);
10164 if (a == error_mark_node)
10165 return error_mark_node;
10166 argarray[j++] = a;
10169 gcc_assert (j <= nargs);
10170 nargs = j;
10171 icip.reset ();
10173 /* Avoid performing argument transformation if warnings are disabled.
10174 When tf_warning is set and at least one of the warnings is active
10175 the check_function_arguments function might warn about something. */
10177 bool warned_p = false;
10178 if ((complain & tf_warning)
10179 && (warn_nonnull
10180 || warn_format
10181 || warn_suggest_attribute_format
10182 || warn_restrict))
10184 tree *fargs = (!nargs ? argarray
10185 : (tree *) alloca (nargs * sizeof (tree)));
10186 for (j = 0; j < nargs; j++)
10188 /* For -Wformat undo the implicit passing by hidden reference
10189 done by convert_arg_to_ellipsis. */
10190 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10191 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10192 fargs[j] = TREE_OPERAND (argarray[j], 0);
10193 else
10194 fargs[j] = argarray[j];
10197 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
10198 nargs, fargs, NULL);
10201 if (DECL_INHERITED_CTOR (fn))
10203 /* Check for passing ellipsis arguments to an inherited constructor. We
10204 could handle this by open-coding the inherited constructor rather than
10205 defining it, but let's not bother now. */
10206 if (!cp_unevaluated_operand
10207 && cand->num_convs
10208 && cand->convs[cand->num_convs-1]->ellipsis_p)
10210 if (complain & tf_error)
10212 sorry ("passing arguments to ellipsis of inherited constructor "
10213 "%qD", cand->fn);
10214 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10216 return error_mark_node;
10219 /* A base constructor inheriting from a virtual base doesn't get the
10220 inherited arguments, just this and __vtt. */
10221 if (ctor_omit_inherited_parms (fn))
10222 nargs = 2;
10225 /* Avoid actually calling copy constructors and copy assignment operators,
10226 if possible. */
10228 if (! flag_elide_constructors && !force_elide)
10229 /* Do things the hard way. */;
10230 else if (cand->num_convs == 1
10231 && (DECL_COPY_CONSTRUCTOR_P (fn)
10232 || DECL_MOVE_CONSTRUCTOR_P (fn))
10233 /* It's unsafe to elide the constructor when handling
10234 a noexcept-expression, it may evaluate to the wrong
10235 value (c++/53025). */
10236 && (force_elide || cp_noexcept_operand == 0))
10238 tree targ;
10239 tree arg = argarray[num_artificial_parms_for (fn)];
10240 tree fa = argarray[0];
10241 bool trivial = trivial_fn_p (fn);
10243 /* Pull out the real argument, disregarding const-correctness. */
10244 targ = arg;
10245 /* Strip the reference binding for the constructor parameter. */
10246 if (CONVERT_EXPR_P (targ)
10247 && TYPE_REF_P (TREE_TYPE (targ)))
10248 targ = TREE_OPERAND (targ, 0);
10249 /* But don't strip any other reference bindings; binding a temporary to a
10250 reference prevents copy elision. */
10251 while ((CONVERT_EXPR_P (targ)
10252 && !TYPE_REF_P (TREE_TYPE (targ)))
10253 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10254 targ = TREE_OPERAND (targ, 0);
10255 if (TREE_CODE (targ) == ADDR_EXPR)
10257 targ = TREE_OPERAND (targ, 0);
10258 if (!same_type_ignoring_top_level_qualifiers_p
10259 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10260 targ = NULL_TREE;
10262 else
10263 targ = NULL_TREE;
10265 if (targ)
10266 arg = targ;
10267 else
10268 arg = cp_build_fold_indirect_ref (arg);
10270 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10271 potentially-overlapping subobject. */
10272 if (CHECKING_P && cxx_dialect >= cxx17)
10273 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10274 || force_elide
10275 /* It's from binding the ref parm to a packed field. */
10276 || convs[0]->need_temporary_p
10277 || seen_error ()
10278 /* See unsafe_copy_elision_p. */
10279 || unsafe_return_slot_p (fa));
10281 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
10282 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10284 /* [class.copy]: the copy constructor is implicitly defined even if the
10285 implementation elided its use. But don't warn about deprecation when
10286 eliding a temporary, as then no copy is actually performed. */
10287 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10288 if (force_elide)
10289 /* The language says this isn't called. */;
10290 else if (!trivial)
10292 if (!mark_used (fn, complain) && !(complain & tf_error))
10293 return error_mark_node;
10294 already_used = true;
10296 else
10297 cp_handle_deprecated_or_unavailable (fn, complain);
10299 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10300 && !make_base_init_ok (arg))
10301 unsafe = true;
10303 /* If we're creating a temp and we already have one, don't create a
10304 new one. If we're not creating a temp but we get one, use
10305 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10306 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10307 temp or an INIT_EXPR otherwise. */
10308 if (is_dummy_object (fa))
10310 if (TREE_CODE (arg) == TARGET_EXPR)
10311 return arg;
10312 else if (trivial)
10313 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10315 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10316 && !unsafe)
10318 tree to = cp_build_fold_indirect_ref (fa);
10319 val = cp_build_init_expr (to, arg);
10320 return val;
10323 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10324 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10325 && trivial_fn_p (fn))
10327 /* Don't use cp_build_fold_indirect_ref, op= returns an lvalue even if
10328 the object argument isn't one. */
10329 tree to = cp_build_indirect_ref (input_location, argarray[0],
10330 RO_ARROW, complain);
10331 tree type = TREE_TYPE (to);
10332 tree as_base = CLASSTYPE_AS_BASE (type);
10333 tree arg = argarray[1];
10334 location_t loc = cp_expr_loc_or_input_loc (arg);
10336 if (is_really_empty_class (type, /*ignore_vptr*/true))
10338 /* Avoid copying empty classes. */
10339 val = build2 (COMPOUND_EXPR, type, arg, to);
10340 suppress_warning (val, OPT_Wunused);
10342 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10344 if (is_std_init_list (type)
10345 && conv_binds_ref_to_prvalue (convs[1]))
10346 warning_at (loc, OPT_Winit_list_lifetime,
10347 "assignment from temporary %<initializer_list%> does "
10348 "not extend the lifetime of the underlying array");
10349 arg = cp_build_fold_indirect_ref (arg);
10350 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10352 else
10354 /* We must only copy the non-tail padding parts. */
10355 tree arg0, arg2, t;
10356 tree array_type, alias_set;
10358 arg2 = TYPE_SIZE_UNIT (as_base);
10359 to = cp_stabilize_reference (to);
10360 arg0 = cp_build_addr_expr (to, complain);
10362 array_type = build_array_type (unsigned_char_type_node,
10363 build_index_type
10364 (size_binop (MINUS_EXPR,
10365 arg2, size_int (1))));
10366 alias_set = build_int_cst (build_pointer_type (type), 0);
10367 t = build2 (MODIFY_EXPR, void_type_node,
10368 build2 (MEM_REF, array_type, arg0, alias_set),
10369 build2 (MEM_REF, array_type, arg, alias_set));
10370 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10371 suppress_warning (val, OPT_Wunused);
10374 cp_handle_deprecated_or_unavailable (fn, complain);
10376 return val;
10378 else if (trivial_fn_p (fn))
10380 if (DECL_DESTRUCTOR_P (fn))
10381 return build_trivial_dtor_call (argarray[0]);
10382 else if (default_ctor_p (fn))
10384 if (is_dummy_object (argarray[0]))
10385 return force_target_expr (DECL_CONTEXT (fn), void_node,
10386 no_cleanup_complain);
10387 else
10388 return cp_build_fold_indirect_ref (argarray[0]);
10392 gcc_assert (!force_elide);
10394 if (!already_used
10395 && !mark_used (fn, complain))
10396 return error_mark_node;
10398 /* Warn if the built-in writes to an object of a non-trivial type. */
10399 if (warn_class_memaccess
10400 && vec_safe_length (args) >= 2
10401 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10402 maybe_warn_class_memaccess (input_location, fn, args);
10404 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10406 tree t;
10407 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10408 DECL_CONTEXT (fn),
10409 ba_any, NULL, complain);
10410 gcc_assert (binfo && binfo != error_mark_node);
10412 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10413 complain);
10414 if (TREE_SIDE_EFFECTS (argarray[0]))
10415 argarray[0] = save_expr (argarray[0]);
10416 t = build_pointer_type (TREE_TYPE (fn));
10417 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10418 TREE_TYPE (fn) = t;
10420 else
10422 /* If FN is marked deprecated or unavailable, then we've already
10423 issued a diagnostic from mark_used above, so avoid redundantly
10424 issuing another one from build_addr_func. */
10425 auto w = make_temp_override (deprecated_state,
10426 UNAVAILABLE_DEPRECATED_SUPPRESS);
10428 fn = build_addr_func (fn, complain);
10429 if (fn == error_mark_node)
10430 return error_mark_node;
10433 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10434 if (call == error_mark_node)
10435 return call;
10436 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10438 tree c = extract_call_expr (call);
10439 /* build_new_op will clear this when appropriate. */
10440 CALL_EXPR_ORDERED_ARGS (c) = true;
10442 if (warned_p)
10444 tree c = extract_call_expr (call);
10445 if (TREE_CODE (c) == CALL_EXPR)
10446 suppress_warning (c /* Suppress all warnings. */);
10448 if (TREE_CODE (fn) == ADDR_EXPR)
10450 tree fndecl = STRIP_TEMPLATE (TREE_OPERAND (fn, 0));
10451 if (immediate_invocation_p (fndecl))
10453 tree obj_arg = NULL_TREE;
10454 /* Undo convert_from_reference called by build_cxx_call. */
10455 if (REFERENCE_REF_P (call))
10456 call = TREE_OPERAND (call, 0);
10457 if (DECL_CONSTRUCTOR_P (fndecl))
10458 obj_arg = cand->first_arg ? cand->first_arg : (*args)[0];
10459 if (obj_arg && is_dummy_object (obj_arg))
10461 call = build_cplus_new (DECL_CONTEXT (fndecl), call, complain);
10462 obj_arg = NULL_TREE;
10464 /* Look through *(const T *)&obj. */
10465 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
10467 tree addr = TREE_OPERAND (obj_arg, 0);
10468 STRIP_NOPS (addr);
10469 if (TREE_CODE (addr) == ADDR_EXPR)
10471 tree typeo = TREE_TYPE (obj_arg);
10472 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
10473 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
10474 obj_arg = TREE_OPERAND (addr, 0);
10477 call = cxx_constant_value (call, obj_arg, complain);
10478 if (obj_arg && !error_operand_p (call))
10479 call = cp_build_init_expr (obj_arg, call);
10480 call = convert_from_reference (call);
10483 return call;
10486 namespace
10489 /* Return the DECL of the first non-static subobject of class TYPE
10490 that satisfies the predicate PRED or null if none can be found. */
10492 template <class Predicate>
10493 tree
10494 first_non_static_field (tree type, Predicate pred)
10496 if (!type || !CLASS_TYPE_P (type))
10497 return NULL_TREE;
10499 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10501 if (TREE_CODE (field) != FIELD_DECL)
10502 continue;
10503 if (TREE_STATIC (field))
10504 continue;
10505 if (pred (field))
10506 return field;
10509 int i = 0;
10511 for (tree base_binfo, binfo = TYPE_BINFO (type);
10512 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10514 tree base = TREE_TYPE (base_binfo);
10515 if (pred (base))
10516 return base;
10517 if (tree field = first_non_static_field (base, pred))
10518 return field;
10521 return NULL_TREE;
10524 struct NonPublicField
10526 bool operator() (const_tree t) const
10528 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10532 /* Return the DECL of the first non-public subobject of class TYPE
10533 or null if none can be found. */
10535 static inline tree
10536 first_non_public_field (tree type)
10538 return first_non_static_field (type, NonPublicField ());
10541 struct NonTrivialField
10543 bool operator() (const_tree t) const
10545 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10549 /* Return the DECL of the first non-trivial subobject of class TYPE
10550 or null if none can be found. */
10552 static inline tree
10553 first_non_trivial_field (tree type)
10555 return first_non_static_field (type, NonTrivialField ());
10558 } /* unnamed namespace */
10560 /* Return true if all copy and move assignment operator overloads for
10561 class TYPE are trivial and at least one of them is not deleted and,
10562 when ACCESS is set, accessible. Return false otherwise. Set
10563 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10564 copy or move assignment. */
10566 static bool
10567 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10569 tree fns = get_class_binding (type, assign_op_identifier);
10570 bool all_trivial = true;
10572 /* Iterate over overloads of the assignment operator, checking
10573 accessible copy assignments for triviality. */
10575 for (tree f : ovl_range (fns))
10577 /* Skip operators that aren't copy assignments. */
10578 if (!copy_fn_p (f))
10579 continue;
10581 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10582 || accessible_p (TYPE_BINFO (type), f, true));
10584 /* Skip template assignment operators and deleted functions. */
10585 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10586 continue;
10588 if (accessible)
10589 *hasassign = true;
10591 if (!accessible || !trivial_fn_p (f))
10592 all_trivial = false;
10594 /* Break early when both properties have been determined. */
10595 if (*hasassign && !all_trivial)
10596 break;
10599 /* Return true if they're all trivial and one of the expressions
10600 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10601 tree ref = cp_build_reference_type (type, false);
10602 return (all_trivial
10603 && (is_trivially_xible (MODIFY_EXPR, type, type)
10604 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10607 /* Return true if all copy and move ctor overloads for class TYPE are
10608 trivial and at least one of them is not deleted and, when ACCESS is
10609 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10610 to true when the TYPE has a (not necessarily trivial) default and copy
10611 (or move) ctor, respectively. */
10613 static bool
10614 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10616 tree fns = get_class_binding (type, complete_ctor_identifier);
10617 bool all_trivial = true;
10619 for (tree f : ovl_range (fns))
10621 /* Skip template constructors. */
10622 if (TREE_CODE (f) != FUNCTION_DECL)
10623 continue;
10625 bool cpy_or_move_ctor_p = copy_fn_p (f);
10627 /* Skip ctors other than default, copy, and move. */
10628 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10629 continue;
10631 if (DECL_DELETED_FN (f))
10632 continue;
10634 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10635 || accessible_p (TYPE_BINFO (type), f, true));
10637 if (accessible)
10638 hasctor[cpy_or_move_ctor_p] = true;
10640 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10641 all_trivial = false;
10643 /* Break early when both properties have been determined. */
10644 if (hasctor[0] && hasctor[1] && !all_trivial)
10645 break;
10648 return all_trivial;
10651 /* Issue a warning on a call to the built-in function FNDECL if it is
10652 a raw memory write whose destination is not an object of (something
10653 like) trivial or standard layout type with a non-deleted assignment
10654 and copy ctor. Detects const correctness violations, corrupting
10655 references, virtual table pointers, and bypassing non-trivial
10656 assignments. */
10658 static void
10659 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10660 const vec<tree, va_gc> *args)
10662 /* Except for bcopy where it's second, the destination pointer is
10663 the first argument for all functions handled here. Compute
10664 the index of the destination and source arguments. */
10665 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10666 unsigned srcidx = !dstidx;
10668 tree dest = (*args)[dstidx];
10669 if (!TREE_TYPE (dest)
10670 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10671 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10672 return;
10674 tree srctype = NULL_TREE;
10676 /* Determine the type of the pointed-to object and whether it's
10677 a complete class type. */
10678 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10680 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10681 return;
10683 /* Check to see if the raw memory call is made by a non-static member
10684 function with THIS as the destination argument for the destination
10685 type. If so, and if the class has no non-trivial bases or members,
10686 be more permissive. */
10687 if (current_function_decl
10688 && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10689 && is_this_parameter (tree_strip_nop_conversions (dest)))
10691 tree ctx = DECL_CONTEXT (current_function_decl);
10692 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10693 tree binfo = TYPE_BINFO (ctx);
10695 if (special
10696 && !BINFO_VTABLE (binfo)
10697 && !first_non_trivial_field (desttype))
10698 return;
10701 /* True if the class is trivial. */
10702 bool trivial = trivial_type_p (desttype);
10704 /* Set to true if DESTYPE has an accessible copy assignment. */
10705 bool hasassign = false;
10706 /* True if all of the class' overloaded copy assignment operators
10707 are all trivial (and not deleted) and at least one of them is
10708 accessible. */
10709 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10711 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10712 respectively. */
10713 bool hasctors[2] = { false, false };
10715 /* True if all of the class' overloaded copy constructors are all
10716 trivial (and not deleted) and at least one of them is accessible. */
10717 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10719 /* Set FLD to the first private/protected member of the class. */
10720 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10722 /* The warning format string. */
10723 const char *warnfmt = NULL;
10724 /* A suggested alternative to offer instead of the raw memory call.
10725 Empty string when none can be come up with. */
10726 const char *suggest = "";
10727 bool warned = false;
10729 switch (DECL_FUNCTION_CODE (fndecl))
10731 case BUILT_IN_MEMSET:
10732 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10734 /* Diagnose setting non-copy-assignable or non-trivial types,
10735 or types with a private member, to (potentially) non-zero
10736 bytes. Since the value of the bytes being written is unknown,
10737 suggest using assignment instead (if one exists). Also warn
10738 for writes into objects for which zero-initialization doesn't
10739 mean all bits clear (pointer-to-member data, where null is all
10740 bits set). Since the value being written is (most likely)
10741 non-zero, simply suggest assignment (but not copy assignment). */
10742 suggest = "; use assignment instead";
10743 if (!trivassign)
10744 warnfmt = G_("%qD writing to an object of type %#qT with "
10745 "no trivial copy-assignment");
10746 else if (!trivial)
10747 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10748 else if (fld)
10750 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10751 warned = warning_at (loc, OPT_Wclass_memaccess,
10752 "%qD writing to an object of type %#qT with "
10753 "%qs member %qD",
10754 fndecl, desttype, access, fld);
10756 else if (!zero_init_p (desttype))
10757 warnfmt = G_("%qD writing to an object of type %#qT containing "
10758 "a pointer to data member%s");
10760 break;
10762 /* Fall through. */
10764 case BUILT_IN_BZERO:
10765 /* Similarly to the above, diagnose clearing non-trivial or non-
10766 standard layout objects, or objects of types with no assignmenmt.
10767 Since the value being written is known to be zero, suggest either
10768 copy assignment, copy ctor, or default ctor as an alternative,
10769 depending on what's available. */
10771 if (hasassign && hasctors[0])
10772 suggest = G_("; use assignment or value-initialization instead");
10773 else if (hasassign)
10774 suggest = G_("; use assignment instead");
10775 else if (hasctors[0])
10776 suggest = G_("; use value-initialization instead");
10778 if (!trivassign)
10779 warnfmt = G_("%qD clearing an object of type %#qT with "
10780 "no trivial copy-assignment%s");
10781 else if (!trivial)
10782 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10783 else if (!zero_init_p (desttype))
10784 warnfmt = G_("%qD clearing an object of type %#qT containing "
10785 "a pointer-to-member%s");
10786 break;
10788 case BUILT_IN_BCOPY:
10789 case BUILT_IN_MEMCPY:
10790 case BUILT_IN_MEMMOVE:
10791 case BUILT_IN_MEMPCPY:
10792 /* Determine the type of the source object. */
10793 srctype = TREE_TYPE ((*args)[srcidx]);
10794 if (!srctype || !INDIRECT_TYPE_P (srctype))
10795 srctype = void_type_node;
10796 else
10797 srctype = TREE_TYPE (srctype);
10799 /* Since it's impossible to determine wheter the byte copy is
10800 being used in place of assignment to an existing object or
10801 as a substitute for initialization, assume it's the former.
10802 Determine the best alternative to use instead depending on
10803 what's not deleted. */
10804 if (hasassign && hasctors[1])
10805 suggest = G_("; use copy-assignment or copy-initialization instead");
10806 else if (hasassign)
10807 suggest = G_("; use copy-assignment instead");
10808 else if (hasctors[1])
10809 suggest = G_("; use copy-initialization instead");
10811 if (!trivassign)
10812 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10813 "copy-assignment%s");
10814 else if (!trivially_copyable_p (desttype))
10815 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10816 "type %#qT%s");
10817 else if (!trivcopy)
10818 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10820 else if (!trivial
10821 && !VOID_TYPE_P (srctype)
10822 && !is_byte_access_type (srctype)
10823 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10824 srctype))
10826 /* Warn when copying into a non-trivial object from an object
10827 of a different type other than void or char. */
10828 warned = warning_at (loc, OPT_Wclass_memaccess,
10829 "%qD copying an object of non-trivial type "
10830 "%#qT from an array of %#qT",
10831 fndecl, desttype, srctype);
10833 else if (fld
10834 && !VOID_TYPE_P (srctype)
10835 && !is_byte_access_type (srctype)
10836 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10837 srctype))
10839 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10840 warned = warning_at (loc, OPT_Wclass_memaccess,
10841 "%qD copying an object of type %#qT with "
10842 "%qs member %qD from an array of %#qT; use "
10843 "assignment or copy-initialization instead",
10844 fndecl, desttype, access, fld, srctype);
10846 else if (!trivial && vec_safe_length (args) > 2)
10848 tree sz = maybe_constant_value ((*args)[2]);
10849 if (!tree_fits_uhwi_p (sz))
10850 break;
10852 /* Finally, warn on partial copies. */
10853 unsigned HOST_WIDE_INT typesize
10854 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10855 if (typesize == 0)
10856 break;
10857 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10858 warned = warning_at (loc, OPT_Wclass_memaccess,
10859 (typesize - partial > 1
10860 ? G_("%qD writing to an object of "
10861 "a non-trivial type %#qT leaves %wu "
10862 "bytes unchanged")
10863 : G_("%qD writing to an object of "
10864 "a non-trivial type %#qT leaves %wu "
10865 "byte unchanged")),
10866 fndecl, desttype, typesize - partial);
10868 break;
10870 case BUILT_IN_REALLOC:
10872 if (!trivially_copyable_p (desttype))
10873 warnfmt = G_("%qD moving an object of non-trivially copyable type "
10874 "%#qT; use %<new%> and %<delete%> instead");
10875 else if (!trivcopy)
10876 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10877 "constructor; use %<new%> and %<delete%> instead");
10878 else if (!get_dtor (desttype, tf_none))
10879 warnfmt = G_("%qD moving an object of type %#qT with deleted "
10880 "destructor");
10881 else if (!trivial)
10883 tree sz = maybe_constant_value ((*args)[1]);
10884 if (TREE_CODE (sz) == INTEGER_CST
10885 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10886 /* Finally, warn on reallocation into insufficient space. */
10887 warned = warning_at (loc, OPT_Wclass_memaccess,
10888 "%qD moving an object of non-trivial type "
10889 "%#qT and size %E into a region of size %E",
10890 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10891 sz);
10893 break;
10895 default:
10896 return;
10899 if (warnfmt)
10901 if (suggest)
10902 warned = warning_at (loc, OPT_Wclass_memaccess,
10903 warnfmt, fndecl, desttype, suggest);
10904 else
10905 warned = warning_at (loc, OPT_Wclass_memaccess,
10906 warnfmt, fndecl, desttype);
10909 if (warned)
10910 inform (location_of (desttype), "%#qT declared here", desttype);
10913 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10914 If FN is the result of resolving an overloaded target built-in,
10915 ORIG_FNDECL is the original function decl, otherwise it is null.
10916 This function performs no overload resolution, conversion, or other
10917 high-level operations. */
10919 tree
10920 build_cxx_call (tree fn, int nargs, tree *argarray,
10921 tsubst_flags_t complain, tree orig_fndecl)
10923 tree fndecl;
10925 /* Remember roughly where this call is. */
10926 location_t loc = cp_expr_loc_or_input_loc (fn);
10927 fn = build_call_a (fn, nargs, argarray);
10928 SET_EXPR_LOCATION (fn, loc);
10930 fndecl = get_callee_fndecl (fn);
10931 if (!orig_fndecl)
10932 orig_fndecl = fndecl;
10934 /* Check that arguments to builtin functions match the expectations. */
10935 if (fndecl
10936 && !processing_template_decl
10937 && fndecl_built_in_p (fndecl))
10939 int i;
10941 /* We need to take care that values to BUILT_IN_NORMAL
10942 are reduced. */
10943 for (i = 0; i < nargs; i++)
10944 argarray[i] = maybe_constant_value (argarray[i]);
10946 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10947 orig_fndecl, nargs, argarray))
10948 return error_mark_node;
10949 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
10951 tree arg0 = argarray[0];
10952 STRIP_NOPS (arg0);
10953 if (TREE_CODE (arg0) == ADDR_EXPR
10954 && DECL_P (TREE_OPERAND (arg0, 0))
10955 && same_type_ignoring_top_level_qualifiers_p
10956 (TREE_TYPE (TREE_TYPE (argarray[0])),
10957 TREE_TYPE (TREE_TYPE (arg0))))
10958 /* For __builtin_clear_padding (&var) we know the type
10959 is for a complete object, so there is no risk in clearing
10960 padding that is reused in some derived class member. */;
10961 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
10963 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
10964 "argument %u in call to function %qE "
10965 "has pointer to a non-trivially-copyable type (%qT)",
10966 1, fndecl, TREE_TYPE (argarray[0]));
10967 return error_mark_node;
10972 if (VOID_TYPE_P (TREE_TYPE (fn)))
10973 return fn;
10975 /* 5.2.2/11: If a function call is a prvalue of object type: if the
10976 function call is either the operand of a decltype-specifier or the
10977 right operand of a comma operator that is the operand of a
10978 decltype-specifier, a temporary object is not introduced for the
10979 prvalue. The type of the prvalue may be incomplete. */
10980 if (!(complain & tf_decltype))
10982 fn = require_complete_type (fn, complain);
10983 if (fn == error_mark_node)
10984 return error_mark_node;
10986 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10988 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10989 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10992 return convert_from_reference (fn);
10995 /* Returns the value to use for the in-charge parameter when making a
10996 call to a function with the indicated NAME.
10998 FIXME:Can't we find a neater way to do this mapping? */
11000 tree
11001 in_charge_arg_for_name (tree name)
11003 if (IDENTIFIER_CTOR_P (name))
11005 if (name == complete_ctor_identifier)
11006 return integer_one_node;
11007 gcc_checking_assert (name == base_ctor_identifier);
11009 else
11011 if (name == complete_dtor_identifier)
11012 return integer_two_node;
11013 else if (name == deleting_dtor_identifier)
11014 return integer_three_node;
11015 gcc_checking_assert (name == base_dtor_identifier);
11018 return integer_zero_node;
11021 /* We've built up a constructor call RET. Complain if it delegates to the
11022 constructor we're currently compiling. */
11024 static void
11025 check_self_delegation (tree ret)
11027 if (TREE_CODE (ret) == TARGET_EXPR)
11028 ret = TARGET_EXPR_INITIAL (ret);
11029 tree fn = cp_get_callee_fndecl_nofold (ret);
11030 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11031 error ("constructor delegates to itself");
11034 /* Build a call to a constructor, destructor, or an assignment
11035 operator for INSTANCE, an expression with class type. NAME
11036 indicates the special member function to call; *ARGS are the
11037 arguments. ARGS may be NULL. This may change ARGS. BINFO
11038 indicates the base of INSTANCE that is to be passed as the `this'
11039 parameter to the member function called.
11041 FLAGS are the LOOKUP_* flags to use when processing the call.
11043 If NAME indicates a complete object constructor, INSTANCE may be
11044 NULL_TREE. In this case, the caller will call build_cplus_new to
11045 store the newly constructed object into a VAR_DECL. */
11047 tree
11048 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11049 tree binfo, int flags, tsubst_flags_t complain)
11051 tree fns;
11052 /* The type of the subobject to be constructed or destroyed. */
11053 tree class_type;
11054 vec<tree, va_gc> *allocated = NULL;
11055 tree ret;
11057 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11059 if (error_operand_p (instance))
11060 return error_mark_node;
11062 if (IDENTIFIER_DTOR_P (name))
11064 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11065 if (!type_build_dtor_call (TREE_TYPE (instance)))
11066 /* Shortcut to avoid lazy destructor declaration. */
11067 return build_trivial_dtor_call (instance);
11070 if (TYPE_P (binfo))
11072 /* Resolve the name. */
11073 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11074 return error_mark_node;
11076 binfo = TYPE_BINFO (binfo);
11079 gcc_assert (binfo != NULL_TREE);
11081 class_type = BINFO_TYPE (binfo);
11083 /* Handle the special case where INSTANCE is NULL_TREE. */
11084 if (name == complete_ctor_identifier && !instance)
11085 instance = build_dummy_object (class_type);
11086 else
11088 /* Convert to the base class, if necessary. */
11089 if (!same_type_ignoring_top_level_qualifiers_p
11090 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11092 if (IDENTIFIER_CDTOR_P (name))
11093 /* For constructors and destructors, either the base is
11094 non-virtual, or it is virtual but we are doing the
11095 conversion from a constructor or destructor for the
11096 complete object. In either case, we can convert
11097 statically. */
11098 instance = convert_to_base_statically (instance, binfo);
11099 else
11101 /* However, for assignment operators, we must convert
11102 dynamically if the base is virtual. */
11103 gcc_checking_assert (name == assign_op_identifier);
11104 instance = build_base_path (PLUS_EXPR, instance,
11105 binfo, /*nonnull=*/1, complain);
11110 gcc_assert (instance != NULL_TREE);
11112 /* In C++17, "If the initializer expression is a prvalue and the
11113 cv-unqualified version of the source type is the same class as the class
11114 of the destination, the initializer expression is used to initialize the
11115 destination object." Handle that here to avoid doing overload
11116 resolution. */
11117 if (cxx_dialect >= cxx17
11118 && args && vec_safe_length (*args) == 1
11119 && !unsafe_return_slot_p (instance))
11121 tree arg = (**args)[0];
11123 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11124 && !TYPE_HAS_LIST_CTOR (class_type)
11125 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11126 && CONSTRUCTOR_NELTS (arg) == 1)
11127 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11129 if ((TREE_CODE (arg) == TARGET_EXPR
11130 || TREE_CODE (arg) == CONSTRUCTOR)
11131 && (same_type_ignoring_top_level_qualifiers_p
11132 (class_type, TREE_TYPE (arg))))
11134 if (is_dummy_object (instance))
11135 return arg;
11136 else if (TREE_CODE (arg) == TARGET_EXPR)
11137 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11139 if ((complain & tf_error)
11140 && (flags & LOOKUP_DELEGATING_CONS))
11141 check_self_delegation (arg);
11142 /* Avoid change of behavior on Wunused-var-2.C. */
11143 instance = mark_lvalue_use (instance);
11144 return cp_build_init_expr (instance, arg);
11148 fns = lookup_fnfields (binfo, name, 1, complain);
11150 /* When making a call to a constructor or destructor for a subobject
11151 that uses virtual base classes, pass down a pointer to a VTT for
11152 the subobject. */
11153 if ((name == base_ctor_identifier
11154 || name == base_dtor_identifier)
11155 && CLASSTYPE_VBASECLASSES (class_type))
11157 tree vtt;
11158 tree sub_vtt;
11160 /* If the current function is a complete object constructor
11161 or destructor, then we fetch the VTT directly.
11162 Otherwise, we look it up using the VTT we were given. */
11163 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11164 vtt = decay_conversion (vtt, complain);
11165 if (vtt == error_mark_node)
11166 return error_mark_node;
11167 vtt = build_if_in_charge (vtt, current_vtt_parm);
11168 if (BINFO_SUBVTT_INDEX (binfo))
11169 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11170 else
11171 sub_vtt = vtt;
11173 if (args == NULL)
11175 allocated = make_tree_vector ();
11176 args = &allocated;
11179 vec_safe_insert (*args, 0, sub_vtt);
11182 ret = build_new_method_call (instance, fns, args,
11183 TYPE_BINFO (BINFO_TYPE (binfo)),
11184 flags, /*fn=*/NULL,
11185 complain);
11187 if (allocated != NULL)
11188 release_tree_vector (allocated);
11190 if ((complain & tf_error)
11191 && (flags & LOOKUP_DELEGATING_CONS)
11192 && name == complete_ctor_identifier)
11193 check_self_delegation (ret);
11195 return ret;
11198 /* Return the NAME, as a C string. The NAME indicates a function that
11199 is a member of TYPE. *FREE_P is set to true if the caller must
11200 free the memory returned.
11202 Rather than go through all of this, we should simply set the names
11203 of constructors and destructors appropriately, and dispense with
11204 ctor_identifier, dtor_identifier, etc. */
11206 static char *
11207 name_as_c_string (tree name, tree type, bool *free_p)
11209 const char *pretty_name;
11211 /* Assume that we will not allocate memory. */
11212 *free_p = false;
11213 /* Constructors and destructors are special. */
11214 if (IDENTIFIER_CDTOR_P (name))
11216 pretty_name
11217 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11218 /* For a destructor, add the '~'. */
11219 if (IDENTIFIER_DTOR_P (name))
11221 pretty_name = concat ("~", pretty_name, NULL);
11222 /* Remember that we need to free the memory allocated. */
11223 *free_p = true;
11226 else if (IDENTIFIER_CONV_OP_P (name))
11228 pretty_name = concat ("operator ",
11229 type_as_string_translate (TREE_TYPE (name),
11230 TFF_PLAIN_IDENTIFIER),
11231 NULL);
11232 /* Remember that we need to free the memory allocated. */
11233 *free_p = true;
11235 else
11236 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11238 return CONST_CAST (char *, pretty_name);
11241 /* If CANDIDATES contains exactly one candidate, return it, otherwise
11242 return NULL. */
11244 static z_candidate *
11245 single_z_candidate (z_candidate *candidates)
11247 if (candidates == NULL)
11248 return NULL;
11250 if (candidates->next)
11251 return NULL;
11253 return candidates;
11256 /* If CANDIDATE is invalid due to a bad argument type, return the
11257 pertinent conversion_info.
11259 Otherwise, return NULL. */
11261 static const conversion_info *
11262 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11264 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11265 rejection_reason *r = candidate->reason;
11267 if (r == NULL)
11268 return NULL;
11270 switch (r->code)
11272 default:
11273 return NULL;
11275 case rr_arg_conversion:
11276 return &r->u.conversion;
11278 case rr_bad_arg_conversion:
11279 return &r->u.bad_conversion;
11283 /* Issue an error and note complaining about a bad argument type at a
11284 callsite with a single candidate FNDECL.
11286 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11287 case input_location is used).
11288 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11289 the formal parameter. */
11291 void
11292 complain_about_bad_argument (location_t arg_loc,
11293 tree from_type, tree to_type,
11294 tree fndecl, int parmnum)
11296 auto_diagnostic_group d;
11297 range_label_for_type_mismatch rhs_label (from_type, to_type);
11298 range_label *label = &rhs_label;
11299 if (arg_loc == UNKNOWN_LOCATION)
11301 arg_loc = input_location;
11302 label = NULL;
11304 gcc_rich_location richloc (arg_loc, label);
11305 error_at (&richloc,
11306 "cannot convert %qH to %qI",
11307 from_type, to_type);
11308 maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
11309 parmnum);
11312 /* Subroutine of build_new_method_call_1, for where there are no viable
11313 candidates for the call. */
11315 static void
11316 complain_about_no_candidates_for_method_call (tree instance,
11317 z_candidate *candidates,
11318 tree explicit_targs,
11319 tree basetype,
11320 tree optype, tree name,
11321 bool skip_first_for_error,
11322 vec<tree, va_gc> *user_args)
11324 auto_diagnostic_group d;
11325 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11326 cxx_incomplete_type_error (instance, basetype);
11327 else if (optype)
11328 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11329 basetype, optype, build_tree_list_vec (user_args),
11330 TREE_TYPE (instance));
11331 else
11333 /* Special-case for when there's a single candidate that's failing
11334 due to a bad argument type. */
11335 if (z_candidate *candidate = single_z_candidate (candidates))
11336 if (const conversion_info *conv
11337 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11339 tree from_type = conv->from;
11340 if (!TYPE_P (conv->from))
11341 from_type = lvalue_type (conv->from);
11342 complain_about_bad_argument (conv->loc,
11343 from_type, conv->to_type,
11344 candidate->fn, conv->n_arg);
11345 return;
11348 tree arglist = build_tree_list_vec (user_args);
11349 tree errname = name;
11350 bool twiddle = false;
11351 if (IDENTIFIER_CDTOR_P (errname))
11353 twiddle = IDENTIFIER_DTOR_P (errname);
11354 errname = constructor_name (basetype);
11356 if (explicit_targs)
11357 errname = lookup_template_function (errname, explicit_targs);
11358 if (skip_first_for_error)
11359 arglist = TREE_CHAIN (arglist);
11360 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11361 basetype, &"~"[!twiddle], errname, arglist,
11362 TREE_TYPE (instance));
11364 print_z_candidates (location_of (name), candidates);
11367 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11368 be set, upon return, to the function called. ARGS may be NULL.
11369 This may change ARGS. */
11371 tree
11372 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11373 tree conversion_path, int flags,
11374 tree *fn_p, tsubst_flags_t complain)
11376 struct z_candidate *candidates = 0, *cand;
11377 tree explicit_targs = NULL_TREE;
11378 tree basetype = NULL_TREE;
11379 tree access_binfo;
11380 tree optype;
11381 tree first_mem_arg = NULL_TREE;
11382 tree name;
11383 bool skip_first_for_error;
11384 vec<tree, va_gc> *user_args;
11385 tree call;
11386 tree fn;
11387 int template_only = 0;
11388 bool any_viable_p;
11389 tree orig_instance;
11390 tree orig_fns;
11391 vec<tree, va_gc> *orig_args = NULL;
11392 void *p;
11394 auto_cond_timevar tv (TV_OVERLOAD);
11396 gcc_assert (instance != NULL_TREE);
11398 /* We don't know what function we're going to call, yet. */
11399 if (fn_p)
11400 *fn_p = NULL_TREE;
11402 if (error_operand_p (instance)
11403 || !fns || error_operand_p (fns))
11404 return error_mark_node;
11406 if (!BASELINK_P (fns))
11408 if (complain & tf_error)
11409 error ("call to non-function %qD", fns);
11410 return error_mark_node;
11413 orig_instance = instance;
11414 orig_fns = fns;
11416 /* Dismantle the baselink to collect all the information we need. */
11417 if (!conversion_path)
11418 conversion_path = BASELINK_BINFO (fns);
11419 access_binfo = BASELINK_ACCESS_BINFO (fns);
11420 optype = BASELINK_OPTYPE (fns);
11421 fns = BASELINK_FUNCTIONS (fns);
11422 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11424 explicit_targs = TREE_OPERAND (fns, 1);
11425 fns = TREE_OPERAND (fns, 0);
11426 template_only = 1;
11428 gcc_assert (OVL_P (fns));
11429 fn = OVL_FIRST (fns);
11430 name = DECL_NAME (fn);
11432 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11433 gcc_assert (CLASS_TYPE_P (basetype));
11435 user_args = args == NULL ? NULL : *args;
11436 /* Under DR 147 A::A() is an invalid constructor call,
11437 not a functional cast. */
11438 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11440 if (! (complain & tf_error))
11441 return error_mark_node;
11443 basetype = DECL_CONTEXT (fn);
11444 name = constructor_name (basetype);
11445 auto_diagnostic_group d;
11446 if (permerror (input_location,
11447 "cannot call constructor %<%T::%D%> directly",
11448 basetype, name))
11449 inform (input_location, "for a function-style cast, remove the "
11450 "redundant %<::%D%>", name);
11451 call = build_functional_cast (input_location, basetype,
11452 build_tree_list_vec (user_args),
11453 complain);
11454 return call;
11457 if (processing_template_decl)
11459 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11460 instance = build_non_dependent_expr (instance);
11461 if (args != NULL)
11462 make_args_non_dependent (*args);
11465 /* Process the argument list. */
11466 if (args != NULL && *args != NULL)
11468 *args = resolve_args (*args, complain);
11469 if (*args == NULL)
11470 return error_mark_node;
11471 user_args = *args;
11474 /* Consider the object argument to be used even if we end up selecting a
11475 static member function. */
11476 instance = mark_type_use (instance);
11478 /* Figure out whether to skip the first argument for the error
11479 message we will display to users if an error occurs. We don't
11480 want to display any compiler-generated arguments. The "this"
11481 pointer hasn't been added yet. However, we must remove the VTT
11482 pointer if this is a call to a base-class constructor or
11483 destructor. */
11484 skip_first_for_error = false;
11485 if (IDENTIFIER_CDTOR_P (name))
11487 /* Callers should explicitly indicate whether they want to ctor
11488 the complete object or just the part without virtual bases. */
11489 gcc_assert (name != ctor_identifier);
11491 /* Remove the VTT pointer, if present. */
11492 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11493 && CLASSTYPE_VBASECLASSES (basetype))
11494 skip_first_for_error = true;
11496 /* It's OK to call destructors and constructors on cv-qualified
11497 objects. Therefore, convert the INSTANCE to the unqualified
11498 type, if necessary. */
11499 if (!same_type_p (basetype, TREE_TYPE (instance)))
11501 instance = build_this (instance);
11502 instance = build_nop (build_pointer_type (basetype), instance);
11503 instance = build_fold_indirect_ref (instance);
11506 else
11507 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11509 /* For the overload resolution we need to find the actual `this`
11510 that would be captured if the call turns out to be to a
11511 non-static member function. Do not actually capture it at this
11512 point. */
11513 if (DECL_CONSTRUCTOR_P (fn))
11514 /* Constructors don't use the enclosing 'this'. */
11515 first_mem_arg = instance;
11516 else
11517 first_mem_arg = maybe_resolve_dummy (instance, false);
11519 /* Get the high-water mark for the CONVERSION_OBSTACK. */
11520 p = conversion_obstack_alloc (0);
11522 /* The number of arguments artificial parms in ARGS; we subtract one because
11523 there's no 'this' in ARGS. */
11524 unsigned skip = num_artificial_parms_for (fn) - 1;
11526 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11527 initializer, not T({ }). */
11528 if (DECL_CONSTRUCTOR_P (fn)
11529 && vec_safe_length (user_args) > skip
11530 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11532 tree init_list = (*user_args)[skip];
11533 tree init = NULL_TREE;
11535 gcc_assert (user_args->length () == skip + 1
11536 && !(flags & LOOKUP_ONLYCONVERTING));
11538 /* If the initializer list has no elements and T is a class type with
11539 a default constructor, the object is value-initialized. Handle
11540 this here so we don't need to handle it wherever we use
11541 build_special_member_call. */
11542 if (CONSTRUCTOR_NELTS (init_list) == 0
11543 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11544 /* For a user-provided default constructor, use the normal
11545 mechanisms so that protected access works. */
11546 && type_has_non_user_provided_default_constructor (basetype)
11547 && !processing_template_decl)
11548 init = build_value_init (basetype, complain);
11550 /* If BASETYPE is an aggregate, we need to do aggregate
11551 initialization. */
11552 else if (CP_AGGREGATE_TYPE_P (basetype))
11554 init = reshape_init (basetype, init_list, complain);
11555 init = digest_init (basetype, init, complain);
11558 if (init)
11560 if (is_dummy_object (instance))
11561 return get_target_expr (init, complain);
11562 return cp_build_init_expr (instance, init);
11565 /* Otherwise go ahead with overload resolution. */
11566 add_list_candidates (fns, first_mem_arg, user_args,
11567 basetype, explicit_targs, template_only,
11568 conversion_path, access_binfo, flags,
11569 &candidates, complain);
11571 else
11572 add_candidates (fns, first_mem_arg, user_args, optype,
11573 explicit_targs, template_only, conversion_path,
11574 access_binfo, flags, &candidates, complain);
11576 any_viable_p = false;
11577 candidates = splice_viable (candidates, false, &any_viable_p);
11579 if (!any_viable_p)
11581 /* [dcl.init], 17.6.2.2:
11583 Otherwise, if no constructor is viable, the destination type is
11584 a (possibly cv-qualified) aggregate class A, and the initializer
11585 is a parenthesized expression-list, the object is initialized as
11586 follows...
11588 We achieve this by building up a CONSTRUCTOR, as for list-init,
11589 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11590 the two. */
11591 if (DECL_CONSTRUCTOR_P (fn)
11592 && !(flags & LOOKUP_ONLYCONVERTING)
11593 && cxx_dialect >= cxx20
11594 && CP_AGGREGATE_TYPE_P (basetype)
11595 && !vec_safe_is_empty (user_args))
11597 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11598 tree ctor = build_constructor_from_vec (init_list_type_node,
11599 user_args);
11600 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11601 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11602 if (is_dummy_object (instance))
11603 return ctor;
11604 else
11606 ctor = digest_init (basetype, ctor, complain);
11607 if (ctor == error_mark_node)
11608 return error_mark_node;
11609 return cp_build_init_expr (instance, ctor);
11612 if (complain & tf_error)
11613 complain_about_no_candidates_for_method_call (instance, candidates,
11614 explicit_targs, basetype,
11615 optype, name,
11616 skip_first_for_error,
11617 user_args);
11618 call = error_mark_node;
11620 else
11622 cand = tourney (candidates, complain);
11623 if (cand == 0)
11625 char *pretty_name;
11626 bool free_p;
11627 tree arglist;
11629 if (complain & tf_error)
11631 pretty_name = name_as_c_string (name, basetype, &free_p);
11632 arglist = build_tree_list_vec (user_args);
11633 if (skip_first_for_error)
11634 arglist = TREE_CHAIN (arglist);
11635 auto_diagnostic_group d;
11636 if (!any_strictly_viable (candidates))
11637 error ("no matching function for call to %<%s(%A)%>",
11638 pretty_name, arglist);
11639 else
11640 error ("call of overloaded %<%s(%A)%> is ambiguous",
11641 pretty_name, arglist);
11642 print_z_candidates (location_of (name), candidates);
11643 if (free_p)
11644 free (pretty_name);
11646 call = error_mark_node;
11647 if (fn_p)
11648 *fn_p = error_mark_node;
11650 else
11652 fn = cand->fn;
11653 call = NULL_TREE;
11655 if (!(flags & LOOKUP_NONVIRTUAL)
11656 && DECL_PURE_VIRTUAL_P (fn)
11657 && instance == current_class_ref
11658 && (complain & tf_warning))
11660 /* This is not an error, it is runtime undefined
11661 behavior. */
11662 if (!current_function_decl)
11663 warning (0, "pure virtual %q#D called from "
11664 "non-static data member initializer", fn);
11665 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11666 || DECL_DESTRUCTOR_P (current_function_decl))
11667 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11668 ? G_("pure virtual %q#D called from constructor")
11669 : G_("pure virtual %q#D called from destructor")),
11670 fn);
11673 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11674 && !DECL_CONSTRUCTOR_P (fn)
11675 && is_dummy_object (instance))
11677 instance = maybe_resolve_dummy (instance, true);
11678 if (instance == error_mark_node)
11679 call = error_mark_node;
11680 else if (!is_dummy_object (instance))
11682 /* We captured 'this' in the current lambda now that
11683 we know we really need it. */
11684 cand->first_arg = instance;
11686 else if (current_class_ptr && any_dependent_bases_p ())
11687 /* We can't tell until instantiation time whether we can use
11688 *this as the implicit object argument. */;
11689 else
11691 if (complain & tf_error)
11692 error ("cannot call member function %qD without object",
11693 fn);
11694 call = error_mark_node;
11698 if (call != error_mark_node)
11700 /* Now we know what function is being called. */
11701 if (fn_p)
11702 *fn_p = fn;
11703 /* Build the actual CALL_EXPR. */
11704 call = build_over_call (cand, flags, complain);
11706 /* Suppress warnings for if (my_struct.operator= (x)) where
11707 my_struct is implicitly converted to bool. */
11708 if (TREE_CODE (call) == MODIFY_EXPR)
11709 suppress_warning (call, OPT_Wparentheses);
11711 /* In an expression of the form `a->f()' where `f' turns
11712 out to be a static member function, `a' is
11713 none-the-less evaluated. */
11714 if (!is_dummy_object (instance))
11715 call = keep_unused_object_arg (call, instance, fn);
11716 if (call != error_mark_node
11717 && DECL_DESTRUCTOR_P (cand->fn)
11718 && !VOID_TYPE_P (TREE_TYPE (call)))
11719 /* An explicit call of the form "x->~X()" has type
11720 "void". However, on platforms where destructors
11721 return "this" (i.e., those where
11722 targetm.cxx.cdtor_returns_this is true), such calls
11723 will appear to have a return value of pointer type
11724 to the low-level call machinery. We do not want to
11725 change the low-level machinery, since we want to be
11726 able to optimize "delete f()" on such platforms as
11727 "operator delete(~X(f()))" (rather than generating
11728 "t = f(), ~X(t), operator delete (t)"). */
11729 call = build_nop (void_type_node, call);
11734 if (processing_template_decl && call != error_mark_node)
11736 bool cast_to_void = false;
11738 if (TREE_CODE (call) == COMPOUND_EXPR)
11739 call = TREE_OPERAND (call, 1);
11740 else if (TREE_CODE (call) == NOP_EXPR)
11742 cast_to_void = true;
11743 call = TREE_OPERAND (call, 0);
11745 if (INDIRECT_REF_P (call))
11746 call = TREE_OPERAND (call, 0);
11748 /* Prune all but the selected function from the original overload
11749 set so that we can avoid some duplicate work at instantiation time. */
11750 if (really_overloaded_fn (fns))
11752 if (DECL_TEMPLATE_INFO (fn)
11753 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11755 /* Use the selected template, not the specialization, so that
11756 this looks like an actual lookup result for sake of
11757 filter_memfn_lookup. */
11759 if (OVL_SINGLE_P (fns))
11760 /* If the original overload set consists of a single function
11761 template, this isn't beneficial. */
11762 goto skip_prune;
11764 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11765 if (template_only)
11766 fn = lookup_template_function (fn, explicit_targs);
11768 orig_fns = copy_node (orig_fns);
11769 BASELINK_FUNCTIONS (orig_fns) = fn;
11770 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11773 skip_prune:
11774 call = (build_min_non_dep_call_vec
11775 (call,
11776 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11777 orig_instance, orig_fns, NULL_TREE),
11778 orig_args));
11779 SET_EXPR_LOCATION (call, input_location);
11780 call = convert_from_reference (call);
11781 if (cast_to_void)
11782 call = build_nop (void_type_node, call);
11785 /* Free all the conversions we allocated. */
11786 obstack_free (&conversion_obstack, p);
11788 if (orig_args != NULL)
11789 release_tree_vector (orig_args);
11791 return call;
11794 /* Returns true iff standard conversion sequence ICS1 is a proper
11795 subsequence of ICS2. */
11797 static bool
11798 is_subseq (conversion *ics1, conversion *ics2)
11800 /* We can assume that a conversion of the same code
11801 between the same types indicates a subsequence since we only get
11802 here if the types we are converting from are the same. */
11804 while (ics1->kind == ck_rvalue
11805 || ics1->kind == ck_lvalue)
11806 ics1 = next_conversion (ics1);
11808 while (1)
11810 while (ics2->kind == ck_rvalue
11811 || ics2->kind == ck_lvalue)
11812 ics2 = next_conversion (ics2);
11814 if (ics2->kind == ck_user
11815 || !has_next (ics2->kind))
11816 /* At this point, ICS1 cannot be a proper subsequence of
11817 ICS2. We can get a USER_CONV when we are comparing the
11818 second standard conversion sequence of two user conversion
11819 sequences. */
11820 return false;
11822 ics2 = next_conversion (ics2);
11824 while (ics2->kind == ck_rvalue
11825 || ics2->kind == ck_lvalue)
11826 ics2 = next_conversion (ics2);
11828 if (ics2->kind == ics1->kind
11829 && same_type_p (ics2->type, ics1->type)
11830 && (ics1->kind == ck_identity
11831 || same_type_p (next_conversion (ics2)->type,
11832 next_conversion (ics1)->type)))
11833 return true;
11837 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11838 be any _TYPE nodes. */
11840 bool
11841 is_properly_derived_from (tree derived, tree base)
11843 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11844 return false;
11846 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11847 considers every class derived from itself. */
11848 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11849 && DERIVED_FROM_P (base, derived));
11852 /* We build the ICS for an implicit object parameter as a pointer
11853 conversion sequence. However, such a sequence should be compared
11854 as if it were a reference conversion sequence. If ICS is the
11855 implicit conversion sequence for an implicit object parameter,
11856 modify it accordingly. */
11858 static void
11859 maybe_handle_implicit_object (conversion **ics)
11861 if ((*ics)->this_p)
11863 /* [over.match.funcs]
11865 For non-static member functions, the type of the
11866 implicit object parameter is "reference to cv X"
11867 where X is the class of which the function is a
11868 member and cv is the cv-qualification on the member
11869 function declaration. */
11870 conversion *t = *ics;
11871 tree reference_type;
11873 /* The `this' parameter is a pointer to a class type. Make the
11874 implicit conversion talk about a reference to that same class
11875 type. */
11876 reference_type = TREE_TYPE (t->type);
11877 reference_type = build_reference_type (reference_type);
11879 if (t->kind == ck_qual)
11880 t = next_conversion (t);
11881 if (t->kind == ck_ptr)
11882 t = next_conversion (t);
11883 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11884 t = direct_reference_binding (reference_type, t);
11885 t->this_p = 1;
11886 t->rvaluedness_matches_p = 0;
11887 *ics = t;
11891 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11892 and return the initial reference binding conversion. Otherwise,
11893 leave *ICS unchanged and return NULL. */
11895 static conversion *
11896 maybe_handle_ref_bind (conversion **ics)
11898 if ((*ics)->kind == ck_ref_bind)
11900 conversion *old_ics = *ics;
11901 *ics = next_conversion (old_ics);
11902 (*ics)->user_conv_p = old_ics->user_conv_p;
11903 return old_ics;
11906 return NULL;
11909 /* Get the expression at the beginning of the conversion chain C. */
11911 static tree
11912 conv_get_original_expr (conversion *c)
11914 for (; c; c = next_conversion (c))
11915 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11916 return c->u.expr;
11917 return NULL_TREE;
11920 /* Return a tree representing the number of elements initialized by the
11921 list-initialization C. The caller must check that C converts to an
11922 array type. */
11924 static tree
11925 nelts_initialized_by_list_init (conversion *c)
11927 /* If the array we're converting to has a dimension, we'll use that. */
11928 if (TYPE_DOMAIN (c->type))
11929 return array_type_nelts_top (c->type);
11930 else
11932 /* Otherwise, we look at how many elements the constructor we're
11933 initializing from has. */
11934 tree ctor = conv_get_original_expr (c);
11935 return size_int (CONSTRUCTOR_NELTS (ctor));
11939 /* True iff C is a conversion that binds a reference or a pointer to
11940 an array of unknown bound. */
11942 static inline bool
11943 conv_binds_to_array_of_unknown_bound (conversion *c)
11945 /* ck_ref_bind won't have the reference stripped. */
11946 tree type = non_reference (c->type);
11947 /* ck_qual won't have the pointer stripped. */
11948 type = strip_pointer_operator (type);
11949 return (TREE_CODE (type) == ARRAY_TYPE
11950 && TYPE_DOMAIN (type) == NULL_TREE);
11953 /* Compare two implicit conversion sequences according to the rules set out in
11954 [over.ics.rank]. Return values:
11956 1: ics1 is better than ics2
11957 -1: ics2 is better than ics1
11958 0: ics1 and ics2 are indistinguishable */
11960 static int
11961 compare_ics (conversion *ics1, conversion *ics2)
11963 tree from_type1;
11964 tree from_type2;
11965 tree to_type1;
11966 tree to_type2;
11967 tree deref_from_type1 = NULL_TREE;
11968 tree deref_from_type2 = NULL_TREE;
11969 tree deref_to_type1 = NULL_TREE;
11970 tree deref_to_type2 = NULL_TREE;
11971 conversion_rank rank1, rank2;
11973 /* REF_BINDING is nonzero if the result of the conversion sequence
11974 is a reference type. In that case REF_CONV is the reference
11975 binding conversion. */
11976 conversion *ref_conv1;
11977 conversion *ref_conv2;
11979 /* Compare badness before stripping the reference conversion. */
11980 if (ics1->bad_p > ics2->bad_p)
11981 return -1;
11982 else if (ics1->bad_p < ics2->bad_p)
11983 return 1;
11985 /* Handle implicit object parameters. */
11986 maybe_handle_implicit_object (&ics1);
11987 maybe_handle_implicit_object (&ics2);
11989 /* Handle reference parameters. */
11990 ref_conv1 = maybe_handle_ref_bind (&ics1);
11991 ref_conv2 = maybe_handle_ref_bind (&ics2);
11993 /* List-initialization sequence L1 is a better conversion sequence than
11994 list-initialization sequence L2 if L1 converts to
11995 std::initializer_list<X> for some X and L2 does not. */
11996 if (ics1->kind == ck_list && ics2->kind != ck_list)
11997 return 1;
11998 if (ics2->kind == ck_list && ics1->kind != ck_list)
11999 return -1;
12001 /* [over.ics.rank]
12003 When comparing the basic forms of implicit conversion sequences (as
12004 defined in _over.best.ics_)
12006 --a standard conversion sequence (_over.ics.scs_) is a better
12007 conversion sequence than a user-defined conversion sequence
12008 or an ellipsis conversion sequence, and
12010 --a user-defined conversion sequence (_over.ics.user_) is a
12011 better conversion sequence than an ellipsis conversion sequence
12012 (_over.ics.ellipsis_). */
12013 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12014 mismatch. If both ICS are bad, we try to make a decision based on
12015 what would have happened if they'd been good. This is not an
12016 extension, we'll still give an error when we build up the call; this
12017 just helps us give a more helpful error message. */
12018 rank1 = BAD_CONVERSION_RANK (ics1);
12019 rank2 = BAD_CONVERSION_RANK (ics2);
12021 if (rank1 > rank2)
12022 return -1;
12023 else if (rank1 < rank2)
12024 return 1;
12026 if (ics1->ellipsis_p)
12027 /* Both conversions are ellipsis conversions. */
12028 return 0;
12030 /* User-defined conversion sequence U1 is a better conversion sequence
12031 than another user-defined conversion sequence U2 if they contain the
12032 same user-defined conversion operator or constructor and if the sec-
12033 ond standard conversion sequence of U1 is better than the second
12034 standard conversion sequence of U2. */
12036 /* Handle list-conversion with the same code even though it isn't always
12037 ranked as a user-defined conversion and it doesn't have a second
12038 standard conversion sequence; it will still have the desired effect.
12039 Specifically, we need to do the reference binding comparison at the
12040 end of this function. */
12042 if (ics1->user_conv_p || ics1->kind == ck_list
12043 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12045 conversion *t1 = strip_standard_conversion (ics1);
12046 conversion *t2 = strip_standard_conversion (ics2);
12048 if (!t1 || !t2 || t1->kind != t2->kind)
12049 return 0;
12050 else if (t1->kind == ck_user)
12052 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12053 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12054 if (f1 != f2)
12055 return 0;
12057 /* List-initialization sequence L1 is a better conversion sequence than
12058 list-initialization sequence L2 if
12060 -- L1 and L2 convert to arrays of the same element type, and either
12061 the number of elements n1 initialized by L1 is less than the number
12062 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12063 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12064 P0388R4.) */
12065 else if (t1->kind == ck_aggr
12066 && TREE_CODE (t1->type) == ARRAY_TYPE
12067 && TREE_CODE (t2->type) == ARRAY_TYPE
12068 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12070 tree n1 = nelts_initialized_by_list_init (t1);
12071 tree n2 = nelts_initialized_by_list_init (t2);
12072 if (tree_int_cst_lt (n1, n2))
12073 return 1;
12074 else if (tree_int_cst_lt (n2, n1))
12075 return -1;
12076 /* The n1 == n2 case. */
12077 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
12078 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
12079 if (c1 && !c2)
12080 return -1;
12081 else if (!c1 && c2)
12082 return 1;
12083 else
12084 return 0;
12086 else
12088 /* For ambiguous or aggregate conversions, use the target type as
12089 a proxy for the conversion function. */
12090 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12091 return 0;
12094 /* We can just fall through here, after setting up
12095 FROM_TYPE1 and FROM_TYPE2. */
12096 from_type1 = t1->type;
12097 from_type2 = t2->type;
12099 else
12101 conversion *t1;
12102 conversion *t2;
12104 /* We're dealing with two standard conversion sequences.
12106 [over.ics.rank]
12108 Standard conversion sequence S1 is a better conversion
12109 sequence than standard conversion sequence S2 if
12111 --S1 is a proper subsequence of S2 (comparing the conversion
12112 sequences in the canonical form defined by _over.ics.scs_,
12113 excluding any Lvalue Transformation; the identity
12114 conversion sequence is considered to be a subsequence of
12115 any non-identity conversion sequence */
12117 t1 = ics1;
12118 while (t1->kind != ck_identity)
12119 t1 = next_conversion (t1);
12120 from_type1 = t1->type;
12122 t2 = ics2;
12123 while (t2->kind != ck_identity)
12124 t2 = next_conversion (t2);
12125 from_type2 = t2->type;
12128 /* One sequence can only be a subsequence of the other if they start with
12129 the same type. They can start with different types when comparing the
12130 second standard conversion sequence in two user-defined conversion
12131 sequences. */
12132 if (same_type_p (from_type1, from_type2))
12134 if (is_subseq (ics1, ics2))
12135 return 1;
12136 if (is_subseq (ics2, ics1))
12137 return -1;
12140 /* [over.ics.rank]
12142 Or, if not that,
12144 --the rank of S1 is better than the rank of S2 (by the rules
12145 defined below):
12147 Standard conversion sequences are ordered by their ranks: an Exact
12148 Match is a better conversion than a Promotion, which is a better
12149 conversion than a Conversion.
12151 Two conversion sequences with the same rank are indistinguishable
12152 unless one of the following rules applies:
12154 --A conversion that does not a convert a pointer, pointer to member,
12155 or std::nullptr_t to bool is better than one that does.
12157 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12158 so that we do not have to check it explicitly. */
12159 if (ics1->rank < ics2->rank)
12160 return 1;
12161 else if (ics2->rank < ics1->rank)
12162 return -1;
12164 to_type1 = ics1->type;
12165 to_type2 = ics2->type;
12167 /* A conversion from scalar arithmetic type to complex is worse than a
12168 conversion between scalar arithmetic types. */
12169 if (same_type_p (from_type1, from_type2)
12170 && ARITHMETIC_TYPE_P (from_type1)
12171 && ARITHMETIC_TYPE_P (to_type1)
12172 && ARITHMETIC_TYPE_P (to_type2)
12173 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12174 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12176 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12177 return -1;
12178 else
12179 return 1;
12183 /* A conversion in either direction between floating-point type FP1 and
12184 floating-point type FP2 is better than a conversion in the same
12185 direction between FP1 and arithmetic type T3 if
12186 - the floating-point conversion rank of FP1 is equal to the rank of
12187 FP2, and
12188 - T3 is not a floating-point type, or T3 is a floating-point type
12189 whose rank is not equal to the rank of FP1, or the floating-point
12190 conversion subrank of FP2 is greater than the subrank of T3. */
12191 tree fp1 = from_type1;
12192 tree fp2 = to_type1;
12193 tree fp3 = from_type2;
12194 tree t3 = to_type2;
12195 int ret = 1;
12196 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12198 std::swap (fp1, fp2);
12199 std::swap (fp3, t3);
12201 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12202 && TREE_CODE (fp1) == REAL_TYPE
12203 /* Only apply this rule if at least one of the 3 types is
12204 extended floating-point type, otherwise keep them as
12205 before for compatibility reasons with types like __float128.
12206 float, double and long double alone have different conversion
12207 ranks and so when just those 3 types are involved, this
12208 rule doesn't trigger. */
12209 && (extended_float_type_p (fp1)
12210 || (TREE_CODE (fp2) == REAL_TYPE && extended_float_type_p (fp2))
12211 || (TREE_CODE (t3) == REAL_TYPE && extended_float_type_p (t3))))
12213 if (TREE_CODE (fp2) != REAL_TYPE)
12215 ret = -ret;
12216 std::swap (fp2, t3);
12218 if (TREE_CODE (fp2) == REAL_TYPE)
12220 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12221 if the conversion rank is equal (-1 or 1 if the subrank is
12222 different). */
12223 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12224 fp2),
12225 -1, 1))
12227 /* Conversion ranks of FP1 and FP2 are equal. */
12228 if (TREE_CODE (t3) != REAL_TYPE
12229 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12230 (fp1, t3),
12231 -1, 1))
12232 /* FP1 <-> FP2 conversion is better. */
12233 return ret;
12234 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12235 gcc_assert (IN_RANGE (c, -1, 1));
12236 if (c == 1)
12237 /* Conversion subrank of FP2 is greater than subrank of T3.
12238 FP1 <-> FP2 conversion is better. */
12239 return ret;
12240 else if (c == -1)
12241 /* Conversion subrank of FP2 is less than subrank of T3.
12242 FP1 <-> T3 conversion is better. */
12243 return -ret;
12245 else if (TREE_CODE (t3) == REAL_TYPE
12246 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12247 (fp1, t3),
12248 -1, 1))
12249 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12250 ranks of FP1 and T3 are equal.
12251 FP1 <-> T3 conversion is better. */
12252 return -ret;
12257 if (TYPE_PTR_P (from_type1)
12258 && TYPE_PTR_P (from_type2)
12259 && TYPE_PTR_P (to_type1)
12260 && TYPE_PTR_P (to_type2))
12262 deref_from_type1 = TREE_TYPE (from_type1);
12263 deref_from_type2 = TREE_TYPE (from_type2);
12264 deref_to_type1 = TREE_TYPE (to_type1);
12265 deref_to_type2 = TREE_TYPE (to_type2);
12267 /* The rules for pointers to members A::* are just like the rules
12268 for pointers A*, except opposite: if B is derived from A then
12269 A::* converts to B::*, not vice versa. For that reason, we
12270 switch the from_ and to_ variables here. */
12271 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12272 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12273 || (TYPE_PTRMEMFUNC_P (from_type1)
12274 && TYPE_PTRMEMFUNC_P (from_type2)
12275 && TYPE_PTRMEMFUNC_P (to_type1)
12276 && TYPE_PTRMEMFUNC_P (to_type2)))
12278 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12279 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12280 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12281 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12284 if (deref_from_type1 != NULL_TREE
12285 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12286 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12288 /* This was one of the pointer or pointer-like conversions.
12290 [over.ics.rank]
12292 --If class B is derived directly or indirectly from class A,
12293 conversion of B* to A* is better than conversion of B* to
12294 void*, and conversion of A* to void* is better than
12295 conversion of B* to void*. */
12296 if (VOID_TYPE_P (deref_to_type1)
12297 && VOID_TYPE_P (deref_to_type2))
12299 if (is_properly_derived_from (deref_from_type1,
12300 deref_from_type2))
12301 return -1;
12302 else if (is_properly_derived_from (deref_from_type2,
12303 deref_from_type1))
12304 return 1;
12306 else if (VOID_TYPE_P (deref_to_type1)
12307 || VOID_TYPE_P (deref_to_type2))
12309 if (same_type_p (deref_from_type1, deref_from_type2))
12311 if (VOID_TYPE_P (deref_to_type2))
12313 if (is_properly_derived_from (deref_from_type1,
12314 deref_to_type1))
12315 return 1;
12317 /* We know that DEREF_TO_TYPE1 is `void' here. */
12318 else if (is_properly_derived_from (deref_from_type1,
12319 deref_to_type2))
12320 return -1;
12323 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12324 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12326 /* [over.ics.rank]
12328 --If class B is derived directly or indirectly from class A
12329 and class C is derived directly or indirectly from B,
12331 --conversion of C* to B* is better than conversion of C* to
12334 --conversion of B* to A* is better than conversion of C* to
12335 A* */
12336 if (same_type_p (deref_from_type1, deref_from_type2))
12338 if (is_properly_derived_from (deref_to_type1,
12339 deref_to_type2))
12340 return 1;
12341 else if (is_properly_derived_from (deref_to_type2,
12342 deref_to_type1))
12343 return -1;
12345 else if (same_type_p (deref_to_type1, deref_to_type2))
12347 if (is_properly_derived_from (deref_from_type2,
12348 deref_from_type1))
12349 return 1;
12350 else if (is_properly_derived_from (deref_from_type1,
12351 deref_from_type2))
12352 return -1;
12356 else if (CLASS_TYPE_P (non_reference (from_type1))
12357 && same_type_p (from_type1, from_type2))
12359 tree from = non_reference (from_type1);
12361 /* [over.ics.rank]
12363 --binding of an expression of type C to a reference of type
12364 B& is better than binding an expression of type C to a
12365 reference of type A&
12367 --conversion of C to B is better than conversion of C to A, */
12368 if (is_properly_derived_from (from, to_type1)
12369 && is_properly_derived_from (from, to_type2))
12371 if (is_properly_derived_from (to_type1, to_type2))
12372 return 1;
12373 else if (is_properly_derived_from (to_type2, to_type1))
12374 return -1;
12377 else if (CLASS_TYPE_P (non_reference (to_type1))
12378 && same_type_p (to_type1, to_type2))
12380 tree to = non_reference (to_type1);
12382 /* [over.ics.rank]
12384 --binding of an expression of type B to a reference of type
12385 A& is better than binding an expression of type C to a
12386 reference of type A&,
12388 --conversion of B to A is better than conversion of C to A */
12389 if (is_properly_derived_from (from_type1, to)
12390 && is_properly_derived_from (from_type2, to))
12392 if (is_properly_derived_from (from_type2, from_type1))
12393 return 1;
12394 else if (is_properly_derived_from (from_type1, from_type2))
12395 return -1;
12399 /* [over.ics.rank]
12401 --S1 and S2 differ only in their qualification conversion and yield
12402 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12403 qualification signature of type T1 is a proper subset of the cv-
12404 qualification signature of type T2 */
12405 if (ics1->kind == ck_qual
12406 && ics2->kind == ck_qual
12407 && same_type_p (from_type1, from_type2))
12409 int result = comp_cv_qual_signature (to_type1, to_type2);
12410 if (result != 0)
12411 return result;
12414 /* [over.ics.rank]
12416 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12417 to an implicit object parameter of a non-static member function
12418 declared without a ref-qualifier, and either S1 binds an lvalue
12419 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12420 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12421 draft standard, 13.3.3.2)
12423 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12424 types to which the references refer are the same type except for
12425 top-level cv-qualifiers, and the type to which the reference
12426 initialized by S2 refers is more cv-qualified than the type to
12427 which the reference initialized by S1 refers.
12429 DR 1328 [over.match.best]: the context is an initialization by
12430 conversion function for direct reference binding (13.3.1.6) of a
12431 reference to function type, the return type of F1 is the same kind of
12432 reference (i.e. lvalue or rvalue) as the reference being initialized,
12433 and the return type of F2 is not. */
12435 if (ref_conv1 && ref_conv2)
12437 if (!ref_conv1->this_p && !ref_conv2->this_p
12438 && (ref_conv1->rvaluedness_matches_p
12439 != ref_conv2->rvaluedness_matches_p)
12440 && (same_type_p (ref_conv1->type, ref_conv2->type)
12441 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12442 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12444 if (ref_conv1->bad_p
12445 && !same_type_p (TREE_TYPE (ref_conv1->type),
12446 TREE_TYPE (ref_conv2->type)))
12447 /* Don't prefer a bad conversion that drops cv-quals to a bad
12448 conversion with the wrong rvalueness. */
12449 return 0;
12450 return (ref_conv1->rvaluedness_matches_p
12451 - ref_conv2->rvaluedness_matches_p);
12454 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12456 /* Per P0388R4:
12458 void f (int(&)[]), // (1)
12459 f (int(&)[1]), // (2)
12460 f (int*); // (3)
12462 (2) is better than (1), but (3) should be equal to (1) and to
12463 (2). For that reason we don't use ck_qual for (1) which would
12464 give it the cr_exact rank while (3) remains ck_identity.
12465 Therefore we compare (1) and (2) here. For (1) we'll have
12467 ck_ref_bind <- ck_identity
12468 int[] & int[1]
12470 so to handle this we must look at ref_conv. */
12471 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12472 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12473 if (c1 && !c2)
12474 return -1;
12475 else if (!c1 && c2)
12476 return 1;
12478 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12479 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12480 if (ref_conv1->bad_p)
12482 /* Prefer the one that drops fewer cv-quals. */
12483 tree ftype = next_conversion (ref_conv1)->type;
12484 int fquals = cp_type_quals (ftype);
12485 q1 ^= fquals;
12486 q2 ^= fquals;
12488 return comp_cv_qualification (q2, q1);
12492 /* [over.ics.rank]
12494 Per CWG 1601:
12495 -- A conversion that promotes an enumeration whose underlying type
12496 is fixed to its underlying type is better than one that promotes to
12497 the promoted underlying type, if the two are different. */
12498 if (ics1->rank == cr_promotion
12499 && ics2->rank == cr_promotion
12500 && UNSCOPED_ENUM_P (from_type1)
12501 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12502 && same_type_p (from_type1, from_type2))
12504 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12505 tree prom = type_promotes_to (from_type1);
12506 if (!same_type_p (utype, prom))
12508 if (same_type_p (to_type1, utype)
12509 && same_type_p (to_type2, prom))
12510 return 1;
12511 else if (same_type_p (to_type2, utype)
12512 && same_type_p (to_type1, prom))
12513 return -1;
12517 /* Neither conversion sequence is better than the other. */
12518 return 0;
12521 /* The source type for this standard conversion sequence. */
12523 static tree
12524 source_type (conversion *t)
12526 return strip_standard_conversion (t)->type;
12529 /* Note a warning about preferring WINNER to LOSER. We do this by storing
12530 a pointer to LOSER and re-running joust to produce the warning if WINNER
12531 is actually used. */
12533 static void
12534 add_warning (struct z_candidate *winner, struct z_candidate *loser)
12536 candidate_warning *cw = (candidate_warning *)
12537 conversion_obstack_alloc (sizeof (candidate_warning));
12538 cw->loser = loser;
12539 cw->next = winner->warnings;
12540 winner->warnings = cw;
12543 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12544 prvalue returned from a conversion function, replace CAND with the candidate
12545 for the conversion and return true. Otherwise, return false. */
12547 static bool
12548 joust_maybe_elide_copy (z_candidate *&cand)
12550 tree fn = cand->fn;
12551 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12552 return false;
12553 conversion *conv = cand->convs[0];
12554 if (conv->kind == ck_ambig)
12555 return false;
12556 gcc_checking_assert (conv->kind == ck_ref_bind);
12557 conv = next_conversion (conv);
12558 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12560 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12561 (conv->type, DECL_CONTEXT (fn)));
12562 z_candidate *uc = conv->cand;
12563 if (DECL_CONV_FN_P (uc->fn))
12565 cand = uc;
12566 return true;
12569 return false;
12572 /* True if the defining declarations of the two candidates have equivalent
12573 parameters. */
12575 static bool
12576 cand_parms_match (z_candidate *c1, z_candidate *c2)
12578 tree fn1 = c1->fn;
12579 tree fn2 = c2->fn;
12580 if (fn1 == fn2)
12581 return true;
12582 if (identifier_p (fn1) || identifier_p (fn2))
12583 return false;
12584 /* We don't look at c1->template_decl because that's only set for primary
12585 templates, not e.g. non-template member functions of class templates. */
12586 tree t1 = most_general_template (fn1);
12587 tree t2 = most_general_template (fn2);
12588 if (t1 || t2)
12590 if (!t1 || !t2)
12591 return false;
12592 if (t1 == t2)
12593 return true;
12594 fn1 = DECL_TEMPLATE_RESULT (t1);
12595 fn2 = DECL_TEMPLATE_RESULT (t2);
12597 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12598 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12599 if (DECL_FUNCTION_MEMBER_P (fn1)
12600 && DECL_FUNCTION_MEMBER_P (fn2)
12601 && (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn1)
12602 != DECL_NONSTATIC_MEMBER_FUNCTION_P (fn2)))
12604 /* Ignore 'this' when comparing the parameters of a static member
12605 function with those of a non-static one. */
12606 parms1 = skip_artificial_parms_for (fn1, parms1);
12607 parms2 = skip_artificial_parms_for (fn2, parms2);
12609 return compparms (parms1, parms2);
12612 /* Compare two candidates for overloading as described in
12613 [over.match.best]. Return values:
12615 1: cand1 is better than cand2
12616 -1: cand2 is better than cand1
12617 0: cand1 and cand2 are indistinguishable */
12619 static int
12620 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12621 tsubst_flags_t complain)
12623 int winner = 0;
12624 int off1 = 0, off2 = 0;
12625 size_t i;
12626 size_t len;
12628 /* Candidates that involve bad conversions are always worse than those
12629 that don't. */
12630 if (cand1->viable > cand2->viable)
12631 return 1;
12632 if (cand1->viable < cand2->viable)
12633 return -1;
12635 /* If we have two pseudo-candidates for conversions to the same type,
12636 or two candidates for the same function, arbitrarily pick one. */
12637 if (cand1->fn == cand2->fn
12638 && cand1->reversed () == cand2->reversed ()
12639 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12640 return 1;
12642 /* Prefer a non-deleted function over an implicitly deleted move
12643 constructor or assignment operator. This differs slightly from the
12644 wording for issue 1402 (which says the move op is ignored by overload
12645 resolution), but this way produces better error messages. */
12646 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12647 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12648 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12650 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12651 && move_fn_p (cand1->fn))
12652 return -1;
12653 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12654 && move_fn_p (cand2->fn))
12655 return 1;
12658 /* a viable function F1
12659 is defined to be a better function than another viable function F2 if
12660 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12661 ICSi(F2), and then */
12663 /* for some argument j, ICSj(F1) is a better conversion sequence than
12664 ICSj(F2) */
12666 /* For comparing static and non-static member functions, we ignore
12667 the implicit object parameter of the non-static function. The
12668 standard says to pretend that the static function has an object
12669 parm, but that won't work with operator overloading. */
12670 len = cand1->num_convs;
12671 if (len != cand2->num_convs)
12673 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12674 && DECL_STATIC_FUNCTION_P (cand1->fn));
12675 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12676 && DECL_STATIC_FUNCTION_P (cand2->fn));
12678 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12679 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12680 && DECL_CONSTRUCTOR_P (cand1->fn)
12681 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12682 /* We're comparing a near-match list constructor and a near-match
12683 non-list constructor. Just treat them as unordered. */
12684 return 0;
12686 gcc_assert (static_1 != static_2);
12688 if (static_1)
12690 /* C++23 [over.best.ics.general] says:
12691 When the parameter is the implicit object parameter of a static
12692 member function, the implicit conversion sequence is a standard
12693 conversion sequence that is neither better nor worse than any
12694 other standard conversion sequence. */
12695 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12696 winner = 1;
12697 off2 = 1;
12699 else
12701 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12702 winner = -1;
12703 off1 = 1;
12704 --len;
12708 /* Handle C++17 copy elision in [over.match.ctor] (direct-init) context. The
12709 standard currently says that only constructors are candidates, but if one
12710 copies a prvalue returned by a conversion function we want to treat the
12711 conversion as the candidate instead.
12713 Clang does something similar, as discussed at
12714 http://lists.isocpp.org/core/2017/10/3166.php
12715 http://lists.isocpp.org/core/2019/03/5721.php */
12716 int elided_tiebreaker = 0;
12717 if (len == 1 && cxx_dialect >= cxx17
12718 && DECL_P (cand1->fn)
12719 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
12720 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
12722 bool elided1 = joust_maybe_elide_copy (cand1);
12723 bool elided2 = joust_maybe_elide_copy (cand2);
12724 /* As a tiebreaker below we will prefer a constructor to a conversion
12725 operator exposed this way. */
12726 elided_tiebreaker = elided2 - elided1;
12729 for (i = 0; i < len; ++i)
12731 conversion *t1 = cand1->convs[i + off1];
12732 conversion *t2 = cand2->convs[i + off2];
12733 int comp = compare_ics (t1, t2);
12735 if (comp != 0)
12737 if ((complain & tf_warning)
12738 && warn_sign_promo
12739 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12740 == cr_std + cr_promotion)
12741 && t1->kind == ck_std
12742 && t2->kind == ck_std
12743 && TREE_CODE (t1->type) == INTEGER_TYPE
12744 && TREE_CODE (t2->type) == INTEGER_TYPE
12745 && (TYPE_PRECISION (t1->type)
12746 == TYPE_PRECISION (t2->type))
12747 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12748 || (TREE_CODE (next_conversion (t1)->type)
12749 == ENUMERAL_TYPE)))
12751 tree type = next_conversion (t1)->type;
12752 tree type1, type2;
12753 struct z_candidate *w, *l;
12754 if (comp > 0)
12755 type1 = t1->type, type2 = t2->type,
12756 w = cand1, l = cand2;
12757 else
12758 type1 = t2->type, type2 = t1->type,
12759 w = cand2, l = cand1;
12761 if (warn)
12763 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12764 type, type1, type2);
12765 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12767 else
12768 add_warning (w, l);
12771 if (winner && comp != winner)
12773 /* Ambiguity between normal and reversed comparison operators
12774 with the same parameter types. P2468 decided not to go with
12775 this approach to resolving the ambiguity, so pedwarn. */
12776 if ((complain & tf_warning_or_error)
12777 && (cand1->reversed () != cand2->reversed ())
12778 && cand_parms_match (cand1, cand2))
12780 struct z_candidate *w, *l;
12781 if (cand2->reversed ())
12782 winner = 1, w = cand1, l = cand2;
12783 else
12784 winner = -1, w = cand2, l = cand1;
12785 if (warn)
12787 auto_diagnostic_group d;
12788 if (pedwarn (input_location, 0,
12789 "C++20 says that these are ambiguous, "
12790 "even though the second is reversed:"))
12792 print_z_candidate (input_location,
12793 N_("candidate 1:"), w);
12794 print_z_candidate (input_location,
12795 N_("candidate 2:"), l);
12796 if (w->fn == l->fn
12797 && DECL_NONSTATIC_MEMBER_FUNCTION_P (w->fn)
12798 && (type_memfn_quals (TREE_TYPE (w->fn))
12799 & TYPE_QUAL_CONST) == 0)
12801 /* Suggest adding const to
12802 struct A { bool operator==(const A&); }; */
12803 tree parmtype
12804 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
12805 parmtype = TREE_VALUE (parmtype);
12806 if (TYPE_REF_P (parmtype)
12807 && TYPE_READONLY (TREE_TYPE (parmtype))
12808 && (same_type_ignoring_top_level_qualifiers_p
12809 (TREE_TYPE (parmtype),
12810 DECL_CONTEXT (w->fn))))
12811 inform (DECL_SOURCE_LOCATION (w->fn),
12812 "try making the operator a %<const%> "
12813 "member function");
12817 else
12818 add_warning (w, l);
12819 return winner;
12822 winner = 0;
12823 goto tweak;
12825 winner = comp;
12829 /* warn about confusing overload resolution for user-defined conversions,
12830 either between a constructor and a conversion op, or between two
12831 conversion ops. */
12832 if ((complain & tf_warning)
12833 /* In C++17, the constructor might have been elided, which means that
12834 an originally null ->second_conv could become non-null. */
12835 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12836 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12837 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
12839 struct z_candidate *w, *l;
12840 bool give_warning = false;
12842 if (winner == 1)
12843 w = cand1, l = cand2;
12844 else
12845 w = cand2, l = cand1;
12847 /* We don't want to complain about `X::operator T1 ()'
12848 beating `X::operator T2 () const', when T2 is a no less
12849 cv-qualified version of T1. */
12850 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12851 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12853 tree t = TREE_TYPE (TREE_TYPE (l->fn));
12854 tree f = TREE_TYPE (TREE_TYPE (w->fn));
12856 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12858 t = TREE_TYPE (t);
12859 f = TREE_TYPE (f);
12861 if (!comp_ptr_ttypes (t, f))
12862 give_warning = true;
12864 else
12865 give_warning = true;
12867 if (!give_warning)
12868 /*NOP*/;
12869 else if (warn)
12871 tree source = source_type (w->convs[0]);
12872 if (INDIRECT_TYPE_P (source))
12873 source = TREE_TYPE (source);
12874 auto_diagnostic_group d;
12875 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12876 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
12877 source, w->second_conv->type))
12879 inform (input_location, " because conversion sequence "
12880 "for the argument is better");
12883 else
12884 add_warning (w, l);
12887 if (winner)
12888 return winner;
12890 /* Put this tiebreaker first, so that we don't try to look at second_conv of
12891 a constructor candidate that doesn't have one. */
12892 if (elided_tiebreaker)
12893 return elided_tiebreaker;
12895 /* DR 495 moved this tiebreaker above the template ones. */
12896 /* or, if not that,
12897 the context is an initialization by user-defined conversion (see
12898 _dcl.init_ and _over.match.user_) and the standard conversion
12899 sequence from the return type of F1 to the destination type (i.e.,
12900 the type of the entity being initialized) is a better conversion
12901 sequence than the standard conversion sequence from the return type
12902 of F2 to the destination type. */
12904 if (cand1->second_conv)
12906 winner = compare_ics (cand1->second_conv, cand2->second_conv);
12907 if (winner)
12908 return winner;
12911 /* or, if not that,
12912 F1 is a non-template function and F2 is a template function
12913 specialization. */
12915 if (!cand1->template_decl && cand2->template_decl)
12916 return 1;
12917 else if (cand1->template_decl && !cand2->template_decl)
12918 return -1;
12920 /* or, if not that,
12921 F1 and F2 are template functions and the function template for F1 is
12922 more specialized than the template for F2 according to the partial
12923 ordering rules. */
12925 if (cand1->template_decl && cand2->template_decl)
12927 winner = more_specialized_fn
12928 (TI_TEMPLATE (cand1->template_decl),
12929 TI_TEMPLATE (cand2->template_decl),
12930 /* [temp.func.order]: The presence of unused ellipsis and default
12931 arguments has no effect on the partial ordering of function
12932 templates. add_function_candidate() will not have
12933 counted the "this" argument for constructors. */
12934 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
12935 if (winner)
12936 return winner;
12939 /* Concepts: F1 and F2 are non-template functions with the same
12940 parameter-type-lists, and F1 is more constrained than F2 according to the
12941 partial ordering of constraints described in 13.5.4. */
12943 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
12944 && !cand1->template_decl && !cand2->template_decl
12945 && cand_parms_match (cand1, cand2))
12947 winner = more_constrained (cand1->fn, cand2->fn);
12948 if (winner)
12949 return winner;
12952 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
12953 rewritten candidates, and F2 is a synthesized candidate with reversed
12954 order of parameters and F1 is not. */
12955 if (cand1->rewritten ())
12957 if (!cand2->rewritten ())
12958 return -1;
12959 if (!cand1->reversed () && cand2->reversed ())
12960 return 1;
12961 if (cand1->reversed () && !cand2->reversed ())
12962 return -1;
12964 else if (cand2->rewritten ())
12965 return 1;
12967 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
12968 if (deduction_guide_p (cand1->fn))
12970 gcc_assert (deduction_guide_p (cand2->fn));
12971 /* We distinguish between candidates from an explicit deduction guide and
12972 candidates built from a constructor based on DECL_ARTIFICIAL. */
12973 int art1 = DECL_ARTIFICIAL (cand1->fn);
12974 int art2 = DECL_ARTIFICIAL (cand2->fn);
12975 if (art1 != art2)
12976 return art2 - art1;
12978 if (art1)
12980 /* Prefer the special copy guide over a declared copy/move
12981 constructor. */
12982 if (copy_guide_p (cand1->fn))
12983 return 1;
12984 if (copy_guide_p (cand2->fn))
12985 return -1;
12987 /* Prefer a candidate generated from a non-template constructor. */
12988 int tg1 = template_guide_p (cand1->fn);
12989 int tg2 = template_guide_p (cand2->fn);
12990 if (tg1 != tg2)
12991 return tg2 - tg1;
12995 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
12996 for all arguments the corresponding parameters of F1 and F2 have the same
12997 type (CWG 2273/2277). */
12998 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
12999 && !DECL_CONV_FN_P (cand1->fn)
13000 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
13001 && !DECL_CONV_FN_P (cand2->fn))
13003 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13004 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13006 bool used1 = false;
13007 bool used2 = false;
13008 if (base1 == base2)
13009 /* No difference. */;
13010 else if (DERIVED_FROM_P (base1, base2))
13011 used1 = true;
13012 else if (DERIVED_FROM_P (base2, base1))
13013 used2 = true;
13015 if (int diff = used2 - used1)
13017 for (i = 0; i < len; ++i)
13019 conversion *t1 = cand1->convs[i + off1];
13020 conversion *t2 = cand2->convs[i + off2];
13021 if (!same_type_p (t1->type, t2->type))
13022 break;
13024 if (i == len)
13025 return diff;
13029 /* Check whether we can discard a builtin candidate, either because we
13030 have two identical ones or matching builtin and non-builtin candidates.
13032 (Pedantically in the latter case the builtin which matched the user
13033 function should not be added to the overload set, but we spot it here.
13035 [over.match.oper]
13036 ... the builtin candidates include ...
13037 - do not have the same parameter type list as any non-template
13038 non-member candidate. */
13040 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
13042 for (i = 0; i < len; ++i)
13043 if (!same_type_p (cand1->convs[i]->type,
13044 cand2->convs[i]->type))
13045 break;
13046 if (i == cand1->num_convs)
13048 if (cand1->fn == cand2->fn)
13049 /* Two built-in candidates; arbitrarily pick one. */
13050 return 1;
13051 else if (identifier_p (cand1->fn))
13052 /* cand1 is built-in; prefer cand2. */
13053 return -1;
13054 else
13055 /* cand2 is built-in; prefer cand1. */
13056 return 1;
13060 /* For candidates of a multi-versioned function, make the version with
13061 the highest priority win. This version will be checked for dispatching
13062 first. If this version can be inlined into the caller, the front-end
13063 will simply make a direct call to this function. */
13065 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13066 && DECL_FUNCTION_VERSIONED (cand1->fn)
13067 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13068 && DECL_FUNCTION_VERSIONED (cand2->fn))
13070 tree f1 = TREE_TYPE (cand1->fn);
13071 tree f2 = TREE_TYPE (cand2->fn);
13072 tree p1 = TYPE_ARG_TYPES (f1);
13073 tree p2 = TYPE_ARG_TYPES (f2);
13075 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13076 is possible that cand1->fn and cand2->fn are function versions but of
13077 different functions. Check types to see if they are versions of the same
13078 function. */
13079 if (compparms (p1, p2)
13080 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13082 /* Always make the version with the higher priority, more
13083 specialized, win. */
13084 gcc_assert (targetm.compare_version_priority);
13085 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13086 return 1;
13087 else
13088 return -1;
13092 /* If the two function declarations represent the same function (this can
13093 happen with declarations in multiple scopes and arg-dependent lookup),
13094 arbitrarily choose one. But first make sure the default args we're
13095 using match. */
13096 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13097 && equal_functions (cand1->fn, cand2->fn))
13099 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13100 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13102 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13104 for (i = 0; i < len; ++i)
13106 /* Don't crash if the fn is variadic. */
13107 if (!parms1)
13108 break;
13109 parms1 = TREE_CHAIN (parms1);
13110 parms2 = TREE_CHAIN (parms2);
13113 if (off1)
13114 parms1 = TREE_CHAIN (parms1);
13115 else if (off2)
13116 parms2 = TREE_CHAIN (parms2);
13118 for (; parms1; ++i)
13120 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13121 TREE_PURPOSE (parms2)))
13123 if (warn)
13125 if (complain & tf_error)
13127 auto_diagnostic_group d;
13128 if (permerror (input_location,
13129 "default argument mismatch in "
13130 "overload resolution"))
13132 inform (DECL_SOURCE_LOCATION (cand1->fn),
13133 " candidate 1: %q#F", cand1->fn);
13134 inform (DECL_SOURCE_LOCATION (cand2->fn),
13135 " candidate 2: %q#F", cand2->fn);
13138 else
13139 return 0;
13141 else
13142 add_warning (cand1, cand2);
13143 break;
13145 parms1 = TREE_CHAIN (parms1);
13146 parms2 = TREE_CHAIN (parms2);
13149 return 1;
13152 tweak:
13154 /* Extension: If the worst conversion for one candidate is better than the
13155 worst conversion for the other, take the first. */
13156 if (!pedantic && (complain & tf_warning_or_error))
13158 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13159 struct z_candidate *w = 0, *l = 0;
13161 for (i = 0; i < len; ++i)
13163 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13164 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13165 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13166 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13168 if (rank1 < rank2)
13169 winner = 1, w = cand1, l = cand2;
13170 if (rank1 > rank2)
13171 winner = -1, w = cand2, l = cand1;
13172 if (winner)
13174 /* Don't choose a deleted function over ambiguity. */
13175 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13176 return 0;
13177 if (warn)
13179 auto_diagnostic_group d;
13180 if (pedwarn (input_location, 0,
13181 "ISO C++ says that these are ambiguous, even "
13182 "though the worst conversion for the first is "
13183 "better than the worst conversion for the second:"))
13185 print_z_candidate (input_location, N_("candidate 1:"), w);
13186 print_z_candidate (input_location, N_("candidate 2:"), l);
13189 else
13190 add_warning (w, l);
13191 return winner;
13195 gcc_assert (!winner);
13196 return 0;
13199 /* Given a list of candidates for overloading, find the best one, if any.
13200 This algorithm has a worst case of O(2n) (winner is last), and a best
13201 case of O(n/2) (totally ambiguous); much better than a sorting
13202 algorithm. */
13204 static struct z_candidate *
13205 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13207 struct z_candidate *champ = candidates, *challenger;
13208 int fate;
13209 struct z_candidate *champ_compared_to_predecessor = nullptr;
13211 /* Walk through the list once, comparing each current champ to the next
13212 candidate, knocking out a candidate or two with each comparison. */
13214 for (challenger = champ->next; challenger; )
13216 fate = joust (champ, challenger, 0, complain);
13217 if (fate == 1)
13218 challenger = challenger->next;
13219 else
13221 if (fate == 0)
13223 champ = challenger->next;
13224 if (champ == 0)
13225 return NULL;
13226 champ_compared_to_predecessor = nullptr;
13228 else
13230 champ_compared_to_predecessor = champ;
13231 champ = challenger;
13234 challenger = champ->next;
13238 /* Make sure the champ is better than all the candidates it hasn't yet
13239 been compared to. */
13241 for (challenger = candidates;
13242 challenger != champ
13243 && challenger != champ_compared_to_predecessor;
13244 challenger = challenger->next)
13246 fate = joust (champ, challenger, 0, complain);
13247 if (fate != 1)
13248 return NULL;
13251 return champ;
13254 /* Returns nonzero if things of type FROM can be converted to TO. */
13256 bool
13257 can_convert (tree to, tree from, tsubst_flags_t complain)
13259 tree arg = NULL_TREE;
13260 /* implicit_conversion only considers user-defined conversions
13261 if it has an expression for the call argument list. */
13262 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13263 arg = build_stub_object (from);
13264 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13267 /* Returns nonzero if things of type FROM can be converted to TO with a
13268 standard conversion. */
13270 bool
13271 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13273 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13276 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13278 bool
13279 can_convert_arg (tree to, tree from, tree arg, int flags,
13280 tsubst_flags_t complain)
13282 conversion *t;
13283 void *p;
13284 bool ok_p;
13286 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13287 p = conversion_obstack_alloc (0);
13288 /* We want to discard any access checks done for this test,
13289 as we might not be in the appropriate access context and
13290 we'll do the check again when we actually perform the
13291 conversion. */
13292 push_deferring_access_checks (dk_deferred);
13294 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13295 flags, complain);
13296 ok_p = (t && !t->bad_p);
13298 /* Discard the access checks now. */
13299 pop_deferring_access_checks ();
13300 /* Free all the conversions we allocated. */
13301 obstack_free (&conversion_obstack, p);
13303 return ok_p;
13306 /* Like can_convert_arg, but allows dubious conversions as well. */
13308 bool
13309 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13310 tsubst_flags_t complain)
13312 conversion *t;
13313 void *p;
13315 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13316 p = conversion_obstack_alloc (0);
13317 /* Try to perform the conversion. */
13318 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13319 flags, complain);
13320 /* Free all the conversions we allocated. */
13321 obstack_free (&conversion_obstack, p);
13323 return t != NULL;
13326 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13327 resolution FLAGS. */
13329 tree
13330 build_implicit_conv_flags (tree type, tree expr, int flags)
13332 /* In a template, we are only concerned about determining the
13333 type of non-dependent expressions, so we do not have to
13334 perform the actual conversion. But for initializers, we
13335 need to be able to perform it at instantiation
13336 (or instantiate_non_dependent_expr) time. */
13337 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13338 if (!(flags & LOOKUP_ONLYCONVERTING))
13339 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13340 if (flags & LOOKUP_NO_NARROWING)
13341 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13342 return expr;
13345 /* Convert EXPR to TYPE. Return the converted expression.
13347 Note that we allow bad conversions here because by the time we get to
13348 this point we are committed to doing the conversion. If we end up
13349 doing a bad conversion, convert_like will complain. */
13351 tree
13352 perform_implicit_conversion_flags (tree type, tree expr,
13353 tsubst_flags_t complain, int flags)
13355 conversion *conv;
13356 void *p;
13357 location_t loc = cp_expr_loc_or_input_loc (expr);
13359 if (TYPE_REF_P (type))
13360 expr = mark_lvalue_use (expr);
13361 else
13362 expr = mark_rvalue_use (expr);
13364 if (error_operand_p (expr))
13365 return error_mark_node;
13367 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13368 p = conversion_obstack_alloc (0);
13370 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13371 /*c_cast_p=*/false,
13372 flags, complain);
13374 if (!conv)
13376 if (complain & tf_error)
13377 implicit_conversion_error (loc, type, expr);
13378 expr = error_mark_node;
13380 else if (processing_template_decl && conv->kind != ck_identity)
13381 expr = build_implicit_conv_flags (type, expr, flags);
13382 else
13384 /* Give a conversion call the same location as expr. */
13385 iloc_sentinel il (loc);
13386 expr = convert_like (conv, expr, complain);
13389 /* Free all the conversions we allocated. */
13390 obstack_free (&conversion_obstack, p);
13392 return expr;
13395 tree
13396 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13398 return perform_implicit_conversion_flags (type, expr, complain,
13399 LOOKUP_IMPLICIT);
13402 /* Convert EXPR to TYPE (as a direct-initialization) if that is
13403 permitted. If the conversion is valid, the converted expression is
13404 returned. Otherwise, NULL_TREE is returned, except in the case
13405 that TYPE is a class type; in that case, an error is issued. If
13406 C_CAST_P is true, then this direct-initialization is taking
13407 place as part of a static_cast being attempted as part of a C-style
13408 cast. */
13410 tree
13411 perform_direct_initialization_if_possible (tree type,
13412 tree expr,
13413 bool c_cast_p,
13414 tsubst_flags_t complain)
13416 conversion *conv;
13417 void *p;
13419 if (type == error_mark_node || error_operand_p (expr))
13420 return error_mark_node;
13421 /* [dcl.init]
13423 If the destination type is a (possibly cv-qualified) class type:
13425 -- If the initialization is direct-initialization ...,
13426 constructors are considered.
13428 -- If overload resolution is successful, the selected constructor
13429 is called to initialize the object, with the initializer expression
13430 or expression-list as its argument(s).
13432 -- Otherwise, if no constructor is viable, the destination type is
13433 a (possibly cv-qualified) aggregate class A, and the initializer is
13434 a parenthesized expression-list, the object is initialized as
13435 follows... */
13436 if (CLASS_TYPE_P (type))
13438 releasing_vec args (make_tree_vector_single (expr));
13439 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13440 &args, type, LOOKUP_NORMAL, complain);
13441 return build_cplus_new (type, expr, complain);
13444 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13445 p = conversion_obstack_alloc (0);
13447 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13448 c_cast_p,
13449 LOOKUP_NORMAL, complain);
13450 if (!conv || conv->bad_p)
13451 expr = NULL_TREE;
13452 else if (processing_template_decl && conv->kind != ck_identity)
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 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13462 else
13463 expr = convert_like (conv, expr, NULL_TREE, 0,
13464 /*issue_conversion_warnings=*/false,
13465 c_cast_p, /*nested_p=*/false, complain);
13467 /* Free all the conversions we allocated. */
13468 obstack_free (&conversion_obstack, p);
13470 return expr;
13473 /* When initializing a reference that lasts longer than a full-expression,
13474 this special rule applies:
13476 [class.temporary]
13478 The temporary to which the reference is bound or the temporary
13479 that is the complete object to which the reference is bound
13480 persists for the lifetime of the reference.
13482 The temporaries created during the evaluation of the expression
13483 initializing the reference, except the temporary to which the
13484 reference is bound, are destroyed at the end of the
13485 full-expression in which they are created.
13487 In that case, we store the converted expression into a new
13488 VAR_DECL in a new scope.
13490 However, we want to be careful not to create temporaries when
13491 they are not required. For example, given:
13493 struct B {};
13494 struct D : public B {};
13495 D f();
13496 const B& b = f();
13498 there is no need to copy the return value from "f"; we can just
13499 extend its lifetime. Similarly, given:
13501 struct S {};
13502 struct T { operator S(); };
13503 T t;
13504 const S& s = t;
13506 we can extend the lifetime of the return value of the conversion
13507 operator.
13509 The next several functions are involved in this lifetime extension. */
13511 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13512 reference is being bound to a temporary. Create and return a new
13513 VAR_DECL with the indicated TYPE; this variable will store the value to
13514 which the reference is bound. */
13516 tree
13517 make_temporary_var_for_ref_to_temp (tree decl, tree type)
13519 tree var = create_temporary_var (type);
13521 /* Register the variable. */
13522 if (VAR_P (decl)
13523 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13525 /* Namespace-scope or local static; give it a mangled name. */
13527 /* If an initializer is visible to multiple translation units, those
13528 translation units must agree on the addresses of the
13529 temporaries. Therefore the temporaries must be given a consistent name
13530 and vague linkage. The mangled name of a temporary is the name of the
13531 non-temporary object in whose initializer they appear, prefixed with
13532 GR and suffixed with a sequence number mangled using the usual rules
13533 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13534 left-to-right walk of the complete initializer. */
13535 copy_linkage (var, decl);
13537 tree name = mangle_ref_init_variable (decl);
13538 DECL_NAME (var) = name;
13539 SET_DECL_ASSEMBLER_NAME (var, name);
13541 else
13542 /* Create a new cleanup level if necessary. */
13543 maybe_push_cleanup_level (type);
13545 return pushdecl (var);
13548 /* EXPR is the initializer for a variable DECL of reference or
13549 std::initializer_list type. Create, push and return a new VAR_DECL
13550 for the initializer so that it will live as long as DECL. Any
13551 cleanup for the new variable is returned through CLEANUP, and the
13552 code to initialize the new variable is returned through INITP. */
13554 static tree
13555 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13556 tree *initp, tree *cond_guard)
13558 tree init;
13559 tree type;
13560 tree var;
13562 /* Create the temporary variable. */
13563 type = TREE_TYPE (expr);
13564 var = make_temporary_var_for_ref_to_temp (decl, type);
13565 layout_decl (var, 0);
13566 /* If the rvalue is the result of a function call it will be
13567 a TARGET_EXPR. If it is some other construct (such as a
13568 member access expression where the underlying object is
13569 itself the result of a function call), turn it into a
13570 TARGET_EXPR here. It is important that EXPR be a
13571 TARGET_EXPR below since otherwise the INIT_EXPR will
13572 attempt to make a bitwise copy of EXPR to initialize
13573 VAR. */
13574 if (TREE_CODE (expr) != TARGET_EXPR)
13575 expr = get_target_expr (expr);
13576 else if (TREE_ADDRESSABLE (expr))
13577 TREE_ADDRESSABLE (var) = 1;
13579 if (TREE_CODE (decl) == FIELD_DECL
13580 && extra_warnings && !warning_suppressed_p (decl))
13582 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13583 "until the constructor exits", decl);
13584 suppress_warning (decl);
13587 /* Recursively extend temps in this initializer. */
13588 TARGET_EXPR_INITIAL (expr)
13589 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13590 cond_guard);
13592 /* Any reference temp has a non-trivial initializer. */
13593 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13595 /* If the initializer is constant, put it in DECL_INITIAL so we get
13596 static initialization and use in constant expressions. */
13597 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13598 /* As in store_init_value. */
13599 init = cp_fully_fold (init);
13600 if (TREE_CONSTANT (init))
13602 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13604 /* 5.19 says that a constant expression can include an
13605 lvalue-rvalue conversion applied to "a glvalue of literal type
13606 that refers to a non-volatile temporary object initialized
13607 with a constant expression". Rather than try to communicate
13608 that this VAR_DECL is a temporary, just mark it constexpr. */
13609 DECL_DECLARED_CONSTEXPR_P (var) = true;
13610 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13611 TREE_CONSTANT (var) = true;
13612 TREE_READONLY (var) = true;
13614 DECL_INITIAL (var) = init;
13615 init = NULL_TREE;
13617 else
13618 /* Create the INIT_EXPR that will initialize the temporary
13619 variable. */
13620 init = split_nonconstant_init (var, expr);
13621 if (at_function_scope_p ())
13623 add_decl_expr (var);
13625 if (TREE_STATIC (var))
13626 init = add_stmt_to_compound (init, register_dtor_fn (var));
13627 else
13629 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13630 if (cleanup)
13632 if (cond_guard && cleanup != error_mark_node)
13634 if (*cond_guard == NULL_TREE)
13636 *cond_guard = build_local_temp (boolean_type_node);
13637 add_decl_expr (*cond_guard);
13638 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13639 *cond_guard, NOP_EXPR,
13640 boolean_false_node,
13641 tf_warning_or_error);
13642 finish_expr_stmt (set);
13644 cleanup = build3 (COND_EXPR, void_type_node,
13645 *cond_guard, cleanup, NULL_TREE);
13647 vec_safe_push (*cleanups, cleanup);
13651 /* We must be careful to destroy the temporary only
13652 after its initialization has taken place. If the
13653 initialization throws an exception, then the
13654 destructor should not be run. We cannot simply
13655 transform INIT into something like:
13657 (INIT, ({ CLEANUP_STMT; }))
13659 because emit_local_var always treats the
13660 initializer as a full-expression. Thus, the
13661 destructor would run too early; it would run at the
13662 end of initializing the reference variable, rather
13663 than at the end of the block enclosing the
13664 reference variable.
13666 The solution is to pass back a cleanup expression
13667 which the caller is responsible for attaching to
13668 the statement tree. */
13670 else
13672 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13673 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13675 if (CP_DECL_THREAD_LOCAL_P (var))
13676 tls_aggregates = tree_cons (NULL_TREE, var,
13677 tls_aggregates);
13678 else
13679 static_aggregates = tree_cons (NULL_TREE, var,
13680 static_aggregates);
13682 else
13683 /* Check whether the dtor is callable. */
13684 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13686 /* Avoid -Wunused-variable warning (c++/38958). */
13687 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13688 && VAR_P (decl))
13689 TREE_USED (decl) = DECL_READ_P (decl) = true;
13691 *initp = init;
13692 return var;
13695 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
13696 initializing a variable of that TYPE. */
13698 tree
13699 initialize_reference (tree type, tree expr,
13700 int flags, tsubst_flags_t complain)
13702 conversion *conv;
13703 void *p;
13704 location_t loc = cp_expr_loc_or_input_loc (expr);
13706 if (type == error_mark_node || error_operand_p (expr))
13707 return error_mark_node;
13709 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13710 p = conversion_obstack_alloc (0);
13712 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13713 flags, complain);
13714 /* If this conversion failed, we're in C++20, and we have something like
13715 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13716 if ((!conv || conv->bad_p)
13717 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13719 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13720 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13721 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13722 conversion *c = reference_binding (type, TREE_TYPE (e), e,
13723 /*c_cast_p=*/false, flags, complain);
13724 /* If this worked, use it. */
13725 if (c && !c->bad_p)
13726 expr = e, conv = c;
13728 if (!conv || conv->bad_p)
13730 if (complain & tf_error)
13732 if (conv)
13733 convert_like (conv, expr, complain);
13734 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13735 && !TYPE_REF_IS_RVALUE (type)
13736 && !lvalue_p (expr))
13737 error_at (loc, "invalid initialization of non-const reference of "
13738 "type %qH from an rvalue of type %qI",
13739 type, TREE_TYPE (expr));
13740 else
13741 error_at (loc, "invalid initialization of reference of type "
13742 "%qH from expression of type %qI", type,
13743 TREE_TYPE (expr));
13745 return error_mark_node;
13748 if (conv->kind == ck_ref_bind)
13749 /* Perform the conversion. */
13750 expr = convert_like (conv, expr, complain);
13751 else if (conv->kind == ck_ambig)
13752 /* We gave an error in build_user_type_conversion_1. */
13753 expr = error_mark_node;
13754 else
13755 gcc_unreachable ();
13757 /* Free all the conversions we allocated. */
13758 obstack_free (&conversion_obstack, p);
13760 return expr;
13763 /* Return true if T is std::pair<const T&, const T&>. */
13765 static bool
13766 std_pair_ref_ref_p (tree t)
13768 /* First, check if we have std::pair. */
13769 if (!NON_UNION_CLASS_TYPE_P (t)
13770 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
13771 return false;
13772 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
13773 if (!decl_in_std_namespace_p (tdecl))
13774 return false;
13775 tree name = DECL_NAME (tdecl);
13776 if (!name || !id_equal (name, "pair"))
13777 return false;
13779 /* Now see if the template arguments are both const T&. */
13780 tree args = CLASSTYPE_TI_ARGS (t);
13781 if (TREE_VEC_LENGTH (args) != 2)
13782 return false;
13783 for (int i = 0; i < 2; i++)
13784 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
13785 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
13786 return false;
13788 return true;
13791 /* Return true if a class CTYPE is either std::reference_wrapper or
13792 std::ref_view, or a reference wrapper class. We consider a class
13793 a reference wrapper class if it has a reference member. We no
13794 longer check that it has a constructor taking the same reference type
13795 since that approach still generated too many false positives. */
13797 static bool
13798 class_has_reference_member_p (tree t)
13800 for (tree fields = TYPE_FIELDS (t);
13801 fields;
13802 fields = DECL_CHAIN (fields))
13803 if (TREE_CODE (fields) == FIELD_DECL
13804 && !DECL_ARTIFICIAL (fields)
13805 && TYPE_REF_P (TREE_TYPE (fields)))
13806 return true;
13807 return false;
13810 /* A wrapper for the above suitable as a callback for dfs_walk_once. */
13812 static tree
13813 class_has_reference_member_p_r (tree binfo, void *)
13815 return (class_has_reference_member_p (BINFO_TYPE (binfo))
13816 ? integer_one_node : NULL_TREE);
13819 static bool
13820 reference_like_class_p (tree ctype)
13822 if (!CLASS_TYPE_P (ctype))
13823 return false;
13825 /* Also accept a std::pair<const T&, const T&>. */
13826 if (std_pair_ref_ref_p (ctype))
13827 return true;
13829 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
13830 if (decl_in_std_namespace_p (tdecl))
13832 tree name = DECL_NAME (tdecl);
13833 if (name
13834 && (id_equal (name, "reference_wrapper")
13835 || id_equal (name, "span")
13836 || id_equal (name, "ref_view")))
13837 return true;
13840 /* Some classes, such as std::tuple, have the reference member in its
13841 (non-direct) base class. */
13842 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
13843 nullptr, nullptr))
13844 return true;
13846 return false;
13849 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
13850 that initializes the LHS (and at least one of its arguments represents
13851 a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
13852 if none found. For instance:
13854 const S& s = S().self(); // S::self (&TARGET_EXPR <...>)
13855 const int& r = (42, f(1)); // f(1)
13856 const int& t = b ? f(1) : f(2); // f(1)
13857 const int& u = b ? f(1) : f(g); // f(1)
13858 const int& v = b ? f(g) : f(2); // f(2)
13859 const int& w = b ? f(g) : f(g); // NULL_TREE
13860 const int& y = (f(1), 42); // NULL_TREE
13861 const int& z = f(f(1)); // f(f(1))
13863 EXPR is the initializer. If ARG_P is true, we're processing an argument
13864 to a function; the point is to distinguish between, for example,
13866 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
13868 where we shouldn't warn, and
13870 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
13872 where we should warn (Ref is a reference_like_class_p so we see through
13873 it. */
13875 static tree
13876 do_warn_dangling_reference (tree expr, bool arg_p)
13878 STRIP_NOPS (expr);
13880 if (arg_p && expr_represents_temporary_p (expr))
13882 /* An attempt to reduce the number of -Wdangling-reference
13883 false positives concerning reference wrappers (c++/107532).
13884 When we encounter a reference_like_class_p, we don't warn
13885 just yet; instead, we keep recursing to see if there were
13886 any temporaries behind the reference-wrapper class. */
13887 tree e = expr;
13888 while (handled_component_p (e))
13889 e = TREE_OPERAND (e, 0);
13890 if (!reference_like_class_p (TREE_TYPE (e)))
13891 return expr;
13894 switch (TREE_CODE (expr))
13896 case CALL_EXPR:
13898 tree fndecl = cp_get_callee_fndecl_nofold (expr);
13899 if (!fndecl
13900 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
13901 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
13902 OPT_Wdangling_reference)
13903 /* Don't emit a false positive for:
13904 std::vector<int> v = ...;
13905 std::vector<int>::const_iterator it = v.begin();
13906 const int &r = *it++;
13907 because R refers to one of the int elements of V, not to
13908 a temporary object. Member operator* may return a reference
13909 but probably not to one of its arguments. */
13910 || (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13911 && DECL_OVERLOADED_OPERATOR_P (fndecl)
13912 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF)))
13913 return NULL_TREE;
13915 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
13916 /* If the function doesn't return a reference, don't warn. This
13917 can be e.g.
13918 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
13919 which doesn't dangle: std::min here returns an int.
13921 If the function returns a std::pair<const T&, const T&>, we
13922 warn, to detect e.g.
13923 std::pair<const int&, const int&> v = std::minmax(1, 2);
13924 which also creates a dangling reference, because std::minmax
13925 returns std::pair<const T&, const T&>(b, a). */
13926 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
13927 return NULL_TREE;
13929 /* Here we're looking to see if any of the arguments is a temporary
13930 initializing a reference parameter. */
13931 for (int i = 0; i < call_expr_nargs (expr); ++i)
13933 tree arg = CALL_EXPR_ARG (expr, i);
13934 /* Check that this argument initializes a reference, except for
13935 the argument initializing the object of a member function. */
13936 if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13937 && !TYPE_REF_P (TREE_TYPE (arg)))
13938 continue;
13939 STRIP_NOPS (arg);
13940 if (TREE_CODE (arg) == ADDR_EXPR)
13941 arg = TREE_OPERAND (arg, 0);
13942 /* Recurse to see if the argument is a temporary. It could also
13943 be another call taking a temporary and returning it and
13944 initializing this reference parameter. */
13945 if (do_warn_dangling_reference (arg, /*arg_p=*/true))
13946 return expr;
13947 /* Don't warn about member function like:
13948 std::any a(...);
13949 S& s = a.emplace<S>({0}, 0);
13950 which constructs a new object and returns a reference to it, but
13951 we still want to detect:
13952 struct S { const S& self () { return *this; } };
13953 const S& s = S().self();
13954 where 's' dangles. If we've gotten here, the object this function
13955 is invoked on is not a temporary. */
13956 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl))
13957 break;
13959 return NULL_TREE;
13961 case COMPOUND_EXPR:
13962 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
13963 case COND_EXPR:
13964 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
13965 return t;
13966 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
13967 case PAREN_EXPR:
13968 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
13969 case TARGET_EXPR:
13970 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
13971 default:
13972 return NULL_TREE;
13976 /* Implement -Wdangling-reference, to detect cases like
13978 int n = 1;
13979 const int& r = std::max(n - 1, n + 1); // r is dangling
13981 This creates temporaries from the arguments, returns a reference to
13982 one of the temporaries, but both temporaries are destroyed at the end
13983 of the full expression.
13985 This works by checking if a reference is initialized with a function
13986 that returns a reference, and at least one parameter of the function
13987 is a reference that is bound to a temporary. It assumes that such a
13988 function actually returns one of its arguments.
13990 DECL is the reference being initialized, INIT is the initializer. */
13992 static void
13993 maybe_warn_dangling_reference (const_tree decl, tree init)
13995 if (!warn_dangling_reference)
13996 return;
13997 tree type = TREE_TYPE (decl);
13998 /* Only warn if what we're initializing has type T&& or const T&, or
13999 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14000 bind to a temporary.) */
14001 if (!((TYPE_REF_OBJ_P (type)
14002 && (TYPE_REF_IS_RVALUE (type)
14003 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14004 || std_pair_ref_ref_p (type)))
14005 return;
14006 /* Don't suppress the diagnostic just because the call comes from
14007 a system header. If the DECL is not in a system header, or if
14008 -Wsystem-headers was provided, warn. */
14009 auto wsh
14010 = make_temp_override (global_dc->dc_warn_system_headers,
14011 (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14012 || global_dc->dc_warn_system_headers));
14013 if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
14015 auto_diagnostic_group d;
14016 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14017 "possibly dangling reference to a temporary"))
14018 inform (EXPR_LOCATION (call), "the temporary was destroyed at "
14019 "the end of the full expression %qE", call);
14023 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
14024 gets used to initialize a reference. */
14026 static tree
14027 prevent_lifetime_extension (tree t)
14029 tree *p = &t;
14030 while (TREE_CODE (*p) == COMPOUND_EXPR)
14031 p = &TREE_OPERAND (*p, 1);
14032 while (handled_component_p (*p))
14033 p = &TREE_OPERAND (*p, 0);
14034 /* Change a TARGET_EXPR from prvalue to xvalue. */
14035 if (TREE_CODE (*p) == TARGET_EXPR)
14036 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14037 move (TARGET_EXPR_SLOT (*p)));
14038 return t;
14041 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14042 which is bound either to a reference or a std::initializer_list. */
14044 static tree
14045 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14046 tree *cond_guard)
14048 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14049 the temporary object that is the complete object of a subobject to which
14050 the reference is bound persists for the lifetime of the reference if the
14051 glvalue to which the reference is bound was obtained through one of the
14052 following:
14053 - a temporary materialization conversion ([conv.rval]),
14054 - ( expression ), where expression is one of these expressions,
14055 - subscripting ([expr.sub]) of an array operand, where that operand is one
14056 of these expressions,
14057 - a class member access ([expr.ref]) using the . operator where the left
14058 operand is one of these expressions and the right operand designates a
14059 non-static data member of non-reference type,
14060 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14061 where the left operand is one of these expressions and the right operand
14062 is a pointer to data member of non-reference type,
14063 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14064 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14065 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14066 a glvalue operand that is one of these expressions to a glvalue that
14067 refers to the object designated by the operand, or to its complete
14068 object or a subobject thereof,
14069 - a conditional expression ([expr.cond]) that is a glvalue where the
14070 second or third operand is one of these expressions, or
14071 - a comma expression ([expr.comma]) that is a glvalue where the right
14072 operand is one of these expressions. */
14074 /* FIXME several cases are still handled wrong (101572, 81420). */
14076 tree sub = init;
14077 tree *p;
14078 STRIP_NOPS (sub);
14079 if (TREE_CODE (sub) == COMPOUND_EXPR)
14081 TREE_OPERAND (sub, 1)
14082 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14083 cond_guard);
14084 return init;
14086 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14087 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14088 (TREE_OPERAND (sub, 1)))))
14090 /* A pointer-to-member operation. */
14091 TREE_OPERAND (sub, 0)
14092 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14093 cond_guard);
14094 return init;
14096 if (TREE_CODE (sub) == COND_EXPR)
14098 tree cur_cond_guard = NULL_TREE;
14099 if (TREE_OPERAND (sub, 1))
14100 TREE_OPERAND (sub, 1)
14101 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14102 &cur_cond_guard);
14103 if (cur_cond_guard)
14105 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14106 NOP_EXPR, boolean_true_node,
14107 tf_warning_or_error);
14108 TREE_OPERAND (sub, 1)
14109 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14110 tf_warning_or_error);
14112 cur_cond_guard = NULL_TREE;
14113 if (TREE_OPERAND (sub, 2))
14114 TREE_OPERAND (sub, 2)
14115 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14116 &cur_cond_guard);
14117 if (cur_cond_guard)
14119 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14120 NOP_EXPR, boolean_true_node,
14121 tf_warning_or_error);
14122 TREE_OPERAND (sub, 2)
14123 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14124 tf_warning_or_error);
14126 return init;
14128 if (TREE_CODE (sub) != ADDR_EXPR)
14129 return init;
14130 /* Deal with binding to a subobject. */
14131 for (p = &TREE_OPERAND (sub, 0);
14132 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14133 p = &TREE_OPERAND (*p, 0);
14134 if (TREE_CODE (*p) == TARGET_EXPR)
14136 tree subinit = NULL_TREE;
14137 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
14138 recompute_tree_invariant_for_addr_expr (sub);
14139 if (init != sub)
14140 init = fold_convert (TREE_TYPE (init), sub);
14141 if (subinit)
14142 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14144 return init;
14147 /* INIT is part of the initializer for DECL. If there are any
14148 reference or initializer lists being initialized, extend their
14149 lifetime to match that of DECL. */
14151 tree
14152 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14153 tree *cond_guard)
14155 tree type = TREE_TYPE (init);
14156 if (processing_template_decl)
14157 return init;
14159 maybe_warn_dangling_reference (decl, init);
14161 if (TYPE_REF_P (type))
14162 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14163 else
14165 tree ctor = init;
14166 if (TREE_CODE (ctor) == TARGET_EXPR)
14167 ctor = TARGET_EXPR_INITIAL (ctor);
14168 if (TREE_CODE (ctor) == CONSTRUCTOR)
14170 /* [dcl.init] When initializing an aggregate from a parenthesized list
14171 of values... a temporary object bound to a reference does not have
14172 its lifetime extended. */
14173 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14174 return init;
14176 if (is_std_init_list (type))
14178 /* The temporary array underlying a std::initializer_list
14179 is handled like a reference temporary. */
14180 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14181 array = extend_ref_init_temps_1 (decl, array, cleanups,
14182 cond_guard);
14183 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14185 else
14187 unsigned i;
14188 constructor_elt *p;
14189 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14190 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14191 p->value = extend_ref_init_temps (decl, p->value, cleanups,
14192 cond_guard);
14194 recompute_constructor_flags (ctor);
14195 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14196 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14200 return init;
14203 /* Returns true iff an initializer for TYPE could contain temporaries that
14204 need to be extended because they are bound to references or
14205 std::initializer_list. */
14207 bool
14208 type_has_extended_temps (tree type)
14210 type = strip_array_types (type);
14211 if (TYPE_REF_P (type))
14212 return true;
14213 if (CLASS_TYPE_P (type))
14215 if (is_std_init_list (type))
14216 return true;
14217 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14218 f; f = next_aggregate_field (DECL_CHAIN (f)))
14219 if (type_has_extended_temps (TREE_TYPE (f)))
14220 return true;
14222 return false;
14225 /* Returns true iff TYPE is some variant of std::initializer_list. */
14227 bool
14228 is_std_init_list (tree type)
14230 if (!TYPE_P (type))
14231 return false;
14232 if (cxx_dialect == cxx98)
14233 return false;
14234 /* Look through typedefs. */
14235 type = TYPE_MAIN_VARIANT (type);
14236 return (CLASS_TYPE_P (type)
14237 && CP_TYPE_CONTEXT (type) == std_node
14238 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14241 /* Returns true iff DECL is a list constructor: i.e. a constructor which
14242 will accept an argument list of a single std::initializer_list<T>. */
14244 bool
14245 is_list_ctor (tree decl)
14247 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14248 tree arg;
14250 if (!args || args == void_list_node)
14251 return false;
14253 arg = non_reference (TREE_VALUE (args));
14254 if (!is_std_init_list (arg))
14255 return false;
14257 args = TREE_CHAIN (args);
14259 if (args && args != void_list_node && !TREE_PURPOSE (args))
14260 /* There are more non-defaulted parms. */
14261 return false;
14263 return true;
14266 #include "gt-cp-call.h"