Don't warn when alignment of global common data exceeds maximum alignment.
[official-gcc.git] / gcc / cp / call.c
blobe4df72ec1a377acd6000faf28f969b9eaed7ca04
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2021 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 "gcc-rich-location.h"
46 /* The various kinds of conversion. */
48 enum conversion_kind {
49 ck_identity,
50 ck_lvalue,
51 ck_fnptr,
52 ck_qual,
53 ck_std,
54 ck_ptr,
55 ck_pmem,
56 ck_base,
57 ck_ref_bind,
58 ck_user,
59 ck_ambig,
60 ck_list,
61 ck_aggr,
62 ck_rvalue
65 /* The rank of the conversion. Order of the enumerals matters; better
66 conversions should come earlier in the list. */
68 enum conversion_rank {
69 cr_identity,
70 cr_exact,
71 cr_promotion,
72 cr_std,
73 cr_pbool,
74 cr_user,
75 cr_ellipsis,
76 cr_bad
79 /* An implicit conversion sequence, in the sense of [over.best.ics].
80 The first conversion to be performed is at the end of the chain.
81 That conversion is always a cr_identity conversion. */
83 struct conversion {
84 /* The kind of conversion represented by this step. */
85 conversion_kind kind;
86 /* The rank of this conversion. */
87 conversion_rank rank;
88 BOOL_BITFIELD user_conv_p : 1;
89 BOOL_BITFIELD ellipsis_p : 1;
90 BOOL_BITFIELD this_p : 1;
91 /* True if this conversion would be permitted with a bending of
92 language standards, e.g. disregarding pointer qualifiers or
93 converting integers to pointers. */
94 BOOL_BITFIELD bad_p : 1;
95 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
96 temporary should be created to hold the result of the
97 conversion. If KIND is ck_ambig or ck_user, true means force
98 copy-initialization. */
99 BOOL_BITFIELD need_temporary_p : 1;
100 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
101 from a pointer-to-derived to pointer-to-base is being performed. */
102 BOOL_BITFIELD base_p : 1;
103 /* If KIND is ck_ref_bind, true when either an lvalue reference is
104 being bound to an lvalue expression or an rvalue reference is
105 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
106 true when we are treating an lvalue as an rvalue (12.8p33). If
107 ck_identity, we will be binding a reference directly or decaying to
108 a pointer. */
109 BOOL_BITFIELD rvaluedness_matches_p: 1;
110 BOOL_BITFIELD check_narrowing: 1;
111 /* Whether check_narrowing should only check TREE_CONSTANTs; used
112 in build_converted_constant_expr. */
113 BOOL_BITFIELD check_narrowing_const_only: 1;
114 /* True if this conversion is taking place in a copy-initialization context
115 and we should only consider converting constructors. Only set in
116 ck_base and ck_rvalue. */
117 BOOL_BITFIELD copy_init_p : 1;
118 /* The type of the expression resulting from the conversion. */
119 tree type;
120 union {
121 /* The next conversion in the chain. Since the conversions are
122 arranged from outermost to innermost, the NEXT conversion will
123 actually be performed before this conversion. This variant is
124 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
125 ck_list. Please use the next_conversion function instead
126 of using this field directly. */
127 conversion *next;
128 /* The expression at the beginning of the conversion chain. This
129 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
130 You can use conv_get_original_expr to get this expression. */
131 tree expr;
132 /* The array of conversions for an initializer_list, so this
133 variant is used only when KIN D is ck_list. */
134 conversion **list;
135 } u;
136 /* The function candidate corresponding to this conversion
137 sequence. This field is only used if KIND is ck_user. */
138 struct z_candidate *cand;
141 #define CONVERSION_RANK(NODE) \
142 ((NODE)->bad_p ? cr_bad \
143 : (NODE)->ellipsis_p ? cr_ellipsis \
144 : (NODE)->user_conv_p ? cr_user \
145 : (NODE)->rank)
147 #define BAD_CONVERSION_RANK(NODE) \
148 ((NODE)->ellipsis_p ? cr_ellipsis \
149 : (NODE)->user_conv_p ? cr_user \
150 : (NODE)->rank)
152 static struct obstack conversion_obstack;
153 static bool conversion_obstack_initialized;
154 struct rejection_reason;
156 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
157 static int equal_functions (tree, tree);
158 static int joust (struct z_candidate *, struct z_candidate *, bool,
159 tsubst_flags_t);
160 static int compare_ics (conversion *, conversion *);
161 static void maybe_warn_class_memaccess (location_t, tree,
162 const vec<tree, va_gc> *);
163 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
164 static tree convert_like (conversion *, tree, tsubst_flags_t);
165 static tree convert_like_with_context (conversion *, tree, tree, int,
166 tsubst_flags_t);
167 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
168 tree, tree, tree, bool);
169 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
170 tsubst_flags_t);
171 static void print_z_candidate (location_t, const char *, struct z_candidate *);
172 static void print_z_candidates (location_t, struct z_candidate *);
173 static tree build_this (tree);
174 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
175 static bool any_strictly_viable (struct z_candidate *);
176 static struct z_candidate *add_template_candidate
177 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
178 tree, tree, tree, int, unification_kind_t, tsubst_flags_t);
179 static struct z_candidate *add_template_candidate_real
180 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
181 tree, tree, tree, int, tree, unification_kind_t, tsubst_flags_t);
182 static bool is_complete (tree);
183 static struct z_candidate *add_conv_candidate
184 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
185 tree, tsubst_flags_t);
186 static struct z_candidate *add_function_candidate
187 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
188 tree, int, conversion**, tsubst_flags_t);
189 static conversion *implicit_conversion (tree, tree, tree, bool, int,
190 tsubst_flags_t);
191 static conversion *reference_binding (tree, tree, tree, bool, int,
192 tsubst_flags_t);
193 static conversion *build_conv (conversion_kind, tree, conversion *);
194 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
195 static conversion *next_conversion (conversion *);
196 static bool is_subseq (conversion *, conversion *);
197 static conversion *maybe_handle_ref_bind (conversion **);
198 static void maybe_handle_implicit_object (conversion **);
199 static struct z_candidate *add_candidate
200 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
201 conversion **, tree, tree, int, struct rejection_reason *, int);
202 static tree source_type (conversion *);
203 static void add_warning (struct z_candidate *, struct z_candidate *);
204 static conversion *direct_reference_binding (tree, conversion *);
205 static bool promoted_arithmetic_type_p (tree);
206 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
207 static char *name_as_c_string (tree, tree, bool *);
208 static tree prep_operand (tree);
209 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
210 bool, tree, tree, int, struct z_candidate **,
211 tsubst_flags_t);
212 static conversion *merge_conversion_sequences (conversion *, conversion *);
213 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
214 static conversion *build_identity_conv (tree, tree);
215 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
216 static bool conv_is_prvalue (conversion *);
217 static tree prevent_lifetime_extension (tree);
219 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
220 NAME can take many forms... */
222 bool
223 check_dtor_name (tree basetype, tree name)
225 /* Just accept something we've already complained about. */
226 if (name == error_mark_node)
227 return true;
229 if (TREE_CODE (name) == TYPE_DECL)
230 name = TREE_TYPE (name);
231 else if (TYPE_P (name))
232 /* OK */;
233 else if (identifier_p (name))
235 if ((MAYBE_CLASS_TYPE_P (basetype)
236 || TREE_CODE (basetype) == ENUMERAL_TYPE)
237 && name == constructor_name (basetype))
238 return true;
240 /* Otherwise lookup the name, it could be an unrelated typedef
241 of the correct type. */
242 name = lookup_name (name, LOOK_want::TYPE);
243 if (!name)
244 return false;
245 name = TREE_TYPE (name);
246 if (name == error_mark_node)
247 return false;
249 else
251 /* In the case of:
253 template <class T> struct S { ~S(); };
254 int i;
255 i.~S();
257 NAME will be a class template. */
258 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
259 return false;
262 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
265 /* We want the address of a function or method. We avoid creating a
266 pointer-to-member function. */
268 tree
269 build_addr_func (tree function, tsubst_flags_t complain)
271 tree type = TREE_TYPE (function);
273 /* We have to do these by hand to avoid real pointer to member
274 functions. */
275 if (TREE_CODE (type) == METHOD_TYPE)
277 if (TREE_CODE (function) == OFFSET_REF)
279 tree object = build_address (TREE_OPERAND (function, 0));
280 return get_member_function_from_ptrfunc (&object,
281 TREE_OPERAND (function, 1),
282 complain);
284 function = build_address (function);
286 else if (TREE_CODE (function) == FUNCTION_DECL
287 && DECL_IMMEDIATE_FUNCTION_P (function))
288 function = build_address (function);
289 else
290 function = decay_conversion (function, complain, /*reject_builtin=*/false);
292 return function;
295 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
296 POINTER_TYPE to those. Note, pointer to member function types
297 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
298 two variants. build_call_a is the primitive taking an array of
299 arguments, while build_call_n is a wrapper that handles varargs. */
301 tree
302 build_call_n (tree function, int n, ...)
304 if (n == 0)
305 return build_call_a (function, 0, NULL);
306 else
308 tree *argarray = XALLOCAVEC (tree, n);
309 va_list ap;
310 int i;
312 va_start (ap, n);
313 for (i = 0; i < n; i++)
314 argarray[i] = va_arg (ap, tree);
315 va_end (ap);
316 return build_call_a (function, n, argarray);
320 /* Update various flags in cfun and the call itself based on what is being
321 called. Split out of build_call_a so that bot_manip can use it too. */
323 void
324 set_flags_from_callee (tree call)
326 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
327 tree decl = cp_get_callee_fndecl_nofold (call);
329 /* We check both the decl and the type; a function may be known not to
330 throw without being declared throw(). */
331 bool nothrow = decl && TREE_NOTHROW (decl);
332 tree callee = cp_get_callee (call);
333 if (callee)
334 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
335 else if (TREE_CODE (call) == CALL_EXPR
336 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
337 nothrow = true;
339 if (cfun && cp_function_chain && !cp_unevaluated_operand)
341 if (!nothrow && at_function_scope_p ())
342 cp_function_chain->can_throw = 1;
344 if (decl && TREE_THIS_VOLATILE (decl))
345 current_function_returns_abnormally = 1;
348 TREE_NOTHROW (call) = nothrow;
351 tree
352 build_call_a (tree function, int n, tree *argarray)
354 tree decl;
355 tree result_type;
356 tree fntype;
357 int i;
359 function = build_addr_func (function, tf_warning_or_error);
361 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
362 fntype = TREE_TYPE (TREE_TYPE (function));
363 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
364 result_type = TREE_TYPE (fntype);
365 /* An rvalue has no cv-qualifiers. */
366 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
367 result_type = cv_unqualified (result_type);
369 function = build_call_array_loc (input_location,
370 result_type, function, n, argarray);
371 set_flags_from_callee (function);
373 decl = get_callee_fndecl (function);
375 if (decl && !TREE_USED (decl))
377 /* We invoke build_call directly for several library
378 functions. These may have been declared normally if
379 we're building libgcc, so we can't just check
380 DECL_ARTIFICIAL. */
381 gcc_assert (DECL_ARTIFICIAL (decl)
382 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
383 "__", 2));
384 mark_used (decl);
387 require_complete_eh_spec_types (fntype, decl);
389 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
391 /* Don't pass empty class objects by value. This is useful
392 for tags in STL, which are used to control overload resolution.
393 We don't need to handle other cases of copying empty classes. */
394 if (!decl || !fndecl_built_in_p (decl))
395 for (i = 0; i < n; i++)
397 tree arg = CALL_EXPR_ARG (function, i);
398 if (is_empty_class (TREE_TYPE (arg))
399 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
401 while (TREE_CODE (arg) == TARGET_EXPR)
402 /* We're disconnecting the initializer from its target,
403 don't create a temporary. */
404 arg = TARGET_EXPR_INITIAL (arg);
405 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
406 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
407 CALL_EXPR_ARG (function, i) = arg;
411 return function;
414 /* New overloading code. */
416 struct z_candidate;
418 struct candidate_warning {
419 z_candidate *loser;
420 candidate_warning *next;
423 /* Information for providing diagnostics about why overloading failed. */
425 enum rejection_reason_code {
426 rr_none,
427 rr_arity,
428 rr_explicit_conversion,
429 rr_template_conversion,
430 rr_arg_conversion,
431 rr_bad_arg_conversion,
432 rr_template_unification,
433 rr_invalid_copy,
434 rr_inherited_ctor,
435 rr_constraint_failure
438 struct conversion_info {
439 /* The index of the argument, 0-based. */
440 int n_arg;
441 /* The actual argument or its type. */
442 tree from;
443 /* The type of the parameter. */
444 tree to_type;
445 /* The location of the argument. */
446 location_t loc;
449 struct rejection_reason {
450 enum rejection_reason_code code;
451 union {
452 /* Information about an arity mismatch. */
453 struct {
454 /* The expected number of arguments. */
455 int expected;
456 /* The actual number of arguments in the call. */
457 int actual;
458 /* Whether the call was a varargs call. */
459 bool call_varargs_p;
460 } arity;
461 /* Information about an argument conversion mismatch. */
462 struct conversion_info conversion;
463 /* Same, but for bad argument conversions. */
464 struct conversion_info bad_conversion;
465 /* Information about template unification failures. These are the
466 parameters passed to fn_type_unification. */
467 struct {
468 tree tmpl;
469 tree explicit_targs;
470 int num_targs;
471 const tree *args;
472 unsigned int nargs;
473 tree return_type;
474 unification_kind_t strict;
475 int flags;
476 } template_unification;
477 /* Information about template instantiation failures. These are the
478 parameters passed to instantiate_template. */
479 struct {
480 tree tmpl;
481 tree targs;
482 } template_instantiation;
483 } u;
486 struct z_candidate {
487 /* The FUNCTION_DECL that will be called if this candidate is
488 selected by overload resolution. */
489 tree fn;
490 /* If not NULL_TREE, the first argument to use when calling this
491 function. */
492 tree first_arg;
493 /* The rest of the arguments to use when calling this function. If
494 there are no further arguments this may be NULL or it may be an
495 empty vector. */
496 const vec<tree, va_gc> *args;
497 /* The implicit conversion sequences for each of the arguments to
498 FN. */
499 conversion **convs;
500 /* The number of implicit conversion sequences. */
501 size_t num_convs;
502 /* If FN is a user-defined conversion, the standard conversion
503 sequence from the type returned by FN to the desired destination
504 type. */
505 conversion *second_conv;
506 struct rejection_reason *reason;
507 /* If FN is a member function, the binfo indicating the path used to
508 qualify the name of FN at the call site. This path is used to
509 determine whether or not FN is accessible if it is selected by
510 overload resolution. The DECL_CONTEXT of FN will always be a
511 (possibly improper) base of this binfo. */
512 tree access_path;
513 /* If FN is a non-static member function, the binfo indicating the
514 subobject to which the `this' pointer should be converted if FN
515 is selected by overload resolution. The type pointed to by
516 the `this' pointer must correspond to the most derived class
517 indicated by the CONVERSION_PATH. */
518 tree conversion_path;
519 tree template_decl;
520 tree explicit_targs;
521 candidate_warning *warnings;
522 z_candidate *next;
523 int viable;
525 /* The flags active in add_candidate. */
526 int flags;
528 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
529 bool reversed () const { return (flags & LOOKUP_REVERSED); }
532 /* Returns true iff T is a null pointer constant in the sense of
533 [conv.ptr]. */
535 bool
536 null_ptr_cst_p (tree t)
538 tree type = TREE_TYPE (t);
540 /* [conv.ptr]
542 A null pointer constant is an integer literal ([lex.icon]) with value
543 zero or a prvalue of type std::nullptr_t. */
544 if (NULLPTR_TYPE_P (type))
545 return true;
547 if (cxx_dialect >= cxx11)
549 STRIP_ANY_LOCATION_WRAPPER (t);
551 /* Core issue 903 says only literal 0 is a null pointer constant. */
552 if (TREE_CODE (t) == INTEGER_CST
553 && !TREE_OVERFLOW (t)
554 && TREE_CODE (type) == INTEGER_TYPE
555 && integer_zerop (t)
556 && !char_type_p (type))
557 return true;
559 else if (CP_INTEGRAL_TYPE_P (type))
561 t = fold_non_dependent_expr (t, tf_none);
562 STRIP_NOPS (t);
563 if (integer_zerop (t) && !TREE_OVERFLOW (t))
564 return true;
567 return false;
570 /* Returns true iff T is a null member pointer value (4.11). */
572 bool
573 null_member_pointer_value_p (tree t)
575 tree type = TREE_TYPE (t);
576 if (!type)
577 return false;
578 else if (TYPE_PTRMEMFUNC_P (type))
579 return (TREE_CODE (t) == CONSTRUCTOR
580 && CONSTRUCTOR_NELTS (t)
581 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
582 else if (TYPE_PTRDATAMEM_P (type))
583 return integer_all_onesp (t);
584 else
585 return false;
588 /* Returns nonzero if PARMLIST consists of only default parms,
589 ellipsis, and/or undeduced parameter packs. */
591 bool
592 sufficient_parms_p (const_tree parmlist)
594 for (; parmlist && parmlist != void_list_node;
595 parmlist = TREE_CHAIN (parmlist))
596 if (!TREE_PURPOSE (parmlist)
597 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
598 return false;
599 return true;
602 /* Allocate N bytes of memory from the conversion obstack. The memory
603 is zeroed before being returned. */
605 static void *
606 conversion_obstack_alloc (size_t n)
608 void *p;
609 if (!conversion_obstack_initialized)
611 gcc_obstack_init (&conversion_obstack);
612 conversion_obstack_initialized = true;
614 p = obstack_alloc (&conversion_obstack, n);
615 memset (p, 0, n);
616 return p;
619 /* Allocate rejection reasons. */
621 static struct rejection_reason *
622 alloc_rejection (enum rejection_reason_code code)
624 struct rejection_reason *p;
625 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
626 p->code = code;
627 return p;
630 static struct rejection_reason *
631 arity_rejection (tree first_arg, int expected, int actual)
633 struct rejection_reason *r = alloc_rejection (rr_arity);
634 int adjust = first_arg != NULL_TREE;
635 r->u.arity.expected = expected - adjust;
636 r->u.arity.actual = actual - adjust;
637 return r;
640 static struct rejection_reason *
641 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
642 location_t loc)
644 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
645 int adjust = first_arg != NULL_TREE;
646 r->u.conversion.n_arg = n_arg - adjust;
647 r->u.conversion.from = from;
648 r->u.conversion.to_type = to;
649 r->u.conversion.loc = loc;
650 return r;
653 static struct rejection_reason *
654 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
655 location_t loc)
657 struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
658 int adjust = first_arg != NULL_TREE;
659 r->u.bad_conversion.n_arg = n_arg - adjust;
660 r->u.bad_conversion.from = from;
661 r->u.bad_conversion.to_type = to;
662 r->u.bad_conversion.loc = loc;
663 return r;
666 static struct rejection_reason *
667 explicit_conversion_rejection (tree from, tree to)
669 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
670 r->u.conversion.n_arg = 0;
671 r->u.conversion.from = from;
672 r->u.conversion.to_type = to;
673 r->u.conversion.loc = UNKNOWN_LOCATION;
674 return r;
677 static struct rejection_reason *
678 template_conversion_rejection (tree from, tree to)
680 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
681 r->u.conversion.n_arg = 0;
682 r->u.conversion.from = from;
683 r->u.conversion.to_type = to;
684 r->u.conversion.loc = UNKNOWN_LOCATION;
685 return r;
688 static struct rejection_reason *
689 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
690 const tree *args, unsigned int nargs,
691 tree return_type, unification_kind_t strict,
692 int flags)
694 size_t args_n_bytes = sizeof (*args) * nargs;
695 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
696 struct rejection_reason *r = alloc_rejection (rr_template_unification);
697 r->u.template_unification.tmpl = tmpl;
698 r->u.template_unification.explicit_targs = explicit_targs;
699 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
700 /* Copy args to our own storage. */
701 memcpy (args1, args, args_n_bytes);
702 r->u.template_unification.args = args1;
703 r->u.template_unification.nargs = nargs;
704 r->u.template_unification.return_type = return_type;
705 r->u.template_unification.strict = strict;
706 r->u.template_unification.flags = flags;
707 return r;
710 static struct rejection_reason *
711 template_unification_error_rejection (void)
713 return alloc_rejection (rr_template_unification);
716 static struct rejection_reason *
717 invalid_copy_with_fn_template_rejection (void)
719 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
720 return r;
723 static struct rejection_reason *
724 inherited_ctor_rejection (void)
726 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
727 return r;
730 /* Build a constraint failure record. */
732 static struct rejection_reason *
733 constraint_failure (void)
735 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
736 return r;
739 /* Dynamically allocate a conversion. */
741 static conversion *
742 alloc_conversion (conversion_kind kind)
744 conversion *c;
745 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
746 c->kind = kind;
747 return c;
750 /* Make sure that all memory on the conversion obstack has been
751 freed. */
753 void
754 validate_conversion_obstack (void)
756 if (conversion_obstack_initialized)
757 gcc_assert ((obstack_next_free (&conversion_obstack)
758 == obstack_base (&conversion_obstack)));
761 /* Dynamically allocate an array of N conversions. */
763 static conversion **
764 alloc_conversions (size_t n)
766 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
769 /* True iff the active member of conversion::u for code CODE is NEXT. */
771 static inline bool
772 has_next (conversion_kind code)
774 return !(code == ck_identity
775 || code == ck_ambig
776 || code == ck_list
777 || code == ck_aggr);
780 static conversion *
781 build_conv (conversion_kind code, tree type, conversion *from)
783 conversion *t;
784 conversion_rank rank = CONVERSION_RANK (from);
786 /* Only call this function for conversions that use u.next. */
787 gcc_assert (from == NULL || has_next (code));
789 /* Note that the caller is responsible for filling in t->cand for
790 user-defined conversions. */
791 t = alloc_conversion (code);
792 t->type = type;
793 t->u.next = from;
795 switch (code)
797 case ck_ptr:
798 case ck_pmem:
799 case ck_base:
800 case ck_std:
801 if (rank < cr_std)
802 rank = cr_std;
803 break;
805 case ck_qual:
806 case ck_fnptr:
807 if (rank < cr_exact)
808 rank = cr_exact;
809 break;
811 default:
812 break;
814 t->rank = rank;
815 t->user_conv_p = (code == ck_user || from->user_conv_p);
816 t->bad_p = from->bad_p;
817 t->base_p = false;
818 return t;
821 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
822 specialization of std::initializer_list<T>, if such a conversion is
823 possible. */
825 static conversion *
826 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
828 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
829 unsigned len = CONSTRUCTOR_NELTS (ctor);
830 conversion **subconvs = alloc_conversions (len);
831 conversion *t;
832 unsigned i;
833 tree val;
835 /* Within a list-initialization we can have more user-defined
836 conversions. */
837 flags &= ~LOOKUP_NO_CONVERSION;
838 /* But no narrowing conversions. */
839 flags |= LOOKUP_NO_NARROWING;
841 /* Can't make an array of these types. */
842 if (TYPE_REF_P (elttype)
843 || TREE_CODE (elttype) == FUNCTION_TYPE
844 || VOID_TYPE_P (elttype))
845 return NULL;
847 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
849 conversion *sub
850 = implicit_conversion (elttype, TREE_TYPE (val), val,
851 false, flags, complain);
852 if (sub == NULL)
853 return NULL;
855 subconvs[i] = sub;
858 t = alloc_conversion (ck_list);
859 t->type = type;
860 t->u.list = subconvs;
861 t->rank = cr_exact;
863 for (i = 0; i < len; ++i)
865 conversion *sub = subconvs[i];
866 if (sub->rank > t->rank)
867 t->rank = sub->rank;
868 if (sub->user_conv_p)
869 t->user_conv_p = true;
870 if (sub->bad_p)
871 t->bad_p = true;
874 return t;
877 /* Return the next conversion of the conversion chain (if applicable),
878 or NULL otherwise. Please use this function instead of directly
879 accessing fields of struct conversion. */
881 static conversion *
882 next_conversion (conversion *conv)
884 if (conv == NULL
885 || !has_next (conv->kind))
886 return NULL;
887 return conv->u.next;
890 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
891 encountered. */
893 static conversion *
894 strip_standard_conversion (conversion *conv)
896 while (conv
897 && conv->kind != ck_user
898 && has_next (conv->kind))
899 conv = next_conversion (conv);
900 return conv;
903 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
904 initializer for array type ATYPE. */
906 static bool
907 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
909 tree elttype = TREE_TYPE (atype);
910 unsigned i;
912 if (TREE_CODE (from) == CONSTRUCTOR)
914 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
916 tree val = CONSTRUCTOR_ELT (from, i)->value;
917 bool ok;
918 if (TREE_CODE (elttype) == ARRAY_TYPE)
919 ok = can_convert_array (elttype, val, flags, complain);
920 else
921 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
922 complain);
923 if (!ok)
924 return false;
926 return true;
929 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
930 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
931 return array_string_literal_compatible_p (atype, from);
933 /* No other valid way to aggregate initialize an array. */
934 return false;
937 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
938 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
939 is in PSET. */
941 static bool
942 field_in_pset (hash_set<tree, true> &pset, tree field)
944 if (pset.contains (field))
945 return true;
946 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
947 for (field = TYPE_FIELDS (TREE_TYPE (field));
948 field; field = DECL_CHAIN (field))
950 field = next_initializable_field (field);
951 if (field == NULL_TREE)
952 break;
953 if (field_in_pset (pset, field))
954 return true;
956 return false;
959 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
960 aggregate class, if such a conversion is possible. */
962 static conversion *
963 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
965 unsigned HOST_WIDE_INT i = 0;
966 conversion *c;
967 tree field = next_initializable_field (TYPE_FIELDS (type));
968 tree empty_ctor = NULL_TREE;
969 hash_set<tree, true> pset;
971 /* We already called reshape_init in implicit_conversion. */
973 /* The conversions within the init-list aren't affected by the enclosing
974 context; they're always simple copy-initialization. */
975 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
977 /* For designated initializers, verify that each initializer is convertible
978 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
979 visited. In the following loop then ignore already visited
980 FIELD_DECLs. */
981 if (CONSTRUCTOR_IS_DESIGNATED_INIT (ctor))
983 tree idx, val;
984 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
986 if (idx && TREE_CODE (idx) == FIELD_DECL)
988 tree ftype = TREE_TYPE (idx);
989 bool ok;
991 if (TREE_CODE (ftype) == ARRAY_TYPE)
992 ok = can_convert_array (ftype, val, flags, complain);
993 else
994 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
995 complain);
997 if (!ok)
998 return NULL;
999 /* For unions, there should be just one initializer. */
1000 if (TREE_CODE (type) == UNION_TYPE)
1002 field = NULL_TREE;
1003 i = 1;
1004 break;
1006 pset.add (idx);
1008 else
1009 return NULL;
1013 for (; field; field = next_initializable_field (DECL_CHAIN (field)))
1015 tree ftype = TREE_TYPE (field);
1016 tree val;
1017 bool ok;
1019 if (!pset.is_empty () && field_in_pset (pset, field))
1020 continue;
1021 if (i < CONSTRUCTOR_NELTS (ctor))
1023 val = CONSTRUCTOR_ELT (ctor, i)->value;
1024 ++i;
1026 else if (DECL_INITIAL (field))
1027 val = get_nsdmi (field, /*ctor*/false, complain);
1028 else if (TYPE_REF_P (ftype))
1029 /* Value-initialization of reference is ill-formed. */
1030 return NULL;
1031 else
1033 if (empty_ctor == NULL_TREE)
1034 empty_ctor = build_constructor (init_list_type_node, NULL);
1035 val = empty_ctor;
1038 if (TREE_CODE (ftype) == ARRAY_TYPE)
1039 ok = can_convert_array (ftype, val, flags, complain);
1040 else
1041 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1042 complain);
1044 if (!ok)
1045 return NULL;
1047 if (TREE_CODE (type) == UNION_TYPE)
1048 break;
1051 if (i < CONSTRUCTOR_NELTS (ctor))
1052 return NULL;
1054 c = alloc_conversion (ck_aggr);
1055 c->type = type;
1056 c->rank = cr_exact;
1057 c->user_conv_p = true;
1058 c->check_narrowing = true;
1059 c->u.expr = ctor;
1060 return c;
1063 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1064 array type, if such a conversion is possible. */
1066 static conversion *
1067 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1069 conversion *c;
1070 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1071 tree elttype = TREE_TYPE (type);
1072 unsigned i;
1073 tree val;
1074 bool bad = false;
1075 bool user = false;
1076 enum conversion_rank rank = cr_exact;
1078 /* We might need to propagate the size from the element to the array. */
1079 complete_type (type);
1081 if (TYPE_DOMAIN (type)
1082 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1084 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1085 if (alen < len)
1086 return NULL;
1089 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1091 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
1093 conversion *sub
1094 = implicit_conversion (elttype, TREE_TYPE (val), val,
1095 false, flags, complain);
1096 if (sub == NULL)
1097 return NULL;
1099 if (sub->rank > rank)
1100 rank = sub->rank;
1101 if (sub->user_conv_p)
1102 user = true;
1103 if (sub->bad_p)
1104 bad = true;
1107 c = alloc_conversion (ck_aggr);
1108 c->type = type;
1109 c->rank = rank;
1110 c->user_conv_p = user;
1111 c->bad_p = bad;
1112 c->u.expr = ctor;
1113 return c;
1116 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1117 complex type, if such a conversion is possible. */
1119 static conversion *
1120 build_complex_conv (tree type, tree ctor, int flags,
1121 tsubst_flags_t complain)
1123 conversion *c;
1124 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1125 tree elttype = TREE_TYPE (type);
1126 unsigned i;
1127 tree val;
1128 bool bad = false;
1129 bool user = false;
1130 enum conversion_rank rank = cr_exact;
1132 if (len != 2)
1133 return NULL;
1135 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1137 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
1139 conversion *sub
1140 = implicit_conversion (elttype, TREE_TYPE (val), val,
1141 false, flags, complain);
1142 if (sub == NULL)
1143 return NULL;
1145 if (sub->rank > rank)
1146 rank = sub->rank;
1147 if (sub->user_conv_p)
1148 user = true;
1149 if (sub->bad_p)
1150 bad = true;
1153 c = alloc_conversion (ck_aggr);
1154 c->type = type;
1155 c->rank = rank;
1156 c->user_conv_p = user;
1157 c->bad_p = bad;
1158 c->u.expr = ctor;
1159 return c;
1162 /* Build a representation of the identity conversion from EXPR to
1163 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1165 static conversion *
1166 build_identity_conv (tree type, tree expr)
1168 conversion *c;
1170 c = alloc_conversion (ck_identity);
1171 c->type = type;
1172 c->u.expr = expr;
1174 return c;
1177 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1178 were multiple user-defined conversions to accomplish the job.
1179 Build a conversion that indicates that ambiguity. */
1181 static conversion *
1182 build_ambiguous_conv (tree type, tree expr)
1184 conversion *c;
1186 c = alloc_conversion (ck_ambig);
1187 c->type = type;
1188 c->u.expr = expr;
1190 return c;
1193 tree
1194 strip_top_quals (tree t)
1196 if (TREE_CODE (t) == ARRAY_TYPE)
1197 return t;
1198 return cp_build_qualified_type (t, 0);
1201 /* Returns the standard conversion path (see [conv]) from type FROM to type
1202 TO, if any. For proper handling of null pointer constants, you must
1203 also pass the expression EXPR to convert from. If C_CAST_P is true,
1204 this conversion is coming from a C-style cast. */
1206 static conversion *
1207 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1208 int flags, tsubst_flags_t complain)
1210 enum tree_code fcode, tcode;
1211 conversion *conv;
1212 bool fromref = false;
1213 tree qualified_to;
1215 to = non_reference (to);
1216 if (TYPE_REF_P (from))
1218 fromref = true;
1219 from = TREE_TYPE (from);
1221 qualified_to = to;
1222 to = strip_top_quals (to);
1223 from = strip_top_quals (from);
1225 if (expr && type_unknown_p (expr))
1227 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1229 tsubst_flags_t tflags = tf_conv;
1230 expr = instantiate_type (to, expr, tflags);
1231 if (expr == error_mark_node)
1232 return NULL;
1233 from = TREE_TYPE (expr);
1235 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1237 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1238 expr = resolve_nondeduced_context (expr, complain);
1239 from = TREE_TYPE (expr);
1243 fcode = TREE_CODE (from);
1244 tcode = TREE_CODE (to);
1246 conv = build_identity_conv (from, expr);
1247 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1249 from = type_decays_to (from);
1250 fcode = TREE_CODE (from);
1251 /* Tell convert_like that we're using the address. */
1252 conv->rvaluedness_matches_p = true;
1253 conv = build_conv (ck_lvalue, from, conv);
1255 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1256 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1257 express the copy constructor call required by copy-initialization. */
1258 else if (fromref || (expr && obvalue_p (expr)))
1260 if (expr)
1262 tree bitfield_type;
1263 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1264 if (bitfield_type)
1266 from = strip_top_quals (bitfield_type);
1267 fcode = TREE_CODE (from);
1270 conv = build_conv (ck_rvalue, from, conv);
1271 if (flags & LOOKUP_PREFER_RVALUE)
1272 /* Tell convert_like to set LOOKUP_PREFER_RVALUE. */
1273 conv->rvaluedness_matches_p = true;
1274 /* If we're performing copy-initialization, remember to skip
1275 explicit constructors. */
1276 if (flags & LOOKUP_ONLYCONVERTING)
1277 conv->copy_init_p = true;
1280 /* Allow conversion between `__complex__' data types. */
1281 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1283 /* The standard conversion sequence to convert FROM to TO is
1284 the standard conversion sequence to perform componentwise
1285 conversion. */
1286 conversion *part_conv = standard_conversion
1287 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1288 complain);
1290 if (!part_conv)
1291 conv = NULL;
1292 else if (part_conv->kind == ck_identity)
1293 /* Leave conv alone. */;
1294 else
1296 conv = build_conv (part_conv->kind, to, conv);
1297 conv->rank = part_conv->rank;
1300 return conv;
1303 if (same_type_p (from, to))
1305 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1306 conv->type = qualified_to;
1307 return conv;
1310 /* [conv.ptr]
1311 A null pointer constant can be converted to a pointer type; ... A
1312 null pointer constant of integral type can be converted to an
1313 rvalue of type std::nullptr_t. */
1314 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1315 || NULLPTR_TYPE_P (to))
1316 && ((expr && null_ptr_cst_p (expr))
1317 || NULLPTR_TYPE_P (from)))
1318 conv = build_conv (ck_std, to, conv);
1319 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1320 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1322 /* For backwards brain damage compatibility, allow interconversion of
1323 pointers and integers with a pedwarn. */
1324 conv = build_conv (ck_std, to, conv);
1325 conv->bad_p = true;
1327 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1329 /* For backwards brain damage compatibility, allow interconversion of
1330 enums and integers with a pedwarn. */
1331 conv = build_conv (ck_std, to, conv);
1332 conv->bad_p = true;
1334 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1335 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1337 tree to_pointee;
1338 tree from_pointee;
1340 if (tcode == POINTER_TYPE)
1342 to_pointee = TREE_TYPE (to);
1343 from_pointee = TREE_TYPE (from);
1345 /* Since this is the target of a pointer, it can't have function
1346 qualifiers, so any TYPE_QUALS must be for attributes const or
1347 noreturn. Strip them. */
1348 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1349 && TYPE_QUALS (to_pointee))
1350 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1351 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1352 && TYPE_QUALS (from_pointee))
1353 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1355 else
1357 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1358 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1361 if (tcode == POINTER_TYPE
1362 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1363 to_pointee))
1365 else if (VOID_TYPE_P (to_pointee)
1366 && !TYPE_PTRDATAMEM_P (from)
1367 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1369 tree nfrom = TREE_TYPE (from);
1370 /* Don't try to apply restrict to void. */
1371 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1372 from_pointee = cp_build_qualified_type (void_type_node, quals);
1373 from = build_pointer_type (from_pointee);
1374 conv = build_conv (ck_ptr, from, conv);
1376 else if (TYPE_PTRDATAMEM_P (from))
1378 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1379 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1381 if (same_type_p (fbase, tbase))
1382 /* No base conversion needed. */;
1383 else if (DERIVED_FROM_P (fbase, tbase)
1384 && (same_type_ignoring_top_level_qualifiers_p
1385 (from_pointee, to_pointee)))
1387 from = build_ptrmem_type (tbase, from_pointee);
1388 conv = build_conv (ck_pmem, from, conv);
1390 else
1391 return NULL;
1393 else if (CLASS_TYPE_P (from_pointee)
1394 && CLASS_TYPE_P (to_pointee)
1395 /* [conv.ptr]
1397 An rvalue of type "pointer to cv D," where D is a
1398 class type, can be converted to an rvalue of type
1399 "pointer to cv B," where B is a base class (clause
1400 _class.derived_) of D. If B is an inaccessible
1401 (clause _class.access_) or ambiguous
1402 (_class.member.lookup_) base class of D, a program
1403 that necessitates this conversion is ill-formed.
1404 Therefore, we use DERIVED_FROM_P, and do not check
1405 access or uniqueness. */
1406 && DERIVED_FROM_P (to_pointee, from_pointee))
1408 from_pointee
1409 = cp_build_qualified_type (to_pointee,
1410 cp_type_quals (from_pointee));
1411 from = build_pointer_type (from_pointee);
1412 conv = build_conv (ck_ptr, from, conv);
1413 conv->base_p = true;
1416 if (same_type_p (from, to))
1417 /* OK */;
1418 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1419 /* In a C-style cast, we ignore CV-qualification because we
1420 are allowed to perform a static_cast followed by a
1421 const_cast. */
1422 conv = build_conv (ck_qual, to, conv);
1423 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1424 conv = build_conv (ck_qual, to, conv);
1425 else if (expr && string_conv_p (to, expr, 0))
1426 /* converting from string constant to char *. */
1427 conv = build_conv (ck_qual, to, conv);
1428 else if (fnptr_conv_p (to, from))
1429 conv = build_conv (ck_fnptr, to, conv);
1430 /* Allow conversions among compatible ObjC pointer types (base
1431 conversions have been already handled above). */
1432 else if (c_dialect_objc ()
1433 && objc_compare_types (to, from, -4, NULL_TREE))
1434 conv = build_conv (ck_ptr, to, conv);
1435 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1437 conv = build_conv (ck_ptr, to, conv);
1438 conv->bad_p = true;
1440 else
1441 return NULL;
1443 from = to;
1445 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1447 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1448 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1449 tree fbase = class_of_this_parm (fromfn);
1450 tree tbase = class_of_this_parm (tofn);
1452 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1453 yields false. But a pointer to member of incomplete class is OK. */
1454 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1455 return NULL;
1457 tree fstat = static_fn_type (fromfn);
1458 tree tstat = static_fn_type (tofn);
1459 if (same_type_p (tstat, fstat)
1460 || fnptr_conv_p (tstat, fstat))
1461 /* OK */;
1462 else
1463 return NULL;
1465 if (!same_type_p (fbase, tbase))
1467 from = build_memfn_type (fstat,
1468 tbase,
1469 cp_type_quals (tbase),
1470 type_memfn_rqual (tofn));
1471 from = build_ptrmemfunc_type (build_pointer_type (from));
1472 conv = build_conv (ck_pmem, from, conv);
1473 conv->base_p = true;
1475 if (fnptr_conv_p (tstat, fstat))
1476 conv = build_conv (ck_fnptr, to, conv);
1478 else if (tcode == BOOLEAN_TYPE)
1480 /* [conv.bool]
1482 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1483 to member type can be converted to a prvalue of type bool. ...
1484 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1485 std::nullptr_t can be converted to a prvalue of type bool; */
1486 if (ARITHMETIC_TYPE_P (from)
1487 || UNSCOPED_ENUM_P (from)
1488 || fcode == POINTER_TYPE
1489 || TYPE_PTRMEM_P (from)
1490 || NULLPTR_TYPE_P (from))
1492 conv = build_conv (ck_std, to, conv);
1493 if (fcode == POINTER_TYPE
1494 || TYPE_PTRDATAMEM_P (from)
1495 || (TYPE_PTRMEMFUNC_P (from)
1496 && conv->rank < cr_pbool)
1497 || NULLPTR_TYPE_P (from))
1498 conv->rank = cr_pbool;
1499 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1500 conv->bad_p = true;
1501 if (flags & LOOKUP_NO_NARROWING)
1502 conv->check_narrowing = true;
1503 return conv;
1506 return NULL;
1508 /* We don't check for ENUMERAL_TYPE here because there are no standard
1509 conversions to enum type. */
1510 /* As an extension, allow conversion to complex type. */
1511 else if (ARITHMETIC_TYPE_P (to))
1513 if (! (INTEGRAL_CODE_P (fcode)
1514 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1515 || SCOPED_ENUM_P (from))
1516 return NULL;
1518 /* If we're parsing an enum with no fixed underlying type, we're
1519 dealing with an incomplete type, which renders the conversion
1520 ill-formed. */
1521 if (!COMPLETE_TYPE_P (from))
1522 return NULL;
1524 conv = build_conv (ck_std, to, conv);
1526 tree underlying_type = NULL_TREE;
1527 if (TREE_CODE (from) == ENUMERAL_TYPE
1528 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1529 underlying_type = ENUM_UNDERLYING_TYPE (from);
1531 /* Give this a better rank if it's a promotion.
1533 To handle CWG 1601, also bump the rank if we are converting
1534 an enumeration with a fixed underlying type to the underlying
1535 type. */
1536 if ((same_type_p (to, type_promotes_to (from))
1537 || (underlying_type && same_type_p (to, underlying_type)))
1538 && next_conversion (conv)->rank <= cr_promotion)
1539 conv->rank = cr_promotion;
1541 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1542 && vector_types_convertible_p (from, to, false))
1543 return build_conv (ck_std, to, conv);
1544 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1545 && is_properly_derived_from (from, to))
1547 if (conv->kind == ck_rvalue)
1548 conv = next_conversion (conv);
1549 conv = build_conv (ck_base, to, conv);
1550 /* The derived-to-base conversion indicates the initialization
1551 of a parameter with base type from an object of a derived
1552 type. A temporary object is created to hold the result of
1553 the conversion unless we're binding directly to a reference. */
1554 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1555 if (flags & LOOKUP_PREFER_RVALUE)
1556 /* Tell convert_like to set LOOKUP_PREFER_RVALUE. */
1557 conv->rvaluedness_matches_p = true;
1558 /* If we're performing copy-initialization, remember to skip
1559 explicit constructors. */
1560 if (flags & LOOKUP_ONLYCONVERTING)
1561 conv->copy_init_p = true;
1563 else
1564 return NULL;
1566 if (flags & LOOKUP_NO_NARROWING)
1567 conv->check_narrowing = true;
1569 return conv;
1572 /* Returns nonzero if T1 is reference-related to T2. */
1574 bool
1575 reference_related_p (tree t1, tree t2)
1577 if (t1 == error_mark_node || t2 == error_mark_node)
1578 return false;
1580 t1 = TYPE_MAIN_VARIANT (t1);
1581 t2 = TYPE_MAIN_VARIANT (t2);
1583 /* [dcl.init.ref]
1585 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1586 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1587 return (similar_type_p (t1, t2)
1588 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1589 && DERIVED_FROM_P (t1, t2)));
1592 /* Returns nonzero if T1 is reference-compatible with T2. */
1594 bool
1595 reference_compatible_p (tree t1, tree t2)
1597 /* [dcl.init.ref]
1599 "cv1 T1" is reference compatible with "cv2 T2" if
1600 a prvalue of type "pointer to cv2 T2" can be converted to the type
1601 "pointer to cv1 T1" via a standard conversion sequence. */
1602 tree ptype1 = build_pointer_type (t1);
1603 tree ptype2 = build_pointer_type (t2);
1604 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1605 /*c_cast_p=*/false, 0, tf_none);
1606 if (!conv || conv->bad_p)
1607 return false;
1608 return true;
1611 /* Return true if converting FROM to TO would involve a qualification
1612 conversion. */
1614 static bool
1615 involves_qualification_conversion_p (tree to, tree from)
1617 /* If we're not convering a pointer to another one, we won't get
1618 a qualification conversion. */
1619 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1620 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1621 return false;
1623 conversion *conv = standard_conversion (to, from, NULL_TREE,
1624 /*c_cast_p=*/false, 0, tf_none);
1625 for (conversion *t = conv; t; t = next_conversion (t))
1626 if (t->kind == ck_qual)
1627 return true;
1629 return false;
1632 /* A reference of the indicated TYPE is being bound directly to the
1633 expression represented by the implicit conversion sequence CONV.
1634 Return a conversion sequence for this binding. */
1636 static conversion *
1637 direct_reference_binding (tree type, conversion *conv)
1639 tree t;
1641 gcc_assert (TYPE_REF_P (type));
1642 gcc_assert (!TYPE_REF_P (conv->type));
1644 t = TREE_TYPE (type);
1646 if (conv->kind == ck_identity)
1647 /* Mark the identity conv as to not decay to rvalue. */
1648 conv->rvaluedness_matches_p = true;
1650 /* [over.ics.rank]
1652 When a parameter of reference type binds directly
1653 (_dcl.init.ref_) to an argument expression, the implicit
1654 conversion sequence is the identity conversion, unless the
1655 argument expression has a type that is a derived class of the
1656 parameter type, in which case the implicit conversion sequence is
1657 a derived-to-base Conversion.
1659 If the parameter binds directly to the result of applying a
1660 conversion function to the argument expression, the implicit
1661 conversion sequence is a user-defined conversion sequence
1662 (_over.ics.user_), with the second standard conversion sequence
1663 either an identity conversion or, if the conversion function
1664 returns an entity of a type that is a derived class of the
1665 parameter type, a derived-to-base conversion. */
1666 if (is_properly_derived_from (conv->type, t))
1668 /* Represent the derived-to-base conversion. */
1669 conv = build_conv (ck_base, t, conv);
1670 /* We will actually be binding to the base-class subobject in
1671 the derived class, so we mark this conversion appropriately.
1672 That way, convert_like knows not to generate a temporary. */
1673 conv->need_temporary_p = false;
1675 else if (involves_qualification_conversion_p (t, conv->type))
1676 /* Represent the qualification conversion. After DR 2352
1677 #1 and #2 were indistinguishable conversion sequences:
1679 void f(int*); // #1
1680 void f(const int* const &); // #2
1681 void g(int* p) { f(p); }
1683 because the types "int *" and "const int *const" are
1684 reference-related and we were binding both directly and they
1685 had the same rank. To break it up, we add a ck_qual under the
1686 ck_ref_bind so that conversion sequence ranking chooses #1. */
1687 conv = build_conv (ck_qual, t, conv);
1689 return build_conv (ck_ref_bind, type, conv);
1692 /* Returns the conversion path from type FROM to reference type TO for
1693 purposes of reference binding. For lvalue binding, either pass a
1694 reference type to FROM or an lvalue expression to EXPR. If the
1695 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1696 the conversion returned. If C_CAST_P is true, this
1697 conversion is coming from a C-style cast. */
1699 static conversion *
1700 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1701 tsubst_flags_t complain)
1703 conversion *conv = NULL;
1704 tree to = TREE_TYPE (rto);
1705 tree from = rfrom;
1706 tree tfrom;
1707 bool related_p;
1708 bool compatible_p;
1709 cp_lvalue_kind gl_kind;
1710 bool is_lvalue;
1712 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1714 expr = instantiate_type (to, expr, tf_none);
1715 if (expr == error_mark_node)
1716 return NULL;
1717 from = TREE_TYPE (expr);
1720 bool copy_list_init = false;
1721 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1723 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1724 /* DR 1288: Otherwise, if the initializer list has a single element
1725 of type E and ... [T's] referenced type is reference-related to E,
1726 the object or reference is initialized from that element...
1728 ??? With P0388R4, we should bind 't' directly to U{}:
1729 using U = A[2];
1730 A (&&t)[] = {U{}};
1731 because A[] and A[2] are reference-related. But we don't do it
1732 because grok_reference_init has deduced the array size (to 1), and
1733 A[1] and A[2] aren't reference-related. */
1734 if (CONSTRUCTOR_NELTS (expr) == 1
1735 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1737 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1738 if (error_operand_p (elt))
1739 return NULL;
1740 tree etype = TREE_TYPE (elt);
1741 if (reference_related_p (to, etype))
1743 expr = elt;
1744 from = etype;
1745 goto skip;
1748 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1749 referenced by T is copy-list-initialized, and the reference is bound
1750 to that temporary. */
1751 copy_list_init = true;
1752 skip:;
1755 if (TYPE_REF_P (from))
1757 from = TREE_TYPE (from);
1758 if (!TYPE_REF_IS_RVALUE (rfrom)
1759 || TREE_CODE (from) == FUNCTION_TYPE)
1760 gl_kind = clk_ordinary;
1761 else
1762 gl_kind = clk_rvalueref;
1764 else if (expr)
1765 gl_kind = lvalue_kind (expr);
1766 else if (CLASS_TYPE_P (from)
1767 || TREE_CODE (from) == ARRAY_TYPE)
1768 gl_kind = clk_class;
1769 else
1770 gl_kind = clk_none;
1772 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1773 if ((flags & LOOKUP_NO_TEMP_BIND)
1774 && (gl_kind & clk_class))
1775 gl_kind = clk_none;
1777 /* Same mask as real_lvalue_p. */
1778 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1780 tfrom = from;
1781 if ((gl_kind & clk_bitfield) != 0)
1782 tfrom = unlowered_expr_type (expr);
1784 /* Figure out whether or not the types are reference-related and
1785 reference compatible. We have to do this after stripping
1786 references from FROM. */
1787 related_p = reference_related_p (to, tfrom);
1788 /* If this is a C cast, first convert to an appropriately qualified
1789 type, so that we can later do a const_cast to the desired type. */
1790 if (related_p && c_cast_p
1791 && !at_least_as_qualified_p (to, tfrom))
1792 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1793 compatible_p = reference_compatible_p (to, tfrom);
1795 /* Directly bind reference when target expression's type is compatible with
1796 the reference and expression is an lvalue. In DR391, the wording in
1797 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1798 const and rvalue references to rvalues of compatible class type.
1799 We should also do direct bindings for non-class xvalues. */
1800 if ((related_p || compatible_p) && gl_kind)
1802 /* [dcl.init.ref]
1804 If the initializer expression
1806 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1807 is reference-compatible with "cv2 T2,"
1809 the reference is bound directly to the initializer expression
1810 lvalue.
1812 [...]
1813 If the initializer expression is an rvalue, with T2 a class type,
1814 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1815 is bound to the object represented by the rvalue or to a sub-object
1816 within that object. */
1818 conv = build_identity_conv (tfrom, expr);
1819 conv = direct_reference_binding (rto, conv);
1821 if (TYPE_REF_P (rfrom))
1822 /* Handle rvalue reference to function properly. */
1823 conv->rvaluedness_matches_p
1824 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1825 else
1826 conv->rvaluedness_matches_p
1827 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1829 if ((gl_kind & clk_bitfield) != 0
1830 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1831 /* For the purposes of overload resolution, we ignore the fact
1832 this expression is a bitfield or packed field. (In particular,
1833 [over.ics.ref] says specifically that a function with a
1834 non-const reference parameter is viable even if the
1835 argument is a bitfield.)
1837 However, when we actually call the function we must create
1838 a temporary to which to bind the reference. If the
1839 reference is volatile, or isn't const, then we cannot make
1840 a temporary, so we just issue an error when the conversion
1841 actually occurs. */
1842 conv->need_temporary_p = true;
1844 /* Don't allow binding of lvalues (other than function lvalues) to
1845 rvalue references. */
1846 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1847 && TREE_CODE (to) != FUNCTION_TYPE)
1848 conv->bad_p = true;
1850 /* Nor the reverse. */
1851 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1852 /* Unless it's really an lvalue. */
1853 && !(cxx_dialect >= cxx20
1854 && (gl_kind & clk_implicit_rval))
1855 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1856 || (flags & LOOKUP_NO_RVAL_BIND))
1857 && TREE_CODE (to) != FUNCTION_TYPE)
1858 conv->bad_p = true;
1860 if (!compatible_p)
1861 conv->bad_p = true;
1863 return conv;
1865 /* [class.conv.fct] A conversion function is never used to convert a
1866 (possibly cv-qualified) object to the (possibly cv-qualified) same
1867 object type (or a reference to it), to a (possibly cv-qualified) base
1868 class of that type (or a reference to it).... */
1869 else if (CLASS_TYPE_P (from) && !related_p
1870 && !(flags & LOOKUP_NO_CONVERSION))
1872 /* [dcl.init.ref]
1874 If the initializer expression
1876 -- has a class type (i.e., T2 is a class type) can be
1877 implicitly converted to an lvalue of type "cv3 T3," where
1878 "cv1 T1" is reference-compatible with "cv3 T3". (this
1879 conversion is selected by enumerating the applicable
1880 conversion functions (_over.match.ref_) and choosing the
1881 best one through overload resolution. (_over.match_).
1883 the reference is bound to the lvalue result of the conversion
1884 in the second case. */
1885 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1886 complain);
1887 if (cand)
1888 return cand->second_conv;
1891 /* From this point on, we conceptually need temporaries, even if we
1892 elide them. Only the cases above are "direct bindings". */
1893 if (flags & LOOKUP_NO_TEMP_BIND)
1894 return NULL;
1896 /* [over.ics.rank]
1898 When a parameter of reference type is not bound directly to an
1899 argument expression, the conversion sequence is the one required
1900 to convert the argument expression to the underlying type of the
1901 reference according to _over.best.ics_. Conceptually, this
1902 conversion sequence corresponds to copy-initializing a temporary
1903 of the underlying type with the argument expression. Any
1904 difference in top-level cv-qualification is subsumed by the
1905 initialization itself and does not constitute a conversion. */
1907 /* [dcl.init.ref]
1909 Otherwise, the reference shall be an lvalue reference to a
1910 non-volatile const type, or the reference shall be an rvalue
1911 reference.
1913 We try below to treat this as a bad conversion to improve diagnostics,
1914 but if TO is an incomplete class, we need to reject this conversion
1915 now to avoid unnecessary instantiation. */
1916 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto)
1917 && !COMPLETE_TYPE_P (to))
1918 return NULL;
1920 /* We're generating a temporary now, but don't bind any more in the
1921 conversion (specifically, don't slice the temporary returned by a
1922 conversion operator). */
1923 flags |= LOOKUP_NO_TEMP_BIND;
1925 /* Core issue 899: When [copy-]initializing a temporary to be bound
1926 to the first parameter of a copy constructor (12.8) called with
1927 a single argument in the context of direct-initialization,
1928 explicit conversion functions are also considered.
1930 So don't set LOOKUP_ONLYCONVERTING in that case. */
1931 if (!(flags & LOOKUP_COPY_PARM))
1932 flags |= LOOKUP_ONLYCONVERTING;
1934 if (!conv)
1935 conv = implicit_conversion (to, from, expr, c_cast_p,
1936 flags, complain);
1937 if (!conv)
1938 return NULL;
1940 if (conv->user_conv_p)
1942 if (copy_list_init)
1943 /* Remember this was copy-list-initialization. */
1944 conv->need_temporary_p = true;
1946 /* If initializing the temporary used a conversion function,
1947 recalculate the second conversion sequence. */
1948 for (conversion *t = conv; t; t = next_conversion (t))
1949 if (t->kind == ck_user
1950 && DECL_CONV_FN_P (t->cand->fn))
1952 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
1953 /* A prvalue of non-class type is cv-unqualified. */
1954 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
1955 ftype = cv_unqualified (ftype);
1956 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
1957 conversion *new_second
1958 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
1959 sflags, complain);
1960 if (!new_second)
1961 return NULL;
1962 return merge_conversion_sequences (t, new_second);
1966 conv = build_conv (ck_ref_bind, rto, conv);
1967 /* This reference binding, unlike those above, requires the
1968 creation of a temporary. */
1969 conv->need_temporary_p = true;
1970 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1972 /* [dcl.init.ref]
1974 Otherwise, the reference shall be an lvalue reference to a
1975 non-volatile const type, or the reference shall be an rvalue
1976 reference. */
1977 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1978 conv->bad_p = true;
1980 /* [dcl.init.ref]
1982 Otherwise, a temporary of type "cv1 T1" is created and
1983 initialized from the initializer expression using the rules for a
1984 non-reference copy initialization. If T1 is reference-related to
1985 T2, cv1 must be the same cv-qualification as, or greater
1986 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1987 if (related_p && !at_least_as_qualified_p (to, from))
1988 conv->bad_p = true;
1990 return conv;
1993 /* Most of the implementation of implicit_conversion, with the same
1994 parameters. */
1996 static conversion *
1997 implicit_conversion_1 (tree to, tree from, tree expr, bool c_cast_p,
1998 int flags, tsubst_flags_t complain)
2000 conversion *conv;
2002 if (from == error_mark_node || to == error_mark_node
2003 || expr == error_mark_node)
2004 return NULL;
2006 /* Other flags only apply to the primary function in overload
2007 resolution, or after we've chosen one. */
2008 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2009 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_PREFER_RVALUE
2010 |LOOKUP_NO_NARROWING|LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL);
2012 /* FIXME: actually we don't want warnings either, but we can't just
2013 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2014 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2015 We really ought not to issue that warning until we've committed
2016 to that conversion. */
2017 complain &= ~tf_error;
2019 /* Call reshape_init early to remove redundant braces. */
2020 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr)
2021 && CLASS_TYPE_P (to)
2022 && COMPLETE_TYPE_P (complete_type (to))
2023 && !CLASSTYPE_NON_AGGREGATE (to))
2025 expr = reshape_init (to, expr, complain);
2026 if (expr == error_mark_node)
2027 return NULL;
2028 from = TREE_TYPE (expr);
2031 if (TYPE_REF_P (to))
2032 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2033 else
2034 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2036 if (conv)
2037 return conv;
2039 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2041 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2042 return build_list_conv (to, expr, flags, complain);
2044 /* As an extension, allow list-initialization of _Complex. */
2045 if (TREE_CODE (to) == COMPLEX_TYPE
2046 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2048 conv = build_complex_conv (to, expr, flags, complain);
2049 if (conv)
2050 return conv;
2053 /* Allow conversion from an initializer-list with one element to a
2054 scalar type. */
2055 if (SCALAR_TYPE_P (to))
2057 int nelts = CONSTRUCTOR_NELTS (expr);
2058 tree elt;
2060 if (nelts == 0)
2061 elt = build_value_init (to, tf_none);
2062 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2063 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2064 else
2065 elt = error_mark_node;
2067 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2068 c_cast_p, flags, complain);
2069 if (conv)
2071 conv->check_narrowing = true;
2072 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2073 /* Too many levels of braces, i.e. '{{1}}'. */
2074 conv->bad_p = true;
2075 return conv;
2078 else if (TREE_CODE (to) == ARRAY_TYPE)
2079 return build_array_conv (to, expr, flags, complain);
2082 if (expr != NULL_TREE
2083 && (MAYBE_CLASS_TYPE_P (from)
2084 || MAYBE_CLASS_TYPE_P (to))
2085 && (flags & LOOKUP_NO_CONVERSION) == 0)
2087 struct z_candidate *cand;
2089 if (CLASS_TYPE_P (to)
2090 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2091 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2092 return build_aggr_conv (to, expr, flags, complain);
2094 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2095 if (cand)
2097 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2098 && CONSTRUCTOR_NELTS (expr) == 1
2099 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2100 && !is_list_ctor (cand->fn))
2102 /* "If C is not an initializer-list constructor and the
2103 initializer list has a single element of type cv U, where U is
2104 X or a class derived from X, the implicit conversion sequence
2105 has Exact Match rank if U is X, or Conversion rank if U is
2106 derived from X." */
2107 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2108 tree elttype = TREE_TYPE (elt);
2109 if (reference_related_p (to, elttype))
2110 return implicit_conversion (to, elttype, elt,
2111 c_cast_p, flags, complain);
2113 conv = cand->second_conv;
2116 /* We used to try to bind a reference to a temporary here, but that
2117 is now handled after the recursive call to this function at the end
2118 of reference_binding. */
2119 return conv;
2122 return NULL;
2125 /* Returns the implicit conversion sequence (see [over.ics]) from type
2126 FROM to type TO. The optional expression EXPR may affect the
2127 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2128 true, this conversion is coming from a C-style cast. */
2130 static conversion *
2131 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2132 int flags, tsubst_flags_t complain)
2134 conversion *conv = implicit_conversion_1 (to, from, expr, c_cast_p,
2135 flags, complain);
2136 if (!conv || conv->bad_p)
2137 return conv;
2138 if (conv_is_prvalue (conv)
2139 && CLASS_TYPE_P (conv->type)
2140 && CLASSTYPE_PURE_VIRTUALS (conv->type))
2141 conv->bad_p = true;
2142 return conv;
2145 /* Like implicit_conversion, but return NULL if the conversion is bad.
2147 This is not static so that check_non_deducible_conversion can call it within
2148 add_template_candidate_real as part of overload resolution; it should not be
2149 called outside of overload resolution. */
2151 conversion *
2152 good_conversion (tree to, tree from, tree expr,
2153 int flags, tsubst_flags_t complain)
2155 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2156 flags, complain);
2157 if (c && c->bad_p)
2158 c = NULL;
2159 return c;
2162 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2163 functions. ARGS will not be changed until a single candidate is
2164 selected. */
2166 static struct z_candidate *
2167 add_candidate (struct z_candidate **candidates,
2168 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2169 size_t num_convs, conversion **convs,
2170 tree access_path, tree conversion_path,
2171 int viable, struct rejection_reason *reason,
2172 int flags)
2174 struct z_candidate *cand = (struct z_candidate *)
2175 conversion_obstack_alloc (sizeof (struct z_candidate));
2177 cand->fn = fn;
2178 cand->first_arg = first_arg;
2179 cand->args = args;
2180 cand->convs = convs;
2181 cand->num_convs = num_convs;
2182 cand->access_path = access_path;
2183 cand->conversion_path = conversion_path;
2184 cand->viable = viable;
2185 cand->reason = reason;
2186 cand->next = *candidates;
2187 cand->flags = flags;
2188 *candidates = cand;
2190 if (convs && cand->reversed ())
2191 /* Swap the conversions for comparison in joust; we'll swap them back
2192 before build_over_call. */
2193 std::swap (convs[0], convs[1]);
2195 return cand;
2198 /* Return the number of remaining arguments in the parameter list
2199 beginning with ARG. */
2202 remaining_arguments (tree arg)
2204 int n;
2206 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2207 arg = TREE_CHAIN (arg))
2208 n++;
2210 return n;
2213 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2214 to the first parameter of a constructor where the parameter is of type
2215 "reference to possibly cv-qualified T" and the constructor is called with a
2216 single argument in the context of direct-initialization of an object of type
2217 "cv2 T", explicit conversion functions are also considered.
2219 So set LOOKUP_COPY_PARM to let reference_binding know that
2220 it's being called in that context. */
2223 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2225 int lflags = flags;
2226 tree t;
2227 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2228 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2229 && (same_type_ignoring_top_level_qualifiers_p
2230 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2232 if (!(flags & LOOKUP_ONLYCONVERTING))
2233 lflags |= LOOKUP_COPY_PARM;
2234 if ((flags & LOOKUP_LIST_INIT_CTOR)
2235 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2236 lflags |= LOOKUP_NO_CONVERSION;
2238 else
2239 lflags |= LOOKUP_ONLYCONVERTING;
2241 return lflags;
2244 /* Create an overload candidate for the function or method FN called
2245 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2246 FLAGS is passed on to implicit_conversion.
2248 This does not change ARGS.
2250 CTYPE, if non-NULL, is the type we want to pretend this function
2251 comes from for purposes of overload resolution. */
2253 static struct z_candidate *
2254 add_function_candidate (struct z_candidate **candidates,
2255 tree fn, tree ctype, tree first_arg,
2256 const vec<tree, va_gc> *args, tree access_path,
2257 tree conversion_path, int flags,
2258 conversion **convs,
2259 tsubst_flags_t complain)
2261 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2262 int i, len;
2263 tree parmnode;
2264 tree orig_first_arg = first_arg;
2265 int skip;
2266 int viable = 1;
2267 struct rejection_reason *reason = NULL;
2269 /* The `this', `in_chrg' and VTT arguments to constructors are not
2270 considered in overload resolution. */
2271 if (DECL_CONSTRUCTOR_P (fn))
2273 if (ctor_omit_inherited_parms (fn))
2274 /* Bring back parameters omitted from an inherited ctor. */
2275 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2276 else
2277 parmlist = skip_artificial_parms_for (fn, parmlist);
2278 skip = num_artificial_parms_for (fn);
2279 if (skip > 0 && first_arg != NULL_TREE)
2281 --skip;
2282 first_arg = NULL_TREE;
2285 else
2286 skip = 0;
2288 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2289 if (!convs)
2290 convs = alloc_conversions (len);
2292 /* 13.3.2 - Viable functions [over.match.viable]
2293 First, to be a viable function, a candidate function shall have enough
2294 parameters to agree in number with the arguments in the list.
2296 We need to check this first; otherwise, checking the ICSes might cause
2297 us to produce an ill-formed template instantiation. */
2299 parmnode = parmlist;
2300 for (i = 0; i < len; ++i)
2302 if (parmnode == NULL_TREE || parmnode == void_list_node)
2303 break;
2304 parmnode = TREE_CHAIN (parmnode);
2307 if ((i < len && parmnode)
2308 || !sufficient_parms_p (parmnode))
2310 int remaining = remaining_arguments (parmnode);
2311 viable = 0;
2312 reason = arity_rejection (first_arg, i + remaining, len);
2315 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2316 parameter of type "reference to cv C" (including such a constructor
2317 instantiated from a template) is excluded from the set of candidate
2318 functions when used to construct an object of type D with an argument list
2319 containing a single argument if C is reference-related to D. */
2320 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2321 && flag_new_inheriting_ctors
2322 && DECL_INHERITED_CTOR (fn))
2324 tree ptype = non_reference (TREE_VALUE (parmlist));
2325 tree dtype = DECL_CONTEXT (fn);
2326 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2327 if (reference_related_p (ptype, dtype)
2328 && reference_related_p (btype, ptype))
2330 viable = false;
2331 reason = inherited_ctor_rejection ();
2335 /* Second, for a function to be viable, its constraints must be
2336 satisfied. */
2337 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2339 reason = constraint_failure ();
2340 viable = false;
2343 /* When looking for a function from a subobject from an implicit
2344 copy/move constructor/operator=, don't consider anything that takes (a
2345 reference to) an unrelated type. See c++/44909 and core 1092. */
2346 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2348 if (DECL_CONSTRUCTOR_P (fn))
2349 i = 1;
2350 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2351 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2352 i = 2;
2353 else
2354 i = 0;
2355 if (i && len == i)
2357 parmnode = chain_index (i-1, parmlist);
2358 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2359 ctype))
2360 viable = 0;
2363 /* This only applies at the top level. */
2364 flags &= ~LOOKUP_DEFAULTED;
2367 if (! viable)
2368 goto out;
2370 /* Third, for F to be a viable function, there shall exist for each
2371 argument an implicit conversion sequence that converts that argument
2372 to the corresponding parameter of F. */
2374 parmnode = parmlist;
2376 for (i = 0; i < len; ++i)
2378 tree argtype, to_type;
2379 tree arg;
2380 conversion *t;
2381 int is_this;
2383 if (parmnode == void_list_node)
2384 break;
2386 if (convs[i])
2388 /* Already set during deduction. */
2389 parmnode = TREE_CHAIN (parmnode);
2390 continue;
2393 if (i == 0 && first_arg != NULL_TREE)
2394 arg = first_arg;
2395 else
2396 arg = CONST_CAST_TREE (
2397 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2398 argtype = lvalue_type (arg);
2400 is_this = (i == 0 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2401 && ! DECL_CONSTRUCTOR_P (fn));
2403 if (parmnode)
2405 tree parmtype = TREE_VALUE (parmnode);
2407 parmnode = TREE_CHAIN (parmnode);
2409 /* The type of the implicit object parameter ('this') for
2410 overload resolution is not always the same as for the
2411 function itself; conversion functions are considered to
2412 be members of the class being converted, and functions
2413 introduced by a using-declaration are considered to be
2414 members of the class that uses them.
2416 Since build_over_call ignores the ICS for the `this'
2417 parameter, we can just change the parm type. */
2418 if (ctype && is_this)
2420 parmtype = cp_build_qualified_type
2421 (ctype, cp_type_quals (TREE_TYPE (parmtype)));
2422 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2424 /* If the function has a ref-qualifier, the implicit
2425 object parameter has reference type. */
2426 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2427 parmtype = cp_build_reference_type (parmtype, rv);
2428 /* The special handling of 'this' conversions in compare_ics
2429 does not apply if there is a ref-qualifier. */
2430 is_this = false;
2432 else
2434 parmtype = build_pointer_type (parmtype);
2435 /* We don't use build_this here because we don't want to
2436 capture the object argument until we've chosen a
2437 non-static member function. */
2438 arg = build_address (arg);
2439 argtype = lvalue_type (arg);
2443 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2445 t = implicit_conversion (parmtype, argtype, arg,
2446 /*c_cast_p=*/false, lflags, complain);
2447 to_type = parmtype;
2449 else
2451 t = build_identity_conv (argtype, arg);
2452 t->ellipsis_p = true;
2453 to_type = argtype;
2456 if (t && is_this)
2457 t->this_p = true;
2459 convs[i] = t;
2460 if (! t)
2462 viable = 0;
2463 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2464 EXPR_LOCATION (arg));
2465 break;
2468 if (t->bad_p)
2470 viable = -1;
2471 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2472 EXPR_LOCATION (arg));
2477 out:
2478 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2479 access_path, conversion_path, viable, reason, flags);
2482 /* Create an overload candidate for the conversion function FN which will
2483 be invoked for expression OBJ, producing a pointer-to-function which
2484 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2485 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2486 passed on to implicit_conversion.
2488 Actually, we don't really care about FN; we care about the type it
2489 converts to. There may be multiple conversion functions that will
2490 convert to that type, and we rely on build_user_type_conversion_1 to
2491 choose the best one; so when we create our candidate, we record the type
2492 instead of the function. */
2494 static struct z_candidate *
2495 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2496 const vec<tree, va_gc> *arglist,
2497 tree access_path, tree conversion_path,
2498 tsubst_flags_t complain)
2500 tree totype = TREE_TYPE (TREE_TYPE (fn));
2501 int i, len, viable, flags;
2502 tree parmlist, parmnode;
2503 conversion **convs;
2504 struct rejection_reason *reason;
2506 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2507 parmlist = TREE_TYPE (parmlist);
2508 parmlist = TYPE_ARG_TYPES (parmlist);
2510 len = vec_safe_length (arglist) + 1;
2511 convs = alloc_conversions (len);
2512 parmnode = parmlist;
2513 viable = 1;
2514 flags = LOOKUP_IMPLICIT;
2515 reason = NULL;
2517 /* Don't bother looking up the same type twice. */
2518 if (*candidates && (*candidates)->fn == totype)
2519 return NULL;
2521 for (i = 0; i < len; ++i)
2523 tree arg, argtype, convert_type = NULL_TREE;
2524 conversion *t;
2526 if (i == 0)
2527 arg = obj;
2528 else
2529 arg = (*arglist)[i - 1];
2530 argtype = lvalue_type (arg);
2532 if (i == 0)
2534 t = build_identity_conv (argtype, NULL_TREE);
2535 t = build_conv (ck_user, totype, t);
2536 /* Leave the 'cand' field null; we'll figure out the conversion in
2537 convert_like if this candidate is chosen. */
2538 convert_type = totype;
2540 else if (parmnode == void_list_node)
2541 break;
2542 else if (parmnode)
2544 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2545 /*c_cast_p=*/false, flags, complain);
2546 convert_type = TREE_VALUE (parmnode);
2548 else
2550 t = build_identity_conv (argtype, arg);
2551 t->ellipsis_p = true;
2552 convert_type = argtype;
2555 convs[i] = t;
2556 if (! t)
2557 break;
2559 if (t->bad_p)
2561 viable = -1;
2562 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2563 EXPR_LOCATION (arg));
2566 if (i == 0)
2567 continue;
2569 if (parmnode)
2570 parmnode = TREE_CHAIN (parmnode);
2573 if (i < len
2574 || ! sufficient_parms_p (parmnode))
2576 int remaining = remaining_arguments (parmnode);
2577 viable = 0;
2578 reason = arity_rejection (NULL_TREE, i + remaining, len);
2581 return add_candidate (candidates, totype, obj, arglist, len, convs,
2582 access_path, conversion_path, viable, reason, flags);
2585 static void
2586 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2587 tree type1, tree type2, const vec<tree,va_gc> &args,
2588 tree *argtypes, int flags, tsubst_flags_t complain)
2590 conversion *t;
2591 conversion **convs;
2592 size_t num_convs;
2593 int viable = 1;
2594 tree types[2];
2595 struct rejection_reason *reason = NULL;
2597 types[0] = type1;
2598 types[1] = type2;
2600 num_convs = args.length ();
2601 convs = alloc_conversions (num_convs);
2603 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2604 conversion ops are allowed. We handle that here by just checking for
2605 boolean_type_node because other operators don't ask for it. COND_EXPR
2606 also does contextual conversion to bool for the first operand, but we
2607 handle that in build_conditional_expr, and type1 here is operand 2. */
2608 if (type1 != boolean_type_node)
2609 flags |= LOOKUP_ONLYCONVERTING;
2611 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2613 t = implicit_conversion (types[i], argtypes[i], args[i],
2614 /*c_cast_p=*/false, flags, complain);
2615 if (! t)
2617 viable = 0;
2618 /* We need something for printing the candidate. */
2619 t = build_identity_conv (types[i], NULL_TREE);
2620 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2621 types[i], EXPR_LOCATION (args[i]));
2623 else if (t->bad_p)
2625 viable = 0;
2626 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2627 types[i],
2628 EXPR_LOCATION (args[i]));
2630 convs[i] = t;
2633 /* For COND_EXPR we rearranged the arguments; undo that now. */
2634 if (num_convs == 3)
2636 convs[2] = convs[1];
2637 convs[1] = convs[0];
2638 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2639 /*c_cast_p=*/false, flags,
2640 complain);
2641 if (t)
2642 convs[0] = t;
2643 else
2645 viable = 0;
2646 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2647 boolean_type_node,
2648 EXPR_LOCATION (args[2]));
2652 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2653 num_convs, convs,
2654 /*access_path=*/NULL_TREE,
2655 /*conversion_path=*/NULL_TREE,
2656 viable, reason, flags);
2659 static bool
2660 is_complete (tree t)
2662 return COMPLETE_TYPE_P (complete_type (t));
2665 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2667 static bool
2668 promoted_arithmetic_type_p (tree type)
2670 /* [over.built]
2672 In this section, the term promoted integral type is used to refer
2673 to those integral types which are preserved by integral promotion
2674 (including e.g. int and long but excluding e.g. char).
2675 Similarly, the term promoted arithmetic type refers to promoted
2676 integral types plus floating types. */
2677 return ((CP_INTEGRAL_TYPE_P (type)
2678 && same_type_p (type_promotes_to (type), type))
2679 || TREE_CODE (type) == REAL_TYPE);
2682 /* Create any builtin operator overload candidates for the operator in
2683 question given the converted operand types TYPE1 and TYPE2. The other
2684 args are passed through from add_builtin_candidates to
2685 build_builtin_candidate.
2687 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2688 If CODE is requires candidates operands of the same type of the kind
2689 of which TYPE1 and TYPE2 are, we add both candidates
2690 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2692 static void
2693 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2694 enum tree_code code2, tree fnname, tree type1,
2695 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2696 int flags, tsubst_flags_t complain)
2698 switch (code)
2700 case POSTINCREMENT_EXPR:
2701 case POSTDECREMENT_EXPR:
2702 args[1] = integer_zero_node;
2703 type2 = integer_type_node;
2704 break;
2705 default:
2706 break;
2709 switch (code)
2712 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2713 and VQ is either volatile or empty, there exist candidate operator
2714 functions of the form
2715 VQ T& operator++(VQ T&);
2716 T operator++(VQ T&, int);
2717 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2718 and VQ is either volatile or empty, there exist candidate operator
2719 functions of the form
2720 VQ T& operator--(VQ T&);
2721 T operator--(VQ T&, int);
2722 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2723 type, and VQ is either volatile or empty, there exist candidate operator
2724 functions of the form
2725 T*VQ& operator++(T*VQ&);
2726 T*VQ& operator--(T*VQ&);
2727 T* operator++(T*VQ&, int);
2728 T* operator--(T*VQ&, int); */
2730 case POSTDECREMENT_EXPR:
2731 case PREDECREMENT_EXPR:
2732 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2733 return;
2734 /* FALLTHRU */
2735 case POSTINCREMENT_EXPR:
2736 case PREINCREMENT_EXPR:
2737 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2738 to p4. */
2739 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2740 return;
2741 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2743 type1 = build_reference_type (type1);
2744 break;
2746 return;
2748 /* 7 For every cv-qualified or cv-unqualified object type T, there
2749 exist candidate operator functions of the form
2751 T& operator*(T*);
2754 8 For every function type T that does not have cv-qualifiers or
2755 a ref-qualifier, there exist candidate operator functions of the form
2756 T& operator*(T*); */
2758 case INDIRECT_REF:
2759 if (TYPE_PTR_P (type1)
2760 && (TYPE_PTROB_P (type1)
2761 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2762 break;
2763 return;
2765 /* 9 For every type T, there exist candidate operator functions of the form
2766 T* operator+(T*);
2768 10 For every floating-point or promoted integral type T, there exist
2769 candidate operator functions of the form
2770 T operator+(T);
2771 T operator-(T); */
2773 case UNARY_PLUS_EXPR: /* unary + */
2774 if (TYPE_PTR_P (type1))
2775 break;
2776 /* FALLTHRU */
2777 case NEGATE_EXPR:
2778 if (ARITHMETIC_TYPE_P (type1))
2779 break;
2780 return;
2782 /* 11 For every promoted integral type T, there exist candidate operator
2783 functions of the form
2784 T operator~(T); */
2786 case BIT_NOT_EXPR:
2787 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2788 break;
2789 return;
2791 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2792 is the same type as C2 or is a derived class of C2, and T is an object
2793 type or a function type there exist candidate operator functions of the
2794 form
2795 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2796 where CV12 is the union of CV1 and CV2. */
2798 case MEMBER_REF:
2799 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2801 tree c1 = TREE_TYPE (type1);
2802 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2804 if (MAYBE_CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2805 && (TYPE_PTRMEMFUNC_P (type2)
2806 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2807 break;
2809 return;
2811 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2812 or promoted integral type, there exist candidate operator functions of the
2813 form
2814 LR operator*(L, R);
2815 LR operator/(L, R);
2816 LR operator+(L, R);
2817 LR operator-(L, R);
2818 bool operator<(L, R);
2819 bool operator>(L, R);
2820 bool operator<=(L, R);
2821 bool operator>=(L, R);
2822 bool operator==(L, R);
2823 bool operator!=(L, R);
2824 where LR is the result of the usual arithmetic conversions between
2825 types L and R.
2827 14 For every integral type T there exists a candidate operator function of
2828 the form
2830 std::strong_ordering operator<=>(T, T);
2832 15 For every pair of floating-point types L and R, there exists a candidate
2833 operator function of the form
2835 std::partial_ordering operator<=>(L, R);
2837 16 For every cv-qualified or cv-unqualified object type T there exist
2838 candidate operator functions of the form
2839 T* operator+(T*, std::ptrdiff_t);
2840 T& operator[](T*, std::ptrdiff_t);
2841 T* operator-(T*, std::ptrdiff_t);
2842 T* operator+(std::ptrdiff_t, T*);
2843 T& operator[](std::ptrdiff_t, T*);
2845 17 For every T, where T is a pointer to object type, there exist candidate
2846 operator functions of the form
2847 std::ptrdiff_t operator-(T, T);
2849 18 For every T, where T is an enumeration type or a pointer type, there
2850 exist candidate operator functions of the form
2851 bool operator<(T, T);
2852 bool operator>(T, T);
2853 bool operator<=(T, T);
2854 bool operator>=(T, T);
2855 bool operator==(T, T);
2856 bool operator!=(T, T);
2857 R operator<=>(T, T);
2859 where R is the result type specified in [expr.spaceship].
2861 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2862 there exist candidate operator functions of the form
2863 bool operator==(T, T);
2864 bool operator!=(T, T); */
2866 case MINUS_EXPR:
2867 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2868 break;
2869 if (TYPE_PTROB_P (type1)
2870 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2872 type2 = ptrdiff_type_node;
2873 break;
2875 /* FALLTHRU */
2876 case MULT_EXPR:
2877 case TRUNC_DIV_EXPR:
2878 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2879 break;
2880 return;
2882 /* This isn't exactly what's specified above for operator<=>, but it's
2883 close enough. In particular, we don't care about the return type
2884 specified above; it doesn't participate in overload resolution and it
2885 doesn't affect the semantics of the built-in operator. */
2886 case SPACESHIP_EXPR:
2887 case EQ_EXPR:
2888 case NE_EXPR:
2889 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2890 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2891 break;
2892 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2893 break;
2894 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2896 type2 = type1;
2897 break;
2899 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2901 type1 = type2;
2902 break;
2904 /* Fall through. */
2905 case LT_EXPR:
2906 case GT_EXPR:
2907 case LE_EXPR:
2908 case GE_EXPR:
2909 case MAX_EXPR:
2910 case MIN_EXPR:
2911 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2912 break;
2913 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2914 break;
2915 if (TREE_CODE (type1) == ENUMERAL_TYPE
2916 && TREE_CODE (type2) == ENUMERAL_TYPE)
2917 break;
2918 if (TYPE_PTR_P (type1)
2919 && null_ptr_cst_p (args[1]))
2921 type2 = type1;
2922 break;
2924 if (null_ptr_cst_p (args[0])
2925 && TYPE_PTR_P (type2))
2927 type1 = type2;
2928 break;
2930 return;
2932 case PLUS_EXPR:
2933 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2934 break;
2935 /* FALLTHRU */
2936 case ARRAY_REF:
2937 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
2939 type1 = ptrdiff_type_node;
2940 break;
2942 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2944 type2 = ptrdiff_type_node;
2945 break;
2947 return;
2949 /* 18For every pair of promoted integral types L and R, there exist candi-
2950 date operator functions of the form
2951 LR operator%(L, R);
2952 LR operator&(L, R);
2953 LR operator^(L, R);
2954 LR operator|(L, R);
2955 L operator<<(L, R);
2956 L operator>>(L, R);
2957 where LR is the result of the usual arithmetic conversions between
2958 types L and R. */
2960 case TRUNC_MOD_EXPR:
2961 case BIT_AND_EXPR:
2962 case BIT_IOR_EXPR:
2963 case BIT_XOR_EXPR:
2964 case LSHIFT_EXPR:
2965 case RSHIFT_EXPR:
2966 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2967 break;
2968 return;
2970 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
2971 type, VQ is either volatile or empty, and R is a promoted arithmetic
2972 type, there exist candidate operator functions of the form
2973 VQ L& operator=(VQ L&, R);
2974 VQ L& operator*=(VQ L&, R);
2975 VQ L& operator/=(VQ L&, R);
2976 VQ L& operator+=(VQ L&, R);
2977 VQ L& operator-=(VQ L&, R);
2979 20For every pair T, VQ), where T is any type and VQ is either volatile
2980 or empty, there exist candidate operator functions of the form
2981 T*VQ& operator=(T*VQ&, T*);
2983 21For every pair T, VQ), where T is a pointer to member type and VQ is
2984 either volatile or empty, there exist candidate operator functions of
2985 the form
2986 VQ T& operator=(VQ T&, T);
2988 22For every triple T, VQ, I), where T is a cv-qualified or cv-
2989 unqualified complete object type, VQ is either volatile or empty, and
2990 I is a promoted integral type, there exist candidate operator func-
2991 tions of the form
2992 T*VQ& operator+=(T*VQ&, I);
2993 T*VQ& operator-=(T*VQ&, I);
2995 23For every triple L, VQ, R), where L is an integral or enumeration
2996 type, VQ is either volatile or empty, and R is a promoted integral
2997 type, there exist candidate operator functions of the form
2999 VQ L& operator%=(VQ L&, R);
3000 VQ L& operator<<=(VQ L&, R);
3001 VQ L& operator>>=(VQ L&, R);
3002 VQ L& operator&=(VQ L&, R);
3003 VQ L& operator^=(VQ L&, R);
3004 VQ L& operator|=(VQ L&, R); */
3006 case MODIFY_EXPR:
3007 switch (code2)
3009 case PLUS_EXPR:
3010 case MINUS_EXPR:
3011 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3013 type2 = ptrdiff_type_node;
3014 break;
3016 /* FALLTHRU */
3017 case MULT_EXPR:
3018 case TRUNC_DIV_EXPR:
3019 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3020 break;
3021 return;
3023 case TRUNC_MOD_EXPR:
3024 case BIT_AND_EXPR:
3025 case BIT_IOR_EXPR:
3026 case BIT_XOR_EXPR:
3027 case LSHIFT_EXPR:
3028 case RSHIFT_EXPR:
3029 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3030 break;
3031 return;
3033 case NOP_EXPR:
3034 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3035 break;
3036 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3037 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3038 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3039 || ((TYPE_PTRMEMFUNC_P (type1)
3040 || TYPE_PTR_P (type1))
3041 && null_ptr_cst_p (args[1])))
3043 type2 = type1;
3044 break;
3046 return;
3048 default:
3049 gcc_unreachable ();
3051 type1 = build_reference_type (type1);
3052 break;
3054 case COND_EXPR:
3055 /* [over.built]
3057 For every pair of promoted arithmetic types L and R, there
3058 exist candidate operator functions of the form
3060 LR operator?(bool, L, R);
3062 where LR is the result of the usual arithmetic conversions
3063 between types L and R.
3065 For every type T, where T is a pointer or pointer-to-member
3066 type, there exist candidate operator functions of the form T
3067 operator?(bool, T, T); */
3069 if (promoted_arithmetic_type_p (type1)
3070 && promoted_arithmetic_type_p (type2))
3071 /* That's OK. */
3072 break;
3074 /* Otherwise, the types should be pointers. */
3075 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3076 return;
3078 /* We don't check that the two types are the same; the logic
3079 below will actually create two candidates; one in which both
3080 parameter types are TYPE1, and one in which both parameter
3081 types are TYPE2. */
3082 break;
3084 case REALPART_EXPR:
3085 case IMAGPART_EXPR:
3086 if (ARITHMETIC_TYPE_P (type1))
3087 break;
3088 return;
3090 default:
3091 gcc_unreachable ();
3094 /* Make sure we don't create builtin candidates with dependent types. */
3095 bool u1 = uses_template_parms (type1);
3096 bool u2 = type2 ? uses_template_parms (type2) : false;
3097 if (u1 || u2)
3099 /* Try to recover if one of the types is non-dependent. But if
3100 there's only one type, there's nothing we can do. */
3101 if (!type2)
3102 return;
3103 /* And we lose if both are dependent. */
3104 if (u1 && u2)
3105 return;
3106 /* Or if they have different forms. */
3107 if (TREE_CODE (type1) != TREE_CODE (type2))
3108 return;
3110 if (u1 && !u2)
3111 type1 = type2;
3112 else if (u2 && !u1)
3113 type2 = type1;
3116 /* If we're dealing with two pointer types or two enumeral types,
3117 we need candidates for both of them. */
3118 if (type2 && !same_type_p (type1, type2)
3119 && TREE_CODE (type1) == TREE_CODE (type2)
3120 && (TYPE_REF_P (type1)
3121 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3122 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3123 || TYPE_PTRMEMFUNC_P (type1)
3124 || MAYBE_CLASS_TYPE_P (type1)
3125 || TREE_CODE (type1) == ENUMERAL_TYPE))
3127 if (TYPE_PTR_OR_PTRMEM_P (type1))
3129 tree cptype = composite_pointer_type (input_location,
3130 type1, type2,
3131 error_mark_node,
3132 error_mark_node,
3133 CPO_CONVERSION,
3134 tf_none);
3135 if (cptype != error_mark_node)
3137 build_builtin_candidate
3138 (candidates, fnname, cptype, cptype, args, argtypes,
3139 flags, complain);
3140 return;
3144 build_builtin_candidate
3145 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3146 build_builtin_candidate
3147 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3148 return;
3151 build_builtin_candidate
3152 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3155 tree
3156 type_decays_to (tree type)
3158 if (TREE_CODE (type) == ARRAY_TYPE)
3159 return build_pointer_type (TREE_TYPE (type));
3160 if (TREE_CODE (type) == FUNCTION_TYPE)
3161 return build_pointer_type (type);
3162 return type;
3165 /* There are three conditions of builtin candidates:
3167 1) bool-taking candidates. These are the same regardless of the input.
3168 2) pointer-pair taking candidates. These are generated for each type
3169 one of the input types converts to.
3170 3) arithmetic candidates. According to the standard, we should generate
3171 all of these, but I'm trying not to...
3173 Here we generate a superset of the possible candidates for this particular
3174 case. That is a subset of the full set the standard defines, plus some
3175 other cases which the standard disallows. add_builtin_candidate will
3176 filter out the invalid set. */
3178 static void
3179 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3180 enum tree_code code2, tree fnname,
3181 vec<tree, va_gc> *argv,
3182 int flags, tsubst_flags_t complain)
3184 int ref1;
3185 int enum_p = 0;
3186 tree type, argtypes[3], t;
3187 /* TYPES[i] is the set of possible builtin-operator parameter types
3188 we will consider for the Ith argument. */
3189 vec<tree, va_gc> *types[2];
3190 unsigned ix;
3191 vec<tree, va_gc> &args = *argv;
3192 unsigned len = args.length ();
3194 for (unsigned i = 0; i < len; ++i)
3196 if (args[i])
3197 argtypes[i] = unlowered_expr_type (args[i]);
3198 else
3199 argtypes[i] = NULL_TREE;
3202 switch (code)
3204 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3205 and VQ is either volatile or empty, there exist candidate operator
3206 functions of the form
3207 VQ T& operator++(VQ T&); */
3209 case POSTINCREMENT_EXPR:
3210 case PREINCREMENT_EXPR:
3211 case POSTDECREMENT_EXPR:
3212 case PREDECREMENT_EXPR:
3213 case MODIFY_EXPR:
3214 ref1 = 1;
3215 break;
3217 /* 24There also exist candidate operator functions of the form
3218 bool operator!(bool);
3219 bool operator&&(bool, bool);
3220 bool operator||(bool, bool); */
3222 case TRUTH_NOT_EXPR:
3223 build_builtin_candidate
3224 (candidates, fnname, boolean_type_node,
3225 NULL_TREE, args, argtypes, flags, complain);
3226 return;
3228 case TRUTH_ORIF_EXPR:
3229 case TRUTH_ANDIF_EXPR:
3230 build_builtin_candidate
3231 (candidates, fnname, boolean_type_node,
3232 boolean_type_node, args, argtypes, flags, complain);
3233 return;
3235 case ADDR_EXPR:
3236 case COMPOUND_EXPR:
3237 case COMPONENT_REF:
3238 case CO_AWAIT_EXPR:
3239 return;
3241 case COND_EXPR:
3242 case EQ_EXPR:
3243 case NE_EXPR:
3244 case LT_EXPR:
3245 case LE_EXPR:
3246 case GT_EXPR:
3247 case GE_EXPR:
3248 case SPACESHIP_EXPR:
3249 enum_p = 1;
3250 /* Fall through. */
3252 default:
3253 ref1 = 0;
3256 types[0] = make_tree_vector ();
3257 types[1] = make_tree_vector ();
3259 if (len == 3)
3260 len = 2;
3261 for (unsigned i = 0; i < len; ++i)
3263 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3265 tree convs;
3267 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3268 return;
3270 convs = lookup_conversions (argtypes[i]);
3272 if (code == COND_EXPR)
3274 if (lvalue_p (args[i]))
3275 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3277 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3280 else if (! convs)
3281 return;
3283 for (; convs; convs = TREE_CHAIN (convs))
3285 type = TREE_TYPE (convs);
3287 if (i == 0 && ref1
3288 && (!TYPE_REF_P (type)
3289 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3290 continue;
3292 if (code == COND_EXPR && TYPE_REF_P (type))
3293 vec_safe_push (types[i], type);
3295 type = non_reference (type);
3296 if (i != 0 || ! ref1)
3298 type = cv_unqualified (type_decays_to (type));
3299 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3300 vec_safe_push (types[i], type);
3301 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3302 type = type_promotes_to (type);
3305 if (! vec_member (type, types[i]))
3306 vec_safe_push (types[i], type);
3309 else
3311 if (code == COND_EXPR && lvalue_p (args[i]))
3312 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3313 type = non_reference (argtypes[i]);
3314 if (i != 0 || ! ref1)
3316 type = cv_unqualified (type_decays_to (type));
3317 if (enum_p && UNSCOPED_ENUM_P (type))
3318 vec_safe_push (types[i], type);
3319 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3320 type = type_promotes_to (type);
3322 vec_safe_push (types[i], type);
3326 /* Run through the possible parameter types of both arguments,
3327 creating candidates with those parameter types. */
3328 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3330 unsigned jx;
3331 tree u;
3333 if (!types[1]->is_empty ())
3334 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3335 add_builtin_candidate
3336 (candidates, code, code2, fnname, t,
3337 u, args, argtypes, flags, complain);
3338 else
3339 add_builtin_candidate
3340 (candidates, code, code2, fnname, t,
3341 NULL_TREE, args, argtypes, flags, complain);
3344 release_tree_vector (types[0]);
3345 release_tree_vector (types[1]);
3349 /* If TMPL can be successfully instantiated as indicated by
3350 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3352 TMPL is the template. EXPLICIT_TARGS are any explicit template
3353 arguments. ARGLIST is the arguments provided at the call-site.
3354 This does not change ARGLIST. The RETURN_TYPE is the desired type
3355 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3356 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3357 CTYPE are ignored, and OBJ is as for add_conv_candidate. */
3359 static struct z_candidate*
3360 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3361 tree ctype, tree explicit_targs, tree first_arg,
3362 const vec<tree, va_gc> *arglist, tree return_type,
3363 tree access_path, tree conversion_path,
3364 int flags, tree obj, unification_kind_t strict,
3365 tsubst_flags_t complain)
3367 int ntparms = DECL_NTPARMS (tmpl);
3368 tree targs = make_tree_vec (ntparms);
3369 unsigned int len = vec_safe_length (arglist);
3370 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3371 unsigned int skip_without_in_chrg = 0;
3372 tree first_arg_without_in_chrg = first_arg;
3373 tree *args_without_in_chrg;
3374 unsigned int nargs_without_in_chrg;
3375 unsigned int ia, ix;
3376 tree arg;
3377 struct z_candidate *cand;
3378 tree fn;
3379 struct rejection_reason *reason = NULL;
3380 int errs;
3381 conversion **convs = NULL;
3383 /* We don't do deduction on the in-charge parameter, the VTT
3384 parameter or 'this'. */
3385 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3387 if (first_arg_without_in_chrg != NULL_TREE)
3388 first_arg_without_in_chrg = NULL_TREE;
3389 else if (return_type && strict == DEDUCE_CALL)
3390 /* We're deducing for a call to the result of a template conversion
3391 function, so the args don't contain 'this'; leave them alone. */;
3392 else
3393 ++skip_without_in_chrg;
3396 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3397 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3398 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3400 if (first_arg_without_in_chrg != NULL_TREE)
3401 first_arg_without_in_chrg = NULL_TREE;
3402 else
3403 ++skip_without_in_chrg;
3406 if (len < skip_without_in_chrg)
3407 return NULL;
3409 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3410 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3411 TREE_TYPE ((*arglist)[0])))
3413 /* 12.8/6 says, "A declaration of a constructor for a class X is
3414 ill-formed if its first parameter is of type (optionally cv-qualified)
3415 X and either there are no other parameters or else all other
3416 parameters have default arguments. A member function template is never
3417 instantiated to produce such a constructor signature."
3419 So if we're trying to copy an object of the containing class, don't
3420 consider a template constructor that has a first parameter type that
3421 is just a template parameter, as we would deduce a signature that we
3422 would then reject in the code below. */
3423 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3425 firstparm = TREE_VALUE (firstparm);
3426 if (PACK_EXPANSION_P (firstparm))
3427 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3428 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3430 gcc_assert (!explicit_targs);
3431 reason = invalid_copy_with_fn_template_rejection ();
3432 goto fail;
3437 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3438 + (len - skip_without_in_chrg));
3439 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3440 ia = 0;
3441 if (first_arg_without_in_chrg != NULL_TREE)
3443 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3444 ++ia;
3446 for (ix = skip_without_in_chrg;
3447 vec_safe_iterate (arglist, ix, &arg);
3448 ++ix)
3450 args_without_in_chrg[ia] = arg;
3451 ++ia;
3453 gcc_assert (ia == nargs_without_in_chrg);
3455 errs = errorcount+sorrycount;
3456 if (!obj)
3457 convs = alloc_conversions (nargs);
3458 fn = fn_type_unification (tmpl, explicit_targs, targs,
3459 args_without_in_chrg,
3460 nargs_without_in_chrg,
3461 return_type, strict, flags, convs,
3462 false, complain & tf_decltype);
3464 if (fn == error_mark_node)
3466 /* Don't repeat unification later if it already resulted in errors. */
3467 if (errorcount+sorrycount == errs)
3468 reason = template_unification_rejection (tmpl, explicit_targs,
3469 targs, args_without_in_chrg,
3470 nargs_without_in_chrg,
3471 return_type, strict, flags);
3472 else
3473 reason = template_unification_error_rejection ();
3474 goto fail;
3477 /* Now the explicit specifier might have been deduced; check if this
3478 declaration is explicit. If it is and we're ignoring non-converting
3479 constructors, don't add this function to the set of candidates. */
3480 if ((flags & LOOKUP_ONLYCONVERTING) && DECL_NONCONVERTING_P (fn))
3481 return NULL;
3483 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3485 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3486 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3487 ctype))
3489 /* We're trying to produce a constructor with a prohibited signature,
3490 as discussed above; handle here any cases we didn't catch then,
3491 such as X(X<T>). */
3492 reason = invalid_copy_with_fn_template_rejection ();
3493 goto fail;
3497 if (obj != NULL_TREE)
3498 /* Aha, this is a conversion function. */
3499 cand = add_conv_candidate (candidates, fn, obj, arglist,
3500 access_path, conversion_path, complain);
3501 else
3502 cand = add_function_candidate (candidates, fn, ctype,
3503 first_arg, arglist, access_path,
3504 conversion_path, flags, convs, complain);
3505 if (DECL_TI_TEMPLATE (fn) != tmpl)
3506 /* This situation can occur if a member template of a template
3507 class is specialized. Then, instantiate_template might return
3508 an instantiation of the specialization, in which case the
3509 DECL_TI_TEMPLATE field will point at the original
3510 specialization. For example:
3512 template <class T> struct S { template <class U> void f(U);
3513 template <> void f(int) {}; };
3514 S<double> sd;
3515 sd.f(3);
3517 Here, TMPL will be template <class U> S<double>::f(U).
3518 And, instantiate template will give us the specialization
3519 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3520 for this will point at template <class T> template <> S<T>::f(int),
3521 so that we can find the definition. For the purposes of
3522 overload resolution, however, we want the original TMPL. */
3523 cand->template_decl = build_template_info (tmpl, targs);
3524 else
3525 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3526 cand->explicit_targs = explicit_targs;
3528 return cand;
3529 fail:
3530 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, NULL,
3531 access_path, conversion_path, 0, reason, flags);
3535 static struct z_candidate *
3536 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3537 tree explicit_targs, tree first_arg,
3538 const vec<tree, va_gc> *arglist, tree return_type,
3539 tree access_path, tree conversion_path, int flags,
3540 unification_kind_t strict, tsubst_flags_t complain)
3542 return
3543 add_template_candidate_real (candidates, tmpl, ctype,
3544 explicit_targs, first_arg, arglist,
3545 return_type, access_path, conversion_path,
3546 flags, NULL_TREE, strict, complain);
3549 /* Create an overload candidate for the conversion function template TMPL,
3550 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3551 pointer-to-function which will in turn be called with the argument list
3552 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3553 passed on to implicit_conversion. */
3555 static struct z_candidate *
3556 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3557 tree obj,
3558 const vec<tree, va_gc> *arglist,
3559 tree return_type, tree access_path,
3560 tree conversion_path, tsubst_flags_t complain)
3562 /* Making this work broke PR 71117 and 85118, so until the committee resolves
3563 core issue 2189, let's disable this candidate if there are any call
3564 operators. */
3565 if (*candidates)
3566 return NULL;
3568 return
3569 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3570 NULL_TREE, arglist, return_type, access_path,
3571 conversion_path, 0, obj, DEDUCE_CALL,
3572 complain);
3575 /* The CANDS are the set of candidates that were considered for
3576 overload resolution. Return the set of viable candidates, or CANDS
3577 if none are viable. If any of the candidates were viable, set
3578 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3579 considered viable only if it is strictly viable. */
3581 static struct z_candidate*
3582 splice_viable (struct z_candidate *cands,
3583 bool strict_p,
3584 bool *any_viable_p)
3586 struct z_candidate *viable;
3587 struct z_candidate **last_viable;
3588 struct z_candidate **cand;
3589 bool found_strictly_viable = false;
3591 /* Be strict inside templates, since build_over_call won't actually
3592 do the conversions to get pedwarns. */
3593 if (processing_template_decl)
3594 strict_p = true;
3596 viable = NULL;
3597 last_viable = &viable;
3598 *any_viable_p = false;
3600 cand = &cands;
3601 while (*cand)
3603 struct z_candidate *c = *cand;
3604 if (!strict_p
3605 && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3607 /* Be strict in the presence of a viable candidate. Also if
3608 there are template candidates, so that we get deduction errors
3609 for them instead of silently preferring a bad conversion. */
3610 strict_p = true;
3611 if (viable && !found_strictly_viable)
3613 /* Put any spliced near matches back onto the main list so
3614 that we see them if there is no strict match. */
3615 *any_viable_p = false;
3616 *last_viable = cands;
3617 cands = viable;
3618 viable = NULL;
3619 last_viable = &viable;
3623 if (strict_p ? c->viable == 1 : c->viable)
3625 *last_viable = c;
3626 *cand = c->next;
3627 c->next = NULL;
3628 last_viable = &c->next;
3629 *any_viable_p = true;
3630 if (c->viable == 1)
3631 found_strictly_viable = true;
3633 else
3634 cand = &c->next;
3637 return viable ? viable : cands;
3640 static bool
3641 any_strictly_viable (struct z_candidate *cands)
3643 for (; cands; cands = cands->next)
3644 if (cands->viable == 1)
3645 return true;
3646 return false;
3649 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3650 words, it is about to become the "this" pointer for a member
3651 function call. Take the address of the object. */
3653 static tree
3654 build_this (tree obj)
3656 /* In a template, we are only concerned about the type of the
3657 expression, so we can take a shortcut. */
3658 if (processing_template_decl)
3659 return build_address (obj);
3661 return cp_build_addr_expr (obj, tf_warning_or_error);
3664 /* Returns true iff functions are equivalent. Equivalent functions are
3665 not '==' only if one is a function-local extern function or if
3666 both are extern "C". */
3668 static inline int
3669 equal_functions (tree fn1, tree fn2)
3671 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3672 return 0;
3673 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3674 return fn1 == fn2;
3675 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3676 || DECL_EXTERN_C_FUNCTION_P (fn1))
3677 return decls_match (fn1, fn2);
3678 return fn1 == fn2;
3681 /* Print information about a candidate FN being rejected due to INFO. */
3683 static void
3684 print_conversion_rejection (location_t loc, struct conversion_info *info,
3685 tree fn)
3687 tree from = info->from;
3688 if (!TYPE_P (from))
3689 from = lvalue_type (from);
3690 if (info->n_arg == -1)
3692 /* Conversion of implicit `this' argument failed. */
3693 if (!TYPE_P (info->from))
3694 /* A bad conversion for 'this' must be discarding cv-quals. */
3695 inform (loc, " passing %qT as %<this%> "
3696 "argument discards qualifiers",
3697 from);
3698 else
3699 inform (loc, " no known conversion for implicit "
3700 "%<this%> parameter from %qH to %qI",
3701 from, info->to_type);
3703 else if (!TYPE_P (info->from))
3705 if (info->n_arg >= 0)
3706 inform (loc, " conversion of argument %d would be ill-formed:",
3707 info->n_arg + 1);
3708 perform_implicit_conversion (info->to_type, info->from,
3709 tf_warning_or_error);
3711 else if (info->n_arg == -2)
3712 /* Conversion of conversion function return value failed. */
3713 inform (loc, " no known conversion from %qH to %qI",
3714 from, info->to_type);
3715 else
3717 if (TREE_CODE (fn) == FUNCTION_DECL)
3718 loc = get_fndecl_argument_location (fn, info->n_arg);
3719 inform (loc, " no known conversion for argument %d from %qH to %qI",
3720 info->n_arg + 1, from, info->to_type);
3724 /* Print information about a candidate with WANT parameters and we found
3725 HAVE. */
3727 static void
3728 print_arity_information (location_t loc, unsigned int have, unsigned int want)
3730 inform_n (loc, want,
3731 " candidate expects %d argument, %d provided",
3732 " candidate expects %d arguments, %d provided",
3733 want, have);
3736 /* Print information about one overload candidate CANDIDATE. MSGSTR
3737 is the text to print before the candidate itself.
3739 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3740 to have been run through gettext by the caller. This wart makes
3741 life simpler in print_z_candidates and for the translators. */
3743 static void
3744 print_z_candidate (location_t loc, const char *msgstr,
3745 struct z_candidate *candidate)
3747 const char *msg = (msgstr == NULL
3748 ? ""
3749 : ACONCAT ((_(msgstr), " ", NULL)));
3750 tree fn = candidate->fn;
3751 if (flag_new_inheriting_ctors)
3752 fn = strip_inheriting_ctors (fn);
3753 location_t cloc = location_of (fn);
3755 if (identifier_p (fn))
3757 cloc = loc;
3758 if (candidate->num_convs == 3)
3759 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3760 candidate->convs[0]->type,
3761 candidate->convs[1]->type,
3762 candidate->convs[2]->type);
3763 else if (candidate->num_convs == 2)
3764 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3765 candidate->convs[0]->type,
3766 candidate->convs[1]->type);
3767 else
3768 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3769 candidate->convs[0]->type);
3771 else if (TYPE_P (fn))
3772 inform (cloc, "%s%qT (conversion)", msg, fn);
3773 else if (candidate->viable == -1)
3774 inform (cloc, "%s%#qD (near match)", msg, fn);
3775 else if (DECL_DELETED_FN (fn))
3776 inform (cloc, "%s%#qD (deleted)", msg, fn);
3777 else if (candidate->reversed ())
3778 inform (cloc, "%s%#qD (reversed)", msg, fn);
3779 else if (candidate->rewritten ())
3780 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3781 else
3782 inform (cloc, "%s%#qD", msg, fn);
3783 if (fn != candidate->fn)
3785 cloc = location_of (candidate->fn);
3786 inform (cloc, " inherited here");
3788 /* Give the user some information about why this candidate failed. */
3789 if (candidate->reason != NULL)
3791 struct rejection_reason *r = candidate->reason;
3793 switch (r->code)
3795 case rr_arity:
3796 print_arity_information (cloc, r->u.arity.actual,
3797 r->u.arity.expected);
3798 break;
3799 case rr_arg_conversion:
3800 print_conversion_rejection (cloc, &r->u.conversion, fn);
3801 break;
3802 case rr_bad_arg_conversion:
3803 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3804 break;
3805 case rr_explicit_conversion:
3806 inform (cloc, " return type %qT of explicit conversion function "
3807 "cannot be converted to %qT with a qualification "
3808 "conversion", r->u.conversion.from,
3809 r->u.conversion.to_type);
3810 break;
3811 case rr_template_conversion:
3812 inform (cloc, " conversion from return type %qT of template "
3813 "conversion function specialization to %qT is not an "
3814 "exact match", r->u.conversion.from,
3815 r->u.conversion.to_type);
3816 break;
3817 case rr_template_unification:
3818 /* We use template_unification_error_rejection if unification caused
3819 actual non-SFINAE errors, in which case we don't need to repeat
3820 them here. */
3821 if (r->u.template_unification.tmpl == NULL_TREE)
3823 inform (cloc, " substitution of deduced template arguments "
3824 "resulted in errors seen above");
3825 break;
3827 /* Re-run template unification with diagnostics. */
3828 inform (cloc, " template argument deduction/substitution failed:");
3829 fn_type_unification (r->u.template_unification.tmpl,
3830 r->u.template_unification.explicit_targs,
3831 (make_tree_vec
3832 (r->u.template_unification.num_targs)),
3833 r->u.template_unification.args,
3834 r->u.template_unification.nargs,
3835 r->u.template_unification.return_type,
3836 r->u.template_unification.strict,
3837 r->u.template_unification.flags,
3838 NULL, true, false);
3839 break;
3840 case rr_invalid_copy:
3841 inform (cloc,
3842 " a constructor taking a single argument of its own "
3843 "class type is invalid");
3844 break;
3845 case rr_constraint_failure:
3846 diagnose_constraints (cloc, fn, NULL_TREE);
3847 break;
3848 case rr_inherited_ctor:
3849 inform (cloc, " an inherited constructor is not a candidate for "
3850 "initialization from an expression of the same or derived "
3851 "type");
3852 break;
3853 case rr_none:
3854 default:
3855 /* This candidate didn't have any issues or we failed to
3856 handle a particular code. Either way... */
3857 gcc_unreachable ();
3862 static void
3863 print_z_candidates (location_t loc, struct z_candidate *candidates)
3865 struct z_candidate *cand1;
3866 struct z_candidate **cand2;
3868 if (!candidates)
3869 return;
3871 /* Remove non-viable deleted candidates. */
3872 cand1 = candidates;
3873 for (cand2 = &cand1; *cand2; )
3875 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
3876 && !(*cand2)->viable
3877 && DECL_DELETED_FN ((*cand2)->fn))
3878 *cand2 = (*cand2)->next;
3879 else
3880 cand2 = &(*cand2)->next;
3882 /* ...if there are any non-deleted ones. */
3883 if (cand1)
3884 candidates = cand1;
3886 /* There may be duplicates in the set of candidates. We put off
3887 checking this condition as long as possible, since we have no way
3888 to eliminate duplicates from a set of functions in less than n^2
3889 time. Now we are about to emit an error message, so it is more
3890 permissible to go slowly. */
3891 for (cand1 = candidates; cand1; cand1 = cand1->next)
3893 tree fn = cand1->fn;
3894 /* Skip builtin candidates and conversion functions. */
3895 if (!DECL_P (fn))
3896 continue;
3897 cand2 = &cand1->next;
3898 while (*cand2)
3900 if (DECL_P ((*cand2)->fn)
3901 && equal_functions (fn, (*cand2)->fn))
3902 *cand2 = (*cand2)->next;
3903 else
3904 cand2 = &(*cand2)->next;
3908 for (; candidates; candidates = candidates->next)
3909 print_z_candidate (loc, N_("candidate:"), candidates);
3912 /* USER_SEQ is a user-defined conversion sequence, beginning with a
3913 USER_CONV. STD_SEQ is the standard conversion sequence applied to
3914 the result of the conversion function to convert it to the final
3915 desired type. Merge the two sequences into a single sequence,
3916 and return the merged sequence. */
3918 static conversion *
3919 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
3921 conversion **t;
3922 bool bad = user_seq->bad_p;
3924 gcc_assert (user_seq->kind == ck_user);
3926 /* Find the end of the second conversion sequence. */
3927 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
3929 /* The entire sequence is a user-conversion sequence. */
3930 (*t)->user_conv_p = true;
3931 if (bad)
3932 (*t)->bad_p = true;
3935 if ((*t)->rvaluedness_matches_p)
3936 /* We're binding a reference directly to the result of the conversion.
3937 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
3938 type, but we want it back. */
3939 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
3941 /* Replace the identity conversion with the user conversion
3942 sequence. */
3943 *t = user_seq;
3945 return std_seq;
3948 /* Handle overload resolution for initializing an object of class type from
3949 an initializer list. First we look for a suitable constructor that
3950 takes a std::initializer_list; if we don't find one, we then look for a
3951 non-list constructor.
3953 Parameters are as for add_candidates, except that the arguments are in
3954 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
3955 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
3957 static void
3958 add_list_candidates (tree fns, tree first_arg,
3959 const vec<tree, va_gc> *args, tree totype,
3960 tree explicit_targs, bool template_only,
3961 tree conversion_path, tree access_path,
3962 int flags,
3963 struct z_candidate **candidates,
3964 tsubst_flags_t complain)
3966 gcc_assert (*candidates == NULL);
3968 /* We're looking for a ctor for list-initialization. */
3969 flags |= LOOKUP_LIST_INIT_CTOR;
3970 /* And we don't allow narrowing conversions. We also use this flag to
3971 avoid the copy constructor call for copy-list-initialization. */
3972 flags |= LOOKUP_NO_NARROWING;
3974 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
3975 tree init_list = (*args)[nart];
3977 /* Always use the default constructor if the list is empty (DR 990). */
3978 if (CONSTRUCTOR_NELTS (init_list) == 0
3979 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
3981 /* If the class has a list ctor, try passing the list as a single
3982 argument first, but only consider list ctors. */
3983 else if (TYPE_HAS_LIST_CTOR (totype))
3985 flags |= LOOKUP_LIST_ONLY;
3986 add_candidates (fns, first_arg, args, NULL_TREE,
3987 explicit_targs, template_only, conversion_path,
3988 access_path, flags, candidates, complain);
3989 if (any_strictly_viable (*candidates))
3990 return;
3992 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
3993 && !CP_AGGREGATE_TYPE_P (totype))
3995 if (complain & tf_error)
3996 error ("designated initializers cannot be used with a "
3997 "non-aggregate type %qT", totype);
3998 return;
4001 /* Expand the CONSTRUCTOR into a new argument vec. */
4002 vec<tree, va_gc> *new_args;
4003 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4004 for (unsigned i = 0; i < nart; ++i)
4005 new_args->quick_push ((*args)[i]);
4006 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4007 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4009 /* We aren't looking for list-ctors anymore. */
4010 flags &= ~LOOKUP_LIST_ONLY;
4011 /* We allow more user-defined conversions within an init-list. */
4012 flags &= ~LOOKUP_NO_CONVERSION;
4014 add_candidates (fns, first_arg, new_args, NULL_TREE,
4015 explicit_targs, template_only, conversion_path,
4016 access_path, flags, candidates, complain);
4019 /* Returns the best overload candidate to perform the requested
4020 conversion. This function is used for three the overloading situations
4021 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4022 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4023 per [dcl.init.ref], so we ignore temporary bindings. */
4025 static struct z_candidate *
4026 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4027 tsubst_flags_t complain)
4029 struct z_candidate *candidates, *cand;
4030 tree fromtype;
4031 tree ctors = NULL_TREE;
4032 tree conv_fns = NULL_TREE;
4033 conversion *conv = NULL;
4034 tree first_arg = NULL_TREE;
4035 vec<tree, va_gc> *args = NULL;
4036 bool any_viable_p;
4037 int convflags;
4039 if (!expr)
4040 return NULL;
4042 fromtype = TREE_TYPE (expr);
4044 /* We represent conversion within a hierarchy using RVALUE_CONV and
4045 BASE_CONV, as specified by [over.best.ics]; these become plain
4046 constructor calls, as specified in [dcl.init]. */
4047 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4048 || !DERIVED_FROM_P (totype, fromtype));
4050 if (CLASS_TYPE_P (totype))
4051 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4052 creating a garbage BASELINK; constructors can't be inherited. */
4053 ctors = get_class_binding (totype, complete_ctor_identifier);
4055 tree to_nonref = non_reference (totype);
4056 if (MAYBE_CLASS_TYPE_P (fromtype))
4058 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4059 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4060 && DERIVED_FROM_P (to_nonref, fromtype)))
4062 /* [class.conv.fct] A conversion function is never used to
4063 convert a (possibly cv-qualified) object to the (possibly
4064 cv-qualified) same object type (or a reference to it), to a
4065 (possibly cv-qualified) base class of that type (or a
4066 reference to it)... */
4068 else
4069 conv_fns = lookup_conversions (fromtype);
4072 candidates = 0;
4073 flags |= LOOKUP_NO_CONVERSION;
4074 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4075 flags |= LOOKUP_NO_NARROWING;
4077 /* It's OK to bind a temporary for converting constructor arguments, but
4078 not in converting the return value of a conversion operator. */
4079 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4080 | (flags & LOOKUP_NO_NARROWING));
4081 flags &= ~LOOKUP_NO_TEMP_BIND;
4083 if (ctors)
4085 int ctorflags = flags;
4087 first_arg = build_dummy_object (totype);
4089 /* We should never try to call the abstract or base constructor
4090 from here. */
4091 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4092 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4094 args = make_tree_vector_single (expr);
4095 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4097 /* List-initialization. */
4098 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4099 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4100 ctorflags, &candidates, complain);
4102 else
4104 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4105 TYPE_BINFO (totype), TYPE_BINFO (totype),
4106 ctorflags, &candidates, complain);
4109 for (cand = candidates; cand; cand = cand->next)
4111 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4113 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4114 set, then this is copy-initialization. In that case, "The
4115 result of the call is then used to direct-initialize the
4116 object that is the destination of the copy-initialization."
4117 [dcl.init]
4119 We represent this in the conversion sequence with an
4120 rvalue conversion, which means a constructor call. */
4121 if (!TYPE_REF_P (totype)
4122 && cxx_dialect < cxx17
4123 && (flags & LOOKUP_ONLYCONVERTING)
4124 && !(convflags & LOOKUP_NO_TEMP_BIND))
4125 cand->second_conv
4126 = build_conv (ck_rvalue, totype, cand->second_conv);
4130 if (conv_fns)
4132 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4133 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4134 else
4135 first_arg = expr;
4138 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4140 tree conversion_path = TREE_PURPOSE (conv_fns);
4141 struct z_candidate *old_candidates;
4143 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4144 would need an addional user-defined conversion, i.e. if the return
4145 type differs in class-ness from the desired type. So we avoid
4146 considering operator bool when calling a copy constructor.
4148 This optimization avoids the failure in PR97600, and is allowed by
4149 [temp.inst]/9: "If the function selected by overload resolution can be
4150 determined without instantiating a class template definition, it is
4151 unspecified whether that instantiation actually takes place." */
4152 tree convtype = non_reference (TREE_TYPE (conv_fns));
4153 if ((flags & LOOKUP_NO_CONVERSION)
4154 && !WILDCARD_TYPE_P (convtype)
4155 && (CLASS_TYPE_P (to_nonref)
4156 != CLASS_TYPE_P (convtype)))
4157 continue;
4159 /* If we are called to convert to a reference type, we are trying to
4160 find a direct binding, so don't even consider temporaries. If
4161 we don't find a direct binding, the caller will try again to
4162 look for a temporary binding. */
4163 if (TYPE_REF_P (totype))
4164 convflags |= LOOKUP_NO_TEMP_BIND;
4166 old_candidates = candidates;
4167 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4168 NULL_TREE, false,
4169 conversion_path, TYPE_BINFO (fromtype),
4170 flags, &candidates, complain);
4172 for (cand = candidates; cand != old_candidates; cand = cand->next)
4174 if (cand->viable == 0)
4175 /* Already rejected, don't change to -1. */
4176 continue;
4178 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4179 conversion *ics
4180 = implicit_conversion (totype,
4181 rettype,
4183 /*c_cast_p=*/false, convflags,
4184 complain);
4186 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4187 copy-initialization. In that case, "The result of the
4188 call is then used to direct-initialize the object that is
4189 the destination of the copy-initialization." [dcl.init]
4191 We represent this in the conversion sequence with an
4192 rvalue conversion, which means a constructor call. But
4193 don't add a second rvalue conversion if there's already
4194 one there. Which there really shouldn't be, but it's
4195 harmless since we'd add it here anyway. */
4196 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4197 && !(convflags & LOOKUP_NO_TEMP_BIND))
4198 ics = build_conv (ck_rvalue, totype, ics);
4200 cand->second_conv = ics;
4202 if (!ics)
4204 cand->viable = 0;
4205 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4206 rettype, totype,
4207 EXPR_LOCATION (expr));
4209 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4210 /* Limit this to non-templates for now (PR90546). */
4211 && !cand->template_decl
4212 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4214 /* If we are called to convert to a reference type, we are trying
4215 to find a direct binding per [over.match.ref], so rvaluedness
4216 must match for non-functions. */
4217 cand->viable = 0;
4219 else if (DECL_NONCONVERTING_P (cand->fn)
4220 && ics->rank > cr_exact)
4222 /* 13.3.1.5: For direct-initialization, those explicit
4223 conversion functions that are not hidden within S and
4224 yield type T or a type that can be converted to type T
4225 with a qualification conversion (4.4) are also candidate
4226 functions. */
4227 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4228 I've raised this issue with the committee. --jason 9/2011 */
4229 cand->viable = -1;
4230 cand->reason = explicit_conversion_rejection (rettype, totype);
4232 else if (cand->viable == 1 && ics->bad_p)
4234 cand->viable = -1;
4235 cand->reason
4236 = bad_arg_conversion_rejection (NULL_TREE, -2,
4237 rettype, totype,
4238 EXPR_LOCATION (expr));
4240 else if (primary_template_specialization_p (cand->fn)
4241 && ics->rank > cr_exact)
4243 /* 13.3.3.1.2: If the user-defined conversion is specified by
4244 a specialization of a conversion function template, the
4245 second standard conversion sequence shall have exact match
4246 rank. */
4247 cand->viable = -1;
4248 cand->reason = template_conversion_rejection (rettype, totype);
4253 candidates = splice_viable (candidates, false, &any_viable_p);
4254 if (!any_viable_p)
4256 if (args)
4257 release_tree_vector (args);
4258 return NULL;
4261 cand = tourney (candidates, complain);
4262 if (cand == NULL)
4264 if (complain & tf_error)
4266 auto_diagnostic_group d;
4267 error_at (cp_expr_loc_or_input_loc (expr),
4268 "conversion from %qH to %qI is ambiguous",
4269 fromtype, totype);
4270 print_z_candidates (location_of (expr), candidates);
4273 cand = candidates; /* any one will do */
4274 cand->second_conv = build_ambiguous_conv (totype, expr);
4275 cand->second_conv->user_conv_p = true;
4276 if (!any_strictly_viable (candidates))
4277 cand->second_conv->bad_p = true;
4278 if (flags & LOOKUP_ONLYCONVERTING)
4279 cand->second_conv->need_temporary_p = true;
4280 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4281 ambiguous conversion is no worse than another user-defined
4282 conversion. */
4284 return cand;
4287 tree convtype;
4288 if (!DECL_CONSTRUCTOR_P (cand->fn))
4289 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4290 else if (cand->second_conv->kind == ck_rvalue)
4291 /* DR 5: [in the first step of copy-initialization]...if the function
4292 is a constructor, the call initializes a temporary of the
4293 cv-unqualified version of the destination type. */
4294 convtype = cv_unqualified (totype);
4295 else
4296 convtype = totype;
4297 /* Build the user conversion sequence. */
4298 conv = build_conv
4299 (ck_user,
4300 convtype,
4301 build_identity_conv (TREE_TYPE (expr), expr));
4302 conv->cand = cand;
4303 if (cand->viable == -1)
4304 conv->bad_p = true;
4306 /* We're performing the maybe-rvalue overload resolution and
4307 a conversion function is in play. Reject converting the return
4308 value of the conversion function to a base class. */
4309 if ((flags & LOOKUP_PREFER_RVALUE) && !DECL_CONSTRUCTOR_P (cand->fn))
4310 for (conversion *t = cand->second_conv; t; t = next_conversion (t))
4311 if (t->kind == ck_base)
4312 return NULL;
4314 /* Remember that this was a list-initialization. */
4315 if (flags & LOOKUP_NO_NARROWING)
4316 conv->check_narrowing = true;
4318 /* Combine it with the second conversion sequence. */
4319 cand->second_conv = merge_conversion_sequences (conv,
4320 cand->second_conv);
4322 return cand;
4325 /* Wrapper for above. */
4327 tree
4328 build_user_type_conversion (tree totype, tree expr, int flags,
4329 tsubst_flags_t complain)
4331 struct z_candidate *cand;
4332 tree ret;
4334 bool subtime = timevar_cond_start (TV_OVERLOAD);
4335 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4337 if (cand)
4339 if (cand->second_conv->kind == ck_ambig)
4340 ret = error_mark_node;
4341 else
4343 expr = convert_like (cand->second_conv, expr, complain);
4344 ret = convert_from_reference (expr);
4347 else
4348 ret = NULL_TREE;
4350 timevar_cond_stop (TV_OVERLOAD, subtime);
4351 return ret;
4354 /* Give a helpful diagnostic when implicit_conversion fails. */
4356 static void
4357 implicit_conversion_error (location_t loc, tree type, tree expr)
4359 tsubst_flags_t complain = tf_warning_or_error;
4361 /* If expr has unknown type, then it is an overloaded function.
4362 Call instantiate_type to get good error messages. */
4363 if (TREE_TYPE (expr) == unknown_type_node)
4364 instantiate_type (type, expr, complain);
4365 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4366 /* We gave an error. */;
4367 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4368 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4369 && !CP_AGGREGATE_TYPE_P (type))
4370 error_at (loc, "designated initializers cannot be used with a "
4371 "non-aggregate type %qT", type);
4372 else
4374 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4375 gcc_rich_location rich_loc (loc, &label);
4376 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4377 expr, TREE_TYPE (expr), type);
4381 /* Worker for build_converted_constant_expr. */
4383 static tree
4384 build_converted_constant_expr_internal (tree type, tree expr,
4385 int flags, tsubst_flags_t complain)
4387 conversion *conv;
4388 void *p;
4389 tree t;
4390 location_t loc = cp_expr_loc_or_input_loc (expr);
4392 if (error_operand_p (expr))
4393 return error_mark_node;
4395 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4396 p = conversion_obstack_alloc (0);
4398 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4399 /*c_cast_p=*/false, flags, complain);
4401 /* A converted constant expression of type T is an expression, implicitly
4402 converted to type T, where the converted expression is a constant
4403 expression and the implicit conversion sequence contains only
4405 * user-defined conversions,
4406 * lvalue-to-rvalue conversions (7.1),
4407 * array-to-pointer conversions (7.2),
4408 * function-to-pointer conversions (7.3),
4409 * qualification conversions (7.5),
4410 * integral promotions (7.6),
4411 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4412 * null pointer conversions (7.11) from std::nullptr_t,
4413 * null member pointer conversions (7.12) from std::nullptr_t, and
4414 * function pointer conversions (7.13),
4416 and where the reference binding (if any) binds directly. */
4418 for (conversion *c = conv;
4419 c && c->kind != ck_identity;
4420 c = next_conversion (c))
4422 switch (c->kind)
4424 /* A conversion function is OK. If it isn't constexpr, we'll
4425 complain later that the argument isn't constant. */
4426 case ck_user:
4427 /* List-initialization is OK. */
4428 case ck_aggr:
4429 /* The lvalue-to-rvalue conversion is OK. */
4430 case ck_rvalue:
4431 /* Array-to-pointer and function-to-pointer. */
4432 case ck_lvalue:
4433 /* Function pointer conversions. */
4434 case ck_fnptr:
4435 /* Qualification conversions. */
4436 case ck_qual:
4437 break;
4439 case ck_ref_bind:
4440 if (c->need_temporary_p)
4442 if (complain & tf_error)
4443 error_at (loc, "initializing %qH with %qI in converted "
4444 "constant expression does not bind directly",
4445 type, next_conversion (c)->type);
4446 conv = NULL;
4448 break;
4450 case ck_base:
4451 case ck_pmem:
4452 case ck_ptr:
4453 case ck_std:
4454 t = next_conversion (c)->type;
4455 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4456 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4457 /* Integral promotion or conversion. */
4458 break;
4459 if (NULLPTR_TYPE_P (t))
4460 /* Conversion from nullptr to pointer or pointer-to-member. */
4461 break;
4463 if (complain & tf_error)
4464 error_at (loc, "conversion from %qH to %qI in a "
4465 "converted constant expression", t, type);
4466 /* fall through. */
4468 default:
4469 conv = NULL;
4470 break;
4474 /* Avoid confusing convert_nontype_argument by introducing
4475 a redundant conversion to the same reference type. */
4476 if (conv && conv->kind == ck_ref_bind
4477 && REFERENCE_REF_P (expr))
4479 tree ref = TREE_OPERAND (expr, 0);
4480 if (same_type_p (type, TREE_TYPE (ref)))
4481 return ref;
4484 if (conv)
4486 /* Don't copy a class in a template. */
4487 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4488 && processing_template_decl)
4489 conv = next_conversion (conv);
4491 /* Issuing conversion warnings for value-dependent expressions is
4492 likely too noisy. */
4493 warning_sentinel w (warn_conversion);
4494 conv->check_narrowing = true;
4495 conv->check_narrowing_const_only = true;
4496 expr = convert_like (conv, expr, complain);
4498 else
4500 if (complain & tf_error)
4501 implicit_conversion_error (loc, type, expr);
4502 expr = error_mark_node;
4505 /* Free all the conversions we allocated. */
4506 obstack_free (&conversion_obstack, p);
4508 return expr;
4511 /* Subroutine of convert_nontype_argument.
4513 EXPR is an expression used in a context that requires a converted
4514 constant-expression, such as a template non-type parameter. Do any
4515 necessary conversions (that are permitted for converted
4516 constant-expressions) to convert it to the desired type.
4518 This function doesn't consider explicit conversion functions. If
4519 you mean to use "a contextually converted constant expression of type
4520 bool", use build_converted_constant_bool_expr.
4522 If conversion is successful, returns the converted expression;
4523 otherwise, returns error_mark_node. */
4525 tree
4526 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4528 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4529 complain);
4532 /* Used to create "a contextually converted constant expression of type
4533 bool". This differs from build_converted_constant_expr in that it
4534 also considers explicit conversion functions. */
4536 tree
4537 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4539 return build_converted_constant_expr_internal (boolean_type_node, expr,
4540 LOOKUP_NORMAL, complain);
4543 /* Do any initial processing on the arguments to a function call. */
4545 vec<tree, va_gc> *
4546 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4548 unsigned int ix;
4549 tree arg;
4551 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4553 if (error_operand_p (arg))
4554 return NULL;
4555 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4557 if (complain & tf_error)
4558 error_at (cp_expr_loc_or_input_loc (arg),
4559 "invalid use of void expression");
4560 return NULL;
4562 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4563 return NULL;
4565 return args;
4568 /* Perform overload resolution on FN, which is called with the ARGS.
4570 Return the candidate function selected by overload resolution, or
4571 NULL if the event that overload resolution failed. In the case
4572 that overload resolution fails, *CANDIDATES will be the set of
4573 candidates considered, and ANY_VIABLE_P will be set to true or
4574 false to indicate whether or not any of the candidates were
4575 viable.
4577 The ARGS should already have gone through RESOLVE_ARGS before this
4578 function is called. */
4580 static struct z_candidate *
4581 perform_overload_resolution (tree fn,
4582 const vec<tree, va_gc> *args,
4583 struct z_candidate **candidates,
4584 bool *any_viable_p, tsubst_flags_t complain)
4586 struct z_candidate *cand;
4587 tree explicit_targs;
4588 int template_only;
4590 bool subtime = timevar_cond_start (TV_OVERLOAD);
4592 explicit_targs = NULL_TREE;
4593 template_only = 0;
4595 *candidates = NULL;
4596 *any_viable_p = true;
4598 /* Check FN. */
4599 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4601 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4603 explicit_targs = TREE_OPERAND (fn, 1);
4604 fn = TREE_OPERAND (fn, 0);
4605 template_only = 1;
4608 /* Add the various candidate functions. */
4609 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4610 explicit_targs, template_only,
4611 /*conversion_path=*/NULL_TREE,
4612 /*access_path=*/NULL_TREE,
4613 LOOKUP_NORMAL,
4614 candidates, complain);
4616 *candidates = splice_viable (*candidates, false, any_viable_p);
4617 if (*any_viable_p)
4618 cand = tourney (*candidates, complain);
4619 else
4620 cand = NULL;
4622 timevar_cond_stop (TV_OVERLOAD, subtime);
4623 return cand;
4626 /* Print an error message about being unable to build a call to FN with
4627 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4628 be located; CANDIDATES is a possibly empty list of such
4629 functions. */
4631 static void
4632 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4633 struct z_candidate *candidates)
4635 tree targs = NULL_TREE;
4636 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4638 targs = TREE_OPERAND (fn, 1);
4639 fn = TREE_OPERAND (fn, 0);
4641 tree name = OVL_NAME (fn);
4642 location_t loc = location_of (name);
4643 if (targs)
4644 name = lookup_template_function (name, targs);
4646 auto_diagnostic_group d;
4647 if (!any_strictly_viable (candidates))
4648 error_at (loc, "no matching function for call to %<%D(%A)%>",
4649 name, build_tree_list_vec (args));
4650 else
4651 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4652 name, build_tree_list_vec (args));
4653 if (candidates)
4654 print_z_candidates (loc, candidates);
4657 /* Perform overload resolution on the set of deduction guides DGUIDES
4658 using ARGS. Returns the selected deduction guide, or error_mark_node
4659 if overload resolution fails. */
4661 tree
4662 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4663 tsubst_flags_t complain)
4665 z_candidate *candidates;
4666 bool any_viable_p;
4667 tree result;
4669 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4671 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4672 void *p = conversion_obstack_alloc (0);
4674 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
4675 &any_viable_p, complain);
4676 if (!cand)
4678 if (complain & tf_error)
4679 print_error_for_call_failure (dguides, args, candidates);
4680 result = error_mark_node;
4682 else
4683 result = cand->fn;
4685 /* Free all the conversions we allocated. */
4686 obstack_free (&conversion_obstack, p);
4688 return result;
4691 /* Return an expression for a call to FN (a namespace-scope function,
4692 or a static member function) with the ARGS. This may change
4693 ARGS. */
4695 tree
4696 build_new_function_call (tree fn, vec<tree, va_gc> **args,
4697 tsubst_flags_t complain)
4699 struct z_candidate *candidates, *cand;
4700 bool any_viable_p;
4701 void *p;
4702 tree result;
4704 if (args != NULL && *args != NULL)
4706 *args = resolve_args (*args, complain);
4707 if (*args == NULL)
4708 return error_mark_node;
4711 if (flag_tm)
4712 tm_malloc_replacement (fn);
4714 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4715 p = conversion_obstack_alloc (0);
4717 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
4718 complain);
4720 if (!cand)
4722 if (complain & tf_error)
4724 // If there is a single (non-viable) function candidate,
4725 // let the error be diagnosed by cp_build_function_call_vec.
4726 if (!any_viable_p && candidates && ! candidates->next
4727 && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
4728 return cp_build_function_call_vec (candidates->fn, args, complain);
4730 // Otherwise, emit notes for non-viable candidates.
4731 print_error_for_call_failure (fn, *args, candidates);
4733 result = error_mark_node;
4735 else
4737 result = build_over_call (cand, LOOKUP_NORMAL, complain);
4740 if (flag_coroutines
4741 && result
4742 && TREE_CODE (result) == CALL_EXPR
4743 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
4744 == BUILT_IN_NORMAL)
4745 result = coro_validate_builtin_call (result);
4747 /* Free all the conversions we allocated. */
4748 obstack_free (&conversion_obstack, p);
4750 return result;
4753 /* Build a call to a global operator new. FNNAME is the name of the
4754 operator (either "operator new" or "operator new[]") and ARGS are
4755 the arguments provided. This may change ARGS. *SIZE points to the
4756 total number of bytes required by the allocation, and is updated if
4757 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
4758 be used. If this function determines that no cookie should be
4759 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
4760 is not NULL_TREE, it is evaluated before calculating the final
4761 array size, and if it fails, the array size is replaced with
4762 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
4763 is non-NULL, it will be set, upon return, to the allocation
4764 function called. */
4766 tree
4767 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
4768 tree *size, tree *cookie_size,
4769 tree align_arg, tree size_check,
4770 tree *fn, tsubst_flags_t complain)
4772 tree original_size = *size;
4773 tree fns;
4774 struct z_candidate *candidates;
4775 struct z_candidate *cand = NULL;
4776 bool any_viable_p;
4778 if (fn)
4779 *fn = NULL_TREE;
4780 /* Set to (size_t)-1 if the size check fails. */
4781 if (size_check != NULL_TREE)
4783 tree errval = TYPE_MAX_VALUE (sizetype);
4784 if (cxx_dialect >= cxx11 && flag_exceptions)
4785 errval = throw_bad_array_new_length ();
4786 *size = fold_build3 (COND_EXPR, sizetype, size_check,
4787 original_size, errval);
4789 vec_safe_insert (*args, 0, *size);
4790 *args = resolve_args (*args, complain);
4791 if (*args == NULL)
4792 return error_mark_node;
4794 /* Based on:
4796 [expr.new]
4798 If this lookup fails to find the name, or if the allocated type
4799 is not a class type, the allocation function's name is looked
4800 up in the global scope.
4802 we disregard block-scope declarations of "operator new". */
4803 fns = lookup_name (fnname, LOOK_where::NAMESPACE);
4804 fns = lookup_arg_dependent (fnname, fns, *args);
4806 if (align_arg)
4808 vec<tree, va_gc>* align_args
4809 = vec_copy_and_insert (*args, align_arg, 1);
4810 cand = perform_overload_resolution (fns, align_args, &candidates,
4811 &any_viable_p, tf_none);
4812 if (cand)
4813 *args = align_args;
4814 /* If no aligned allocation function matches, try again without the
4815 alignment. */
4818 /* Figure out what function is being called. */
4819 if (!cand)
4820 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
4821 complain);
4823 /* If no suitable function could be found, issue an error message
4824 and give up. */
4825 if (!cand)
4827 if (complain & tf_error)
4828 print_error_for_call_failure (fns, *args, candidates);
4829 return error_mark_node;
4832 /* If a cookie is required, add some extra space. Whether
4833 or not a cookie is required cannot be determined until
4834 after we know which function was called. */
4835 if (*cookie_size)
4837 bool use_cookie = true;
4838 tree arg_types;
4840 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
4841 /* Skip the size_t parameter. */
4842 arg_types = TREE_CHAIN (arg_types);
4843 /* Check the remaining parameters (if any). */
4844 if (arg_types
4845 && TREE_CHAIN (arg_types) == void_list_node
4846 && same_type_p (TREE_VALUE (arg_types),
4847 ptr_type_node))
4848 use_cookie = false;
4849 /* If we need a cookie, adjust the number of bytes allocated. */
4850 if (use_cookie)
4852 /* Update the total size. */
4853 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
4854 if (size_check)
4856 /* Set to (size_t)-1 if the size check fails. */
4857 gcc_assert (size_check != NULL_TREE);
4858 *size = fold_build3 (COND_EXPR, sizetype, size_check,
4859 *size, TYPE_MAX_VALUE (sizetype));
4861 /* Update the argument list to reflect the adjusted size. */
4862 (**args)[0] = *size;
4864 else
4865 *cookie_size = NULL_TREE;
4868 /* Tell our caller which function we decided to call. */
4869 if (fn)
4870 *fn = cand->fn;
4872 /* Build the CALL_EXPR. */
4873 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
4875 /* Set this flag for all callers of this function. In addition to
4876 new-expressions, this is called for allocating coroutine state; treat
4877 that as an implicit new-expression. */
4878 tree call = extract_call_expr (ret);
4879 if (TREE_CODE (call) == CALL_EXPR)
4880 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
4882 return ret;
4885 /* Build a new call to operator(). This may change ARGS. */
4887 static tree
4888 build_op_call_1 (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
4890 struct z_candidate *candidates = 0, *cand;
4891 tree fns, convs, first_mem_arg = NULL_TREE;
4892 bool any_viable_p;
4893 tree result = NULL_TREE;
4894 void *p;
4896 obj = mark_lvalue_use (obj);
4898 if (error_operand_p (obj))
4899 return error_mark_node;
4901 tree type = TREE_TYPE (obj);
4903 obj = prep_operand (obj);
4905 if (TYPE_PTRMEMFUNC_P (type))
4907 if (complain & tf_error)
4908 /* It's no good looking for an overloaded operator() on a
4909 pointer-to-member-function. */
4910 error ("pointer-to-member function %qE cannot be called without "
4911 "an object; consider using %<.*%> or %<->*%>", obj);
4912 return error_mark_node;
4915 if (TYPE_BINFO (type))
4917 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
4918 if (fns == error_mark_node)
4919 return error_mark_node;
4921 else
4922 fns = NULL_TREE;
4924 if (args != NULL && *args != NULL)
4926 *args = resolve_args (*args, complain);
4927 if (*args == NULL)
4928 return error_mark_node;
4931 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4932 p = conversion_obstack_alloc (0);
4934 if (fns)
4936 first_mem_arg = obj;
4938 add_candidates (BASELINK_FUNCTIONS (fns),
4939 first_mem_arg, *args, NULL_TREE,
4940 NULL_TREE, false,
4941 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
4942 LOOKUP_NORMAL, &candidates, complain);
4945 convs = lookup_conversions (type);
4947 for (; convs; convs = TREE_CHAIN (convs))
4949 tree totype = TREE_TYPE (convs);
4951 if (TYPE_PTRFN_P (totype)
4952 || TYPE_REFFN_P (totype)
4953 || (TYPE_REF_P (totype)
4954 && TYPE_PTRFN_P (TREE_TYPE (totype))))
4955 for (tree fn : ovl_range (TREE_VALUE (convs)))
4957 if (DECL_NONCONVERTING_P (fn))
4958 continue;
4960 if (TREE_CODE (fn) == TEMPLATE_DECL)
4961 add_template_conv_candidate
4962 (&candidates, fn, obj, *args, totype,
4963 /*access_path=*/NULL_TREE,
4964 /*conversion_path=*/NULL_TREE, complain);
4965 else
4966 add_conv_candidate (&candidates, fn, obj,
4967 *args, /*conversion_path=*/NULL_TREE,
4968 /*access_path=*/NULL_TREE, complain);
4972 /* Be strict here because if we choose a bad conversion candidate, the
4973 errors we get won't mention the call context. */
4974 candidates = splice_viable (candidates, true, &any_viable_p);
4975 if (!any_viable_p)
4977 if (complain & tf_error)
4979 auto_diagnostic_group d;
4980 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
4981 build_tree_list_vec (*args));
4982 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
4984 result = error_mark_node;
4986 else
4988 cand = tourney (candidates, complain);
4989 if (cand == 0)
4991 if (complain & tf_error)
4993 auto_diagnostic_group d;
4994 error ("call of %<(%T) (%A)%> is ambiguous",
4995 TREE_TYPE (obj), build_tree_list_vec (*args));
4996 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
4998 result = error_mark_node;
5000 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5001 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5002 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5003 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5004 else
5006 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5007 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5008 -1, complain);
5009 else
5011 gcc_checking_assert (TYPE_P (cand->fn));
5012 obj = convert_like (cand->convs[0], obj, complain);
5014 obj = convert_from_reference (obj);
5015 result = cp_build_function_call_vec (obj, args, complain);
5019 /* Free all the conversions we allocated. */
5020 obstack_free (&conversion_obstack, p);
5022 return result;
5025 /* Wrapper for above. */
5027 tree
5028 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5030 tree ret;
5031 bool subtime = timevar_cond_start (TV_OVERLOAD);
5032 ret = build_op_call_1 (obj, args, complain);
5033 timevar_cond_stop (TV_OVERLOAD, subtime);
5034 return ret;
5037 /* Called by op_error to prepare format strings suitable for the error
5038 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5039 and a suffix (controlled by NTYPES). */
5041 static const char *
5042 op_error_string (const char *errmsg, int ntypes, bool match)
5044 const char *msg;
5046 const char *msgp = concat (match ? G_("ambiguous overload for ")
5047 : G_("no match for "), errmsg, NULL);
5049 if (ntypes == 3)
5050 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5051 else if (ntypes == 2)
5052 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5053 else
5054 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5056 return msg;
5059 static void
5060 op_error (const op_location_t &loc,
5061 enum tree_code code, enum tree_code code2,
5062 tree arg1, tree arg2, tree arg3, bool match)
5064 bool assop = code == MODIFY_EXPR;
5065 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5067 switch (code)
5069 case COND_EXPR:
5070 if (flag_diagnostics_show_caret)
5071 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5072 3, match),
5073 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5074 else
5075 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5076 "in %<%E ? %E : %E%>"), 3, match),
5077 arg1, arg2, arg3,
5078 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5079 break;
5081 case POSTINCREMENT_EXPR:
5082 case POSTDECREMENT_EXPR:
5083 if (flag_diagnostics_show_caret)
5084 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5085 opname, TREE_TYPE (arg1));
5086 else
5087 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5088 1, match),
5089 opname, arg1, opname, TREE_TYPE (arg1));
5090 break;
5092 case ARRAY_REF:
5093 if (flag_diagnostics_show_caret)
5094 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5095 TREE_TYPE (arg1), TREE_TYPE (arg2));
5096 else
5097 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5098 2, match),
5099 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5100 break;
5102 case REALPART_EXPR:
5103 case IMAGPART_EXPR:
5104 if (flag_diagnostics_show_caret)
5105 error_at (loc, op_error_string (G_("%qs"), 1, match),
5106 opname, TREE_TYPE (arg1));
5107 else
5108 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5109 opname, opname, arg1, TREE_TYPE (arg1));
5110 break;
5112 case CO_AWAIT_EXPR:
5113 if (flag_diagnostics_show_caret)
5114 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5115 opname, TREE_TYPE (arg1));
5116 else
5117 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5118 1, match),
5119 opname, opname, arg1, TREE_TYPE (arg1));
5120 break;
5122 default:
5123 if (arg2)
5124 if (flag_diagnostics_show_caret)
5126 binary_op_rich_location richloc (loc, arg1, arg2, true);
5127 error_at (&richloc,
5128 op_error_string (G_("%<operator%s%>"), 2, match),
5129 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5131 else
5132 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5133 2, match),
5134 opname, arg1, opname, arg2,
5135 TREE_TYPE (arg1), TREE_TYPE (arg2));
5136 else
5137 if (flag_diagnostics_show_caret)
5138 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5139 opname, TREE_TYPE (arg1));
5140 else
5141 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5142 1, match),
5143 opname, opname, arg1, TREE_TYPE (arg1));
5144 break;
5148 /* Return the implicit conversion sequence that could be used to
5149 convert E1 to E2 in [expr.cond]. */
5151 static conversion *
5152 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5154 tree t1 = non_reference (TREE_TYPE (e1));
5155 tree t2 = non_reference (TREE_TYPE (e2));
5156 conversion *conv;
5157 bool good_base;
5159 /* [expr.cond]
5161 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5162 implicitly converted (clause _conv_) to the type "lvalue reference to
5163 T2", subject to the constraint that in the conversion the
5164 reference must bind directly (_dcl.init.ref_) to an lvalue.
5166 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5167 implicitly converted to the type "rvalue reference to T2", subject to
5168 the constraint that the reference must bind directly. */
5169 if (glvalue_p (e2))
5171 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5172 conv = implicit_conversion (rtype,
5175 /*c_cast_p=*/false,
5176 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5177 |LOOKUP_ONLYCONVERTING,
5178 complain);
5179 if (conv && !conv->bad_p)
5180 return conv;
5183 /* If E2 is a prvalue or if neither of the conversions above can be done
5184 and at least one of the operands has (possibly cv-qualified) class
5185 type: */
5186 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5187 return NULL;
5189 /* [expr.cond]
5191 If E1 and E2 have class type, and the underlying class types are
5192 the same or one is a base class of the other: E1 can be converted
5193 to match E2 if the class of T2 is the same type as, or a base
5194 class of, the class of T1, and the cv-qualification of T2 is the
5195 same cv-qualification as, or a greater cv-qualification than, the
5196 cv-qualification of T1. If the conversion is applied, E1 is
5197 changed to an rvalue of type T2 that still refers to the original
5198 source class object (or the appropriate subobject thereof). */
5199 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5200 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5202 if (good_base && at_least_as_qualified_p (t2, t1))
5204 conv = build_identity_conv (t1, e1);
5205 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5206 TYPE_MAIN_VARIANT (t2)))
5207 conv = build_conv (ck_base, t2, conv);
5208 else
5209 conv = build_conv (ck_rvalue, t2, conv);
5210 return conv;
5212 else
5213 return NULL;
5215 else
5216 /* [expr.cond]
5218 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5219 converted to the type that expression E2 would have if E2 were
5220 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5221 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5222 LOOKUP_IMPLICIT, complain);
5225 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5226 arguments to the conditional expression. */
5228 static tree
5229 build_conditional_expr_1 (const op_location_t &loc,
5230 tree arg1, tree arg2, tree arg3,
5231 tsubst_flags_t complain)
5233 tree arg2_type;
5234 tree arg3_type;
5235 tree result = NULL_TREE;
5236 tree result_type = NULL_TREE;
5237 bool is_glvalue = true;
5238 struct z_candidate *candidates = 0;
5239 struct z_candidate *cand;
5240 void *p;
5241 tree orig_arg2, orig_arg3;
5243 /* As a G++ extension, the second argument to the conditional can be
5244 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5245 c'.) If the second operand is omitted, make sure it is
5246 calculated only once. */
5247 if (!arg2)
5249 if (complain & tf_error)
5250 pedwarn (loc, OPT_Wpedantic,
5251 "ISO C++ forbids omitting the middle term of "
5252 "a %<?:%> expression");
5254 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5255 warn_for_omitted_condop (loc, arg1);
5257 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5258 if (glvalue_p (arg1))
5260 arg1 = cp_stabilize_reference (arg1);
5261 arg2 = arg1 = prevent_lifetime_extension (arg1);
5263 else
5264 arg2 = arg1 = cp_save_expr (arg1);
5267 /* If something has already gone wrong, just pass that fact up the
5268 tree. */
5269 if (error_operand_p (arg1)
5270 || error_operand_p (arg2)
5271 || error_operand_p (arg3))
5272 return error_mark_node;
5274 orig_arg2 = arg2;
5275 orig_arg3 = arg3;
5277 if (gnu_vector_type_p (TREE_TYPE (arg1))
5278 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5280 tree arg1_type = TREE_TYPE (arg1);
5282 /* If arg1 is another cond_expr choosing between -1 and 0,
5283 then we can use its comparison. It may help to avoid
5284 additional comparison, produce more accurate diagnostics
5285 and enables folding. */
5286 if (TREE_CODE (arg1) == VEC_COND_EXPR
5287 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5288 && integer_zerop (TREE_OPERAND (arg1, 2)))
5289 arg1 = TREE_OPERAND (arg1, 0);
5291 arg1 = force_rvalue (arg1, complain);
5292 arg2 = force_rvalue (arg2, complain);
5293 arg3 = force_rvalue (arg3, complain);
5295 /* force_rvalue can return error_mark on valid arguments. */
5296 if (error_operand_p (arg1)
5297 || error_operand_p (arg2)
5298 || error_operand_p (arg3))
5299 return error_mark_node;
5301 arg2_type = TREE_TYPE (arg2);
5302 arg3_type = TREE_TYPE (arg3);
5304 if (!VECTOR_TYPE_P (arg2_type)
5305 && !VECTOR_TYPE_P (arg3_type))
5307 /* Rely on the error messages of the scalar version. */
5308 tree scal = build_conditional_expr_1 (loc, integer_one_node,
5309 orig_arg2, orig_arg3, complain);
5310 if (scal == error_mark_node)
5311 return error_mark_node;
5312 tree stype = TREE_TYPE (scal);
5313 tree ctype = TREE_TYPE (arg1_type);
5314 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5315 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5317 if (complain & tf_error)
5318 error_at (loc, "inferred scalar type %qT is not an integer or "
5319 "floating-point type of the same size as %qT", stype,
5320 COMPARISON_CLASS_P (arg1)
5321 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5322 : ctype);
5323 return error_mark_node;
5326 tree vtype = build_opaque_vector_type (stype,
5327 TYPE_VECTOR_SUBPARTS (arg1_type));
5328 /* We could pass complain & tf_warning to unsafe_conversion_p,
5329 but the warnings (like Wsign-conversion) have already been
5330 given by the scalar build_conditional_expr_1. We still check
5331 unsafe_conversion_p to forbid truncating long long -> float. */
5332 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5334 if (complain & tf_error)
5335 error_at (loc, "conversion of scalar %qH to vector %qI "
5336 "involves truncation", arg2_type, vtype);
5337 return error_mark_node;
5339 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5341 if (complain & tf_error)
5342 error_at (loc, "conversion of scalar %qH to vector %qI "
5343 "involves truncation", arg3_type, vtype);
5344 return error_mark_node;
5347 arg2 = cp_convert (stype, arg2, complain);
5348 arg2 = save_expr (arg2);
5349 arg2 = build_vector_from_val (vtype, arg2);
5350 arg2_type = vtype;
5351 arg3 = cp_convert (stype, arg3, complain);
5352 arg3 = save_expr (arg3);
5353 arg3 = build_vector_from_val (vtype, arg3);
5354 arg3_type = vtype;
5357 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5358 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5360 enum stv_conv convert_flag =
5361 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5362 complain & tf_error);
5364 switch (convert_flag)
5366 case stv_error:
5367 return error_mark_node;
5368 case stv_firstarg:
5370 arg2 = save_expr (arg2);
5371 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5372 arg2 = build_vector_from_val (arg3_type, arg2);
5373 arg2_type = TREE_TYPE (arg2);
5374 break;
5376 case stv_secondarg:
5378 arg3 = save_expr (arg3);
5379 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5380 arg3 = build_vector_from_val (arg2_type, arg3);
5381 arg3_type = TREE_TYPE (arg3);
5382 break;
5384 default:
5385 break;
5389 if (!gnu_vector_type_p (arg2_type)
5390 || !gnu_vector_type_p (arg3_type)
5391 || !same_type_p (arg2_type, arg3_type)
5392 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5393 TYPE_VECTOR_SUBPARTS (arg2_type))
5394 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5396 if (complain & tf_error)
5397 error_at (loc,
5398 "incompatible vector types in conditional expression: "
5399 "%qT, %qT and %qT", TREE_TYPE (arg1),
5400 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5401 return error_mark_node;
5404 if (!COMPARISON_CLASS_P (arg1))
5406 tree cmp_type = truth_type_for (arg1_type);
5407 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5409 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5412 /* [expr.cond]
5414 The first expression is implicitly converted to bool (clause
5415 _conv_). */
5416 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5417 LOOKUP_NORMAL);
5418 if (error_operand_p (arg1))
5419 return error_mark_node;
5421 /* [expr.cond]
5423 If either the second or the third operand has type (possibly
5424 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5425 array-to-pointer (_conv.array_), and function-to-pointer
5426 (_conv.func_) standard conversions are performed on the second
5427 and third operands. */
5428 arg2_type = unlowered_expr_type (arg2);
5429 arg3_type = unlowered_expr_type (arg3);
5430 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5432 /* 'void' won't help in resolving an overloaded expression on the
5433 other side, so require it to resolve by itself. */
5434 if (arg2_type == unknown_type_node)
5436 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5437 arg2_type = TREE_TYPE (arg2);
5439 if (arg3_type == unknown_type_node)
5441 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5442 arg3_type = TREE_TYPE (arg3);
5445 /* [expr.cond]
5447 One of the following shall hold:
5449 --The second or the third operand (but not both) is a
5450 throw-expression (_except.throw_); the result is of the type
5451 and value category of the other.
5453 --Both the second and the third operands have type void; the
5454 result is of type void and is a prvalue. */
5455 if (TREE_CODE (arg2) == THROW_EXPR
5456 && TREE_CODE (arg3) != THROW_EXPR)
5458 result_type = arg3_type;
5459 is_glvalue = glvalue_p (arg3);
5461 else if (TREE_CODE (arg2) != THROW_EXPR
5462 && TREE_CODE (arg3) == THROW_EXPR)
5464 result_type = arg2_type;
5465 is_glvalue = glvalue_p (arg2);
5467 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5469 result_type = void_type_node;
5470 is_glvalue = false;
5472 else
5474 if (complain & tf_error)
5476 if (VOID_TYPE_P (arg2_type))
5477 error_at (cp_expr_loc_or_loc (arg3, loc),
5478 "second operand to the conditional operator "
5479 "is of type %<void%>, but the third operand is "
5480 "neither a throw-expression nor of type %<void%>");
5481 else
5482 error_at (cp_expr_loc_or_loc (arg2, loc),
5483 "third operand to the conditional operator "
5484 "is of type %<void%>, but the second operand is "
5485 "neither a throw-expression nor of type %<void%>");
5487 return error_mark_node;
5490 goto valid_operands;
5492 /* [expr.cond]
5494 Otherwise, if the second and third operand have different types,
5495 and either has (possibly cv-qualified) class type, or if both are
5496 glvalues of the same value category and the same type except for
5497 cv-qualification, an attempt is made to convert each of those operands
5498 to the type of the other. */
5499 else if (!same_type_p (arg2_type, arg3_type)
5500 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5501 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5502 arg3_type)
5503 && glvalue_p (arg2) && glvalue_p (arg3)
5504 && lvalue_p (arg2) == lvalue_p (arg3))))
5506 conversion *conv2;
5507 conversion *conv3;
5508 bool converted = false;
5510 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5511 p = conversion_obstack_alloc (0);
5513 conv2 = conditional_conversion (arg2, arg3, complain);
5514 conv3 = conditional_conversion (arg3, arg2, complain);
5516 /* [expr.cond]
5518 If both can be converted, or one can be converted but the
5519 conversion is ambiguous, the program is ill-formed. If
5520 neither can be converted, the operands are left unchanged and
5521 further checking is performed as described below. If exactly
5522 one conversion is possible, that conversion is applied to the
5523 chosen operand and the converted operand is used in place of
5524 the original operand for the remainder of this section. */
5525 if ((conv2 && !conv2->bad_p
5526 && conv3 && !conv3->bad_p)
5527 || (conv2 && conv2->kind == ck_ambig)
5528 || (conv3 && conv3->kind == ck_ambig))
5530 if (complain & tf_error)
5532 error_at (loc, "operands to %<?:%> have different types "
5533 "%qT and %qT",
5534 arg2_type, arg3_type);
5535 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5536 inform (loc, " and each type can be converted to the other");
5537 else if (conv2 && conv2->kind == ck_ambig)
5538 convert_like (conv2, arg2, complain);
5539 else
5540 convert_like (conv3, arg3, complain);
5542 result = error_mark_node;
5544 else if (conv2 && !conv2->bad_p)
5546 arg2 = convert_like (conv2, arg2, complain);
5547 arg2 = convert_from_reference (arg2);
5548 arg2_type = TREE_TYPE (arg2);
5549 /* Even if CONV2 is a valid conversion, the result of the
5550 conversion may be invalid. For example, if ARG3 has type
5551 "volatile X", and X does not have a copy constructor
5552 accepting a "volatile X&", then even if ARG2 can be
5553 converted to X, the conversion will fail. */
5554 if (error_operand_p (arg2))
5555 result = error_mark_node;
5556 converted = true;
5558 else if (conv3 && !conv3->bad_p)
5560 arg3 = convert_like (conv3, arg3, complain);
5561 arg3 = convert_from_reference (arg3);
5562 arg3_type = TREE_TYPE (arg3);
5563 if (error_operand_p (arg3))
5564 result = error_mark_node;
5565 converted = true;
5568 /* Free all the conversions we allocated. */
5569 obstack_free (&conversion_obstack, p);
5571 if (result)
5572 return result;
5574 /* If, after the conversion, both operands have class type,
5575 treat the cv-qualification of both operands as if it were the
5576 union of the cv-qualification of the operands.
5578 The standard is not clear about what to do in this
5579 circumstance. For example, if the first operand has type
5580 "const X" and the second operand has a user-defined
5581 conversion to "volatile X", what is the type of the second
5582 operand after this step? Making it be "const X" (matching
5583 the first operand) seems wrong, as that discards the
5584 qualification without actually performing a copy. Leaving it
5585 as "volatile X" seems wrong as that will result in the
5586 conditional expression failing altogether, even though,
5587 according to this step, the one operand could be converted to
5588 the type of the other. */
5589 if (converted
5590 && CLASS_TYPE_P (arg2_type)
5591 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5592 arg2_type = arg3_type =
5593 cp_build_qualified_type (arg2_type,
5594 cp_type_quals (arg2_type)
5595 | cp_type_quals (arg3_type));
5598 /* [expr.cond]
5600 If the second and third operands are glvalues of the same value
5601 category and have the same type, the result is of that type and
5602 value category. */
5603 if (((lvalue_p (arg2) && lvalue_p (arg3))
5604 || (xvalue_p (arg2) && xvalue_p (arg3)))
5605 && same_type_p (arg2_type, arg3_type))
5607 result_type = arg2_type;
5608 goto valid_operands;
5611 /* [expr.cond]
5613 Otherwise, the result is an rvalue. If the second and third
5614 operand do not have the same type, and either has (possibly
5615 cv-qualified) class type, overload resolution is used to
5616 determine the conversions (if any) to be applied to the operands
5617 (_over.match.oper_, _over.built_). */
5618 is_glvalue = false;
5619 if (!same_type_p (arg2_type, arg3_type)
5620 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
5622 releasing_vec args;
5623 conversion *conv;
5624 bool any_viable_p;
5626 /* Rearrange the arguments so that add_builtin_candidate only has
5627 to know about two args. In build_builtin_candidate, the
5628 arguments are unscrambled. */
5629 args->quick_push (arg2);
5630 args->quick_push (arg3);
5631 args->quick_push (arg1);
5632 add_builtin_candidates (&candidates,
5633 COND_EXPR,
5634 NOP_EXPR,
5635 ovl_op_identifier (false, COND_EXPR),
5636 args,
5637 LOOKUP_NORMAL, complain);
5639 /* [expr.cond]
5641 If the overload resolution fails, the program is
5642 ill-formed. */
5643 candidates = splice_viable (candidates, false, &any_viable_p);
5644 if (!any_viable_p)
5646 if (complain & tf_error)
5647 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5648 arg2_type, arg3_type);
5649 return error_mark_node;
5651 cand = tourney (candidates, complain);
5652 if (!cand)
5654 if (complain & tf_error)
5656 auto_diagnostic_group d;
5657 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
5658 print_z_candidates (loc, candidates);
5660 return error_mark_node;
5663 /* [expr.cond]
5665 Otherwise, the conversions thus determined are applied, and
5666 the converted operands are used in place of the original
5667 operands for the remainder of this section. */
5668 conv = cand->convs[0];
5669 arg1 = convert_like (conv, arg1, complain);
5670 conv = cand->convs[1];
5671 arg2 = convert_like (conv, arg2, complain);
5672 arg2_type = TREE_TYPE (arg2);
5673 conv = cand->convs[2];
5674 arg3 = convert_like (conv, arg3, complain);
5675 arg3_type = TREE_TYPE (arg3);
5678 /* [expr.cond]
5680 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
5681 and function-to-pointer (_conv.func_) standard conversions are
5682 performed on the second and third operands.
5684 We need to force the lvalue-to-rvalue conversion here for class types,
5685 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
5686 that isn't wrapped with a TARGET_EXPR plays havoc with exception
5687 regions. */
5689 arg2 = force_rvalue (arg2, complain);
5690 if (!CLASS_TYPE_P (arg2_type))
5691 arg2_type = TREE_TYPE (arg2);
5693 arg3 = force_rvalue (arg3, complain);
5694 if (!CLASS_TYPE_P (arg3_type))
5695 arg3_type = TREE_TYPE (arg3);
5697 if (arg2 == error_mark_node || arg3 == error_mark_node)
5698 return error_mark_node;
5700 /* [expr.cond]
5702 After those conversions, one of the following shall hold:
5704 --The second and third operands have the same type; the result is of
5705 that type. */
5706 if (same_type_p (arg2_type, arg3_type))
5707 result_type = arg2_type;
5708 /* [expr.cond]
5710 --The second and third operands have arithmetic or enumeration
5711 type; the usual arithmetic conversions are performed to bring
5712 them to a common type, and the result is of that type. */
5713 else if ((ARITHMETIC_TYPE_P (arg2_type)
5714 || UNSCOPED_ENUM_P (arg2_type))
5715 && (ARITHMETIC_TYPE_P (arg3_type)
5716 || UNSCOPED_ENUM_P (arg3_type)))
5718 /* In this case, there is always a common type. */
5719 result_type = type_after_usual_arithmetic_conversions (arg2_type,
5720 arg3_type);
5721 if (complain & tf_warning)
5722 do_warn_double_promotion (result_type, arg2_type, arg3_type,
5723 "implicit conversion from %qH to %qI to "
5724 "match other result of conditional",
5725 loc);
5727 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
5728 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
5730 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
5731 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
5732 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
5733 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
5734 && (DECL_CONTEXT (stripped_orig_arg2)
5735 == DECL_CONTEXT (stripped_orig_arg3)))
5736 /* Two enumerators from the same enumeration can have different
5737 types when the enumeration is still being defined. */;
5738 else if (complain & tf_warning)
5739 warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
5740 "in conditional expression: %qT vs %qT",
5741 arg2_type, arg3_type);
5743 else if ((complain & tf_warning)
5744 && warn_deprecated_enum_float_conv
5745 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5746 && TREE_CODE (arg3_type) == REAL_TYPE)
5747 || (TREE_CODE (arg2_type) == REAL_TYPE
5748 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
5750 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
5751 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5752 "conditional expression between enumeration type "
5753 "%qT and floating-point type %qT is deprecated",
5754 arg2_type, arg3_type);
5755 else
5756 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5757 "conditional expression between floating-point "
5758 "type %qT and enumeration type %qT is deprecated",
5759 arg2_type, arg3_type);
5761 else if ((extra_warnings || warn_enum_conversion)
5762 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5763 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
5764 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
5765 && !same_type_p (arg2_type,
5766 type_promotes_to (arg3_type)))))
5768 if (complain & tf_warning)
5770 enum opt_code opt = (warn_enum_conversion
5771 ? OPT_Wenum_conversion
5772 : OPT_Wextra);
5773 warning_at (loc, opt, "enumerated and "
5774 "non-enumerated type in conditional expression");
5778 arg2 = perform_implicit_conversion (result_type, arg2, complain);
5779 arg3 = perform_implicit_conversion (result_type, arg3, complain);
5781 /* [expr.cond]
5783 --The second and third operands have pointer type, or one has
5784 pointer type and the other is a null pointer constant; pointer
5785 conversions (_conv.ptr_) and qualification conversions
5786 (_conv.qual_) are performed to bring them to their composite
5787 pointer type (_expr.rel_). The result is of the composite
5788 pointer type.
5790 --The second and third operands have pointer to member type, or
5791 one has pointer to member type and the other is a null pointer
5792 constant; pointer to member conversions (_conv.mem_) and
5793 qualification conversions (_conv.qual_) are performed to bring
5794 them to a common type, whose cv-qualification shall match the
5795 cv-qualification of either the second or the third operand.
5796 The result is of the common type. */
5797 else if ((null_ptr_cst_p (arg2)
5798 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
5799 || (null_ptr_cst_p (arg3)
5800 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
5801 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
5802 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
5803 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
5805 result_type = composite_pointer_type (loc,
5806 arg2_type, arg3_type, arg2,
5807 arg3, CPO_CONDITIONAL_EXPR,
5808 complain);
5809 if (result_type == error_mark_node)
5810 return error_mark_node;
5811 arg2 = perform_implicit_conversion (result_type, arg2, complain);
5812 arg3 = perform_implicit_conversion (result_type, arg3, complain);
5815 if (!result_type)
5817 if (complain & tf_error)
5818 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5819 arg2_type, arg3_type);
5820 return error_mark_node;
5823 if (arg2 == error_mark_node || arg3 == error_mark_node)
5824 return error_mark_node;
5826 valid_operands:
5827 if (processing_template_decl && is_glvalue)
5829 /* Let lvalue_kind know this was a glvalue. */
5830 tree arg = (result_type == arg2_type ? arg2 : arg3);
5831 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
5834 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
5836 /* If the ARG2 and ARG3 are the same and don't have side-effects,
5837 warn here, because the COND_EXPR will be turned into ARG2. */
5838 if (warn_duplicated_branches
5839 && (complain & tf_warning)
5840 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
5841 OEP_ADDRESS_OF_SAME_FIELD)))
5842 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
5843 "this condition has identical branches");
5845 /* We can't use result_type below, as fold might have returned a
5846 throw_expr. */
5848 if (!is_glvalue)
5850 /* Expand both sides into the same slot, hopefully the target of
5851 the ?: expression. We used to check for TARGET_EXPRs here,
5852 but now we sometimes wrap them in NOP_EXPRs so the test would
5853 fail. */
5854 if (CLASS_TYPE_P (TREE_TYPE (result)))
5855 result = get_target_expr_sfinae (result, complain);
5856 /* If this expression is an rvalue, but might be mistaken for an
5857 lvalue, we must add a NON_LVALUE_EXPR. */
5858 result = rvalue (result);
5860 else
5861 result = force_paren_expr (result);
5863 return result;
5866 /* Wrapper for above. */
5868 tree
5869 build_conditional_expr (const op_location_t &loc,
5870 tree arg1, tree arg2, tree arg3,
5871 tsubst_flags_t complain)
5873 tree ret;
5874 bool subtime = timevar_cond_start (TV_OVERLOAD);
5875 ret = build_conditional_expr_1 (loc, arg1, arg2, arg3, complain);
5876 timevar_cond_stop (TV_OVERLOAD, subtime);
5877 return ret;
5880 /* OPERAND is an operand to an expression. Perform necessary steps
5881 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
5882 returned. */
5884 static tree
5885 prep_operand (tree operand)
5887 if (operand)
5889 if (CLASS_TYPE_P (TREE_TYPE (operand))
5890 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
5891 /* Make sure the template type is instantiated now. */
5892 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
5895 return operand;
5898 /* True iff CONV represents a conversion sequence which no other can be better
5899 than under [over.ics.rank]: in other words, a "conversion" to the exact same
5900 type (including binding to a reference to the same type). This is stronger
5901 than the standard's "identity" category, which also includes reference
5902 bindings that add cv-qualifiers or change rvalueness. */
5904 static bool
5905 perfect_conversion_p (conversion *conv)
5907 if (CONVERSION_RANK (conv) != cr_identity)
5908 return false;
5909 if (conv->kind == ck_ref_bind)
5911 if (!conv->rvaluedness_matches_p)
5912 return false;
5913 if (!same_type_p (TREE_TYPE (conv->type),
5914 next_conversion (conv)->type))
5915 return false;
5917 if (conv->check_narrowing)
5918 /* Brace elision is imperfect. */
5919 return false;
5920 return true;
5923 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
5924 other candidate can be a better match. Since the template/non-template
5925 tiebreaker comes immediately after the conversion comparison in
5926 [over.match.best], a perfect non-template candidate is better than all
5927 templates. */
5929 static bool
5930 perfect_candidate_p (z_candidate *cand)
5932 if (cand->viable < 1)
5933 return false;
5934 /* CWG1402 makes an implicitly deleted move op worse than other
5935 candidates. */
5936 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
5937 && move_fn_p (cand->fn))
5938 return false;
5939 int len = cand->num_convs;
5940 for (int i = 0; i < len; ++i)
5941 if (!perfect_conversion_p (cand->convs[i]))
5942 return false;
5943 if (conversion *conv = cand->second_conv)
5944 if (!perfect_conversion_p (conv))
5945 return false;
5946 return true;
5949 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
5950 OVERLOAD) to the CANDIDATES, returning an updated list of
5951 CANDIDATES. The ARGS are the arguments provided to the call;
5952 if FIRST_ARG is non-null it is the implicit object argument,
5953 otherwise the first element of ARGS is used if needed. The
5954 EXPLICIT_TARGS are explicit template arguments provided.
5955 TEMPLATE_ONLY is true if only template functions should be
5956 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
5957 add_function_candidate. */
5959 static void
5960 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
5961 tree return_type,
5962 tree explicit_targs, bool template_only,
5963 tree conversion_path, tree access_path,
5964 int flags,
5965 struct z_candidate **candidates,
5966 tsubst_flags_t complain)
5968 tree ctype;
5969 const vec<tree, va_gc> *non_static_args;
5970 bool check_list_ctor = false;
5971 bool check_converting = false;
5972 unification_kind_t strict;
5974 if (!fns)
5975 return;
5977 /* Precalculate special handling of constructors and conversion ops. */
5978 tree fn = OVL_FIRST (fns);
5979 if (DECL_CONV_FN_P (fn))
5981 check_list_ctor = false;
5982 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
5983 if (flags & LOOKUP_NO_CONVERSION)
5984 /* We're doing return_type(x). */
5985 strict = DEDUCE_CONV;
5986 else
5987 /* We're doing x.operator return_type(). */
5988 strict = DEDUCE_EXACT;
5989 /* [over.match.funcs] For conversion functions, the function
5990 is considered to be a member of the class of the implicit
5991 object argument for the purpose of defining the type of
5992 the implicit object parameter. */
5993 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
5995 else
5997 if (DECL_CONSTRUCTOR_P (fn))
5999 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6000 /* For list-initialization we consider explicit constructors
6001 and complain if one is chosen. */
6002 check_converting
6003 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6004 == LOOKUP_ONLYCONVERTING);
6006 strict = DEDUCE_CALL;
6007 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6010 if (first_arg)
6011 non_static_args = args;
6012 else
6013 /* Delay creating the implicit this parameter until it is needed. */
6014 non_static_args = NULL;
6016 /* If there's a non-template perfect match, we don't need to consider
6017 templates. So check non-templates first. This optimization is only
6018 really needed for the defaulted copy constructor of tuple and the like
6019 (96926), but it seems like we might as well enable it more generally. */
6020 bool seen_perfect = false;
6021 enum { templates, non_templates, either } which = either;
6022 if (template_only)
6023 which = templates;
6024 else /*if (flags & LOOKUP_DEFAULTED)*/
6025 which = non_templates;
6027 again:
6028 for (tree fn : lkp_range (fns))
6030 if (check_converting && DECL_NONCONVERTING_P (fn))
6031 continue;
6032 if (check_list_ctor && !is_list_ctor (fn))
6033 continue;
6034 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6035 continue;
6036 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6037 continue;
6039 tree fn_first_arg = NULL_TREE;
6040 const vec<tree, va_gc> *fn_args = args;
6042 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6044 /* Figure out where the object arg comes from. If this
6045 function is a non-static member and we didn't get an
6046 implicit object argument, move it out of args. */
6047 if (first_arg == NULL_TREE)
6049 unsigned int ix;
6050 tree arg;
6051 vec<tree, va_gc> *tempvec;
6052 vec_alloc (tempvec, args->length () - 1);
6053 for (ix = 1; args->iterate (ix, &arg); ++ix)
6054 tempvec->quick_push (arg);
6055 non_static_args = tempvec;
6056 first_arg = (*args)[0];
6059 fn_first_arg = first_arg;
6060 fn_args = non_static_args;
6063 /* Don't bother reversing an operator with two identical parameters. */
6064 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6066 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6067 if (same_type_p (TREE_VALUE (parmlist),
6068 TREE_VALUE (TREE_CHAIN (parmlist))))
6069 continue;
6072 if (TREE_CODE (fn) == TEMPLATE_DECL)
6073 add_template_candidate (candidates,
6075 ctype,
6076 explicit_targs,
6077 fn_first_arg,
6078 fn_args,
6079 return_type,
6080 access_path,
6081 conversion_path,
6082 flags,
6083 strict,
6084 complain);
6085 else
6087 add_function_candidate (candidates,
6089 ctype,
6090 fn_first_arg,
6091 fn_args,
6092 access_path,
6093 conversion_path,
6094 flags,
6095 NULL,
6096 complain);
6097 if (perfect_candidate_p (*candidates))
6098 seen_perfect = true;
6101 if (which == non_templates && !seen_perfect)
6103 which = templates;
6104 goto again;
6108 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6109 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6111 static int
6112 op_is_ordered (tree_code code)
6114 switch (code)
6116 // 5. b @= a
6117 case MODIFY_EXPR:
6118 return (flag_strong_eval_order > 1 ? -1 : 0);
6120 // 6. a[b]
6121 case ARRAY_REF:
6122 return (flag_strong_eval_order > 1 ? 1 : 0);
6124 // 1. a.b
6125 // Not overloadable (yet).
6126 // 2. a->b
6127 // Only one argument.
6128 // 3. a->*b
6129 case MEMBER_REF:
6130 // 7. a << b
6131 case LSHIFT_EXPR:
6132 // 8. a >> b
6133 case RSHIFT_EXPR:
6134 // a && b
6135 // Predates P0145R3.
6136 case TRUTH_ANDIF_EXPR:
6137 // a || b
6138 // Predates P0145R3.
6139 case TRUTH_ORIF_EXPR:
6140 // a , b
6141 // Predates P0145R3.
6142 case COMPOUND_EXPR:
6143 return (flag_strong_eval_order ? 1 : 0);
6145 default:
6146 return 0;
6150 /* Subroutine of build_new_op_1: Add to CANDIDATES all candidates for the
6151 operator indicated by CODE/CODE2. This function calls itself recursively to
6152 handle C++20 rewritten comparison operator candidates. */
6154 static tree
6155 add_operator_candidates (z_candidate **candidates,
6156 tree_code code, tree_code code2,
6157 vec<tree, va_gc> *arglist,
6158 int flags, tsubst_flags_t complain)
6160 z_candidate *start_candidates = *candidates;
6161 bool ismodop = code2 != ERROR_MARK;
6162 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6164 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6165 rewrite from, and also when we're looking for the e.g. < operator to use
6166 on the result of <=>. In the latter case, we don't want the flag set in
6167 the candidate, we just want to suppress looking for rewrites. */
6168 bool rewritten = (flags & LOOKUP_REWRITTEN);
6169 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6170 flags &= ~LOOKUP_REWRITTEN;
6172 bool memonly = false;
6173 switch (code)
6175 /* =, ->, [], () must be non-static member functions. */
6176 case MODIFY_EXPR:
6177 if (code2 != NOP_EXPR)
6178 break;
6179 /* FALLTHRU */
6180 case COMPONENT_REF:
6181 case ARRAY_REF:
6182 memonly = true;
6183 break;
6185 default:
6186 break;
6189 /* Add namespace-scope operators to the list of functions to
6190 consider. */
6191 if (!memonly)
6193 tree fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6194 fns = lookup_arg_dependent (fnname, fns, arglist);
6195 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6196 NULL_TREE, false, NULL_TREE, NULL_TREE,
6197 flags, candidates, complain);
6200 /* Add class-member operators to the candidate set. */
6201 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6202 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6203 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6204 if (CLASS_TYPE_P (arg1_type))
6206 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6207 if (fns == error_mark_node)
6208 return error_mark_node;
6209 if (fns)
6210 add_candidates (BASELINK_FUNCTIONS (fns),
6211 NULL_TREE, arglist, NULL_TREE,
6212 NULL_TREE, false,
6213 BASELINK_BINFO (fns),
6214 BASELINK_ACCESS_BINFO (fns),
6215 flags, candidates, complain);
6217 /* Per [over.match.oper]3.2, if no operand has a class type, then
6218 only non-member functions that have type T1 or reference to
6219 cv-qualified-opt T1 for the first argument, if the first argument
6220 has an enumeration type, or T2 or reference to cv-qualified-opt
6221 T2 for the second argument, if the second argument has an
6222 enumeration type. Filter out those that don't match. */
6223 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6225 struct z_candidate **candp, **next;
6227 for (candp = candidates; *candp != start_candidates; candp = next)
6229 unsigned i;
6230 z_candidate *cand = *candp;
6231 next = &cand->next;
6233 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6235 for (i = 0; i < nargs; ++i)
6237 tree parmtype = TREE_VALUE (parmlist);
6238 tree argtype = unlowered_expr_type ((*arglist)[i]);
6240 if (TYPE_REF_P (parmtype))
6241 parmtype = TREE_TYPE (parmtype);
6242 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6243 && (same_type_ignoring_top_level_qualifiers_p
6244 (argtype, parmtype)))
6245 break;
6247 parmlist = TREE_CHAIN (parmlist);
6250 /* No argument has an appropriate type, so remove this
6251 candidate function from the list. */
6252 if (i == nargs)
6254 *candp = cand->next;
6255 next = candp;
6260 if (!rewritten)
6262 /* The standard says to rewrite built-in candidates, too,
6263 but there's no point. */
6264 add_builtin_candidates (candidates, code, code2, fnname, arglist,
6265 flags, complain);
6267 /* Maybe add C++20 rewritten comparison candidates. */
6268 tree_code rewrite_code = ERROR_MARK;
6269 if (cxx_dialect >= cxx20
6270 && nargs == 2
6271 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6272 switch (code)
6274 case LT_EXPR:
6275 case LE_EXPR:
6276 case GT_EXPR:
6277 case GE_EXPR:
6278 case SPACESHIP_EXPR:
6279 rewrite_code = SPACESHIP_EXPR;
6280 break;
6282 case NE_EXPR:
6283 case EQ_EXPR:
6284 rewrite_code = EQ_EXPR;
6285 break;
6287 default:;
6290 if (rewrite_code)
6292 flags |= LOOKUP_REWRITTEN;
6293 if (rewrite_code != code)
6294 /* Add rewritten candidates in same order. */
6295 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6296 arglist, flags, complain);
6298 z_candidate *save_cand = *candidates;
6300 /* Add rewritten candidates in reverse order. */
6301 flags |= LOOKUP_REVERSED;
6302 vec<tree,va_gc> *revlist = make_tree_vector ();
6303 revlist->quick_push ((*arglist)[1]);
6304 revlist->quick_push ((*arglist)[0]);
6305 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6306 revlist, flags, complain);
6308 /* Release the vec if we didn't add a candidate that uses it. */
6309 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6310 if (c->args == revlist)
6312 revlist = NULL;
6313 break;
6315 release_tree_vector (revlist);
6319 return NULL_TREE;
6322 static tree
6323 build_new_op_1 (const op_location_t &loc, enum tree_code code, int flags,
6324 tree arg1, tree arg2, tree arg3, tree *overload,
6325 tsubst_flags_t complain)
6327 struct z_candidate *candidates = 0, *cand;
6328 vec<tree, va_gc> *arglist;
6329 tree result = NULL_TREE;
6330 bool result_valid_p = false;
6331 enum tree_code code2 = ERROR_MARK;
6332 enum tree_code code_orig_arg1 = ERROR_MARK;
6333 enum tree_code code_orig_arg2 = ERROR_MARK;
6334 conversion *conv;
6335 void *p;
6336 bool strict_p;
6337 bool any_viable_p;
6339 if (error_operand_p (arg1)
6340 || error_operand_p (arg2)
6341 || error_operand_p (arg3))
6342 return error_mark_node;
6344 bool ismodop = code == MODIFY_EXPR;
6345 if (ismodop)
6347 code2 = TREE_CODE (arg3);
6348 arg3 = NULL_TREE;
6351 tree arg1_type = unlowered_expr_type (arg1);
6352 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6354 arg1 = prep_operand (arg1);
6356 switch (code)
6358 case NEW_EXPR:
6359 case VEC_NEW_EXPR:
6360 case VEC_DELETE_EXPR:
6361 case DELETE_EXPR:
6362 /* Use build_operator_new_call and build_op_delete_call instead. */
6363 gcc_unreachable ();
6365 case CALL_EXPR:
6366 /* Use build_op_call instead. */
6367 gcc_unreachable ();
6369 case TRUTH_ORIF_EXPR:
6370 case TRUTH_ANDIF_EXPR:
6371 case TRUTH_AND_EXPR:
6372 case TRUTH_OR_EXPR:
6373 /* These are saved for the sake of warn_logical_operator. */
6374 code_orig_arg1 = TREE_CODE (arg1);
6375 code_orig_arg2 = TREE_CODE (arg2);
6376 break;
6377 case GT_EXPR:
6378 case LT_EXPR:
6379 case GE_EXPR:
6380 case LE_EXPR:
6381 case EQ_EXPR:
6382 case NE_EXPR:
6383 /* These are saved for the sake of maybe_warn_bool_compare. */
6384 code_orig_arg1 = TREE_CODE (arg1_type);
6385 code_orig_arg2 = TREE_CODE (arg2_type);
6386 break;
6388 default:
6389 break;
6392 arg2 = prep_operand (arg2);
6393 arg3 = prep_operand (arg3);
6395 if (code == COND_EXPR)
6396 /* Use build_conditional_expr instead. */
6397 gcc_unreachable ();
6398 else if (! OVERLOAD_TYPE_P (arg1_type)
6399 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
6400 goto builtin;
6402 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
6404 arg2 = integer_zero_node;
6405 arg2_type = integer_type_node;
6408 vec_alloc (arglist, 3);
6409 arglist->quick_push (arg1);
6410 if (arg2 != NULL_TREE)
6411 arglist->quick_push (arg2);
6412 if (arg3 != NULL_TREE)
6413 arglist->quick_push (arg3);
6415 /* Get the high-water mark for the CONVERSION_OBSTACK. */
6416 p = conversion_obstack_alloc (0);
6418 result = add_operator_candidates (&candidates, code, code2, arglist,
6419 flags, complain);
6420 if (result == error_mark_node)
6421 goto user_defined_result_ready;
6423 switch (code)
6425 case COMPOUND_EXPR:
6426 case ADDR_EXPR:
6427 /* For these, the built-in candidates set is empty
6428 [over.match.oper]/3. We don't want non-strict matches
6429 because exact matches are always possible with built-in
6430 operators. The built-in candidate set for COMPONENT_REF
6431 would be empty too, but since there are no such built-in
6432 operators, we accept non-strict matches for them. */
6433 strict_p = true;
6434 break;
6436 default:
6437 strict_p = false;
6438 break;
6441 candidates = splice_viable (candidates, strict_p, &any_viable_p);
6442 if (!any_viable_p)
6444 switch (code)
6446 case POSTINCREMENT_EXPR:
6447 case POSTDECREMENT_EXPR:
6448 /* Don't try anything fancy if we're not allowed to produce
6449 errors. */
6450 if (!(complain & tf_error))
6451 return error_mark_node;
6453 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
6454 distinguish between prefix and postfix ++ and
6455 operator++() was used for both, so we allow this with
6456 -fpermissive. */
6457 else
6459 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6460 const char *msg = (flag_permissive)
6461 ? G_("no %<%D(int)%> declared for postfix %qs,"
6462 " trying prefix operator instead")
6463 : G_("no %<%D(int)%> declared for postfix %qs");
6464 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
6467 if (!flag_permissive)
6468 return error_mark_node;
6470 if (code == POSTINCREMENT_EXPR)
6471 code = PREINCREMENT_EXPR;
6472 else
6473 code = PREDECREMENT_EXPR;
6474 result = build_new_op_1 (loc, code, flags, arg1, NULL_TREE,
6475 NULL_TREE, overload, complain);
6476 break;
6478 /* The caller will deal with these. */
6479 case ADDR_EXPR:
6480 case COMPOUND_EXPR:
6481 case COMPONENT_REF:
6482 case CO_AWAIT_EXPR:
6483 result = NULL_TREE;
6484 result_valid_p = true;
6485 break;
6487 default:
6488 if (complain & tf_error)
6490 /* If one of the arguments of the operator represents
6491 an invalid use of member function pointer, try to report
6492 a meaningful error ... */
6493 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
6494 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
6495 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
6496 /* We displayed the error message. */;
6497 else
6499 /* ... Otherwise, report the more generic
6500 "no matching operator found" error */
6501 auto_diagnostic_group d;
6502 op_error (loc, code, code2, arg1, arg2, arg3, FALSE);
6503 print_z_candidates (loc, candidates);
6506 result = error_mark_node;
6507 break;
6510 else
6512 cand = tourney (candidates, complain);
6513 if (cand == 0)
6515 if (complain & tf_error)
6517 auto_diagnostic_group d;
6518 op_error (loc, code, code2, arg1, arg2, arg3, TRUE);
6519 print_z_candidates (loc, candidates);
6521 result = error_mark_node;
6522 if (overload)
6523 *overload = error_mark_node;
6525 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
6527 if (overload)
6528 *overload = cand->fn;
6530 if (resolve_args (arglist, complain) == NULL)
6531 result = error_mark_node;
6532 else
6534 tsubst_flags_t ocomplain = complain;
6535 if (cand->rewritten ())
6536 /* We'll wrap this call in another one. */
6537 ocomplain &= ~tf_decltype;
6538 if (cand->reversed ())
6540 /* We swapped these in add_candidate, swap them back now. */
6541 std::swap (cand->convs[0], cand->convs[1]);
6542 if (cand->fn == current_function_decl)
6543 warning_at (loc, 0, "in C++20 this comparison calls the "
6544 "current function recursively with reversed "
6545 "arguments");
6547 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
6550 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
6551 /* There won't be a CALL_EXPR. */;
6552 else if (result && result != error_mark_node)
6554 tree call = extract_call_expr (result);
6555 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
6557 /* Specify evaluation order as per P0145R2. */
6558 CALL_EXPR_ORDERED_ARGS (call) = false;
6559 switch (op_is_ordered (code))
6561 case -1:
6562 CALL_EXPR_REVERSE_ARGS (call) = true;
6563 break;
6565 case 1:
6566 CALL_EXPR_ORDERED_ARGS (call) = true;
6567 break;
6569 default:
6570 break;
6574 /* If this was a C++20 rewritten comparison, adjust the result. */
6575 if (cand->rewritten ())
6577 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
6578 if (overload)
6579 *overload = NULL_TREE;
6580 switch (code)
6582 case EQ_EXPR:
6583 gcc_checking_assert (cand->reversed ());
6584 gcc_fallthrough ();
6585 case NE_EXPR:
6586 /* If a rewritten operator== candidate is selected by
6587 overload resolution for an operator @, its return type
6588 shall be cv bool.... */
6589 if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
6591 if (complain & tf_error)
6593 auto_diagnostic_group d;
6594 error_at (loc, "return type of %qD is not %qs",
6595 cand->fn, "bool");
6596 inform (loc, "used as rewritten candidate for "
6597 "comparison of %qT and %qT",
6598 arg1_type, arg2_type);
6600 result = error_mark_node;
6602 else if (code == NE_EXPR)
6603 /* !(y == x) or !(x == y) */
6604 result = build1_loc (loc, TRUTH_NOT_EXPR,
6605 boolean_type_node, result);
6606 break;
6608 /* If a rewritten operator<=> candidate is selected by
6609 overload resolution for an operator @, x @ y is
6610 interpreted as 0 @ (y <=> x) if the selected candidate is
6611 a synthesized candidate with reversed order of parameters,
6612 or (x <=> y) @ 0 otherwise, using the selected rewritten
6613 operator<=> candidate. */
6614 case SPACESHIP_EXPR:
6615 if (!cand->reversed ())
6616 /* We're in the build_new_op call below for an outer
6617 reversed call; we don't need to do anything more. */
6618 break;
6619 gcc_fallthrough ();
6620 case LT_EXPR:
6621 case LE_EXPR:
6622 case GT_EXPR:
6623 case GE_EXPR:
6625 tree lhs = result;
6626 tree rhs = integer_zero_node;
6627 if (cand->reversed ())
6628 std::swap (lhs, rhs);
6629 warning_sentinel ws (warn_zero_as_null_pointer_constant);
6630 result = build_new_op (loc, code,
6631 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
6632 lhs, rhs, NULL_TREE,
6633 NULL, complain);
6635 break;
6637 default:
6638 gcc_unreachable ();
6642 else
6644 /* Give any warnings we noticed during overload resolution. */
6645 if (cand->warnings && (complain & tf_warning))
6647 struct candidate_warning *w;
6648 for (w = cand->warnings; w; w = w->next)
6649 joust (cand, w->loser, 1, complain);
6652 /* Check for comparison of different enum types. */
6653 switch (code)
6655 case GT_EXPR:
6656 case LT_EXPR:
6657 case GE_EXPR:
6658 case LE_EXPR:
6659 case EQ_EXPR:
6660 case NE_EXPR:
6661 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
6662 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
6663 && (TYPE_MAIN_VARIANT (arg1_type)
6664 != TYPE_MAIN_VARIANT (arg2_type))
6665 && (complain & tf_warning))
6666 warning_at (loc, OPT_Wenum_compare,
6667 "comparison between %q#T and %q#T",
6668 arg1_type, arg2_type);
6669 break;
6670 default:
6671 break;
6674 /* "If a built-in candidate is selected by overload resolution, the
6675 operands of class type are converted to the types of the
6676 corresponding parameters of the selected operation function,
6677 except that the second standard conversion sequence of a
6678 user-defined conversion sequence (12.3.3.1.2) is not applied." */
6679 conv = cand->convs[0];
6680 if (conv->user_conv_p)
6682 conv = strip_standard_conversion (conv);
6683 arg1 = convert_like (conv, arg1, complain);
6686 if (arg2)
6688 conv = cand->convs[1];
6689 if (conv->user_conv_p)
6691 conv = strip_standard_conversion (conv);
6692 arg2 = convert_like (conv, arg2, complain);
6696 if (arg3)
6698 conv = cand->convs[2];
6699 if (conv->user_conv_p)
6701 conv = strip_standard_conversion (conv);
6702 arg3 = convert_like (conv, arg3, complain);
6708 user_defined_result_ready:
6710 /* Free all the conversions we allocated. */
6711 obstack_free (&conversion_obstack, p);
6713 if (result || result_valid_p)
6714 return result;
6716 builtin:
6717 switch (code)
6719 case MODIFY_EXPR:
6720 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
6722 case INDIRECT_REF:
6723 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
6725 case TRUTH_ANDIF_EXPR:
6726 case TRUTH_ORIF_EXPR:
6727 case TRUTH_AND_EXPR:
6728 case TRUTH_OR_EXPR:
6729 if (complain & tf_warning)
6730 warn_logical_operator (loc, code, boolean_type_node,
6731 code_orig_arg1, arg1,
6732 code_orig_arg2, arg2);
6733 /* Fall through. */
6734 case GT_EXPR:
6735 case LT_EXPR:
6736 case GE_EXPR:
6737 case LE_EXPR:
6738 case EQ_EXPR:
6739 case NE_EXPR:
6740 if ((complain & tf_warning)
6741 && ((code_orig_arg1 == BOOLEAN_TYPE)
6742 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
6743 maybe_warn_bool_compare (loc, code, arg1, arg2);
6744 if (complain & tf_warning && warn_tautological_compare)
6745 warn_tautological_cmp (loc, code, arg1, arg2);
6746 /* Fall through. */
6747 case SPACESHIP_EXPR:
6748 case PLUS_EXPR:
6749 case MINUS_EXPR:
6750 case MULT_EXPR:
6751 case TRUNC_DIV_EXPR:
6752 case MAX_EXPR:
6753 case MIN_EXPR:
6754 case LSHIFT_EXPR:
6755 case RSHIFT_EXPR:
6756 case TRUNC_MOD_EXPR:
6757 case BIT_AND_EXPR:
6758 case BIT_IOR_EXPR:
6759 case BIT_XOR_EXPR:
6760 return cp_build_binary_op (loc, code, arg1, arg2, complain);
6762 case UNARY_PLUS_EXPR:
6763 case NEGATE_EXPR:
6764 case BIT_NOT_EXPR:
6765 case TRUTH_NOT_EXPR:
6766 case PREINCREMENT_EXPR:
6767 case POSTINCREMENT_EXPR:
6768 case PREDECREMENT_EXPR:
6769 case POSTDECREMENT_EXPR:
6770 case REALPART_EXPR:
6771 case IMAGPART_EXPR:
6772 case ABS_EXPR:
6773 case CO_AWAIT_EXPR:
6774 return cp_build_unary_op (code, arg1, false, complain);
6776 case ARRAY_REF:
6777 return cp_build_array_ref (input_location, arg1, arg2, complain);
6779 case MEMBER_REF:
6780 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
6781 RO_ARROW_STAR,
6782 complain),
6783 arg2, complain);
6785 /* The caller will deal with these. */
6786 case ADDR_EXPR:
6787 case COMPONENT_REF:
6788 case COMPOUND_EXPR:
6789 return NULL_TREE;
6791 default:
6792 gcc_unreachable ();
6794 return NULL_TREE;
6797 /* Wrapper for above. */
6799 tree
6800 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6801 tree arg1, tree arg2, tree arg3,
6802 tree *overload, tsubst_flags_t complain)
6804 tree ret;
6805 bool subtime = timevar_cond_start (TV_OVERLOAD);
6806 ret = build_new_op_1 (loc, code, flags, arg1, arg2, arg3,
6807 overload, complain);
6808 timevar_cond_stop (TV_OVERLOAD, subtime);
6809 return ret;
6812 /* CALL was returned by some call-building function; extract the actual
6813 CALL_EXPR from any bits that have been tacked on, e.g. by
6814 convert_from_reference. */
6816 tree
6817 extract_call_expr (tree call)
6819 while (TREE_CODE (call) == COMPOUND_EXPR)
6820 call = TREE_OPERAND (call, 1);
6821 if (REFERENCE_REF_P (call))
6822 call = TREE_OPERAND (call, 0);
6823 if (TREE_CODE (call) == TARGET_EXPR)
6824 call = TARGET_EXPR_INITIAL (call);
6825 if (cxx_dialect >= cxx20)
6826 switch (TREE_CODE (call))
6828 /* C++20 rewritten comparison operators. */
6829 case TRUTH_NOT_EXPR:
6830 call = TREE_OPERAND (call, 0);
6831 break;
6832 case LT_EXPR:
6833 case LE_EXPR:
6834 case GT_EXPR:
6835 case GE_EXPR:
6836 case SPACESHIP_EXPR:
6838 tree op0 = TREE_OPERAND (call, 0);
6839 if (integer_zerop (op0))
6840 call = TREE_OPERAND (call, 1);
6841 else
6842 call = op0;
6844 break;
6845 default:;
6848 gcc_assert (TREE_CODE (call) == CALL_EXPR
6849 || TREE_CODE (call) == AGGR_INIT_EXPR
6850 || call == error_mark_node);
6851 return call;
6854 /* Returns true if FN has two parameters, of which the second has type
6855 size_t. */
6857 static bool
6858 second_parm_is_size_t (tree fn)
6860 tree t = FUNCTION_ARG_CHAIN (fn);
6861 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
6862 return false;
6863 t = TREE_CHAIN (t);
6864 if (t == void_list_node)
6865 return true;
6866 return false;
6869 /* True if T, an allocation function, has std::align_val_t as its second
6870 argument. */
6872 bool
6873 aligned_allocation_fn_p (tree t)
6875 if (!aligned_new_threshold)
6876 return false;
6878 tree a = FUNCTION_ARG_CHAIN (t);
6879 return (a && same_type_p (TREE_VALUE (a), align_type_node));
6882 /* True if T is std::destroying_delete_t. */
6884 static bool
6885 std_destroying_delete_t_p (tree t)
6887 return (TYPE_CONTEXT (t) == std_node
6888 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
6891 /* A deallocation function with at least two parameters whose second parameter
6892 type is of type std::destroying_delete_t is a destroying operator delete. A
6893 destroying operator delete shall be a class member function named operator
6894 delete. [ Note: Array deletion cannot use a destroying operator
6895 delete. --end note ] */
6897 tree
6898 destroying_delete_p (tree t)
6900 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
6901 if (!a || !TREE_CHAIN (a))
6902 return NULL_TREE;
6903 tree type = TREE_VALUE (TREE_CHAIN (a));
6904 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
6907 struct dealloc_info
6909 bool sized;
6910 bool aligned;
6911 tree destroying;
6914 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
6915 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
6916 non-null, also set *DI. */
6918 static bool
6919 usual_deallocation_fn_p (tree t, dealloc_info *di)
6921 if (di) *di = dealloc_info();
6923 /* A template instance is never a usual deallocation function,
6924 regardless of its signature. */
6925 if (TREE_CODE (t) == TEMPLATE_DECL
6926 || primary_template_specialization_p (t))
6927 return false;
6929 /* A usual deallocation function is a deallocation function whose parameters
6930 after the first are
6931 - optionally, a parameter of type std::destroying_delete_t, then
6932 - optionally, a parameter of type std::size_t, then
6933 - optionally, a parameter of type std::align_val_t. */
6934 bool global = DECL_NAMESPACE_SCOPE_P (t);
6935 tree chain = FUNCTION_ARG_CHAIN (t);
6936 if (chain && destroying_delete_p (t))
6938 if (di) di->destroying = TREE_VALUE (chain);
6939 chain = TREE_CHAIN (chain);
6941 if (chain
6942 && (!global || flag_sized_deallocation)
6943 && same_type_p (TREE_VALUE (chain), size_type_node))
6945 if (di) di->sized = true;
6946 chain = TREE_CHAIN (chain);
6948 if (chain && aligned_new_threshold
6949 && same_type_p (TREE_VALUE (chain), align_type_node))
6951 if (di) di->aligned = true;
6952 chain = TREE_CHAIN (chain);
6954 return (chain == void_list_node);
6957 /* Just return whether FN is a usual deallocation function. */
6959 bool
6960 usual_deallocation_fn_p (tree fn)
6962 return usual_deallocation_fn_p (fn, NULL);
6965 /* Build a call to operator delete. This has to be handled very specially,
6966 because the restrictions on what signatures match are different from all
6967 other call instances. For a normal delete, only a delete taking (void *)
6968 or (void *, size_t) is accepted. For a placement delete, only an exact
6969 match with the placement new is accepted.
6971 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
6972 ADDR is the pointer to be deleted.
6973 SIZE is the size of the memory block to be deleted.
6974 GLOBAL_P is true if the delete-expression should not consider
6975 class-specific delete operators.
6976 PLACEMENT is the corresponding placement new call, or NULL_TREE.
6978 If this call to "operator delete" is being generated as part to
6979 deallocate memory allocated via a new-expression (as per [expr.new]
6980 which requires that if the initialization throws an exception then
6981 we call a deallocation function), then ALLOC_FN is the allocation
6982 function. */
6984 tree
6985 build_op_delete_call (enum tree_code code, tree addr, tree size,
6986 bool global_p, tree placement,
6987 tree alloc_fn, tsubst_flags_t complain)
6989 tree fn = NULL_TREE;
6990 tree fns, fnname, type, t;
6991 dealloc_info di_fn = { };
6993 if (addr == error_mark_node)
6994 return error_mark_node;
6996 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
6998 fnname = ovl_op_identifier (false, code);
7000 if (CLASS_TYPE_P (type)
7001 && COMPLETE_TYPE_P (complete_type (type))
7002 && !global_p)
7003 /* In [class.free]
7005 If the result of the lookup is ambiguous or inaccessible, or if
7006 the lookup selects a placement deallocation function, the
7007 program is ill-formed.
7009 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7011 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7012 if (fns == error_mark_node)
7013 return error_mark_node;
7015 else
7016 fns = NULL_TREE;
7018 if (fns == NULL_TREE)
7019 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7021 /* Strip const and volatile from addr. */
7022 tree oaddr = addr;
7023 addr = cp_convert (ptr_type_node, addr, complain);
7025 if (placement)
7027 /* "A declaration of a placement deallocation function matches the
7028 declaration of a placement allocation function if it has the same
7029 number of parameters and, after parameter transformations (8.3.5),
7030 all parameter types except the first are identical."
7032 So we build up the function type we want and ask instantiate_type
7033 to get it for us. */
7034 t = FUNCTION_ARG_CHAIN (alloc_fn);
7035 t = tree_cons (NULL_TREE, ptr_type_node, t);
7036 t = build_function_type (void_type_node, t);
7038 fn = instantiate_type (t, fns, tf_none);
7039 if (fn == error_mark_node)
7040 return NULL_TREE;
7042 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7044 /* "If the lookup finds the two-parameter form of a usual deallocation
7045 function (3.7.4.2) and that function, considered as a placement
7046 deallocation function, would have been selected as a match for the
7047 allocation function, the program is ill-formed." */
7048 if (second_parm_is_size_t (fn))
7050 const char *const msg1
7051 = G_("exception cleanup for this placement new selects "
7052 "non-placement %<operator delete%>");
7053 const char *const msg2
7054 = G_("%qD is a usual (non-placement) deallocation "
7055 "function in C++14 (or with %<-fsized-deallocation%>)");
7057 /* But if the class has an operator delete (void *), then that is
7058 the usual deallocation function, so we shouldn't complain
7059 about using the operator delete (void *, size_t). */
7060 if (DECL_CLASS_SCOPE_P (fn))
7061 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7063 if (usual_deallocation_fn_p (elt)
7064 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7065 goto ok;
7067 /* Before C++14 a two-parameter global deallocation function is
7068 always a placement deallocation function, but warn if
7069 -Wc++14-compat. */
7070 else if (!flag_sized_deallocation)
7072 if (complain & tf_warning)
7074 auto_diagnostic_group d;
7075 if (warning (OPT_Wc__14_compat, msg1))
7076 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7078 goto ok;
7081 if (complain & tf_warning_or_error)
7083 auto_diagnostic_group d;
7084 if (permerror (input_location, msg1))
7086 /* Only mention C++14 for namespace-scope delete. */
7087 if (DECL_NAMESPACE_SCOPE_P (fn))
7088 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7089 else
7090 inform (DECL_SOURCE_LOCATION (fn),
7091 "%qD is a usual (non-placement) deallocation "
7092 "function", fn);
7095 else
7096 return error_mark_node;
7097 ok:;
7100 else
7101 /* "Any non-placement deallocation function matches a non-placement
7102 allocation function. If the lookup finds a single matching
7103 deallocation function, that function will be called; otherwise, no
7104 deallocation function will be called." */
7105 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7107 dealloc_info di_elt;
7108 if (usual_deallocation_fn_p (elt, &di_elt))
7110 if (!fn)
7112 fn = elt;
7113 di_fn = di_elt;
7114 continue;
7117 /* -- If any of the deallocation functions is a destroying
7118 operator delete, all deallocation functions that are not
7119 destroying operator deletes are eliminated from further
7120 consideration. */
7121 if (di_elt.destroying != di_fn.destroying)
7123 if (di_elt.destroying)
7125 fn = elt;
7126 di_fn = di_elt;
7128 continue;
7131 /* -- If the type has new-extended alignment, a function with a
7132 parameter of type std::align_val_t is preferred; otherwise a
7133 function without such a parameter is preferred. If exactly one
7134 preferred function is found, that function is selected and the
7135 selection process terminates. If more than one preferred
7136 function is found, all non-preferred functions are eliminated
7137 from further consideration. */
7138 if (aligned_new_threshold)
7140 bool want_align = type_has_new_extended_alignment (type);
7141 if (di_elt.aligned != di_fn.aligned)
7143 if (want_align == di_elt.aligned)
7145 fn = elt;
7146 di_fn = di_elt;
7148 continue;
7152 /* -- If the deallocation functions have class scope, the one
7153 without a parameter of type std::size_t is selected. */
7154 bool want_size;
7155 if (DECL_CLASS_SCOPE_P (fn))
7156 want_size = false;
7158 /* -- If the type is complete and if, for the second alternative
7159 (delete array) only, the operand is a pointer to a class type
7160 with a non-trivial destructor or a (possibly multi-dimensional)
7161 array thereof, the function with a parameter of type std::size_t
7162 is selected.
7164 -- Otherwise, it is unspecified whether a deallocation function
7165 with a parameter of type std::size_t is selected. */
7166 else
7168 want_size = COMPLETE_TYPE_P (type);
7169 if (code == VEC_DELETE_EXPR
7170 && !TYPE_VEC_NEW_USES_COOKIE (type))
7171 /* We need a cookie to determine the array size. */
7172 want_size = false;
7174 gcc_assert (di_fn.sized != di_elt.sized);
7175 if (want_size == di_elt.sized)
7177 fn = elt;
7178 di_fn = di_elt;
7183 /* If we have a matching function, call it. */
7184 if (fn)
7186 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7188 /* If the FN is a member function, make sure that it is
7189 accessible. */
7190 if (BASELINK_P (fns))
7191 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7192 complain);
7194 /* Core issue 901: It's ok to new a type with deleted delete. */
7195 if (DECL_DELETED_FN (fn) && alloc_fn)
7196 return NULL_TREE;
7198 tree ret;
7199 if (placement)
7201 /* The placement args might not be suitable for overload
7202 resolution at this point, so build the call directly. */
7203 int nargs = call_expr_nargs (placement);
7204 tree *argarray = XALLOCAVEC (tree, nargs);
7205 int i;
7206 argarray[0] = addr;
7207 for (i = 1; i < nargs; i++)
7208 argarray[i] = CALL_EXPR_ARG (placement, i);
7209 if (!mark_used (fn, complain) && !(complain & tf_error))
7210 return error_mark_node;
7211 ret = build_cxx_call (fn, nargs, argarray, complain);
7213 else
7215 tree destroying = di_fn.destroying;
7216 if (destroying)
7218 /* Strip const and volatile from addr but retain the type of the
7219 object. */
7220 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7221 rtype = cv_unqualified (rtype);
7222 rtype = TYPE_POINTER_TO (rtype);
7223 addr = cp_convert (rtype, oaddr, complain);
7224 destroying = build_functional_cast (input_location,
7225 destroying, NULL_TREE,
7226 complain);
7229 releasing_vec args;
7230 args->quick_push (addr);
7231 if (destroying)
7232 args->quick_push (destroying);
7233 if (di_fn.sized)
7234 args->quick_push (size);
7235 if (di_fn.aligned)
7237 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7238 args->quick_push (al);
7240 ret = cp_build_function_call_vec (fn, &args, complain);
7243 /* Set this flag for all callers of this function. In addition to
7244 delete-expressions, this is called for deallocating coroutine state;
7245 treat that as an implicit delete-expression. This is also called for
7246 the delete if the constructor throws in a new-expression, and for a
7247 deleting destructor (which implements a delete-expression). */
7248 /* But leave this flag off for destroying delete to avoid wrong
7249 assumptions in the optimizers. */
7250 tree call = extract_call_expr (ret);
7251 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
7252 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7254 return ret;
7257 /* [expr.new]
7259 If no unambiguous matching deallocation function can be found,
7260 propagating the exception does not cause the object's memory to
7261 be freed. */
7262 if (alloc_fn)
7264 if ((complain & tf_warning)
7265 && !placement)
7266 warning (0, "no corresponding deallocation function for %qD",
7267 alloc_fn);
7268 return NULL_TREE;
7271 if (complain & tf_error)
7272 error ("no suitable %<operator %s%> for %qT",
7273 OVL_OP_INFO (false, code)->name, type);
7274 return error_mark_node;
7277 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
7278 in the diagnostics.
7280 If ISSUE_ERROR is true, then issue an error about the access, followed
7281 by a note showing the declaration. Otherwise, just show the note.
7283 DIAG_DECL and DIAG_LOCATION will almost always be the same.
7284 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
7285 parameter used to specify why DECL wasn't accessible (e.g. ak_private
7286 would be because DECL was private). If not using NO_ACCESS_REASON,
7287 then it must be ak_none, and the access failure reason will be
7288 figured out by looking at the protection of DECL. */
7290 void
7291 complain_about_access (tree decl, tree diag_decl, tree diag_location,
7292 bool issue_error, access_kind no_access_reason)
7294 /* If we have not already figured out why DECL is inaccessible... */
7295 if (no_access_reason == ak_none)
7297 /* Examine the access of DECL to find out why. */
7298 if (TREE_PRIVATE (decl))
7299 no_access_reason = ak_private;
7300 else if (TREE_PROTECTED (decl))
7301 no_access_reason = ak_protected;
7304 /* Now generate an error message depending on calculated access. */
7305 if (no_access_reason == ak_private)
7307 if (issue_error)
7308 error ("%q#D is private within this context", diag_decl);
7309 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
7311 else if (no_access_reason == ak_protected)
7313 if (issue_error)
7314 error ("%q#D is protected within this context", diag_decl);
7315 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
7317 /* Couldn't figure out why DECL is inaccesible, so just say it's
7318 inaccessible. */
7319 else
7321 if (issue_error)
7322 error ("%q#D is inaccessible within this context", diag_decl);
7323 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
7327 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
7328 bitwise or of LOOKUP_* values. If any errors are warnings are
7329 generated, set *DIAGNOSTIC_FN to "error" or "warning",
7330 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
7331 to NULL. */
7333 static tree
7334 build_temp (tree expr, tree type, int flags,
7335 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
7337 int savew, savee;
7339 *diagnostic_kind = DK_UNSPECIFIED;
7341 /* If the source is a packed field, calling the copy constructor will require
7342 binding the field to the reference parameter to the copy constructor, and
7343 we'll end up with an infinite loop. If we can use a bitwise copy, then
7344 do that now. */
7345 if ((lvalue_kind (expr) & clk_packed)
7346 && CLASS_TYPE_P (TREE_TYPE (expr))
7347 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
7348 return get_target_expr_sfinae (expr, complain);
7350 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
7351 But it turns out to be a subexpression, so perform temporary
7352 materialization now. */
7353 if (TREE_CODE (expr) == CALL_EXPR
7354 && CLASS_TYPE_P (type)
7355 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7356 expr = build_cplus_new (type, expr, complain);
7358 savew = warningcount + werrorcount, savee = errorcount;
7359 releasing_vec args (make_tree_vector_single (expr));
7360 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7361 &args, type, flags, complain);
7362 if (warningcount + werrorcount > savew)
7363 *diagnostic_kind = DK_WARNING;
7364 else if (errorcount > savee)
7365 *diagnostic_kind = DK_ERROR;
7366 return expr;
7369 /* Get any location for EXPR, falling back to input_location.
7371 If the result is in a system header and is the virtual location for
7372 a token coming from the expansion of a macro, unwind it to the
7373 location of the expansion point of the macro (e.g. to avoid the
7374 diagnostic being suppressed for expansions of NULL where "NULL" is
7375 in a system header). */
7377 static location_t
7378 get_location_for_expr_unwinding_for_system_header (tree expr)
7380 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
7381 loc = expansion_point_location_if_in_system_header (loc);
7382 return loc;
7385 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
7386 Also handle a subset of zero as null warnings.
7387 EXPR is implicitly converted to type TOTYPE.
7388 FN and ARGNUM are used for diagnostics. */
7390 static void
7391 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
7393 /* Issue warnings about peculiar, but valid, uses of NULL. */
7394 if (TREE_CODE (totype) != BOOLEAN_TYPE
7395 && ARITHMETIC_TYPE_P (totype)
7396 && null_node_p (expr))
7398 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7399 if (fn)
7401 auto_diagnostic_group d;
7402 if (warning_at (loc, OPT_Wconversion_null,
7403 "passing NULL to non-pointer argument %P of %qD",
7404 argnum, fn))
7405 inform (get_fndecl_argument_location (fn, argnum),
7406 " declared here");
7408 else
7409 warning_at (loc, OPT_Wconversion_null,
7410 "converting to non-pointer type %qT from NULL", totype);
7413 /* Issue warnings if "false" is converted to a NULL pointer */
7414 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
7415 && TYPE_PTR_P (totype))
7417 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7418 if (fn)
7420 auto_diagnostic_group d;
7421 if (warning_at (loc, OPT_Wconversion_null,
7422 "converting %<false%> to pointer type for argument "
7423 "%P of %qD", argnum, fn))
7424 inform (get_fndecl_argument_location (fn, argnum),
7425 " declared here");
7427 else
7428 warning_at (loc, OPT_Wconversion_null,
7429 "converting %<false%> to pointer type %qT", totype);
7431 /* Handle zero as null pointer warnings for cases other
7432 than EQ_EXPR and NE_EXPR */
7433 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
7434 && null_ptr_cst_p (expr))
7436 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7437 maybe_warn_zero_as_null_pointer_constant (expr, loc);
7441 /* We gave a diagnostic during a conversion. If this was in the second
7442 standard conversion sequence of a user-defined conversion sequence, say
7443 which user-defined conversion. */
7445 static void
7446 maybe_print_user_conv_context (conversion *convs)
7448 if (convs->user_conv_p)
7449 for (conversion *t = convs; t; t = next_conversion (t))
7450 if (t->kind == ck_user)
7452 print_z_candidate (0, N_(" after user-defined conversion:"),
7453 t->cand);
7454 break;
7458 /* Locate the parameter with the given index within FNDECL.
7459 ARGNUM is zero based, -1 indicates the `this' argument of a method.
7460 Return the location of the FNDECL itself if there are problems. */
7462 location_t
7463 get_fndecl_argument_location (tree fndecl, int argnum)
7465 /* The locations of implicitly-declared functions are likely to be
7466 more meaningful than those of their parameters. */
7467 if (DECL_ARTIFICIAL (fndecl))
7468 return DECL_SOURCE_LOCATION (fndecl);
7470 int i;
7471 tree param;
7473 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
7474 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
7475 i < argnum && param;
7476 i++, param = TREE_CHAIN (param))
7479 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
7480 return the location of FNDECL. */
7481 if (param == NULL)
7482 return DECL_SOURCE_LOCATION (fndecl);
7484 return DECL_SOURCE_LOCATION (param);
7487 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
7488 within its declaration (or the fndecl itself if something went
7489 wrong). */
7491 void
7492 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
7494 if (fn)
7495 inform (get_fndecl_argument_location (fn, argnum),
7496 " initializing argument %P of %qD", argnum, fn);
7499 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
7500 the conversion, EXPR is the expression we're converting. */
7502 static void
7503 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
7505 if (cxx_dialect >= cxx20)
7506 return;
7508 tree type = TREE_TYPE (expr);
7509 type = strip_pointer_operator (type);
7511 if (TREE_CODE (type) != ARRAY_TYPE
7512 || TYPE_DOMAIN (type) == NULL_TREE)
7513 return;
7515 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
7516 pedwarn (loc, OPT_Wc__20_extensions,
7517 "conversions to arrays of unknown bound "
7518 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
7521 /* We call this recursively in convert_like_internal. */
7522 static tree convert_like (conversion *, tree, tree, int, bool, bool,
7523 tsubst_flags_t);
7525 /* Perform the conversions in CONVS on the expression EXPR. FN and
7526 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
7527 indicates the `this' argument of a method. INNER is nonzero when
7528 being called to continue a conversion chain. It is negative when a
7529 reference binding will be applied, positive otherwise. If
7530 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
7531 conversions will be emitted if appropriate. If C_CAST_P is true,
7532 this conversion is coming from a C-style cast; in that case,
7533 conversions to inaccessible bases are permitted. */
7535 static tree
7536 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
7537 bool issue_conversion_warnings, bool c_cast_p,
7538 tsubst_flags_t complain)
7540 tree totype = convs->type;
7541 diagnostic_t diag_kind;
7542 int flags;
7543 location_t loc = cp_expr_loc_or_input_loc (expr);
7545 if (convs->bad_p && !(complain & tf_error))
7546 return error_mark_node;
7548 if (convs->bad_p
7549 && convs->kind != ck_user
7550 && convs->kind != ck_list
7551 && convs->kind != ck_ambig
7552 && (convs->kind != ck_ref_bind
7553 || (convs->user_conv_p && next_conversion (convs)->bad_p))
7554 && (convs->kind != ck_rvalue
7555 || SCALAR_TYPE_P (totype))
7556 && convs->kind != ck_base)
7558 bool complained = false;
7559 conversion *t = convs;
7561 /* Give a helpful error if this is bad because of excess braces. */
7562 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7563 && SCALAR_TYPE_P (totype)
7564 && CONSTRUCTOR_NELTS (expr) > 0
7565 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
7567 complained = permerror (loc, "too many braces around initializer "
7568 "for %qT", totype);
7569 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
7570 && CONSTRUCTOR_NELTS (expr) == 1)
7571 expr = CONSTRUCTOR_ELT (expr, 0)->value;
7574 /* Give a helpful error if this is bad because a conversion to bool
7575 from std::nullptr_t requires direct-initialization. */
7576 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
7577 && TREE_CODE (totype) == BOOLEAN_TYPE)
7578 complained = permerror (loc, "converting to %qH from %qI requires "
7579 "direct-initialization",
7580 totype, TREE_TYPE (expr));
7582 for (; t ; t = next_conversion (t))
7584 if (t->kind == ck_user && t->cand->reason)
7586 auto_diagnostic_group d;
7587 complained = permerror (loc, "invalid user-defined conversion "
7588 "from %qH to %qI", TREE_TYPE (expr),
7589 totype);
7590 if (complained)
7591 print_z_candidate (loc, N_("candidate is:"), t->cand);
7592 expr = convert_like (t, expr, fn, argnum,
7593 /*issue_conversion_warnings=*/false,
7594 /*c_cast_p=*/false, complain);
7595 if (convs->kind == ck_ref_bind)
7596 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
7597 LOOKUP_NORMAL, NULL_TREE,
7598 complain);
7599 else
7600 expr = cp_convert (totype, expr, complain);
7601 if (complained)
7602 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7603 return expr;
7605 else if (t->kind == ck_user || !t->bad_p)
7607 expr = convert_like (t, expr, fn, argnum,
7608 /*issue_conversion_warnings=*/false,
7609 /*c_cast_p=*/false, complain);
7610 break;
7612 else if (t->kind == ck_ambig)
7613 return convert_like (t, expr, fn, argnum,
7614 /*issue_conversion_warnings=*/false,
7615 /*c_cast_p=*/false, complain);
7616 else if (t->kind == ck_identity)
7617 break;
7619 if (!complained && expr != error_mark_node)
7621 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
7622 gcc_rich_location richloc (loc, &label);
7623 complained = permerror (&richloc,
7624 "invalid conversion from %qH to %qI",
7625 TREE_TYPE (expr), totype);
7627 if (complained)
7628 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7630 return cp_convert (totype, expr, complain);
7633 if (issue_conversion_warnings && (complain & tf_warning))
7634 conversion_null_warnings (totype, expr, fn, argnum);
7636 switch (convs->kind)
7638 case ck_user:
7640 struct z_candidate *cand = convs->cand;
7642 if (cand == NULL)
7643 /* We chose the surrogate function from add_conv_candidate, now we
7644 actually need to build the conversion. */
7645 cand = build_user_type_conversion_1 (totype, expr,
7646 LOOKUP_NO_CONVERSION, complain);
7648 tree convfn = cand->fn;
7650 /* When converting from an init list we consider explicit
7651 constructors, but actually trying to call one is an error. */
7652 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
7653 && BRACE_ENCLOSED_INITIALIZER_P (expr)
7654 /* Unless this is for direct-list-initialization. */
7655 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
7656 /* And in C++98 a default constructor can't be explicit. */
7657 && cxx_dialect >= cxx11)
7659 if (!(complain & tf_error))
7660 return error_mark_node;
7661 location_t loc = location_of (expr);
7662 if (CONSTRUCTOR_NELTS (expr) == 0
7663 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
7665 auto_diagnostic_group d;
7666 if (pedwarn (loc, 0, "converting to %qT from initializer list "
7667 "would use explicit constructor %qD",
7668 totype, convfn))
7669 inform (loc, "in C++11 and above a default constructor "
7670 "can be explicit");
7672 else
7673 error ("converting to %qT from initializer list would use "
7674 "explicit constructor %qD", totype, convfn);
7677 /* If we're initializing from {}, it's value-initialization. */
7678 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7679 && CONSTRUCTOR_NELTS (expr) == 0
7680 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
7681 && !processing_template_decl)
7683 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
7684 if (abstract_virtuals_error_sfinae (NULL_TREE, totype, complain))
7685 return error_mark_node;
7686 expr = build_value_init (totype, complain);
7687 expr = get_target_expr_sfinae (expr, complain);
7688 if (expr != error_mark_node)
7690 TARGET_EXPR_LIST_INIT_P (expr) = true;
7691 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
7693 return expr;
7696 /* We don't know here whether EXPR is being used as an lvalue or
7697 rvalue, but we know it's read. */
7698 mark_exp_read (expr);
7700 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
7701 any more UDCs. */
7702 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
7703 complain);
7705 /* If this is a constructor or a function returning an aggr type,
7706 we need to build up a TARGET_EXPR. */
7707 if (DECL_CONSTRUCTOR_P (convfn))
7709 expr = build_cplus_new (totype, expr, complain);
7711 /* Remember that this was list-initialization. */
7712 if (convs->check_narrowing && expr != error_mark_node)
7713 TARGET_EXPR_LIST_INIT_P (expr) = true;
7716 return expr;
7718 case ck_identity:
7719 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
7721 int nelts = CONSTRUCTOR_NELTS (expr);
7722 if (nelts == 0)
7723 expr = build_value_init (totype, complain);
7724 else if (nelts == 1)
7725 expr = CONSTRUCTOR_ELT (expr, 0)->value;
7726 else
7727 gcc_unreachable ();
7729 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
7730 /*read_p=*/true, UNKNOWN_LOCATION,
7731 /*reject_builtin=*/true);
7733 if (type_unknown_p (expr))
7734 expr = instantiate_type (totype, expr, complain);
7735 if (expr == null_node
7736 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
7737 /* If __null has been converted to an integer type, we do not want to
7738 continue to warn about uses of EXPR as an integer, rather than as a
7739 pointer. */
7740 expr = build_int_cst (totype, 0);
7741 return expr;
7742 case ck_ambig:
7743 /* We leave bad_p off ck_ambig because overload resolution considers
7744 it valid, it just fails when we try to perform it. So we need to
7745 check complain here, too. */
7746 if (complain & tf_error)
7748 /* Call build_user_type_conversion again for the error. */
7749 int flags = (convs->need_temporary_p
7750 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
7751 build_user_type_conversion (totype, convs->u.expr, flags, complain);
7752 gcc_assert (seen_error ());
7753 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7755 return error_mark_node;
7757 case ck_list:
7759 /* Conversion to std::initializer_list<T>. */
7760 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
7761 unsigned len = CONSTRUCTOR_NELTS (expr);
7762 tree array;
7764 if (len)
7766 tree val; unsigned ix;
7768 tree new_ctor = build_constructor (init_list_type_node, NULL);
7770 /* Convert all the elements. */
7771 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
7773 tree sub = convert_like (convs->u.list[ix], val, fn,
7774 argnum, false, false, complain);
7775 if (sub == error_mark_node)
7776 return sub;
7777 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
7778 && !check_narrowing (TREE_TYPE (sub), val, complain))
7779 return error_mark_node;
7780 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
7781 NULL_TREE, sub);
7782 if (!TREE_CONSTANT (sub))
7783 TREE_CONSTANT (new_ctor) = false;
7785 /* Build up the array. */
7786 elttype = cp_build_qualified_type
7787 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
7788 array = build_array_of_n_type (elttype, len);
7789 array = finish_compound_literal (array, new_ctor, complain);
7790 /* Take the address explicitly rather than via decay_conversion
7791 to avoid the error about taking the address of a temporary. */
7792 array = cp_build_addr_expr (array, complain);
7794 else
7795 array = nullptr_node;
7797 array = cp_convert (build_pointer_type (elttype), array, complain);
7798 if (array == error_mark_node)
7799 return error_mark_node;
7801 /* Build up the initializer_list object. Note: fail gracefully
7802 if the object cannot be completed because, for example, no
7803 definition is provided (c++/80956). */
7804 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
7805 if (!totype)
7806 return error_mark_node;
7807 tree field = next_initializable_field (TYPE_FIELDS (totype));
7808 vec<constructor_elt, va_gc> *vec = NULL;
7809 CONSTRUCTOR_APPEND_ELT (vec, field, array);
7810 field = next_initializable_field (DECL_CHAIN (field));
7811 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
7812 tree new_ctor = build_constructor (totype, vec);
7813 return get_target_expr_sfinae (new_ctor, complain);
7816 case ck_aggr:
7817 if (TREE_CODE (totype) == COMPLEX_TYPE)
7819 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
7820 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
7821 real = perform_implicit_conversion (TREE_TYPE (totype),
7822 real, complain);
7823 imag = perform_implicit_conversion (TREE_TYPE (totype),
7824 imag, complain);
7825 expr = build2 (COMPLEX_EXPR, totype, real, imag);
7826 return expr;
7828 expr = reshape_init (totype, expr, complain);
7829 expr = get_target_expr_sfinae (digest_init (totype, expr, complain),
7830 complain);
7831 if (expr != error_mark_node)
7832 TARGET_EXPR_LIST_INIT_P (expr) = true;
7833 return expr;
7835 default:
7836 break;
7839 expr = convert_like (next_conversion (convs), expr, fn, argnum,
7840 convs->kind == ck_ref_bind
7841 ? issue_conversion_warnings : false,
7842 c_cast_p, complain & ~tf_no_cleanup);
7843 if (expr == error_mark_node)
7844 return error_mark_node;
7846 switch (convs->kind)
7848 case ck_rvalue:
7849 expr = decay_conversion (expr, complain);
7850 if (expr == error_mark_node)
7852 if (complain & tf_error)
7854 auto_diagnostic_group d;
7855 maybe_print_user_conv_context (convs);
7856 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7858 return error_mark_node;
7861 if (! MAYBE_CLASS_TYPE_P (totype))
7862 return expr;
7864 /* Don't introduce copies when passing arguments along to the inherited
7865 constructor. */
7866 if (current_function_decl
7867 && flag_new_inheriting_ctors
7868 && DECL_INHERITED_CTOR (current_function_decl))
7869 return expr;
7871 if (TREE_CODE (expr) == TARGET_EXPR
7872 && TARGET_EXPR_LIST_INIT_P (expr))
7873 /* Copy-list-initialization doesn't actually involve a copy. */
7874 return expr;
7876 /* Fall through. */
7877 case ck_base:
7878 if (convs->kind == ck_base && !convs->need_temporary_p)
7880 /* We are going to bind a reference directly to a base-class
7881 subobject of EXPR. */
7882 /* Build an expression for `*((base*) &expr)'. */
7883 expr = convert_to_base (expr, totype,
7884 !c_cast_p, /*nonnull=*/true, complain);
7885 return expr;
7888 /* Copy-initialization where the cv-unqualified version of the source
7889 type is the same class as, or a derived class of, the class of the
7890 destination [is treated as direct-initialization]. [dcl.init] */
7891 flags = LOOKUP_NORMAL;
7892 /* This conversion is being done in the context of a user-defined
7893 conversion (i.e. the second step of copy-initialization), so
7894 don't allow any more. */
7895 if (convs->user_conv_p)
7896 flags |= LOOKUP_NO_CONVERSION;
7897 /* We might be performing a conversion of the argument
7898 to the user-defined conversion, i.e., not a conversion of the
7899 result of the user-defined conversion. In which case we skip
7900 explicit constructors. */
7901 if (convs->copy_init_p)
7902 flags |= LOOKUP_ONLYCONVERTING;
7903 if (convs->rvaluedness_matches_p)
7904 /* standard_conversion got LOOKUP_PREFER_RVALUE. */
7905 flags |= LOOKUP_PREFER_RVALUE;
7906 expr = build_temp (expr, totype, flags, &diag_kind, complain);
7907 if (diag_kind && complain)
7909 auto_diagnostic_group d;
7910 maybe_print_user_conv_context (convs);
7911 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7914 return build_cplus_new (totype, expr, complain);
7916 case ck_ref_bind:
7918 tree ref_type = totype;
7920 /* direct_reference_binding might have inserted a ck_qual under
7921 this ck_ref_bind for the benefit of conversion sequence ranking.
7922 Ignore the conversion; we'll create our own below. */
7923 if (next_conversion (convs)->kind == ck_qual
7924 && !convs->need_temporary_p)
7926 gcc_assert (same_type_p (TREE_TYPE (expr),
7927 next_conversion (convs)->type));
7928 /* Strip the cast created by the ck_qual; cp_build_addr_expr
7929 below expects an lvalue. */
7930 STRIP_NOPS (expr);
7933 if (convs->bad_p && !next_conversion (convs)->bad_p)
7935 tree extype = TREE_TYPE (expr);
7936 auto_diagnostic_group d;
7937 if (TYPE_REF_IS_RVALUE (ref_type)
7938 && lvalue_p (expr))
7939 error_at (loc, "cannot bind rvalue reference of type %qH to "
7940 "lvalue of type %qI", totype, extype);
7941 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
7942 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
7944 conversion *next = next_conversion (convs);
7945 if (next->kind == ck_std)
7947 next = next_conversion (next);
7948 error_at (loc, "cannot bind non-const lvalue reference of "
7949 "type %qH to a value of type %qI",
7950 totype, next->type);
7952 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
7953 error_at (loc, "cannot bind non-const lvalue reference of "
7954 "type %qH to an rvalue of type %qI", totype, extype);
7955 else // extype is volatile
7956 error_at (loc, "cannot bind lvalue reference of type "
7957 "%qH to an rvalue of type %qI", totype,
7958 extype);
7960 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
7962 /* If we're converting from T[] to T[N], don't talk
7963 about discarding qualifiers. (Converting from T[N] to
7964 T[] is allowed by P0388R4.) */
7965 if (TREE_CODE (extype) == ARRAY_TYPE
7966 && TYPE_DOMAIN (extype) == NULL_TREE
7967 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
7968 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
7969 error_at (loc, "cannot bind reference of type %qH to %qI "
7970 "due to different array bounds", totype, extype);
7971 else
7972 error_at (loc, "binding reference of type %qH to %qI "
7973 "discards qualifiers", totype, extype);
7975 else
7976 gcc_unreachable ();
7977 maybe_print_user_conv_context (convs);
7978 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7980 return error_mark_node;
7982 else if (complain & tf_warning)
7983 maybe_warn_array_conv (loc, convs, expr);
7985 /* If necessary, create a temporary.
7987 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
7988 that need temporaries, even when their types are reference
7989 compatible with the type of reference being bound, so the
7990 upcoming call to cp_build_addr_expr doesn't fail. */
7991 if (convs->need_temporary_p
7992 || TREE_CODE (expr) == CONSTRUCTOR
7993 || TREE_CODE (expr) == VA_ARG_EXPR)
7995 /* Otherwise, a temporary of type "cv1 T1" is created and
7996 initialized from the initializer expression using the rules
7997 for a non-reference copy-initialization (8.5). */
7999 tree type = TREE_TYPE (ref_type);
8000 cp_lvalue_kind lvalue = lvalue_kind (expr);
8002 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8003 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8004 && !TYPE_REF_IS_RVALUE (ref_type))
8006 /* If the reference is volatile or non-const, we
8007 cannot create a temporary. */
8008 if (complain & tf_error)
8010 if (lvalue & clk_bitfield)
8011 error_at (loc, "cannot bind bit-field %qE to %qT",
8012 expr, ref_type);
8013 else if (lvalue & clk_packed)
8014 error_at (loc, "cannot bind packed field %qE to %qT",
8015 expr, ref_type);
8016 else
8017 error_at (loc, "cannot bind rvalue %qE to %qT",
8018 expr, ref_type);
8020 return error_mark_node;
8022 /* If the source is a packed field, and we must use a copy
8023 constructor, then building the target expr will require
8024 binding the field to the reference parameter to the
8025 copy constructor, and we'll end up with an infinite
8026 loop. If we can use a bitwise copy, then we'll be
8027 OK. */
8028 if ((lvalue & clk_packed)
8029 && CLASS_TYPE_P (type)
8030 && type_has_nontrivial_copy_init (type))
8032 error_at (loc, "cannot bind packed field %qE to %qT",
8033 expr, ref_type);
8034 return error_mark_node;
8036 if (lvalue & clk_bitfield)
8038 expr = convert_bitfield_to_declared_type (expr);
8039 expr = fold_convert (type, expr);
8042 /* Creating &TARGET_EXPR<> in a template would break when
8043 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8044 instead. This can happen even when there's no class
8045 involved, e.g., when converting an integer to a reference
8046 type. */
8047 if (processing_template_decl)
8048 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8049 expr = build_target_expr_with_type (expr, type, complain);
8052 /* Take the address of the thing to which we will bind the
8053 reference. */
8054 expr = cp_build_addr_expr (expr, complain);
8055 if (expr == error_mark_node)
8056 return error_mark_node;
8058 /* Convert it to a pointer to the type referred to by the
8059 reference. This will adjust the pointer if a derived to
8060 base conversion is being performed. */
8061 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8062 expr, complain);
8063 /* Convert the pointer to the desired reference type. */
8064 return build_nop (ref_type, expr);
8067 case ck_lvalue:
8068 return decay_conversion (expr, complain);
8070 case ck_fnptr:
8071 /* ??? Should the address of a transaction-safe pointer point to the TM
8072 clone, and this conversion look up the primary function? */
8073 return build_nop (totype, expr);
8075 case ck_qual:
8076 /* Warn about deprecated conversion if appropriate. */
8077 if (complain & tf_warning)
8079 string_conv_p (totype, expr, 1);
8080 maybe_warn_array_conv (loc, convs, expr);
8082 break;
8084 case ck_ptr:
8085 if (convs->base_p)
8086 expr = convert_to_base (expr, totype, !c_cast_p,
8087 /*nonnull=*/false, complain);
8088 return build_nop (totype, expr);
8090 case ck_pmem:
8091 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8092 c_cast_p, complain);
8094 default:
8095 break;
8098 if (convs->check_narrowing
8099 && !check_narrowing (totype, expr, complain,
8100 convs->check_narrowing_const_only))
8101 return error_mark_node;
8103 warning_sentinel w (warn_zero_as_null_pointer_constant);
8104 if (issue_conversion_warnings)
8105 expr = cp_convert_and_check (totype, expr, complain);
8106 else
8107 expr = cp_convert (totype, expr, complain);
8109 return expr;
8112 /* Return true if converting FROM to TO is unsafe in a template. */
8114 static bool
8115 conv_unsafe_in_template_p (tree to, tree from)
8117 /* Converting classes involves TARGET_EXPR. */
8118 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8119 return true;
8121 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8122 doesn't handle. */
8123 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8124 return true;
8126 /* Converting integer to real isn't a trivial conversion, either. */
8127 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8128 return true;
8130 return false;
8133 /* Wrapper for convert_like_internal that handles creating
8134 IMPLICIT_CONV_EXPR. */
8136 static tree
8137 convert_like (conversion *convs, tree expr, tree fn, int argnum,
8138 bool issue_conversion_warnings, bool c_cast_p,
8139 tsubst_flags_t complain)
8141 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8142 and creating a CALL_EXPR in a template breaks in finish_call_expr
8143 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
8144 created such codes e.g. when calling a user-defined conversion
8145 function. */
8146 tree conv_expr = NULL_TREE;
8147 if (processing_template_decl
8148 && convs->kind != ck_identity
8149 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
8151 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8152 if (convs->kind != ck_ref_bind)
8153 conv_expr = convert_from_reference (conv_expr);
8154 if (!convs->bad_p)
8155 return conv_expr;
8156 /* Do the normal processing to give the bad_p errors. But we still
8157 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8158 error_mark_node. */
8160 expr = convert_like_internal (convs, expr, fn, argnum,
8161 issue_conversion_warnings, c_cast_p, complain);
8162 if (expr == error_mark_node)
8163 return error_mark_node;
8164 return conv_expr ? conv_expr : expr;
8167 /* Convenience wrapper for convert_like. */
8169 static inline tree
8170 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8172 return convert_like (convs, expr, NULL_TREE, 0,
8173 /*issue_conversion_warnings=*/true,
8174 /*c_cast_p=*/false, complain);
8177 /* Convenience wrapper for convert_like. */
8179 static inline tree
8180 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8181 tsubst_flags_t complain)
8183 return convert_like (convs, expr, fn, argnum,
8184 /*issue_conversion_warnings=*/true,
8185 /*c_cast_p=*/false, complain);
8188 /* ARG is being passed to a varargs function. Perform any conversions
8189 required. Return the converted value. */
8191 tree
8192 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8194 tree arg_type = TREE_TYPE (arg);
8195 location_t loc = cp_expr_loc_or_input_loc (arg);
8197 /* [expr.call]
8199 If the argument has integral or enumeration type that is subject
8200 to the integral promotions (_conv.prom_), or a floating-point
8201 type that is subject to the floating-point promotion
8202 (_conv.fpprom_), the value of the argument is converted to the
8203 promoted type before the call. */
8204 if (TREE_CODE (arg_type) == REAL_TYPE
8205 && (TYPE_PRECISION (arg_type)
8206 < TYPE_PRECISION (double_type_node))
8207 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type)))
8209 if ((complain & tf_warning)
8210 && warn_double_promotion && !c_inhibit_evaluation_warnings)
8211 warning_at (loc, OPT_Wdouble_promotion,
8212 "implicit conversion from %qH to %qI when passing "
8213 "argument to function",
8214 arg_type, double_type_node);
8215 arg = mark_rvalue_use (arg);
8216 arg = convert_to_real_nofold (double_type_node, arg);
8218 else if (NULLPTR_TYPE_P (arg_type))
8220 arg = mark_rvalue_use (arg);
8221 if (TREE_SIDE_EFFECTS (arg))
8223 warning_sentinel w(warn_unused_result);
8224 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
8226 else
8227 arg = null_pointer_node;
8229 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
8231 if (SCOPED_ENUM_P (arg_type))
8233 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
8234 complain);
8235 prom = cp_perform_integral_promotions (prom, complain);
8236 if (abi_version_crosses (6)
8237 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
8238 && (complain & tf_warning))
8239 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
8240 " as %qT before %<-fabi-version=6%>, %qT after",
8241 arg_type,
8242 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
8243 if (!abi_version_at_least (6))
8244 arg = prom;
8246 else
8247 arg = cp_perform_integral_promotions (arg, complain);
8249 else
8250 /* [expr.call]
8252 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
8253 standard conversions are performed. */
8254 arg = decay_conversion (arg, complain);
8256 arg = require_complete_type_sfinae (arg, complain);
8257 arg_type = TREE_TYPE (arg);
8259 if (arg != error_mark_node
8260 /* In a template (or ill-formed code), we can have an incomplete type
8261 even after require_complete_type_sfinae, in which case we don't know
8262 whether it has trivial copy or not. */
8263 && COMPLETE_TYPE_P (arg_type)
8264 && !cp_unevaluated_operand)
8266 /* [expr.call] 5.2.2/7:
8267 Passing a potentially-evaluated argument of class type (Clause 9)
8268 with a non-trivial copy constructor or a non-trivial destructor
8269 with no corresponding parameter is conditionally-supported, with
8270 implementation-defined semantics.
8272 We support it as pass-by-invisible-reference, just like a normal
8273 value parameter.
8275 If the call appears in the context of a sizeof expression,
8276 it is not potentially-evaluated. */
8277 if (type_has_nontrivial_copy_init (arg_type)
8278 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
8280 arg = force_rvalue (arg, complain);
8281 if (complain & tf_warning)
8282 warning (OPT_Wconditionally_supported,
8283 "passing objects of non-trivially-copyable "
8284 "type %q#T through %<...%> is conditionally supported",
8285 arg_type);
8286 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
8288 /* Build up a real lvalue-to-rvalue conversion in case the
8289 copy constructor is trivial but not callable. */
8290 else if (CLASS_TYPE_P (arg_type))
8291 force_rvalue (arg, complain);
8295 return arg;
8298 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
8300 tree
8301 build_x_va_arg (location_t loc, tree expr, tree type)
8303 if (processing_template_decl)
8305 tree r = build_min (VA_ARG_EXPR, type, expr);
8306 SET_EXPR_LOCATION (r, loc);
8307 return r;
8310 type = complete_type_or_else (type, NULL_TREE);
8312 if (expr == error_mark_node || !type)
8313 return error_mark_node;
8315 expr = mark_lvalue_use (expr);
8317 if (TYPE_REF_P (type))
8319 error ("cannot receive reference type %qT through %<...%>", type);
8320 return error_mark_node;
8323 if (type_has_nontrivial_copy_init (type)
8324 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
8326 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
8327 it as pass by invisible reference. */
8328 warning_at (loc, OPT_Wconditionally_supported,
8329 "receiving objects of non-trivially-copyable type %q#T "
8330 "through %<...%> is conditionally-supported", type);
8332 tree ref = cp_build_reference_type (type, false);
8333 expr = build_va_arg (loc, expr, ref);
8334 return convert_from_reference (expr);
8337 tree ret = build_va_arg (loc, expr, type);
8338 if (CLASS_TYPE_P (type))
8339 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
8340 know how to handle it. */
8341 ret = get_target_expr (ret);
8342 return ret;
8345 /* TYPE has been given to va_arg. Apply the default conversions which
8346 would have happened when passed via ellipsis. Return the promoted
8347 type, or the passed type if there is no change. */
8349 tree
8350 cxx_type_promotes_to (tree type)
8352 tree promote;
8354 /* Perform the array-to-pointer and function-to-pointer
8355 conversions. */
8356 type = type_decays_to (type);
8358 promote = type_promotes_to (type);
8359 if (same_type_p (type, promote))
8360 promote = type;
8362 return promote;
8365 /* ARG is a default argument expression being passed to a parameter of
8366 the indicated TYPE, which is a parameter to FN. PARMNUM is the
8367 zero-based argument number. Do any required conversions. Return
8368 the converted value. */
8370 static GTY(()) vec<tree, va_gc> *default_arg_context;
8371 void
8372 push_defarg_context (tree fn)
8373 { vec_safe_push (default_arg_context, fn); }
8375 void
8376 pop_defarg_context (void)
8377 { default_arg_context->pop (); }
8379 tree
8380 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
8381 tsubst_flags_t complain)
8383 int i;
8384 tree t;
8386 /* See through clones. */
8387 fn = DECL_ORIGIN (fn);
8388 /* And inheriting ctors. */
8389 if (flag_new_inheriting_ctors)
8390 fn = strip_inheriting_ctors (fn);
8392 /* Detect recursion. */
8393 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
8394 if (t == fn)
8396 if (complain & tf_error)
8397 error ("recursive evaluation of default argument for %q#D", fn);
8398 return error_mark_node;
8401 /* If the ARG is an unparsed default argument expression, the
8402 conversion cannot be performed. */
8403 if (TREE_CODE (arg) == DEFERRED_PARSE)
8405 if (complain & tf_error)
8406 error ("call to %qD uses the default argument for parameter %P, which "
8407 "is not yet defined", fn, parmnum);
8408 return error_mark_node;
8411 push_defarg_context (fn);
8413 if (fn && DECL_TEMPLATE_INFO (fn))
8414 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
8416 /* Due to:
8418 [dcl.fct.default]
8420 The names in the expression are bound, and the semantic
8421 constraints are checked, at the point where the default
8422 expressions appears.
8424 we must not perform access checks here. */
8425 push_deferring_access_checks (dk_no_check);
8426 /* We must make a copy of ARG, in case subsequent processing
8427 alters any part of it. */
8428 arg = break_out_target_exprs (arg, /*clear location*/true);
8430 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
8431 ICR_DEFAULT_ARGUMENT, fn, parmnum,
8432 complain);
8433 arg = convert_for_arg_passing (type, arg, complain);
8434 pop_deferring_access_checks();
8436 pop_defarg_context ();
8438 return arg;
8441 /* Returns the type which will really be used for passing an argument of
8442 type TYPE. */
8444 tree
8445 type_passed_as (tree type)
8447 /* Pass classes with copy ctors by invisible reference. */
8448 if (TREE_ADDRESSABLE (type))
8449 type = build_reference_type (type);
8450 else if (targetm.calls.promote_prototypes (NULL_TREE)
8451 && INTEGRAL_TYPE_P (type)
8452 && COMPLETE_TYPE_P (type)
8453 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8454 type = integer_type_node;
8456 return type;
8459 /* Actually perform the appropriate conversion. */
8461 tree
8462 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
8464 tree bitfield_type;
8466 /* If VAL is a bitfield, then -- since it has already been converted
8467 to TYPE -- it cannot have a precision greater than TYPE.
8469 If it has a smaller precision, we must widen it here. For
8470 example, passing "int f:3;" to a function expecting an "int" will
8471 not result in any conversion before this point.
8473 If the precision is the same we must not risk widening. For
8474 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
8475 often have type "int", even though the C++ type for the field is
8476 "long long". If the value is being passed to a function
8477 expecting an "int", then no conversions will be required. But,
8478 if we call convert_bitfield_to_declared_type, the bitfield will
8479 be converted to "long long". */
8480 bitfield_type = is_bitfield_expr_with_lowered_type (val);
8481 if (bitfield_type
8482 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
8483 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
8485 if (val == error_mark_node)
8487 /* Pass classes with copy ctors by invisible reference. */
8488 else if (TREE_ADDRESSABLE (type))
8489 val = build1 (ADDR_EXPR, build_reference_type (type), val);
8490 else if (targetm.calls.promote_prototypes (NULL_TREE)
8491 && INTEGRAL_TYPE_P (type)
8492 && COMPLETE_TYPE_P (type)
8493 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8494 val = cp_perform_integral_promotions (val, complain);
8495 if (complain & tf_warning)
8497 if (warn_suggest_attribute_format)
8499 tree rhstype = TREE_TYPE (val);
8500 const enum tree_code coder = TREE_CODE (rhstype);
8501 const enum tree_code codel = TREE_CODE (type);
8502 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
8503 && coder == codel
8504 && check_missing_format_attribute (type, rhstype))
8505 warning (OPT_Wsuggest_attribute_format,
8506 "argument of function call might be a candidate "
8507 "for a format attribute");
8509 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
8512 if (complain & tf_warning)
8513 warn_for_address_or_pointer_of_packed_member (type, val);
8515 return val;
8518 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
8519 which just decay_conversion or no conversions at all should be done.
8520 This is true for some builtins which don't act like normal functions.
8521 Return 2 if no conversions at all should be done, 1 if just
8522 decay_conversion. Return 3 for special treatment of the 3rd argument
8523 for __builtin_*_overflow_p. */
8526 magic_varargs_p (tree fn)
8528 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8529 switch (DECL_FUNCTION_CODE (fn))
8531 case BUILT_IN_CLASSIFY_TYPE:
8532 case BUILT_IN_CONSTANT_P:
8533 case BUILT_IN_NEXT_ARG:
8534 case BUILT_IN_VA_START:
8535 return 1;
8537 case BUILT_IN_ADD_OVERFLOW_P:
8538 case BUILT_IN_SUB_OVERFLOW_P:
8539 case BUILT_IN_MUL_OVERFLOW_P:
8540 return 3;
8542 default:;
8543 return lookup_attribute ("type generic",
8544 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
8547 return 0;
8550 /* Returns the decl of the dispatcher function if FN is a function version. */
8552 tree
8553 get_function_version_dispatcher (tree fn)
8555 tree dispatcher_decl = NULL;
8557 if (DECL_LOCAL_DECL_P (fn))
8558 fn = DECL_LOCAL_DECL_ALIAS (fn);
8560 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
8561 && DECL_FUNCTION_VERSIONED (fn));
8563 gcc_assert (targetm.get_function_versions_dispatcher);
8564 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
8566 if (dispatcher_decl == NULL)
8568 error_at (input_location, "use of multiversioned function "
8569 "without a default");
8570 return NULL;
8573 retrofit_lang_decl (dispatcher_decl);
8574 gcc_assert (dispatcher_decl != NULL);
8575 return dispatcher_decl;
8578 /* fn is a function version dispatcher that is marked used. Mark all the
8579 semantically identical function versions it will dispatch as used. */
8581 void
8582 mark_versions_used (tree fn)
8584 struct cgraph_node *node;
8585 struct cgraph_function_version_info *node_v;
8586 struct cgraph_function_version_info *it_v;
8588 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8590 node = cgraph_node::get (fn);
8591 if (node == NULL)
8592 return;
8594 gcc_assert (node->dispatcher_function);
8596 node_v = node->function_version ();
8597 if (node_v == NULL)
8598 return;
8600 /* All semantically identical versions are chained. Traverse and mark each
8601 one of them as used. */
8602 it_v = node_v->next;
8603 while (it_v != NULL)
8605 mark_used (it_v->this_node->decl);
8606 it_v = it_v->next;
8610 /* Build a call to "the copy constructor" for the type of A, even if it
8611 wouldn't be selected by normal overload resolution. Used for
8612 diagnostics. */
8614 static tree
8615 call_copy_ctor (tree a, tsubst_flags_t complain)
8617 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
8618 tree binfo = TYPE_BINFO (ctype);
8619 tree copy = get_copy_ctor (ctype, complain);
8620 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
8621 tree ob = build_dummy_object (ctype);
8622 releasing_vec args (make_tree_vector_single (a));
8623 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
8624 LOOKUP_NORMAL, NULL, complain);
8625 return r;
8628 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
8630 static tree
8631 base_ctor_for (tree complete_ctor)
8633 tree clone;
8634 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
8635 if (DECL_BASE_CONSTRUCTOR_P (clone))
8636 return clone;
8637 return NULL_TREE;
8640 /* Try to make EXP suitable to be used as the initializer for a base subobject,
8641 and return whether we were successful. EXP must have already been cleared
8642 by unsafe_copy_elision_p{,_opt}. */
8644 static bool
8645 make_base_init_ok (tree exp)
8647 if (TREE_CODE (exp) == TARGET_EXPR)
8648 exp = TARGET_EXPR_INITIAL (exp);
8649 while (TREE_CODE (exp) == COMPOUND_EXPR)
8650 exp = TREE_OPERAND (exp, 1);
8651 if (TREE_CODE (exp) == COND_EXPR)
8653 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
8654 if (tree op1 = TREE_OPERAND (exp, 1))
8656 bool r1 = make_base_init_ok (op1);
8657 /* If unsafe_copy_elision_p was false, the arms should match. */
8658 gcc_assert (r1 == ret);
8660 return ret;
8662 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
8663 /* A trivial copy is OK. */
8664 return true;
8665 if (!AGGR_INIT_VIA_CTOR_P (exp))
8666 /* unsafe_copy_elision_p_opt must have said this is OK. */
8667 return true;
8668 tree fn = cp_get_callee_fndecl_nofold (exp);
8669 if (DECL_BASE_CONSTRUCTOR_P (fn))
8670 return true;
8671 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
8672 fn = base_ctor_for (fn);
8673 if (!fn || DECL_HAS_VTT_PARM_P (fn))
8674 /* The base constructor has more parameters, so we can't just change the
8675 call target. It would be possible to splice in the appropriate
8676 arguments, but probably not worth the complexity. */
8677 return false;
8678 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
8679 return true;
8682 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
8683 neither of which can be used for return by invisible reference. We avoid
8684 doing C++17 mandatory copy elision for either of these cases.
8686 This returns non-zero even if the type of T has no tail padding that other
8687 data could be allocated into, because that depends on the particular ABI.
8688 unsafe_copy_elision_p_opt does consider whether there is padding. */
8691 unsafe_return_slot_p (tree t)
8693 /* Check empty bases separately, they don't have fields. */
8694 if (is_empty_base_ref (t))
8695 return 2;
8697 STRIP_NOPS (t);
8698 if (TREE_CODE (t) == ADDR_EXPR)
8699 t = TREE_OPERAND (t, 0);
8700 if (TREE_CODE (t) == COMPONENT_REF)
8701 t = TREE_OPERAND (t, 1);
8702 if (TREE_CODE (t) != FIELD_DECL)
8703 return false;
8704 if (!CLASS_TYPE_P (TREE_TYPE (t)))
8705 /* The middle-end will do the right thing for scalar types. */
8706 return false;
8707 if (DECL_FIELD_IS_BASE (t))
8708 return 2;
8709 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
8710 return 1;
8711 return 0;
8714 /* True IFF EXP is a prvalue that represents return by invisible reference. */
8716 static bool
8717 init_by_return_slot_p (tree exp)
8719 /* Copy elision only happens with a TARGET_EXPR. */
8720 if (TREE_CODE (exp) != TARGET_EXPR)
8721 return false;
8722 tree init = TARGET_EXPR_INITIAL (exp);
8723 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
8724 while (TREE_CODE (init) == COMPOUND_EXPR)
8725 init = TREE_OPERAND (init, 1);
8726 if (TREE_CODE (init) == COND_EXPR)
8728 /* We'll end up copying from each of the arms of the COND_EXPR directly
8729 into the target, so look at them. */
8730 if (tree op = TREE_OPERAND (init, 1))
8731 if (init_by_return_slot_p (op))
8732 return true;
8733 return init_by_return_slot_p (TREE_OPERAND (init, 2));
8735 return (TREE_CODE (init) == AGGR_INIT_EXPR
8736 && !AGGR_INIT_VIA_CTOR_P (init));
8739 /* We can't elide a copy from a function returning by value to a
8740 potentially-overlapping subobject, as the callee might clobber tail padding.
8741 Return true iff this could be that case.
8743 Places that use this function (or _opt) to decide to elide a copy should
8744 probably use make_safe_copy_elision instead. */
8746 static bool
8747 unsafe_copy_elision_p (tree target, tree exp)
8749 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
8752 /* As above, but for optimization allow more cases that are actually safe. */
8754 static bool
8755 unsafe_copy_elision_p_opt (tree target, tree exp)
8757 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
8758 /* It's safe to elide the copy for a class with no tail padding. */
8759 if (!is_empty_class (type)
8760 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
8761 return false;
8762 return unsafe_copy_elision_p (target, exp);
8765 /* Try to make EXP suitable to be used as the initializer for TARGET,
8766 and return whether we were successful. */
8768 bool
8769 make_safe_copy_elision (tree target, tree exp)
8771 int uns = unsafe_return_slot_p (target);
8772 if (!uns)
8773 return true;
8774 if (init_by_return_slot_p (exp))
8775 return false;
8776 if (uns == 1)
8777 return true;
8778 return make_base_init_ok (exp);
8781 /* True IFF the result of the conversion C is a prvalue. */
8783 static bool
8784 conv_is_prvalue (conversion *c)
8786 if (c->kind == ck_rvalue)
8787 return true;
8788 if (c->kind == ck_base && c->need_temporary_p)
8789 return true;
8790 if (c->kind == ck_user && !TYPE_REF_P (c->type))
8791 return true;
8792 if (c->kind == ck_identity && c->u.expr
8793 && TREE_CODE (c->u.expr) == TARGET_EXPR)
8794 return true;
8796 return false;
8799 /* True iff C is a conversion that binds a reference to a prvalue. */
8801 static bool
8802 conv_binds_ref_to_prvalue (conversion *c)
8804 if (c->kind != ck_ref_bind)
8805 return false;
8806 if (c->need_temporary_p)
8807 return true;
8809 return conv_is_prvalue (next_conversion (c));
8812 /* True iff converting EXPR to a reference type TYPE does not involve
8813 creating a temporary. */
8815 bool
8816 ref_conv_binds_directly_p (tree type, tree expr)
8818 gcc_assert (TYPE_REF_P (type));
8820 /* Get the high-water mark for the CONVERSION_OBSTACK. */
8821 void *p = conversion_obstack_alloc (0);
8823 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
8824 /*c_cast_p=*/false,
8825 LOOKUP_IMPLICIT, tf_none);
8826 bool ret = conv && !conv->bad_p && !conv_binds_ref_to_prvalue (conv);
8828 /* Free all the conversions we allocated. */
8829 obstack_free (&conversion_obstack, p);
8831 return ret;
8834 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
8835 class type or a pointer to class type. If NO_PTR_DEREF is true and
8836 INSTANCE has pointer type, clobber the pointer rather than what it points
8837 to. */
8839 tree
8840 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
8842 gcc_assert (!is_dummy_object (instance));
8844 if (!flag_lifetime_dse)
8846 no_clobber:
8847 return fold_convert (void_type_node, instance);
8850 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
8851 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
8853 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
8854 goto no_clobber;
8855 instance = cp_build_fold_indirect_ref (instance);
8858 /* A trivial destructor should still clobber the object. */
8859 tree clobber = build_clobber (TREE_TYPE (instance));
8860 return build2 (MODIFY_EXPR, void_type_node,
8861 instance, clobber);
8864 /* Return true if a call to FN with number of arguments NARGS
8865 is an immediate invocation. */
8867 static bool
8868 immediate_invocation_p (tree fn, int nargs)
8870 return (TREE_CODE (fn) == FUNCTION_DECL
8871 && DECL_IMMEDIATE_FUNCTION_P (fn)
8872 && cp_unevaluated_operand == 0
8873 && (current_function_decl == NULL_TREE
8874 || !DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
8875 && (current_binding_level->kind != sk_function_parms
8876 || !current_binding_level->immediate_fn_ctx_p)
8877 && !in_consteval_if_p
8878 /* As an exception, we defer std::source_location::current ()
8879 invocations until genericization because LWG3396 mandates
8880 special behavior for it. */
8881 && (nargs > 1 || !source_location_current_p (fn)));
8884 /* Subroutine of the various build_*_call functions. Overload resolution
8885 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
8886 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
8887 bitmask of various LOOKUP_* flags which apply to the call itself. */
8889 static tree
8890 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
8892 tree fn = cand->fn;
8893 const vec<tree, va_gc> *args = cand->args;
8894 tree first_arg = cand->first_arg;
8895 conversion **convs = cand->convs;
8896 conversion *conv;
8897 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
8898 int parmlen;
8899 tree val;
8900 int i = 0;
8901 int j = 0;
8902 unsigned int arg_index = 0;
8903 int is_method = 0;
8904 int nargs;
8905 tree *argarray;
8906 bool already_used = false;
8908 /* In a template, there is no need to perform all of the work that
8909 is normally done. We are only interested in the type of the call
8910 expression, i.e., the return type of the function. Any semantic
8911 errors will be deferred until the template is instantiated. */
8912 if (processing_template_decl)
8914 tree expr, addr;
8915 tree return_type;
8916 const tree *argarray;
8917 unsigned int nargs;
8919 if (undeduced_auto_decl (fn))
8920 mark_used (fn, complain);
8921 else
8922 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
8923 See PR80598. */
8924 TREE_USED (fn) = 1;
8926 return_type = TREE_TYPE (TREE_TYPE (fn));
8927 nargs = vec_safe_length (args);
8928 if (first_arg == NULL_TREE)
8929 argarray = args->address ();
8930 else
8932 tree *alcarray;
8933 unsigned int ix;
8934 tree arg;
8936 ++nargs;
8937 alcarray = XALLOCAVEC (tree, nargs);
8938 alcarray[0] = build_this (first_arg);
8939 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
8940 alcarray[ix + 1] = arg;
8941 argarray = alcarray;
8944 addr = build_addr_func (fn, complain);
8945 if (addr == error_mark_node)
8946 return error_mark_node;
8947 expr = build_call_array_loc (input_location, return_type,
8948 addr, nargs, argarray);
8949 if (TREE_THIS_VOLATILE (fn) && cfun)
8950 current_function_returns_abnormally = 1;
8951 if (immediate_invocation_p (fn, nargs))
8953 tree obj_arg = NULL_TREE, exprimm = expr;
8954 if (DECL_CONSTRUCTOR_P (fn))
8955 obj_arg = first_arg;
8956 if (obj_arg
8957 && is_dummy_object (obj_arg)
8958 && !type_dependent_expression_p (obj_arg))
8960 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
8961 obj_arg = NULL_TREE;
8963 /* Look through *(const T *)&obj. */
8964 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
8966 tree addr = TREE_OPERAND (obj_arg, 0);
8967 STRIP_NOPS (addr);
8968 if (TREE_CODE (addr) == ADDR_EXPR)
8970 tree typeo = TREE_TYPE (obj_arg);
8971 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
8972 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
8973 obj_arg = TREE_OPERAND (addr, 0);
8976 fold_non_dependent_expr (exprimm, complain,
8977 /*manifestly_const_eval=*/true,
8978 obj_arg);
8980 return convert_from_reference (expr);
8983 /* Give any warnings we noticed during overload resolution. */
8984 if (cand->warnings && (complain & tf_warning))
8986 struct candidate_warning *w;
8987 for (w = cand->warnings; w; w = w->next)
8988 joust (cand, w->loser, 1, complain);
8991 /* Core issue 2327: P0135 doesn't say how to handle the case where the
8992 argument to the copy constructor ends up being a prvalue after
8993 conversion. Let's do the normal processing, but pretend we aren't
8994 actually using the copy constructor. */
8995 bool force_elide = false;
8996 if (cxx_dialect >= cxx17
8997 && cand->num_convs == 1
8998 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
8999 && (DECL_COPY_CONSTRUCTOR_P (fn)
9000 || DECL_MOVE_CONSTRUCTOR_P (fn))
9001 && !unsafe_return_slot_p (first_arg)
9002 && conv_binds_ref_to_prvalue (convs[0]))
9004 force_elide = true;
9005 goto not_really_used;
9008 /* OK, we're actually calling this inherited constructor; set its deletedness
9009 appropriately. We can get away with doing this here because calling is
9010 the only way to refer to a constructor. */
9011 if (DECL_INHERITED_CTOR (fn)
9012 && !deduce_inheriting_ctor (fn))
9014 if (complain & tf_error)
9015 mark_used (fn);
9016 return error_mark_node;
9019 /* Make =delete work with SFINAE. */
9020 if (DECL_DELETED_FN (fn))
9022 if (complain & tf_error)
9023 mark_used (fn);
9024 return error_mark_node;
9027 if (DECL_FUNCTION_MEMBER_P (fn))
9029 tree access_fn;
9030 /* If FN is a template function, two cases must be considered.
9031 For example:
9033 struct A {
9034 protected:
9035 template <class T> void f();
9037 template <class T> struct B {
9038 protected:
9039 void g();
9041 struct C : A, B<int> {
9042 using A::f; // #1
9043 using B<int>::g; // #2
9046 In case #1 where `A::f' is a member template, DECL_ACCESS is
9047 recorded in the primary template but not in its specialization.
9048 We check access of FN using its primary template.
9050 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9051 because it is a member of class template B, DECL_ACCESS is
9052 recorded in the specialization `B<int>::g'. We cannot use its
9053 primary template because `B<T>::g' and `B<int>::g' may have
9054 different access. */
9055 if (DECL_TEMPLATE_INFO (fn)
9056 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9057 access_fn = DECL_TI_TEMPLATE (fn);
9058 else
9059 access_fn = fn;
9060 if (!perform_or_defer_access_check (cand->access_path, access_fn,
9061 fn, complain))
9062 return error_mark_node;
9065 /* If we're checking for implicit delete, don't bother with argument
9066 conversions. */
9067 if (flags & LOOKUP_SPECULATIVE)
9069 if (cand->viable == 1)
9070 return fn;
9071 else if (!(complain & tf_error))
9072 /* Reject bad conversions now. */
9073 return error_mark_node;
9074 /* else continue to get conversion error. */
9077 not_really_used:
9079 /* N3276 magic doesn't apply to nested calls. */
9080 tsubst_flags_t decltype_flag = (complain & tf_decltype);
9081 complain &= ~tf_decltype;
9082 /* No-Cleanup doesn't apply to nested calls either. */
9083 tsubst_flags_t no_cleanup_complain = complain;
9084 complain &= ~tf_no_cleanup;
9086 /* Find maximum size of vector to hold converted arguments. */
9087 parmlen = list_length (parm);
9088 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
9089 if (parmlen > nargs)
9090 nargs = parmlen;
9091 argarray = XALLOCAVEC (tree, nargs);
9093 /* The implicit parameters to a constructor are not considered by overload
9094 resolution, and must be of the proper type. */
9095 if (DECL_CONSTRUCTOR_P (fn))
9097 tree object_arg;
9098 if (first_arg != NULL_TREE)
9100 object_arg = first_arg;
9101 first_arg = NULL_TREE;
9103 else
9105 object_arg = (*args)[arg_index];
9106 ++arg_index;
9108 argarray[j++] = build_this (object_arg);
9109 parm = TREE_CHAIN (parm);
9110 /* We should never try to call the abstract constructor. */
9111 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9113 if (DECL_HAS_VTT_PARM_P (fn))
9115 argarray[j++] = (*args)[arg_index];
9116 ++arg_index;
9117 parm = TREE_CHAIN (parm);
9120 if (cxx_dialect < cxx20
9121 && (cand->flags & LOOKUP_PREFER_RVALUE))
9123 /* The implicit move specified in 15.8.3/3 fails "...if the type of
9124 the first parameter of the selected constructor is not an rvalue
9125 reference to the object's type (possibly cv-qualified)...." */
9126 gcc_assert (!(complain & tf_error));
9127 tree ptype = convs[0]->type;
9128 /* Allow calling a by-value converting constructor even though it
9129 isn't permitted by the above, because we've allowed it since GCC 5
9130 (PR58051) and it's allowed in C++20. But don't call a copy
9131 constructor. */
9132 if ((TYPE_REF_P (ptype) && !TYPE_REF_IS_RVALUE (ptype))
9133 || CONVERSION_RANK (convs[0]) > cr_exact)
9134 return error_mark_node;
9137 /* Bypass access control for 'this' parameter. */
9138 else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9140 tree arg = build_this (first_arg != NULL_TREE
9141 ? first_arg
9142 : (*args)[arg_index]);
9143 tree argtype = TREE_TYPE (arg);
9145 if (arg == error_mark_node)
9146 return error_mark_node;
9148 if (convs[i]->bad_p)
9150 if (complain & tf_error)
9152 auto_diagnostic_group d;
9153 if (permerror (input_location, "passing %qT as %<this%> "
9154 "argument discards qualifiers",
9155 TREE_TYPE (argtype)))
9156 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
9158 else
9159 return error_mark_node;
9162 /* The class where FN is defined. */
9163 tree ctx = DECL_CONTEXT (fn);
9165 /* See if the function member or the whole class type is declared
9166 final and the call can be devirtualized. */
9167 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9168 flags |= LOOKUP_NONVIRTUAL;
9170 /* [class.mfct.non-static]: If a non-static member function of a class
9171 X is called for an object that is not of type X, or of a type
9172 derived from X, the behavior is undefined.
9174 So we can assume that anything passed as 'this' is non-null, and
9175 optimize accordingly. */
9176 /* Check that the base class is accessible. */
9177 if (!accessible_base_p (TREE_TYPE (argtype),
9178 BINFO_TYPE (cand->conversion_path), true))
9180 if (complain & tf_error)
9181 error ("%qT is not an accessible base of %qT",
9182 BINFO_TYPE (cand->conversion_path),
9183 TREE_TYPE (argtype));
9184 else
9185 return error_mark_node;
9187 /* If fn was found by a using declaration, the conversion path
9188 will be to the derived class, not the base declaring fn. We
9189 must convert to the base. */
9190 tree base_binfo = cand->conversion_path;
9191 if (BINFO_TYPE (base_binfo) != ctx)
9193 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
9194 if (base_binfo == error_mark_node)
9195 return error_mark_node;
9198 /* If we know the dynamic type of the object, look up the final overrider
9199 in the BINFO. */
9200 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
9201 && resolves_to_fixed_type_p (arg))
9203 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
9205 /* And unwind base_binfo to match. If we don't find the type we're
9206 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
9207 inheritance; for now do a normal virtual call in that case. */
9208 tree octx = DECL_CONTEXT (ov);
9209 tree obinfo = base_binfo;
9210 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
9211 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
9212 if (obinfo)
9214 fn = ov;
9215 base_binfo = obinfo;
9216 flags |= LOOKUP_NONVIRTUAL;
9220 tree converted_arg = build_base_path (PLUS_EXPR, arg,
9221 base_binfo, 1, complain);
9223 argarray[j++] = converted_arg;
9224 parm = TREE_CHAIN (parm);
9225 if (first_arg != NULL_TREE)
9226 first_arg = NULL_TREE;
9227 else
9228 ++arg_index;
9229 ++i;
9230 is_method = 1;
9233 gcc_assert (first_arg == NULL_TREE);
9234 for (; arg_index < vec_safe_length (args) && parm;
9235 parm = TREE_CHAIN (parm), ++arg_index, ++i)
9237 tree type = TREE_VALUE (parm);
9238 tree arg = (*args)[arg_index];
9239 bool conversion_warning = true;
9241 conv = convs[i];
9243 /* If the argument is NULL and used to (implicitly) instantiate a
9244 template function (and bind one of the template arguments to
9245 the type of 'long int'), we don't want to warn about passing NULL
9246 to non-pointer argument.
9247 For example, if we have this template function:
9249 template<typename T> void func(T x) {}
9251 we want to warn (when -Wconversion is enabled) in this case:
9253 void foo() {
9254 func<int>(NULL);
9257 but not in this case:
9259 void foo() {
9260 func(NULL);
9263 if (null_node_p (arg)
9264 && DECL_TEMPLATE_INFO (fn)
9265 && cand->template_decl
9266 && !cand->explicit_targs)
9267 conversion_warning = false;
9269 /* Set user_conv_p on the argument conversions, so rvalue/base handling
9270 knows not to allow any more UDCs. This needs to happen after we
9271 process cand->warnings. */
9272 if (flags & LOOKUP_NO_CONVERSION)
9273 conv->user_conv_p = true;
9275 tsubst_flags_t arg_complain = complain;
9276 if (!conversion_warning)
9277 arg_complain &= ~tf_warning;
9279 val = convert_like_with_context (conv, arg, fn, i - is_method,
9280 arg_complain);
9281 val = convert_for_arg_passing (type, val, arg_complain);
9283 if (val == error_mark_node)
9284 return error_mark_node;
9285 else
9286 argarray[j++] = val;
9289 /* Default arguments */
9290 for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
9292 if (TREE_VALUE (parm) == error_mark_node)
9293 return error_mark_node;
9294 val = convert_default_arg (TREE_VALUE (parm),
9295 TREE_PURPOSE (parm),
9296 fn, i - is_method,
9297 complain);
9298 if (val == error_mark_node)
9299 return error_mark_node;
9300 argarray[j++] = val;
9303 /* Ellipsis */
9304 int magic = magic_varargs_p (fn);
9305 for (; arg_index < vec_safe_length (args); ++arg_index)
9307 tree a = (*args)[arg_index];
9308 if ((magic == 3 && arg_index == 2) || magic == 2)
9310 /* Do no conversions for certain magic varargs. */
9311 a = mark_type_use (a);
9312 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
9313 return error_mark_node;
9315 else if (magic != 0)
9316 /* For other magic varargs only do decay_conversion. */
9317 a = decay_conversion (a, complain);
9318 else if (DECL_CONSTRUCTOR_P (fn)
9319 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
9320 TREE_TYPE (a)))
9322 /* Avoid infinite recursion trying to call A(...). */
9323 if (complain & tf_error)
9324 /* Try to call the actual copy constructor for a good error. */
9325 call_copy_ctor (a, complain);
9326 return error_mark_node;
9328 else
9329 a = convert_arg_to_ellipsis (a, complain);
9330 if (a == error_mark_node)
9331 return error_mark_node;
9332 argarray[j++] = a;
9335 gcc_assert (j <= nargs);
9336 nargs = j;
9338 /* Avoid performing argument transformation if warnings are disabled.
9339 When tf_warning is set and at least one of the warnings is active
9340 the check_function_arguments function might warn about something. */
9342 bool warned_p = false;
9343 if ((complain & tf_warning)
9344 && (warn_nonnull
9345 || warn_format
9346 || warn_suggest_attribute_format
9347 || warn_restrict))
9349 tree *fargs = (!nargs ? argarray
9350 : (tree *) alloca (nargs * sizeof (tree)));
9351 for (j = 0; j < nargs; j++)
9353 /* For -Wformat undo the implicit passing by hidden reference
9354 done by convert_arg_to_ellipsis. */
9355 if (TREE_CODE (argarray[j]) == ADDR_EXPR
9356 && TYPE_REF_P (TREE_TYPE (argarray[j])))
9357 fargs[j] = TREE_OPERAND (argarray[j], 0);
9358 else
9359 fargs[j] = argarray[j];
9362 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
9363 nargs, fargs, NULL);
9366 if (DECL_INHERITED_CTOR (fn))
9368 /* Check for passing ellipsis arguments to an inherited constructor. We
9369 could handle this by open-coding the inherited constructor rather than
9370 defining it, but let's not bother now. */
9371 if (!cp_unevaluated_operand
9372 && cand->num_convs
9373 && cand->convs[cand->num_convs-1]->ellipsis_p)
9375 if (complain & tf_error)
9377 sorry ("passing arguments to ellipsis of inherited constructor "
9378 "%qD", cand->fn);
9379 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
9381 return error_mark_node;
9384 /* A base constructor inheriting from a virtual base doesn't get the
9385 inherited arguments, just this and __vtt. */
9386 if (ctor_omit_inherited_parms (fn))
9387 nargs = 2;
9390 /* Avoid actually calling copy constructors and copy assignment operators,
9391 if possible. */
9393 if (! flag_elide_constructors && !force_elide)
9394 /* Do things the hard way. */;
9395 else if (cand->num_convs == 1
9396 && (DECL_COPY_CONSTRUCTOR_P (fn)
9397 || DECL_MOVE_CONSTRUCTOR_P (fn))
9398 /* It's unsafe to elide the constructor when handling
9399 a noexcept-expression, it may evaluate to the wrong
9400 value (c++/53025). */
9401 && (force_elide || cp_noexcept_operand == 0))
9403 tree targ;
9404 tree arg = argarray[num_artificial_parms_for (fn)];
9405 tree fa = argarray[0];
9406 bool trivial = trivial_fn_p (fn);
9408 /* Pull out the real argument, disregarding const-correctness. */
9409 targ = arg;
9410 /* Strip the reference binding for the constructor parameter. */
9411 if (CONVERT_EXPR_P (targ)
9412 && TYPE_REF_P (TREE_TYPE (targ)))
9413 targ = TREE_OPERAND (targ, 0);
9414 /* But don't strip any other reference bindings; binding a temporary to a
9415 reference prevents copy elision. */
9416 while ((CONVERT_EXPR_P (targ)
9417 && !TYPE_REF_P (TREE_TYPE (targ)))
9418 || TREE_CODE (targ) == NON_LVALUE_EXPR)
9419 targ = TREE_OPERAND (targ, 0);
9420 if (TREE_CODE (targ) == ADDR_EXPR)
9422 targ = TREE_OPERAND (targ, 0);
9423 if (!same_type_ignoring_top_level_qualifiers_p
9424 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
9425 targ = NULL_TREE;
9427 else
9428 targ = NULL_TREE;
9430 if (targ)
9431 arg = targ;
9432 else
9433 arg = cp_build_fold_indirect_ref (arg);
9435 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
9436 potentially-overlapping subobject. */
9437 if (CHECKING_P && cxx_dialect >= cxx17)
9438 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
9439 || force_elide
9440 /* It's from binding the ref parm to a packed field. */
9441 || convs[0]->need_temporary_p
9442 || seen_error ()
9443 /* See unsafe_copy_elision_p. */
9444 || unsafe_return_slot_p (fa));
9446 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
9447 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
9449 /* [class.copy]: the copy constructor is implicitly defined even if the
9450 implementation elided its use. But don't warn about deprecation when
9451 eliding a temporary, as then no copy is actually performed. */
9452 warning_sentinel s (warn_deprecated_copy, eliding_temp);
9453 if (force_elide)
9454 /* The language says this isn't called. */;
9455 else if (!trivial)
9457 if (!mark_used (fn, complain) && !(complain & tf_error))
9458 return error_mark_node;
9459 already_used = true;
9461 else
9462 cp_warn_deprecated_use (fn, complain);
9464 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
9465 && !make_base_init_ok (arg))
9466 unsafe = true;
9468 /* If we're creating a temp and we already have one, don't create a
9469 new one. If we're not creating a temp but we get one, use
9470 INIT_EXPR to collapse the temp into our target. Otherwise, if the
9471 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
9472 temp or an INIT_EXPR otherwise. */
9473 if (is_dummy_object (fa))
9475 if (TREE_CODE (arg) == TARGET_EXPR)
9476 return arg;
9477 else if (trivial)
9478 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
9480 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
9481 && !unsafe)
9483 tree to = cp_build_fold_indirect_ref (fa);
9484 val = build2 (INIT_EXPR, DECL_CONTEXT (fn), to, arg);
9485 return val;
9488 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
9489 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
9490 && trivial_fn_p (fn))
9492 tree to = cp_build_fold_indirect_ref (argarray[0]);
9493 tree type = TREE_TYPE (to);
9494 tree as_base = CLASSTYPE_AS_BASE (type);
9495 tree arg = argarray[1];
9496 location_t loc = cp_expr_loc_or_input_loc (arg);
9498 if (is_really_empty_class (type, /*ignore_vptr*/true))
9500 /* Avoid copying empty classes. */
9501 val = build2 (COMPOUND_EXPR, type, arg, to);
9502 suppress_warning (val, OPT_Wunused);
9504 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
9506 if (is_std_init_list (type)
9507 && conv_binds_ref_to_prvalue (convs[1]))
9508 warning_at (loc, OPT_Winit_list_lifetime,
9509 "assignment from temporary %<initializer_list%> does "
9510 "not extend the lifetime of the underlying array");
9511 arg = cp_build_fold_indirect_ref (arg);
9512 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
9514 else
9516 /* We must only copy the non-tail padding parts. */
9517 tree arg0, arg2, t;
9518 tree array_type, alias_set;
9520 arg2 = TYPE_SIZE_UNIT (as_base);
9521 to = cp_stabilize_reference (to);
9522 arg0 = cp_build_addr_expr (to, complain);
9524 array_type = build_array_type (unsigned_char_type_node,
9525 build_index_type
9526 (size_binop (MINUS_EXPR,
9527 arg2, size_int (1))));
9528 alias_set = build_int_cst (build_pointer_type (type), 0);
9529 t = build2 (MODIFY_EXPR, void_type_node,
9530 build2 (MEM_REF, array_type, arg0, alias_set),
9531 build2 (MEM_REF, array_type, arg, alias_set));
9532 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
9533 suppress_warning (val, OPT_Wunused);
9536 cp_warn_deprecated_use (fn, complain);
9538 return val;
9540 else if (trivial_fn_p (fn))
9542 if (DECL_DESTRUCTOR_P (fn))
9543 return build_trivial_dtor_call (argarray[0]);
9544 else if (default_ctor_p (fn))
9546 if (is_dummy_object (argarray[0]))
9547 return force_target_expr (DECL_CONTEXT (fn), void_node,
9548 no_cleanup_complain);
9549 else
9550 return cp_build_fold_indirect_ref (argarray[0]);
9554 gcc_assert (!force_elide);
9556 if (!already_used
9557 && !mark_used (fn, complain))
9558 return error_mark_node;
9560 /* Warn if the built-in writes to an object of a non-trivial type. */
9561 if (warn_class_memaccess
9562 && vec_safe_length (args) >= 2
9563 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9564 maybe_warn_class_memaccess (input_location, fn, args);
9566 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
9568 tree t;
9569 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
9570 DECL_CONTEXT (fn),
9571 ba_any, NULL, complain);
9572 gcc_assert (binfo && binfo != error_mark_node);
9574 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
9575 complain);
9576 if (TREE_SIDE_EFFECTS (argarray[0]))
9577 argarray[0] = save_expr (argarray[0]);
9578 t = build_pointer_type (TREE_TYPE (fn));
9579 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
9580 TREE_TYPE (fn) = t;
9582 else
9584 /* If FN is marked deprecated, then we've already issued a deprecated-use
9585 warning from mark_used above, so avoid redundantly issuing another one
9586 from build_addr_func. */
9587 warning_sentinel w (warn_deprecated_decl);
9589 fn = build_addr_func (fn, complain);
9590 if (fn == error_mark_node)
9591 return error_mark_node;
9594 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
9595 if (call == error_mark_node)
9596 return call;
9597 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
9599 tree c = extract_call_expr (call);
9600 /* build_new_op_1 will clear this when appropriate. */
9601 CALL_EXPR_ORDERED_ARGS (c) = true;
9603 if (warned_p)
9605 tree c = extract_call_expr (call);
9606 if (TREE_CODE (c) == CALL_EXPR)
9607 suppress_warning (c /* Suppress all warnings. */);
9609 if (TREE_CODE (fn) == ADDR_EXPR)
9611 tree fndecl = STRIP_TEMPLATE (TREE_OPERAND (fn, 0));
9612 if (immediate_invocation_p (fndecl, nargs))
9614 tree obj_arg = NULL_TREE;
9615 /* Undo convert_from_reference called by build_cxx_call. */
9616 if (REFERENCE_REF_P (call))
9617 call = TREE_OPERAND (call, 0);
9618 if (DECL_CONSTRUCTOR_P (fndecl))
9619 obj_arg = cand->first_arg ? cand->first_arg : (*args)[0];
9620 if (obj_arg && is_dummy_object (obj_arg))
9622 call = build_cplus_new (DECL_CONTEXT (fndecl), call, complain);
9623 obj_arg = NULL_TREE;
9625 /* Look through *(const T *)&obj. */
9626 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9628 tree addr = TREE_OPERAND (obj_arg, 0);
9629 STRIP_NOPS (addr);
9630 if (TREE_CODE (addr) == ADDR_EXPR)
9632 tree typeo = TREE_TYPE (obj_arg);
9633 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9634 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9635 obj_arg = TREE_OPERAND (addr, 0);
9638 call = cxx_constant_value (call, obj_arg);
9639 if (obj_arg && !error_operand_p (call))
9640 call = build2 (INIT_EXPR, void_type_node, obj_arg, call);
9641 call = convert_from_reference (call);
9644 return call;
9647 namespace
9650 /* Return the DECL of the first non-static subobject of class TYPE
9651 that satisfies the predicate PRED or null if none can be found. */
9653 template <class Predicate>
9654 tree
9655 first_non_static_field (tree type, Predicate pred)
9657 if (!type || !CLASS_TYPE_P (type))
9658 return NULL_TREE;
9660 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9662 if (TREE_CODE (field) != FIELD_DECL)
9663 continue;
9664 if (TREE_STATIC (field))
9665 continue;
9666 if (pred (field))
9667 return field;
9670 int i = 0;
9672 for (tree base_binfo, binfo = TYPE_BINFO (type);
9673 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
9675 tree base = TREE_TYPE (base_binfo);
9676 if (pred (base))
9677 return base;
9678 if (tree field = first_non_static_field (base, pred))
9679 return field;
9682 return NULL_TREE;
9685 struct NonPublicField
9687 bool operator() (const_tree t) const
9689 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
9693 /* Return the DECL of the first non-public subobject of class TYPE
9694 or null if none can be found. */
9696 static inline tree
9697 first_non_public_field (tree type)
9699 return first_non_static_field (type, NonPublicField ());
9702 struct NonTrivialField
9704 bool operator() (const_tree t) const
9706 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
9710 /* Return the DECL of the first non-trivial subobject of class TYPE
9711 or null if none can be found. */
9713 static inline tree
9714 first_non_trivial_field (tree type)
9716 return first_non_static_field (type, NonTrivialField ());
9719 } /* unnamed namespace */
9721 /* Return true if all copy and move assignment operator overloads for
9722 class TYPE are trivial and at least one of them is not deleted and,
9723 when ACCESS is set, accessible. Return false otherwise. Set
9724 HASASSIGN to true when the TYPE has a (not necessarily trivial)
9725 copy or move assignment. */
9727 static bool
9728 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
9730 tree fns = get_class_binding (type, assign_op_identifier);
9731 bool all_trivial = true;
9733 /* Iterate over overloads of the assignment operator, checking
9734 accessible copy assignments for triviality. */
9736 for (tree f : ovl_range (fns))
9738 /* Skip operators that aren't copy assignments. */
9739 if (!copy_fn_p (f))
9740 continue;
9742 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
9743 || accessible_p (TYPE_BINFO (type), f, true));
9745 /* Skip template assignment operators and deleted functions. */
9746 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
9747 continue;
9749 if (accessible)
9750 *hasassign = true;
9752 if (!accessible || !trivial_fn_p (f))
9753 all_trivial = false;
9755 /* Break early when both properties have been determined. */
9756 if (*hasassign && !all_trivial)
9757 break;
9760 /* Return true if they're all trivial and one of the expressions
9761 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
9762 tree ref = cp_build_reference_type (type, false);
9763 return (all_trivial
9764 && (is_trivially_xible (MODIFY_EXPR, type, type)
9765 || is_trivially_xible (MODIFY_EXPR, type, ref)));
9768 /* Return true if all copy and move ctor overloads for class TYPE are
9769 trivial and at least one of them is not deleted and, when ACCESS is
9770 set, accessible. Return false otherwise. Set each element of HASCTOR[]
9771 to true when the TYPE has a (not necessarily trivial) default and copy
9772 (or move) ctor, respectively. */
9774 static bool
9775 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
9777 tree fns = get_class_binding (type, complete_ctor_identifier);
9778 bool all_trivial = true;
9780 for (tree f : ovl_range (fns))
9782 /* Skip template constructors. */
9783 if (TREE_CODE (f) != FUNCTION_DECL)
9784 continue;
9786 bool cpy_or_move_ctor_p = copy_fn_p (f);
9788 /* Skip ctors other than default, copy, and move. */
9789 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
9790 continue;
9792 if (DECL_DELETED_FN (f))
9793 continue;
9795 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
9796 || accessible_p (TYPE_BINFO (type), f, true));
9798 if (accessible)
9799 hasctor[cpy_or_move_ctor_p] = true;
9801 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
9802 all_trivial = false;
9804 /* Break early when both properties have been determined. */
9805 if (hasctor[0] && hasctor[1] && !all_trivial)
9806 break;
9809 return all_trivial;
9812 /* Issue a warning on a call to the built-in function FNDECL if it is
9813 a raw memory write whose destination is not an object of (something
9814 like) trivial or standard layout type with a non-deleted assignment
9815 and copy ctor. Detects const correctness violations, corrupting
9816 references, virtual table pointers, and bypassing non-trivial
9817 assignments. */
9819 static void
9820 maybe_warn_class_memaccess (location_t loc, tree fndecl,
9821 const vec<tree, va_gc> *args)
9823 /* Except for bcopy where it's second, the destination pointer is
9824 the first argument for all functions handled here. Compute
9825 the index of the destination and source arguments. */
9826 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
9827 unsigned srcidx = !dstidx;
9829 tree dest = (*args)[dstidx];
9830 if (!TREE_TYPE (dest)
9831 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
9832 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
9833 return;
9835 tree srctype = NULL_TREE;
9837 /* Determine the type of the pointed-to object and whether it's
9838 a complete class type. */
9839 tree desttype = TREE_TYPE (TREE_TYPE (dest));
9841 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
9842 return;
9844 /* Check to see if the raw memory call is made by a non-static member
9845 function with THIS as the destination argument for the destination
9846 type. If so, and if the class has no non-trivial bases or members,
9847 be more permissive. */
9848 if (current_function_decl
9849 && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
9850 && is_this_parameter (tree_strip_nop_conversions (dest)))
9852 tree ctx = DECL_CONTEXT (current_function_decl);
9853 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
9854 tree binfo = TYPE_BINFO (ctx);
9856 if (special
9857 && !BINFO_VTABLE (binfo)
9858 && !first_non_trivial_field (desttype))
9859 return;
9862 /* True if the class is trivial. */
9863 bool trivial = trivial_type_p (desttype);
9865 /* Set to true if DESTYPE has an accessible copy assignment. */
9866 bool hasassign = false;
9867 /* True if all of the class' overloaded copy assignment operators
9868 are all trivial (and not deleted) and at least one of them is
9869 accessible. */
9870 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
9872 /* Set to true if DESTTYPE has an accessible default and copy ctor,
9873 respectively. */
9874 bool hasctors[2] = { false, false };
9876 /* True if all of the class' overloaded copy constructors are all
9877 trivial (and not deleted) and at least one of them is accessible. */
9878 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
9880 /* Set FLD to the first private/protected member of the class. */
9881 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
9883 /* The warning format string. */
9884 const char *warnfmt = NULL;
9885 /* A suggested alternative to offer instead of the raw memory call.
9886 Empty string when none can be come up with. */
9887 const char *suggest = "";
9888 bool warned = false;
9890 switch (DECL_FUNCTION_CODE (fndecl))
9892 case BUILT_IN_MEMSET:
9893 if (!integer_zerop (maybe_constant_value ((*args)[1])))
9895 /* Diagnose setting non-copy-assignable or non-trivial types,
9896 or types with a private member, to (potentially) non-zero
9897 bytes. Since the value of the bytes being written is unknown,
9898 suggest using assignment instead (if one exists). Also warn
9899 for writes into objects for which zero-initialization doesn't
9900 mean all bits clear (pointer-to-member data, where null is all
9901 bits set). Since the value being written is (most likely)
9902 non-zero, simply suggest assignment (but not copy assignment). */
9903 suggest = "; use assignment instead";
9904 if (!trivassign)
9905 warnfmt = G_("%qD writing to an object of type %#qT with "
9906 "no trivial copy-assignment");
9907 else if (!trivial)
9908 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
9909 else if (fld)
9911 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
9912 warned = warning_at (loc, OPT_Wclass_memaccess,
9913 "%qD writing to an object of type %#qT with "
9914 "%qs member %qD",
9915 fndecl, desttype, access, fld);
9917 else if (!zero_init_p (desttype))
9918 warnfmt = G_("%qD writing to an object of type %#qT containing "
9919 "a pointer to data member%s");
9921 break;
9923 /* Fall through. */
9925 case BUILT_IN_BZERO:
9926 /* Similarly to the above, diagnose clearing non-trivial or non-
9927 standard layout objects, or objects of types with no assignmenmt.
9928 Since the value being written is known to be zero, suggest either
9929 copy assignment, copy ctor, or default ctor as an alternative,
9930 depending on what's available. */
9932 if (hasassign && hasctors[0])
9933 suggest = G_("; use assignment or value-initialization instead");
9934 else if (hasassign)
9935 suggest = G_("; use assignment instead");
9936 else if (hasctors[0])
9937 suggest = G_("; use value-initialization instead");
9939 if (!trivassign)
9940 warnfmt = G_("%qD clearing an object of type %#qT with "
9941 "no trivial copy-assignment%s");
9942 else if (!trivial)
9943 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
9944 else if (!zero_init_p (desttype))
9945 warnfmt = G_("%qD clearing an object of type %#qT containing "
9946 "a pointer-to-member%s");
9947 break;
9949 case BUILT_IN_BCOPY:
9950 case BUILT_IN_MEMCPY:
9951 case BUILT_IN_MEMMOVE:
9952 case BUILT_IN_MEMPCPY:
9953 /* Determine the type of the source object. */
9954 srctype = TREE_TYPE ((*args)[srcidx]);
9955 if (!srctype || !INDIRECT_TYPE_P (srctype))
9956 srctype = void_type_node;
9957 else
9958 srctype = TREE_TYPE (srctype);
9960 /* Since it's impossible to determine wheter the byte copy is
9961 being used in place of assignment to an existing object or
9962 as a substitute for initialization, assume it's the former.
9963 Determine the best alternative to use instead depending on
9964 what's not deleted. */
9965 if (hasassign && hasctors[1])
9966 suggest = G_("; use copy-assignment or copy-initialization instead");
9967 else if (hasassign)
9968 suggest = G_("; use copy-assignment instead");
9969 else if (hasctors[1])
9970 suggest = G_("; use copy-initialization instead");
9972 if (!trivassign)
9973 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
9974 "copy-assignment%s");
9975 else if (!trivially_copyable_p (desttype))
9976 warnfmt = G_("%qD writing to an object of non-trivially copyable "
9977 "type %#qT%s");
9978 else if (!trivcopy)
9979 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
9981 else if (!trivial
9982 && !VOID_TYPE_P (srctype)
9983 && !is_byte_access_type (srctype)
9984 && !same_type_ignoring_top_level_qualifiers_p (desttype,
9985 srctype))
9987 /* Warn when copying into a non-trivial object from an object
9988 of a different type other than void or char. */
9989 warned = warning_at (loc, OPT_Wclass_memaccess,
9990 "%qD copying an object of non-trivial type "
9991 "%#qT from an array of %#qT",
9992 fndecl, desttype, srctype);
9994 else if (fld
9995 && !VOID_TYPE_P (srctype)
9996 && !is_byte_access_type (srctype)
9997 && !same_type_ignoring_top_level_qualifiers_p (desttype,
9998 srctype))
10000 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10001 warned = warning_at (loc, OPT_Wclass_memaccess,
10002 "%qD copying an object of type %#qT with "
10003 "%qs member %qD from an array of %#qT; use "
10004 "assignment or copy-initialization instead",
10005 fndecl, desttype, access, fld, srctype);
10007 else if (!trivial && vec_safe_length (args) > 2)
10009 tree sz = maybe_constant_value ((*args)[2]);
10010 if (!tree_fits_uhwi_p (sz))
10011 break;
10013 /* Finally, warn on partial copies. */
10014 unsigned HOST_WIDE_INT typesize
10015 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10016 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10017 warned = warning_at (loc, OPT_Wclass_memaccess,
10018 (typesize - partial > 1
10019 ? G_("%qD writing to an object of "
10020 "a non-trivial type %#qT leaves %wu "
10021 "bytes unchanged")
10022 : G_("%qD writing to an object of "
10023 "a non-trivial type %#qT leaves %wu "
10024 "byte unchanged")),
10025 fndecl, desttype, typesize - partial);
10027 break;
10029 case BUILT_IN_REALLOC:
10031 if (!trivially_copyable_p (desttype))
10032 warnfmt = G_("%qD moving an object of non-trivially copyable type "
10033 "%#qT; use %<new%> and %<delete%> instead");
10034 else if (!trivcopy)
10035 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10036 "constructor; use %<new%> and %<delete%> instead");
10037 else if (!get_dtor (desttype, tf_none))
10038 warnfmt = G_("%qD moving an object of type %#qT with deleted "
10039 "destructor");
10040 else if (!trivial)
10042 tree sz = maybe_constant_value ((*args)[1]);
10043 if (TREE_CODE (sz) == INTEGER_CST
10044 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10045 /* Finally, warn on reallocation into insufficient space. */
10046 warned = warning_at (loc, OPT_Wclass_memaccess,
10047 "%qD moving an object of non-trivial type "
10048 "%#qT and size %E into a region of size %E",
10049 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10050 sz);
10052 break;
10054 default:
10055 return;
10058 if (warnfmt)
10060 if (suggest)
10061 warned = warning_at (loc, OPT_Wclass_memaccess,
10062 warnfmt, fndecl, desttype, suggest);
10063 else
10064 warned = warning_at (loc, OPT_Wclass_memaccess,
10065 warnfmt, fndecl, desttype);
10068 if (warned)
10069 inform (location_of (desttype), "%#qT declared here", desttype);
10072 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10073 If FN is the result of resolving an overloaded target built-in,
10074 ORIG_FNDECL is the original function decl, otherwise it is null.
10075 This function performs no overload resolution, conversion, or other
10076 high-level operations. */
10078 tree
10079 build_cxx_call (tree fn, int nargs, tree *argarray,
10080 tsubst_flags_t complain, tree orig_fndecl)
10082 tree fndecl;
10084 /* Remember roughly where this call is. */
10085 location_t loc = cp_expr_loc_or_input_loc (fn);
10086 fn = build_call_a (fn, nargs, argarray);
10087 SET_EXPR_LOCATION (fn, loc);
10089 fndecl = get_callee_fndecl (fn);
10090 if (!orig_fndecl)
10091 orig_fndecl = fndecl;
10093 /* Check that arguments to builtin functions match the expectations. */
10094 if (fndecl
10095 && !processing_template_decl
10096 && fndecl_built_in_p (fndecl))
10098 int i;
10100 /* We need to take care that values to BUILT_IN_NORMAL
10101 are reduced. */
10102 for (i = 0; i < nargs; i++)
10103 argarray[i] = maybe_constant_value (argarray[i]);
10105 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10106 orig_fndecl, nargs, argarray))
10107 return error_mark_node;
10110 if (VOID_TYPE_P (TREE_TYPE (fn)))
10111 return fn;
10113 /* 5.2.2/11: If a function call is a prvalue of object type: if the
10114 function call is either the operand of a decltype-specifier or the
10115 right operand of a comma operator that is the operand of a
10116 decltype-specifier, a temporary object is not introduced for the
10117 prvalue. The type of the prvalue may be incomplete. */
10118 if (!(complain & tf_decltype))
10120 fn = require_complete_type_sfinae (fn, complain);
10121 if (fn == error_mark_node)
10122 return error_mark_node;
10124 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10126 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10127 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10130 return convert_from_reference (fn);
10133 /* Returns the value to use for the in-charge parameter when making a
10134 call to a function with the indicated NAME.
10136 FIXME:Can't we find a neater way to do this mapping? */
10138 tree
10139 in_charge_arg_for_name (tree name)
10141 if (IDENTIFIER_CTOR_P (name))
10143 if (name == complete_ctor_identifier)
10144 return integer_one_node;
10145 gcc_checking_assert (name == base_ctor_identifier);
10147 else
10149 if (name == complete_dtor_identifier)
10150 return integer_two_node;
10151 else if (name == deleting_dtor_identifier)
10152 return integer_three_node;
10153 gcc_checking_assert (name == base_dtor_identifier);
10156 return integer_zero_node;
10159 /* We've built up a constructor call RET. Complain if it delegates to the
10160 constructor we're currently compiling. */
10162 static void
10163 check_self_delegation (tree ret)
10165 if (TREE_CODE (ret) == TARGET_EXPR)
10166 ret = TARGET_EXPR_INITIAL (ret);
10167 tree fn = cp_get_callee_fndecl_nofold (ret);
10168 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
10169 error ("constructor delegates to itself");
10172 /* Build a call to a constructor, destructor, or an assignment
10173 operator for INSTANCE, an expression with class type. NAME
10174 indicates the special member function to call; *ARGS are the
10175 arguments. ARGS may be NULL. This may change ARGS. BINFO
10176 indicates the base of INSTANCE that is to be passed as the `this'
10177 parameter to the member function called.
10179 FLAGS are the LOOKUP_* flags to use when processing the call.
10181 If NAME indicates a complete object constructor, INSTANCE may be
10182 NULL_TREE. In this case, the caller will call build_cplus_new to
10183 store the newly constructed object into a VAR_DECL. */
10185 tree
10186 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
10187 tree binfo, int flags, tsubst_flags_t complain)
10189 tree fns;
10190 /* The type of the subobject to be constructed or destroyed. */
10191 tree class_type;
10192 vec<tree, va_gc> *allocated = NULL;
10193 tree ret;
10195 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
10197 if (error_operand_p (instance))
10198 return error_mark_node;
10200 if (IDENTIFIER_DTOR_P (name))
10202 gcc_assert (args == NULL || vec_safe_is_empty (*args));
10203 if (!type_build_dtor_call (TREE_TYPE (instance)))
10204 /* Shortcut to avoid lazy destructor declaration. */
10205 return build_trivial_dtor_call (instance);
10208 if (TYPE_P (binfo))
10210 /* Resolve the name. */
10211 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
10212 return error_mark_node;
10214 binfo = TYPE_BINFO (binfo);
10217 gcc_assert (binfo != NULL_TREE);
10219 class_type = BINFO_TYPE (binfo);
10221 /* Handle the special case where INSTANCE is NULL_TREE. */
10222 if (name == complete_ctor_identifier && !instance)
10223 instance = build_dummy_object (class_type);
10224 else
10226 /* Convert to the base class, if necessary. */
10227 if (!same_type_ignoring_top_level_qualifiers_p
10228 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
10230 if (IDENTIFIER_CDTOR_P (name))
10231 /* For constructors and destructors, either the base is
10232 non-virtual, or it is virtual but we are doing the
10233 conversion from a constructor or destructor for the
10234 complete object. In either case, we can convert
10235 statically. */
10236 instance = convert_to_base_statically (instance, binfo);
10237 else
10239 /* However, for assignment operators, we must convert
10240 dynamically if the base is virtual. */
10241 gcc_checking_assert (name == assign_op_identifier);
10242 instance = build_base_path (PLUS_EXPR, instance,
10243 binfo, /*nonnull=*/1, complain);
10248 gcc_assert (instance != NULL_TREE);
10250 /* In C++17, "If the initializer expression is a prvalue and the
10251 cv-unqualified version of the source type is the same class as the class
10252 of the destination, the initializer expression is used to initialize the
10253 destination object." Handle that here to avoid doing overload
10254 resolution. */
10255 if (cxx_dialect >= cxx17
10256 && args && vec_safe_length (*args) == 1
10257 && !unsafe_return_slot_p (instance))
10259 tree arg = (**args)[0];
10261 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
10262 && !TYPE_HAS_LIST_CTOR (class_type)
10263 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
10264 && CONSTRUCTOR_NELTS (arg) == 1)
10265 arg = CONSTRUCTOR_ELT (arg, 0)->value;
10267 if ((TREE_CODE (arg) == TARGET_EXPR
10268 || TREE_CODE (arg) == CONSTRUCTOR)
10269 && (same_type_ignoring_top_level_qualifiers_p
10270 (class_type, TREE_TYPE (arg))))
10272 if (is_dummy_object (instance))
10273 return arg;
10274 else if (TREE_CODE (arg) == TARGET_EXPR)
10275 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
10277 if ((complain & tf_error)
10278 && (flags & LOOKUP_DELEGATING_CONS))
10279 check_self_delegation (arg);
10280 /* Avoid change of behavior on Wunused-var-2.C. */
10281 instance = mark_lvalue_use (instance);
10282 return build2 (INIT_EXPR, class_type, instance, arg);
10286 fns = lookup_fnfields (binfo, name, 1, complain);
10288 /* When making a call to a constructor or destructor for a subobject
10289 that uses virtual base classes, pass down a pointer to a VTT for
10290 the subobject. */
10291 if ((name == base_ctor_identifier
10292 || name == base_dtor_identifier)
10293 && CLASSTYPE_VBASECLASSES (class_type))
10295 tree vtt;
10296 tree sub_vtt;
10298 /* If the current function is a complete object constructor
10299 or destructor, then we fetch the VTT directly.
10300 Otherwise, we look it up using the VTT we were given. */
10301 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
10302 vtt = decay_conversion (vtt, complain);
10303 if (vtt == error_mark_node)
10304 return error_mark_node;
10305 vtt = build_if_in_charge (vtt, current_vtt_parm);
10306 if (BINFO_SUBVTT_INDEX (binfo))
10307 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
10308 else
10309 sub_vtt = vtt;
10311 if (args == NULL)
10313 allocated = make_tree_vector ();
10314 args = &allocated;
10317 vec_safe_insert (*args, 0, sub_vtt);
10320 ret = build_new_method_call (instance, fns, args,
10321 TYPE_BINFO (BINFO_TYPE (binfo)),
10322 flags, /*fn=*/NULL,
10323 complain);
10325 if (allocated != NULL)
10326 release_tree_vector (allocated);
10328 if ((complain & tf_error)
10329 && (flags & LOOKUP_DELEGATING_CONS)
10330 && name == complete_ctor_identifier)
10331 check_self_delegation (ret);
10333 return ret;
10336 /* Return the NAME, as a C string. The NAME indicates a function that
10337 is a member of TYPE. *FREE_P is set to true if the caller must
10338 free the memory returned.
10340 Rather than go through all of this, we should simply set the names
10341 of constructors and destructors appropriately, and dispense with
10342 ctor_identifier, dtor_identifier, etc. */
10344 static char *
10345 name_as_c_string (tree name, tree type, bool *free_p)
10347 const char *pretty_name;
10349 /* Assume that we will not allocate memory. */
10350 *free_p = false;
10351 /* Constructors and destructors are special. */
10352 if (IDENTIFIER_CDTOR_P (name))
10354 pretty_name
10355 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
10356 /* For a destructor, add the '~'. */
10357 if (IDENTIFIER_DTOR_P (name))
10359 pretty_name = concat ("~", pretty_name, NULL);
10360 /* Remember that we need to free the memory allocated. */
10361 *free_p = true;
10364 else if (IDENTIFIER_CONV_OP_P (name))
10366 pretty_name = concat ("operator ",
10367 type_as_string_translate (TREE_TYPE (name),
10368 TFF_PLAIN_IDENTIFIER),
10369 NULL);
10370 /* Remember that we need to free the memory allocated. */
10371 *free_p = true;
10373 else
10374 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
10376 return CONST_CAST (char *, pretty_name);
10379 /* If CANDIDATES contains exactly one candidate, return it, otherwise
10380 return NULL. */
10382 static z_candidate *
10383 single_z_candidate (z_candidate *candidates)
10385 if (candidates == NULL)
10386 return NULL;
10388 if (candidates->next)
10389 return NULL;
10391 return candidates;
10394 /* If CANDIDATE is invalid due to a bad argument type, return the
10395 pertinent conversion_info.
10397 Otherwise, return NULL. */
10399 static const conversion_info *
10400 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
10402 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
10403 rejection_reason *r = candidate->reason;
10405 if (r == NULL)
10406 return NULL;
10408 switch (r->code)
10410 default:
10411 return NULL;
10413 case rr_arg_conversion:
10414 return &r->u.conversion;
10416 case rr_bad_arg_conversion:
10417 return &r->u.bad_conversion;
10421 /* Issue an error and note complaining about a bad argument type at a
10422 callsite with a single candidate FNDECL.
10424 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
10425 case input_location is used).
10426 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
10427 the formal parameter. */
10429 void
10430 complain_about_bad_argument (location_t arg_loc,
10431 tree from_type, tree to_type,
10432 tree fndecl, int parmnum)
10434 auto_diagnostic_group d;
10435 range_label_for_type_mismatch rhs_label (from_type, to_type);
10436 range_label *label = &rhs_label;
10437 if (arg_loc == UNKNOWN_LOCATION)
10439 arg_loc = input_location;
10440 label = NULL;
10442 gcc_rich_location richloc (arg_loc, label);
10443 error_at (&richloc,
10444 "cannot convert %qH to %qI",
10445 from_type, to_type);
10446 maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
10447 parmnum);
10450 /* Subroutine of build_new_method_call_1, for where there are no viable
10451 candidates for the call. */
10453 static void
10454 complain_about_no_candidates_for_method_call (tree instance,
10455 z_candidate *candidates,
10456 tree explicit_targs,
10457 tree basetype,
10458 tree optype, tree name,
10459 bool skip_first_for_error,
10460 vec<tree, va_gc> *user_args)
10462 auto_diagnostic_group d;
10463 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
10464 cxx_incomplete_type_error (instance, basetype);
10465 else if (optype)
10466 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
10467 basetype, optype, build_tree_list_vec (user_args),
10468 TREE_TYPE (instance));
10469 else
10471 /* Special-case for when there's a single candidate that's failing
10472 due to a bad argument type. */
10473 if (z_candidate *candidate = single_z_candidate (candidates))
10474 if (const conversion_info *conv
10475 = maybe_get_bad_conversion_for_unmatched_call (candidate))
10477 tree from_type = conv->from;
10478 if (!TYPE_P (conv->from))
10479 from_type = lvalue_type (conv->from);
10480 complain_about_bad_argument (conv->loc,
10481 from_type, conv->to_type,
10482 candidate->fn, conv->n_arg);
10483 return;
10486 tree arglist = build_tree_list_vec (user_args);
10487 tree errname = name;
10488 bool twiddle = false;
10489 if (IDENTIFIER_CDTOR_P (errname))
10491 twiddle = IDENTIFIER_DTOR_P (errname);
10492 errname = constructor_name (basetype);
10494 if (explicit_targs)
10495 errname = lookup_template_function (errname, explicit_targs);
10496 if (skip_first_for_error)
10497 arglist = TREE_CHAIN (arglist);
10498 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
10499 basetype, &"~"[!twiddle], errname, arglist,
10500 TREE_TYPE (instance));
10502 print_z_candidates (location_of (name), candidates);
10505 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
10506 be set, upon return, to the function called. ARGS may be NULL.
10507 This may change ARGS. */
10509 static tree
10510 build_new_method_call_1 (tree instance, tree fns, vec<tree, va_gc> **args,
10511 tree conversion_path, int flags,
10512 tree *fn_p, tsubst_flags_t complain)
10514 struct z_candidate *candidates = 0, *cand;
10515 tree explicit_targs = NULL_TREE;
10516 tree basetype = NULL_TREE;
10517 tree access_binfo;
10518 tree optype;
10519 tree first_mem_arg = NULL_TREE;
10520 tree name;
10521 bool skip_first_for_error;
10522 vec<tree, va_gc> *user_args;
10523 tree call;
10524 tree fn;
10525 int template_only = 0;
10526 bool any_viable_p;
10527 tree orig_instance;
10528 tree orig_fns;
10529 vec<tree, va_gc> *orig_args = NULL;
10530 void *p;
10532 gcc_assert (instance != NULL_TREE);
10534 /* We don't know what function we're going to call, yet. */
10535 if (fn_p)
10536 *fn_p = NULL_TREE;
10538 if (error_operand_p (instance)
10539 || !fns || error_operand_p (fns))
10540 return error_mark_node;
10542 if (!BASELINK_P (fns))
10544 if (complain & tf_error)
10545 error ("call to non-function %qD", fns);
10546 return error_mark_node;
10549 orig_instance = instance;
10550 orig_fns = fns;
10552 /* Dismantle the baselink to collect all the information we need. */
10553 if (!conversion_path)
10554 conversion_path = BASELINK_BINFO (fns);
10555 access_binfo = BASELINK_ACCESS_BINFO (fns);
10556 optype = BASELINK_OPTYPE (fns);
10557 fns = BASELINK_FUNCTIONS (fns);
10558 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10560 explicit_targs = TREE_OPERAND (fns, 1);
10561 fns = TREE_OPERAND (fns, 0);
10562 template_only = 1;
10564 gcc_assert (OVL_P (fns));
10565 fn = OVL_FIRST (fns);
10566 name = DECL_NAME (fn);
10568 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
10569 gcc_assert (CLASS_TYPE_P (basetype));
10571 user_args = args == NULL ? NULL : *args;
10572 /* Under DR 147 A::A() is an invalid constructor call,
10573 not a functional cast. */
10574 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
10576 if (! (complain & tf_error))
10577 return error_mark_node;
10579 basetype = DECL_CONTEXT (fn);
10580 name = constructor_name (basetype);
10581 auto_diagnostic_group d;
10582 if (permerror (input_location,
10583 "cannot call constructor %<%T::%D%> directly",
10584 basetype, name))
10585 inform (input_location, "for a function-style cast, remove the "
10586 "redundant %<::%D%>", name);
10587 call = build_functional_cast (input_location, basetype,
10588 build_tree_list_vec (user_args),
10589 complain);
10590 return call;
10593 if (processing_template_decl)
10595 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
10596 instance = build_non_dependent_expr (instance);
10597 if (args != NULL)
10598 make_args_non_dependent (*args);
10601 /* Process the argument list. */
10602 if (args != NULL && *args != NULL)
10604 *args = resolve_args (*args, complain);
10605 if (*args == NULL)
10606 return error_mark_node;
10607 user_args = *args;
10610 /* Consider the object argument to be used even if we end up selecting a
10611 static member function. */
10612 instance = mark_type_use (instance);
10614 /* Figure out whether to skip the first argument for the error
10615 message we will display to users if an error occurs. We don't
10616 want to display any compiler-generated arguments. The "this"
10617 pointer hasn't been added yet. However, we must remove the VTT
10618 pointer if this is a call to a base-class constructor or
10619 destructor. */
10620 skip_first_for_error = false;
10621 if (IDENTIFIER_CDTOR_P (name))
10623 /* Callers should explicitly indicate whether they want to ctor
10624 the complete object or just the part without virtual bases. */
10625 gcc_assert (name != ctor_identifier);
10627 /* Remove the VTT pointer, if present. */
10628 if ((name == base_ctor_identifier || name == base_dtor_identifier)
10629 && CLASSTYPE_VBASECLASSES (basetype))
10630 skip_first_for_error = true;
10632 /* It's OK to call destructors and constructors on cv-qualified
10633 objects. Therefore, convert the INSTANCE to the unqualified
10634 type, if necessary. */
10635 if (!same_type_p (basetype, TREE_TYPE (instance)))
10637 instance = build_this (instance);
10638 instance = build_nop (build_pointer_type (basetype), instance);
10639 instance = build_fold_indirect_ref (instance);
10642 else
10643 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
10645 /* For the overload resolution we need to find the actual `this`
10646 that would be captured if the call turns out to be to a
10647 non-static member function. Do not actually capture it at this
10648 point. */
10649 if (DECL_CONSTRUCTOR_P (fn))
10650 /* Constructors don't use the enclosing 'this'. */
10651 first_mem_arg = instance;
10652 else
10653 first_mem_arg = maybe_resolve_dummy (instance, false);
10655 /* Get the high-water mark for the CONVERSION_OBSTACK. */
10656 p = conversion_obstack_alloc (0);
10658 /* The number of arguments artificial parms in ARGS; we subtract one because
10659 there's no 'this' in ARGS. */
10660 unsigned skip = num_artificial_parms_for (fn) - 1;
10662 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
10663 initializer, not T({ }). */
10664 if (DECL_CONSTRUCTOR_P (fn)
10665 && vec_safe_length (user_args) > skip
10666 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
10668 tree init_list = (*user_args)[skip];
10669 tree init = NULL_TREE;
10671 gcc_assert (user_args->length () == skip + 1
10672 && !(flags & LOOKUP_ONLYCONVERTING));
10674 /* If the initializer list has no elements and T is a class type with
10675 a default constructor, the object is value-initialized. Handle
10676 this here so we don't need to handle it wherever we use
10677 build_special_member_call. */
10678 if (CONSTRUCTOR_NELTS (init_list) == 0
10679 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
10680 /* For a user-provided default constructor, use the normal
10681 mechanisms so that protected access works. */
10682 && type_has_non_user_provided_default_constructor (basetype)
10683 && !processing_template_decl)
10684 init = build_value_init (basetype, complain);
10686 /* If BASETYPE is an aggregate, we need to do aggregate
10687 initialization. */
10688 else if (CP_AGGREGATE_TYPE_P (basetype))
10690 init = reshape_init (basetype, init_list, complain);
10691 init = digest_init (basetype, init, complain);
10694 if (init)
10696 if (is_dummy_object (instance))
10697 return get_target_expr_sfinae (init, complain);
10698 init = build2 (INIT_EXPR, TREE_TYPE (instance), instance, init);
10699 TREE_SIDE_EFFECTS (init) = true;
10700 return init;
10703 /* Otherwise go ahead with overload resolution. */
10704 add_list_candidates (fns, first_mem_arg, user_args,
10705 basetype, explicit_targs, template_only,
10706 conversion_path, access_binfo, flags,
10707 &candidates, complain);
10709 else
10710 add_candidates (fns, first_mem_arg, user_args, optype,
10711 explicit_targs, template_only, conversion_path,
10712 access_binfo, flags, &candidates, complain);
10714 any_viable_p = false;
10715 candidates = splice_viable (candidates, false, &any_viable_p);
10717 if (!any_viable_p)
10719 /* [dcl.init], 17.6.2.2:
10721 Otherwise, if no constructor is viable, the destination type is
10722 a (possibly cv-qualified) aggregate class A, and the initializer
10723 is a parenthesized expression-list, the object is initialized as
10724 follows...
10726 We achieve this by building up a CONSTRUCTOR, as for list-init,
10727 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
10728 the two. */
10729 if (DECL_CONSTRUCTOR_P (fn)
10730 && !(flags & LOOKUP_ONLYCONVERTING)
10731 && cxx_dialect >= cxx20
10732 && CP_AGGREGATE_TYPE_P (basetype)
10733 && !vec_safe_is_empty (user_args))
10735 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
10736 tree ctor = build_constructor_from_vec (init_list_type_node,
10737 user_args);
10738 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
10739 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
10740 if (is_dummy_object (instance))
10741 return ctor;
10742 else
10744 ctor = digest_init (basetype, ctor, complain);
10745 if (ctor == error_mark_node)
10746 return error_mark_node;
10747 ctor = build2 (INIT_EXPR, TREE_TYPE (instance), instance, ctor);
10748 TREE_SIDE_EFFECTS (ctor) = true;
10749 return ctor;
10752 if (complain & tf_error)
10753 complain_about_no_candidates_for_method_call (instance, candidates,
10754 explicit_targs, basetype,
10755 optype, name,
10756 skip_first_for_error,
10757 user_args);
10758 call = error_mark_node;
10760 else
10762 cand = tourney (candidates, complain);
10763 if (cand == 0)
10765 char *pretty_name;
10766 bool free_p;
10767 tree arglist;
10769 if (complain & tf_error)
10771 pretty_name = name_as_c_string (name, basetype, &free_p);
10772 arglist = build_tree_list_vec (user_args);
10773 if (skip_first_for_error)
10774 arglist = TREE_CHAIN (arglist);
10775 auto_diagnostic_group d;
10776 if (!any_strictly_viable (candidates))
10777 error ("no matching function for call to %<%s(%A)%>",
10778 pretty_name, arglist);
10779 else
10780 error ("call of overloaded %<%s(%A)%> is ambiguous",
10781 pretty_name, arglist);
10782 print_z_candidates (location_of (name), candidates);
10783 if (free_p)
10784 free (pretty_name);
10786 call = error_mark_node;
10787 if (fn_p)
10788 *fn_p = error_mark_node;
10790 else
10792 fn = cand->fn;
10793 call = NULL_TREE;
10795 if (!(flags & LOOKUP_NONVIRTUAL)
10796 && DECL_PURE_VIRTUAL_P (fn)
10797 && instance == current_class_ref
10798 && (complain & tf_warning))
10800 /* This is not an error, it is runtime undefined
10801 behavior. */
10802 if (!current_function_decl)
10803 warning (0, "pure virtual %q#D called from "
10804 "non-static data member initializer", fn);
10805 else if (DECL_CONSTRUCTOR_P (current_function_decl)
10806 || DECL_DESTRUCTOR_P (current_function_decl))
10807 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
10808 ? G_("pure virtual %q#D called from constructor")
10809 : G_("pure virtual %q#D called from destructor")),
10810 fn);
10813 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
10814 && !DECL_CONSTRUCTOR_P (fn)
10815 && is_dummy_object (instance))
10817 instance = maybe_resolve_dummy (instance, true);
10818 if (instance == error_mark_node)
10819 call = error_mark_node;
10820 else if (!is_dummy_object (instance))
10822 /* We captured 'this' in the current lambda now that
10823 we know we really need it. */
10824 cand->first_arg = instance;
10826 else if (any_dependent_bases_p ())
10827 /* We can't tell until instantiation time whether we can use
10828 *this as the implicit object argument. */;
10829 else
10831 if (complain & tf_error)
10832 error ("cannot call member function %qD without object",
10833 fn);
10834 call = error_mark_node;
10838 if (call != error_mark_node)
10840 /* Now we know what function is being called. */
10841 if (fn_p)
10842 *fn_p = fn;
10843 /* Build the actual CALL_EXPR. */
10844 call = build_over_call (cand, flags, complain);
10845 /* In an expression of the form `a->f()' where `f' turns
10846 out to be a static member function, `a' is
10847 none-the-less evaluated. */
10848 if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
10849 && !is_dummy_object (instance)
10850 && TREE_SIDE_EFFECTS (instance))
10852 /* But avoid the implicit lvalue-rvalue conversion when 'a'
10853 is volatile. */
10854 tree a = instance;
10855 if (TREE_THIS_VOLATILE (a))
10856 a = build_this (a);
10857 if (TREE_SIDE_EFFECTS (a))
10858 call = build2 (COMPOUND_EXPR, TREE_TYPE (call), a, call);
10860 else if (call != error_mark_node
10861 && DECL_DESTRUCTOR_P (cand->fn)
10862 && !VOID_TYPE_P (TREE_TYPE (call)))
10863 /* An explicit call of the form "x->~X()" has type
10864 "void". However, on platforms where destructors
10865 return "this" (i.e., those where
10866 targetm.cxx.cdtor_returns_this is true), such calls
10867 will appear to have a return value of pointer type
10868 to the low-level call machinery. We do not want to
10869 change the low-level machinery, since we want to be
10870 able to optimize "delete f()" on such platforms as
10871 "operator delete(~X(f()))" (rather than generating
10872 "t = f(), ~X(t), operator delete (t)"). */
10873 call = build_nop (void_type_node, call);
10878 if (processing_template_decl && call != error_mark_node)
10880 bool cast_to_void = false;
10882 if (TREE_CODE (call) == COMPOUND_EXPR)
10883 call = TREE_OPERAND (call, 1);
10884 else if (TREE_CODE (call) == NOP_EXPR)
10886 cast_to_void = true;
10887 call = TREE_OPERAND (call, 0);
10889 if (INDIRECT_REF_P (call))
10890 call = TREE_OPERAND (call, 0);
10891 call = (build_min_non_dep_call_vec
10892 (call,
10893 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
10894 orig_instance, orig_fns, NULL_TREE),
10895 orig_args));
10896 SET_EXPR_LOCATION (call, input_location);
10897 call = convert_from_reference (call);
10898 if (cast_to_void)
10899 call = build_nop (void_type_node, call);
10902 /* Free all the conversions we allocated. */
10903 obstack_free (&conversion_obstack, p);
10905 if (orig_args != NULL)
10906 release_tree_vector (orig_args);
10908 return call;
10911 /* Wrapper for above. */
10913 tree
10914 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
10915 tree conversion_path, int flags,
10916 tree *fn_p, tsubst_flags_t complain)
10918 tree ret;
10919 bool subtime = timevar_cond_start (TV_OVERLOAD);
10920 ret = build_new_method_call_1 (instance, fns, args, conversion_path, flags,
10921 fn_p, complain);
10922 timevar_cond_stop (TV_OVERLOAD, subtime);
10923 return ret;
10926 /* Returns true iff standard conversion sequence ICS1 is a proper
10927 subsequence of ICS2. */
10929 static bool
10930 is_subseq (conversion *ics1, conversion *ics2)
10932 /* We can assume that a conversion of the same code
10933 between the same types indicates a subsequence since we only get
10934 here if the types we are converting from are the same. */
10936 while (ics1->kind == ck_rvalue
10937 || ics1->kind == ck_lvalue)
10938 ics1 = next_conversion (ics1);
10940 while (1)
10942 while (ics2->kind == ck_rvalue
10943 || ics2->kind == ck_lvalue)
10944 ics2 = next_conversion (ics2);
10946 if (ics2->kind == ck_user
10947 || !has_next (ics2->kind))
10948 /* At this point, ICS1 cannot be a proper subsequence of
10949 ICS2. We can get a USER_CONV when we are comparing the
10950 second standard conversion sequence of two user conversion
10951 sequences. */
10952 return false;
10954 ics2 = next_conversion (ics2);
10956 while (ics2->kind == ck_rvalue
10957 || ics2->kind == ck_lvalue)
10958 ics2 = next_conversion (ics2);
10960 if (ics2->kind == ics1->kind
10961 && same_type_p (ics2->type, ics1->type)
10962 && (ics1->kind == ck_identity
10963 || same_type_p (next_conversion (ics2)->type,
10964 next_conversion (ics1)->type)))
10965 return true;
10969 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
10970 be any _TYPE nodes. */
10972 bool
10973 is_properly_derived_from (tree derived, tree base)
10975 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
10976 return false;
10978 /* We only allow proper derivation here. The DERIVED_FROM_P macro
10979 considers every class derived from itself. */
10980 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
10981 && DERIVED_FROM_P (base, derived));
10984 /* We build the ICS for an implicit object parameter as a pointer
10985 conversion sequence. However, such a sequence should be compared
10986 as if it were a reference conversion sequence. If ICS is the
10987 implicit conversion sequence for an implicit object parameter,
10988 modify it accordingly. */
10990 static void
10991 maybe_handle_implicit_object (conversion **ics)
10993 if ((*ics)->this_p)
10995 /* [over.match.funcs]
10997 For non-static member functions, the type of the
10998 implicit object parameter is "reference to cv X"
10999 where X is the class of which the function is a
11000 member and cv is the cv-qualification on the member
11001 function declaration. */
11002 conversion *t = *ics;
11003 tree reference_type;
11005 /* The `this' parameter is a pointer to a class type. Make the
11006 implicit conversion talk about a reference to that same class
11007 type. */
11008 reference_type = TREE_TYPE (t->type);
11009 reference_type = build_reference_type (reference_type);
11011 if (t->kind == ck_qual)
11012 t = next_conversion (t);
11013 if (t->kind == ck_ptr)
11014 t = next_conversion (t);
11015 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11016 t = direct_reference_binding (reference_type, t);
11017 t->this_p = 1;
11018 t->rvaluedness_matches_p = 0;
11019 *ics = t;
11023 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11024 and return the initial reference binding conversion. Otherwise,
11025 leave *ICS unchanged and return NULL. */
11027 static conversion *
11028 maybe_handle_ref_bind (conversion **ics)
11030 if ((*ics)->kind == ck_ref_bind)
11032 conversion *old_ics = *ics;
11033 *ics = next_conversion (old_ics);
11034 (*ics)->user_conv_p = old_ics->user_conv_p;
11035 return old_ics;
11038 return NULL;
11041 /* Get the expression at the beginning of the conversion chain C. */
11043 static tree
11044 conv_get_original_expr (conversion *c)
11046 for (; c; c = next_conversion (c))
11047 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11048 return c->u.expr;
11049 return NULL_TREE;
11052 /* Return a tree representing the number of elements initialized by the
11053 list-initialization C. The caller must check that C converts to an
11054 array type. */
11056 static tree
11057 nelts_initialized_by_list_init (conversion *c)
11059 /* If the array we're converting to has a dimension, we'll use that. */
11060 if (TYPE_DOMAIN (c->type))
11061 return array_type_nelts_top (c->type);
11062 else
11064 /* Otherwise, we look at how many elements the constructor we're
11065 initializing from has. */
11066 tree ctor = conv_get_original_expr (c);
11067 return size_int (CONSTRUCTOR_NELTS (ctor));
11071 /* True iff C is a conversion that binds a reference or a pointer to
11072 an array of unknown bound. */
11074 static inline bool
11075 conv_binds_to_array_of_unknown_bound (conversion *c)
11077 /* ck_ref_bind won't have the reference stripped. */
11078 tree type = non_reference (c->type);
11079 /* ck_qual won't have the pointer stripped. */
11080 type = strip_pointer_operator (type);
11081 return (TREE_CODE (type) == ARRAY_TYPE
11082 && TYPE_DOMAIN (type) == NULL_TREE);
11085 /* Compare two implicit conversion sequences according to the rules set out in
11086 [over.ics.rank]. Return values:
11088 1: ics1 is better than ics2
11089 -1: ics2 is better than ics1
11090 0: ics1 and ics2 are indistinguishable */
11092 static int
11093 compare_ics (conversion *ics1, conversion *ics2)
11095 tree from_type1;
11096 tree from_type2;
11097 tree to_type1;
11098 tree to_type2;
11099 tree deref_from_type1 = NULL_TREE;
11100 tree deref_from_type2 = NULL_TREE;
11101 tree deref_to_type1 = NULL_TREE;
11102 tree deref_to_type2 = NULL_TREE;
11103 conversion_rank rank1, rank2;
11105 /* REF_BINDING is nonzero if the result of the conversion sequence
11106 is a reference type. In that case REF_CONV is the reference
11107 binding conversion. */
11108 conversion *ref_conv1;
11109 conversion *ref_conv2;
11111 /* Compare badness before stripping the reference conversion. */
11112 if (ics1->bad_p > ics2->bad_p)
11113 return -1;
11114 else if (ics1->bad_p < ics2->bad_p)
11115 return 1;
11117 /* Handle implicit object parameters. */
11118 maybe_handle_implicit_object (&ics1);
11119 maybe_handle_implicit_object (&ics2);
11121 /* Handle reference parameters. */
11122 ref_conv1 = maybe_handle_ref_bind (&ics1);
11123 ref_conv2 = maybe_handle_ref_bind (&ics2);
11125 /* List-initialization sequence L1 is a better conversion sequence than
11126 list-initialization sequence L2 if L1 converts to
11127 std::initializer_list<X> for some X and L2 does not. */
11128 if (ics1->kind == ck_list && ics2->kind != ck_list)
11129 return 1;
11130 if (ics2->kind == ck_list && ics1->kind != ck_list)
11131 return -1;
11133 /* [over.ics.rank]
11135 When comparing the basic forms of implicit conversion sequences (as
11136 defined in _over.best.ics_)
11138 --a standard conversion sequence (_over.ics.scs_) is a better
11139 conversion sequence than a user-defined conversion sequence
11140 or an ellipsis conversion sequence, and
11142 --a user-defined conversion sequence (_over.ics.user_) is a
11143 better conversion sequence than an ellipsis conversion sequence
11144 (_over.ics.ellipsis_). */
11145 /* Use BAD_CONVERSION_RANK because we already checked for a badness
11146 mismatch. If both ICS are bad, we try to make a decision based on
11147 what would have happened if they'd been good. This is not an
11148 extension, we'll still give an error when we build up the call; this
11149 just helps us give a more helpful error message. */
11150 rank1 = BAD_CONVERSION_RANK (ics1);
11151 rank2 = BAD_CONVERSION_RANK (ics2);
11153 if (rank1 > rank2)
11154 return -1;
11155 else if (rank1 < rank2)
11156 return 1;
11158 if (ics1->ellipsis_p)
11159 /* Both conversions are ellipsis conversions. */
11160 return 0;
11162 /* User-defined conversion sequence U1 is a better conversion sequence
11163 than another user-defined conversion sequence U2 if they contain the
11164 same user-defined conversion operator or constructor and if the sec-
11165 ond standard conversion sequence of U1 is better than the second
11166 standard conversion sequence of U2. */
11168 /* Handle list-conversion with the same code even though it isn't always
11169 ranked as a user-defined conversion and it doesn't have a second
11170 standard conversion sequence; it will still have the desired effect.
11171 Specifically, we need to do the reference binding comparison at the
11172 end of this function. */
11174 if (ics1->user_conv_p || ics1->kind == ck_list
11175 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
11177 conversion *t1 = strip_standard_conversion (ics1);
11178 conversion *t2 = strip_standard_conversion (ics2);
11180 if (!t1 || !t2 || t1->kind != t2->kind)
11181 return 0;
11182 else if (t1->kind == ck_user)
11184 tree f1 = t1->cand ? t1->cand->fn : t1->type;
11185 tree f2 = t2->cand ? t2->cand->fn : t2->type;
11186 if (f1 != f2)
11187 return 0;
11189 /* List-initialization sequence L1 is a better conversion sequence than
11190 list-initialization sequence L2 if
11192 -- L1 and L2 convert to arrays of the same element type, and either
11193 the number of elements n1 initialized by L1 is less than the number
11194 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
11195 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
11196 P0388R4.) */
11197 else if (t1->kind == ck_aggr
11198 && TREE_CODE (t1->type) == ARRAY_TYPE
11199 && TREE_CODE (t2->type) == ARRAY_TYPE)
11201 /* The type of the array elements must be the same. */
11202 if (!same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
11203 return 0;
11205 tree n1 = nelts_initialized_by_list_init (t1);
11206 tree n2 = nelts_initialized_by_list_init (t2);
11207 if (tree_int_cst_lt (n1, n2))
11208 return 1;
11209 else if (tree_int_cst_lt (n2, n1))
11210 return -1;
11211 /* The n1 == n2 case. */
11212 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
11213 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
11214 if (c1 && !c2)
11215 return -1;
11216 else if (!c1 && c2)
11217 return 1;
11218 else
11219 return 0;
11221 else
11223 /* For ambiguous or aggregate conversions, use the target type as
11224 a proxy for the conversion function. */
11225 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
11226 return 0;
11229 /* We can just fall through here, after setting up
11230 FROM_TYPE1 and FROM_TYPE2. */
11231 from_type1 = t1->type;
11232 from_type2 = t2->type;
11234 else
11236 conversion *t1;
11237 conversion *t2;
11239 /* We're dealing with two standard conversion sequences.
11241 [over.ics.rank]
11243 Standard conversion sequence S1 is a better conversion
11244 sequence than standard conversion sequence S2 if
11246 --S1 is a proper subsequence of S2 (comparing the conversion
11247 sequences in the canonical form defined by _over.ics.scs_,
11248 excluding any Lvalue Transformation; the identity
11249 conversion sequence is considered to be a subsequence of
11250 any non-identity conversion sequence */
11252 t1 = ics1;
11253 while (t1->kind != ck_identity)
11254 t1 = next_conversion (t1);
11255 from_type1 = t1->type;
11257 t2 = ics2;
11258 while (t2->kind != ck_identity)
11259 t2 = next_conversion (t2);
11260 from_type2 = t2->type;
11263 /* One sequence can only be a subsequence of the other if they start with
11264 the same type. They can start with different types when comparing the
11265 second standard conversion sequence in two user-defined conversion
11266 sequences. */
11267 if (same_type_p (from_type1, from_type2))
11269 if (is_subseq (ics1, ics2))
11270 return 1;
11271 if (is_subseq (ics2, ics1))
11272 return -1;
11275 /* [over.ics.rank]
11277 Or, if not that,
11279 --the rank of S1 is better than the rank of S2 (by the rules
11280 defined below):
11282 Standard conversion sequences are ordered by their ranks: an Exact
11283 Match is a better conversion than a Promotion, which is a better
11284 conversion than a Conversion.
11286 Two conversion sequences with the same rank are indistinguishable
11287 unless one of the following rules applies:
11289 --A conversion that does not a convert a pointer, pointer to member,
11290 or std::nullptr_t to bool is better than one that does.
11292 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
11293 so that we do not have to check it explicitly. */
11294 if (ics1->rank < ics2->rank)
11295 return 1;
11296 else if (ics2->rank < ics1->rank)
11297 return -1;
11299 to_type1 = ics1->type;
11300 to_type2 = ics2->type;
11302 /* A conversion from scalar arithmetic type to complex is worse than a
11303 conversion between scalar arithmetic types. */
11304 if (same_type_p (from_type1, from_type2)
11305 && ARITHMETIC_TYPE_P (from_type1)
11306 && ARITHMETIC_TYPE_P (to_type1)
11307 && ARITHMETIC_TYPE_P (to_type2)
11308 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
11309 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
11311 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
11312 return -1;
11313 else
11314 return 1;
11317 if (TYPE_PTR_P (from_type1)
11318 && TYPE_PTR_P (from_type2)
11319 && TYPE_PTR_P (to_type1)
11320 && TYPE_PTR_P (to_type2))
11322 deref_from_type1 = TREE_TYPE (from_type1);
11323 deref_from_type2 = TREE_TYPE (from_type2);
11324 deref_to_type1 = TREE_TYPE (to_type1);
11325 deref_to_type2 = TREE_TYPE (to_type2);
11327 /* The rules for pointers to members A::* are just like the rules
11328 for pointers A*, except opposite: if B is derived from A then
11329 A::* converts to B::*, not vice versa. For that reason, we
11330 switch the from_ and to_ variables here. */
11331 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
11332 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
11333 || (TYPE_PTRMEMFUNC_P (from_type1)
11334 && TYPE_PTRMEMFUNC_P (from_type2)
11335 && TYPE_PTRMEMFUNC_P (to_type1)
11336 && TYPE_PTRMEMFUNC_P (to_type2)))
11338 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
11339 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
11340 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
11341 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
11344 if (deref_from_type1 != NULL_TREE
11345 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
11346 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
11348 /* This was one of the pointer or pointer-like conversions.
11350 [over.ics.rank]
11352 --If class B is derived directly or indirectly from class A,
11353 conversion of B* to A* is better than conversion of B* to
11354 void*, and conversion of A* to void* is better than
11355 conversion of B* to void*. */
11356 if (VOID_TYPE_P (deref_to_type1)
11357 && VOID_TYPE_P (deref_to_type2))
11359 if (is_properly_derived_from (deref_from_type1,
11360 deref_from_type2))
11361 return -1;
11362 else if (is_properly_derived_from (deref_from_type2,
11363 deref_from_type1))
11364 return 1;
11366 else if (VOID_TYPE_P (deref_to_type1)
11367 || VOID_TYPE_P (deref_to_type2))
11369 if (same_type_p (deref_from_type1, deref_from_type2))
11371 if (VOID_TYPE_P (deref_to_type2))
11373 if (is_properly_derived_from (deref_from_type1,
11374 deref_to_type1))
11375 return 1;
11377 /* We know that DEREF_TO_TYPE1 is `void' here. */
11378 else if (is_properly_derived_from (deref_from_type1,
11379 deref_to_type2))
11380 return -1;
11383 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
11384 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
11386 /* [over.ics.rank]
11388 --If class B is derived directly or indirectly from class A
11389 and class C is derived directly or indirectly from B,
11391 --conversion of C* to B* is better than conversion of C* to
11394 --conversion of B* to A* is better than conversion of C* to
11395 A* */
11396 if (same_type_p (deref_from_type1, deref_from_type2))
11398 if (is_properly_derived_from (deref_to_type1,
11399 deref_to_type2))
11400 return 1;
11401 else if (is_properly_derived_from (deref_to_type2,
11402 deref_to_type1))
11403 return -1;
11405 else if (same_type_p (deref_to_type1, deref_to_type2))
11407 if (is_properly_derived_from (deref_from_type2,
11408 deref_from_type1))
11409 return 1;
11410 else if (is_properly_derived_from (deref_from_type1,
11411 deref_from_type2))
11412 return -1;
11416 else if (CLASS_TYPE_P (non_reference (from_type1))
11417 && same_type_p (from_type1, from_type2))
11419 tree from = non_reference (from_type1);
11421 /* [over.ics.rank]
11423 --binding of an expression of type C to a reference of type
11424 B& is better than binding an expression of type C to a
11425 reference of type A&
11427 --conversion of C to B is better than conversion of C to A, */
11428 if (is_properly_derived_from (from, to_type1)
11429 && is_properly_derived_from (from, to_type2))
11431 if (is_properly_derived_from (to_type1, to_type2))
11432 return 1;
11433 else if (is_properly_derived_from (to_type2, to_type1))
11434 return -1;
11437 else if (CLASS_TYPE_P (non_reference (to_type1))
11438 && same_type_p (to_type1, to_type2))
11440 tree to = non_reference (to_type1);
11442 /* [over.ics.rank]
11444 --binding of an expression of type B to a reference of type
11445 A& is better than binding an expression of type C to a
11446 reference of type A&,
11448 --conversion of B to A is better than conversion of C to A */
11449 if (is_properly_derived_from (from_type1, to)
11450 && is_properly_derived_from (from_type2, to))
11452 if (is_properly_derived_from (from_type2, from_type1))
11453 return 1;
11454 else if (is_properly_derived_from (from_type1, from_type2))
11455 return -1;
11459 /* [over.ics.rank]
11461 --S1 and S2 differ only in their qualification conversion and yield
11462 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
11463 qualification signature of type T1 is a proper subset of the cv-
11464 qualification signature of type T2 */
11465 if (ics1->kind == ck_qual
11466 && ics2->kind == ck_qual
11467 && same_type_p (from_type1, from_type2))
11469 int result = comp_cv_qual_signature (to_type1, to_type2);
11470 if (result != 0)
11471 return result;
11474 /* [over.ics.rank]
11476 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
11477 to an implicit object parameter of a non-static member function
11478 declared without a ref-qualifier, and either S1 binds an lvalue
11479 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
11480 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
11481 draft standard, 13.3.3.2)
11483 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
11484 types to which the references refer are the same type except for
11485 top-level cv-qualifiers, and the type to which the reference
11486 initialized by S2 refers is more cv-qualified than the type to
11487 which the reference initialized by S1 refers.
11489 DR 1328 [over.match.best]: the context is an initialization by
11490 conversion function for direct reference binding (13.3.1.6) of a
11491 reference to function type, the return type of F1 is the same kind of
11492 reference (i.e. lvalue or rvalue) as the reference being initialized,
11493 and the return type of F2 is not. */
11495 if (ref_conv1 && ref_conv2)
11497 if (!ref_conv1->this_p && !ref_conv2->this_p
11498 && (ref_conv1->rvaluedness_matches_p
11499 != ref_conv2->rvaluedness_matches_p)
11500 && (same_type_p (ref_conv1->type, ref_conv2->type)
11501 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
11502 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
11504 if (ref_conv1->bad_p
11505 && !same_type_p (TREE_TYPE (ref_conv1->type),
11506 TREE_TYPE (ref_conv2->type)))
11507 /* Don't prefer a bad conversion that drops cv-quals to a bad
11508 conversion with the wrong rvalueness. */
11509 return 0;
11510 return (ref_conv1->rvaluedness_matches_p
11511 - ref_conv2->rvaluedness_matches_p);
11514 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
11516 /* Per P0388R4:
11518 void f (int(&)[]), // (1)
11519 f (int(&)[1]), // (2)
11520 f (int*); // (3)
11522 (2) is better than (1), but (3) should be equal to (1) and to
11523 (2). For that reason we don't use ck_qual for (1) which would
11524 give it the cr_exact rank while (3) remains ck_identity.
11525 Therefore we compare (1) and (2) here. For (1) we'll have
11527 ck_ref_bind <- ck_identity
11528 int[] & int[1]
11530 so to handle this we must look at ref_conv. */
11531 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
11532 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
11533 if (c1 && !c2)
11534 return -1;
11535 else if (!c1 && c2)
11536 return 1;
11538 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
11539 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
11540 if (ref_conv1->bad_p)
11542 /* Prefer the one that drops fewer cv-quals. */
11543 tree ftype = next_conversion (ref_conv1)->type;
11544 int fquals = cp_type_quals (ftype);
11545 q1 ^= fquals;
11546 q2 ^= fquals;
11548 return comp_cv_qualification (q2, q1);
11552 /* [over.ics.rank]
11554 Per CWG 1601:
11555 -- A conversion that promotes an enumeration whose underlying type
11556 is fixed to its underlying type is better than one that promotes to
11557 the promoted underlying type, if the two are different. */
11558 if (ics1->rank == cr_promotion
11559 && ics2->rank == cr_promotion
11560 && UNSCOPED_ENUM_P (from_type1)
11561 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
11562 && same_type_p (from_type1, from_type2))
11564 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
11565 tree prom = type_promotes_to (from_type1);
11566 if (!same_type_p (utype, prom))
11568 if (same_type_p (to_type1, utype)
11569 && same_type_p (to_type2, prom))
11570 return 1;
11571 else if (same_type_p (to_type2, utype)
11572 && same_type_p (to_type1, prom))
11573 return -1;
11577 /* Neither conversion sequence is better than the other. */
11578 return 0;
11581 /* The source type for this standard conversion sequence. */
11583 static tree
11584 source_type (conversion *t)
11586 return strip_standard_conversion (t)->type;
11589 /* Note a warning about preferring WINNER to LOSER. We do this by storing
11590 a pointer to LOSER and re-running joust to produce the warning if WINNER
11591 is actually used. */
11593 static void
11594 add_warning (struct z_candidate *winner, struct z_candidate *loser)
11596 candidate_warning *cw = (candidate_warning *)
11597 conversion_obstack_alloc (sizeof (candidate_warning));
11598 cw->loser = loser;
11599 cw->next = winner->warnings;
11600 winner->warnings = cw;
11603 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
11604 prvalue returned from a conversion function, replace CAND with the candidate
11605 for the conversion and return true. Otherwise, return false. */
11607 static bool
11608 joust_maybe_elide_copy (z_candidate *&cand)
11610 tree fn = cand->fn;
11611 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
11612 return false;
11613 conversion *conv = cand->convs[0];
11614 gcc_checking_assert (conv->kind == ck_ref_bind);
11615 conv = next_conversion (conv);
11616 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
11618 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
11619 (conv->type, DECL_CONTEXT (fn)));
11620 z_candidate *uc = conv->cand;
11621 if (DECL_CONV_FN_P (uc->fn))
11623 cand = uc;
11624 return true;
11627 return false;
11630 /* True if the defining declarations of the two candidates have equivalent
11631 parameters. */
11633 bool
11634 cand_parms_match (z_candidate *c1, z_candidate *c2)
11636 tree fn1 = c1->fn;
11637 tree fn2 = c2->fn;
11638 if (fn1 == fn2)
11639 return true;
11640 if (identifier_p (fn1) || identifier_p (fn2))
11641 return false;
11642 /* We don't look at c1->template_decl because that's only set for primary
11643 templates, not e.g. non-template member functions of class templates. */
11644 tree t1 = most_general_template (fn1);
11645 tree t2 = most_general_template (fn2);
11646 if (t1 || t2)
11648 if (!t1 || !t2)
11649 return false;
11650 if (t1 == t2)
11651 return true;
11652 fn1 = DECL_TEMPLATE_RESULT (t1);
11653 fn2 = DECL_TEMPLATE_RESULT (t2);
11655 return compparms (TYPE_ARG_TYPES (TREE_TYPE (fn1)),
11656 TYPE_ARG_TYPES (TREE_TYPE (fn2)));
11659 /* Compare two candidates for overloading as described in
11660 [over.match.best]. Return values:
11662 1: cand1 is better than cand2
11663 -1: cand2 is better than cand1
11664 0: cand1 and cand2 are indistinguishable */
11666 static int
11667 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
11668 tsubst_flags_t complain)
11670 int winner = 0;
11671 int off1 = 0, off2 = 0;
11672 size_t i;
11673 size_t len;
11675 /* Candidates that involve bad conversions are always worse than those
11676 that don't. */
11677 if (cand1->viable > cand2->viable)
11678 return 1;
11679 if (cand1->viable < cand2->viable)
11680 return -1;
11682 /* If we have two pseudo-candidates for conversions to the same type,
11683 or two candidates for the same function, arbitrarily pick one. */
11684 if (cand1->fn == cand2->fn
11685 && cand1->reversed () == cand2->reversed ()
11686 && (IS_TYPE_OR_DECL_P (cand1->fn)))
11687 return 1;
11689 /* Prefer a non-deleted function over an implicitly deleted move
11690 constructor or assignment operator. This differs slightly from the
11691 wording for issue 1402 (which says the move op is ignored by overload
11692 resolution), but this way produces better error messages. */
11693 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
11694 && TREE_CODE (cand2->fn) == FUNCTION_DECL
11695 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
11697 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
11698 && move_fn_p (cand1->fn))
11699 return -1;
11700 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
11701 && move_fn_p (cand2->fn))
11702 return 1;
11705 /* a viable function F1
11706 is defined to be a better function than another viable function F2 if
11707 for all arguments i, ICSi(F1) is not a worse conversion sequence than
11708 ICSi(F2), and then */
11710 /* for some argument j, ICSj(F1) is a better conversion sequence than
11711 ICSj(F2) */
11713 /* For comparing static and non-static member functions, we ignore
11714 the implicit object parameter of the non-static function. The
11715 standard says to pretend that the static function has an object
11716 parm, but that won't work with operator overloading. */
11717 len = cand1->num_convs;
11718 if (len != cand2->num_convs)
11720 int static_1 = DECL_STATIC_FUNCTION_P (cand1->fn);
11721 int static_2 = DECL_STATIC_FUNCTION_P (cand2->fn);
11723 if (DECL_CONSTRUCTOR_P (cand1->fn)
11724 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
11725 /* We're comparing a near-match list constructor and a near-match
11726 non-list constructor. Just treat them as unordered. */
11727 return 0;
11729 gcc_assert (static_1 != static_2);
11731 if (static_1)
11732 off2 = 1;
11733 else
11735 off1 = 1;
11736 --len;
11740 /* Handle C++17 copy elision in [over.match.ctor] (direct-init) context. The
11741 standard currently says that only constructors are candidates, but if one
11742 copies a prvalue returned by a conversion function we want to treat the
11743 conversion as the candidate instead.
11745 Clang does something similar, as discussed at
11746 http://lists.isocpp.org/core/2017/10/3166.php
11747 http://lists.isocpp.org/core/2019/03/5721.php */
11748 int elided_tiebreaker = 0;
11749 if (len == 1 && cxx_dialect >= cxx17
11750 && DECL_P (cand1->fn)
11751 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
11752 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
11754 bool elided1 = joust_maybe_elide_copy (cand1);
11755 bool elided2 = joust_maybe_elide_copy (cand2);
11756 /* As a tiebreaker below we will prefer a constructor to a conversion
11757 operator exposed this way. */
11758 elided_tiebreaker = elided2 - elided1;
11761 for (i = 0; i < len; ++i)
11763 conversion *t1 = cand1->convs[i + off1];
11764 conversion *t2 = cand2->convs[i + off2];
11765 int comp = compare_ics (t1, t2);
11767 if (comp != 0)
11769 if ((complain & tf_warning)
11770 && warn_sign_promo
11771 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
11772 == cr_std + cr_promotion)
11773 && t1->kind == ck_std
11774 && t2->kind == ck_std
11775 && TREE_CODE (t1->type) == INTEGER_TYPE
11776 && TREE_CODE (t2->type) == INTEGER_TYPE
11777 && (TYPE_PRECISION (t1->type)
11778 == TYPE_PRECISION (t2->type))
11779 && (TYPE_UNSIGNED (next_conversion (t1)->type)
11780 || (TREE_CODE (next_conversion (t1)->type)
11781 == ENUMERAL_TYPE)))
11783 tree type = next_conversion (t1)->type;
11784 tree type1, type2;
11785 struct z_candidate *w, *l;
11786 if (comp > 0)
11787 type1 = t1->type, type2 = t2->type,
11788 w = cand1, l = cand2;
11789 else
11790 type1 = t2->type, type2 = t1->type,
11791 w = cand2, l = cand1;
11793 if (warn)
11795 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
11796 type, type1, type2);
11797 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
11799 else
11800 add_warning (w, l);
11803 if (winner && comp != winner)
11805 /* Ambiguity between normal and reversed comparison operators
11806 with the same parameter types; prefer the normal one. */
11807 if ((cand1->reversed () != cand2->reversed ())
11808 && cand_parms_match (cand1, cand2))
11809 return cand1->reversed () ? -1 : 1;
11811 winner = 0;
11812 goto tweak;
11814 winner = comp;
11818 /* warn about confusing overload resolution for user-defined conversions,
11819 either between a constructor and a conversion op, or between two
11820 conversion ops. */
11821 if ((complain & tf_warning)
11822 /* In C++17, the constructor might have been elided, which means that
11823 an originally null ->second_conv could become non-null. */
11824 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
11825 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
11826 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
11828 struct z_candidate *w, *l;
11829 bool give_warning = false;
11831 if (winner == 1)
11832 w = cand1, l = cand2;
11833 else
11834 w = cand2, l = cand1;
11836 /* We don't want to complain about `X::operator T1 ()'
11837 beating `X::operator T2 () const', when T2 is a no less
11838 cv-qualified version of T1. */
11839 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
11840 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
11842 tree t = TREE_TYPE (TREE_TYPE (l->fn));
11843 tree f = TREE_TYPE (TREE_TYPE (w->fn));
11845 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
11847 t = TREE_TYPE (t);
11848 f = TREE_TYPE (f);
11850 if (!comp_ptr_ttypes (t, f))
11851 give_warning = true;
11853 else
11854 give_warning = true;
11856 if (!give_warning)
11857 /*NOP*/;
11858 else if (warn)
11860 tree source = source_type (w->convs[0]);
11861 if (INDIRECT_TYPE_P (source))
11862 source = TREE_TYPE (source);
11863 auto_diagnostic_group d;
11864 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
11865 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
11866 source, w->second_conv->type))
11868 inform (input_location, " because conversion sequence "
11869 "for the argument is better");
11872 else
11873 add_warning (w, l);
11876 if (winner)
11877 return winner;
11879 /* Put this tiebreaker first, so that we don't try to look at second_conv of
11880 a constructor candidate that doesn't have one. */
11881 if (elided_tiebreaker)
11882 return elided_tiebreaker;
11884 /* DR 495 moved this tiebreaker above the template ones. */
11885 /* or, if not that,
11886 the context is an initialization by user-defined conversion (see
11887 _dcl.init_ and _over.match.user_) and the standard conversion
11888 sequence from the return type of F1 to the destination type (i.e.,
11889 the type of the entity being initialized) is a better conversion
11890 sequence than the standard conversion sequence from the return type
11891 of F2 to the destination type. */
11893 if (cand1->second_conv)
11895 winner = compare_ics (cand1->second_conv, cand2->second_conv);
11896 if (winner)
11897 return winner;
11900 /* or, if not that,
11901 F1 is a non-template function and F2 is a template function
11902 specialization. */
11904 if (!cand1->template_decl && cand2->template_decl)
11905 return 1;
11906 else if (cand1->template_decl && !cand2->template_decl)
11907 return -1;
11909 /* or, if not that,
11910 F1 and F2 are template functions and the function template for F1 is
11911 more specialized than the template for F2 according to the partial
11912 ordering rules. */
11914 if (cand1->template_decl && cand2->template_decl)
11916 winner = more_specialized_fn
11917 (TI_TEMPLATE (cand1->template_decl),
11918 TI_TEMPLATE (cand2->template_decl),
11919 /* [temp.func.order]: The presence of unused ellipsis and default
11920 arguments has no effect on the partial ordering of function
11921 templates. add_function_candidate() will not have
11922 counted the "this" argument for constructors. */
11923 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
11924 if (winner)
11925 return winner;
11928 /* Concepts: F1 and F2 are non-template functions with the same
11929 parameter-type-lists, and F1 is more constrained than F2 according to the
11930 partial ordering of constraints described in 13.5.4. */
11932 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
11933 && !cand1->template_decl && !cand2->template_decl
11934 && cand_parms_match (cand1, cand2))
11936 winner = more_constrained (cand1->fn, cand2->fn);
11937 if (winner)
11938 return winner;
11941 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
11942 rewritten candidates, and F2 is a synthesized candidate with reversed
11943 order of parameters and F1 is not. */
11944 if (cand1->rewritten ())
11946 if (!cand2->rewritten ())
11947 return -1;
11948 if (!cand1->reversed () && cand2->reversed ())
11949 return 1;
11950 if (cand1->reversed () && !cand2->reversed ())
11951 return -1;
11953 else if (cand2->rewritten ())
11954 return 1;
11956 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
11957 if (deduction_guide_p (cand1->fn))
11959 gcc_assert (deduction_guide_p (cand2->fn));
11960 /* We distinguish between candidates from an explicit deduction guide and
11961 candidates built from a constructor based on DECL_ARTIFICIAL. */
11962 int art1 = DECL_ARTIFICIAL (cand1->fn);
11963 int art2 = DECL_ARTIFICIAL (cand2->fn);
11964 if (art1 != art2)
11965 return art2 - art1;
11967 if (art1)
11969 /* Prefer the special copy guide over a declared copy/move
11970 constructor. */
11971 if (copy_guide_p (cand1->fn))
11972 return 1;
11973 if (copy_guide_p (cand2->fn))
11974 return -1;
11976 /* Prefer a candidate generated from a non-template constructor. */
11977 int tg1 = template_guide_p (cand1->fn);
11978 int tg2 = template_guide_p (cand2->fn);
11979 if (tg1 != tg2)
11980 return tg2 - tg1;
11984 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
11985 for all arguments the corresponding parameters of F1 and F2 have the same
11986 type (CWG 2273/2277). */
11987 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
11988 && !DECL_CONV_FN_P (cand1->fn)
11989 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
11990 && !DECL_CONV_FN_P (cand2->fn))
11992 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
11993 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
11995 bool used1 = false;
11996 bool used2 = false;
11997 if (base1 == base2)
11998 /* No difference. */;
11999 else if (DERIVED_FROM_P (base1, base2))
12000 used1 = true;
12001 else if (DERIVED_FROM_P (base2, base1))
12002 used2 = true;
12004 if (int diff = used2 - used1)
12006 for (i = 0; i < len; ++i)
12008 conversion *t1 = cand1->convs[i + off1];
12009 conversion *t2 = cand2->convs[i + off2];
12010 if (!same_type_p (t1->type, t2->type))
12011 break;
12013 if (i == len)
12014 return diff;
12018 /* Check whether we can discard a builtin candidate, either because we
12019 have two identical ones or matching builtin and non-builtin candidates.
12021 (Pedantically in the latter case the builtin which matched the user
12022 function should not be added to the overload set, but we spot it here.
12024 [over.match.oper]
12025 ... the builtin candidates include ...
12026 - do not have the same parameter type list as any non-template
12027 non-member candidate. */
12029 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
12031 for (i = 0; i < len; ++i)
12032 if (!same_type_p (cand1->convs[i]->type,
12033 cand2->convs[i]->type))
12034 break;
12035 if (i == cand1->num_convs)
12037 if (cand1->fn == cand2->fn)
12038 /* Two built-in candidates; arbitrarily pick one. */
12039 return 1;
12040 else if (identifier_p (cand1->fn))
12041 /* cand1 is built-in; prefer cand2. */
12042 return -1;
12043 else
12044 /* cand2 is built-in; prefer cand1. */
12045 return 1;
12049 /* For candidates of a multi-versioned function, make the version with
12050 the highest priority win. This version will be checked for dispatching
12051 first. If this version can be inlined into the caller, the front-end
12052 will simply make a direct call to this function. */
12054 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12055 && DECL_FUNCTION_VERSIONED (cand1->fn)
12056 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12057 && DECL_FUNCTION_VERSIONED (cand2->fn))
12059 tree f1 = TREE_TYPE (cand1->fn);
12060 tree f2 = TREE_TYPE (cand2->fn);
12061 tree p1 = TYPE_ARG_TYPES (f1);
12062 tree p2 = TYPE_ARG_TYPES (f2);
12064 /* Check if cand1->fn and cand2->fn are versions of the same function. It
12065 is possible that cand1->fn and cand2->fn are function versions but of
12066 different functions. Check types to see if they are versions of the same
12067 function. */
12068 if (compparms (p1, p2)
12069 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
12071 /* Always make the version with the higher priority, more
12072 specialized, win. */
12073 gcc_assert (targetm.compare_version_priority);
12074 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
12075 return 1;
12076 else
12077 return -1;
12081 /* If the two function declarations represent the same function (this can
12082 happen with declarations in multiple scopes and arg-dependent lookup),
12083 arbitrarily choose one. But first make sure the default args we're
12084 using match. */
12085 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
12086 && equal_functions (cand1->fn, cand2->fn))
12088 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
12089 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
12091 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
12093 for (i = 0; i < len; ++i)
12095 /* Don't crash if the fn is variadic. */
12096 if (!parms1)
12097 break;
12098 parms1 = TREE_CHAIN (parms1);
12099 parms2 = TREE_CHAIN (parms2);
12102 if (off1)
12103 parms1 = TREE_CHAIN (parms1);
12104 else if (off2)
12105 parms2 = TREE_CHAIN (parms2);
12107 for (; parms1; ++i)
12109 if (!cp_tree_equal (TREE_PURPOSE (parms1),
12110 TREE_PURPOSE (parms2)))
12112 if (warn)
12114 if (complain & tf_error)
12116 auto_diagnostic_group d;
12117 if (permerror (input_location,
12118 "default argument mismatch in "
12119 "overload resolution"))
12121 inform (DECL_SOURCE_LOCATION (cand1->fn),
12122 " candidate 1: %q#F", cand1->fn);
12123 inform (DECL_SOURCE_LOCATION (cand2->fn),
12124 " candidate 2: %q#F", cand2->fn);
12127 else
12128 return 0;
12130 else
12131 add_warning (cand1, cand2);
12132 break;
12134 parms1 = TREE_CHAIN (parms1);
12135 parms2 = TREE_CHAIN (parms2);
12138 return 1;
12141 tweak:
12143 /* Extension: If the worst conversion for one candidate is better than the
12144 worst conversion for the other, take the first. */
12145 if (!pedantic && (complain & tf_warning_or_error))
12147 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
12148 struct z_candidate *w = 0, *l = 0;
12150 for (i = 0; i < len; ++i)
12152 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
12153 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
12154 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
12155 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
12157 if (rank1 < rank2)
12158 winner = 1, w = cand1, l = cand2;
12159 if (rank1 > rank2)
12160 winner = -1, w = cand2, l = cand1;
12161 if (winner)
12163 /* Don't choose a deleted function over ambiguity. */
12164 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
12165 return 0;
12166 if (warn)
12168 auto_diagnostic_group d;
12169 if (pedwarn (input_location, 0,
12170 "ISO C++ says that these are ambiguous, even "
12171 "though the worst conversion for the first is "
12172 "better than the worst conversion for the second:"))
12174 print_z_candidate (input_location, N_("candidate 1:"), w);
12175 print_z_candidate (input_location, N_("candidate 2:"), l);
12178 else
12179 add_warning (w, l);
12180 return winner;
12184 gcc_assert (!winner);
12185 return 0;
12188 /* Given a list of candidates for overloading, find the best one, if any.
12189 This algorithm has a worst case of O(2n) (winner is last), and a best
12190 case of O(n/2) (totally ambiguous); much better than a sorting
12191 algorithm. */
12193 static struct z_candidate *
12194 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
12196 struct z_candidate *champ = candidates, *challenger;
12197 int fate;
12198 int champ_compared_to_predecessor = 0;
12200 /* Walk through the list once, comparing each current champ to the next
12201 candidate, knocking out a candidate or two with each comparison. */
12203 for (challenger = champ->next; challenger; )
12205 fate = joust (champ, challenger, 0, complain);
12206 if (fate == 1)
12207 challenger = challenger->next;
12208 else
12210 if (fate == 0)
12212 champ = challenger->next;
12213 if (champ == 0)
12214 return NULL;
12215 champ_compared_to_predecessor = 0;
12217 else
12219 champ = challenger;
12220 champ_compared_to_predecessor = 1;
12223 challenger = champ->next;
12227 /* Make sure the champ is better than all the candidates it hasn't yet
12228 been compared to. */
12230 for (challenger = candidates;
12231 challenger != champ
12232 && !(champ_compared_to_predecessor && challenger->next == champ);
12233 challenger = challenger->next)
12235 fate = joust (champ, challenger, 0, complain);
12236 if (fate != 1)
12237 return NULL;
12240 return champ;
12243 /* Returns nonzero if things of type FROM can be converted to TO. */
12245 bool
12246 can_convert (tree to, tree from, tsubst_flags_t complain)
12248 tree arg = NULL_TREE;
12249 /* implicit_conversion only considers user-defined conversions
12250 if it has an expression for the call argument list. */
12251 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
12252 arg = build_stub_object (from);
12253 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
12256 /* Returns nonzero if things of type FROM can be converted to TO with a
12257 standard conversion. */
12259 bool
12260 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
12262 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
12265 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
12267 bool
12268 can_convert_arg (tree to, tree from, tree arg, int flags,
12269 tsubst_flags_t complain)
12271 conversion *t;
12272 void *p;
12273 bool ok_p;
12275 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12276 p = conversion_obstack_alloc (0);
12277 /* We want to discard any access checks done for this test,
12278 as we might not be in the appropriate access context and
12279 we'll do the check again when we actually perform the
12280 conversion. */
12281 push_deferring_access_checks (dk_deferred);
12283 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12284 flags, complain);
12285 ok_p = (t && !t->bad_p);
12287 /* Discard the access checks now. */
12288 pop_deferring_access_checks ();
12289 /* Free all the conversions we allocated. */
12290 obstack_free (&conversion_obstack, p);
12292 return ok_p;
12295 /* Like can_convert_arg, but allows dubious conversions as well. */
12297 bool
12298 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
12299 tsubst_flags_t complain)
12301 conversion *t;
12302 void *p;
12304 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12305 p = conversion_obstack_alloc (0);
12306 /* Try to perform the conversion. */
12307 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12308 flags, complain);
12309 /* Free all the conversions we allocated. */
12310 obstack_free (&conversion_obstack, p);
12312 return t != NULL;
12315 /* Convert EXPR to TYPE. Return the converted expression.
12317 Note that we allow bad conversions here because by the time we get to
12318 this point we are committed to doing the conversion. If we end up
12319 doing a bad conversion, convert_like will complain. */
12321 tree
12322 perform_implicit_conversion_flags (tree type, tree expr,
12323 tsubst_flags_t complain, int flags)
12325 conversion *conv;
12326 void *p;
12327 location_t loc = cp_expr_loc_or_input_loc (expr);
12329 if (TYPE_REF_P (type))
12330 expr = mark_lvalue_use (expr);
12331 else
12332 expr = mark_rvalue_use (expr);
12334 if (error_operand_p (expr))
12335 return error_mark_node;
12337 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12338 p = conversion_obstack_alloc (0);
12340 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12341 /*c_cast_p=*/false,
12342 flags, complain);
12344 if (!conv)
12346 if (complain & tf_error)
12347 implicit_conversion_error (loc, type, expr);
12348 expr = error_mark_node;
12350 else if (processing_template_decl && conv->kind != ck_identity)
12352 /* In a template, we are only concerned about determining the
12353 type of non-dependent expressions, so we do not have to
12354 perform the actual conversion. But for initializers, we
12355 need to be able to perform it at instantiation
12356 (or instantiate_non_dependent_expr) time. */
12357 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
12358 if (!(flags & LOOKUP_ONLYCONVERTING))
12359 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12360 if (flags & LOOKUP_NO_NARROWING)
12361 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
12363 else
12364 expr = convert_like (conv, expr, complain);
12366 /* Free all the conversions we allocated. */
12367 obstack_free (&conversion_obstack, p);
12369 return expr;
12372 tree
12373 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
12375 return perform_implicit_conversion_flags (type, expr, complain,
12376 LOOKUP_IMPLICIT);
12379 /* Convert EXPR to TYPE (as a direct-initialization) if that is
12380 permitted. If the conversion is valid, the converted expression is
12381 returned. Otherwise, NULL_TREE is returned, except in the case
12382 that TYPE is a class type; in that case, an error is issued. If
12383 C_CAST_P is true, then this direct-initialization is taking
12384 place as part of a static_cast being attempted as part of a C-style
12385 cast. */
12387 tree
12388 perform_direct_initialization_if_possible (tree type,
12389 tree expr,
12390 bool c_cast_p,
12391 tsubst_flags_t complain)
12393 conversion *conv;
12394 void *p;
12396 if (type == error_mark_node || error_operand_p (expr))
12397 return error_mark_node;
12398 /* [dcl.init]
12400 If the destination type is a (possibly cv-qualified) class type:
12402 -- If the initialization is direct-initialization ...,
12403 constructors are considered.
12405 -- If overload resolution is successful, the selected constructor
12406 is called to initialize the object, with the initializer expression
12407 or expression-list as its argument(s).
12409 -- Otherwise, if no constructor is viable, the destination type is
12410 a (possibly cv-qualified) aggregate class A, and the initializer is
12411 a parenthesized expression-list, the object is initialized as
12412 follows... */
12413 if (CLASS_TYPE_P (type))
12415 releasing_vec args (make_tree_vector_single (expr));
12416 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
12417 &args, type, LOOKUP_NORMAL, complain);
12418 return build_cplus_new (type, expr, complain);
12421 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12422 p = conversion_obstack_alloc (0);
12424 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12425 c_cast_p,
12426 LOOKUP_NORMAL, complain);
12427 if (!conv || conv->bad_p)
12428 expr = NULL_TREE;
12429 else if (processing_template_decl && conv->kind != ck_identity)
12431 /* In a template, we are only concerned about determining the
12432 type of non-dependent expressions, so we do not have to
12433 perform the actual conversion. But for initializers, we
12434 need to be able to perform it at instantiation
12435 (or instantiate_non_dependent_expr) time. */
12436 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
12437 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12439 else
12440 expr = convert_like (conv, expr, NULL_TREE, 0,
12441 /*issue_conversion_warnings=*/false,
12442 c_cast_p, complain);
12444 /* Free all the conversions we allocated. */
12445 obstack_free (&conversion_obstack, p);
12447 return expr;
12450 /* When initializing a reference that lasts longer than a full-expression,
12451 this special rule applies:
12453 [class.temporary]
12455 The temporary to which the reference is bound or the temporary
12456 that is the complete object to which the reference is bound
12457 persists for the lifetime of the reference.
12459 The temporaries created during the evaluation of the expression
12460 initializing the reference, except the temporary to which the
12461 reference is bound, are destroyed at the end of the
12462 full-expression in which they are created.
12464 In that case, we store the converted expression into a new
12465 VAR_DECL in a new scope.
12467 However, we want to be careful not to create temporaries when
12468 they are not required. For example, given:
12470 struct B {};
12471 struct D : public B {};
12472 D f();
12473 const B& b = f();
12475 there is no need to copy the return value from "f"; we can just
12476 extend its lifetime. Similarly, given:
12478 struct S {};
12479 struct T { operator S(); };
12480 T t;
12481 const S& s = t;
12483 we can extend the lifetime of the return value of the conversion
12484 operator.
12486 The next several functions are involved in this lifetime extension. */
12488 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
12489 reference is being bound to a temporary. Create and return a new
12490 VAR_DECL with the indicated TYPE; this variable will store the value to
12491 which the reference is bound. */
12493 tree
12494 make_temporary_var_for_ref_to_temp (tree decl, tree type)
12496 tree var = create_temporary_var (type);
12498 /* Register the variable. */
12499 if (VAR_P (decl)
12500 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
12502 /* Namespace-scope or local static; give it a mangled name. */
12504 /* If an initializer is visible to multiple translation units, those
12505 translation units must agree on the addresses of the
12506 temporaries. Therefore the temporaries must be given a consistent name
12507 and vague linkage. The mangled name of a temporary is the name of the
12508 non-temporary object in whose initializer they appear, prefixed with
12509 GR and suffixed with a sequence number mangled using the usual rules
12510 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
12511 left-to-right walk of the complete initializer. */
12512 copy_linkage (var, decl);
12514 tree name = mangle_ref_init_variable (decl);
12515 DECL_NAME (var) = name;
12516 SET_DECL_ASSEMBLER_NAME (var, name);
12518 else
12519 /* Create a new cleanup level if necessary. */
12520 maybe_push_cleanup_level (type);
12522 return pushdecl (var);
12525 /* EXPR is the initializer for a variable DECL of reference or
12526 std::initializer_list type. Create, push and return a new VAR_DECL
12527 for the initializer so that it will live as long as DECL. Any
12528 cleanup for the new variable is returned through CLEANUP, and the
12529 code to initialize the new variable is returned through INITP. */
12531 static tree
12532 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
12533 tree *initp, tree *cond_guard)
12535 tree init;
12536 tree type;
12537 tree var;
12539 /* Create the temporary variable. */
12540 type = TREE_TYPE (expr);
12541 var = make_temporary_var_for_ref_to_temp (decl, type);
12542 layout_decl (var, 0);
12543 /* If the rvalue is the result of a function call it will be
12544 a TARGET_EXPR. If it is some other construct (such as a
12545 member access expression where the underlying object is
12546 itself the result of a function call), turn it into a
12547 TARGET_EXPR here. It is important that EXPR be a
12548 TARGET_EXPR below since otherwise the INIT_EXPR will
12549 attempt to make a bitwise copy of EXPR to initialize
12550 VAR. */
12551 if (TREE_CODE (expr) != TARGET_EXPR)
12552 expr = get_target_expr (expr);
12553 else if (TREE_ADDRESSABLE (expr))
12554 TREE_ADDRESSABLE (var) = 1;
12556 if (TREE_CODE (decl) == FIELD_DECL
12557 && extra_warnings && !warning_suppressed_p (decl))
12559 warning (OPT_Wextra, "a temporary bound to %qD only persists "
12560 "until the constructor exits", decl);
12561 suppress_warning (decl);
12564 /* Recursively extend temps in this initializer. */
12565 TARGET_EXPR_INITIAL (expr)
12566 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
12567 cond_guard);
12569 /* Any reference temp has a non-trivial initializer. */
12570 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
12572 /* If the initializer is constant, put it in DECL_INITIAL so we get
12573 static initialization and use in constant expressions. */
12574 init = maybe_constant_init (expr);
12575 /* As in store_init_value. */
12576 init = cp_fully_fold (init);
12577 if (TREE_CONSTANT (init))
12579 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
12581 /* 5.19 says that a constant expression can include an
12582 lvalue-rvalue conversion applied to "a glvalue of literal type
12583 that refers to a non-volatile temporary object initialized
12584 with a constant expression". Rather than try to communicate
12585 that this VAR_DECL is a temporary, just mark it constexpr. */
12586 DECL_DECLARED_CONSTEXPR_P (var) = true;
12587 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
12588 TREE_CONSTANT (var) = true;
12589 TREE_READONLY (var) = true;
12591 DECL_INITIAL (var) = init;
12592 init = NULL_TREE;
12594 else
12595 /* Create the INIT_EXPR that will initialize the temporary
12596 variable. */
12597 init = split_nonconstant_init (var, expr);
12598 if (at_function_scope_p ())
12600 add_decl_expr (var);
12602 if (TREE_STATIC (var))
12603 init = add_stmt_to_compound (init, register_dtor_fn (var));
12604 else
12606 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
12607 if (cleanup)
12609 if (cond_guard && cleanup != error_mark_node)
12611 if (*cond_guard == NULL_TREE)
12613 *cond_guard = build_local_temp (boolean_type_node);
12614 add_decl_expr (*cond_guard);
12615 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
12616 *cond_guard, NOP_EXPR,
12617 boolean_false_node,
12618 tf_warning_or_error);
12619 finish_expr_stmt (set);
12621 cleanup = build3 (COND_EXPR, void_type_node,
12622 *cond_guard, cleanup, NULL_TREE);
12624 vec_safe_push (*cleanups, cleanup);
12628 /* We must be careful to destroy the temporary only
12629 after its initialization has taken place. If the
12630 initialization throws an exception, then the
12631 destructor should not be run. We cannot simply
12632 transform INIT into something like:
12634 (INIT, ({ CLEANUP_STMT; }))
12636 because emit_local_var always treats the
12637 initializer as a full-expression. Thus, the
12638 destructor would run too early; it would run at the
12639 end of initializing the reference variable, rather
12640 than at the end of the block enclosing the
12641 reference variable.
12643 The solution is to pass back a cleanup expression
12644 which the caller is responsible for attaching to
12645 the statement tree. */
12647 else
12649 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
12650 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
12652 if (CP_DECL_THREAD_LOCAL_P (var))
12653 tls_aggregates = tree_cons (NULL_TREE, var,
12654 tls_aggregates);
12655 else
12656 static_aggregates = tree_cons (NULL_TREE, var,
12657 static_aggregates);
12659 else
12660 /* Check whether the dtor is callable. */
12661 cxx_maybe_build_cleanup (var, tf_warning_or_error);
12663 /* Avoid -Wunused-variable warning (c++/38958). */
12664 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
12665 && VAR_P (decl))
12666 TREE_USED (decl) = DECL_READ_P (decl) = true;
12668 *initp = init;
12669 return var;
12672 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
12673 initializing a variable of that TYPE. */
12675 tree
12676 initialize_reference (tree type, tree expr,
12677 int flags, tsubst_flags_t complain)
12679 conversion *conv;
12680 void *p;
12681 location_t loc = cp_expr_loc_or_input_loc (expr);
12683 if (type == error_mark_node || error_operand_p (expr))
12684 return error_mark_node;
12686 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12687 p = conversion_obstack_alloc (0);
12689 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
12690 flags, complain);
12691 /* If this conversion failed, we're in C++20, and we have something like
12692 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
12693 if ((!conv || conv->bad_p)
12694 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
12696 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
12697 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
12698 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
12699 conversion *c = reference_binding (type, TREE_TYPE (e), e,
12700 /*c_cast_p=*/false, flags, complain);
12701 /* If this worked, use it. */
12702 if (c && !c->bad_p)
12703 expr = e, conv = c;
12705 if (!conv || conv->bad_p)
12707 if (complain & tf_error)
12709 if (conv)
12710 convert_like (conv, expr, complain);
12711 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
12712 && !TYPE_REF_IS_RVALUE (type)
12713 && !lvalue_p (expr))
12714 error_at (loc, "invalid initialization of non-const reference of "
12715 "type %qH from an rvalue of type %qI",
12716 type, TREE_TYPE (expr));
12717 else
12718 error_at (loc, "invalid initialization of reference of type "
12719 "%qH from expression of type %qI", type,
12720 TREE_TYPE (expr));
12722 return error_mark_node;
12725 if (conv->kind == ck_ref_bind)
12726 /* Perform the conversion. */
12727 expr = convert_like (conv, expr, complain);
12728 else if (conv->kind == ck_ambig)
12729 /* We gave an error in build_user_type_conversion_1. */
12730 expr = error_mark_node;
12731 else
12732 gcc_unreachable ();
12734 /* Free all the conversions we allocated. */
12735 obstack_free (&conversion_obstack, p);
12737 return expr;
12740 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
12741 gets used to initialize a reference. */
12743 static tree
12744 prevent_lifetime_extension (tree t)
12746 tree *p = &t;
12747 while (TREE_CODE (*p) == COMPOUND_EXPR)
12748 p = &TREE_OPERAND (*p, 1);
12749 while (handled_component_p (*p))
12750 p = &TREE_OPERAND (*p, 0);
12751 /* Change a TARGET_EXPR from prvalue to xvalue. */
12752 if (TREE_CODE (*p) == TARGET_EXPR)
12753 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
12754 move (TARGET_EXPR_SLOT (*p)));
12755 return t;
12758 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
12759 which is bound either to a reference or a std::initializer_list. */
12761 static tree
12762 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
12763 tree *cond_guard)
12765 tree sub = init;
12766 tree *p;
12767 STRIP_NOPS (sub);
12768 if (TREE_CODE (sub) == COMPOUND_EXPR)
12770 TREE_OPERAND (sub, 1)
12771 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
12772 cond_guard);
12773 return init;
12775 if (TREE_CODE (sub) == COND_EXPR)
12777 tree cur_cond_guard = NULL_TREE;
12778 if (TREE_OPERAND (sub, 1))
12779 TREE_OPERAND (sub, 1)
12780 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
12781 &cur_cond_guard);
12782 if (cur_cond_guard)
12784 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
12785 NOP_EXPR, boolean_true_node,
12786 tf_warning_or_error);
12787 TREE_OPERAND (sub, 1)
12788 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
12789 tf_warning_or_error);
12791 cur_cond_guard = NULL_TREE;
12792 if (TREE_OPERAND (sub, 2))
12793 TREE_OPERAND (sub, 2)
12794 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
12795 &cur_cond_guard);
12796 if (cur_cond_guard)
12798 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
12799 NOP_EXPR, boolean_true_node,
12800 tf_warning_or_error);
12801 TREE_OPERAND (sub, 2)
12802 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
12803 tf_warning_or_error);
12805 return init;
12807 if (TREE_CODE (sub) != ADDR_EXPR)
12808 return init;
12809 /* Deal with binding to a subobject. */
12810 for (p = &TREE_OPERAND (sub, 0);
12811 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
12812 p = &TREE_OPERAND (*p, 0);
12813 if (TREE_CODE (*p) == TARGET_EXPR)
12815 tree subinit = NULL_TREE;
12816 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
12817 recompute_tree_invariant_for_addr_expr (sub);
12818 if (init != sub)
12819 init = fold_convert (TREE_TYPE (init), sub);
12820 if (subinit)
12821 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
12823 return init;
12826 /* INIT is part of the initializer for DECL. If there are any
12827 reference or initializer lists being initialized, extend their
12828 lifetime to match that of DECL. */
12830 tree
12831 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
12832 tree *cond_guard)
12834 tree type = TREE_TYPE (init);
12835 if (processing_template_decl)
12836 return init;
12837 if (TYPE_REF_P (type))
12838 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
12839 else
12841 tree ctor = init;
12842 if (TREE_CODE (ctor) == TARGET_EXPR)
12843 ctor = TARGET_EXPR_INITIAL (ctor);
12844 if (TREE_CODE (ctor) == CONSTRUCTOR)
12846 /* [dcl.init] When initializing an aggregate from a parenthesized list
12847 of values... a temporary object bound to a reference does not have
12848 its lifetime extended. */
12849 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
12850 return init;
12852 if (is_std_init_list (type))
12854 /* The temporary array underlying a std::initializer_list
12855 is handled like a reference temporary. */
12856 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
12857 array = extend_ref_init_temps_1 (decl, array, cleanups,
12858 cond_guard);
12859 CONSTRUCTOR_ELT (ctor, 0)->value = array;
12861 else
12863 unsigned i;
12864 constructor_elt *p;
12865 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
12866 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
12867 p->value = extend_ref_init_temps (decl, p->value, cleanups,
12868 cond_guard);
12870 recompute_constructor_flags (ctor);
12871 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
12872 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
12876 return init;
12879 /* Returns true iff an initializer for TYPE could contain temporaries that
12880 need to be extended because they are bound to references or
12881 std::initializer_list. */
12883 bool
12884 type_has_extended_temps (tree type)
12886 type = strip_array_types (type);
12887 if (TYPE_REF_P (type))
12888 return true;
12889 if (CLASS_TYPE_P (type))
12891 if (is_std_init_list (type))
12892 return true;
12893 for (tree f = next_initializable_field (TYPE_FIELDS (type));
12894 f; f = next_initializable_field (DECL_CHAIN (f)))
12895 if (type_has_extended_temps (TREE_TYPE (f)))
12896 return true;
12898 return false;
12901 /* Returns true iff TYPE is some variant of std::initializer_list. */
12903 bool
12904 is_std_init_list (tree type)
12906 if (!TYPE_P (type))
12907 return false;
12908 if (cxx_dialect == cxx98)
12909 return false;
12910 /* Look through typedefs. */
12911 type = TYPE_MAIN_VARIANT (type);
12912 return (CLASS_TYPE_P (type)
12913 && CP_TYPE_CONTEXT (type) == std_node
12914 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
12917 /* Returns true iff DECL is a list constructor: i.e. a constructor which
12918 will accept an argument list of a single std::initializer_list<T>. */
12920 bool
12921 is_list_ctor (tree decl)
12923 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
12924 tree arg;
12926 if (!args || args == void_list_node)
12927 return false;
12929 arg = non_reference (TREE_VALUE (args));
12930 if (!is_std_init_list (arg))
12931 return false;
12933 args = TREE_CHAIN (args);
12935 if (args && args != void_list_node && !TREE_PURPOSE (args))
12936 /* There are more non-defaulted parms. */
12937 return false;
12939 return true;
12942 #include "gt-cp-call.h"