Merge branch 'vendor/GCC47'
[dragonfly.git] / contrib / gcc-4.7 / gcc / cp / call.c
1 /* Functions related to invoking methods and overloaded functions.
2    Copyright (C) 1987, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4    2010, 2011, 2012
5    Free Software Foundation, Inc.
6    Contributed by Michael Tiemann (tiemann@cygnus.com) and
7    modified by Brendan Kehoe (brendan@cygnus.com).
8
9 This file is part of GCC.
10
11 GCC is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3, or (at your option)
14 any later version.
15
16 GCC is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING3.  If not see
23 <http://www.gnu.org/licenses/>.  */
24
25
26 /* High-level class interface.  */
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "tree.h"
33 #include "cp-tree.h"
34 #include "output.h"
35 #include "flags.h"
36 #include "toplev.h"
37 #include "diagnostic-core.h"
38 #include "intl.h"
39 #include "target.h"
40 #include "convert.h"
41 #include "langhooks.h"
42 #include "c-family/c-objc.h"
43 #include "timevar.h"
44
45 /* The various kinds of conversion.  */
46
47 typedef enum conversion_kind {
48   ck_identity,
49   ck_lvalue,
50   ck_qual,
51   ck_std,
52   ck_ptr,
53   ck_pmem,
54   ck_base,
55   ck_ref_bind,
56   ck_user,
57   ck_ambig,
58   ck_list,
59   ck_aggr,
60   ck_rvalue
61 } conversion_kind;
62
63 /* The rank of the conversion.  Order of the enumerals matters; better
64    conversions should come earlier in the list.  */
65
66 typedef enum conversion_rank {
67   cr_identity,
68   cr_exact,
69   cr_promotion,
70   cr_std,
71   cr_pbool,
72   cr_user,
73   cr_ellipsis,
74   cr_bad
75 } conversion_rank;
76
77 /* An implicit conversion sequence, in the sense of [over.best.ics].
78    The first conversion to be performed is at the end of the chain.
79    That conversion is always a cr_identity conversion.  */
80
81 typedef struct conversion conversion;
82 struct conversion {
83   /* The kind of conversion represented by this step.  */
84   conversion_kind kind;
85   /* The rank of this conversion.  */
86   conversion_rank rank;
87   BOOL_BITFIELD user_conv_p : 1;
88   BOOL_BITFIELD ellipsis_p : 1;
89   BOOL_BITFIELD this_p : 1;
90   /* True if this conversion would be permitted with a bending of
91      language standards, e.g. disregarding pointer qualifiers or
92      converting integers to pointers.  */
93   BOOL_BITFIELD bad_p : 1;
94   /* If KIND is ck_ref_bind ck_base_conv, true to indicate that a
95      temporary should be created to hold the result of the
96      conversion.  */
97   BOOL_BITFIELD need_temporary_p : 1;
98   /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
99      from a pointer-to-derived to pointer-to-base is being performed.  */
100   BOOL_BITFIELD base_p : 1;
101   /* If KIND is ck_ref_bind, true when either an lvalue reference is
102      being bound to an lvalue expression or an rvalue reference is
103      being bound to an rvalue expression.  If KIND is ck_rvalue,
104      true when we should treat an lvalue as an rvalue (12.8p33).  If
105      KIND is ck_base, always false.  */
106   BOOL_BITFIELD rvaluedness_matches_p: 1;
107   BOOL_BITFIELD check_narrowing: 1;
108   /* The type of the expression resulting from the conversion.  */
109   tree type;
110   union {
111     /* The next conversion in the chain.  Since the conversions are
112        arranged from outermost to innermost, the NEXT conversion will
113        actually be performed before this conversion.  This variant is
114        used only when KIND is neither ck_identity, ck_ambig nor
115        ck_list.  Please use the next_conversion function instead
116        of using this field directly.  */
117     conversion *next;
118     /* The expression at the beginning of the conversion chain.  This
119        variant is used only if KIND is ck_identity or ck_ambig.  */
120     tree expr;
121     /* The array of conversions for an initializer_list, so this
122        variant is used only when KIN D is ck_list.  */
123     conversion **list;
124   } u;
125   /* The function candidate corresponding to this conversion
126      sequence.  This field is only used if KIND is ck_user.  */
127   struct z_candidate *cand;
128 };
129
130 #define CONVERSION_RANK(NODE)                   \
131   ((NODE)->bad_p ? cr_bad                       \
132    : (NODE)->ellipsis_p ? cr_ellipsis           \
133    : (NODE)->user_conv_p ? cr_user              \
134    : (NODE)->rank)
135
136 #define BAD_CONVERSION_RANK(NODE)               \
137   ((NODE)->ellipsis_p ? cr_ellipsis             \
138    : (NODE)->user_conv_p ? cr_user              \
139    : (NODE)->rank)
140
141 static struct obstack conversion_obstack;
142 static bool conversion_obstack_initialized;
143 struct rejection_reason;
144
145 static struct z_candidate * tourney (struct z_candidate *);
146 static int equal_functions (tree, tree);
147 static int joust (struct z_candidate *, struct z_candidate *, bool);
148 static int compare_ics (conversion *, conversion *);
149 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
150 static tree build_java_interface_fn_ref (tree, tree);
151 #define convert_like(CONV, EXPR, COMPLAIN)                      \
152   convert_like_real ((CONV), (EXPR), NULL_TREE, 0, 0,           \
153                      /*issue_conversion_warnings=*/true,        \
154                      /*c_cast_p=*/false, (COMPLAIN))
155 #define convert_like_with_context(CONV, EXPR, FN, ARGNO, COMPLAIN )     \
156   convert_like_real ((CONV), (EXPR), (FN), (ARGNO), 0,                  \
157                      /*issue_conversion_warnings=*/true,                \
158                      /*c_cast_p=*/false, (COMPLAIN))
159 static tree convert_like_real (conversion *, tree, tree, int, int, bool,
160                                bool, tsubst_flags_t);
161 static void op_error (enum tree_code, enum tree_code, tree, tree,
162                       tree, bool);
163 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int);
164 static void print_z_candidate (const char *, struct z_candidate *);
165 static void print_z_candidates (location_t, struct z_candidate *);
166 static tree build_this (tree);
167 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
168 static bool any_strictly_viable (struct z_candidate *);
169 static struct z_candidate *add_template_candidate
170         (struct z_candidate **, tree, tree, tree, tree, const VEC(tree,gc) *,
171          tree, tree, tree, int, unification_kind_t);
172 static struct z_candidate *add_template_candidate_real
173         (struct z_candidate **, tree, tree, tree, tree, const VEC(tree,gc) *,
174          tree, tree, tree, int, tree, unification_kind_t);
175 static struct z_candidate *add_template_conv_candidate
176         (struct z_candidate **, tree, tree, tree, const VEC(tree,gc) *, tree,
177          tree, tree);
178 static void add_builtin_candidates
179         (struct z_candidate **, enum tree_code, enum tree_code,
180          tree, tree *, int);
181 static void add_builtin_candidate
182         (struct z_candidate **, enum tree_code, enum tree_code,
183          tree, tree, tree, tree *, tree *, int);
184 static bool is_complete (tree);
185 static void build_builtin_candidate
186         (struct z_candidate **, tree, tree, tree, tree *, tree *,
187          int);
188 static struct z_candidate *add_conv_candidate
189         (struct z_candidate **, tree, tree, tree, const VEC(tree,gc) *, tree,
190          tree);
191 static struct z_candidate *add_function_candidate
192         (struct z_candidate **, tree, tree, tree, const VEC(tree,gc) *, tree,
193          tree, int);
194 static conversion *implicit_conversion (tree, tree, tree, bool, int);
195 static conversion *standard_conversion (tree, tree, tree, bool, int);
196 static conversion *reference_binding (tree, tree, tree, bool, int);
197 static conversion *build_conv (conversion_kind, tree, conversion *);
198 static conversion *build_list_conv (tree, tree, int);
199 static conversion *next_conversion (conversion *);
200 static bool is_subseq (conversion *, conversion *);
201 static conversion *maybe_handle_ref_bind (conversion **);
202 static void maybe_handle_implicit_object (conversion **);
203 static struct z_candidate *add_candidate
204         (struct z_candidate **, tree, tree, const VEC(tree,gc) *, size_t,
205          conversion **, tree, tree, int, struct rejection_reason *);
206 static tree source_type (conversion *);
207 static void add_warning (struct z_candidate *, struct z_candidate *);
208 static bool reference_compatible_p (tree, tree);
209 static conversion *direct_reference_binding (tree, conversion *);
210 static bool promoted_arithmetic_type_p (tree);
211 static conversion *conditional_conversion (tree, tree);
212 static char *name_as_c_string (tree, tree, bool *);
213 static tree prep_operand (tree);
214 static void add_candidates (tree, tree, const VEC(tree,gc) *, tree, tree, bool,
215                             tree, tree, int, struct z_candidate **);
216 static conversion *merge_conversion_sequences (conversion *, conversion *);
217 static bool magic_varargs_p (tree);
218 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
219
220 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
221    NAME can take many forms...  */
222
223 bool
224 check_dtor_name (tree basetype, tree name)
225 {
226   /* Just accept something we've already complained about.  */
227   if (name == error_mark_node)
228     return true;
229
230   if (TREE_CODE (name) == TYPE_DECL)
231     name = TREE_TYPE (name);
232   else if (TYPE_P (name))
233     /* OK */;
234   else if (TREE_CODE (name) == IDENTIFIER_NODE)
235     {
236       if ((MAYBE_CLASS_TYPE_P (basetype)
237            && name == constructor_name (basetype))
238           || (TREE_CODE (basetype) == ENUMERAL_TYPE
239               && name == TYPE_IDENTIFIER (basetype)))
240         return true;
241       else
242         name = get_type_value (name);
243     }
244   else
245     {
246       /* In the case of:
247
248          template <class T> struct S { ~S(); };
249          int i;
250          i.~S();
251
252          NAME will be a class template.  */
253       gcc_assert (DECL_CLASS_TEMPLATE_P (name));
254       return false;
255     }
256
257   if (!name || name == error_mark_node)
258     return false;
259   return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
260 }
261
262 /* We want the address of a function or method.  We avoid creating a
263    pointer-to-member function.  */
264
265 tree
266 build_addr_func (tree function)
267 {
268   tree type = TREE_TYPE (function);
269
270   /* We have to do these by hand to avoid real pointer to member
271      functions.  */
272   if (TREE_CODE (type) == METHOD_TYPE)
273     {
274       if (TREE_CODE (function) == OFFSET_REF)
275         {
276           tree object = build_address (TREE_OPERAND (function, 0));
277           return get_member_function_from_ptrfunc (&object,
278                                                    TREE_OPERAND (function, 1));
279         }
280       function = build_address (function);
281     }
282   else
283     function = decay_conversion (function);
284
285   return function;
286 }
287
288 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
289    POINTER_TYPE to those.  Note, pointer to member function types
290    (TYPE_PTRMEMFUNC_P) must be handled by our callers.  There are
291    two variants.  build_call_a is the primitive taking an array of
292    arguments, while build_call_n is a wrapper that handles varargs.  */
293
294 tree
295 build_call_n (tree function, int n, ...)
296 {
297   if (n == 0)
298     return build_call_a (function, 0, NULL);
299   else
300     {
301       tree *argarray = XALLOCAVEC (tree, n);
302       va_list ap;
303       int i;
304
305       va_start (ap, n);
306       for (i = 0; i < n; i++)
307         argarray[i] = va_arg (ap, tree);
308       va_end (ap);
309       return build_call_a (function, n, argarray);
310     }
311 }
312
313 /* Update various flags in cfun and the call itself based on what is being
314    called.  Split out of build_call_a so that bot_manip can use it too.  */
315
316 void
317 set_flags_from_callee (tree call)
318 {
319   int nothrow;
320   tree decl = get_callee_fndecl (call);
321
322   /* We check both the decl and the type; a function may be known not to
323      throw without being declared throw().  */
324   nothrow = ((decl && TREE_NOTHROW (decl))
325              || TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (call)))));
326
327   if (!nothrow && at_function_scope_p () && cfun && cp_function_chain)
328     cp_function_chain->can_throw = 1;
329
330   if (decl && TREE_THIS_VOLATILE (decl) && cfun && cp_function_chain)
331     current_function_returns_abnormally = 1;
332
333   TREE_NOTHROW (call) = nothrow;
334 }
335
336 tree
337 build_call_a (tree function, int n, tree *argarray)
338 {
339   tree decl;
340   tree result_type;
341   tree fntype;
342   int i;
343
344   function = build_addr_func (function);
345
346   gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
347   fntype = TREE_TYPE (TREE_TYPE (function));
348   gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
349               || TREE_CODE (fntype) == METHOD_TYPE);
350   result_type = TREE_TYPE (fntype);
351   /* An rvalue has no cv-qualifiers.  */
352   if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
353     result_type = cv_unqualified (result_type);
354
355   function = build_call_array_loc (input_location,
356                                    result_type, function, n, argarray);
357   set_flags_from_callee (function);
358
359   decl = get_callee_fndecl (function);
360
361   if (decl && !TREE_USED (decl))
362     {
363       /* We invoke build_call directly for several library
364          functions.  These may have been declared normally if
365          we're building libgcc, so we can't just check
366          DECL_ARTIFICIAL.  */
367       gcc_assert (DECL_ARTIFICIAL (decl)
368                   || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
369                                "__", 2));
370       mark_used (decl);
371     }
372
373   if (decl && TREE_DEPRECATED (decl))
374     warn_deprecated_use (decl, NULL_TREE);
375   require_complete_eh_spec_types (fntype, decl);
376
377   TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
378
379   /* Don't pass empty class objects by value.  This is useful
380      for tags in STL, which are used to control overload resolution.
381      We don't need to handle other cases of copying empty classes.  */
382   if (! decl || ! DECL_BUILT_IN (decl))
383     for (i = 0; i < n; i++)
384       {
385         tree arg = CALL_EXPR_ARG (function, i);
386         if (is_empty_class (TREE_TYPE (arg))
387             && ! TREE_ADDRESSABLE (TREE_TYPE (arg)))
388           {
389             tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
390             arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
391             CALL_EXPR_ARG (function, i) = arg;
392           }
393       }
394
395   return function;
396 }
397
398 /* Build something of the form ptr->method (args)
399    or object.method (args).  This can also build
400    calls to constructors, and find friends.
401
402    Member functions always take their class variable
403    as a pointer.
404
405    INSTANCE is a class instance.
406
407    NAME is the name of the method desired, usually an IDENTIFIER_NODE.
408
409    PARMS help to figure out what that NAME really refers to.
410
411    BASETYPE_PATH, if non-NULL, contains a chain from the type of INSTANCE
412    down to the real instance type to use for access checking.  We need this
413    information to get protected accesses correct.
414
415    FLAGS is the logical disjunction of zero or more LOOKUP_
416    flags.  See cp-tree.h for more info.
417
418    If this is all OK, calls build_function_call with the resolved
419    member function.
420
421    This function must also handle being called to perform
422    initialization, promotion/coercion of arguments, and
423    instantiation of default parameters.
424
425    Note that NAME may refer to an instance variable name.  If
426    `operator()()' is defined for the type of that field, then we return
427    that result.  */
428
429 /* New overloading code.  */
430
431 typedef struct z_candidate z_candidate;
432
433 typedef struct candidate_warning candidate_warning;
434 struct candidate_warning {
435   z_candidate *loser;
436   candidate_warning *next;
437 };
438
439 /* Information for providing diagnostics about why overloading failed.  */
440
441 enum rejection_reason_code {
442   rr_none,
443   rr_arity,
444   rr_explicit_conversion,
445   rr_template_conversion,
446   rr_arg_conversion,
447   rr_bad_arg_conversion,
448   rr_template_unification,
449   rr_template_instantiation,
450   rr_invalid_copy
451 };
452
453 struct conversion_info {
454   /* The index of the argument, 0-based.  */
455   int n_arg;
456   /* The type of the actual argument.  */
457   tree from_type;
458   /* The type of the formal argument.  */
459   tree to_type;
460 };
461   
462 struct rejection_reason {
463   enum rejection_reason_code code;
464   union {
465     /* Information about an arity mismatch.  */
466     struct {
467       /* The expected number of arguments.  */
468       int expected;
469       /* The actual number of arguments in the call.  */
470       int actual;
471       /* Whether the call was a varargs call.  */
472       bool call_varargs_p;
473     } arity;
474     /* Information about an argument conversion mismatch.  */
475     struct conversion_info conversion;
476     /* Same, but for bad argument conversions.  */
477     struct conversion_info bad_conversion;
478     /* Information about template unification failures.  These are the
479        parameters passed to fn_type_unification.  */
480     struct {
481       tree tmpl;
482       tree explicit_targs;
483       tree targs;
484       const tree *args;
485       unsigned int nargs;
486       tree return_type;
487       unification_kind_t strict;
488       int flags;
489     } template_unification;
490     /* Information about template instantiation failures.  These are the
491        parameters passed to instantiate_template.  */
492     struct {
493       tree tmpl;
494       tree targs;
495     } template_instantiation;
496   } u;
497 };
498
499 struct z_candidate {
500   /* The FUNCTION_DECL that will be called if this candidate is
501      selected by overload resolution.  */
502   tree fn;
503   /* If not NULL_TREE, the first argument to use when calling this
504      function.  */
505   tree first_arg;
506   /* The rest of the arguments to use when calling this function.  If
507      there are no further arguments this may be NULL or it may be an
508      empty vector.  */
509   const VEC(tree,gc) *args;
510   /* The implicit conversion sequences for each of the arguments to
511      FN.  */
512   conversion **convs;
513   /* The number of implicit conversion sequences.  */
514   size_t num_convs;
515   /* If FN is a user-defined conversion, the standard conversion
516      sequence from the type returned by FN to the desired destination
517      type.  */
518   conversion *second_conv;
519   int viable;
520   struct rejection_reason *reason;
521   /* If FN is a member function, the binfo indicating the path used to
522      qualify the name of FN at the call site.  This path is used to
523      determine whether or not FN is accessible if it is selected by
524      overload resolution.  The DECL_CONTEXT of FN will always be a
525      (possibly improper) base of this binfo.  */
526   tree access_path;
527   /* If FN is a non-static member function, the binfo indicating the
528      subobject to which the `this' pointer should be converted if FN
529      is selected by overload resolution.  The type pointed to by
530      the `this' pointer must correspond to the most derived class
531      indicated by the CONVERSION_PATH.  */
532   tree conversion_path;
533   tree template_decl;
534   tree explicit_targs;
535   candidate_warning *warnings;
536   z_candidate *next;
537 };
538
539 /* Returns true iff T is a null pointer constant in the sense of
540    [conv.ptr].  */
541
542 bool
543 null_ptr_cst_p (tree t)
544 {
545   /* [conv.ptr]
546
547      A null pointer constant is an integral constant expression
548      (_expr.const_) rvalue of integer type that evaluates to zero or
549      an rvalue of type std::nullptr_t. */
550   if (NULLPTR_TYPE_P (TREE_TYPE (t)))
551     return true;
552   if (CP_INTEGRAL_TYPE_P (TREE_TYPE (t)))
553     {
554       /* Core issue 903 says only literal 0 is a null pointer constant.  */
555       if (cxx_dialect < cxx0x)
556         t = integral_constant_value (t);
557       STRIP_NOPS (t);
558       if (integer_zerop (t) && !TREE_OVERFLOW (t))
559         return true;
560     }
561   return false;
562 }
563
564 /* Returns true iff T is a null member pointer value (4.11).  */
565
566 bool
567 null_member_pointer_value_p (tree t)
568 {
569   tree type = TREE_TYPE (t);
570   if (!type)
571     return false;
572   else if (TYPE_PTRMEMFUNC_P (type))
573     return (TREE_CODE (t) == CONSTRUCTOR
574             && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
575   else if (TYPE_PTRMEM_P (type))
576     return integer_all_onesp (t);
577   else
578     return false;
579 }
580
581 /* Returns nonzero if PARMLIST consists of only default parms,
582    ellipsis, and/or undeduced parameter packs.  */
583
584 bool
585 sufficient_parms_p (const_tree parmlist)
586 {
587   for (; parmlist && parmlist != void_list_node;
588        parmlist = TREE_CHAIN (parmlist))
589     if (!TREE_PURPOSE (parmlist)
590         && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
591       return false;
592   return true;
593 }
594
595 /* Allocate N bytes of memory from the conversion obstack.  The memory
596    is zeroed before being returned.  */
597
598 static void *
599 conversion_obstack_alloc (size_t n)
600 {
601   void *p;
602   if (!conversion_obstack_initialized)
603     {
604       gcc_obstack_init (&conversion_obstack);
605       conversion_obstack_initialized = true;
606     }
607   p = obstack_alloc (&conversion_obstack, n);
608   memset (p, 0, n);
609   return p;
610 }
611
612 /* Allocate rejection reasons.  */
613
614 static struct rejection_reason *
615 alloc_rejection (enum rejection_reason_code code)
616 {
617   struct rejection_reason *p;
618   p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
619   p->code = code;
620   return p;
621 }
622
623 static struct rejection_reason *
624 arity_rejection (tree first_arg, int expected, int actual)
625 {
626   struct rejection_reason *r = alloc_rejection (rr_arity);
627   int adjust = first_arg != NULL_TREE;
628   r->u.arity.expected = expected - adjust;
629   r->u.arity.actual = actual - adjust;
630   return r;
631 }
632
633 static struct rejection_reason *
634 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to)
635 {
636   struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
637   int adjust = first_arg != NULL_TREE;
638   r->u.conversion.n_arg = n_arg - adjust;
639   r->u.conversion.from_type = from;
640   r->u.conversion.to_type = to;
641   return r;
642 }
643
644 static struct rejection_reason *
645 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to)
646 {
647   struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
648   int adjust = first_arg != NULL_TREE;
649   r->u.bad_conversion.n_arg = n_arg - adjust;
650   r->u.bad_conversion.from_type = from;
651   r->u.bad_conversion.to_type = to;
652   return r;
653 }
654
655 static struct rejection_reason *
656 explicit_conversion_rejection (tree from, tree to)
657 {
658   struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
659   r->u.conversion.n_arg = 0;
660   r->u.conversion.from_type = from;
661   r->u.conversion.to_type = to;
662   return r;
663 }
664
665 static struct rejection_reason *
666 template_conversion_rejection (tree from, tree to)
667 {
668   struct rejection_reason *r = alloc_rejection (rr_template_conversion);
669   r->u.conversion.n_arg = 0;
670   r->u.conversion.from_type = from;
671   r->u.conversion.to_type = to;
672   return r;
673 }
674
675 static struct rejection_reason *
676 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
677                                 const tree *args, unsigned int nargs,
678                                 tree return_type, unification_kind_t strict,
679                                 int flags)
680 {
681   size_t args_n_bytes = sizeof (*args) * nargs;
682   tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
683   struct rejection_reason *r = alloc_rejection (rr_template_unification);
684   r->u.template_unification.tmpl = tmpl;
685   r->u.template_unification.explicit_targs = explicit_targs;
686   r->u.template_unification.targs = targs;
687   /* Copy args to our own storage.  */
688   memcpy (args1, args, args_n_bytes);
689   r->u.template_unification.args = args1;
690   r->u.template_unification.nargs = nargs;
691   r->u.template_unification.return_type = return_type;
692   r->u.template_unification.strict = strict;
693   r->u.template_unification.flags = flags;
694   return r;
695 }
696
697 static struct rejection_reason *
698 template_unification_error_rejection (void)
699 {
700   return alloc_rejection (rr_template_unification);
701 }
702
703 static struct rejection_reason *
704 template_instantiation_rejection (tree tmpl, tree targs)
705 {
706   struct rejection_reason *r = alloc_rejection (rr_template_instantiation);
707   r->u.template_instantiation.tmpl = tmpl;
708   r->u.template_instantiation.targs = targs;
709   return r;
710 }
711
712 static struct rejection_reason *
713 invalid_copy_with_fn_template_rejection (void)
714 {
715   struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
716   return r;
717 }
718
719 /* Dynamically allocate a conversion.  */
720
721 static conversion *
722 alloc_conversion (conversion_kind kind)
723 {
724   conversion *c;
725   c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
726   c->kind = kind;
727   return c;
728 }
729
730 #ifdef ENABLE_CHECKING
731
732 /* Make sure that all memory on the conversion obstack has been
733    freed.  */
734
735 void
736 validate_conversion_obstack (void)
737 {
738   if (conversion_obstack_initialized)
739     gcc_assert ((obstack_next_free (&conversion_obstack)
740                  == obstack_base (&conversion_obstack)));
741 }
742
743 #endif /* ENABLE_CHECKING */
744
745 /* Dynamically allocate an array of N conversions.  */
746
747 static conversion **
748 alloc_conversions (size_t n)
749 {
750   return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
751 }
752
753 static conversion *
754 build_conv (conversion_kind code, tree type, conversion *from)
755 {
756   conversion *t;
757   conversion_rank rank = CONVERSION_RANK (from);
758
759   /* Note that the caller is responsible for filling in t->cand for
760      user-defined conversions.  */
761   t = alloc_conversion (code);
762   t->type = type;
763   t->u.next = from;
764
765   switch (code)
766     {
767     case ck_ptr:
768     case ck_pmem:
769     case ck_base:
770     case ck_std:
771       if (rank < cr_std)
772         rank = cr_std;
773       break;
774
775     case ck_qual:
776       if (rank < cr_exact)
777         rank = cr_exact;
778       break;
779
780     default:
781       break;
782     }
783   t->rank = rank;
784   t->user_conv_p = (code == ck_user || from->user_conv_p);
785   t->bad_p = from->bad_p;
786   t->base_p = false;
787   return t;
788 }
789
790 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
791    specialization of std::initializer_list<T>, if such a conversion is
792    possible.  */
793
794 static conversion *
795 build_list_conv (tree type, tree ctor, int flags)
796 {
797   tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
798   unsigned len = CONSTRUCTOR_NELTS (ctor);
799   conversion **subconvs = alloc_conversions (len);
800   conversion *t;
801   unsigned i;
802   tree val;
803
804   /* Within a list-initialization we can have more user-defined
805      conversions.  */
806   flags &= ~LOOKUP_NO_CONVERSION;
807   /* But no narrowing conversions.  */
808   flags |= LOOKUP_NO_NARROWING;
809
810   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
811     {
812       conversion *sub
813         = implicit_conversion (elttype, TREE_TYPE (val), val,
814                                false, flags);
815       if (sub == NULL)
816         return NULL;
817
818       subconvs[i] = sub;
819     }
820
821   t = alloc_conversion (ck_list);
822   t->type = type;
823   t->u.list = subconvs;
824   t->rank = cr_exact;
825
826   for (i = 0; i < len; ++i)
827     {
828       conversion *sub = subconvs[i];
829       if (sub->rank > t->rank)
830         t->rank = sub->rank;
831       if (sub->user_conv_p)
832         t->user_conv_p = true;
833       if (sub->bad_p)
834         t->bad_p = true;
835     }
836
837   return t;
838 }
839
840 /* Return the next conversion of the conversion chain (if applicable),
841    or NULL otherwise.  Please use this function instead of directly
842    accessing fields of struct conversion.  */
843
844 static conversion *
845 next_conversion (conversion *conv)
846 {
847   if (conv == NULL
848       || conv->kind == ck_identity
849       || conv->kind == ck_ambig
850       || conv->kind == ck_list)
851     return NULL;
852   return conv->u.next;
853 }
854
855 /* Subroutine of build_aggr_conv: check whether CTOR, a braced-init-list,
856    is a valid aggregate initializer for array type ATYPE.  */
857
858 static bool
859 can_convert_array (tree atype, tree ctor, int flags)
860 {
861   unsigned i;
862   tree elttype = TREE_TYPE (atype);
863   for (i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
864     {
865       tree val = CONSTRUCTOR_ELT (ctor, i)->value;
866       bool ok;
867       if (TREE_CODE (elttype) == ARRAY_TYPE
868           && TREE_CODE (val) == CONSTRUCTOR)
869         ok = can_convert_array (elttype, val, flags);
870       else
871         ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags);
872       if (!ok)
873         return false;
874     }
875   return true;
876 }
877
878 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
879    aggregate class, if such a conversion is possible.  */
880
881 static conversion *
882 build_aggr_conv (tree type, tree ctor, int flags)
883 {
884   unsigned HOST_WIDE_INT i = 0;
885   conversion *c;
886   tree field = next_initializable_field (TYPE_FIELDS (type));
887   tree empty_ctor = NULL_TREE;
888
889   for (; field; field = next_initializable_field (DECL_CHAIN (field)))
890     {
891       tree ftype = TREE_TYPE (field);
892       tree val;
893       bool ok;
894
895       if (i < CONSTRUCTOR_NELTS (ctor))
896         val = CONSTRUCTOR_ELT (ctor, i)->value;
897       else if (TREE_CODE (ftype) == REFERENCE_TYPE)
898         /* Value-initialization of reference is ill-formed.  */
899         return NULL;
900       else
901         {
902           if (empty_ctor == NULL_TREE)
903             empty_ctor = build_constructor (init_list_type_node, NULL);
904           val = empty_ctor;
905         }
906       ++i;
907
908       if (TREE_CODE (ftype) == ARRAY_TYPE
909           && TREE_CODE (val) == CONSTRUCTOR)
910         ok = can_convert_array (ftype, val, flags);
911       else
912         ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags);
913
914       if (!ok)
915         return NULL;
916
917       if (TREE_CODE (type) == UNION_TYPE)
918         break;
919     }
920
921   if (i < CONSTRUCTOR_NELTS (ctor))
922     return NULL;
923
924   c = alloc_conversion (ck_aggr);
925   c->type = type;
926   c->rank = cr_exact;
927   c->user_conv_p = true;
928   c->u.next = NULL;
929   return c;
930 }
931
932 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
933    array type, if such a conversion is possible.  */
934
935 static conversion *
936 build_array_conv (tree type, tree ctor, int flags)
937 {
938   conversion *c;
939   unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
940   tree elttype = TREE_TYPE (type);
941   unsigned i;
942   tree val;
943   bool bad = false;
944   bool user = false;
945   enum conversion_rank rank = cr_exact;
946
947   if (TYPE_DOMAIN (type))
948     {
949       unsigned HOST_WIDE_INT alen = tree_low_cst (array_type_nelts_top (type), 1);
950       if (alen < len)
951         return NULL;
952     }
953
954   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
955     {
956       conversion *sub
957         = implicit_conversion (elttype, TREE_TYPE (val), val,
958                                false, flags);
959       if (sub == NULL)
960         return NULL;
961
962       if (sub->rank > rank)
963         rank = sub->rank;
964       if (sub->user_conv_p)
965         user = true;
966       if (sub->bad_p)
967         bad = true;
968     }
969
970   c = alloc_conversion (ck_aggr);
971   c->type = type;
972   c->rank = rank;
973   c->user_conv_p = user;
974   c->bad_p = bad;
975   c->u.next = NULL;
976   return c;
977 }
978
979 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
980    complex type, if such a conversion is possible.  */
981
982 static conversion *
983 build_complex_conv (tree type, tree ctor, int flags)
984 {
985   conversion *c;
986   unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
987   tree elttype = TREE_TYPE (type);
988   unsigned i;
989   tree val;
990   bool bad = false;
991   bool user = false;
992   enum conversion_rank rank = cr_exact;
993
994   if (len != 2)
995     return NULL;
996
997   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
998     {
999       conversion *sub
1000         = implicit_conversion (elttype, TREE_TYPE (val), val,
1001                                false, flags);
1002       if (sub == NULL)
1003         return NULL;
1004
1005       if (sub->rank > rank)
1006         rank = sub->rank;
1007       if (sub->user_conv_p)
1008         user = true;
1009       if (sub->bad_p)
1010         bad = true;
1011     }
1012
1013   c = alloc_conversion (ck_aggr);
1014   c->type = type;
1015   c->rank = rank;
1016   c->user_conv_p = user;
1017   c->bad_p = bad;
1018   c->u.next = NULL;
1019   return c;
1020 }
1021
1022 /* Build a representation of the identity conversion from EXPR to
1023    itself.  The TYPE should match the type of EXPR, if EXPR is non-NULL.  */
1024
1025 static conversion *
1026 build_identity_conv (tree type, tree expr)
1027 {
1028   conversion *c;
1029
1030   c = alloc_conversion (ck_identity);
1031   c->type = type;
1032   c->u.expr = expr;
1033
1034   return c;
1035 }
1036
1037 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1038    were multiple user-defined conversions to accomplish the job.
1039    Build a conversion that indicates that ambiguity.  */
1040
1041 static conversion *
1042 build_ambiguous_conv (tree type, tree expr)
1043 {
1044   conversion *c;
1045
1046   c = alloc_conversion (ck_ambig);
1047   c->type = type;
1048   c->u.expr = expr;
1049
1050   return c;
1051 }
1052
1053 tree
1054 strip_top_quals (tree t)
1055 {
1056   if (TREE_CODE (t) == ARRAY_TYPE)
1057     return t;
1058   return cp_build_qualified_type (t, 0);
1059 }
1060
1061 /* Returns the standard conversion path (see [conv]) from type FROM to type
1062    TO, if any.  For proper handling of null pointer constants, you must
1063    also pass the expression EXPR to convert from.  If C_CAST_P is true,
1064    this conversion is coming from a C-style cast.  */
1065
1066 static conversion *
1067 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1068                      int flags)
1069 {
1070   enum tree_code fcode, tcode;
1071   conversion *conv;
1072   bool fromref = false;
1073   tree qualified_to;
1074
1075   to = non_reference (to);
1076   if (TREE_CODE (from) == REFERENCE_TYPE)
1077     {
1078       fromref = true;
1079       from = TREE_TYPE (from);
1080     }
1081   qualified_to = to;
1082   to = strip_top_quals (to);
1083   from = strip_top_quals (from);
1084
1085   if ((TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1086       && expr && type_unknown_p (expr))
1087     {
1088       tsubst_flags_t tflags = tf_conv;
1089       if (!(flags & LOOKUP_PROTECT))
1090         tflags |= tf_no_access_control;
1091       expr = instantiate_type (to, expr, tflags);
1092       if (expr == error_mark_node)
1093         return NULL;
1094       from = TREE_TYPE (expr);
1095     }
1096
1097   fcode = TREE_CODE (from);
1098   tcode = TREE_CODE (to);
1099
1100   conv = build_identity_conv (from, expr);
1101   if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1102     {
1103       from = type_decays_to (from);
1104       fcode = TREE_CODE (from);
1105       conv = build_conv (ck_lvalue, from, conv);
1106     }
1107   else if (fromref || (expr && lvalue_p (expr)))
1108     {
1109       if (expr)
1110         {
1111           tree bitfield_type;
1112           bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1113           if (bitfield_type)
1114             {
1115               from = strip_top_quals (bitfield_type);
1116               fcode = TREE_CODE (from);
1117             }
1118         }
1119       conv = build_conv (ck_rvalue, from, conv);
1120       if (flags & LOOKUP_PREFER_RVALUE)
1121         conv->rvaluedness_matches_p = true;
1122     }
1123
1124    /* Allow conversion between `__complex__' data types.  */
1125   if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1126     {
1127       /* The standard conversion sequence to convert FROM to TO is
1128          the standard conversion sequence to perform componentwise
1129          conversion.  */
1130       conversion *part_conv = standard_conversion
1131         (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags);
1132
1133       if (part_conv)
1134         {
1135           conv = build_conv (part_conv->kind, to, conv);
1136           conv->rank = part_conv->rank;
1137         }
1138       else
1139         conv = NULL;
1140
1141       return conv;
1142     }
1143
1144   if (same_type_p (from, to))
1145     {
1146       if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1147         conv->type = qualified_to;
1148       return conv;
1149     }
1150
1151   /* [conv.ptr]
1152      A null pointer constant can be converted to a pointer type; ... A
1153      null pointer constant of integral type can be converted to an
1154      rvalue of type std::nullptr_t. */
1155   if ((tcode == POINTER_TYPE || TYPE_PTR_TO_MEMBER_P (to)
1156        || NULLPTR_TYPE_P (to))
1157       && expr && null_ptr_cst_p (expr))
1158     conv = build_conv (ck_std, to, conv);
1159   else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1160            || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1161     {
1162       /* For backwards brain damage compatibility, allow interconversion of
1163          pointers and integers with a pedwarn.  */
1164       conv = build_conv (ck_std, to, conv);
1165       conv->bad_p = true;
1166     }
1167   else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1168     {
1169       /* For backwards brain damage compatibility, allow interconversion of
1170          enums and integers with a pedwarn.  */
1171       conv = build_conv (ck_std, to, conv);
1172       conv->bad_p = true;
1173     }
1174   else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1175            || (TYPE_PTRMEM_P (to) && TYPE_PTRMEM_P (from)))
1176     {
1177       tree to_pointee;
1178       tree from_pointee;
1179
1180       if (tcode == POINTER_TYPE
1181           && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (from),
1182                                                         TREE_TYPE (to)))
1183         ;
1184       else if (VOID_TYPE_P (TREE_TYPE (to))
1185                && !TYPE_PTRMEM_P (from)
1186                && TREE_CODE (TREE_TYPE (from)) != FUNCTION_TYPE)
1187         {
1188           tree nfrom = TREE_TYPE (from);
1189           from = build_pointer_type
1190             (cp_build_qualified_type (void_type_node, 
1191                                       cp_type_quals (nfrom)));
1192           conv = build_conv (ck_ptr, from, conv);
1193         }
1194       else if (TYPE_PTRMEM_P (from))
1195         {
1196           tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1197           tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1198
1199           if (DERIVED_FROM_P (fbase, tbase)
1200               && (same_type_ignoring_top_level_qualifiers_p
1201                   (TYPE_PTRMEM_POINTED_TO_TYPE (from),
1202                    TYPE_PTRMEM_POINTED_TO_TYPE (to))))
1203             {
1204               from = build_ptrmem_type (tbase,
1205                                         TYPE_PTRMEM_POINTED_TO_TYPE (from));
1206               conv = build_conv (ck_pmem, from, conv);
1207             }
1208           else if (!same_type_p (fbase, tbase))
1209             return NULL;
1210         }
1211       else if (CLASS_TYPE_P (TREE_TYPE (from))
1212                && CLASS_TYPE_P (TREE_TYPE (to))
1213                /* [conv.ptr]
1214
1215                   An rvalue of type "pointer to cv D," where D is a
1216                   class type, can be converted to an rvalue of type
1217                   "pointer to cv B," where B is a base class (clause
1218                   _class.derived_) of D.  If B is an inaccessible
1219                   (clause _class.access_) or ambiguous
1220                   (_class.member.lookup_) base class of D, a program
1221                   that necessitates this conversion is ill-formed.
1222                   Therefore, we use DERIVED_FROM_P, and do not check
1223                   access or uniqueness.  */
1224                && DERIVED_FROM_P (TREE_TYPE (to), TREE_TYPE (from)))
1225         {
1226           from =
1227             cp_build_qualified_type (TREE_TYPE (to),
1228                                      cp_type_quals (TREE_TYPE (from)));
1229           from = build_pointer_type (from);
1230           conv = build_conv (ck_ptr, from, conv);
1231           conv->base_p = true;
1232         }
1233
1234       if (tcode == POINTER_TYPE)
1235         {
1236           to_pointee = TREE_TYPE (to);
1237           from_pointee = TREE_TYPE (from);
1238         }
1239       else
1240         {
1241           to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1242           from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1243         }
1244
1245       if (same_type_p (from, to))
1246         /* OK */;
1247       else if (c_cast_p && comp_ptr_ttypes_const (to, from))
1248         /* In a C-style cast, we ignore CV-qualification because we
1249            are allowed to perform a static_cast followed by a
1250            const_cast.  */
1251         conv = build_conv (ck_qual, to, conv);
1252       else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1253         conv = build_conv (ck_qual, to, conv);
1254       else if (expr && string_conv_p (to, expr, 0))
1255         /* converting from string constant to char *.  */
1256         conv = build_conv (ck_qual, to, conv);
1257       /* Allow conversions among compatible ObjC pointer types (base
1258          conversions have been already handled above).  */
1259       else if (c_dialect_objc ()
1260                && objc_compare_types (to, from, -4, NULL_TREE))
1261         conv = build_conv (ck_ptr, to, conv);
1262       else if (ptr_reasonably_similar (to_pointee, from_pointee))
1263         {
1264           conv = build_conv (ck_ptr, to, conv);
1265           conv->bad_p = true;
1266         }
1267       else
1268         return NULL;
1269
1270       from = to;
1271     }
1272   else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1273     {
1274       tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1275       tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1276       tree fbase = class_of_this_parm (fromfn);
1277       tree tbase = class_of_this_parm (tofn);
1278
1279       if (!DERIVED_FROM_P (fbase, tbase)
1280           || !same_type_p (static_fn_type (fromfn),
1281                            static_fn_type (tofn)))
1282         return NULL;
1283
1284       from = build_memfn_type (fromfn, tbase, cp_type_quals (tbase));
1285       from = build_ptrmemfunc_type (build_pointer_type (from));
1286       conv = build_conv (ck_pmem, from, conv);
1287       conv->base_p = true;
1288     }
1289   else if (tcode == BOOLEAN_TYPE)
1290     {
1291       /* [conv.bool]
1292
1293           An rvalue of arithmetic, unscoped enumeration, pointer, or
1294           pointer to member type can be converted to an rvalue of type
1295           bool. ... An rvalue of type std::nullptr_t can be converted
1296           to an rvalue of type bool;  */
1297       if (ARITHMETIC_TYPE_P (from)
1298           || UNSCOPED_ENUM_P (from)
1299           || fcode == POINTER_TYPE
1300           || TYPE_PTR_TO_MEMBER_P (from)
1301           || NULLPTR_TYPE_P (from))
1302         {
1303           conv = build_conv (ck_std, to, conv);
1304           if (fcode == POINTER_TYPE
1305               || TYPE_PTRMEM_P (from)
1306               || (TYPE_PTRMEMFUNC_P (from)
1307                   && conv->rank < cr_pbool)
1308               || NULLPTR_TYPE_P (from))
1309             conv->rank = cr_pbool;
1310           return conv;
1311         }
1312
1313       return NULL;
1314     }
1315   /* We don't check for ENUMERAL_TYPE here because there are no standard
1316      conversions to enum type.  */
1317   /* As an extension, allow conversion to complex type.  */
1318   else if (ARITHMETIC_TYPE_P (to))
1319     {
1320       if (! (INTEGRAL_CODE_P (fcode) || fcode == REAL_TYPE)
1321           || SCOPED_ENUM_P (from))
1322         return NULL;
1323       conv = build_conv (ck_std, to, conv);
1324
1325       /* Give this a better rank if it's a promotion.  */
1326       if (same_type_p (to, type_promotes_to (from))
1327           && conv->u.next->rank <= cr_promotion)
1328         conv->rank = cr_promotion;
1329     }
1330   else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1331            && vector_types_convertible_p (from, to, false))
1332     return build_conv (ck_std, to, conv);
1333   else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1334            && is_properly_derived_from (from, to))
1335     {
1336       if (conv->kind == ck_rvalue)
1337         conv = conv->u.next;
1338       conv = build_conv (ck_base, to, conv);
1339       /* The derived-to-base conversion indicates the initialization
1340          of a parameter with base type from an object of a derived
1341          type.  A temporary object is created to hold the result of
1342          the conversion unless we're binding directly to a reference.  */
1343       conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1344     }
1345   else
1346     return NULL;
1347
1348   if (flags & LOOKUP_NO_NARROWING)
1349     conv->check_narrowing = true;
1350
1351   return conv;
1352 }
1353
1354 /* Returns nonzero if T1 is reference-related to T2.  */
1355
1356 bool
1357 reference_related_p (tree t1, tree t2)
1358 {
1359   if (t1 == error_mark_node || t2 == error_mark_node)
1360     return false;
1361
1362   t1 = TYPE_MAIN_VARIANT (t1);
1363   t2 = TYPE_MAIN_VARIANT (t2);
1364
1365   /* [dcl.init.ref]
1366
1367      Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1368      to "cv2 T2" if T1 is the same type as T2, or T1 is a base class
1369      of T2.  */
1370   return (same_type_p (t1, t2)
1371           || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1372               && DERIVED_FROM_P (t1, t2)));
1373 }
1374
1375 /* Returns nonzero if T1 is reference-compatible with T2.  */
1376
1377 static bool
1378 reference_compatible_p (tree t1, tree t2)
1379 {
1380   /* [dcl.init.ref]
1381
1382      "cv1 T1" is reference compatible with "cv2 T2" if T1 is
1383      reference-related to T2 and cv1 is the same cv-qualification as,
1384      or greater cv-qualification than, cv2.  */
1385   return (reference_related_p (t1, t2)
1386           && at_least_as_qualified_p (t1, t2));
1387 }
1388
1389 /* A reference of the indicated TYPE is being bound directly to the
1390    expression represented by the implicit conversion sequence CONV.
1391    Return a conversion sequence for this binding.  */
1392
1393 static conversion *
1394 direct_reference_binding (tree type, conversion *conv)
1395 {
1396   tree t;
1397
1398   gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
1399   gcc_assert (TREE_CODE (conv->type) != REFERENCE_TYPE);
1400
1401   t = TREE_TYPE (type);
1402
1403   /* [over.ics.rank]
1404
1405      When a parameter of reference type binds directly
1406      (_dcl.init.ref_) to an argument expression, the implicit
1407      conversion sequence is the identity conversion, unless the
1408      argument expression has a type that is a derived class of the
1409      parameter type, in which case the implicit conversion sequence is
1410      a derived-to-base Conversion.
1411
1412      If the parameter binds directly to the result of applying a
1413      conversion function to the argument expression, the implicit
1414      conversion sequence is a user-defined conversion sequence
1415      (_over.ics.user_), with the second standard conversion sequence
1416      either an identity conversion or, if the conversion function
1417      returns an entity of a type that is a derived class of the
1418      parameter type, a derived-to-base conversion.  */
1419   if (!same_type_ignoring_top_level_qualifiers_p (t, conv->type))
1420     {
1421       /* Represent the derived-to-base conversion.  */
1422       conv = build_conv (ck_base, t, conv);
1423       /* We will actually be binding to the base-class subobject in
1424          the derived class, so we mark this conversion appropriately.
1425          That way, convert_like knows not to generate a temporary.  */
1426       conv->need_temporary_p = false;
1427     }
1428   return build_conv (ck_ref_bind, type, conv);
1429 }
1430
1431 /* Returns the conversion path from type FROM to reference type TO for
1432    purposes of reference binding.  For lvalue binding, either pass a
1433    reference type to FROM or an lvalue expression to EXPR.  If the
1434    reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1435    the conversion returned.  If C_CAST_P is true, this
1436    conversion is coming from a C-style cast.  */
1437
1438 static conversion *
1439 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags)
1440 {
1441   conversion *conv = NULL;
1442   tree to = TREE_TYPE (rto);
1443   tree from = rfrom;
1444   tree tfrom;
1445   bool related_p;
1446   bool compatible_p;
1447   cp_lvalue_kind gl_kind;
1448   bool is_lvalue;
1449
1450   if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1451     {
1452       expr = instantiate_type (to, expr, tf_none);
1453       if (expr == error_mark_node)
1454         return NULL;
1455       from = TREE_TYPE (expr);
1456     }
1457
1458   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1459     {
1460       maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1461       conv = implicit_conversion (to, from, expr, c_cast_p,
1462                                   flags);
1463       if (!CLASS_TYPE_P (to)
1464           && CONSTRUCTOR_NELTS (expr) == 1)
1465         {
1466           expr = CONSTRUCTOR_ELT (expr, 0)->value;
1467           if (error_operand_p (expr))
1468             return NULL;
1469           from = TREE_TYPE (expr);
1470         }
1471     }
1472
1473   if (TREE_CODE (from) == REFERENCE_TYPE)
1474     {
1475       from = TREE_TYPE (from);
1476       if (!TYPE_REF_IS_RVALUE (rfrom)
1477           || TREE_CODE (from) == FUNCTION_TYPE)
1478         gl_kind = clk_ordinary;
1479       else
1480         gl_kind = clk_rvalueref;
1481     }
1482   else if (expr)
1483     {
1484       gl_kind = lvalue_kind (expr);
1485       if (gl_kind & clk_class)
1486         /* A class prvalue is not a glvalue.  */
1487         gl_kind = clk_none;
1488     }
1489   else
1490     gl_kind = clk_none;
1491   is_lvalue = gl_kind && !(gl_kind & clk_rvalueref);
1492
1493   tfrom = from;
1494   if ((gl_kind & clk_bitfield) != 0)
1495     tfrom = unlowered_expr_type (expr);
1496
1497   /* Figure out whether or not the types are reference-related and
1498      reference compatible.  We have do do this after stripping
1499      references from FROM.  */
1500   related_p = reference_related_p (to, tfrom);
1501   /* If this is a C cast, first convert to an appropriately qualified
1502      type, so that we can later do a const_cast to the desired type.  */
1503   if (related_p && c_cast_p
1504       && !at_least_as_qualified_p (to, tfrom))
1505     to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1506   compatible_p = reference_compatible_p (to, tfrom);
1507
1508   /* Directly bind reference when target expression's type is compatible with
1509      the reference and expression is an lvalue. In DR391, the wording in
1510      [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1511      const and rvalue references to rvalues of compatible class type.
1512      We should also do direct bindings for non-class xvalues.  */
1513   if (compatible_p
1514       && (is_lvalue
1515           || (((CP_TYPE_CONST_NON_VOLATILE_P (to)
1516                 && !(flags & LOOKUP_NO_RVAL_BIND))
1517                || TYPE_REF_IS_RVALUE (rto))
1518               && (gl_kind
1519                   || (!(flags & LOOKUP_NO_TEMP_BIND)
1520                       && (CLASS_TYPE_P (from)
1521                           || TREE_CODE (from) == ARRAY_TYPE))))))
1522     {
1523       /* [dcl.init.ref]
1524
1525          If the initializer expression
1526
1527          -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1528             is reference-compatible with "cv2 T2,"
1529
1530          the reference is bound directly to the initializer expression
1531          lvalue.
1532
1533          [...]
1534          If the initializer expression is an rvalue, with T2 a class type,
1535          and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1536          is bound to the object represented by the rvalue or to a sub-object
1537          within that object.  */
1538
1539       conv = build_identity_conv (tfrom, expr);
1540       conv = direct_reference_binding (rto, conv);
1541
1542       if (flags & LOOKUP_PREFER_RVALUE)
1543         /* The top-level caller requested that we pretend that the lvalue
1544            be treated as an rvalue.  */
1545         conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1546       else if (TREE_CODE (rfrom) == REFERENCE_TYPE)
1547         /* Handle rvalue reference to function properly.  */
1548         conv->rvaluedness_matches_p
1549           = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1550       else
1551         conv->rvaluedness_matches_p 
1552           = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1553
1554       if ((gl_kind & clk_bitfield) != 0
1555           || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1556         /* For the purposes of overload resolution, we ignore the fact
1557            this expression is a bitfield or packed field. (In particular,
1558            [over.ics.ref] says specifically that a function with a
1559            non-const reference parameter is viable even if the
1560            argument is a bitfield.)
1561
1562            However, when we actually call the function we must create
1563            a temporary to which to bind the reference.  If the
1564            reference is volatile, or isn't const, then we cannot make
1565            a temporary, so we just issue an error when the conversion
1566            actually occurs.  */
1567         conv->need_temporary_p = true;
1568
1569       /* Don't allow binding of lvalues (other than function lvalues) to
1570          rvalue references.  */
1571       if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1572           && TREE_CODE (to) != FUNCTION_TYPE
1573           && !(flags & LOOKUP_PREFER_RVALUE))
1574         conv->bad_p = true;
1575
1576       return conv;
1577     }
1578   /* [class.conv.fct] A conversion function is never used to convert a
1579      (possibly cv-qualified) object to the (possibly cv-qualified) same
1580      object type (or a reference to it), to a (possibly cv-qualified) base
1581      class of that type (or a reference to it).... */
1582   else if (CLASS_TYPE_P (from) && !related_p
1583            && !(flags & LOOKUP_NO_CONVERSION))
1584     {
1585       /* [dcl.init.ref]
1586
1587          If the initializer expression
1588
1589          -- has a class type (i.e., T2 is a class type) can be
1590             implicitly converted to an lvalue of type "cv3 T3," where
1591             "cv1 T1" is reference-compatible with "cv3 T3".  (this
1592             conversion is selected by enumerating the applicable
1593             conversion functions (_over.match.ref_) and choosing the
1594             best one through overload resolution.  (_over.match_).
1595
1596         the reference is bound to the lvalue result of the conversion
1597         in the second case.  */
1598       z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags);
1599       if (cand)
1600         return cand->second_conv;
1601     }
1602
1603   /* From this point on, we conceptually need temporaries, even if we
1604      elide them.  Only the cases above are "direct bindings".  */
1605   if (flags & LOOKUP_NO_TEMP_BIND)
1606     return NULL;
1607
1608   /* [over.ics.rank]
1609
1610      When a parameter of reference type is not bound directly to an
1611      argument expression, the conversion sequence is the one required
1612      to convert the argument expression to the underlying type of the
1613      reference according to _over.best.ics_.  Conceptually, this
1614      conversion sequence corresponds to copy-initializing a temporary
1615      of the underlying type with the argument expression.  Any
1616      difference in top-level cv-qualification is subsumed by the
1617      initialization itself and does not constitute a conversion.  */
1618
1619   /* [dcl.init.ref]
1620
1621      Otherwise, the reference shall be to a non-volatile const type.
1622
1623      Under C++0x, [8.5.3/5 dcl.init.ref] it may also be an rvalue reference */
1624   if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1625     return NULL;
1626
1627   /* [dcl.init.ref]
1628
1629      Otherwise, a temporary of type "cv1 T1" is created and
1630      initialized from the initializer expression using the rules for a
1631      non-reference copy initialization.  If T1 is reference-related to
1632      T2, cv1 must be the same cv-qualification as, or greater
1633      cv-qualification than, cv2; otherwise, the program is ill-formed.  */
1634   if (related_p && !at_least_as_qualified_p (to, from))
1635     return NULL;
1636
1637   /* We're generating a temporary now, but don't bind any more in the
1638      conversion (specifically, don't slice the temporary returned by a
1639      conversion operator).  */
1640   flags |= LOOKUP_NO_TEMP_BIND;
1641
1642   /* Core issue 899: When [copy-]initializing a temporary to be bound
1643      to the first parameter of a copy constructor (12.8) called with
1644      a single argument in the context of direct-initialization,
1645      explicit conversion functions are also considered.
1646
1647      So don't set LOOKUP_ONLYCONVERTING in that case.  */
1648   if (!(flags & LOOKUP_COPY_PARM))
1649     flags |= LOOKUP_ONLYCONVERTING;
1650
1651   if (!conv)
1652     conv = implicit_conversion (to, from, expr, c_cast_p,
1653                                 flags);
1654   if (!conv)
1655     return NULL;
1656
1657   conv = build_conv (ck_ref_bind, rto, conv);
1658   /* This reference binding, unlike those above, requires the
1659      creation of a temporary.  */
1660   conv->need_temporary_p = true;
1661   conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1662
1663   return conv;
1664 }
1665
1666 /* Returns the implicit conversion sequence (see [over.ics]) from type
1667    FROM to type TO.  The optional expression EXPR may affect the
1668    conversion.  FLAGS are the usual overloading flags.  If C_CAST_P is
1669    true, this conversion is coming from a C-style cast.  */
1670
1671 static conversion *
1672 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
1673                      int flags)
1674 {
1675   conversion *conv;
1676
1677   if (from == error_mark_node || to == error_mark_node
1678       || expr == error_mark_node)
1679     return NULL;
1680
1681   /* Other flags only apply to the primary function in overload
1682      resolution, or after we've chosen one.  */
1683   flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
1684             |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_PREFER_RVALUE
1685             |LOOKUP_NO_NARROWING|LOOKUP_PROTECT);
1686
1687   if (TREE_CODE (to) == REFERENCE_TYPE)
1688     conv = reference_binding (to, from, expr, c_cast_p, flags);
1689   else
1690     conv = standard_conversion (to, from, expr, c_cast_p, flags);
1691
1692   if (conv)
1693     return conv;
1694
1695   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1696     {
1697       if (is_std_init_list (to))
1698         return build_list_conv (to, expr, flags);
1699
1700       /* As an extension, allow list-initialization of _Complex.  */
1701       if (TREE_CODE (to) == COMPLEX_TYPE)
1702         {
1703           conv = build_complex_conv (to, expr, flags);
1704           if (conv)
1705             return conv;
1706         }
1707
1708       /* Allow conversion from an initializer-list with one element to a
1709          scalar type.  */
1710       if (SCALAR_TYPE_P (to))
1711         {
1712           int nelts = CONSTRUCTOR_NELTS (expr);
1713           tree elt;
1714
1715           if (nelts == 0)
1716             elt = build_value_init (to, tf_none);
1717           else if (nelts == 1)
1718             elt = CONSTRUCTOR_ELT (expr, 0)->value;
1719           else
1720             elt = error_mark_node;
1721
1722           conv = implicit_conversion (to, TREE_TYPE (elt), elt,
1723                                       c_cast_p, flags);
1724           if (conv)
1725             {
1726               conv->check_narrowing = true;
1727               if (BRACE_ENCLOSED_INITIALIZER_P (elt))
1728                 /* Too many levels of braces, i.e. '{{1}}'.  */
1729                 conv->bad_p = true;
1730               return conv;
1731             }
1732         }
1733       else if (TREE_CODE (to) == ARRAY_TYPE)
1734         return build_array_conv (to, expr, flags);
1735     }
1736
1737   if (expr != NULL_TREE
1738       && (MAYBE_CLASS_TYPE_P (from)
1739           || MAYBE_CLASS_TYPE_P (to))
1740       && (flags & LOOKUP_NO_CONVERSION) == 0)
1741     {
1742       struct z_candidate *cand;
1743
1744       if (CLASS_TYPE_P (to)
1745           && BRACE_ENCLOSED_INITIALIZER_P (expr)
1746           && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
1747         return build_aggr_conv (to, expr, flags);
1748
1749       cand = build_user_type_conversion_1 (to, expr, flags);
1750       if (cand)
1751         conv = cand->second_conv;
1752
1753       /* We used to try to bind a reference to a temporary here, but that
1754          is now handled after the recursive call to this function at the end
1755          of reference_binding.  */
1756       return conv;
1757     }
1758
1759   return NULL;
1760 }
1761
1762 /* Add a new entry to the list of candidates.  Used by the add_*_candidate
1763    functions.  ARGS will not be changed until a single candidate is
1764    selected.  */
1765
1766 static struct z_candidate *
1767 add_candidate (struct z_candidate **candidates,
1768                tree fn, tree first_arg, const VEC(tree,gc) *args,
1769                size_t num_convs, conversion **convs,
1770                tree access_path, tree conversion_path,
1771                int viable, struct rejection_reason *reason)
1772 {
1773   struct z_candidate *cand = (struct z_candidate *)
1774     conversion_obstack_alloc (sizeof (struct z_candidate));
1775
1776   cand->fn = fn;
1777   cand->first_arg = first_arg;
1778   cand->args = args;
1779   cand->convs = convs;
1780   cand->num_convs = num_convs;
1781   cand->access_path = access_path;
1782   cand->conversion_path = conversion_path;
1783   cand->viable = viable;
1784   cand->reason = reason;
1785   cand->next = *candidates;
1786   *candidates = cand;
1787
1788   return cand;
1789 }
1790
1791 /* Return the number of remaining arguments in the parameter list
1792    beginning with ARG.  */
1793
1794 static int
1795 remaining_arguments (tree arg)
1796 {
1797   int n;
1798
1799   for (n = 0; arg != NULL_TREE && arg != void_list_node;
1800        arg = TREE_CHAIN (arg))
1801     n++;
1802
1803   return n;
1804 }
1805
1806 /* Create an overload candidate for the function or method FN called
1807    with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
1808    FLAGS is passed on to implicit_conversion.
1809
1810    This does not change ARGS.
1811
1812    CTYPE, if non-NULL, is the type we want to pretend this function
1813    comes from for purposes of overload resolution.  */
1814
1815 static struct z_candidate *
1816 add_function_candidate (struct z_candidate **candidates,
1817                         tree fn, tree ctype, tree first_arg,
1818                         const VEC(tree,gc) *args, tree access_path,
1819                         tree conversion_path, int flags)
1820 {
1821   tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
1822   int i, len;
1823   conversion **convs;
1824   tree parmnode;
1825   tree orig_first_arg = first_arg;
1826   int skip;
1827   int viable = 1;
1828   struct rejection_reason *reason = NULL;
1829
1830   /* At this point we should not see any functions which haven't been
1831      explicitly declared, except for friend functions which will have
1832      been found using argument dependent lookup.  */
1833   gcc_assert (!DECL_ANTICIPATED (fn) || DECL_HIDDEN_FRIEND_P (fn));
1834
1835   /* The `this', `in_chrg' and VTT arguments to constructors are not
1836      considered in overload resolution.  */
1837   if (DECL_CONSTRUCTOR_P (fn))
1838     {
1839       parmlist = skip_artificial_parms_for (fn, parmlist);
1840       skip = num_artificial_parms_for (fn);
1841       if (skip > 0 && first_arg != NULL_TREE)
1842         {
1843           --skip;
1844           first_arg = NULL_TREE;
1845         }
1846     }
1847   else
1848     skip = 0;
1849
1850   len = VEC_length (tree, args) - skip + (first_arg != NULL_TREE ? 1 : 0);
1851   convs = alloc_conversions (len);
1852
1853   /* 13.3.2 - Viable functions [over.match.viable]
1854      First, to be a viable function, a candidate function shall have enough
1855      parameters to agree in number with the arguments in the list.
1856
1857      We need to check this first; otherwise, checking the ICSes might cause
1858      us to produce an ill-formed template instantiation.  */
1859
1860   parmnode = parmlist;
1861   for (i = 0; i < len; ++i)
1862     {
1863       if (parmnode == NULL_TREE || parmnode == void_list_node)
1864         break;
1865       parmnode = TREE_CHAIN (parmnode);
1866     }
1867
1868   if ((i < len && parmnode)
1869       || !sufficient_parms_p (parmnode))
1870     {
1871       int remaining = remaining_arguments (parmnode);
1872       viable = 0;
1873       reason = arity_rejection (first_arg, i + remaining, len);
1874     }
1875   /* When looking for a function from a subobject from an implicit
1876      copy/move constructor/operator=, don't consider anything that takes (a
1877      reference to) an unrelated type.  See c++/44909 and core 1092.  */
1878   else if (parmlist && (flags & LOOKUP_DEFAULTED))
1879     {
1880       if (DECL_CONSTRUCTOR_P (fn))
1881         i = 1;
1882       else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
1883                && DECL_OVERLOADED_OPERATOR_P (fn) == NOP_EXPR)
1884         i = 2;
1885       else
1886         i = 0;
1887       if (i && len == i)
1888         {
1889           parmnode = chain_index (i-1, parmlist);
1890           if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
1891                                     ctype))
1892             viable = 0;
1893         }
1894
1895       /* This only applies at the top level.  */
1896       flags &= ~LOOKUP_DEFAULTED;
1897     }
1898
1899   if (! viable)
1900     goto out;
1901
1902   /* Second, for F to be a viable function, there shall exist for each
1903      argument an implicit conversion sequence that converts that argument
1904      to the corresponding parameter of F.  */
1905
1906   parmnode = parmlist;
1907
1908   for (i = 0; i < len; ++i)
1909     {
1910       tree arg, argtype, to_type;
1911       conversion *t;
1912       int is_this;
1913
1914       if (parmnode == void_list_node)
1915         break;
1916
1917       if (i == 0 && first_arg != NULL_TREE)
1918         arg = first_arg;
1919       else
1920         arg = VEC_index (tree, args,
1921                          i + skip - (first_arg != NULL_TREE ? 1 : 0));
1922       argtype = lvalue_type (arg);
1923
1924       is_this = (i == 0 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1925                  && ! DECL_CONSTRUCTOR_P (fn));
1926
1927       if (parmnode)
1928         {
1929           tree parmtype = TREE_VALUE (parmnode);
1930           int lflags = flags;
1931
1932           parmnode = TREE_CHAIN (parmnode);
1933
1934           /* The type of the implicit object parameter ('this') for
1935              overload resolution is not always the same as for the
1936              function itself; conversion functions are considered to
1937              be members of the class being converted, and functions
1938              introduced by a using-declaration are considered to be
1939              members of the class that uses them.
1940
1941              Since build_over_call ignores the ICS for the `this'
1942              parameter, we can just change the parm type.  */
1943           if (ctype && is_this)
1944             {
1945               parmtype = cp_build_qualified_type
1946                 (ctype, cp_type_quals (TREE_TYPE (parmtype)));
1947               parmtype = build_pointer_type (parmtype);
1948             }
1949
1950           /* Core issue 899: When [copy-]initializing a temporary to be bound
1951              to the first parameter of a copy constructor (12.8) called with
1952              a single argument in the context of direct-initialization,
1953              explicit conversion functions are also considered.
1954
1955              So set LOOKUP_COPY_PARM to let reference_binding know that
1956              it's being called in that context.  We generalize the above
1957              to handle move constructors and template constructors as well;
1958              the standardese should soon be updated similarly.  */
1959           if (ctype && i == 0 && (len-skip == 1)
1960               && DECL_CONSTRUCTOR_P (fn)
1961               && parmtype != error_mark_node
1962               && (same_type_ignoring_top_level_qualifiers_p
1963                   (non_reference (parmtype), ctype)))
1964             {
1965               if (!(flags & LOOKUP_ONLYCONVERTING))
1966                 lflags |= LOOKUP_COPY_PARM;
1967               /* We allow user-defined conversions within init-lists, but
1968                  don't list-initialize the copy parm, as that would mean
1969                  using two levels of braces for the same type.  */
1970               if ((flags & LOOKUP_LIST_INIT_CTOR)
1971                   && BRACE_ENCLOSED_INITIALIZER_P (arg))
1972                 lflags |= LOOKUP_NO_CONVERSION;
1973             }
1974           else
1975             lflags |= LOOKUP_ONLYCONVERTING;
1976
1977           t = implicit_conversion (parmtype, argtype, arg,
1978                                    /*c_cast_p=*/false, lflags);
1979           to_type = parmtype;
1980         }
1981       else
1982         {
1983           t = build_identity_conv (argtype, arg);
1984           t->ellipsis_p = true;
1985           to_type = argtype;
1986         }
1987
1988       if (t && is_this)
1989         t->this_p = true;
1990
1991       convs[i] = t;
1992       if (! t)
1993         {
1994           viable = 0;
1995           reason = arg_conversion_rejection (first_arg, i, argtype, to_type);
1996           break;
1997         }
1998
1999       if (t->bad_p)
2000         {
2001           viable = -1;
2002           reason = bad_arg_conversion_rejection (first_arg, i, argtype, to_type);
2003         }
2004     }
2005
2006  out:
2007   return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2008                         access_path, conversion_path, viable, reason);
2009 }
2010
2011 /* Create an overload candidate for the conversion function FN which will
2012    be invoked for expression OBJ, producing a pointer-to-function which
2013    will in turn be called with the argument list FIRST_ARG/ARGLIST,
2014    and add it to CANDIDATES.  This does not change ARGLIST.  FLAGS is
2015    passed on to implicit_conversion.
2016
2017    Actually, we don't really care about FN; we care about the type it
2018    converts to.  There may be multiple conversion functions that will
2019    convert to that type, and we rely on build_user_type_conversion_1 to
2020    choose the best one; so when we create our candidate, we record the type
2021    instead of the function.  */
2022
2023 static struct z_candidate *
2024 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2025                     tree first_arg, const VEC(tree,gc) *arglist,
2026                     tree access_path, tree conversion_path)
2027 {
2028   tree totype = TREE_TYPE (TREE_TYPE (fn));
2029   int i, len, viable, flags;
2030   tree parmlist, parmnode;
2031   conversion **convs;
2032   struct rejection_reason *reason;
2033
2034   for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2035     parmlist = TREE_TYPE (parmlist);
2036   parmlist = TYPE_ARG_TYPES (parmlist);
2037
2038   len = VEC_length (tree, arglist) + (first_arg != NULL_TREE ? 1 : 0) + 1;
2039   convs = alloc_conversions (len);
2040   parmnode = parmlist;
2041   viable = 1;
2042   flags = LOOKUP_IMPLICIT;
2043   reason = NULL;
2044
2045   /* Don't bother looking up the same type twice.  */
2046   if (*candidates && (*candidates)->fn == totype)
2047     return NULL;
2048
2049   for (i = 0; i < len; ++i)
2050     {
2051       tree arg, argtype, convert_type = NULL_TREE;
2052       conversion *t;
2053
2054       if (i == 0)
2055         arg = obj;
2056       else if (i == 1 && first_arg != NULL_TREE)
2057         arg = first_arg;
2058       else
2059         arg = VEC_index (tree, arglist,
2060                          i - (first_arg != NULL_TREE ? 1 : 0) - 1);
2061       argtype = lvalue_type (arg);
2062
2063       if (i == 0)
2064         {
2065           t = implicit_conversion (totype, argtype, arg, /*c_cast_p=*/false,
2066                                    flags);
2067           convert_type = totype;
2068         }
2069       else if (parmnode == void_list_node)
2070         break;
2071       else if (parmnode)
2072         {
2073           t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2074                                    /*c_cast_p=*/false, flags);
2075           convert_type = TREE_VALUE (parmnode);
2076         }
2077       else
2078         {
2079           t = build_identity_conv (argtype, arg);
2080           t->ellipsis_p = true;
2081           convert_type = argtype;
2082         }
2083
2084       convs[i] = t;
2085       if (! t)
2086         break;
2087
2088       if (t->bad_p)
2089         {
2090           viable = -1;
2091           reason = bad_arg_conversion_rejection (NULL_TREE, i, argtype, convert_type);
2092         }
2093
2094       if (i == 0)
2095         continue;
2096
2097       if (parmnode)
2098         parmnode = TREE_CHAIN (parmnode);
2099     }
2100
2101   if (i < len
2102       || ! sufficient_parms_p (parmnode))
2103     {
2104       int remaining = remaining_arguments (parmnode);
2105       viable = 0;
2106       reason = arity_rejection (NULL_TREE, i + remaining, len);
2107     }
2108
2109   return add_candidate (candidates, totype, first_arg, arglist, len, convs,
2110                         access_path, conversion_path, viable, reason);
2111 }
2112
2113 static void
2114 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2115                          tree type1, tree type2, tree *args, tree *argtypes,
2116                          int flags)
2117 {
2118   conversion *t;
2119   conversion **convs;
2120   size_t num_convs;
2121   int viable = 1, i;
2122   tree types[2];
2123   struct rejection_reason *reason = NULL;
2124
2125   types[0] = type1;
2126   types[1] = type2;
2127
2128   num_convs =  args[2] ? 3 : (args[1] ? 2 : 1);
2129   convs = alloc_conversions (num_convs);
2130
2131   /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2132      conversion ops are allowed.  We handle that here by just checking for
2133      boolean_type_node because other operators don't ask for it.  COND_EXPR
2134      also does contextual conversion to bool for the first operand, but we
2135      handle that in build_conditional_expr, and type1 here is operand 2.  */
2136   if (type1 != boolean_type_node)
2137     flags |= LOOKUP_ONLYCONVERTING;
2138
2139   for (i = 0; i < 2; ++i)
2140     {
2141       if (! args[i])
2142         break;
2143
2144       t = implicit_conversion (types[i], argtypes[i], args[i],
2145                                /*c_cast_p=*/false, flags);
2146       if (! t)
2147         {
2148           viable = 0;
2149           /* We need something for printing the candidate.  */
2150           t = build_identity_conv (types[i], NULL_TREE);
2151           reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i], types[i]);
2152         }
2153       else if (t->bad_p)
2154         {
2155           viable = 0;
2156           reason = bad_arg_conversion_rejection (NULL_TREE, i, argtypes[i], types[i]);
2157         }
2158       convs[i] = t;
2159     }
2160
2161   /* For COND_EXPR we rearranged the arguments; undo that now.  */
2162   if (args[2])
2163     {
2164       convs[2] = convs[1];
2165       convs[1] = convs[0];
2166       t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2167                                /*c_cast_p=*/false, flags);
2168       if (t)
2169         convs[0] = t;
2170       else
2171         {
2172           viable = 0;
2173           reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2174                                              boolean_type_node);
2175         }
2176     }
2177
2178   add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2179                  num_convs, convs,
2180                  /*access_path=*/NULL_TREE,
2181                  /*conversion_path=*/NULL_TREE,
2182                  viable, reason);
2183 }
2184
2185 static bool
2186 is_complete (tree t)
2187 {
2188   return COMPLETE_TYPE_P (complete_type (t));
2189 }
2190
2191 /* Returns nonzero if TYPE is a promoted arithmetic type.  */
2192
2193 static bool
2194 promoted_arithmetic_type_p (tree type)
2195 {
2196   /* [over.built]
2197
2198      In this section, the term promoted integral type is used to refer
2199      to those integral types which are preserved by integral promotion
2200      (including e.g.  int and long but excluding e.g.  char).
2201      Similarly, the term promoted arithmetic type refers to promoted
2202      integral types plus floating types.  */
2203   return ((CP_INTEGRAL_TYPE_P (type)
2204            && same_type_p (type_promotes_to (type), type))
2205           || TREE_CODE (type) == REAL_TYPE);
2206 }
2207
2208 /* Create any builtin operator overload candidates for the operator in
2209    question given the converted operand types TYPE1 and TYPE2.  The other
2210    args are passed through from add_builtin_candidates to
2211    build_builtin_candidate.
2212
2213    TYPE1 and TYPE2 may not be permissible, and we must filter them.
2214    If CODE is requires candidates operands of the same type of the kind
2215    of which TYPE1 and TYPE2 are, we add both candidates
2216    CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2).  */
2217
2218 static void
2219 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2220                        enum tree_code code2, tree fnname, tree type1,
2221                        tree type2, tree *args, tree *argtypes, int flags)
2222 {
2223   switch (code)
2224     {
2225     case POSTINCREMENT_EXPR:
2226     case POSTDECREMENT_EXPR:
2227       args[1] = integer_zero_node;
2228       type2 = integer_type_node;
2229       break;
2230     default:
2231       break;
2232     }
2233
2234   switch (code)
2235     {
2236
2237 /* 4 For every pair T, VQ), where T is an arithmetic or  enumeration  type,
2238      and  VQ  is  either  volatile or empty, there exist candidate operator
2239      functions of the form
2240              VQ T&   operator++(VQ T&);
2241              T       operator++(VQ T&, int);
2242    5 For every pair T, VQ), where T is an enumeration type or an arithmetic
2243      type  other than bool, and VQ is either volatile or empty, there exist
2244      candidate operator functions of the form
2245              VQ T&   operator--(VQ T&);
2246              T       operator--(VQ T&, int);
2247    6 For every pair T, VQ), where T is  a  cv-qualified  or  cv-unqualified
2248      complete  object type, and VQ is either volatile or empty, there exist
2249      candidate operator functions of the form
2250              T*VQ&   operator++(T*VQ&);
2251              T*VQ&   operator--(T*VQ&);
2252              T*      operator++(T*VQ&, int);
2253              T*      operator--(T*VQ&, int);  */
2254
2255     case POSTDECREMENT_EXPR:
2256     case PREDECREMENT_EXPR:
2257       if (TREE_CODE (type1) == BOOLEAN_TYPE)
2258         return;
2259     case POSTINCREMENT_EXPR:
2260     case PREINCREMENT_EXPR:
2261       if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2262         {
2263           type1 = build_reference_type (type1);
2264           break;
2265         }
2266       return;
2267
2268 /* 7 For every cv-qualified or cv-unqualified object type T, there
2269      exist candidate operator functions of the form
2270
2271              T&      operator*(T*);
2272
2273    8 For every function type T, there exist candidate operator functions of
2274      the form
2275              T&      operator*(T*);  */
2276
2277     case INDIRECT_REF:
2278       if (TREE_CODE (type1) == POINTER_TYPE
2279           && !uses_template_parms (TREE_TYPE (type1))
2280           && (TYPE_PTROB_P (type1)
2281               || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2282         break;
2283       return;
2284
2285 /* 9 For every type T, there exist candidate operator functions of the form
2286              T*      operator+(T*);
2287
2288    10For  every  promoted arithmetic type T, there exist candidate operator
2289      functions of the form
2290              T       operator+(T);
2291              T       operator-(T);  */
2292
2293     case UNARY_PLUS_EXPR: /* unary + */
2294       if (TREE_CODE (type1) == POINTER_TYPE)
2295         break;
2296     case NEGATE_EXPR:
2297       if (ARITHMETIC_TYPE_P (type1))
2298         break;
2299       return;
2300
2301 /* 11For every promoted integral type T,  there  exist  candidate  operator
2302      functions of the form
2303              T       operator~(T);  */
2304
2305     case BIT_NOT_EXPR:
2306       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2307         break;
2308       return;
2309
2310 /* 12For every quintuple C1, C2, T, CV1, CV2), where C2 is a class type, C1
2311      is the same type as C2 or is a derived class of C2, T  is  a  complete
2312      object type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
2313      there exist candidate operator functions of the form
2314              CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2315      where CV12 is the union of CV1 and CV2.  */
2316
2317     case MEMBER_REF:
2318       if (TREE_CODE (type1) == POINTER_TYPE
2319           && TYPE_PTR_TO_MEMBER_P (type2))
2320         {
2321           tree c1 = TREE_TYPE (type1);
2322           tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2323
2324           if (MAYBE_CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2325               && (TYPE_PTRMEMFUNC_P (type2)
2326                   || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2327             break;
2328         }
2329       return;
2330
2331 /* 13For every pair of promoted arithmetic types L and R, there exist  can-
2332      didate operator functions of the form
2333              LR      operator*(L, R);
2334              LR      operator/(L, R);
2335              LR      operator+(L, R);
2336              LR      operator-(L, R);
2337              bool    operator<(L, R);
2338              bool    operator>(L, R);
2339              bool    operator<=(L, R);
2340              bool    operator>=(L, R);
2341              bool    operator==(L, R);
2342              bool    operator!=(L, R);
2343      where  LR  is  the  result of the usual arithmetic conversions between
2344      types L and R.
2345
2346    14For every pair of types T and I, where T  is  a  cv-qualified  or  cv-
2347      unqualified  complete  object  type and I is a promoted integral type,
2348      there exist candidate operator functions of the form
2349              T*      operator+(T*, I);
2350              T&      operator[](T*, I);
2351              T*      operator-(T*, I);
2352              T*      operator+(I, T*);
2353              T&      operator[](I, T*);
2354
2355    15For every T, where T is a pointer to complete object type, there exist
2356      candidate operator functions of the form112)
2357              ptrdiff_t operator-(T, T);
2358
2359    16For every pointer or enumeration type T, there exist candidate operator
2360      functions of the form
2361              bool    operator<(T, T);
2362              bool    operator>(T, T);
2363              bool    operator<=(T, T);
2364              bool    operator>=(T, T);
2365              bool    operator==(T, T);
2366              bool    operator!=(T, T);
2367
2368    17For every pointer to member type T,  there  exist  candidate  operator
2369      functions of the form
2370              bool    operator==(T, T);
2371              bool    operator!=(T, T);  */
2372
2373     case MINUS_EXPR:
2374       if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2375         break;
2376       if (TYPE_PTROB_P (type1)
2377           && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2378         {
2379           type2 = ptrdiff_type_node;
2380           break;
2381         }
2382     case MULT_EXPR:
2383     case TRUNC_DIV_EXPR:
2384       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2385         break;
2386       return;
2387
2388     case EQ_EXPR:
2389     case NE_EXPR:
2390       if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2391           || (TYPE_PTRMEM_P (type1) && TYPE_PTRMEM_P (type2)))
2392         break;
2393       if (TYPE_PTR_TO_MEMBER_P (type1) && null_ptr_cst_p (args[1]))
2394         {
2395           type2 = type1;
2396           break;
2397         }
2398       if (TYPE_PTR_TO_MEMBER_P (type2) && null_ptr_cst_p (args[0]))
2399         {
2400           type1 = type2;
2401           break;
2402         }
2403       /* Fall through.  */
2404     case LT_EXPR:
2405     case GT_EXPR:
2406     case LE_EXPR:
2407     case GE_EXPR:
2408     case MAX_EXPR:
2409     case MIN_EXPR:
2410       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2411         break;
2412       if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2413         break;
2414       if (TREE_CODE (type1) == ENUMERAL_TYPE 
2415           && TREE_CODE (type2) == ENUMERAL_TYPE)
2416         break;
2417       if (TYPE_PTR_P (type1) 
2418           && null_ptr_cst_p (args[1])
2419           && !uses_template_parms (type1))
2420         {
2421           type2 = type1;
2422           break;
2423         }
2424       if (null_ptr_cst_p (args[0]) 
2425           && TYPE_PTR_P (type2)
2426           && !uses_template_parms (type2))
2427         {
2428           type1 = type2;
2429           break;
2430         }
2431       return;
2432
2433     case PLUS_EXPR:
2434       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2435         break;
2436     case ARRAY_REF:
2437       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
2438         {
2439           type1 = ptrdiff_type_node;
2440           break;
2441         }
2442       if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2443         {
2444           type2 = ptrdiff_type_node;
2445           break;
2446         }
2447       return;
2448
2449 /* 18For  every pair of promoted integral types L and R, there exist candi-
2450      date operator functions of the form
2451              LR      operator%(L, R);
2452              LR      operator&(L, R);
2453              LR      operator^(L, R);
2454              LR      operator|(L, R);
2455              L       operator<<(L, R);
2456              L       operator>>(L, R);
2457      where LR is the result of the  usual  arithmetic  conversions  between
2458      types L and R.  */
2459
2460     case TRUNC_MOD_EXPR:
2461     case BIT_AND_EXPR:
2462     case BIT_IOR_EXPR:
2463     case BIT_XOR_EXPR:
2464     case LSHIFT_EXPR:
2465     case RSHIFT_EXPR:
2466       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2467         break;
2468       return;
2469
2470 /* 19For  every  triple  L, VQ, R), where L is an arithmetic or enumeration
2471      type, VQ is either volatile or empty, and R is a  promoted  arithmetic
2472      type, there exist candidate operator functions of the form
2473              VQ L&   operator=(VQ L&, R);
2474              VQ L&   operator*=(VQ L&, R);
2475              VQ L&   operator/=(VQ L&, R);
2476              VQ L&   operator+=(VQ L&, R);
2477              VQ L&   operator-=(VQ L&, R);
2478
2479    20For  every  pair T, VQ), where T is any type and VQ is either volatile
2480      or empty, there exist candidate operator functions of the form
2481              T*VQ&   operator=(T*VQ&, T*);
2482
2483    21For every pair T, VQ), where T is a pointer to member type and  VQ  is
2484      either  volatile or empty, there exist candidate operator functions of
2485      the form
2486              VQ T&   operator=(VQ T&, T);
2487
2488    22For every triple  T,  VQ,  I),  where  T  is  a  cv-qualified  or  cv-
2489      unqualified  complete object type, VQ is either volatile or empty, and
2490      I is a promoted integral type, there exist  candidate  operator  func-
2491      tions of the form
2492              T*VQ&   operator+=(T*VQ&, I);
2493              T*VQ&   operator-=(T*VQ&, I);
2494
2495    23For  every  triple  L,  VQ,  R), where L is an integral or enumeration
2496      type, VQ is either volatile or empty, and R  is  a  promoted  integral
2497      type, there exist candidate operator functions of the form
2498
2499              VQ L&   operator%=(VQ L&, R);
2500              VQ L&   operator<<=(VQ L&, R);
2501              VQ L&   operator>>=(VQ L&, R);
2502              VQ L&   operator&=(VQ L&, R);
2503              VQ L&   operator^=(VQ L&, R);
2504              VQ L&   operator|=(VQ L&, R);  */
2505
2506     case MODIFY_EXPR:
2507       switch (code2)
2508         {
2509         case PLUS_EXPR:
2510         case MINUS_EXPR:
2511           if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2512             {
2513               type2 = ptrdiff_type_node;
2514               break;
2515             }
2516         case MULT_EXPR:
2517         case TRUNC_DIV_EXPR:
2518           if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2519             break;
2520           return;
2521
2522         case TRUNC_MOD_EXPR:
2523         case BIT_AND_EXPR:
2524         case BIT_IOR_EXPR:
2525         case BIT_XOR_EXPR:
2526         case LSHIFT_EXPR:
2527         case RSHIFT_EXPR:
2528           if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2529             break;
2530           return;
2531
2532         case NOP_EXPR:
2533           if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2534             break;
2535           if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2536               || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2537               || (TYPE_PTRMEM_P (type1) && TYPE_PTRMEM_P (type2))
2538               || ((TYPE_PTRMEMFUNC_P (type1)
2539                    || TREE_CODE (type1) == POINTER_TYPE)
2540                   && null_ptr_cst_p (args[1])))
2541             {
2542               type2 = type1;
2543               break;
2544             }
2545           return;
2546
2547         default:
2548           gcc_unreachable ();
2549         }
2550       type1 = build_reference_type (type1);
2551       break;
2552
2553     case COND_EXPR:
2554       /* [over.built]
2555
2556          For every pair of promoted arithmetic types L and R, there
2557          exist candidate operator functions of the form
2558
2559          LR operator?(bool, L, R);
2560
2561          where LR is the result of the usual arithmetic conversions
2562          between types L and R.
2563
2564          For every type T, where T is a pointer or pointer-to-member
2565          type, there exist candidate operator functions of the form T
2566          operator?(bool, T, T);  */
2567
2568       if (promoted_arithmetic_type_p (type1)
2569           && promoted_arithmetic_type_p (type2))
2570         /* That's OK.  */
2571         break;
2572
2573       /* Otherwise, the types should be pointers.  */
2574       if (!(TYPE_PTR_P (type1) || TYPE_PTR_TO_MEMBER_P (type1))
2575           || !(TYPE_PTR_P (type2) || TYPE_PTR_TO_MEMBER_P (type2)))
2576         return;
2577
2578       /* We don't check that the two types are the same; the logic
2579          below will actually create two candidates; one in which both
2580          parameter types are TYPE1, and one in which both parameter
2581          types are TYPE2.  */
2582       break;
2583
2584     case REALPART_EXPR:
2585     case IMAGPART_EXPR:
2586       if (ARITHMETIC_TYPE_P (type1))
2587         break;
2588       return;
2589  
2590     default:
2591       gcc_unreachable ();
2592     }
2593
2594   /* If we're dealing with two pointer types or two enumeral types,
2595      we need candidates for both of them.  */
2596   if (type2 && !same_type_p (type1, type2)
2597       && TREE_CODE (type1) == TREE_CODE (type2)
2598       && (TREE_CODE (type1) == REFERENCE_TYPE
2599           || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2600           || (TYPE_PTRMEM_P (type1) && TYPE_PTRMEM_P (type2))
2601           || TYPE_PTRMEMFUNC_P (type1)
2602           || MAYBE_CLASS_TYPE_P (type1)
2603           || TREE_CODE (type1) == ENUMERAL_TYPE))
2604     {
2605       if (TYPE_PTR_P (type1) || TYPE_PTR_TO_MEMBER_P (type1))
2606         {
2607           tree cptype = composite_pointer_type (type1, type2,
2608                                                 error_mark_node,
2609                                                 error_mark_node,
2610                                                 CPO_CONVERSION,
2611                                                 tf_none);
2612           if (cptype != error_mark_node)
2613             {
2614               build_builtin_candidate
2615                 (candidates, fnname, cptype, cptype, args, argtypes, flags);
2616               return;
2617             }
2618         }
2619
2620       build_builtin_candidate
2621         (candidates, fnname, type1, type1, args, argtypes, flags);
2622       build_builtin_candidate
2623         (candidates, fnname, type2, type2, args, argtypes, flags);
2624       return;
2625     }
2626
2627   build_builtin_candidate
2628     (candidates, fnname, type1, type2, args, argtypes, flags);
2629 }
2630
2631 tree
2632 type_decays_to (tree type)
2633 {
2634   if (TREE_CODE (type) == ARRAY_TYPE)
2635     return build_pointer_type (TREE_TYPE (type));
2636   if (TREE_CODE (type) == FUNCTION_TYPE)
2637     return build_pointer_type (type);
2638   return type;
2639 }
2640
2641 /* There are three conditions of builtin candidates:
2642
2643    1) bool-taking candidates.  These are the same regardless of the input.
2644    2) pointer-pair taking candidates.  These are generated for each type
2645       one of the input types converts to.
2646    3) arithmetic candidates.  According to the standard, we should generate
2647       all of these, but I'm trying not to...
2648
2649    Here we generate a superset of the possible candidates for this particular
2650    case.  That is a subset of the full set the standard defines, plus some
2651    other cases which the standard disallows. add_builtin_candidate will
2652    filter out the invalid set.  */
2653
2654 static void
2655 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
2656                         enum tree_code code2, tree fnname, tree *args,
2657                         int flags)
2658 {
2659   int ref1, i;
2660   int enum_p = 0;
2661   tree type, argtypes[3], t;
2662   /* TYPES[i] is the set of possible builtin-operator parameter types
2663      we will consider for the Ith argument.  */
2664   VEC(tree,gc) *types[2];
2665   unsigned ix;
2666
2667   for (i = 0; i < 3; ++i)
2668     {
2669       if (args[i])
2670         argtypes[i] = unlowered_expr_type (args[i]);
2671       else
2672         argtypes[i] = NULL_TREE;
2673     }
2674
2675   switch (code)
2676     {
2677 /* 4 For every pair T, VQ), where T is an arithmetic or  enumeration  type,
2678      and  VQ  is  either  volatile or empty, there exist candidate operator
2679      functions of the form
2680                  VQ T&   operator++(VQ T&);  */
2681
2682     case POSTINCREMENT_EXPR:
2683     case PREINCREMENT_EXPR:
2684     case POSTDECREMENT_EXPR:
2685     case PREDECREMENT_EXPR:
2686     case MODIFY_EXPR:
2687       ref1 = 1;
2688       break;
2689
2690 /* 24There also exist candidate operator functions of the form
2691              bool    operator!(bool);
2692              bool    operator&&(bool, bool);
2693              bool    operator||(bool, bool);  */
2694
2695     case TRUTH_NOT_EXPR:
2696       build_builtin_candidate
2697         (candidates, fnname, boolean_type_node,
2698          NULL_TREE, args, argtypes, flags);
2699       return;
2700
2701     case TRUTH_ORIF_EXPR:
2702     case TRUTH_ANDIF_EXPR:
2703       build_builtin_candidate
2704         (candidates, fnname, boolean_type_node,
2705          boolean_type_node, args, argtypes, flags);
2706       return;
2707
2708     case ADDR_EXPR:
2709     case COMPOUND_EXPR:
2710     case COMPONENT_REF:
2711       return;
2712
2713     case COND_EXPR:
2714     case EQ_EXPR:
2715     case NE_EXPR:
2716     case LT_EXPR:
2717     case LE_EXPR:
2718     case GT_EXPR:
2719     case GE_EXPR:
2720       enum_p = 1;
2721       /* Fall through.  */
2722
2723     default:
2724       ref1 = 0;
2725     }
2726
2727   types[0] = make_tree_vector ();
2728   types[1] = make_tree_vector ();
2729
2730   for (i = 0; i < 2; ++i)
2731     {
2732       if (! args[i])
2733         ;
2734       else if (MAYBE_CLASS_TYPE_P (argtypes[i]))
2735         {
2736           tree convs;
2737
2738           if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
2739             return;
2740
2741           convs = lookup_conversions (argtypes[i]);
2742
2743           if (code == COND_EXPR)
2744             {
2745               if (real_lvalue_p (args[i]))
2746                 VEC_safe_push (tree, gc, types[i],
2747                                build_reference_type (argtypes[i]));
2748
2749               VEC_safe_push (tree, gc, types[i],
2750                              TYPE_MAIN_VARIANT (argtypes[i]));
2751             }
2752
2753           else if (! convs)
2754             return;
2755
2756           for (; convs; convs = TREE_CHAIN (convs))
2757             {
2758               type = TREE_TYPE (convs);
2759
2760               if (i == 0 && ref1
2761                   && (TREE_CODE (type) != REFERENCE_TYPE
2762                       || CP_TYPE_CONST_P (TREE_TYPE (type))))
2763                 continue;
2764
2765               if (code == COND_EXPR && TREE_CODE (type) == REFERENCE_TYPE)
2766                 VEC_safe_push (tree, gc, types[i], type);
2767
2768               type = non_reference (type);
2769               if (i != 0 || ! ref1)
2770                 {
2771                   type = cv_unqualified (type_decays_to (type));
2772                   if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
2773                     VEC_safe_push (tree, gc, types[i], type);
2774                   if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
2775                     type = type_promotes_to (type);
2776                 }
2777
2778               if (! vec_member (type, types[i]))
2779                 VEC_safe_push (tree, gc, types[i], type);
2780             }
2781         }
2782       else
2783         {
2784           if (code == COND_EXPR && real_lvalue_p (args[i]))
2785             VEC_safe_push (tree, gc, types[i],
2786                            build_reference_type (argtypes[i]));
2787           type = non_reference (argtypes[i]);
2788           if (i != 0 || ! ref1)
2789             {
2790               type = cv_unqualified (type_decays_to (type));
2791               if (enum_p && UNSCOPED_ENUM_P (type))
2792                 VEC_safe_push (tree, gc, types[i], type);
2793               if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
2794                 type = type_promotes_to (type);
2795             }
2796           VEC_safe_push (tree, gc, types[i], type);
2797         }
2798     }
2799
2800   /* Run through the possible parameter types of both arguments,
2801      creating candidates with those parameter types.  */
2802   FOR_EACH_VEC_ELT_REVERSE (tree, types[0], ix, t)
2803     {
2804       unsigned jx;
2805       tree u;
2806
2807       if (!VEC_empty (tree, types[1]))
2808         FOR_EACH_VEC_ELT_REVERSE (tree, types[1], jx, u)
2809           add_builtin_candidate
2810             (candidates, code, code2, fnname, t,
2811              u, args, argtypes, flags);
2812       else
2813         add_builtin_candidate
2814           (candidates, code, code2, fnname, t,
2815            NULL_TREE, args, argtypes, flags);
2816     }
2817
2818   release_tree_vector (types[0]);
2819   release_tree_vector (types[1]);
2820 }
2821
2822
2823 /* If TMPL can be successfully instantiated as indicated by
2824    EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
2825
2826    TMPL is the template.  EXPLICIT_TARGS are any explicit template
2827    arguments.  ARGLIST is the arguments provided at the call-site.
2828    This does not change ARGLIST.  The RETURN_TYPE is the desired type
2829    for conversion operators.  If OBJ is NULL_TREE, FLAGS and CTYPE are
2830    as for add_function_candidate.  If an OBJ is supplied, FLAGS and
2831    CTYPE are ignored, and OBJ is as for add_conv_candidate.  */
2832
2833 static struct z_candidate*
2834 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
2835                              tree ctype, tree explicit_targs, tree first_arg,
2836                              const VEC(tree,gc) *arglist, tree return_type,
2837                              tree access_path, tree conversion_path,
2838                              int flags, tree obj, unification_kind_t strict)
2839 {
2840   int ntparms = DECL_NTPARMS (tmpl);
2841   tree targs = make_tree_vec (ntparms);
2842   unsigned int len = VEC_length (tree, arglist);
2843   unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
2844   unsigned int skip_without_in_chrg = 0;
2845   tree first_arg_without_in_chrg = first_arg;
2846   tree *args_without_in_chrg;
2847   unsigned int nargs_without_in_chrg;
2848   unsigned int ia, ix;
2849   tree arg;
2850   struct z_candidate *cand;
2851   int i;
2852   tree fn;
2853   struct rejection_reason *reason = NULL;
2854   int errs;
2855
2856   /* We don't do deduction on the in-charge parameter, the VTT
2857      parameter or 'this'.  */
2858   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
2859     {
2860       if (first_arg_without_in_chrg != NULL_TREE)
2861         first_arg_without_in_chrg = NULL_TREE;
2862       else
2863         ++skip_without_in_chrg;
2864     }
2865
2866   if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
2867        || DECL_BASE_CONSTRUCTOR_P (tmpl))
2868       && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
2869     {
2870       if (first_arg_without_in_chrg != NULL_TREE)
2871         first_arg_without_in_chrg = NULL_TREE;
2872       else
2873         ++skip_without_in_chrg;
2874     }
2875
2876   if (len < skip_without_in_chrg)
2877     return NULL;
2878
2879   nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
2880                            + (len - skip_without_in_chrg));
2881   args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
2882   ia = 0;
2883   if (first_arg_without_in_chrg != NULL_TREE)
2884     {
2885       args_without_in_chrg[ia] = first_arg_without_in_chrg;
2886       ++ia;
2887     }
2888   for (ix = skip_without_in_chrg;
2889        VEC_iterate (tree, arglist, ix, arg);
2890        ++ix)
2891     {
2892       args_without_in_chrg[ia] = arg;
2893       ++ia;
2894     }
2895   gcc_assert (ia == nargs_without_in_chrg);
2896
2897   errs = errorcount+sorrycount;
2898   i = fn_type_unification (tmpl, explicit_targs, targs,
2899                            args_without_in_chrg,
2900                            nargs_without_in_chrg,
2901                            return_type, strict, flags, false);
2902
2903   if (i != 0)
2904     {
2905       /* Don't repeat unification later if it already resulted in errors.  */
2906       if (errorcount+sorrycount == errs)
2907         reason = template_unification_rejection (tmpl, explicit_targs,
2908                                                  targs, args_without_in_chrg,
2909                                                  nargs_without_in_chrg,
2910                                                  return_type, strict, flags);
2911       else
2912         reason = template_unification_error_rejection ();
2913       goto fail;
2914     }
2915
2916   fn = instantiate_template (tmpl, targs, tf_none);
2917   if (fn == error_mark_node)
2918     {
2919       reason = template_instantiation_rejection (tmpl, targs);
2920       goto fail;
2921     }
2922
2923   /* In [class.copy]:
2924
2925        A member function template is never instantiated to perform the
2926        copy of a class object to an object of its class type.
2927
2928      It's a little unclear what this means; the standard explicitly
2929      does allow a template to be used to copy a class.  For example,
2930      in:
2931
2932        struct A {
2933          A(A&);
2934          template <class T> A(const T&);
2935        };
2936        const A f ();
2937        void g () { A a (f ()); }
2938
2939      the member template will be used to make the copy.  The section
2940      quoted above appears in the paragraph that forbids constructors
2941      whose only parameter is (a possibly cv-qualified variant of) the
2942      class type, and a logical interpretation is that the intent was
2943      to forbid the instantiation of member templates which would then
2944      have that form.  */
2945   if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
2946     {
2947       tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
2948       if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
2949                                     ctype))
2950         {
2951           reason = invalid_copy_with_fn_template_rejection ();
2952           goto fail;
2953         }
2954     }
2955
2956   if (obj != NULL_TREE)
2957     /* Aha, this is a conversion function.  */
2958     cand = add_conv_candidate (candidates, fn, obj, first_arg, arglist,
2959                                access_path, conversion_path);
2960   else
2961     cand = add_function_candidate (candidates, fn, ctype,
2962                                    first_arg, arglist, access_path,
2963                                    conversion_path, flags);
2964   if (DECL_TI_TEMPLATE (fn) != tmpl)
2965     /* This situation can occur if a member template of a template
2966        class is specialized.  Then, instantiate_template might return
2967        an instantiation of the specialization, in which case the
2968        DECL_TI_TEMPLATE field will point at the original
2969        specialization.  For example:
2970
2971          template <class T> struct S { template <class U> void f(U);
2972                                        template <> void f(int) {}; };
2973          S<double> sd;
2974          sd.f(3);
2975
2976        Here, TMPL will be template <class U> S<double>::f(U).
2977        And, instantiate template will give us the specialization
2978        template <> S<double>::f(int).  But, the DECL_TI_TEMPLATE field
2979        for this will point at template <class T> template <> S<T>::f(int),
2980        so that we can find the definition.  For the purposes of
2981        overload resolution, however, we want the original TMPL.  */
2982     cand->template_decl = build_template_info (tmpl, targs);
2983   else
2984     cand->template_decl = DECL_TEMPLATE_INFO (fn);
2985   cand->explicit_targs = explicit_targs;
2986
2987   return cand;
2988  fail:
2989   return add_candidate (candidates, tmpl, first_arg, arglist, nargs, NULL,
2990                         access_path, conversion_path, 0, reason);
2991 }
2992
2993
2994 static struct z_candidate *
2995 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
2996                         tree explicit_targs, tree first_arg,
2997                         const VEC(tree,gc) *arglist, tree return_type,
2998                         tree access_path, tree conversion_path, int flags,
2999                         unification_kind_t strict)
3000 {
3001   return
3002     add_template_candidate_real (candidates, tmpl, ctype,
3003                                  explicit_targs, first_arg, arglist,
3004                                  return_type, access_path, conversion_path,
3005                                  flags, NULL_TREE, strict);
3006 }
3007
3008
3009 static struct z_candidate *
3010 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3011                              tree obj, tree first_arg,
3012                              const VEC(tree,gc) *arglist,
3013                              tree return_type, tree access_path,
3014                              tree conversion_path)
3015 {
3016   return
3017     add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3018                                  first_arg, arglist, return_type, access_path,
3019                                  conversion_path, 0, obj, DEDUCE_CONV);
3020 }
3021
3022 /* The CANDS are the set of candidates that were considered for
3023    overload resolution.  Return the set of viable candidates, or CANDS
3024    if none are viable.  If any of the candidates were viable, set
3025    *ANY_VIABLE_P to true.  STRICT_P is true if a candidate should be
3026    considered viable only if it is strictly viable.  */
3027
3028 static struct z_candidate*
3029 splice_viable (struct z_candidate *cands,
3030                bool strict_p,
3031                bool *any_viable_p)
3032 {
3033   struct z_candidate *viable;
3034   struct z_candidate **last_viable;
3035   struct z_candidate **cand;
3036
3037   /* Be strict inside templates, since build_over_call won't actually
3038      do the conversions to get pedwarns.  */
3039   if (processing_template_decl)
3040     strict_p = true;
3041
3042   viable = NULL;
3043   last_viable = &viable;
3044   *any_viable_p = false;
3045
3046   cand = &cands;
3047   while (*cand)
3048     {
3049       struct z_candidate *c = *cand;
3050       if (strict_p ? c->viable == 1 : c->viable)
3051         {
3052           *last_viable = c;
3053           *cand = c->next;
3054           c->next = NULL;
3055           last_viable = &c->next;
3056           *any_viable_p = true;
3057         }
3058       else
3059         cand = &c->next;
3060     }
3061
3062   return viable ? viable : cands;
3063 }
3064
3065 static bool
3066 any_strictly_viable (struct z_candidate *cands)
3067 {
3068   for (; cands; cands = cands->next)
3069     if (cands->viable == 1)
3070       return true;
3071   return false;
3072 }
3073
3074 /* OBJ is being used in an expression like "OBJ.f (...)".  In other
3075    words, it is about to become the "this" pointer for a member
3076    function call.  Take the address of the object.  */
3077
3078 static tree
3079 build_this (tree obj)
3080 {
3081   /* In a template, we are only concerned about the type of the
3082      expression, so we can take a shortcut.  */
3083   if (processing_template_decl)
3084     return build_address (obj);
3085
3086   return cp_build_addr_expr (obj, tf_warning_or_error);
3087 }
3088
3089 /* Returns true iff functions are equivalent. Equivalent functions are
3090    not '==' only if one is a function-local extern function or if
3091    both are extern "C".  */
3092
3093 static inline int
3094 equal_functions (tree fn1, tree fn2)
3095 {
3096   if (TREE_CODE (fn1) != TREE_CODE (fn2))
3097     return 0;
3098   if (TREE_CODE (fn1) == TEMPLATE_DECL)
3099     return fn1 == fn2;
3100   if (DECL_LOCAL_FUNCTION_P (fn1) || DECL_LOCAL_FUNCTION_P (fn2)
3101       || DECL_EXTERN_C_FUNCTION_P (fn1))
3102     return decls_match (fn1, fn2);
3103   return fn1 == fn2;
3104 }
3105
3106 /* Print information about a candidate being rejected due to INFO.  */
3107
3108 static void
3109 print_conversion_rejection (location_t loc, struct conversion_info *info)
3110 {
3111   if (info->n_arg == -1)
3112     /* Conversion of implicit `this' argument failed.  */
3113     inform (loc, "  no known conversion for implicit "
3114             "%<this%> parameter from %qT to %qT",
3115             info->from_type, info->to_type);
3116   else
3117     inform (loc, "  no known conversion for argument %d from %qT to %qT",
3118             info->n_arg+1, info->from_type, info->to_type);
3119 }
3120
3121 /* Print information about a candidate with WANT parameters and we found
3122    HAVE.  */
3123
3124 static void
3125 print_arity_information (location_t loc, unsigned int have, unsigned int want)
3126 {
3127   inform_n (loc, want,
3128             "  candidate expects %d argument, %d provided",
3129             "  candidate expects %d arguments, %d provided",
3130             want, have);
3131 }
3132
3133 /* Print information about one overload candidate CANDIDATE.  MSGSTR
3134    is the text to print before the candidate itself.
3135
3136    NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3137    to have been run through gettext by the caller.  This wart makes
3138    life simpler in print_z_candidates and for the translators.  */
3139
3140 static void
3141 print_z_candidate (const char *msgstr, struct z_candidate *candidate)
3142 {
3143   const char *msg = (msgstr == NULL
3144                      ? ""
3145                      : ACONCAT ((msgstr, " ", NULL)));
3146   location_t loc = location_of (candidate->fn);
3147
3148   if (TREE_CODE (candidate->fn) == IDENTIFIER_NODE)
3149     {
3150       if (candidate->num_convs == 3)
3151         inform (input_location, "%s%D(%T, %T, %T) <built-in>", msg, candidate->fn,
3152                 candidate->convs[0]->type,
3153                 candidate->convs[1]->type,
3154                 candidate->convs[2]->type);
3155       else if (candidate->num_convs == 2)
3156         inform (input_location, "%s%D(%T, %T) <built-in>", msg, candidate->fn,
3157                 candidate->convs[0]->type,
3158                 candidate->convs[1]->type);
3159       else
3160         inform (input_location, "%s%D(%T) <built-in>", msg, candidate->fn,
3161                 candidate->convs[0]->type);
3162     }
3163   else if (TYPE_P (candidate->fn))
3164     inform (input_location, "%s%T <conversion>", msg, candidate->fn);
3165   else if (candidate->viable == -1)
3166     inform (loc, "%s%#D <near match>", msg, candidate->fn);
3167   else if (DECL_DELETED_FN (STRIP_TEMPLATE (candidate->fn)))
3168     inform (loc, "%s%#D <deleted>", msg, candidate->fn);
3169   else
3170     inform (loc, "%s%#D", msg, candidate->fn);
3171   /* Give the user some information about why this candidate failed.  */
3172   if (candidate->reason != NULL)
3173     {
3174       struct rejection_reason *r = candidate->reason;
3175
3176       switch (r->code)
3177         {
3178         case rr_arity:
3179           print_arity_information (loc, r->u.arity.actual,
3180                                    r->u.arity.expected);
3181           break;
3182         case rr_arg_conversion:
3183           print_conversion_rejection (loc, &r->u.conversion);
3184           break;
3185         case rr_bad_arg_conversion:
3186           print_conversion_rejection (loc, &r->u.bad_conversion);
3187           break;
3188         case rr_explicit_conversion:
3189           inform (loc, "  return type %qT of explicit conversion function "
3190                   "cannot be converted to %qT with a qualification "
3191                   "conversion", r->u.conversion.from_type,
3192                   r->u.conversion.to_type);
3193           break;
3194         case rr_template_conversion:
3195           inform (loc, "  conversion from return type %qT of template "
3196                   "conversion function specialization to %qT is not an "
3197                   "exact match", r->u.conversion.from_type,
3198                   r->u.conversion.to_type);
3199           break;
3200         case rr_template_unification:
3201           /* We use template_unification_error_rejection if unification caused
3202              actual non-SFINAE errors, in which case we don't need to repeat
3203              them here.  */
3204           if (r->u.template_unification.tmpl == NULL_TREE)
3205             {
3206               inform (loc, "  substitution of deduced template arguments "
3207                       "resulted in errors seen above");
3208               break;
3209             }
3210           /* Re-run template unification with diagnostics.  */
3211           inform (loc, "  template argument deduction/substitution failed:");
3212           fn_type_unification (r->u.template_unification.tmpl,
3213                                r->u.template_unification.explicit_targs,
3214                                r->u.template_unification.targs,
3215                                r->u.template_unification.args,
3216                                r->u.template_unification.nargs,
3217                                r->u.template_unification.return_type,
3218                                r->u.template_unification.strict,
3219                                r->u.template_unification.flags,
3220                                true);
3221           break;
3222         case rr_template_instantiation:
3223           /* Re-run template instantiation with diagnostics.  */
3224           instantiate_template (r->u.template_instantiation.tmpl,
3225                                 r->u.template_instantiation.targs,
3226                                 tf_warning_or_error);
3227           break;
3228         case rr_invalid_copy:
3229           inform (loc,
3230                   "  a constructor taking a single argument of its own "
3231                   "class type is invalid");
3232           break;
3233         case rr_none:
3234         default:
3235           /* This candidate didn't have any issues or we failed to
3236              handle a particular code.  Either way...  */
3237           gcc_unreachable ();
3238         }
3239     }
3240 }
3241
3242 static void
3243 print_z_candidates (location_t loc, struct z_candidate *candidates)
3244 {
3245   struct z_candidate *cand1;
3246   struct z_candidate **cand2;
3247   int n_candidates;
3248
3249   if (!candidates)
3250     return;
3251
3252   /* Remove non-viable deleted candidates.  */
3253   cand1 = candidates;
3254   for (cand2 = &cand1; *cand2; )
3255     {
3256       if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
3257           && !(*cand2)->viable
3258           && DECL_DELETED_FN ((*cand2)->fn))
3259         *cand2 = (*cand2)->next;
3260       else
3261         cand2 = &(*cand2)->next;
3262     }
3263   /* ...if there are any non-deleted ones.  */
3264   if (cand1)
3265     candidates = cand1;
3266
3267   /* There may be duplicates in the set of candidates.  We put off
3268      checking this condition as long as possible, since we have no way
3269      to eliminate duplicates from a set of functions in less than n^2
3270      time.  Now we are about to emit an error message, so it is more
3271      permissible to go slowly.  */
3272   for (cand1 = candidates; cand1; cand1 = cand1->next)
3273     {
3274       tree fn = cand1->fn;
3275       /* Skip builtin candidates and conversion functions.  */
3276       if (!DECL_P (fn))
3277         continue;
3278       cand2 = &cand1->next;
3279       while (*cand2)
3280         {
3281           if (DECL_P ((*cand2)->fn)
3282               && equal_functions (fn, (*cand2)->fn))
3283             *cand2 = (*cand2)->next;
3284           else
3285             cand2 = &(*cand2)->next;
3286         }
3287     }
3288
3289   for (n_candidates = 0, cand1 = candidates; cand1; cand1 = cand1->next)
3290     n_candidates++;
3291
3292   inform_n (loc, n_candidates, "candidate is:", "candidates are:");
3293   for (; candidates; candidates = candidates->next)
3294     print_z_candidate (NULL, candidates);
3295 }
3296
3297 /* USER_SEQ is a user-defined conversion sequence, beginning with a
3298    USER_CONV.  STD_SEQ is the standard conversion sequence applied to
3299    the result of the conversion function to convert it to the final
3300    desired type.  Merge the two sequences into a single sequence,
3301    and return the merged sequence.  */
3302
3303 static conversion *
3304 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
3305 {
3306   conversion **t;
3307   bool bad = user_seq->bad_p;
3308
3309   gcc_assert (user_seq->kind == ck_user);
3310
3311   /* Find the end of the second conversion sequence.  */
3312   for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
3313     {
3314       /* The entire sequence is a user-conversion sequence.  */
3315       (*t)->user_conv_p = true;
3316       if (bad)
3317         (*t)->bad_p = true;
3318     }
3319
3320   /* Replace the identity conversion with the user conversion
3321      sequence.  */
3322   *t = user_seq;
3323
3324   return std_seq;
3325 }
3326
3327 /* Handle overload resolution for initializing an object of class type from
3328    an initializer list.  First we look for a suitable constructor that
3329    takes a std::initializer_list; if we don't find one, we then look for a
3330    non-list constructor.
3331
3332    Parameters are as for add_candidates, except that the arguments are in
3333    the form of a CONSTRUCTOR (the initializer list) rather than a VEC, and
3334    the RETURN_TYPE parameter is replaced by TOTYPE, the desired type.  */
3335
3336 static void
3337 add_list_candidates (tree fns, tree first_arg,
3338                      tree init_list, tree totype,
3339                      tree explicit_targs, bool template_only,
3340                      tree conversion_path, tree access_path,
3341                      int flags,
3342                      struct z_candidate **candidates)
3343 {
3344   VEC(tree,gc) *args;
3345
3346   gcc_assert (*candidates == NULL);
3347
3348   /* We're looking for a ctor for list-initialization.  */
3349   flags |= LOOKUP_LIST_INIT_CTOR;
3350   /* And we don't allow narrowing conversions.  We also use this flag to
3351      avoid the copy constructor call for copy-list-initialization.  */
3352   flags |= LOOKUP_NO_NARROWING;
3353
3354   /* Always use the default constructor if the list is empty (DR 990).  */
3355   if (CONSTRUCTOR_NELTS (init_list) == 0
3356       && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
3357     ;
3358   /* If the class has a list ctor, try passing the list as a single
3359      argument first, but only consider list ctors.  */
3360   else if (TYPE_HAS_LIST_CTOR (totype))
3361     {
3362       flags |= LOOKUP_LIST_ONLY;
3363       args = make_tree_vector_single (init_list);
3364       add_candidates (fns, first_arg, args, NULL_TREE,
3365                       explicit_targs, template_only, conversion_path,
3366                       access_path, flags, candidates);
3367       if (any_strictly_viable (*candidates))
3368         return;
3369     }
3370
3371   args = ctor_to_vec (init_list);
3372
3373   /* We aren't looking for list-ctors anymore.  */
3374   flags &= ~LOOKUP_LIST_ONLY;
3375   /* We allow more user-defined conversions within an init-list.  */
3376   flags &= ~LOOKUP_NO_CONVERSION;
3377
3378   add_candidates (fns, first_arg, args, NULL_TREE,
3379                   explicit_targs, template_only, conversion_path,
3380                   access_path, flags, candidates);
3381 }
3382
3383 /* Returns the best overload candidate to perform the requested
3384    conversion.  This function is used for three the overloading situations
3385    described in [over.match.copy], [over.match.conv], and [over.match.ref].
3386    If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
3387    per [dcl.init.ref], so we ignore temporary bindings.  */
3388
3389 static struct z_candidate *
3390 build_user_type_conversion_1 (tree totype, tree expr, int flags)
3391 {
3392   struct z_candidate *candidates, *cand;
3393   tree fromtype;
3394   tree ctors = NULL_TREE;
3395   tree conv_fns = NULL_TREE;
3396   conversion *conv = NULL;
3397   tree first_arg = NULL_TREE;
3398   VEC(tree,gc) *args = NULL;
3399   bool any_viable_p;
3400   int convflags;
3401
3402   if (!expr)
3403     return NULL;
3404
3405   fromtype = TREE_TYPE (expr);
3406
3407   /* We represent conversion within a hierarchy using RVALUE_CONV and
3408      BASE_CONV, as specified by [over.best.ics]; these become plain
3409      constructor calls, as specified in [dcl.init].  */
3410   gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
3411               || !DERIVED_FROM_P (totype, fromtype));
3412
3413   if (MAYBE_CLASS_TYPE_P (totype))
3414     /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
3415        creating a garbage BASELINK; constructors can't be inherited.  */
3416     ctors = lookup_fnfields_slot (totype, complete_ctor_identifier);
3417
3418   if (MAYBE_CLASS_TYPE_P (fromtype))
3419     {
3420       tree to_nonref = non_reference (totype);
3421       if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
3422           (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
3423            && DERIVED_FROM_P (to_nonref, fromtype)))
3424         {
3425           /* [class.conv.fct] A conversion function is never used to
3426              convert a (possibly cv-qualified) object to the (possibly
3427              cv-qualified) same object type (or a reference to it), to a
3428              (possibly cv-qualified) base class of that type (or a
3429              reference to it)...  */
3430         }
3431       else
3432         conv_fns = lookup_conversions (fromtype);
3433     }
3434
3435   candidates = 0;
3436   flags |= LOOKUP_NO_CONVERSION;
3437   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
3438     flags |= LOOKUP_NO_NARROWING;
3439
3440   /* It's OK to bind a temporary for converting constructor arguments, but
3441      not in converting the return value of a conversion operator.  */
3442   convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION);
3443   flags &= ~LOOKUP_NO_TEMP_BIND;
3444
3445   if (ctors)
3446     {
3447       int ctorflags = flags;
3448
3449       first_arg = build_int_cst (build_pointer_type (totype), 0);
3450
3451       /* We should never try to call the abstract or base constructor
3452          from here.  */
3453       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_CURRENT (ctors))
3454                   && !DECL_HAS_VTT_PARM_P (OVL_CURRENT (ctors)));
3455
3456       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
3457         {
3458           /* List-initialization.  */
3459           add_list_candidates (ctors, first_arg, expr, totype, NULL_TREE,
3460                                false, TYPE_BINFO (totype), TYPE_BINFO (totype),
3461                                ctorflags, &candidates);
3462         }
3463       else
3464         {
3465           args = make_tree_vector_single (expr);
3466           add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
3467                           TYPE_BINFO (totype), TYPE_BINFO (totype),
3468                           ctorflags, &candidates);
3469         }
3470
3471       for (cand = candidates; cand; cand = cand->next)
3472         {
3473           cand->second_conv = build_identity_conv (totype, NULL_TREE);
3474
3475           /* If totype isn't a reference, and LOOKUP_NO_TEMP_BIND isn't
3476              set, then this is copy-initialization.  In that case, "The
3477              result of the call is then used to direct-initialize the
3478              object that is the destination of the copy-initialization."
3479              [dcl.init]
3480
3481              We represent this in the conversion sequence with an
3482              rvalue conversion, which means a constructor call.  */
3483           if (TREE_CODE (totype) != REFERENCE_TYPE
3484               && !(convflags & LOOKUP_NO_TEMP_BIND))
3485             cand->second_conv
3486               = build_conv (ck_rvalue, totype, cand->second_conv);
3487         }
3488     }
3489
3490   if (conv_fns)
3491     first_arg = build_this (expr);
3492
3493   for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
3494     {
3495       tree conversion_path = TREE_PURPOSE (conv_fns);
3496       struct z_candidate *old_candidates;
3497
3498       /* If we are called to convert to a reference type, we are trying to
3499          find a direct binding, so don't even consider temporaries.  If
3500          we don't find a direct binding, the caller will try again to
3501          look for a temporary binding.  */
3502       if (TREE_CODE (totype) == REFERENCE_TYPE)
3503         convflags |= LOOKUP_NO_TEMP_BIND;
3504
3505       old_candidates = candidates;
3506       add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
3507                       NULL_TREE, false,
3508                       conversion_path, TYPE_BINFO (fromtype),
3509                       flags, &candidates);
3510
3511       for (cand = candidates; cand != old_candidates; cand = cand->next)
3512         {
3513           tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
3514           conversion *ics
3515             = implicit_conversion (totype,
3516                                    rettype,
3517                                    0,
3518                                    /*c_cast_p=*/false, convflags);
3519
3520           /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
3521              copy-initialization.  In that case, "The result of the
3522              call is then used to direct-initialize the object that is
3523              the destination of the copy-initialization."  [dcl.init]
3524
3525              We represent this in the conversion sequence with an
3526              rvalue conversion, which means a constructor call.  But
3527              don't add a second rvalue conversion if there's already
3528              one there.  Which there really shouldn't be, but it's
3529              harmless since we'd add it here anyway. */
3530           if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
3531               && !(convflags & LOOKUP_NO_TEMP_BIND))
3532             ics = build_conv (ck_rvalue, totype, ics);
3533
3534           cand->second_conv = ics;
3535
3536           if (!ics)
3537             {
3538               cand->viable = 0;
3539               cand->reason = arg_conversion_rejection (NULL_TREE, -1,
3540                                                        rettype, totype);
3541             }
3542           else if (DECL_NONCONVERTING_P (cand->fn)
3543                    && ics->rank > cr_exact)
3544             {
3545               /* 13.3.1.5: For direct-initialization, those explicit
3546                  conversion functions that are not hidden within S and
3547                  yield type T or a type that can be converted to type T
3548                  with a qualification conversion (4.4) are also candidate
3549                  functions.  */
3550               /* 13.3.1.6 doesn't have a parallel restriction, but it should;
3551                  I've raised this issue with the committee. --jason 9/2011 */
3552               cand->viable = -1;
3553               cand->reason = explicit_conversion_rejection (rettype, totype);
3554             }
3555           else if (cand->viable == 1 && ics->bad_p)
3556             {
3557               cand->viable = -1;
3558               cand->reason
3559                 = bad_arg_conversion_rejection (NULL_TREE, -1,
3560                                                 rettype, totype);
3561             }
3562           else if (primary_template_instantiation_p (cand->fn)
3563                    && ics->rank > cr_exact)
3564             {
3565               /* 13.3.3.1.2: If the user-defined conversion is specified by
3566                  a specialization of a conversion function template, the
3567                  second standard conversion sequence shall have exact match
3568                  rank.  */
3569               cand->viable = -1;
3570               cand->reason = template_conversion_rejection (rettype, totype);
3571             }
3572         }
3573     }
3574
3575   candidates = splice_viable (candidates, pedantic, &any_viable_p);
3576   if (!any_viable_p)
3577     {
3578       if (args)
3579         release_tree_vector (args);
3580       return NULL;
3581     }
3582
3583   cand = tourney (candidates);
3584   if (cand == 0)
3585     {
3586       if (flags & LOOKUP_COMPLAIN)
3587         {
3588           error ("conversion from %qT to %qT is ambiguous",
3589                     fromtype, totype);
3590           print_z_candidates (location_of (expr), candidates);
3591         }
3592
3593       cand = candidates;        /* any one will do */
3594       cand->second_conv = build_ambiguous_conv (totype, expr);
3595       cand->second_conv->user_conv_p = true;
3596       if (!any_strictly_viable (candidates))
3597         cand->second_conv->bad_p = true;
3598       /* If there are viable candidates, don't set ICS_BAD_FLAG; an
3599          ambiguous conversion is no worse than another user-defined
3600          conversion.  */
3601
3602       return cand;
3603     }
3604
3605   /* Build the user conversion sequence.  */
3606   conv = build_conv
3607     (ck_user,
3608      (DECL_CONSTRUCTOR_P (cand->fn)
3609       ? totype : non_reference (TREE_TYPE (TREE_TYPE (cand->fn)))),
3610      build_identity_conv (TREE_TYPE (expr), expr));
3611   conv->cand = cand;
3612   if (cand->viable == -1)
3613     conv->bad_p = true;
3614
3615   /* Remember that this was a list-initialization.  */
3616   if (flags & LOOKUP_NO_NARROWING)
3617     conv->check_narrowing = true;
3618
3619   /* Combine it with the second conversion sequence.  */
3620   cand->second_conv = merge_conversion_sequences (conv,
3621                                                   cand->second_conv);
3622
3623   return cand;
3624 }
3625
3626 /* Wrapper for above. */
3627
3628 tree
3629 build_user_type_conversion (tree totype, tree expr, int flags)
3630 {
3631   struct z_candidate *cand;
3632   tree ret;
3633
3634   bool subtime = timevar_cond_start (TV_OVERLOAD);
3635   cand = build_user_type_conversion_1 (totype, expr, flags);
3636
3637   if (cand)
3638     {
3639       if (cand->second_conv->kind == ck_ambig)
3640         ret = error_mark_node;
3641       else
3642         {
3643           expr = convert_like (cand->second_conv, expr, tf_warning_or_error);
3644           ret = convert_from_reference (expr);
3645         }
3646     }
3647   else
3648     ret = NULL_TREE;
3649
3650   timevar_cond_stop (TV_OVERLOAD, subtime);
3651   return ret;
3652 }
3653
3654 /* Subroutine of convert_nontype_argument.
3655
3656    EXPR is an argument for a template non-type parameter of integral or
3657    enumeration type.  Do any necessary conversions (that are permitted for
3658    non-type arguments) to convert it to the parameter type.
3659
3660    If conversion is successful, returns the converted expression;
3661    otherwise, returns error_mark_node.  */
3662
3663 tree
3664 build_integral_nontype_arg_conv (tree type, tree expr, tsubst_flags_t complain)
3665 {
3666   conversion *conv;
3667   void *p;
3668   tree t;
3669
3670   if (error_operand_p (expr))
3671     return error_mark_node;
3672
3673   gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
3674
3675   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3676   p = conversion_obstack_alloc (0);
3677
3678   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
3679                               /*c_cast_p=*/false,
3680                               LOOKUP_IMPLICIT);
3681
3682   /* for a non-type template-parameter of integral or
3683      enumeration type, integral promotions (4.5) and integral
3684      conversions (4.7) are applied.  */
3685   /* It should be sufficient to check the outermost conversion step, since
3686      there are no qualification conversions to integer type.  */
3687   if (conv)
3688     switch (conv->kind)
3689       {
3690         /* A conversion function is OK.  If it isn't constexpr, we'll
3691            complain later that the argument isn't constant.  */
3692       case ck_user:
3693         /* The lvalue-to-rvalue conversion is OK.  */
3694       case ck_rvalue:
3695       case ck_identity:
3696         break;
3697
3698       case ck_std:
3699         t = conv->u.next->type;
3700         if (INTEGRAL_OR_ENUMERATION_TYPE_P (t))
3701           break;
3702
3703         if (complain & tf_error)
3704           error ("conversion from %qT to %qT not considered for "
3705                  "non-type template argument", t, type);
3706         /* and fall through.  */
3707
3708       default:
3709         conv = NULL;
3710         break;
3711       }
3712
3713   if (conv)
3714     expr = convert_like (conv, expr, complain);
3715   else
3716     expr = error_mark_node;
3717
3718   /* Free all the conversions we allocated.  */
3719   obstack_free (&conversion_obstack, p);
3720
3721   return expr;
3722 }
3723
3724 /* Do any initial processing on the arguments to a function call.  */
3725
3726 static VEC(tree,gc) *
3727 resolve_args (VEC(tree,gc) *args, tsubst_flags_t complain)
3728 {
3729   unsigned int ix;
3730   tree arg;
3731
3732   FOR_EACH_VEC_ELT (tree, args, ix, arg)
3733     {
3734       if (error_operand_p (arg))
3735         return NULL;
3736       else if (VOID_TYPE_P (TREE_TYPE (arg)))
3737         {
3738           if (complain & tf_error)
3739             error ("invalid use of void expression");
3740           return NULL;
3741         }
3742       else if (invalid_nonstatic_memfn_p (arg, tf_warning_or_error))
3743         return NULL;
3744     }
3745   return args;
3746 }
3747
3748 /* Perform overload resolution on FN, which is called with the ARGS.
3749
3750    Return the candidate function selected by overload resolution, or
3751    NULL if the event that overload resolution failed.  In the case
3752    that overload resolution fails, *CANDIDATES will be the set of
3753    candidates considered, and ANY_VIABLE_P will be set to true or
3754    false to indicate whether or not any of the candidates were
3755    viable.
3756
3757    The ARGS should already have gone through RESOLVE_ARGS before this
3758    function is called.  */
3759
3760 static struct z_candidate *
3761 perform_overload_resolution (tree fn,
3762                              const VEC(tree,gc) *args,
3763                              struct z_candidate **candidates,
3764                              bool *any_viable_p)
3765 {
3766   struct z_candidate *cand;
3767   tree explicit_targs;
3768   int template_only;
3769
3770   bool subtime = timevar_cond_start (TV_OVERLOAD);
3771
3772   explicit_targs = NULL_TREE;
3773   template_only = 0;
3774
3775   *candidates = NULL;
3776   *any_viable_p = true;
3777
3778   /* Check FN.  */
3779   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
3780               || TREE_CODE (fn) == TEMPLATE_DECL
3781               || TREE_CODE (fn) == OVERLOAD
3782               || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
3783
3784   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3785     {
3786       explicit_targs = TREE_OPERAND (fn, 1);
3787       fn = TREE_OPERAND (fn, 0);
3788       template_only = 1;
3789     }
3790
3791   /* Add the various candidate functions.  */
3792   add_candidates (fn, NULL_TREE, args, NULL_TREE,
3793                   explicit_targs, template_only,
3794                   /*conversion_path=*/NULL_TREE,
3795                   /*access_path=*/NULL_TREE,
3796                   LOOKUP_NORMAL,
3797                   candidates);
3798
3799   *candidates = splice_viable (*candidates, pedantic, any_viable_p);
3800   if (*any_viable_p)
3801     cand = tourney (*candidates);
3802   else
3803     cand = NULL;
3804
3805   timevar_cond_stop (TV_OVERLOAD, subtime);
3806   return cand;
3807 }
3808
3809 /* Print an error message about being unable to build a call to FN with
3810    ARGS.  ANY_VIABLE_P indicates whether any candidate functions could
3811    be located; CANDIDATES is a possibly empty list of such
3812    functions.  */
3813
3814 static void
3815 print_error_for_call_failure (tree fn, VEC(tree,gc) *args, bool any_viable_p,
3816                               struct z_candidate *candidates)
3817 {
3818   tree name = DECL_NAME (OVL_CURRENT (fn));
3819   location_t loc = location_of (name);
3820
3821   if (!any_viable_p)
3822     error_at (loc, "no matching function for call to %<%D(%A)%>",
3823               name, build_tree_list_vec (args));
3824   else
3825     error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
3826               name, build_tree_list_vec (args));
3827   if (candidates)
3828     print_z_candidates (loc, candidates);
3829 }
3830
3831 /* Return an expression for a call to FN (a namespace-scope function,
3832    or a static member function) with the ARGS.  This may change
3833    ARGS.  */
3834
3835 tree
3836 build_new_function_call (tree fn, VEC(tree,gc) **args, bool koenig_p, 
3837                          tsubst_flags_t complain)
3838 {
3839   struct z_candidate *candidates, *cand;
3840   bool any_viable_p;
3841   void *p;
3842   tree result;
3843
3844   if (args != NULL && *args != NULL)
3845     {
3846       *args = resolve_args (*args, complain);
3847       if (*args == NULL)
3848         return error_mark_node;
3849     }
3850
3851   if (flag_tm)
3852     tm_malloc_replacement (fn);
3853
3854   /* If this function was found without using argument dependent
3855      lookup, then we want to ignore any undeclared friend
3856      functions.  */
3857   if (!koenig_p)
3858     {
3859       tree orig_fn = fn;
3860
3861       fn = remove_hidden_names (fn);
3862       if (!fn)
3863         {
3864           if (complain & tf_error)
3865             print_error_for_call_failure (orig_fn, *args, false, NULL);
3866           return error_mark_node;
3867         }
3868     }
3869
3870   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3871   p = conversion_obstack_alloc (0);
3872
3873   cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p);
3874
3875   if (!cand)
3876     {
3877       if (complain & tf_error)
3878         {
3879           if (!any_viable_p && candidates && ! candidates->next
3880               && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
3881             return cp_build_function_call_vec (candidates->fn, args, complain);
3882           if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3883             fn = TREE_OPERAND (fn, 0);
3884           print_error_for_call_failure (fn, *args, any_viable_p, candidates);
3885         }
3886       result = error_mark_node;
3887     }
3888   else
3889     {
3890       int flags = LOOKUP_NORMAL;
3891       /* If fn is template_id_expr, the call has explicit template arguments
3892          (e.g. func<int>(5)), communicate this info to build_over_call
3893          through flags so that later we can use it to decide whether to warn
3894          about peculiar null pointer conversion.  */
3895       if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3896         flags |= LOOKUP_EXPLICIT_TMPL_ARGS;
3897       result = build_over_call (cand, flags, complain);
3898     }
3899
3900   /* Free all the conversions we allocated.  */
3901   obstack_free (&conversion_obstack, p);
3902
3903   return result;
3904 }
3905
3906 /* Build a call to a global operator new.  FNNAME is the name of the
3907    operator (either "operator new" or "operator new[]") and ARGS are
3908    the arguments provided.  This may change ARGS.  *SIZE points to the
3909    total number of bytes required by the allocation, and is updated if
3910    that is changed here.  *COOKIE_SIZE is non-NULL if a cookie should
3911    be used.  If this function determines that no cookie should be
3912    used, after all, *COOKIE_SIZE is set to NULL_TREE.  If FN is
3913    non-NULL, it will be set, upon return, to the allocation function
3914    called.  */
3915
3916 tree
3917 build_operator_new_call (tree fnname, VEC(tree,gc) **args,
3918                          tree *size, tree *cookie_size,
3919                          tree *fn)
3920 {
3921   tree fns;
3922   struct z_candidate *candidates;
3923   struct z_candidate *cand;
3924   bool any_viable_p;
3925
3926   if (fn)
3927     *fn = NULL_TREE;
3928   VEC_safe_insert (tree, gc, *args, 0, *size);
3929   *args = resolve_args (*args, tf_warning_or_error);
3930   if (*args == NULL)
3931     return error_mark_node;
3932
3933   /* Based on:
3934
3935        [expr.new]
3936
3937        If this lookup fails to find the name, or if the allocated type
3938        is not a class type, the allocation function's name is looked
3939        up in the global scope.
3940
3941      we disregard block-scope declarations of "operator new".  */
3942   fns = lookup_function_nonclass (fnname, *args, /*block_p=*/false);
3943
3944   /* Figure out what function is being called.  */
3945   cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p);
3946
3947   /* If no suitable function could be found, issue an error message
3948      and give up.  */
3949   if (!cand)
3950     {
3951       print_error_for_call_failure (fns, *args, any_viable_p, candidates);
3952       return error_mark_node;
3953     }
3954
3955    /* If a cookie is required, add some extra space.  Whether
3956       or not a cookie is required cannot be determined until
3957       after we know which function was called.  */
3958    if (*cookie_size)
3959      {
3960        bool use_cookie = true;
3961        if (!abi_version_at_least (2))
3962          {
3963            /* In G++ 3.2, the check was implemented incorrectly; it
3964               looked at the placement expression, rather than the
3965               type of the function.  */
3966            if (VEC_length (tree, *args) == 2
3967                && same_type_p (TREE_TYPE (VEC_index (tree, *args, 1)),
3968                                ptr_type_node))
3969              use_cookie = false;
3970          }
3971        else
3972          {
3973            tree arg_types;
3974
3975            arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
3976            /* Skip the size_t parameter.  */
3977            arg_types = TREE_CHAIN (arg_types);
3978            /* Check the remaining parameters (if any).  */
3979            if (arg_types
3980                && TREE_CHAIN (arg_types) == void_list_node
3981                && same_type_p (TREE_VALUE (arg_types),
3982                                ptr_type_node))
3983              use_cookie = false;
3984          }
3985        /* If we need a cookie, adjust the number of bytes allocated.  */
3986        if (use_cookie)
3987          {
3988            /* Update the total size.  */
3989            *size = size_binop (PLUS_EXPR, *size, *cookie_size);
3990            /* Update the argument list to reflect the adjusted size.  */
3991            VEC_replace (tree, *args, 0, *size);
3992          }
3993        else
3994          *cookie_size = NULL_TREE;
3995      }
3996
3997    /* Tell our caller which function we decided to call.  */
3998    if (fn)
3999      *fn = cand->fn;
4000
4001    /* Build the CALL_EXPR.  */
4002    return build_over_call (cand, LOOKUP_NORMAL, tf_warning_or_error);
4003 }
4004
4005 /* Build a new call to operator().  This may change ARGS.  */
4006
4007 static tree
4008 build_op_call_1 (tree obj, VEC(tree,gc) **args, tsubst_flags_t complain)
4009 {
4010   struct z_candidate *candidates = 0, *cand;
4011   tree fns, convs, first_mem_arg = NULL_TREE;
4012   tree type = TREE_TYPE (obj);
4013   bool any_viable_p;
4014   tree result = NULL_TREE;
4015   void *p;
4016
4017   if (error_operand_p (obj))
4018     return error_mark_node;
4019
4020   obj = prep_operand (obj);
4021
4022   if (TYPE_PTRMEMFUNC_P (type))
4023     {
4024       if (complain & tf_error)
4025         /* It's no good looking for an overloaded operator() on a
4026            pointer-to-member-function.  */
4027         error ("pointer-to-member function %E cannot be called without an object; consider using .* or ->*", obj);
4028       return error_mark_node;
4029     }
4030
4031   if (TYPE_BINFO (type))
4032     {
4033       fns = lookup_fnfields (TYPE_BINFO (type), ansi_opname (CALL_EXPR), 1);
4034       if (fns == error_mark_node)
4035         return error_mark_node;
4036     }
4037   else
4038     fns = NULL_TREE;
4039
4040   if (args != NULL && *args != NULL)
4041     {
4042       *args = resolve_args (*args, complain);
4043       if (*args == NULL)
4044         return error_mark_node;
4045     }
4046
4047   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4048   p = conversion_obstack_alloc (0);
4049
4050   if (fns)
4051     {
4052       first_mem_arg = build_this (obj);
4053
4054       add_candidates (BASELINK_FUNCTIONS (fns),
4055                       first_mem_arg, *args, NULL_TREE,
4056                       NULL_TREE, false,
4057                       BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
4058                       LOOKUP_NORMAL, &candidates);
4059     }
4060
4061   convs = lookup_conversions (type);
4062
4063   for (; convs; convs = TREE_CHAIN (convs))
4064     {
4065       tree fns = TREE_VALUE (convs);
4066       tree totype = TREE_TYPE (convs);
4067
4068       if ((TREE_CODE (totype) == POINTER_TYPE
4069            && TREE_CODE (TREE_TYPE (totype)) == FUNCTION_TYPE)
4070           || (TREE_CODE (totype) == REFERENCE_TYPE
4071               && TREE_CODE (TREE_TYPE (totype)) == FUNCTION_TYPE)
4072           || (TREE_CODE (totype) == REFERENCE_TYPE
4073               && TREE_CODE (TREE_TYPE (totype)) == POINTER_TYPE
4074               && TREE_CODE (TREE_TYPE (TREE_TYPE (totype))) == FUNCTION_TYPE))
4075         for (; fns; fns = OVL_NEXT (fns))
4076           {
4077             tree fn = OVL_CURRENT (fns);
4078
4079             if (DECL_NONCONVERTING_P (fn))
4080               continue;
4081
4082             if (TREE_CODE (fn) == TEMPLATE_DECL)
4083               add_template_conv_candidate
4084                 (&candidates, fn, obj, NULL_TREE, *args, totype,
4085                  /*access_path=*/NULL_TREE,
4086                  /*conversion_path=*/NULL_TREE);
4087             else
4088               add_conv_candidate (&candidates, fn, obj, NULL_TREE,
4089                                   *args, /*conversion_path=*/NULL_TREE,
4090                                   /*access_path=*/NULL_TREE);
4091           }
4092     }
4093
4094   candidates = splice_viable (candidates, pedantic, &any_viable_p);
4095   if (!any_viable_p)
4096     {
4097       if (complain & tf_error)
4098         {
4099           error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
4100                  build_tree_list_vec (*args));
4101           print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
4102         }
4103       result = error_mark_node;
4104     }
4105   else
4106     {
4107       cand = tourney (candidates);
4108       if (cand == 0)
4109         {
4110           if (complain & tf_error)
4111             {
4112               error ("call of %<(%T) (%A)%> is ambiguous", 
4113                      TREE_TYPE (obj), build_tree_list_vec (*args));
4114               print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
4115             }
4116           result = error_mark_node;
4117         }
4118       /* Since cand->fn will be a type, not a function, for a conversion
4119          function, we must be careful not to unconditionally look at
4120          DECL_NAME here.  */
4121       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
4122                && DECL_OVERLOADED_OPERATOR_P (cand->fn) == CALL_EXPR)
4123         result = build_over_call (cand, LOOKUP_NORMAL, complain);
4124       else
4125         {
4126           obj = convert_like_with_context (cand->convs[0], obj, cand->fn, -1,
4127                                            complain);
4128           obj = convert_from_reference (obj);
4129           result = cp_build_function_call_vec (obj, args, complain);
4130         }
4131     }
4132
4133   /* Free all the conversions we allocated.  */
4134   obstack_free (&conversion_obstack, p);
4135
4136   return result;
4137 }
4138
4139 /* Wrapper for above.  */
4140
4141 tree
4142 build_op_call (tree obj, VEC(tree,gc) **args, tsubst_flags_t complain)
4143 {
4144   tree ret;
4145   bool subtime = timevar_cond_start (TV_OVERLOAD);
4146   ret = build_op_call_1 (obj, args, complain);
4147   timevar_cond_stop (TV_OVERLOAD, subtime);
4148   return ret;
4149 }
4150
4151 static void
4152 op_error (enum tree_code code, enum tree_code code2,
4153           tree arg1, tree arg2, tree arg3, bool match)
4154 {
4155   const char *opname;
4156
4157   if (code == MODIFY_EXPR)
4158     opname = assignment_operator_name_info[code2].name;
4159   else
4160     opname = operator_name_info[code].name;
4161
4162   switch (code)
4163     {
4164     case COND_EXPR:
4165       if (match)
4166         error ("ambiguous overload for ternary %<operator?:%> "
4167                "in %<%E ? %E : %E%>", arg1, arg2, arg3);
4168       else
4169         error ("no match for ternary %<operator?:%> "
4170                "in %<%E ? %E : %E%>", arg1, arg2, arg3);
4171       break;
4172
4173     case POSTINCREMENT_EXPR:
4174     case POSTDECREMENT_EXPR:
4175       if (match)
4176         error ("ambiguous overload for %<operator%s%> in %<%E%s%>",
4177                opname, arg1, opname);
4178       else
4179         error ("no match for %<operator%s%> in %<%E%s%>", 
4180                opname, arg1, opname);
4181       break;
4182
4183     case ARRAY_REF:
4184       if (match)
4185         error ("ambiguous overload for %<operator[]%> in %<%E[%E]%>", 
4186                arg1, arg2);
4187       else
4188         error ("no match for %<operator[]%> in %<%E[%E]%>", 
4189                arg1, arg2);
4190       break;
4191
4192     case REALPART_EXPR:
4193     case IMAGPART_EXPR:
4194       if (match)
4195         error ("ambiguous overload for %qs in %<%s %E%>", 
4196                opname, opname, arg1);
4197       else
4198         error ("no match for %qs in %<%s %E%>",
4199                opname, opname, arg1);
4200       break;
4201
4202     default:
4203       if (arg2)
4204         if (match)
4205           error ("ambiguous overload for %<operator%s%> in %<%E %s %E%>",
4206                   opname, arg1, opname, arg2);
4207         else
4208           error ("no match for %<operator%s%> in %<%E %s %E%>",
4209                  opname, arg1, opname, arg2);
4210       else
4211         if (match)
4212           error ("ambiguous overload for %<operator%s%> in %<%s%E%>",
4213                  opname, opname, arg1);
4214         else
4215           error ("no match for %<operator%s%> in %<%s%E%>",
4216                  opname, opname, arg1);
4217       break;
4218     }
4219 }
4220
4221 /* Return the implicit conversion sequence that could be used to
4222    convert E1 to E2 in [expr.cond].  */
4223
4224 static conversion *
4225 conditional_conversion (tree e1, tree e2)
4226 {
4227   tree t1 = non_reference (TREE_TYPE (e1));
4228   tree t2 = non_reference (TREE_TYPE (e2));
4229   conversion *conv;
4230   bool good_base;
4231
4232   /* [expr.cond]
4233
4234      If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
4235      implicitly converted (clause _conv_) to the type "lvalue reference to
4236      T2", subject to the constraint that in the conversion the
4237      reference must bind directly (_dcl.init.ref_) to an lvalue.  */
4238   if (real_lvalue_p (e2))
4239     {
4240       conv = implicit_conversion (build_reference_type (t2),
4241                                   t1,
4242                                   e1,
4243                                   /*c_cast_p=*/false,
4244                                   LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
4245                                   |LOOKUP_ONLYCONVERTING);
4246       if (conv)
4247         return conv;
4248     }
4249
4250   /* [expr.cond]
4251
4252      If E1 and E2 have class type, and the underlying class types are
4253      the same or one is a base class of the other: E1 can be converted
4254      to match E2 if the class of T2 is the same type as, or a base
4255      class of, the class of T1, and the cv-qualification of T2 is the
4256      same cv-qualification as, or a greater cv-qualification than, the
4257      cv-qualification of T1.  If the conversion is applied, E1 is
4258      changed to an rvalue of type T2 that still refers to the original
4259      source class object (or the appropriate subobject thereof).  */
4260   if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
4261       && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
4262     {
4263       if (good_base && at_least_as_qualified_p (t2, t1))
4264         {
4265           conv = build_identity_conv (t1, e1);
4266           if (!same_type_p (TYPE_MAIN_VARIANT (t1),
4267                             TYPE_MAIN_VARIANT (t2)))
4268             conv = build_conv (ck_base, t2, conv);
4269           else
4270             conv = build_conv (ck_rvalue, t2, conv);
4271           return conv;
4272         }
4273       else
4274         return NULL;
4275     }
4276   else
4277     /* [expr.cond]
4278
4279        Otherwise: E1 can be converted to match E2 if E1 can be implicitly
4280        converted to the type that expression E2 would have if E2 were
4281        converted to an rvalue (or the type it has, if E2 is an rvalue).  */
4282     return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
4283                                 LOOKUP_IMPLICIT);
4284 }
4285
4286 /* Implement [expr.cond].  ARG1, ARG2, and ARG3 are the three
4287    arguments to the conditional expression.  */
4288
4289 static tree
4290 build_conditional_expr_1 (tree arg1, tree arg2, tree arg3,
4291                           tsubst_flags_t complain)
4292 {
4293   tree arg2_type;
4294   tree arg3_type;
4295   tree result = NULL_TREE;
4296   tree result_type = NULL_TREE;
4297   bool lvalue_p = true;
4298   struct z_candidate *candidates = 0;
4299   struct z_candidate *cand;
4300   void *p;
4301
4302   /* As a G++ extension, the second argument to the conditional can be
4303      omitted.  (So that `a ? : c' is roughly equivalent to `a ? a :
4304      c'.)  If the second operand is omitted, make sure it is
4305      calculated only once.  */
4306   if (!arg2)
4307     {
4308       if (complain & tf_error)
4309         pedwarn (input_location, OPT_pedantic, 
4310                  "ISO C++ forbids omitting the middle term of a ?: expression");
4311
4312       /* Make sure that lvalues remain lvalues.  See g++.oliva/ext1.C.  */
4313       if (real_lvalue_p (arg1))
4314         arg2 = arg1 = stabilize_reference (arg1);
4315       else
4316         arg2 = arg1 = save_expr (arg1);
4317     }
4318
4319   /* [expr.cond]
4320
4321      The first expression is implicitly converted to bool (clause
4322      _conv_).  */
4323   arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
4324                                             LOOKUP_NORMAL);
4325
4326   /* If something has already gone wrong, just pass that fact up the
4327      tree.  */
4328   if (error_operand_p (arg1)
4329       || error_operand_p (arg2)
4330       || error_operand_p (arg3))
4331     return error_mark_node;
4332
4333   /* [expr.cond]
4334
4335      If either the second or the third operand has type (possibly
4336      cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
4337      array-to-pointer (_conv.array_), and function-to-pointer
4338      (_conv.func_) standard conversions are performed on the second
4339      and third operands.  */
4340   arg2_type = unlowered_expr_type (arg2);
4341   arg3_type = unlowered_expr_type (arg3);
4342   if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
4343     {
4344       /* Do the conversions.  We don't these for `void' type arguments
4345          since it can't have any effect and since decay_conversion
4346          does not handle that case gracefully.  */
4347       if (!VOID_TYPE_P (arg2_type))
4348         arg2 = decay_conversion (arg2);
4349       if (!VOID_TYPE_P (arg3_type))
4350         arg3 = decay_conversion (arg3);
4351       arg2_type = TREE_TYPE (arg2);
4352       arg3_type = TREE_TYPE (arg3);
4353
4354       /* [expr.cond]
4355
4356          One of the following shall hold:
4357
4358          --The second or the third operand (but not both) is a
4359            throw-expression (_except.throw_); the result is of the
4360            type of the other and is an rvalue.
4361
4362          --Both the second and the third operands have type void; the
4363            result is of type void and is an rvalue.
4364
4365          We must avoid calling force_rvalue for expressions of type
4366          "void" because it will complain that their value is being
4367          used.  */
4368       if (TREE_CODE (arg2) == THROW_EXPR
4369           && TREE_CODE (arg3) != THROW_EXPR)
4370         {
4371           if (!VOID_TYPE_P (arg3_type))
4372             {
4373               arg3 = force_rvalue (arg3, complain);
4374               if (arg3 == error_mark_node)
4375                 return error_mark_node;
4376             }
4377           arg3_type = TREE_TYPE (arg3);
4378           result_type = arg3_type;
4379         }
4380       else if (TREE_CODE (arg2) != THROW_EXPR
4381                && TREE_CODE (arg3) == THROW_EXPR)
4382         {
4383           if (!VOID_TYPE_P (arg2_type))
4384             {
4385               arg2 = force_rvalue (arg2, complain);
4386               if (arg2 == error_mark_node)
4387                 return error_mark_node;
4388             }
4389           arg2_type = TREE_TYPE (arg2);
4390           result_type = arg2_type;
4391         }
4392       else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
4393         result_type = void_type_node;
4394       else
4395         {
4396           if (complain & tf_error)
4397             {
4398               if (VOID_TYPE_P (arg2_type))
4399                 error ("second operand to the conditional operator "
4400                        "is of type %<void%>, "
4401                        "but the third operand is neither a throw-expression "
4402                        "nor of type %<void%>");
4403               else
4404                 error ("third operand to the conditional operator "
4405                        "is of type %<void%>, "
4406                        "but the second operand is neither a throw-expression "
4407                        "nor of type %<void%>");
4408             }
4409           return error_mark_node;
4410         }
4411
4412       lvalue_p = false;
4413       goto valid_operands;
4414     }
4415   /* [expr.cond]
4416
4417      Otherwise, if the second and third operand have different types,
4418      and either has (possibly cv-qualified) class type, an attempt is
4419      made to convert each of those operands to the type of the other.  */
4420   else if (!same_type_p (arg2_type, arg3_type)
4421            && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
4422     {
4423       conversion *conv2;
4424       conversion *conv3;
4425
4426       /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4427       p = conversion_obstack_alloc (0);
4428
4429       conv2 = conditional_conversion (arg2, arg3);
4430       conv3 = conditional_conversion (arg3, arg2);
4431
4432       /* [expr.cond]
4433
4434          If both can be converted, or one can be converted but the
4435          conversion is ambiguous, the program is ill-formed.  If
4436          neither can be converted, the operands are left unchanged and
4437          further checking is performed as described below.  If exactly
4438          one conversion is possible, that conversion is applied to the
4439          chosen operand and the converted operand is used in place of
4440          the original operand for the remainder of this section.  */
4441       if ((conv2 && !conv2->bad_p
4442            && conv3 && !conv3->bad_p)
4443           || (conv2 && conv2->kind == ck_ambig)
4444           || (conv3 && conv3->kind == ck_ambig))
4445         {
4446           error ("operands to ?: have different types %qT and %qT",
4447                  arg2_type, arg3_type);
4448           result = error_mark_node;
4449         }
4450       else if (conv2 && (!conv2->bad_p || !conv3))
4451         {
4452           arg2 = convert_like (conv2, arg2, complain);
4453           arg2 = convert_from_reference (arg2);
4454           arg2_type = TREE_TYPE (arg2);
4455           /* Even if CONV2 is a valid conversion, the result of the
4456              conversion may be invalid.  For example, if ARG3 has type
4457              "volatile X", and X does not have a copy constructor
4458              accepting a "volatile X&", then even if ARG2 can be
4459              converted to X, the conversion will fail.  */
4460           if (error_operand_p (arg2))
4461             result = error_mark_node;
4462         }
4463       else if (conv3 && (!conv3->bad_p || !conv2))
4464         {
4465           arg3 = convert_like (conv3, arg3, complain);
4466           arg3 = convert_from_reference (arg3);
4467           arg3_type = TREE_TYPE (arg3);
4468           if (error_operand_p (arg3))
4469             result = error_mark_node;
4470         }
4471
4472       /* Free all the conversions we allocated.  */
4473       obstack_free (&conversion_obstack, p);
4474
4475       if (result)
4476         return result;
4477
4478       /* If, after the conversion, both operands have class type,
4479          treat the cv-qualification of both operands as if it were the
4480          union of the cv-qualification of the operands.
4481
4482          The standard is not clear about what to do in this
4483          circumstance.  For example, if the first operand has type
4484          "const X" and the second operand has a user-defined
4485          conversion to "volatile X", what is the type of the second
4486          operand after this step?  Making it be "const X" (matching
4487          the first operand) seems wrong, as that discards the
4488          qualification without actually performing a copy.  Leaving it
4489          as "volatile X" seems wrong as that will result in the
4490          conditional expression failing altogether, even though,
4491          according to this step, the one operand could be converted to
4492          the type of the other.  */
4493       if ((conv2 || conv3)
4494           && CLASS_TYPE_P (arg2_type)
4495           && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
4496         arg2_type = arg3_type =
4497           cp_build_qualified_type (arg2_type,
4498                                    cp_type_quals (arg2_type)
4499                                    | cp_type_quals (arg3_type));
4500     }
4501
4502   /* [expr.cond]
4503
4504      If the second and third operands are lvalues and have the same
4505      type, the result is of that type and is an lvalue.  */
4506   if (real_lvalue_p (arg2)
4507       && real_lvalue_p (arg3)
4508       && same_type_p (arg2_type, arg3_type))
4509     {
4510       result_type = arg2_type;
4511       arg2 = mark_lvalue_use (arg2);
4512       arg3 = mark_lvalue_use (arg3);
4513       goto valid_operands;
4514     }
4515
4516   /* [expr.cond]
4517
4518      Otherwise, the result is an rvalue.  If the second and third
4519      operand do not have the same type, and either has (possibly
4520      cv-qualified) class type, overload resolution is used to
4521      determine the conversions (if any) to be applied to the operands
4522      (_over.match.oper_, _over.built_).  */
4523   lvalue_p = false;
4524   if (!same_type_p (arg2_type, arg3_type)
4525       && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
4526     {
4527       tree args[3];
4528       conversion *conv;
4529       bool any_viable_p;
4530
4531       /* Rearrange the arguments so that add_builtin_candidate only has
4532          to know about two args.  In build_builtin_candidate, the
4533          arguments are unscrambled.  */
4534       args[0] = arg2;
4535       args[1] = arg3;
4536       args[2] = arg1;
4537       add_builtin_candidates (&candidates,
4538                               COND_EXPR,
4539                               NOP_EXPR,
4540                               ansi_opname (COND_EXPR),
4541                               args,
4542                               LOOKUP_NORMAL);
4543
4544       /* [expr.cond]
4545
4546          If the overload resolution fails, the program is
4547          ill-formed.  */
4548       candidates = splice_viable (candidates, pedantic, &any_viable_p);
4549       if (!any_viable_p)
4550         {
4551           if (complain & tf_error)
4552             {
4553               op_error (COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
4554               print_z_candidates (location_of (arg1), candidates);
4555             }
4556           return error_mark_node;
4557         }
4558       cand = tourney (candidates);
4559       if (!cand)
4560         {
4561           if (complain & tf_error)
4562             {
4563               op_error (COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
4564               print_z_candidates (location_of (arg1), candidates);
4565             }
4566           return error_mark_node;
4567         }
4568
4569       /* [expr.cond]
4570
4571          Otherwise, the conversions thus determined are applied, and
4572          the converted operands are used in place of the original
4573          operands for the remainder of this section.  */
4574       conv = cand->convs[0];
4575       arg1 = convert_like (conv, arg1, complain);
4576       conv = cand->convs[1];
4577       arg2 = convert_like (conv, arg2, complain);
4578       arg2_type = TREE_TYPE (arg2);
4579       conv = cand->convs[2];
4580       arg3 = convert_like (conv, arg3, complain);
4581       arg3_type = TREE_TYPE (arg3);
4582     }
4583
4584   /* [expr.cond]
4585
4586      Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
4587      and function-to-pointer (_conv.func_) standard conversions are
4588      performed on the second and third operands.
4589
4590      We need to force the lvalue-to-rvalue conversion here for class types,
4591      so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
4592      that isn't wrapped with a TARGET_EXPR plays havoc with exception
4593      regions.  */
4594
4595   arg2 = force_rvalue (arg2, complain);
4596   if (!CLASS_TYPE_P (arg2_type))
4597     arg2_type = TREE_TYPE (arg2);
4598
4599   arg3 = force_rvalue (arg3, complain);
4600   if (!CLASS_TYPE_P (arg3_type))
4601     arg3_type = TREE_TYPE (arg3);
4602
4603   if (arg2 == error_mark_node || arg3 == error_mark_node)
4604     return error_mark_node;
4605
4606   /* [expr.cond]
4607
4608      After those conversions, one of the following shall hold:
4609
4610      --The second and third operands have the same type; the result  is  of
4611        that type.  */
4612   if (same_type_p (arg2_type, arg3_type))
4613     result_type = arg2_type;
4614   /* [expr.cond]
4615
4616      --The second and third operands have arithmetic or enumeration
4617        type; the usual arithmetic conversions are performed to bring
4618        them to a common type, and the result is of that type.  */
4619   else if ((ARITHMETIC_TYPE_P (arg2_type)
4620             || UNSCOPED_ENUM_P (arg2_type))
4621            && (ARITHMETIC_TYPE_P (arg3_type)
4622                || UNSCOPED_ENUM_P (arg3_type)))
4623     {
4624       /* In this case, there is always a common type.  */
4625       result_type = type_after_usual_arithmetic_conversions (arg2_type,
4626                                                              arg3_type);
4627       do_warn_double_promotion (result_type, arg2_type, arg3_type,
4628                                 "implicit conversion from %qT to %qT to "
4629                                 "match other result of conditional",
4630                                 input_location);
4631
4632       if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
4633           && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
4634         {
4635           if (complain & tf_warning)
4636             warning (OPT_Wenum_compare, 
4637                      "enumeral mismatch in conditional expression: %qT vs %qT",
4638                      arg2_type, arg3_type);
4639         }
4640       else if (extra_warnings
4641                && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
4642                     && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
4643                    || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
4644                        && !same_type_p (arg2_type, type_promotes_to (arg3_type)))))
4645         {
4646           if (complain & tf_warning)
4647             warning (0, 
4648                      "enumeral and non-enumeral type in conditional expression");
4649         }
4650
4651       arg2 = perform_implicit_conversion (result_type, arg2, complain);
4652       arg3 = perform_implicit_conversion (result_type, arg3, complain);
4653     }
4654   /* [expr.cond]
4655
4656      --The second and third operands have pointer type, or one has
4657        pointer type and the other is a null pointer constant; pointer
4658        conversions (_conv.ptr_) and qualification conversions
4659        (_conv.qual_) are performed to bring them to their composite
4660        pointer type (_expr.rel_).  The result is of the composite
4661        pointer type.
4662
4663      --The second and third operands have pointer to member type, or
4664        one has pointer to member type and the other is a null pointer
4665        constant; pointer to member conversions (_conv.mem_) and
4666        qualification conversions (_conv.qual_) are performed to bring
4667        them to a common type, whose cv-qualification shall match the
4668        cv-qualification of either the second or the third operand.
4669        The result is of the common type.  */
4670   else if ((null_ptr_cst_p (arg2)
4671             && (TYPE_PTR_P (arg3_type) || TYPE_PTR_TO_MEMBER_P (arg3_type)))
4672            || (null_ptr_cst_p (arg3)
4673                && (TYPE_PTR_P (arg2_type) || TYPE_PTR_TO_MEMBER_P (arg2_type)))
4674            || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
4675            || (TYPE_PTRMEM_P (arg2_type) && TYPE_PTRMEM_P (arg3_type))
4676            || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
4677     {
4678       result_type = composite_pointer_type (arg2_type, arg3_type, arg2,
4679                                             arg3, CPO_CONDITIONAL_EXPR,
4680                                             complain);
4681       if (result_type == error_mark_node)
4682         return error_mark_node;
4683       arg2 = perform_implicit_conversion (result_type, arg2, complain);
4684       arg3 = perform_implicit_conversion (result_type, arg3, complain);
4685     }
4686
4687   if (!result_type)
4688     {
4689       if (complain & tf_error)
4690         error ("operands to ?: have different types %qT and %qT",
4691                arg2_type, arg3_type);
4692       return error_mark_node;
4693     }
4694
4695  valid_operands:
4696   result = build3 (COND_EXPR, result_type, arg1, arg2, arg3);
4697   if (!cp_unevaluated_operand)
4698     /* Avoid folding within decltype (c++/42013) and noexcept.  */
4699     result = fold_if_not_in_template (result);
4700
4701   /* We can't use result_type below, as fold might have returned a
4702      throw_expr.  */
4703
4704   if (!lvalue_p)
4705     {
4706       /* Expand both sides into the same slot, hopefully the target of
4707          the ?: expression.  We used to check for TARGET_EXPRs here,
4708          but now we sometimes wrap them in NOP_EXPRs so the test would
4709          fail.  */
4710       if (CLASS_TYPE_P (TREE_TYPE (result)))
4711         result = get_target_expr (result);
4712       /* If this expression is an rvalue, but might be mistaken for an
4713          lvalue, we must add a NON_LVALUE_EXPR.  */
4714       result = rvalue (result);
4715     }
4716
4717   return result;
4718 }
4719
4720 /* Wrapper for above.  */
4721
4722 tree
4723 build_conditional_expr (tree arg1, tree arg2, tree arg3,
4724                         tsubst_flags_t complain)
4725 {
4726   tree ret;
4727   bool subtime = timevar_cond_start (TV_OVERLOAD);
4728   ret = build_conditional_expr_1 (arg1, arg2, arg3, complain);
4729   timevar_cond_stop (TV_OVERLOAD, subtime);
4730   return ret;
4731 }
4732
4733 /* OPERAND is an operand to an expression.  Perform necessary steps
4734    required before using it.  If OPERAND is NULL_TREE, NULL_TREE is
4735    returned.  */
4736
4737 static tree
4738 prep_operand (tree operand)
4739 {
4740   if (operand)
4741     {
4742       if (CLASS_TYPE_P (TREE_TYPE (operand))
4743           && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
4744         /* Make sure the template type is instantiated now.  */
4745         instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
4746     }
4747
4748   return operand;
4749 }
4750
4751 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
4752    OVERLOAD) to the CANDIDATES, returning an updated list of
4753    CANDIDATES.  The ARGS are the arguments provided to the call;
4754    if FIRST_ARG is non-null it is the implicit object argument,
4755    otherwise the first element of ARGS is used if needed.  The
4756    EXPLICIT_TARGS are explicit template arguments provided.
4757    TEMPLATE_ONLY is true if only template functions should be
4758    considered.  CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
4759    add_function_candidate.  */
4760
4761 static void
4762 add_candidates (tree fns, tree first_arg, const VEC(tree,gc) *args,
4763                 tree return_type,
4764                 tree explicit_targs, bool template_only,
4765                 tree conversion_path, tree access_path,
4766                 int flags,
4767                 struct z_candidate **candidates)
4768 {
4769   tree ctype;
4770   const VEC(tree,gc) *non_static_args;
4771   bool check_list_ctor;
4772   bool check_converting;
4773   unification_kind_t strict;
4774   tree fn;
4775
4776   if (!fns)
4777     return;
4778
4779   /* Precalculate special handling of constructors and conversion ops.  */
4780   fn = OVL_CURRENT (fns);
4781   if (DECL_CONV_FN_P (fn))
4782     {
4783       check_list_ctor = false;
4784       check_converting = !!(flags & LOOKUP_ONLYCONVERTING);
4785       if (flags & LOOKUP_NO_CONVERSION)
4786         /* We're doing return_type(x).  */
4787         strict = DEDUCE_CONV;
4788       else
4789         /* We're doing x.operator return_type().  */
4790         strict = DEDUCE_EXACT;
4791       /* [over.match.funcs] For conversion functions, the function
4792          is considered to be a member of the class of the implicit
4793          object argument for the purpose of defining the type of
4794          the implicit object parameter.  */
4795       ctype = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (first_arg)));
4796     }
4797   else
4798     {
4799       if (DECL_CONSTRUCTOR_P (fn))
4800         {
4801           check_list_ctor = !!(flags & LOOKUP_LIST_ONLY);
4802           /* For list-initialization we consider explicit constructors
4803              and complain if one is chosen.  */
4804           check_converting
4805             = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
4806                == LOOKUP_ONLYCONVERTING);
4807         }
4808       else
4809         {
4810           check_list_ctor = false;
4811           check_converting = false;
4812         }
4813       strict = DEDUCE_CALL;
4814       ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
4815     }
4816
4817   if (first_arg)
4818     non_static_args = args;
4819   else
4820     /* Delay creating the implicit this parameter until it is needed.  */
4821     non_static_args = NULL;
4822
4823   for (; fns; fns = OVL_NEXT (fns))
4824     {
4825       tree fn_first_arg;
4826       const VEC(tree,gc) *fn_args;
4827
4828       fn = OVL_CURRENT (fns);
4829
4830       if (check_converting && DECL_NONCONVERTING_P (fn))
4831         continue;
4832       if (check_list_ctor && !is_list_ctor (fn))
4833         continue;
4834
4835       /* Figure out which set of arguments to use.  */
4836       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
4837         {
4838           /* If this function is a non-static member and we didn't get an
4839              implicit object argument, move it out of args.  */
4840           if (first_arg == NULL_TREE)
4841             {
4842               unsigned int ix;
4843               tree arg;
4844               VEC(tree,gc) *tempvec
4845                 = VEC_alloc (tree, gc, VEC_length (tree, args) - 1);
4846               for (ix = 1; VEC_iterate (tree, args, ix, arg); ++ix)
4847                 VEC_quick_push (tree, tempvec, arg);
4848               non_static_args = tempvec;
4849               first_arg = build_this (VEC_index (tree, args, 0));
4850             }
4851
4852           fn_first_arg = first_arg;
4853           fn_args = non_static_args;
4854         }
4855       else
4856         {
4857           /* Otherwise, just use the list of arguments provided.  */
4858           fn_first_arg = NULL_TREE;
4859           fn_args = args;
4860         }
4861
4862       if (TREE_CODE (fn) == TEMPLATE_DECL)
4863         add_template_candidate (candidates,
4864                                 fn,
4865                                 ctype,
4866                                 explicit_targs,
4867                                 fn_first_arg, 
4868                                 fn_args,
4869                                 return_type,
4870                                 access_path,
4871                                 conversion_path,
4872                                 flags,
4873                                 strict);
4874       else if (!template_only)
4875         add_function_candidate (candidates,
4876                                 fn,
4877                                 ctype,
4878                                 fn_first_arg,
4879                                 fn_args,
4880                                 access_path,
4881                                 conversion_path,
4882                                 flags);
4883     }
4884 }
4885
4886 static tree
4887 build_new_op_1 (enum tree_code code, int flags, tree arg1, tree arg2, tree arg3,
4888                 tree *overload, tsubst_flags_t complain)
4889 {
4890   struct z_candidate *candidates = 0, *cand;
4891   VEC(tree,gc) *arglist;
4892   tree fnname;
4893   tree args[3];
4894   tree result = NULL_TREE;
4895   bool result_valid_p = false;
4896   enum tree_code code2 = NOP_EXPR;
4897   enum tree_code code_orig_arg1 = ERROR_MARK;
4898   enum tree_code code_orig_arg2 = ERROR_MARK;
4899   conversion *conv;
4900   void *p;
4901   bool strict_p;
4902   bool any_viable_p;
4903
4904   if (error_operand_p (arg1)
4905       || error_operand_p (arg2)
4906       || error_operand_p (arg3))
4907     return error_mark_node;
4908
4909   if (code == MODIFY_EXPR)
4910     {
4911       code2 = TREE_CODE (arg3);
4912       arg3 = NULL_TREE;
4913       fnname = ansi_assopname (code2);
4914     }
4915   else
4916     fnname = ansi_opname (code);
4917
4918   arg1 = prep_operand (arg1);
4919
4920   switch (code)
4921     {
4922     case NEW_EXPR:
4923     case VEC_NEW_EXPR:
4924     case VEC_DELETE_EXPR:
4925     case DELETE_EXPR:
4926       /* Use build_op_new_call and build_op_delete_call instead.  */
4927       gcc_unreachable ();
4928
4929     case CALL_EXPR:
4930       /* Use build_op_call instead.  */
4931       gcc_unreachable ();
4932
4933     case TRUTH_ORIF_EXPR:
4934     case TRUTH_ANDIF_EXPR:
4935     case TRUTH_AND_EXPR:
4936     case TRUTH_OR_EXPR:
4937       /* These are saved for the sake of warn_logical_operator.  */
4938       code_orig_arg1 = TREE_CODE (arg1);
4939       code_orig_arg2 = TREE_CODE (arg2);
4940
4941     default:
4942       break;
4943     }
4944
4945   arg2 = prep_operand (arg2);
4946   arg3 = prep_operand (arg3);
4947
4948   if (code == COND_EXPR)
4949     /* Use build_conditional_expr instead.  */
4950     gcc_unreachable ();
4951   else if (! IS_OVERLOAD_TYPE (TREE_TYPE (arg1))
4952            && (! arg2 || ! IS_OVERLOAD_TYPE (TREE_TYPE (arg2))))
4953     goto builtin;
4954
4955   if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
4956     arg2 = integer_zero_node;
4957
4958   arglist = VEC_alloc (tree, gc, 3);
4959   VEC_quick_push (tree, arglist, arg1);
4960   if (arg2 != NULL_TREE)
4961     VEC_quick_push (tree, arglist, arg2);
4962   if (arg3 != NULL_TREE)
4963     VEC_quick_push (tree, arglist, arg3);
4964
4965   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4966   p = conversion_obstack_alloc (0);
4967
4968   /* Add namespace-scope operators to the list of functions to
4969      consider.  */
4970   add_candidates (lookup_function_nonclass (fnname, arglist, /*block_p=*/true),
4971                   NULL_TREE, arglist, NULL_TREE,
4972                   NULL_TREE, false, NULL_TREE, NULL_TREE,
4973                   flags, &candidates);
4974   /* Add class-member operators to the candidate set.  */
4975   if (CLASS_TYPE_P (TREE_TYPE (arg1)))
4976     {
4977       tree fns;
4978
4979       fns = lookup_fnfields (TREE_TYPE (arg1), fnname, 1);
4980       if (fns == error_mark_node)
4981         {
4982           result = error_mark_node;
4983           goto user_defined_result_ready;
4984         }
4985       if (fns)
4986         add_candidates (BASELINK_FUNCTIONS (fns),
4987                         NULL_TREE, arglist, NULL_TREE,
4988                         NULL_TREE, false,
4989                         BASELINK_BINFO (fns),
4990                         BASELINK_ACCESS_BINFO (fns),
4991                         flags, &candidates);
4992     }
4993
4994   args[0] = arg1;
4995   args[1] = arg2;
4996   args[2] = NULL_TREE;
4997
4998   add_builtin_candidates (&candidates, code, code2, fnname, args, flags);
4999
5000   switch (code)
5001     {
5002     case COMPOUND_EXPR:
5003     case ADDR_EXPR:
5004       /* For these, the built-in candidates set is empty
5005          [over.match.oper]/3.  We don't want non-strict matches
5006          because exact matches are always possible with built-in
5007          operators.  The built-in candidate set for COMPONENT_REF
5008          would be empty too, but since there are no such built-in
5009          operators, we accept non-strict matches for them.  */
5010       strict_p = true;
5011       break;
5012
5013     default:
5014       strict_p = pedantic;
5015       break;
5016     }
5017
5018   candidates = splice_viable (candidates, strict_p, &any_viable_p);
5019   if (!any_viable_p)
5020     {
5021       switch (code)
5022         {
5023         case POSTINCREMENT_EXPR:
5024         case POSTDECREMENT_EXPR:
5025           /* Don't try anything fancy if we're not allowed to produce
5026              errors.  */
5027           if (!(complain & tf_error))
5028             return error_mark_node;
5029
5030           /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
5031              distinguish between prefix and postfix ++ and
5032              operator++() was used for both, so we allow this with
5033              -fpermissive.  */
5034           if (flags & LOOKUP_COMPLAIN)
5035             {
5036               const char *msg = (flag_permissive) 
5037                 ? G_("no %<%D(int)%> declared for postfix %qs,"
5038                      " trying prefix operator instead")
5039                 : G_("no %<%D(int)%> declared for postfix %qs");
5040               permerror (input_location, msg, fnname,
5041                          operator_name_info[code].name);
5042             }
5043
5044           if (!flag_permissive)
5045             return error_mark_node;
5046
5047           if (code == POSTINCREMENT_EXPR)
5048             code = PREINCREMENT_EXPR;
5049           else
5050             code = PREDECREMENT_EXPR;
5051           result = build_new_op_1 (code, flags, arg1, NULL_TREE, NULL_TREE,
5052                                    overload, complain);
5053           break;
5054
5055           /* The caller will deal with these.  */
5056         case ADDR_EXPR:
5057         case COMPOUND_EXPR:
5058         case COMPONENT_REF:
5059           result = NULL_TREE;
5060           result_valid_p = true;
5061           break;
5062
5063         default:
5064           if ((flags & LOOKUP_COMPLAIN) && (complain & tf_error))
5065             {
5066                 /* If one of the arguments of the operator represents
5067                    an invalid use of member function pointer, try to report
5068                    a meaningful error ...  */
5069                 if (invalid_nonstatic_memfn_p (arg1, tf_error)
5070                     || invalid_nonstatic_memfn_p (arg2, tf_error)
5071                     || invalid_nonstatic_memfn_p (arg3, tf_error))
5072                   /* We displayed the error message.  */;
5073                 else
5074                   {
5075                     /* ... Otherwise, report the more generic
5076                        "no matching operator found" error */
5077                     op_error (code, code2, arg1, arg2, arg3, FALSE);
5078                     print_z_candidates (input_location, candidates);
5079                   }
5080             }
5081           result = error_mark_node;
5082           break;
5083         }
5084     }
5085   else
5086     {
5087       cand = tourney (candidates);
5088       if (cand == 0)
5089         {
5090           if ((flags & LOOKUP_COMPLAIN) && (complain & tf_error))
5091             {
5092               op_error (code, code2, arg1, arg2, arg3, TRUE);
5093               print_z_candidates (input_location, candidates);
5094             }
5095           result = error_mark_node;
5096         }
5097       else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5098         {
5099           if (overload)
5100             *overload = cand->fn;
5101
5102           if (resolve_args (arglist, complain) == NULL)
5103             result = error_mark_node;
5104           else
5105             result = build_over_call (cand, LOOKUP_NORMAL, complain);
5106         }
5107       else
5108         {
5109           /* Give any warnings we noticed during overload resolution.  */
5110           if (cand->warnings && (complain & tf_warning))
5111             {
5112               struct candidate_warning *w;
5113               for (w = cand->warnings; w; w = w->next)
5114                 joust (cand, w->loser, 1);
5115             }
5116
5117           /* Check for comparison of different enum types.  */
5118           switch (code)
5119             {
5120             case GT_EXPR:
5121             case LT_EXPR:
5122             case GE_EXPR:
5123             case LE_EXPR:
5124             case EQ_EXPR:
5125             case NE_EXPR:
5126               if (TREE_CODE (TREE_TYPE (arg1)) == ENUMERAL_TYPE
5127                   && TREE_CODE (TREE_TYPE (arg2)) == ENUMERAL_TYPE
5128                   && (TYPE_MAIN_VARIANT (TREE_TYPE (arg1))
5129                       != TYPE_MAIN_VARIANT (TREE_TYPE (arg2)))
5130                   && (complain & tf_warning))
5131                 {
5132                   warning (OPT_Wenum_compare,
5133                            "comparison between %q#T and %q#T",
5134                            TREE_TYPE (arg1), TREE_TYPE (arg2));
5135                 }
5136               break;
5137             default:
5138               break;
5139             }
5140
5141           /* We need to strip any leading REF_BIND so that bitfields
5142              don't cause errors.  This should not remove any important
5143              conversions, because builtins don't apply to class
5144              objects directly.  */
5145           conv = cand->convs[0];
5146           if (conv->kind == ck_ref_bind)
5147             conv = conv->u.next;
5148           arg1 = convert_like (conv, arg1, complain);
5149
5150           if (arg2)
5151             {
5152               /* We need to call warn_logical_operator before
5153                  converting arg2 to a boolean_type.  */
5154               if (complain & tf_warning)
5155                 warn_logical_operator (input_location, code, boolean_type_node,
5156                                        code_orig_arg1, arg1,
5157                                        code_orig_arg2, arg2);
5158
5159               conv = cand->convs[1];
5160               if (conv->kind == ck_ref_bind)
5161                 conv = conv->u.next;
5162               arg2 = convert_like (conv, arg2, complain);
5163             }
5164           if (arg3)
5165             {
5166               conv = cand->convs[2];
5167               if (conv->kind == ck_ref_bind)
5168                 conv = conv->u.next;
5169               arg3 = convert_like (conv, arg3, complain);
5170             }
5171
5172         }
5173     }
5174
5175  user_defined_result_ready:
5176
5177   /* Free all the conversions we allocated.  */
5178   obstack_free (&conversion_obstack, p);
5179
5180   if (result || result_valid_p)
5181     return result;
5182
5183  builtin:
5184   switch (code)
5185     {
5186     case MODIFY_EXPR:
5187       return cp_build_modify_expr (arg1, code2, arg2, complain);
5188
5189     case INDIRECT_REF:
5190       return cp_build_indirect_ref (arg1, RO_UNARY_STAR, complain);
5191
5192     case TRUTH_ANDIF_EXPR:
5193     case TRUTH_ORIF_EXPR:
5194     case TRUTH_AND_EXPR:
5195     case TRUTH_OR_EXPR:
5196       warn_logical_operator (input_location, code, boolean_type_node,
5197                              code_orig_arg1, arg1, code_orig_arg2, arg2);
5198       /* Fall through.  */
5199     case PLUS_EXPR:
5200     case MINUS_EXPR:
5201     case MULT_EXPR:
5202     case TRUNC_DIV_EXPR:
5203     case GT_EXPR:
5204     case LT_EXPR:
5205     case GE_EXPR:
5206     case LE_EXPR:
5207     case EQ_EXPR:
5208     case NE_EXPR:
5209     case MAX_EXPR:
5210     case MIN_EXPR:
5211     case LSHIFT_EXPR:
5212     case RSHIFT_EXPR:
5213     case TRUNC_MOD_EXPR:
5214     case BIT_AND_EXPR:
5215     case BIT_IOR_EXPR:
5216     case BIT_XOR_EXPR:
5217       return cp_build_binary_op (input_location, code, arg1, arg2, complain);
5218
5219     case UNARY_PLUS_EXPR:
5220     case NEGATE_EXPR:
5221     case BIT_NOT_EXPR:
5222     case TRUTH_NOT_EXPR:
5223     case PREINCREMENT_EXPR:
5224     case POSTINCREMENT_EXPR:
5225     case PREDECREMENT_EXPR:
5226     case POSTDECREMENT_EXPR:
5227     case REALPART_EXPR:
5228     case IMAGPART_EXPR:
5229     case ABS_EXPR:
5230       return cp_build_unary_op (code, arg1, candidates != 0, complain);
5231
5232     case ARRAY_REF:
5233       return cp_build_array_ref (input_location, arg1, arg2, complain);
5234
5235     case MEMBER_REF:
5236       return build_m_component_ref (cp_build_indirect_ref (arg1, RO_NULL, 
5237                                                            complain), 
5238                                     arg2);
5239
5240       /* The caller will deal with these.  */
5241     case ADDR_EXPR:
5242     case COMPONENT_REF:
5243     case COMPOUND_EXPR:
5244       return NULL_TREE;
5245
5246     default:
5247       gcc_unreachable ();
5248     }
5249   return NULL_TREE;
5250 }
5251
5252 /* Wrapper for above.  */
5253
5254 tree
5255 build_new_op (enum tree_code code, int flags, tree arg1, tree arg2, tree arg3,
5256               tree *overload, tsubst_flags_t complain)
5257 {
5258   tree ret;
5259   bool subtime = timevar_cond_start (TV_OVERLOAD);
5260   ret = build_new_op_1 (code, flags, arg1, arg2, arg3, overload, complain);
5261   timevar_cond_stop (TV_OVERLOAD, subtime);
5262   return ret;
5263 }
5264
5265 /* Returns true iff T, an element of an OVERLOAD chain, is a usual
5266    deallocation function (3.7.4.2 [basic.stc.dynamic.deallocation]).  */
5267
5268 static bool
5269 non_placement_deallocation_fn_p (tree t)
5270 {
5271   /* A template instance is never a usual deallocation function,
5272      regardless of its signature.  */
5273   if (TREE_CODE (t) == TEMPLATE_DECL
5274       || primary_template_instantiation_p (t))
5275     return false;
5276
5277   /* If a class T has a member deallocation function named operator delete
5278      with exactly one parameter, then that function is a usual
5279      (non-placement) deallocation function. If class T does not declare
5280      such an operator delete but does declare a member deallocation
5281      function named operator delete with exactly two parameters, the second
5282      of which has type std::size_t (18.2), then this function is a usual
5283      deallocation function.  */
5284   t = FUNCTION_ARG_CHAIN (t);
5285   if (t == void_list_node
5286       || (t && same_type_p (TREE_VALUE (t), size_type_node)
5287           && TREE_CHAIN (t) == void_list_node))
5288     return true;
5289   return false;
5290 }
5291
5292 /* Build a call to operator delete.  This has to be handled very specially,
5293    because the restrictions on what signatures match are different from all
5294    other call instances.  For a normal delete, only a delete taking (void *)
5295    or (void *, size_t) is accepted.  For a placement delete, only an exact
5296    match with the placement new is accepted.
5297
5298    CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
5299    ADDR is the pointer to be deleted.
5300    SIZE is the size of the memory block to be deleted.
5301    GLOBAL_P is true if the delete-expression should not consider
5302    class-specific delete operators.
5303    PLACEMENT is the corresponding placement new call, or NULL_TREE.
5304
5305    If this call to "operator delete" is being generated as part to
5306    deallocate memory allocated via a new-expression (as per [expr.new]
5307    which requires that if the initialization throws an exception then
5308    we call a deallocation function), then ALLOC_FN is the allocation
5309    function.  */
5310
5311 tree
5312 build_op_delete_call (enum tree_code code, tree addr, tree size,
5313                       bool global_p, tree placement,
5314                       tree alloc_fn)
5315 {
5316   tree fn = NULL_TREE;
5317   tree fns, fnname, type, t;
5318
5319   if (addr == error_mark_node)
5320     return error_mark_node;
5321
5322   type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
5323
5324   fnname = ansi_opname (code);
5325
5326   if (CLASS_TYPE_P (type)
5327       && COMPLETE_TYPE_P (complete_type (type))
5328       && !global_p)
5329     /* In [class.free]
5330
5331        If the result of the lookup is ambiguous or inaccessible, or if
5332        the lookup selects a placement deallocation function, the
5333        program is ill-formed.
5334
5335        Therefore, we ask lookup_fnfields to complain about ambiguity.  */
5336     {
5337       fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1);
5338       if (fns == error_mark_node)
5339         return error_mark_node;
5340     }
5341   else
5342     fns = NULL_TREE;
5343
5344   if (fns == NULL_TREE)
5345     fns = lookup_name_nonclass (fnname);
5346
5347   /* Strip const and volatile from addr.  */
5348   addr = cp_convert (ptr_type_node, addr);
5349
5350   if (placement)
5351     {
5352       /* "A declaration of a placement deallocation function matches the
5353          declaration of a placement allocation function if it has the same
5354          number of parameters and, after parameter transformations (8.3.5),
5355          all parameter types except the first are identical."
5356
5357          So we build up the function type we want and ask instantiate_type
5358          to get it for us.  */
5359       t = FUNCTION_ARG_CHAIN (alloc_fn);
5360       t = tree_cons (NULL_TREE, ptr_type_node, t);
5361       t = build_function_type (void_type_node, t);
5362
5363       fn = instantiate_type (t, fns, tf_none);
5364       if (fn == error_mark_node)
5365         return NULL_TREE;
5366
5367       if (BASELINK_P (fn))
5368         fn = BASELINK_FUNCTIONS (fn);
5369
5370       /* "If the lookup finds the two-parameter form of a usual deallocation
5371          function (3.7.4.2) and that function, considered as a placement
5372          deallocation function, would have been selected as a match for the
5373          allocation function, the program is ill-formed."  */
5374       if (non_placement_deallocation_fn_p (fn))
5375         {
5376           /* But if the class has an operator delete (void *), then that is
5377              the usual deallocation function, so we shouldn't complain
5378              about using the operator delete (void *, size_t).  */
5379           for (t = BASELINK_P (fns) ? BASELINK_FUNCTIONS (fns) : fns;
5380                t; t = OVL_NEXT (t))
5381             {
5382               tree elt = OVL_CURRENT (t);
5383               if (non_placement_deallocation_fn_p (elt)
5384                   && FUNCTION_ARG_CHAIN (elt) == void_list_node)
5385                 goto ok;
5386             }
5387           permerror (0, "non-placement deallocation function %q+D", fn);
5388           permerror (input_location, "selected for placement delete");
5389         ok:;
5390         }
5391     }
5392   else
5393     /* "Any non-placement deallocation function matches a non-placement
5394        allocation function. If the lookup finds a single matching
5395        deallocation function, that function will be called; otherwise, no
5396        deallocation function will be called."  */
5397     for (t = BASELINK_P (fns) ? BASELINK_FUNCTIONS (fns) : fns;
5398          t; t = OVL_NEXT (t))
5399       {
5400         tree elt = OVL_CURRENT (t);
5401         if (non_placement_deallocation_fn_p (elt))
5402           {
5403             fn = elt;
5404             /* "If a class T has a member deallocation function named
5405                operator delete with exactly one parameter, then that
5406                function is a usual (non-placement) deallocation
5407                function. If class T does not declare such an operator
5408                delete but does declare a member deallocation function named
5409                operator delete with exactly two parameters, the second of
5410                which has type std::size_t (18.2), then this function is a
5411                usual deallocation function."
5412
5413                So (void*) beats (void*, size_t).  */
5414             if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
5415               break;
5416           }
5417       }
5418
5419   /* If we have a matching function, call it.  */
5420   if (fn)
5421     {
5422       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
5423
5424       /* If the FN is a member function, make sure that it is
5425          accessible.  */
5426       if (BASELINK_P (fns))
5427         perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn);
5428
5429       /* Core issue 901: It's ok to new a type with deleted delete.  */
5430       if (DECL_DELETED_FN (fn) && alloc_fn)
5431         return NULL_TREE;
5432
5433       if (placement)
5434         {
5435           /* The placement args might not be suitable for overload
5436              resolution at this point, so build the call directly.  */
5437           int nargs = call_expr_nargs (placement);
5438           tree *argarray = XALLOCAVEC (tree, nargs);
5439           int i;
5440           argarray[0] = addr;
5441           for (i = 1; i < nargs; i++)
5442             argarray[i] = CALL_EXPR_ARG (placement, i);
5443           mark_used (fn);
5444           return build_cxx_call (fn, nargs, argarray);
5445         }
5446       else
5447         {
5448           tree ret;
5449           VEC(tree,gc) *args = VEC_alloc (tree, gc, 2);
5450           VEC_quick_push (tree, args, addr);
5451           if (FUNCTION_ARG_CHAIN (fn) != void_list_node)
5452             VEC_quick_push (tree, args, size);
5453           ret = cp_build_function_call_vec (fn, &args, tf_warning_or_error);
5454           VEC_free (tree, gc, args);
5455           return ret;
5456         }
5457     }
5458
5459   /* [expr.new]
5460
5461      If no unambiguous matching deallocation function can be found,
5462      propagating the exception does not cause the object's memory to
5463      be freed.  */
5464   if (alloc_fn)
5465     {
5466       if (!placement)
5467         warning (0, "no corresponding deallocation function for %qD",
5468                  alloc_fn);
5469       return NULL_TREE;
5470     }
5471
5472   error ("no suitable %<operator %s%> for %qT",
5473          operator_name_info[(int)code].name, type);
5474   return error_mark_node;
5475 }
5476
5477 /* If the current scope isn't allowed to access DECL along
5478    BASETYPE_PATH, give an error.  The most derived class in
5479    BASETYPE_PATH is the one used to qualify DECL. DIAG_DECL is
5480    the declaration to use in the error diagnostic.  */
5481
5482 bool
5483 enforce_access (tree basetype_path, tree decl, tree diag_decl)
5484 {
5485   gcc_assert (TREE_CODE (basetype_path) == TREE_BINFO);
5486
5487   if (!accessible_p (basetype_path, decl, true))
5488     {
5489       if (TREE_PRIVATE (decl))
5490         error ("%q+#D is private", diag_decl);
5491       else if (TREE_PROTECTED (decl))
5492         error ("%q+#D is protected", diag_decl);
5493       else
5494         error ("%q+#D is inaccessible", diag_decl);
5495       error ("within this context");
5496       return false;
5497     }
5498
5499   return true;
5500 }
5501
5502 /* Initialize a temporary of type TYPE with EXPR.  The FLAGS are a
5503    bitwise or of LOOKUP_* values.  If any errors are warnings are
5504    generated, set *DIAGNOSTIC_FN to "error" or "warning",
5505    respectively.  If no diagnostics are generated, set *DIAGNOSTIC_FN
5506    to NULL.  */
5507
5508 static tree
5509 build_temp (tree expr, tree type, int flags,
5510             diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
5511 {
5512   int savew, savee;
5513   VEC(tree,gc) *args;
5514
5515   savew = warningcount, savee = errorcount;
5516   args = make_tree_vector_single (expr);
5517   expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5518                                     &args, type, flags, complain);
5519   release_tree_vector (args);
5520   if (warningcount > savew)
5521     *diagnostic_kind = DK_WARNING;
5522   else if (errorcount > savee)
5523     *diagnostic_kind = DK_ERROR;
5524   else
5525     *diagnostic_kind = DK_UNSPECIFIED;
5526   return expr;
5527 }
5528
5529 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
5530    EXPR is implicitly converted to type TOTYPE.
5531    FN and ARGNUM are used for diagnostics.  */
5532
5533 static void
5534 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
5535 {
5536   /* Issue warnings about peculiar, but valid, uses of NULL.  */
5537   if (expr == null_node && TREE_CODE (totype) != BOOLEAN_TYPE
5538       && ARITHMETIC_TYPE_P (totype))
5539     {
5540       if (fn)
5541         warning_at (input_location, OPT_Wconversion_null,
5542                     "passing NULL to non-pointer argument %P of %qD",
5543                     argnum, fn);
5544       else
5545         warning_at (input_location, OPT_Wconversion_null,
5546                     "converting to non-pointer type %qT from NULL", totype);
5547     }
5548
5549   /* Issue warnings if "false" is converted to a NULL pointer */
5550   else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
5551            && TYPE_PTR_P (totype))
5552     {
5553       if (fn)
5554         warning_at (input_location, OPT_Wconversion_null,
5555                     "converting %<false%> to pointer type for argument %P "
5556                     "of %qD", argnum, fn);
5557       else
5558         warning_at (input_location, OPT_Wconversion_null,
5559                     "converting %<false%> to pointer type %qT", totype);
5560     }
5561 }
5562
5563 /* Perform the conversions in CONVS on the expression EXPR.  FN and
5564    ARGNUM are used for diagnostics.  ARGNUM is zero based, -1
5565    indicates the `this' argument of a method.  INNER is nonzero when
5566    being called to continue a conversion chain. It is negative when a
5567    reference binding will be applied, positive otherwise.  If
5568    ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
5569    conversions will be emitted if appropriate.  If C_CAST_P is true,
5570    this conversion is coming from a C-style cast; in that case,
5571    conversions to inaccessible bases are permitted.  */
5572
5573 static tree
5574 convert_like_real (conversion *convs, tree expr, tree fn, int argnum,
5575                    int inner, bool issue_conversion_warnings,
5576                    bool c_cast_p, tsubst_flags_t complain)
5577 {
5578   tree totype = convs->type;
5579   diagnostic_t diag_kind;
5580   int flags;
5581
5582   if (convs->bad_p && !(complain & tf_error))
5583     return error_mark_node;
5584
5585   if (convs->bad_p
5586       && convs->kind != ck_user
5587       && convs->kind != ck_list
5588       && convs->kind != ck_ambig
5589       && (convs->kind != ck_ref_bind
5590           || convs->user_conv_p)
5591       && convs->kind != ck_rvalue
5592       && convs->kind != ck_base)
5593     {
5594       conversion *t = convs;
5595
5596       /* Give a helpful error if this is bad because of excess braces.  */
5597       if (BRACE_ENCLOSED_INITIALIZER_P (expr)
5598           && SCALAR_TYPE_P (totype)
5599           && CONSTRUCTOR_NELTS (expr) > 0
5600           && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
5601         permerror (input_location, "too many braces around initializer for %qT", totype);
5602
5603       for (; t ; t = next_conversion (t))
5604         {
5605           if (t->kind == ck_user && t->cand->reason)
5606             {
5607               permerror (input_location, "invalid user-defined conversion "
5608                          "from %qT to %qT", TREE_TYPE (expr), totype);
5609               print_z_candidate ("candidate is:", t->cand);
5610               expr = convert_like_real (t, expr, fn, argnum, 1,
5611                                         /*issue_conversion_warnings=*/false,
5612                                         /*c_cast_p=*/false,
5613                                         complain);
5614               if (convs->kind == ck_ref_bind)
5615                 return convert_to_reference (totype, expr, CONV_IMPLICIT,
5616                                              LOOKUP_NORMAL, NULL_TREE);
5617               else
5618                 return cp_convert (totype, expr);
5619             }
5620           else if (t->kind == ck_user || !t->bad_p)
5621             {
5622               expr = convert_like_real (t, expr, fn, argnum, 1,
5623                                         /*issue_conversion_warnings=*/false,
5624                                         /*c_cast_p=*/false,
5625                                         complain);
5626               break;
5627             }
5628           else if (t->kind == ck_ambig)
5629             return convert_like_real (t, expr, fn, argnum, 1,
5630                                       /*issue_conversion_warnings=*/false,
5631                                       /*c_cast_p=*/false,
5632                                       complain);
5633           else if (t->kind == ck_identity)
5634             break;
5635         }
5636
5637       permerror (input_location, "invalid conversion from %qT to %qT",
5638                  TREE_TYPE (expr), totype);
5639       if (fn)
5640         permerror (DECL_SOURCE_LOCATION (fn),
5641                    "  initializing argument %P of %qD", argnum, fn);
5642
5643       return cp_convert (totype, expr);
5644     }
5645
5646   if (issue_conversion_warnings && (complain & tf_warning))
5647     conversion_null_warnings (totype, expr, fn, argnum);
5648
5649   switch (convs->kind)
5650     {
5651     case ck_user:
5652       {
5653         struct z_candidate *cand = convs->cand;
5654         tree convfn = cand->fn;
5655         unsigned i;
5656
5657         /* If we're initializing from {}, it's value-initialization.  */
5658         if (BRACE_ENCLOSED_INITIALIZER_P (expr)
5659             && CONSTRUCTOR_NELTS (expr) == 0
5660             && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
5661           {
5662             bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
5663             expr = build_value_init (totype, complain);
5664             expr = get_target_expr_sfinae (expr, complain);
5665             if (expr != error_mark_node)
5666               {
5667                 TARGET_EXPR_LIST_INIT_P (expr) = true;
5668                 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
5669               }
5670             return expr;
5671           }
5672
5673         expr = mark_rvalue_use (expr);
5674
5675         /* When converting from an init list we consider explicit
5676            constructors, but actually trying to call one is an error.  */
5677         if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
5678             /* Unless this is for direct-list-initialization.  */
5679             && !(BRACE_ENCLOSED_INITIALIZER_P (expr)
5680                  && CONSTRUCTOR_IS_DIRECT_INIT (expr))
5681             /* Unless we're calling it for value-initialization from an
5682                empty list, since that is handled separately in 8.5.4.  */
5683             && cand->num_convs > 0)
5684           {
5685             error ("converting to %qT from initializer list would use "
5686                    "explicit constructor %qD", totype, convfn);
5687           }
5688
5689         /* Set user_conv_p on the argument conversions, so rvalue/base
5690            handling knows not to allow any more UDCs.  */
5691         for (i = 0; i < cand->num_convs; ++i)
5692           cand->convs[i]->user_conv_p = true;
5693
5694         expr = build_over_call (cand, LOOKUP_NORMAL, complain);
5695
5696         /* If this is a constructor or a function returning an aggr type,
5697            we need to build up a TARGET_EXPR.  */
5698         if (DECL_CONSTRUCTOR_P (convfn))
5699           {
5700             expr = build_cplus_new (totype, expr, complain);
5701
5702             /* Remember that this was list-initialization.  */
5703             if (convs->check_narrowing && expr != error_mark_node)
5704               TARGET_EXPR_LIST_INIT_P (expr) = true;
5705           }
5706
5707         return expr;
5708       }
5709     case ck_identity:
5710       expr = mark_rvalue_use (expr);
5711       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
5712         {
5713           int nelts = CONSTRUCTOR_NELTS (expr);
5714           if (nelts == 0)
5715             expr = build_value_init (totype, complain);
5716           else if (nelts == 1)
5717             expr = CONSTRUCTOR_ELT (expr, 0)->value;
5718           else
5719             gcc_unreachable ();
5720         }
5721
5722       if (type_unknown_p (expr))
5723         expr = instantiate_type (totype, expr, complain);
5724       /* Convert a constant to its underlying value, unless we are
5725          about to bind it to a reference, in which case we need to
5726          leave it as an lvalue.  */
5727       if (inner >= 0)
5728         {   
5729           expr = decl_constant_value_safe (expr);
5730           if (expr == null_node && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
5731             /* If __null has been converted to an integer type, we do not
5732                want to warn about uses of EXPR as an integer, rather than
5733                as a pointer.  */
5734             expr = build_int_cst (totype, 0);
5735         }
5736       return expr;
5737     case ck_ambig:
5738       /* We leave bad_p off ck_ambig because overload resolution considers
5739          it valid, it just fails when we try to perform it.  So we need to
5740          check complain here, too.  */
5741       if (complain & tf_error)
5742         {
5743           /* Call build_user_type_conversion again for the error.  */
5744           build_user_type_conversion (totype, convs->u.expr, LOOKUP_NORMAL);
5745           if (fn)
5746             error ("  initializing argument %P of %q+D", argnum, fn);
5747         }
5748       return error_mark_node;
5749
5750     case ck_list:
5751       {
5752         /* Conversion to std::initializer_list<T>.  */
5753         tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
5754         tree new_ctor = build_constructor (init_list_type_node, NULL);
5755         unsigned len = CONSTRUCTOR_NELTS (expr);
5756         tree array, val, field;
5757         VEC(constructor_elt,gc) *vec = NULL;
5758         unsigned ix;
5759
5760         /* Convert all the elements.  */
5761         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
5762           {
5763             tree sub = convert_like_real (convs->u.list[ix], val, fn, argnum,
5764                                           1, false, false, complain);
5765             if (sub == error_mark_node)
5766               return sub;
5767             if (!BRACE_ENCLOSED_INITIALIZER_P (val))
5768               check_narrowing (TREE_TYPE (sub), val);
5769             CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor), NULL_TREE, sub);
5770             if (!TREE_CONSTANT (sub))
5771               TREE_CONSTANT (new_ctor) = false;
5772           }
5773         /* Build up the array.  */
5774         elttype = cp_build_qualified_type
5775           (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
5776         array = build_array_of_n_type (elttype, len);
5777         array = finish_compound_literal (array, new_ctor, complain);
5778         /* Take the address explicitly rather than via decay_conversion
5779            to avoid the error about taking the address of a temporary.  */
5780         array = cp_build_addr_expr (array, complain);
5781         array = cp_convert (build_pointer_type (elttype), array);
5782
5783         /* Build up the initializer_list object.  */
5784         totype = complete_type (totype);
5785         field = next_initializable_field (TYPE_FIELDS (totype));
5786         CONSTRUCTOR_APPEND_ELT (vec, field, array);
5787         field = next_initializable_field (DECL_CHAIN (field));
5788         CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
5789         new_ctor = build_constructor (totype, vec);
5790         return get_target_expr (new_ctor);
5791       }
5792
5793     case ck_aggr:
5794       if (TREE_CODE (totype) == COMPLEX_TYPE)
5795         {
5796           tree real = CONSTRUCTOR_ELT (expr, 0)->value;
5797           tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
5798           real = perform_implicit_conversion (TREE_TYPE (totype),
5799                                               real, complain);
5800           imag = perform_implicit_conversion (TREE_TYPE (totype),
5801                                               imag, complain);
5802           expr = build2 (COMPLEX_EXPR, totype, real, imag);
5803           return fold_if_not_in_template (expr);
5804         }
5805       return get_target_expr (digest_init (totype, expr, complain));
5806
5807     default:
5808       break;
5809     };
5810
5811   expr = convert_like_real (convs->u.next, expr, fn, argnum,
5812                             convs->kind == ck_ref_bind ? -1 : 1,
5813                             convs->kind == ck_ref_bind ? issue_conversion_warnings : false, 
5814                             c_cast_p,
5815                             complain);
5816   if (expr == error_mark_node)
5817     return error_mark_node;
5818
5819   switch (convs->kind)
5820     {
5821     case ck_rvalue:
5822       expr = decay_conversion (expr);
5823       if (! MAYBE_CLASS_TYPE_P (totype))
5824         return expr;
5825       /* Else fall through.  */
5826     case ck_base:
5827       if (convs->kind == ck_base && !convs->need_temporary_p)
5828         {
5829           /* We are going to bind a reference directly to a base-class
5830              subobject of EXPR.  */
5831           /* Build an expression for `*((base*) &expr)'.  */
5832           expr = cp_build_addr_expr (expr, complain);
5833           expr = convert_to_base (expr, build_pointer_type (totype),
5834                                   !c_cast_p, /*nonnull=*/true, complain);
5835           expr = cp_build_indirect_ref (expr, RO_IMPLICIT_CONVERSION, complain);
5836           return expr;
5837         }
5838
5839       /* Copy-initialization where the cv-unqualified version of the source
5840          type is the same class as, or a derived class of, the class of the
5841          destination [is treated as direct-initialization].  [dcl.init] */
5842       flags = LOOKUP_NORMAL|LOOKUP_ONLYCONVERTING;
5843       if (convs->user_conv_p)
5844         /* This conversion is being done in the context of a user-defined
5845            conversion (i.e. the second step of copy-initialization), so
5846            don't allow any more.  */
5847         flags |= LOOKUP_NO_CONVERSION;
5848       if (convs->rvaluedness_matches_p)
5849         flags |= LOOKUP_PREFER_RVALUE;
5850       if (TREE_CODE (expr) == TARGET_EXPR
5851           && TARGET_EXPR_LIST_INIT_P (expr))
5852         /* Copy-list-initialization doesn't actually involve a copy.  */
5853         return expr;
5854       expr = build_temp (expr, totype, flags, &diag_kind, complain);
5855       if (diag_kind && fn && complain)
5856         emit_diagnostic (diag_kind, DECL_SOURCE_LOCATION (fn), 0,
5857                          "  initializing argument %P of %qD", argnum, fn);
5858       return build_cplus_new (totype, expr, complain);
5859
5860     case ck_ref_bind:
5861       {
5862         tree ref_type = totype;
5863
5864         if (convs->bad_p && !convs->u.next->bad_p)
5865           {
5866             gcc_assert (TYPE_REF_IS_RVALUE (ref_type)
5867                         && real_lvalue_p (expr));
5868
5869             error ("cannot bind %qT lvalue to %qT",
5870                    TREE_TYPE (expr), totype);
5871             if (fn)
5872               error ("  initializing argument %P of %q+D", argnum, fn);
5873             return error_mark_node;
5874           }
5875
5876         /* If necessary, create a temporary. 
5877
5878            VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
5879            that need temporaries, even when their types are reference
5880            compatible with the type of reference being bound, so the
5881            upcoming call to cp_build_addr_expr doesn't fail.  */
5882         if (convs->need_temporary_p
5883             || TREE_CODE (expr) == CONSTRUCTOR
5884             || TREE_CODE (expr) == VA_ARG_EXPR)
5885           {
5886             /* Otherwise, a temporary of type "cv1 T1" is created and
5887                initialized from the initializer expression using the rules
5888                for a non-reference copy-initialization (8.5).  */
5889
5890             tree type = TREE_TYPE (ref_type);
5891             cp_lvalue_kind lvalue = real_lvalue_p (expr);
5892
5893             gcc_assert (same_type_ignoring_top_level_qualifiers_p
5894                         (type, convs->u.next->type));
5895             if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
5896                 && !TYPE_REF_IS_RVALUE (ref_type))
5897               {
5898                 /* If the reference is volatile or non-const, we
5899                    cannot create a temporary.  */
5900                 if (lvalue & clk_bitfield)
5901                   error ("cannot bind bitfield %qE to %qT",
5902                          expr, ref_type);
5903                 else if (lvalue & clk_packed)
5904                   error ("cannot bind packed field %qE to %qT",
5905                          expr, ref_type);
5906                 else
5907                   error ("cannot bind rvalue %qE to %qT", expr, ref_type);
5908                 return error_mark_node;
5909               }
5910             /* If the source is a packed field, and we must use a copy
5911                constructor, then building the target expr will require
5912                binding the field to the reference parameter to the
5913                copy constructor, and we'll end up with an infinite
5914                loop.  If we can use a bitwise copy, then we'll be
5915                OK.  */
5916             if ((lvalue & clk_packed)
5917                 && CLASS_TYPE_P (type)
5918                 && type_has_nontrivial_copy_init (type))
5919               {
5920                 error ("cannot bind packed field %qE to %qT",
5921                        expr, ref_type);
5922                 return error_mark_node;
5923               }
5924             if (lvalue & clk_bitfield)
5925               {
5926                 expr = convert_bitfield_to_declared_type (expr);
5927                 expr = fold_convert (type, expr);
5928               }
5929             expr = build_target_expr_with_type (expr, type, complain);
5930           }
5931
5932         /* Take the address of the thing to which we will bind the
5933            reference.  */
5934         expr = cp_build_addr_expr (expr, complain);
5935         if (expr == error_mark_node)
5936           return error_mark_node;
5937
5938         /* Convert it to a pointer to the type referred to by the
5939            reference.  This will adjust the pointer if a derived to
5940            base conversion is being performed.  */
5941         expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
5942                            expr);
5943         /* Convert the pointer to the desired reference type.  */
5944         return build_nop (ref_type, expr);
5945       }
5946
5947     case ck_lvalue:
5948       return decay_conversion (expr);
5949
5950     case ck_qual:
5951       /* Warn about deprecated conversion if appropriate.  */
5952       string_conv_p (totype, expr, 1);
5953       break;
5954
5955     case ck_ptr:
5956       if (convs->base_p)
5957         expr = convert_to_base (expr, totype, !c_cast_p,
5958                                 /*nonnull=*/false, complain);
5959       return build_nop (totype, expr);
5960
5961     case ck_pmem:
5962       return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
5963                              c_cast_p, complain);
5964
5965     default:
5966       break;
5967     }
5968
5969   if (convs->check_narrowing)
5970     check_narrowing (totype, expr);
5971
5972   if (issue_conversion_warnings && (complain & tf_warning))
5973     expr = convert_and_check (totype, expr);
5974   else
5975     expr = convert (totype, expr);
5976
5977   return expr;
5978 }
5979
5980 /* ARG is being passed to a varargs function.  Perform any conversions
5981    required.  Return the converted value.  */
5982
5983 tree
5984 convert_arg_to_ellipsis (tree arg)
5985 {
5986   tree arg_type;
5987
5988   /* [expr.call]
5989
5990      The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
5991      standard conversions are performed.  */
5992   arg = decay_conversion (arg);
5993   arg_type = TREE_TYPE (arg);
5994   /* [expr.call]
5995
5996      If the argument has integral or enumeration type that is subject
5997      to the integral promotions (_conv.prom_), or a floating point
5998      type that is subject to the floating point promotion
5999      (_conv.fpprom_), the value of the argument is converted to the
6000      promoted type before the call.  */
6001   if (TREE_CODE (arg_type) == REAL_TYPE
6002       && (TYPE_PRECISION (arg_type)
6003           < TYPE_PRECISION (double_type_node))
6004       && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type)))
6005     {
6006       if (warn_double_promotion && !c_inhibit_evaluation_warnings)
6007         warning (OPT_Wdouble_promotion,
6008                  "implicit conversion from %qT to %qT when passing "
6009                  "argument to function",
6010                  arg_type, double_type_node);
6011       arg = convert_to_real (double_type_node, arg);
6012     }
6013   else if (NULLPTR_TYPE_P (arg_type))
6014     arg = null_pointer_node;
6015   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
6016     {
6017       if (SCOPED_ENUM_P (arg_type) && !abi_version_at_least (6))
6018         {
6019           warning (OPT_Wabi, "scoped enum %qT will not promote to an "
6020                    "integral type in a future version of GCC", arg_type);
6021           arg = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg);
6022         }
6023       arg = perform_integral_promotions (arg);
6024     }
6025
6026   arg = require_complete_type (arg);
6027   arg_type = TREE_TYPE (arg);
6028
6029   if (arg != error_mark_node
6030       /* In a template (or ill-formed code), we can have an incomplete type
6031          even after require_complete_type, in which case we don't know
6032          whether it has trivial copy or not.  */
6033       && COMPLETE_TYPE_P (arg_type))
6034     {
6035       /* Build up a real lvalue-to-rvalue conversion in case the
6036          copy constructor is trivial but not callable.  */
6037       if (!cp_unevaluated_operand && CLASS_TYPE_P (arg_type))
6038         force_rvalue (arg, tf_warning_or_error);
6039
6040       /* [expr.call] 5.2.2/7:
6041          Passing a potentially-evaluated argument of class type (Clause 9)
6042          with a non-trivial copy constructor or a non-trivial destructor
6043          with no corresponding parameter is conditionally-supported, with
6044          implementation-defined semantics.
6045
6046          We used to just warn here and do a bitwise copy, but now
6047          cp_expr_size will abort if we try to do that.
6048
6049          If the call appears in the context of a sizeof expression,
6050          it is not potentially-evaluated.  */
6051       if (cp_unevaluated_operand == 0
6052           && (type_has_nontrivial_copy_init (arg_type)
6053               || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type)))
6054         error ("cannot pass objects of non-trivially-copyable "
6055                "type %q#T through %<...%>", arg_type);
6056     }
6057
6058   return arg;
6059 }
6060
6061 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused.  */
6062
6063 tree
6064 build_x_va_arg (tree expr, tree type)
6065 {
6066   if (processing_template_decl)
6067     return build_min (VA_ARG_EXPR, type, expr);
6068
6069   type = complete_type_or_else (type, NULL_TREE);
6070
6071   if (expr == error_mark_node || !type)
6072     return error_mark_node;
6073
6074   expr = mark_lvalue_use (expr);
6075
6076   if (type_has_nontrivial_copy_init (type)
6077       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
6078       || TREE_CODE (type) == REFERENCE_TYPE)
6079     {
6080       /* Remove reference types so we don't ICE later on.  */
6081       tree type1 = non_reference (type);
6082       /* conditionally-supported behavior [expr.call] 5.2.2/7.  */
6083       error ("cannot receive objects of non-trivially-copyable type %q#T "
6084              "through %<...%>; ", type);
6085       expr = convert (build_pointer_type (type1), null_node);
6086       expr = cp_build_indirect_ref (expr, RO_NULL, tf_warning_or_error);
6087       return expr;
6088     }
6089
6090   return build_va_arg (input_location, expr, type);
6091 }
6092
6093 /* TYPE has been given to va_arg.  Apply the default conversions which
6094    would have happened when passed via ellipsis.  Return the promoted
6095    type, or the passed type if there is no change.  */
6096
6097 tree
6098 cxx_type_promotes_to (tree type)
6099 {
6100   tree promote;
6101
6102   /* Perform the array-to-pointer and function-to-pointer
6103      conversions.  */
6104   type = type_decays_to (type);
6105
6106   promote = type_promotes_to (type);
6107   if (same_type_p (type, promote))
6108     promote = type;
6109
6110   return promote;
6111 }
6112
6113 /* ARG is a default argument expression being passed to a parameter of
6114    the indicated TYPE, which is a parameter to FN.  PARMNUM is the
6115    zero-based argument number.  Do any required conversions.  Return
6116    the converted value.  */
6117
6118 static GTY(()) VEC(tree,gc) *default_arg_context;
6119 void
6120 push_defarg_context (tree fn)
6121 { VEC_safe_push (tree, gc, default_arg_context, fn); }
6122 void
6123 pop_defarg_context (void)
6124 { VEC_pop (tree, default_arg_context); }
6125
6126 tree
6127 convert_default_arg (tree type, tree arg, tree fn, int parmnum)
6128 {
6129   int i;
6130   tree t;
6131
6132   /* See through clones.  */
6133   fn = DECL_ORIGIN (fn);
6134
6135   /* Detect recursion.  */
6136   FOR_EACH_VEC_ELT (tree, default_arg_context, i, t)
6137     if (t == fn)
6138       {
6139         error ("recursive evaluation of default argument for %q#D", fn);
6140         return error_mark_node;
6141       }
6142
6143   /* If the ARG is an unparsed default argument expression, the
6144      conversion cannot be performed.  */
6145   if (TREE_CODE (arg) == DEFAULT_ARG)
6146     {
6147       error ("call to %qD uses the default argument for parameter %P, which "
6148              "is not yet defined", fn, parmnum);
6149       return error_mark_node;
6150     }
6151
6152   push_defarg_context (fn);
6153
6154   if (fn && DECL_TEMPLATE_INFO (fn))
6155     arg = tsubst_default_argument (fn, type, arg);
6156
6157   /* Due to:
6158
6159        [dcl.fct.default]
6160
6161        The names in the expression are bound, and the semantic
6162        constraints are checked, at the point where the default
6163        expressions appears.
6164
6165      we must not perform access checks here.  */
6166   push_deferring_access_checks (dk_no_check);
6167   /* We must make a copy of ARG, in case subsequent processing
6168      alters any part of it.  */
6169   arg = break_out_target_exprs (arg);
6170   if (TREE_CODE (arg) == CONSTRUCTOR)
6171     {
6172       arg = digest_init (type, arg, tf_warning_or_error);
6173       arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
6174                                         ICR_DEFAULT_ARGUMENT, fn, parmnum,
6175                                         tf_warning_or_error);
6176     }
6177   else
6178     {
6179       arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
6180                                         ICR_DEFAULT_ARGUMENT, fn, parmnum,
6181                                         tf_warning_or_error);
6182       arg = convert_for_arg_passing (type, arg);
6183     }
6184   pop_deferring_access_checks();
6185
6186   pop_defarg_context ();
6187
6188   return arg;
6189 }
6190
6191 /* Returns the type which will really be used for passing an argument of
6192    type TYPE.  */
6193
6194 tree
6195 type_passed_as (tree type)
6196 {
6197   /* Pass classes with copy ctors by invisible reference.  */
6198   if (TREE_ADDRESSABLE (type))
6199     {
6200       type = build_reference_type (type);
6201       /* There are no other pointers to this temporary.  */
6202       type = cp_build_qualified_type (type, TYPE_QUAL_RESTRICT);
6203     }
6204   else if (targetm.calls.promote_prototypes (type)
6205            && INTEGRAL_TYPE_P (type)
6206            && COMPLETE_TYPE_P (type)
6207            && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
6208                                    TYPE_SIZE (integer_type_node)))
6209     type = integer_type_node;
6210
6211   return type;
6212 }
6213
6214 /* Actually perform the appropriate conversion.  */
6215
6216 tree
6217 convert_for_arg_passing (tree type, tree val)
6218 {
6219   tree bitfield_type;
6220
6221   /* If VAL is a bitfield, then -- since it has already been converted
6222      to TYPE -- it cannot have a precision greater than TYPE.  
6223
6224      If it has a smaller precision, we must widen it here.  For
6225      example, passing "int f:3;" to a function expecting an "int" will
6226      not result in any conversion before this point.
6227
6228      If the precision is the same we must not risk widening.  For
6229      example, the COMPONENT_REF for a 32-bit "long long" bitfield will
6230      often have type "int", even though the C++ type for the field is
6231      "long long".  If the value is being passed to a function
6232      expecting an "int", then no conversions will be required.  But,
6233      if we call convert_bitfield_to_declared_type, the bitfield will
6234      be converted to "long long".  */
6235   bitfield_type = is_bitfield_expr_with_lowered_type (val);
6236   if (bitfield_type 
6237       && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
6238     val = convert_to_integer (TYPE_MAIN_VARIANT (bitfield_type), val);
6239
6240   if (val == error_mark_node)
6241     ;
6242   /* Pass classes with copy ctors by invisible reference.  */
6243   else if (TREE_ADDRESSABLE (type))
6244     val = build1 (ADDR_EXPR, build_reference_type (type), val);
6245   else if (targetm.calls.promote_prototypes (type)
6246            && INTEGRAL_TYPE_P (type)
6247            && COMPLETE_TYPE_P (type)
6248            && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
6249                                    TYPE_SIZE (integer_type_node)))
6250     val = perform_integral_promotions (val);
6251   if (warn_missing_format_attribute)
6252     {
6253       tree rhstype = TREE_TYPE (val);
6254       const enum tree_code coder = TREE_CODE (rhstype);
6255       const enum tree_code codel = TREE_CODE (type);
6256       if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
6257           && coder == codel
6258           && check_missing_format_attribute (type, rhstype))
6259         warning (OPT_Wmissing_format_attribute,
6260                  "argument of function call might be a candidate for a format attribute");
6261     }
6262   return val;
6263 }
6264
6265 /* Returns true iff FN is a function with magic varargs, i.e. ones for
6266    which no conversions at all should be done.  This is true for some
6267    builtins which don't act like normal functions.  */
6268
6269 static bool
6270 magic_varargs_p (tree fn)
6271 {
6272   if (DECL_BUILT_IN (fn))
6273     switch (DECL_FUNCTION_CODE (fn))
6274       {
6275       case BUILT_IN_CLASSIFY_TYPE:
6276       case BUILT_IN_CONSTANT_P:
6277       case BUILT_IN_NEXT_ARG:
6278       case BUILT_IN_VA_START:
6279         return true;
6280
6281       default:;
6282         return lookup_attribute ("type generic",
6283                                  TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
6284       }
6285
6286   return false;
6287 }
6288
6289 /* Subroutine of the various build_*_call functions.  Overload resolution
6290    has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
6291    ARGS is a TREE_LIST of the unconverted arguments to the call.  FLAGS is a
6292    bitmask of various LOOKUP_* flags which apply to the call itself.  */
6293
6294 static tree
6295 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
6296 {
6297   tree fn = cand->fn;
6298   const VEC(tree,gc) *args = cand->args;
6299   tree first_arg = cand->first_arg;
6300   conversion **convs = cand->convs;
6301   conversion *conv;
6302   tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
6303   int parmlen;
6304   tree val;
6305   int i = 0;
6306   int j = 0;
6307   unsigned int arg_index = 0;
6308   int is_method = 0;
6309   int nargs;
6310   tree *argarray;
6311   bool already_used = false;
6312
6313   /* In a template, there is no need to perform all of the work that
6314      is normally done.  We are only interested in the type of the call
6315      expression, i.e., the return type of the function.  Any semantic
6316      errors will be deferred until the template is instantiated.  */
6317   if (processing_template_decl)
6318     {
6319       tree expr;
6320       tree return_type;
6321       const tree *argarray;
6322       unsigned int nargs;
6323
6324       return_type = TREE_TYPE (TREE_TYPE (fn));
6325       nargs = VEC_length (tree, args);
6326       if (first_arg == NULL_TREE)
6327         argarray = VEC_address (tree, CONST_CAST (VEC(tree,gc) *, args));
6328       else
6329         {
6330           tree *alcarray;
6331           unsigned int ix;
6332           tree arg;
6333
6334           ++nargs;
6335           alcarray = XALLOCAVEC (tree, nargs);
6336           alcarray[0] = first_arg;
6337           FOR_EACH_VEC_ELT (tree, args, ix, arg)
6338             alcarray[ix + 1] = arg;
6339           argarray = alcarray;
6340         }
6341       expr = build_call_array_loc (input_location,
6342                                    return_type, build_addr_func (fn), nargs,
6343                                    argarray);
6344       if (TREE_THIS_VOLATILE (fn) && cfun)
6345         current_function_returns_abnormally = 1;
6346       return convert_from_reference (expr);
6347     }
6348
6349   /* Give any warnings we noticed during overload resolution.  */
6350   if (cand->warnings && (complain & tf_warning))
6351     {
6352       struct candidate_warning *w;
6353       for (w = cand->warnings; w; w = w->next)
6354         joust (cand, w->loser, 1);
6355     }
6356
6357   /* Make =delete work with SFINAE.  */
6358   if (DECL_DELETED_FN (fn) && !(complain & tf_error))
6359     return error_mark_node;
6360
6361   if (DECL_FUNCTION_MEMBER_P (fn))
6362     {
6363       tree access_fn;
6364       /* If FN is a template function, two cases must be considered.
6365          For example:
6366
6367            struct A {
6368              protected:
6369                template <class T> void f();
6370            };
6371            template <class T> struct B {
6372              protected:
6373                void g();
6374            };
6375            struct C : A, B<int> {
6376              using A::f;        // #1
6377              using B<int>::g;   // #2
6378            };
6379
6380          In case #1 where `A::f' is a member template, DECL_ACCESS is
6381          recorded in the primary template but not in its specialization.
6382          We check access of FN using its primary template.
6383
6384          In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
6385          because it is a member of class template B, DECL_ACCESS is
6386          recorded in the specialization `B<int>::g'.  We cannot use its
6387          primary template because `B<T>::g' and `B<int>::g' may have
6388          different access.  */
6389       if (DECL_TEMPLATE_INFO (fn)
6390           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
6391         access_fn = DECL_TI_TEMPLATE (fn);
6392       else
6393         access_fn = fn;
6394       if (flags & LOOKUP_SPECULATIVE)
6395         {
6396           if (!speculative_access_check (cand->access_path, access_fn, fn,
6397                                          !!(flags & LOOKUP_COMPLAIN)))
6398             return error_mark_node;
6399         }
6400       else
6401         perform_or_defer_access_check (cand->access_path, access_fn, fn);
6402     }
6403
6404   /* If we're checking for implicit delete, don't bother with argument
6405      conversions.  */
6406   if (flags & LOOKUP_SPECULATIVE)
6407     {
6408       if (DECL_DELETED_FN (fn))
6409         {
6410           if (flags & LOOKUP_COMPLAIN)
6411             mark_used (fn);
6412           return error_mark_node;
6413         }
6414       if (cand->viable == 1)
6415         return fn;
6416       else if (!(flags & LOOKUP_COMPLAIN))
6417         /* Reject bad conversions now.  */
6418         return error_mark_node;
6419       /* else continue to get conversion error.  */
6420     }
6421
6422   /* Find maximum size of vector to hold converted arguments.  */
6423   parmlen = list_length (parm);
6424   nargs = VEC_length (tree, args) + (first_arg != NULL_TREE ? 1 : 0);
6425   if (parmlen > nargs)
6426     nargs = parmlen;
6427   argarray = XALLOCAVEC (tree, nargs);
6428
6429   /* The implicit parameters to a constructor are not considered by overload
6430      resolution, and must be of the proper type.  */
6431   if (DECL_CONSTRUCTOR_P (fn))
6432     {
6433       if (first_arg != NULL_TREE)
6434         {
6435           argarray[j++] = first_arg;
6436           first_arg = NULL_TREE;
6437         }
6438       else
6439         {
6440           argarray[j++] = VEC_index (tree, args, arg_index);
6441           ++arg_index;
6442         }
6443       parm = TREE_CHAIN (parm);
6444       /* We should never try to call the abstract constructor.  */
6445       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
6446
6447       if (DECL_HAS_VTT_PARM_P (fn))
6448         {
6449           argarray[j++] = VEC_index (tree, args, arg_index);
6450           ++arg_index;
6451           parm = TREE_CHAIN (parm);
6452         }
6453     }
6454   /* Bypass access control for 'this' parameter.  */
6455   else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
6456     {
6457       tree parmtype = TREE_VALUE (parm);
6458       tree arg = (first_arg != NULL_TREE
6459                   ? first_arg
6460                   : VEC_index (tree, args, arg_index));
6461       tree argtype = TREE_TYPE (arg);
6462       tree converted_arg;
6463       tree base_binfo;
6464
6465       if (convs[i]->bad_p)
6466         {
6467           if (complain & tf_error)
6468             permerror (input_location, "passing %qT as %<this%> argument of %q#D discards qualifiers",
6469                        TREE_TYPE (argtype), fn);
6470           else
6471             return error_mark_node;
6472         }
6473
6474       /* See if the function member or the whole class type is declared
6475          final and the call can be devirtualized.  */
6476       if (DECL_FINAL_P (fn)
6477           || CLASSTYPE_FINAL (TYPE_METHOD_BASETYPE (TREE_TYPE (fn))))
6478         flags |= LOOKUP_NONVIRTUAL;
6479
6480       /* [class.mfct.nonstatic]: If a nonstatic member function of a class
6481          X is called for an object that is not of type X, or of a type
6482          derived from X, the behavior is undefined.
6483
6484          So we can assume that anything passed as 'this' is non-null, and
6485          optimize accordingly.  */
6486       gcc_assert (TREE_CODE (parmtype) == POINTER_TYPE);
6487       /* Convert to the base in which the function was declared.  */
6488       gcc_assert (cand->conversion_path != NULL_TREE);
6489       converted_arg = build_base_path (PLUS_EXPR,
6490                                        arg,
6491                                        cand->conversion_path,
6492                                        1, complain);
6493       /* Check that the base class is accessible.  */
6494       if (!accessible_base_p (TREE_TYPE (argtype),
6495                               BINFO_TYPE (cand->conversion_path), true))
6496         error ("%qT is not an accessible base of %qT",
6497                BINFO_TYPE (cand->conversion_path),
6498                TREE_TYPE (argtype));
6499       /* If fn was found by a using declaration, the conversion path
6500          will be to the derived class, not the base declaring fn. We
6501          must convert from derived to base.  */
6502       base_binfo = lookup_base (TREE_TYPE (TREE_TYPE (converted_arg)),
6503                                 TREE_TYPE (parmtype), ba_unique, NULL);
6504       converted_arg = build_base_path (PLUS_EXPR, converted_arg,
6505                                        base_binfo, 1, complain);
6506
6507       argarray[j++] = converted_arg;
6508       parm = TREE_CHAIN (parm);
6509       if (first_arg != NULL_TREE)
6510         first_arg = NULL_TREE;
6511       else
6512         ++arg_index;
6513       ++i;
6514       is_method = 1;
6515     }
6516
6517   gcc_assert (first_arg == NULL_TREE);
6518   for (; arg_index < VEC_length (tree, args) && parm;
6519        parm = TREE_CHAIN (parm), ++arg_index, ++i)
6520     {
6521       tree type = TREE_VALUE (parm);
6522       tree arg = VEC_index (tree, args, arg_index);
6523       bool conversion_warning = true;
6524
6525       conv = convs[i];
6526
6527       /* If the argument is NULL and used to (implicitly) instantiate a
6528          template function (and bind one of the template arguments to
6529          the type of 'long int'), we don't want to warn about passing NULL
6530          to non-pointer argument.
6531          For example, if we have this template function:
6532
6533            template<typename T> void func(T x) {}
6534
6535          we want to warn (when -Wconversion is enabled) in this case:
6536
6537            void foo() {
6538              func<int>(NULL);
6539            }
6540
6541          but not in this case:
6542
6543            void foo() {
6544              func(NULL);
6545            }
6546       */
6547       if (arg == null_node
6548           && DECL_TEMPLATE_INFO (fn)
6549           && cand->template_decl
6550           && !(flags & LOOKUP_EXPLICIT_TMPL_ARGS))
6551         conversion_warning = false;
6552
6553       /* Warn about initializer_list deduction that isn't currently in the
6554          working draft.  */
6555       if (cxx_dialect > cxx98
6556           && flag_deduce_init_list
6557           && cand->template_decl
6558           && is_std_init_list (non_reference (type))
6559           && BRACE_ENCLOSED_INITIALIZER_P (arg))
6560         {
6561           tree tmpl = TI_TEMPLATE (cand->template_decl);
6562           tree realparm = chain_index (j, DECL_ARGUMENTS (cand->fn));
6563           tree patparm = get_pattern_parm (realparm, tmpl);
6564           tree pattype = TREE_TYPE (patparm);
6565           if (PACK_EXPANSION_P (pattype))
6566             pattype = PACK_EXPANSION_PATTERN (pattype);
6567           pattype = non_reference (pattype);
6568
6569           if (TREE_CODE (pattype) == TEMPLATE_TYPE_PARM
6570               && (cand->explicit_targs == NULL_TREE
6571                   || (TREE_VEC_LENGTH (cand->explicit_targs)
6572                       <= TEMPLATE_TYPE_IDX (pattype))))
6573             {
6574               pedwarn (input_location, 0, "deducing %qT as %qT",
6575                        non_reference (TREE_TYPE (patparm)),
6576                        non_reference (type));
6577               pedwarn (input_location, 0, "  in call to %q+D", cand->fn);
6578               pedwarn (input_location, 0,
6579                        "  (you can disable this with -fno-deduce-init-list)");
6580             }
6581         }
6582
6583       val = convert_like_with_context (conv, arg, fn, i-is_method,
6584                                        conversion_warning
6585                                        ? complain
6586                                        : complain & (~tf_warning));
6587
6588       val = convert_for_arg_passing (type, val);
6589       if (val == error_mark_node)
6590         return error_mark_node;
6591       else
6592         argarray[j++] = val;
6593     }
6594
6595   /* Default arguments */
6596   for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
6597     {
6598       if (TREE_VALUE (parm) == error_mark_node)
6599         return error_mark_node;
6600       argarray[j++] = convert_default_arg (TREE_VALUE (parm),
6601                                            TREE_PURPOSE (parm),
6602                                            fn, i - is_method);
6603     }
6604
6605   /* Ellipsis */
6606   for (; arg_index < VEC_length (tree, args); ++arg_index)
6607     {
6608       tree a = VEC_index (tree, args, arg_index);
6609       if (magic_varargs_p (fn))
6610         /* Do no conversions for magic varargs.  */
6611         a = mark_type_use (a);
6612       else
6613         a = convert_arg_to_ellipsis (a);
6614       argarray[j++] = a;
6615     }
6616
6617   gcc_assert (j <= nargs);
6618   nargs = j;
6619
6620   check_function_arguments (TREE_TYPE (fn), nargs, argarray);
6621
6622   /* Avoid actually calling copy constructors and copy assignment operators,
6623      if possible.  */
6624
6625   if (! flag_elide_constructors)
6626     /* Do things the hard way.  */;
6627   else if (cand->num_convs == 1 
6628            && (DECL_COPY_CONSTRUCTOR_P (fn) 
6629                || DECL_MOVE_CONSTRUCTOR_P (fn)))
6630     {
6631       tree targ;
6632       tree arg = argarray[num_artificial_parms_for (fn)];
6633       tree fa;
6634       bool trivial = trivial_fn_p (fn);
6635
6636       /* Pull out the real argument, disregarding const-correctness.  */
6637       targ = arg;
6638       while (CONVERT_EXPR_P (targ)
6639              || TREE_CODE (targ) == NON_LVALUE_EXPR)
6640         targ = TREE_OPERAND (targ, 0);
6641       if (TREE_CODE (targ) == ADDR_EXPR)
6642         {
6643           targ = TREE_OPERAND (targ, 0);
6644           if (!same_type_ignoring_top_level_qualifiers_p
6645               (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
6646             targ = NULL_TREE;
6647         }
6648       else
6649         targ = NULL_TREE;
6650
6651       if (targ)
6652         arg = targ;
6653       else
6654         arg = cp_build_indirect_ref (arg, RO_NULL, complain);
6655
6656       /* [class.copy]: the copy constructor is implicitly defined even if
6657          the implementation elided its use.  */
6658       if (!trivial || DECL_DELETED_FN (fn))
6659         {
6660           mark_used (fn);
6661           already_used = true;
6662         }
6663
6664       /* If we're creating a temp and we already have one, don't create a
6665          new one.  If we're not creating a temp but we get one, use
6666          INIT_EXPR to collapse the temp into our target.  Otherwise, if the
6667          ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
6668          temp or an INIT_EXPR otherwise.  */
6669       fa = argarray[0];
6670       if (integer_zerop (fa))
6671         {
6672           if (TREE_CODE (arg) == TARGET_EXPR)
6673             return arg;
6674           else if (trivial)
6675             return force_target_expr (DECL_CONTEXT (fn), arg, complain);
6676         }
6677       else if (TREE_CODE (arg) == TARGET_EXPR || trivial)
6678         {
6679           tree to = stabilize_reference (cp_build_indirect_ref (fa, RO_NULL,
6680                                                                 complain));
6681
6682           val = build2 (INIT_EXPR, DECL_CONTEXT (fn), to, arg);
6683           return val;
6684         }
6685     }
6686   else if (DECL_OVERLOADED_OPERATOR_P (fn) == NOP_EXPR
6687            && trivial_fn_p (fn)
6688            && !DECL_DELETED_FN (fn))
6689     {
6690       tree to = stabilize_reference
6691         (cp_build_indirect_ref (argarray[0], RO_NULL, complain));
6692       tree type = TREE_TYPE (to);
6693       tree as_base = CLASSTYPE_AS_BASE (type);
6694       tree arg = argarray[1];
6695
6696       if (is_really_empty_class (type))
6697         {
6698           /* Avoid copying empty classes.  */
6699           val = build2 (COMPOUND_EXPR, void_type_node, to, arg);
6700           TREE_NO_WARNING (val) = 1;
6701           val = build2 (COMPOUND_EXPR, type, val, to);
6702           TREE_NO_WARNING (val) = 1;
6703         }
6704       else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
6705         {
6706           arg = cp_build_indirect_ref (arg, RO_NULL, complain);
6707           val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
6708         }
6709       else
6710         {
6711           /* We must only copy the non-tail padding parts.  */
6712           tree arg0, arg2, t;
6713           tree array_type, alias_set;
6714
6715           arg2 = TYPE_SIZE_UNIT (as_base);
6716           arg0 = cp_build_addr_expr (to, complain);
6717
6718           array_type = build_array_type (char_type_node,
6719                                          build_index_type
6720                                            (size_binop (MINUS_EXPR,
6721                                                         arg2, size_int (1))));
6722           alias_set = build_int_cst (build_pointer_type (type), 0);
6723           t = build2 (MODIFY_EXPR, void_type_node,
6724                       build2 (MEM_REF, array_type, arg0, alias_set),
6725                       build2 (MEM_REF, array_type, arg, alias_set));
6726           val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
6727           TREE_NO_WARNING (val) = 1;
6728         }
6729
6730       return val;
6731     }
6732   else if (DECL_DESTRUCTOR_P (fn)
6733            && trivial_fn_p (fn)
6734            && !DECL_DELETED_FN (fn))
6735     return fold_convert (void_type_node, argarray[0]);
6736   /* FIXME handle trivial default constructor, too.  */
6737
6738   if (!already_used)
6739     mark_used (fn);
6740
6741   if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
6742     {
6743       tree t;
6744       tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
6745                                 DECL_CONTEXT (fn),
6746                                 ba_any, NULL);
6747       gcc_assert (binfo && binfo != error_mark_node);
6748
6749       /* Warn about deprecated virtual functions now, since we're about
6750          to throw away the decl.  */
6751       if (TREE_DEPRECATED (fn))
6752         warn_deprecated_use (fn, NULL_TREE);
6753
6754       argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
6755                                      complain);
6756       if (TREE_SIDE_EFFECTS (argarray[0]))
6757         argarray[0] = save_expr (argarray[0]);
6758       t = build_pointer_type (TREE_TYPE (fn));
6759       if (DECL_CONTEXT (fn) && TYPE_JAVA_INTERFACE (DECL_CONTEXT (fn)))
6760         fn = build_java_interface_fn_ref (fn, argarray[0]);
6761       else
6762         fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
6763       TREE_TYPE (fn) = t;
6764     }
6765   else
6766     fn = build_addr_func (fn);
6767
6768   return build_cxx_call (fn, nargs, argarray);
6769 }
6770
6771 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
6772    This function performs no overload resolution, conversion, or other
6773    high-level operations.  */
6774
6775 tree
6776 build_cxx_call (tree fn, int nargs, tree *argarray)
6777 {
6778   tree fndecl;
6779
6780   /* Remember roughly where this call is.  */
6781   location_t loc = EXPR_LOC_OR_HERE (fn);
6782   fn = build_call_a (fn, nargs, argarray);
6783   SET_EXPR_LOCATION (fn, loc);
6784
6785   fndecl = get_callee_fndecl (fn);
6786
6787   /* Check that arguments to builtin functions match the expectations.  */
6788   if (fndecl
6789       && DECL_BUILT_IN (fndecl)
6790       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6791       && !check_builtin_function_arguments (fndecl, nargs, argarray))
6792     return error_mark_node;
6793
6794   /* Some built-in function calls will be evaluated at compile-time in
6795      fold ().  */
6796   fn = fold_if_not_in_template (fn);
6797
6798   if (VOID_TYPE_P (TREE_TYPE (fn)))
6799     return fn;
6800
6801   fn = require_complete_type (fn);
6802   if (fn == error_mark_node)
6803     return error_mark_node;
6804
6805   if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
6806     fn = build_cplus_new (TREE_TYPE (fn), fn, tf_warning_or_error);
6807   return convert_from_reference (fn);
6808 }
6809
6810 static GTY(()) tree java_iface_lookup_fn;
6811
6812 /* Make an expression which yields the address of the Java interface
6813    method FN.  This is achieved by generating a call to libjava's
6814    _Jv_LookupInterfaceMethodIdx().  */
6815
6816 static tree
6817 build_java_interface_fn_ref (tree fn, tree instance)
6818 {
6819   tree lookup_fn, method, idx;
6820   tree klass_ref, iface, iface_ref;
6821   int i;
6822
6823   if (!java_iface_lookup_fn)
6824     {
6825       tree ftype = build_function_type_list (ptr_type_node,
6826                                              ptr_type_node, ptr_type_node,
6827                                              java_int_type_node, NULL_TREE);
6828       java_iface_lookup_fn
6829         = add_builtin_function ("_Jv_LookupInterfaceMethodIdx", ftype,
6830                                 0, NOT_BUILT_IN, NULL, NULL_TREE);
6831     }
6832
6833   /* Look up the pointer to the runtime java.lang.Class object for `instance'.
6834      This is the first entry in the vtable.  */
6835   klass_ref = build_vtbl_ref (cp_build_indirect_ref (instance, RO_NULL, 
6836                                                      tf_warning_or_error),
6837                               integer_zero_node);
6838
6839   /* Get the java.lang.Class pointer for the interface being called.  */
6840   iface = DECL_CONTEXT (fn);
6841   iface_ref = lookup_field (iface, get_identifier ("class$"), 0, false);
6842   if (!iface_ref || TREE_CODE (iface_ref) != VAR_DECL
6843       || DECL_CONTEXT (iface_ref) != iface)
6844     {
6845       error ("could not find class$ field in java interface type %qT",
6846                 iface);
6847       return error_mark_node;
6848     }
6849   iface_ref = build_address (iface_ref);
6850   iface_ref = convert (build_pointer_type (iface), iface_ref);
6851
6852   /* Determine the itable index of FN.  */
6853   i = 1;
6854   for (method = TYPE_METHODS (iface); method; method = DECL_CHAIN (method))
6855     {
6856       if (!DECL_VIRTUAL_P (method))
6857         continue;
6858       if (fn == method)
6859         break;
6860       i++;
6861     }
6862   idx = build_int_cst (NULL_TREE, i);
6863
6864   lookup_fn = build1 (ADDR_EXPR,
6865                       build_pointer_type (TREE_TYPE (java_iface_lookup_fn)),
6866                       java_iface_lookup_fn);
6867   return build_call_nary (ptr_type_node, lookup_fn,
6868                           3, klass_ref, iface_ref, idx);
6869 }
6870
6871 /* Returns the value to use for the in-charge parameter when making a
6872    call to a function with the indicated NAME.
6873
6874    FIXME:Can't we find a neater way to do this mapping?  */
6875
6876 tree
6877 in_charge_arg_for_name (tree name)
6878 {
6879  if (name == base_ctor_identifier
6880       || name == base_dtor_identifier)
6881     return integer_zero_node;
6882   else if (name == complete_ctor_identifier)
6883     return integer_one_node;
6884   else if (name == complete_dtor_identifier)
6885     return integer_two_node;
6886   else if (name == deleting_dtor_identifier)
6887     return integer_three_node;
6888
6889   /* This function should only be called with one of the names listed
6890      above.  */
6891   gcc_unreachable ();
6892   return NULL_TREE;
6893 }
6894
6895 /* Build a call to a constructor, destructor, or an assignment
6896    operator for INSTANCE, an expression with class type.  NAME
6897    indicates the special member function to call; *ARGS are the
6898    arguments.  ARGS may be NULL.  This may change ARGS.  BINFO
6899    indicates the base of INSTANCE that is to be passed as the `this'
6900    parameter to the member function called.
6901
6902    FLAGS are the LOOKUP_* flags to use when processing the call.
6903
6904    If NAME indicates a complete object constructor, INSTANCE may be
6905    NULL_TREE.  In this case, the caller will call build_cplus_new to
6906    store the newly constructed object into a VAR_DECL.  */
6907
6908 tree
6909 build_special_member_call (tree instance, tree name, VEC(tree,gc) **args,
6910                            tree binfo, int flags, tsubst_flags_t complain)
6911 {
6912   tree fns;
6913   /* The type of the subobject to be constructed or destroyed.  */
6914   tree class_type;
6915   VEC(tree,gc) *allocated = NULL;
6916   tree ret;
6917
6918   gcc_assert (name == complete_ctor_identifier
6919               || name == base_ctor_identifier
6920               || name == complete_dtor_identifier
6921               || name == base_dtor_identifier
6922               || name == deleting_dtor_identifier
6923               || name == ansi_assopname (NOP_EXPR));
6924   if (TYPE_P (binfo))
6925     {
6926       /* Resolve the name.  */
6927       if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
6928         return error_mark_node;
6929
6930       binfo = TYPE_BINFO (binfo);
6931     }
6932
6933   gcc_assert (binfo != NULL_TREE);
6934
6935   class_type = BINFO_TYPE (binfo);
6936
6937   /* Handle the special case where INSTANCE is NULL_TREE.  */
6938   if (name == complete_ctor_identifier && !instance)
6939     {
6940       instance = build_int_cst (build_pointer_type (class_type), 0);
6941       instance = build1 (INDIRECT_REF, class_type, instance);
6942     }
6943   else
6944     {
6945       if (name == complete_dtor_identifier
6946           || name == base_dtor_identifier
6947           || name == deleting_dtor_identifier)
6948         gcc_assert (args == NULL || VEC_empty (tree, *args));
6949
6950       /* Convert to the base class, if necessary.  */
6951       if (!same_type_ignoring_top_level_qualifiers_p
6952           (TREE_TYPE (instance), BINFO_TYPE (binfo)))
6953         {
6954           if (name != ansi_assopname (NOP_EXPR))
6955             /* For constructors and destructors, either the base is
6956                non-virtual, or it is virtual but we are doing the
6957                conversion from a constructor or destructor for the
6958                complete object.  In either case, we can convert
6959                statically.  */
6960             instance = convert_to_base_statically (instance, binfo);
6961           else
6962             /* However, for assignment operators, we must convert
6963                dynamically if the base is virtual.  */
6964             instance = build_base_path (PLUS_EXPR, instance,
6965                                         binfo, /*nonnull=*/1, complain);
6966         }
6967     }
6968
6969   gcc_assert (instance != NULL_TREE);
6970
6971   fns = lookup_fnfields (binfo, name, 1);
6972
6973   /* When making a call to a constructor or destructor for a subobject
6974      that uses virtual base classes, pass down a pointer to a VTT for
6975      the subobject.  */
6976   if ((name == base_ctor_identifier
6977        || name == base_dtor_identifier)
6978       && CLASSTYPE_VBASECLASSES (class_type))
6979     {
6980       tree vtt;
6981       tree sub_vtt;
6982
6983       /* If the current function is a complete object constructor
6984          or destructor, then we fetch the VTT directly.
6985          Otherwise, we look it up using the VTT we were given.  */
6986       vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
6987       vtt = decay_conversion (vtt);
6988       vtt = build3 (COND_EXPR, TREE_TYPE (vtt),
6989                     build2 (EQ_EXPR, boolean_type_node,
6990                             current_in_charge_parm, integer_zero_node),
6991                     current_vtt_parm,
6992                     vtt);
6993       if (BINFO_SUBVTT_INDEX (binfo))
6994         sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
6995       else
6996         sub_vtt = vtt;
6997
6998       if (args == NULL)
6999         {
7000           allocated = make_tree_vector ();
7001           args = &allocated;
7002         }
7003
7004       VEC_safe_insert (tree, gc, *args, 0, sub_vtt);
7005     }
7006
7007   ret = build_new_method_call (instance, fns, args,
7008                                TYPE_BINFO (BINFO_TYPE (binfo)),
7009                                flags, /*fn=*/NULL,
7010                                complain);
7011
7012   if (allocated != NULL)
7013     release_tree_vector (allocated);
7014
7015   return ret;
7016 }
7017
7018 /* Return the NAME, as a C string.  The NAME indicates a function that
7019    is a member of TYPE.  *FREE_P is set to true if the caller must
7020    free the memory returned.
7021
7022    Rather than go through all of this, we should simply set the names
7023    of constructors and destructors appropriately, and dispense with
7024    ctor_identifier, dtor_identifier, etc.  */
7025
7026 static char *
7027 name_as_c_string (tree name, tree type, bool *free_p)
7028 {
7029   char *pretty_name;
7030
7031   /* Assume that we will not allocate memory.  */
7032   *free_p = false;
7033   /* Constructors and destructors are special.  */
7034   if (IDENTIFIER_CTOR_OR_DTOR_P (name))
7035     {
7036       pretty_name
7037         = CONST_CAST (char *, identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type))));
7038       /* For a destructor, add the '~'.  */
7039       if (name == complete_dtor_identifier
7040           || name == base_dtor_identifier
7041           || name == deleting_dtor_identifier)
7042         {
7043           pretty_name = concat ("~", pretty_name, NULL);
7044           /* Remember that we need to free the memory allocated.  */
7045           *free_p = true;
7046         }
7047     }
7048   else if (IDENTIFIER_TYPENAME_P (name))
7049     {
7050       pretty_name = concat ("operator ",
7051                             type_as_string_translate (TREE_TYPE (name),
7052                                                       TFF_PLAIN_IDENTIFIER),
7053                             NULL);
7054       /* Remember that we need to free the memory allocated.  */
7055       *free_p = true;
7056     }
7057   else
7058     pretty_name = CONST_CAST (char *, identifier_to_locale (IDENTIFIER_POINTER (name)));
7059
7060   return pretty_name;
7061 }
7062
7063 /* Build a call to "INSTANCE.FN (ARGS)".  If FN_P is non-NULL, it will
7064    be set, upon return, to the function called.  ARGS may be NULL.
7065    This may change ARGS.  */
7066
7067 static tree
7068 build_new_method_call_1 (tree instance, tree fns, VEC(tree,gc) **args,
7069                          tree conversion_path, int flags,
7070                          tree *fn_p, tsubst_flags_t complain)
7071 {
7072   struct z_candidate *candidates = 0, *cand;
7073   tree explicit_targs = NULL_TREE;
7074   tree basetype = NULL_TREE;
7075   tree access_binfo;
7076   tree optype;
7077   tree first_mem_arg = NULL_TREE;
7078   tree instance_ptr;
7079   tree name;
7080   bool skip_first_for_error;
7081   VEC(tree,gc) *user_args;
7082   tree call;
7083   tree fn;
7084   int template_only = 0;
7085   bool any_viable_p;
7086   tree orig_instance;
7087   tree orig_fns;
7088   VEC(tree,gc) *orig_args = NULL;
7089   void *p;
7090
7091   gcc_assert (instance != NULL_TREE);
7092
7093   /* We don't know what function we're going to call, yet.  */
7094   if (fn_p)
7095     *fn_p = NULL_TREE;
7096
7097   if (error_operand_p (instance)
7098       || !fns || error_operand_p (fns))
7099     return error_mark_node;
7100
7101   if (!BASELINK_P (fns))
7102     {
7103       if (complain & tf_error)
7104         error ("call to non-function %qD", fns);
7105       return error_mark_node;
7106     }
7107
7108   orig_instance = instance;
7109   orig_fns = fns;
7110
7111   /* Dismantle the baselink to collect all the information we need.  */
7112   if (!conversion_path)
7113     conversion_path = BASELINK_BINFO (fns);
7114   access_binfo = BASELINK_ACCESS_BINFO (fns);
7115   optype = BASELINK_OPTYPE (fns);
7116   fns = BASELINK_FUNCTIONS (fns);
7117   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
7118     {
7119       explicit_targs = TREE_OPERAND (fns, 1);
7120       fns = TREE_OPERAND (fns, 0);
7121       template_only = 1;
7122     }
7123   gcc_assert (TREE_CODE (fns) == FUNCTION_DECL
7124               || TREE_CODE (fns) == TEMPLATE_DECL
7125               || TREE_CODE (fns) == OVERLOAD);
7126   fn = get_first_fn (fns);
7127   name = DECL_NAME (fn);
7128
7129   basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
7130   gcc_assert (CLASS_TYPE_P (basetype));
7131
7132   if (processing_template_decl)
7133     {
7134       orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
7135       instance = build_non_dependent_expr (instance);
7136       if (args != NULL)
7137         make_args_non_dependent (*args);
7138     }
7139
7140   user_args = args == NULL ? NULL : *args;
7141   /* Under DR 147 A::A() is an invalid constructor call,
7142      not a functional cast.  */
7143   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
7144     {
7145       if (! (complain & tf_error))
7146         return error_mark_node;
7147
7148       permerror (input_location,
7149                  "cannot call constructor %<%T::%D%> directly",
7150                  basetype, name);
7151       permerror (input_location, "  for a function-style cast, remove the "
7152                  "redundant %<::%D%>", name);
7153       call = build_functional_cast (basetype, build_tree_list_vec (user_args),
7154                                     complain);
7155       return call;
7156     }
7157
7158   /* Figure out whether to skip the first argument for the error
7159      message we will display to users if an error occurs.  We don't
7160      want to display any compiler-generated arguments.  The "this"
7161      pointer hasn't been added yet.  However, we must remove the VTT
7162      pointer if this is a call to a base-class constructor or
7163      destructor.  */
7164   skip_first_for_error = false;
7165   if (IDENTIFIER_CTOR_OR_DTOR_P (name))
7166     {
7167       /* Callers should explicitly indicate whether they want to construct
7168          the complete object or just the part without virtual bases.  */
7169       gcc_assert (name != ctor_identifier);
7170       /* Similarly for destructors.  */
7171       gcc_assert (name != dtor_identifier);
7172       /* Remove the VTT pointer, if present.  */
7173       if ((name == base_ctor_identifier || name == base_dtor_identifier)
7174           && CLASSTYPE_VBASECLASSES (basetype))
7175         skip_first_for_error = true;
7176     }
7177
7178   /* Process the argument list.  */
7179   if (args != NULL && *args != NULL)
7180     {
7181       *args = resolve_args (*args, complain);
7182       if (*args == NULL)
7183         return error_mark_node;
7184     }
7185
7186   instance_ptr = build_this (instance);
7187
7188   /* It's OK to call destructors and constructors on cv-qualified objects.
7189      Therefore, convert the INSTANCE_PTR to the unqualified type, if
7190      necessary.  */
7191   if (DECL_DESTRUCTOR_P (fn)
7192       || DECL_CONSTRUCTOR_P (fn))
7193     {
7194       tree type = build_pointer_type (basetype);
7195       if (!same_type_p (type, TREE_TYPE (instance_ptr)))
7196         instance_ptr = build_nop (type, instance_ptr);
7197     }
7198   if (DECL_DESTRUCTOR_P (fn))
7199     name = complete_dtor_identifier;
7200
7201   first_mem_arg = instance_ptr;
7202
7203   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7204   p = conversion_obstack_alloc (0);
7205
7206   /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
7207      initializer, not T({ }).  */
7208   if (DECL_CONSTRUCTOR_P (fn) && args != NULL && !VEC_empty (tree, *args)
7209       && BRACE_ENCLOSED_INITIALIZER_P (VEC_index (tree, *args, 0))
7210       && CONSTRUCTOR_IS_DIRECT_INIT (VEC_index (tree, *args, 0)))
7211     {
7212       tree init_list = VEC_index (tree, *args, 0);
7213       tree init = NULL_TREE;
7214
7215       gcc_assert (VEC_length (tree, *args) == 1
7216                   && !(flags & LOOKUP_ONLYCONVERTING));
7217
7218       /* If the initializer list has no elements and T is a class type with
7219          a default constructor, the object is value-initialized.  Handle
7220          this here so we don't need to handle it wherever we use
7221          build_special_member_call.  */
7222       if (CONSTRUCTOR_NELTS (init_list) == 0
7223           && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
7224           /* For a user-provided default constructor, use the normal
7225              mechanisms so that protected access works.  */
7226           && !type_has_user_provided_default_constructor (basetype)
7227           && !processing_template_decl)
7228         init = build_value_init (basetype, complain);
7229
7230       /* If BASETYPE is an aggregate, we need to do aggregate
7231          initialization.  */
7232       else if (CP_AGGREGATE_TYPE_P (basetype))
7233         init = digest_init (basetype, init_list, complain);
7234
7235       if (init)
7236         {
7237           tree ob;
7238           if (integer_zerop (instance_ptr))
7239             return get_target_expr_sfinae (init, complain);
7240           ob = build_fold_indirect_ref (instance_ptr);
7241           init = build2 (INIT_EXPR, TREE_TYPE (ob), ob, init);
7242           TREE_SIDE_EFFECTS (init) = true;
7243           return init;
7244         }
7245
7246       /* Otherwise go ahead with overload resolution.  */
7247       add_list_candidates (fns, first_mem_arg, init_list,
7248                            basetype, explicit_targs, template_only,
7249                            conversion_path, access_binfo, flags, &candidates);
7250     }
7251   else
7252     {
7253       add_candidates (fns, first_mem_arg, user_args, optype,
7254                       explicit_targs, template_only, conversion_path,
7255                       access_binfo, flags, &candidates);
7256     }
7257   any_viable_p = false;
7258   candidates = splice_viable (candidates, pedantic, &any_viable_p);
7259
7260   if (!any_viable_p)
7261     {
7262       if (complain & tf_error)
7263         {
7264           if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
7265             cxx_incomplete_type_error (instance_ptr, basetype);
7266           else if (optype)
7267             error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
7268                    basetype, optype, build_tree_list_vec (user_args),
7269                    TREE_TYPE (TREE_TYPE (instance_ptr)));
7270           else
7271             {
7272               char *pretty_name;
7273               bool free_p;
7274               tree arglist;
7275
7276               pretty_name = name_as_c_string (name, basetype, &free_p);
7277               arglist = build_tree_list_vec (user_args);
7278               if (skip_first_for_error)
7279                 arglist = TREE_CHAIN (arglist);
7280               error ("no matching function for call to %<%T::%s(%A)%#V%>",
7281                      basetype, pretty_name, arglist,
7282                      TREE_TYPE (TREE_TYPE (instance_ptr)));
7283               if (free_p)
7284                 free (pretty_name);
7285             }
7286           print_z_candidates (location_of (name), candidates);
7287         }
7288       call = error_mark_node;
7289     }
7290   else
7291     {
7292       cand = tourney (candidates);
7293       if (cand == 0)
7294         {
7295           char *pretty_name;
7296           bool free_p;
7297           tree arglist;
7298
7299           if (complain & tf_error)
7300             {
7301               pretty_name = name_as_c_string (name, basetype, &free_p);
7302               arglist = build_tree_list_vec (user_args);
7303               if (skip_first_for_error)
7304                 arglist = TREE_CHAIN (arglist);
7305               error ("call of overloaded %<%s(%A)%> is ambiguous", pretty_name,
7306                      arglist);
7307               print_z_candidates (location_of (name), candidates);
7308               if (free_p)
7309                 free (pretty_name);
7310             }
7311           call = error_mark_node;
7312         }
7313       else
7314         {
7315           fn = cand->fn;
7316
7317           if (!(flags & LOOKUP_NONVIRTUAL)
7318               && DECL_PURE_VIRTUAL_P (fn)
7319               && instance == current_class_ref
7320               && (DECL_CONSTRUCTOR_P (current_function_decl)
7321                   || DECL_DESTRUCTOR_P (current_function_decl))
7322               && (complain & tf_warning))
7323             /* This is not an error, it is runtime undefined
7324                behavior.  */
7325             warning (0, (DECL_CONSTRUCTOR_P (current_function_decl) ?
7326                       "pure virtual %q#D called from constructor"
7327                       : "pure virtual %q#D called from destructor"),
7328                      fn);
7329
7330           if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
7331               && is_dummy_object (instance_ptr))
7332             {
7333               if (complain & tf_error)
7334                 error ("cannot call member function %qD without object",
7335                        fn);
7336               call = error_mark_node;
7337             }
7338           else
7339             {
7340               /* Optimize away vtable lookup if we know that this function
7341                  can't be overridden.  */
7342               if (DECL_VINDEX (fn) && ! (flags & LOOKUP_NONVIRTUAL)
7343                   && resolves_to_fixed_type_p (instance, 0))
7344                 flags |= LOOKUP_NONVIRTUAL;
7345               if (explicit_targs)
7346                 flags |= LOOKUP_EXPLICIT_TMPL_ARGS;
7347               /* Now we know what function is being called.  */
7348               if (fn_p)
7349                 *fn_p = fn;
7350               /* Build the actual CALL_EXPR.  */
7351               call = build_over_call (cand, flags, complain);
7352               /* In an expression of the form `a->f()' where `f' turns
7353                  out to be a static member function, `a' is
7354                  none-the-less evaluated.  */
7355               if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
7356                   && !is_dummy_object (instance_ptr)
7357                   && TREE_SIDE_EFFECTS (instance_ptr))
7358                 call = build2 (COMPOUND_EXPR, TREE_TYPE (call),
7359                                instance_ptr, call);
7360               else if (call != error_mark_node
7361                        && DECL_DESTRUCTOR_P (cand->fn)
7362                        && !VOID_TYPE_P (TREE_TYPE (call)))
7363                 /* An explicit call of the form "x->~X()" has type
7364                    "void".  However, on platforms where destructors
7365                    return "this" (i.e., those where
7366                    targetm.cxx.cdtor_returns_this is true), such calls
7367                    will appear to have a return value of pointer type
7368                    to the low-level call machinery.  We do not want to
7369                    change the low-level machinery, since we want to be
7370                    able to optimize "delete f()" on such platforms as
7371                    "operator delete(~X(f()))" (rather than generating
7372                    "t = f(), ~X(t), operator delete (t)").  */
7373                 call = build_nop (void_type_node, call);
7374             }
7375         }
7376     }
7377
7378   if (processing_template_decl && call != error_mark_node)
7379     {
7380       bool cast_to_void = false;
7381
7382       if (TREE_CODE (call) == COMPOUND_EXPR)
7383         call = TREE_OPERAND (call, 1);
7384       else if (TREE_CODE (call) == NOP_EXPR)
7385         {
7386           cast_to_void = true;
7387           call = TREE_OPERAND (call, 0);
7388         }
7389       if (TREE_CODE (call) == INDIRECT_REF)
7390         call = TREE_OPERAND (call, 0);
7391       call = (build_min_non_dep_call_vec
7392               (call,
7393                build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
7394                           orig_instance, orig_fns, NULL_TREE),
7395                orig_args));
7396       call = convert_from_reference (call);
7397       if (cast_to_void)
7398         call = build_nop (void_type_node, call);
7399     }
7400
7401  /* Free all the conversions we allocated.  */
7402   obstack_free (&conversion_obstack, p);
7403
7404   if (orig_args != NULL)
7405     release_tree_vector (orig_args);
7406
7407   return call;
7408 }
7409
7410 /* Wrapper for above.  */
7411
7412 tree
7413 build_new_method_call (tree instance, tree fns, VEC(tree,gc) **args,
7414                        tree conversion_path, int flags,
7415                        tree *fn_p, tsubst_flags_t complain)
7416 {
7417   tree ret;
7418   bool subtime = timevar_cond_start (TV_OVERLOAD);
7419   ret = build_new_method_call_1 (instance, fns, args, conversion_path, flags,
7420                                  fn_p, complain);
7421   timevar_cond_stop (TV_OVERLOAD, subtime);
7422   return ret;
7423 }
7424
7425 /* Returns true iff standard conversion sequence ICS1 is a proper
7426    subsequence of ICS2.  */
7427
7428 static bool
7429 is_subseq (conversion *ics1, conversion *ics2)
7430 {
7431   /* We can assume that a conversion of the same code
7432      between the same types indicates a subsequence since we only get
7433      here if the types we are converting from are the same.  */
7434
7435   while (ics1->kind == ck_rvalue
7436          || ics1->kind == ck_lvalue)
7437     ics1 = ics1->u.next;
7438
7439   while (1)
7440     {
7441       while (ics2->kind == ck_rvalue
7442              || ics2->kind == ck_lvalue)
7443         ics2 = ics2->u.next;
7444
7445       if (ics2->kind == ck_user
7446           || ics2->kind == ck_ambig
7447           || ics2->kind == ck_aggr
7448           || ics2->kind == ck_list
7449           || ics2->kind == ck_identity)
7450         /* At this point, ICS1 cannot be a proper subsequence of
7451            ICS2.  We can get a USER_CONV when we are comparing the
7452            second standard conversion sequence of two user conversion
7453            sequences.  */
7454         return false;
7455
7456       ics2 = ics2->u.next;
7457
7458       if (ics2->kind == ics1->kind
7459           && same_type_p (ics2->type, ics1->type)
7460           && same_type_p (ics2->u.next->type,
7461                           ics1->u.next->type))
7462         return true;
7463     }
7464 }
7465
7466 /* Returns nonzero iff DERIVED is derived from BASE.  The inputs may
7467    be any _TYPE nodes.  */
7468
7469 bool
7470 is_properly_derived_from (tree derived, tree base)
7471 {
7472   if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
7473     return false;
7474
7475   /* We only allow proper derivation here.  The DERIVED_FROM_P macro
7476      considers every class derived from itself.  */
7477   return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
7478           && DERIVED_FROM_P (base, derived));
7479 }
7480
7481 /* We build the ICS for an implicit object parameter as a pointer
7482    conversion sequence.  However, such a sequence should be compared
7483    as if it were a reference conversion sequence.  If ICS is the
7484    implicit conversion sequence for an implicit object parameter,
7485    modify it accordingly.  */
7486
7487 static void
7488 maybe_handle_implicit_object (conversion **ics)
7489 {
7490   if ((*ics)->this_p)
7491     {
7492       /* [over.match.funcs]
7493
7494          For non-static member functions, the type of the
7495          implicit object parameter is "reference to cv X"
7496          where X is the class of which the function is a
7497          member and cv is the cv-qualification on the member
7498          function declaration.  */
7499       conversion *t = *ics;
7500       tree reference_type;
7501
7502       /* The `this' parameter is a pointer to a class type.  Make the
7503          implicit conversion talk about a reference to that same class
7504          type.  */
7505       reference_type = TREE_TYPE (t->type);
7506       reference_type = build_reference_type (reference_type);
7507
7508       if (t->kind == ck_qual)
7509         t = t->u.next;
7510       if (t->kind == ck_ptr)
7511         t = t->u.next;
7512       t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
7513       t = direct_reference_binding (reference_type, t);
7514       t->this_p = 1;
7515       t->rvaluedness_matches_p = 0;
7516       *ics = t;
7517     }
7518 }
7519
7520 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
7521    and return the initial reference binding conversion. Otherwise,
7522    leave *ICS unchanged and return NULL.  */
7523
7524 static conversion *
7525 maybe_handle_ref_bind (conversion **ics)
7526 {
7527   if ((*ics)->kind == ck_ref_bind)
7528     {
7529       conversion *old_ics = *ics;
7530       *ics = old_ics->u.next;
7531       (*ics)->user_conv_p = old_ics->user_conv_p;
7532       return old_ics;
7533     }
7534
7535   return NULL;
7536 }
7537
7538 /* Compare two implicit conversion sequences according to the rules set out in
7539    [over.ics.rank].  Return values:
7540
7541       1: ics1 is better than ics2
7542      -1: ics2 is better than ics1
7543       0: ics1 and ics2 are indistinguishable */
7544
7545 static int
7546 compare_ics (conversion *ics1, conversion *ics2)
7547 {
7548   tree from_type1;
7549   tree from_type2;
7550   tree to_type1;
7551   tree to_type2;
7552   tree deref_from_type1 = NULL_TREE;
7553   tree deref_from_type2 = NULL_TREE;
7554   tree deref_to_type1 = NULL_TREE;
7555   tree deref_to_type2 = NULL_TREE;
7556   conversion_rank rank1, rank2;
7557
7558   /* REF_BINDING is nonzero if the result of the conversion sequence
7559      is a reference type.   In that case REF_CONV is the reference
7560      binding conversion. */
7561   conversion *ref_conv1;
7562   conversion *ref_conv2;
7563
7564   /* Handle implicit object parameters.  */
7565   maybe_handle_implicit_object (&ics1);
7566   maybe_handle_implicit_object (&ics2);
7567
7568   /* Handle reference parameters.  */
7569   ref_conv1 = maybe_handle_ref_bind (&ics1);
7570   ref_conv2 = maybe_handle_ref_bind (&ics2);
7571
7572   /* List-initialization sequence L1 is a better conversion sequence than
7573      list-initialization sequence L2 if L1 converts to
7574      std::initializer_list<X> for some X and L2 does not.  */
7575   if (ics1->kind == ck_list && ics2->kind != ck_list)
7576     return 1;
7577   if (ics2->kind == ck_list && ics1->kind != ck_list)
7578     return -1;
7579
7580   /* [over.ics.rank]
7581
7582      When  comparing  the  basic forms of implicit conversion sequences (as
7583      defined in _over.best.ics_)
7584
7585      --a standard conversion sequence (_over.ics.scs_) is a better
7586        conversion sequence than a user-defined conversion sequence
7587        or an ellipsis conversion sequence, and
7588
7589      --a user-defined conversion sequence (_over.ics.user_) is a
7590        better conversion sequence than an ellipsis conversion sequence
7591        (_over.ics.ellipsis_).  */
7592   rank1 = CONVERSION_RANK (ics1);
7593   rank2 = CONVERSION_RANK (ics2);
7594
7595   if (rank1 > rank2)
7596     return -1;
7597   else if (rank1 < rank2)
7598     return 1;
7599
7600   if (rank1 == cr_bad)
7601     {
7602       /* Both ICS are bad.  We try to make a decision based on what would
7603          have happened if they'd been good.  This is not an extension,
7604          we'll still give an error when we build up the call; this just
7605          helps us give a more helpful error message.  */
7606       rank1 = BAD_CONVERSION_RANK (ics1);
7607       rank2 = BAD_CONVERSION_RANK (ics2);
7608
7609       if (rank1 > rank2)
7610         return -1;
7611       else if (rank1 < rank2)
7612         return 1;
7613
7614       /* We couldn't make up our minds; try to figure it out below.  */
7615     }
7616
7617   if (ics1->ellipsis_p)
7618     /* Both conversions are ellipsis conversions.  */
7619     return 0;
7620
7621   /* User-defined  conversion sequence U1 is a better conversion sequence
7622      than another user-defined conversion sequence U2 if they contain the
7623      same user-defined conversion operator or constructor and if the sec-
7624      ond standard conversion sequence of U1 is  better  than  the  second
7625      standard conversion sequence of U2.  */
7626
7627   /* Handle list-conversion with the same code even though it isn't always
7628      ranked as a user-defined conversion and it doesn't have a second
7629      standard conversion sequence; it will still have the desired effect.
7630      Specifically, we need to do the reference binding comparison at the
7631      end of this function.  */
7632
7633   if (ics1->user_conv_p || ics1->kind == ck_list || ics1->kind == ck_aggr)
7634     {
7635       conversion *t1;
7636       conversion *t2;
7637
7638       for (t1 = ics1; t1->kind != ck_user; t1 = t1->u.next)
7639         if (t1->kind == ck_ambig || t1->kind == ck_aggr
7640             || t1->kind == ck_list)
7641           break;
7642       for (t2 = ics2; t2->kind != ck_user; t2 = t2->u.next)
7643         if (t2->kind == ck_ambig || t2->kind == ck_aggr
7644             || t2->kind == ck_list)
7645           break;
7646
7647       if (t1->kind != t2->kind)
7648         return 0;
7649       else if (t1->kind == ck_user)
7650         {
7651           if (t1->cand->fn != t2->cand->fn)
7652             return 0;
7653         }
7654       else
7655         {
7656           /* For ambiguous or aggregate conversions, use the target type as
7657              a proxy for the conversion function.  */
7658           if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
7659             return 0;
7660         }
7661
7662       /* We can just fall through here, after setting up
7663          FROM_TYPE1 and FROM_TYPE2.  */
7664       from_type1 = t1->type;
7665       from_type2 = t2->type;
7666     }
7667   else
7668     {
7669       conversion *t1;
7670       conversion *t2;
7671
7672       /* We're dealing with two standard conversion sequences.
7673
7674          [over.ics.rank]
7675
7676          Standard conversion sequence S1 is a better conversion
7677          sequence than standard conversion sequence S2 if
7678
7679          --S1 is a proper subsequence of S2 (comparing the conversion
7680            sequences in the canonical form defined by _over.ics.scs_,
7681            excluding any Lvalue Transformation; the identity
7682            conversion sequence is considered to be a subsequence of
7683            any non-identity conversion sequence */
7684
7685       t1 = ics1;
7686       while (t1->kind != ck_identity)
7687         t1 = t1->u.next;
7688       from_type1 = t1->type;
7689
7690       t2 = ics2;
7691       while (t2->kind != ck_identity)
7692         t2 = t2->u.next;
7693       from_type2 = t2->type;
7694     }
7695
7696   /* One sequence can only be a subsequence of the other if they start with
7697      the same type.  They can start with different types when comparing the
7698      second standard conversion sequence in two user-defined conversion
7699      sequences.  */
7700   if (same_type_p (from_type1, from_type2))
7701     {
7702       if (is_subseq (ics1, ics2))
7703         return 1;
7704       if (is_subseq (ics2, ics1))
7705         return -1;
7706     }
7707
7708   /* [over.ics.rank]
7709
7710      Or, if not that,
7711
7712      --the rank of S1 is better than the rank of S2 (by the rules
7713        defined below):
7714
7715     Standard conversion sequences are ordered by their ranks: an Exact
7716     Match is a better conversion than a Promotion, which is a better
7717     conversion than a Conversion.
7718
7719     Two conversion sequences with the same rank are indistinguishable
7720     unless one of the following rules applies:
7721
7722     --A conversion that does not a convert a pointer, pointer to member,
7723       or std::nullptr_t to bool is better than one that does.
7724
7725     The ICS_STD_RANK automatically handles the pointer-to-bool rule,
7726     so that we do not have to check it explicitly.  */
7727   if (ics1->rank < ics2->rank)
7728     return 1;
7729   else if (ics2->rank < ics1->rank)
7730     return -1;
7731
7732   to_type1 = ics1->type;
7733   to_type2 = ics2->type;
7734
7735   /* A conversion from scalar arithmetic type to complex is worse than a
7736      conversion between scalar arithmetic types.  */
7737   if (same_type_p (from_type1, from_type2)
7738       && ARITHMETIC_TYPE_P (from_type1)
7739       && ARITHMETIC_TYPE_P (to_type1)
7740       && ARITHMETIC_TYPE_P (to_type2)
7741       && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
7742           != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
7743     {
7744       if (TREE_CODE (to_type1) == COMPLEX_TYPE)
7745         return -1;
7746       else
7747         return 1;
7748     }
7749
7750   if (TYPE_PTR_P (from_type1)
7751       && TYPE_PTR_P (from_type2)
7752       && TYPE_PTR_P (to_type1)
7753       && TYPE_PTR_P (to_type2))
7754     {
7755       deref_from_type1 = TREE_TYPE (from_type1);
7756       deref_from_type2 = TREE_TYPE (from_type2);
7757       deref_to_type1 = TREE_TYPE (to_type1);
7758       deref_to_type2 = TREE_TYPE (to_type2);
7759     }
7760   /* The rules for pointers to members A::* are just like the rules
7761      for pointers A*, except opposite: if B is derived from A then
7762      A::* converts to B::*, not vice versa.  For that reason, we
7763      switch the from_ and to_ variables here.  */
7764   else if ((TYPE_PTRMEM_P (from_type1) && TYPE_PTRMEM_P (from_type2)
7765             && TYPE_PTRMEM_P (to_type1) && TYPE_PTRMEM_P (to_type2))
7766            || (TYPE_PTRMEMFUNC_P (from_type1)
7767                && TYPE_PTRMEMFUNC_P (from_type2)
7768                && TYPE_PTRMEMFUNC_P (to_type1)
7769                && TYPE_PTRMEMFUNC_P (to_type2)))
7770     {
7771       deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
7772       deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
7773       deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
7774       deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
7775     }
7776
7777   if (deref_from_type1 != NULL_TREE
7778       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
7779       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
7780     {
7781       /* This was one of the pointer or pointer-like conversions.
7782
7783          [over.ics.rank]
7784
7785          --If class B is derived directly or indirectly from class A,
7786            conversion of B* to A* is better than conversion of B* to
7787            void*, and conversion of A* to void* is better than
7788            conversion of B* to void*.  */
7789       if (TREE_CODE (deref_to_type1) == VOID_TYPE
7790           && TREE_CODE (deref_to_type2) == VOID_TYPE)
7791         {
7792           if (is_properly_derived_from (deref_from_type1,
7793                                         deref_from_type2))
7794             return -1;
7795           else if (is_properly_derived_from (deref_from_type2,
7796                                              deref_from_type1))
7797             return 1;
7798         }
7799       else if (TREE_CODE (deref_to_type1) == VOID_TYPE
7800                || TREE_CODE (deref_to_type2) == VOID_TYPE)
7801         {
7802           if (same_type_p (deref_from_type1, deref_from_type2))
7803             {
7804               if (TREE_CODE (deref_to_type2) == VOID_TYPE)
7805                 {
7806                   if (is_properly_derived_from (deref_from_type1,
7807                                                 deref_to_type1))
7808                     return 1;
7809                 }
7810               /* We know that DEREF_TO_TYPE1 is `void' here.  */
7811               else if (is_properly_derived_from (deref_from_type1,
7812                                                  deref_to_type2))
7813                 return -1;
7814             }
7815         }
7816       else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
7817                && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
7818         {
7819           /* [over.ics.rank]
7820
7821              --If class B is derived directly or indirectly from class A
7822                and class C is derived directly or indirectly from B,
7823
7824              --conversion of C* to B* is better than conversion of C* to
7825                A*,
7826
7827              --conversion of B* to A* is better than conversion of C* to
7828                A*  */
7829           if (same_type_p (deref_from_type1, deref_from_type2))
7830             {
7831               if (is_properly_derived_from (deref_to_type1,
7832                                             deref_to_type2))
7833                 return 1;
7834               else if (is_properly_derived_from (deref_to_type2,
7835                                                  deref_to_type1))
7836                 return -1;
7837             }
7838           else if (same_type_p (deref_to_type1, deref_to_type2))
7839             {
7840               if (is_properly_derived_from (deref_from_type2,
7841                                             deref_from_type1))
7842                 return 1;
7843               else if (is_properly_derived_from (deref_from_type1,
7844                                                  deref_from_type2))
7845                 return -1;
7846             }
7847         }
7848     }
7849   else if (CLASS_TYPE_P (non_reference (from_type1))
7850            && same_type_p (from_type1, from_type2))
7851     {
7852       tree from = non_reference (from_type1);
7853
7854       /* [over.ics.rank]
7855
7856          --binding of an expression of type C to a reference of type
7857            B& is better than binding an expression of type C to a
7858            reference of type A&
7859
7860          --conversion of C to B is better than conversion of C to A,  */
7861       if (is_properly_derived_from (from, to_type1)
7862           && is_properly_derived_from (from, to_type2))
7863         {
7864           if (is_properly_derived_from (to_type1, to_type2))
7865             return 1;
7866           else if (is_properly_derived_from (to_type2, to_type1))
7867             return -1;
7868         }
7869     }
7870   else if (CLASS_TYPE_P (non_reference (to_type1))
7871            && same_type_p (to_type1, to_type2))
7872     {
7873       tree to = non_reference (to_type1);
7874
7875       /* [over.ics.rank]
7876
7877          --binding of an expression of type B to a reference of type
7878            A& is better than binding an expression of type C to a
7879            reference of type A&,
7880
7881          --conversion of B to A is better than conversion of C to A  */
7882       if (is_properly_derived_from (from_type1, to)
7883           && is_properly_derived_from (from_type2, to))
7884         {
7885           if (is_properly_derived_from (from_type2, from_type1))
7886             return 1;
7887           else if (is_properly_derived_from (from_type1, from_type2))
7888             return -1;
7889         }
7890     }
7891
7892   /* [over.ics.rank]
7893
7894      --S1 and S2 differ only in their qualification conversion and  yield
7895        similar  types  T1 and T2 (_conv.qual_), respectively, and the cv-
7896        qualification signature of type T1 is a proper subset of  the  cv-
7897        qualification signature of type T2  */
7898   if (ics1->kind == ck_qual
7899       && ics2->kind == ck_qual
7900       && same_type_p (from_type1, from_type2))
7901     {
7902       int result = comp_cv_qual_signature (to_type1, to_type2);
7903       if (result != 0)
7904         return result;
7905     }
7906
7907   /* [over.ics.rank]
7908
7909      --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
7910      to an implicit object parameter, and either S1 binds an lvalue reference
7911      to an lvalue and S2 binds an rvalue reference or S1 binds an rvalue
7912      reference to an rvalue and S2 binds an lvalue reference
7913      (C++0x draft standard, 13.3.3.2)
7914
7915      --S1 and S2 are reference bindings (_dcl.init.ref_), and the
7916      types to which the references refer are the same type except for
7917      top-level cv-qualifiers, and the type to which the reference
7918      initialized by S2 refers is more cv-qualified than the type to
7919      which the reference initialized by S1 refers.
7920
7921      DR 1328 [over.match.best]: the context is an initialization by
7922      conversion function for direct reference binding (13.3.1.6) of a
7923      reference to function type, the return type of F1 is the same kind of
7924      reference (i.e. lvalue or rvalue) as the reference being initialized,
7925      and the return type of F2 is not.  */
7926
7927   if (ref_conv1 && ref_conv2)
7928     {
7929       if (!ref_conv1->this_p && !ref_conv2->this_p
7930           && (ref_conv1->rvaluedness_matches_p
7931               != ref_conv2->rvaluedness_matches_p)
7932           && (same_type_p (ref_conv1->type, ref_conv2->type)
7933               || (TYPE_REF_IS_RVALUE (ref_conv1->type)
7934                   != TYPE_REF_IS_RVALUE (ref_conv2->type))))
7935         {
7936           return (ref_conv1->rvaluedness_matches_p
7937                   - ref_conv2->rvaluedness_matches_p);
7938         }
7939
7940       if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
7941         return comp_cv_qualification (TREE_TYPE (ref_conv2->type),
7942                                       TREE_TYPE (ref_conv1->type));
7943     }
7944
7945   /* Neither conversion sequence is better than the other.  */
7946   return 0;
7947 }
7948
7949 /* The source type for this standard conversion sequence.  */
7950
7951 static tree
7952 source_type (conversion *t)
7953 {
7954   for (;; t = t->u.next)
7955     {
7956       if (t->kind == ck_user
7957           || t->kind == ck_ambig
7958           || t->kind == ck_identity)
7959         return t->type;
7960     }
7961   gcc_unreachable ();
7962 }
7963
7964 /* Note a warning about preferring WINNER to LOSER.  We do this by storing
7965    a pointer to LOSER and re-running joust to produce the warning if WINNER
7966    is actually used.  */
7967
7968 static void
7969 add_warning (struct z_candidate *winner, struct z_candidate *loser)
7970 {
7971   candidate_warning *cw = (candidate_warning *)
7972     conversion_obstack_alloc (sizeof (candidate_warning));
7973   cw->loser = loser;
7974   cw->next = winner->warnings;
7975   winner->warnings = cw;
7976 }
7977
7978 /* Compare two candidates for overloading as described in
7979    [over.match.best].  Return values:
7980
7981       1: cand1 is better than cand2
7982      -1: cand2 is better than cand1
7983       0: cand1 and cand2 are indistinguishable */
7984
7985 static int
7986 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn)
7987 {
7988   int winner = 0;
7989   int off1 = 0, off2 = 0;
7990   size_t i;
7991   size_t len;
7992
7993   /* Candidates that involve bad conversions are always worse than those
7994      that don't.  */
7995   if (cand1->viable > cand2->viable)
7996     return 1;
7997   if (cand1->viable < cand2->viable)
7998     return -1;
7999
8000   /* If we have two pseudo-candidates for conversions to the same type,
8001      or two candidates for the same function, arbitrarily pick one.  */
8002   if (cand1->fn == cand2->fn
8003       && (IS_TYPE_OR_DECL_P (cand1->fn)))
8004     return 1;
8005
8006   /* a viable function F1
8007      is defined to be a better function than another viable function F2  if
8008      for  all arguments i, ICSi(F1) is not a worse conversion sequence than
8009      ICSi(F2), and then */
8010
8011   /* for some argument j, ICSj(F1) is a better conversion  sequence  than
8012      ICSj(F2) */
8013
8014   /* For comparing static and non-static member functions, we ignore
8015      the implicit object parameter of the non-static function.  The
8016      standard says to pretend that the static function has an object
8017      parm, but that won't work with operator overloading.  */
8018   len = cand1->num_convs;
8019   if (len != cand2->num_convs)
8020     {
8021       int static_1 = DECL_STATIC_FUNCTION_P (cand1->fn);
8022       int static_2 = DECL_STATIC_FUNCTION_P (cand2->fn);
8023
8024       if (DECL_CONSTRUCTOR_P (cand1->fn)
8025           && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
8026         /* We're comparing a near-match list constructor and a near-match
8027            non-list constructor.  Just treat them as unordered.  */
8028         return 0;
8029
8030       gcc_assert (static_1 != static_2);
8031
8032       if (static_1)
8033         off2 = 1;
8034       else
8035         {
8036           off1 = 1;
8037           --len;
8038         }
8039     }
8040
8041   for (i = 0; i < len; ++i)
8042     {
8043       conversion *t1 = cand1->convs[i + off1];
8044       conversion *t2 = cand2->convs[i + off2];
8045       int comp = compare_ics (t1, t2);
8046
8047       if (comp != 0)
8048         {
8049           if (warn_sign_promo
8050               && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
8051                   == cr_std + cr_promotion)
8052               && t1->kind == ck_std
8053               && t2->kind == ck_std
8054               && TREE_CODE (t1->type) == INTEGER_TYPE
8055               && TREE_CODE (t2->type) == INTEGER_TYPE
8056               && (TYPE_PRECISION (t1->type)
8057                   == TYPE_PRECISION (t2->type))
8058               && (TYPE_UNSIGNED (t1->u.next->type)
8059                   || (TREE_CODE (t1->u.next->type)
8060                       == ENUMERAL_TYPE)))
8061             {
8062               tree type = t1->u.next->type;
8063               tree type1, type2;
8064               struct z_candidate *w, *l;
8065               if (comp > 0)
8066                 type1 = t1->type, type2 = t2->type,
8067                   w = cand1, l = cand2;
8068               else
8069                 type1 = t2->type, type2 = t1->type,
8070                   w = cand2, l = cand1;
8071
8072               if (warn)
8073                 {
8074                   warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
8075                            type, type1, type2);
8076                   warning (OPT_Wsign_promo, "  in call to %qD", w->fn);
8077                 }
8078               else
8079                 add_warning (w, l);
8080             }
8081
8082           if (winner && comp != winner)
8083             {
8084               winner = 0;
8085               goto tweak;
8086             }
8087           winner = comp;
8088         }
8089     }
8090
8091   /* warn about confusing overload resolution for user-defined conversions,
8092      either between a constructor and a conversion op, or between two
8093      conversion ops.  */
8094   if (winner && warn_conversion && cand1->second_conv
8095       && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
8096       && winner != compare_ics (cand1->second_conv, cand2->second_conv))
8097     {
8098       struct z_candidate *w, *l;
8099       bool give_warning = false;
8100
8101       if (winner == 1)
8102         w = cand1, l = cand2;
8103       else
8104         w = cand2, l = cand1;
8105
8106       /* We don't want to complain about `X::operator T1 ()'
8107          beating `X::operator T2 () const', when T2 is a no less
8108          cv-qualified version of T1.  */
8109       if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
8110           && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
8111         {
8112           tree t = TREE_TYPE (TREE_TYPE (l->fn));
8113           tree f = TREE_TYPE (TREE_TYPE (w->fn));
8114
8115           if (TREE_CODE (t) == TREE_CODE (f) && POINTER_TYPE_P (t))
8116             {
8117               t = TREE_TYPE (t);
8118               f = TREE_TYPE (f);
8119             }
8120           if (!comp_ptr_ttypes (t, f))
8121             give_warning = true;
8122         }
8123       else
8124         give_warning = true;
8125
8126       if (!give_warning)
8127         /*NOP*/;
8128       else if (warn)
8129         {
8130           tree source = source_type (w->convs[0]);
8131           if (! DECL_CONSTRUCTOR_P (w->fn))
8132             source = TREE_TYPE (source);
8133           if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
8134               && warning (OPT_Wconversion, "  for conversion from %qT to %qT",
8135                           source, w->second_conv->type)) 
8136             {
8137               inform (input_location, "  because conversion sequence for the argument is better");
8138             }
8139         }
8140       else
8141         add_warning (w, l);
8142     }
8143
8144   if (winner)
8145     return winner;
8146
8147   /* DR 495 moved this tiebreaker above the template ones.  */
8148   /* or, if not that,
8149      the  context  is  an  initialization by user-defined conversion (see
8150      _dcl.init_  and  _over.match.user_)  and  the  standard   conversion
8151      sequence  from  the return type of F1 to the destination type (i.e.,
8152      the type of the entity being initialized)  is  a  better  conversion
8153      sequence  than the standard conversion sequence from the return type
8154      of F2 to the destination type.  */
8155
8156   if (cand1->second_conv)
8157     {
8158       winner = compare_ics (cand1->second_conv, cand2->second_conv);
8159       if (winner)
8160         return winner;
8161     }
8162
8163   /* or, if not that,
8164      F1 is a non-template function and F2 is a template function
8165      specialization.  */
8166
8167   if (!cand1->template_decl && cand2->template_decl)
8168     return 1;
8169   else if (cand1->template_decl && !cand2->template_decl)
8170     return -1;
8171
8172   /* or, if not that,
8173      F1 and F2 are template functions and the function template for F1 is
8174      more specialized than the template for F2 according to the partial
8175      ordering rules.  */
8176
8177   if (cand1->template_decl && cand2->template_decl)
8178     {
8179       winner = more_specialized_fn
8180         (TI_TEMPLATE (cand1->template_decl),
8181          TI_TEMPLATE (cand2->template_decl),
8182          /* [temp.func.order]: The presence of unused ellipsis and default
8183             arguments has no effect on the partial ordering of function
8184             templates.   add_function_candidate() will not have
8185             counted the "this" argument for constructors.  */
8186          cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
8187       if (winner)
8188         return winner;
8189     }
8190
8191   /* Check whether we can discard a builtin candidate, either because we
8192      have two identical ones or matching builtin and non-builtin candidates.
8193
8194      (Pedantically in the latter case the builtin which matched the user
8195      function should not be added to the overload set, but we spot it here.
8196
8197      [over.match.oper]
8198      ... the builtin candidates include ...
8199      - do not have the same parameter type list as any non-template
8200        non-member candidate.  */
8201
8202   if (TREE_CODE (cand1->fn) == IDENTIFIER_NODE
8203       || TREE_CODE (cand2->fn) == IDENTIFIER_NODE)
8204     {
8205       for (i = 0; i < len; ++i)
8206         if (!same_type_p (cand1->convs[i]->type,
8207                           cand2->convs[i]->type))
8208           break;
8209       if (i == cand1->num_convs)
8210         {
8211           if (cand1->fn == cand2->fn)
8212             /* Two built-in candidates; arbitrarily pick one.  */
8213             return 1;
8214           else if (TREE_CODE (cand1->fn) == IDENTIFIER_NODE)
8215             /* cand1 is built-in; prefer cand2.  */
8216             return -1;
8217           else
8218             /* cand2 is built-in; prefer cand1.  */
8219             return 1;
8220         }
8221     }
8222
8223   /* If the two function declarations represent the same function (this can
8224      happen with declarations in multiple scopes and arg-dependent lookup),
8225      arbitrarily choose one.  But first make sure the default args we're
8226      using match.  */
8227   if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
8228       && equal_functions (cand1->fn, cand2->fn))
8229     {
8230       tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
8231       tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
8232
8233       gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
8234
8235       for (i = 0; i < len; ++i)
8236         {
8237           /* Don't crash if the fn is variadic.  */
8238           if (!parms1)
8239             break;
8240           parms1 = TREE_CHAIN (parms1);
8241           parms2 = TREE_CHAIN (parms2);
8242         }
8243
8244       if (off1)
8245         parms1 = TREE_CHAIN (parms1);
8246       else if (off2)
8247         parms2 = TREE_CHAIN (parms2);
8248
8249       for (; parms1; ++i)
8250         {
8251           if (!cp_tree_equal (TREE_PURPOSE (parms1),
8252                               TREE_PURPOSE (parms2)))
8253             {
8254               if (warn)
8255                 {
8256                   permerror (input_location, "default argument mismatch in "
8257                              "overload resolution");
8258                   inform (input_location,
8259                           " candidate 1: %q+#F", cand1->fn);
8260                   inform (input_location,
8261                           " candidate 2: %q+#F", cand2->fn);
8262                 }
8263               else
8264                 add_warning (cand1, cand2);
8265               break;
8266             }
8267           parms1 = TREE_CHAIN (parms1);
8268           parms2 = TREE_CHAIN (parms2);
8269         }
8270
8271       return 1;
8272     }
8273
8274 tweak:
8275
8276   /* Extension: If the worst conversion for one candidate is worse than the
8277      worst conversion for the other, take the first.  */
8278   if (!pedantic)
8279     {
8280       conversion_rank rank1 = cr_identity, rank2 = cr_identity;
8281       struct z_candidate *w = 0, *l = 0;
8282
8283       for (i = 0; i < len; ++i)
8284         {
8285           if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
8286             rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
8287           if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
8288             rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
8289         }
8290       if (rank1 < rank2)
8291         winner = 1, w = cand1, l = cand2;
8292       if (rank1 > rank2)
8293         winner = -1, w = cand2, l = cand1;
8294       if (winner)
8295         {
8296           /* Don't choose a deleted function over ambiguity.  */
8297           if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
8298             return 0;
8299           if (warn)
8300             {
8301               pedwarn (input_location, 0,
8302               "ISO C++ says that these are ambiguous, even "
8303               "though the worst conversion for the first is better than "
8304               "the worst conversion for the second:");
8305               print_z_candidate (_("candidate 1:"), w);
8306               print_z_candidate (_("candidate 2:"), l);
8307             }
8308           else
8309             add_warning (w, l);
8310           return winner;
8311         }
8312     }
8313
8314   gcc_assert (!winner);
8315   return 0;
8316 }
8317
8318 /* Given a list of candidates for overloading, find the best one, if any.
8319    This algorithm has a worst case of O(2n) (winner is last), and a best
8320    case of O(n/2) (totally ambiguous); much better than a sorting
8321    algorithm.  */
8322
8323 static struct z_candidate *
8324 tourney (struct z_candidate *candidates)
8325 {
8326   struct z_candidate *champ = candidates, *challenger;
8327   int fate;
8328   int champ_compared_to_predecessor = 0;
8329
8330   /* Walk through the list once, comparing each current champ to the next
8331      candidate, knocking out a candidate or two with each comparison.  */
8332
8333   for (challenger = champ->next; challenger; )
8334     {
8335       fate = joust (champ, challenger, 0);
8336       if (fate == 1)
8337         challenger = challenger->next;
8338       else
8339         {
8340           if (fate == 0)
8341             {
8342               champ = challenger->next;
8343               if (champ == 0)
8344                 return NULL;
8345               champ_compared_to_predecessor = 0;
8346             }
8347           else
8348             {
8349               champ = challenger;
8350               champ_compared_to_predecessor = 1;
8351             }
8352
8353           challenger = champ->next;
8354         }
8355     }
8356
8357   /* Make sure the champ is better than all the candidates it hasn't yet
8358      been compared to.  */
8359
8360   for (challenger = candidates;
8361        challenger != champ
8362          && !(champ_compared_to_predecessor && challenger->next == champ);
8363        challenger = challenger->next)
8364     {
8365       fate = joust (champ, challenger, 0);
8366       if (fate != 1)
8367         return NULL;
8368     }
8369
8370   return champ;
8371 }
8372
8373 /* Returns nonzero if things of type FROM can be converted to TO.  */
8374
8375 bool
8376 can_convert (tree to, tree from)
8377 {
8378   return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT);
8379 }
8380
8381 /* Returns nonzero if ARG (of type FROM) can be converted to TO.  */
8382
8383 bool
8384 can_convert_arg (tree to, tree from, tree arg, int flags)
8385 {
8386   conversion *t;
8387   void *p;
8388   bool ok_p;
8389
8390   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
8391   p = conversion_obstack_alloc (0);
8392
8393   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
8394                             flags);
8395   ok_p = (t && !t->bad_p);
8396
8397   /* Free all the conversions we allocated.  */
8398   obstack_free (&conversion_obstack, p);
8399
8400   return ok_p;
8401 }
8402
8403 /* Like can_convert_arg, but allows dubious conversions as well.  */
8404
8405 bool
8406 can_convert_arg_bad (tree to, tree from, tree arg, int flags)
8407 {
8408   conversion *t;
8409   void *p;
8410
8411   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
8412   p = conversion_obstack_alloc (0);
8413   /* Try to perform the conversion.  */
8414   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
8415                             flags);
8416   /* Free all the conversions we allocated.  */
8417   obstack_free (&conversion_obstack, p);
8418
8419   return t != NULL;
8420 }
8421
8422 /* Convert EXPR to TYPE.  Return the converted expression.
8423
8424    Note that we allow bad conversions here because by the time we get to
8425    this point we are committed to doing the conversion.  If we end up
8426    doing a bad conversion, convert_like will complain.  */
8427
8428 tree
8429 perform_implicit_conversion_flags (tree type, tree expr, tsubst_flags_t complain, int flags)
8430 {
8431   conversion *conv;
8432   void *p;
8433
8434   if (error_operand_p (expr))
8435     return error_mark_node;
8436
8437   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
8438   p = conversion_obstack_alloc (0);
8439
8440   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
8441                               /*c_cast_p=*/false,
8442                               flags);
8443
8444   if (!conv)
8445     {
8446       if (complain & tf_error)
8447         {
8448           /* If expr has unknown type, then it is an overloaded function.
8449              Call instantiate_type to get good error messages.  */
8450           if (TREE_TYPE (expr) == unknown_type_node)
8451             instantiate_type (type, expr, complain);
8452           else if (invalid_nonstatic_memfn_p (expr, complain))
8453             /* We gave an error.  */;
8454           else
8455             error ("could not convert %qE from %qT to %qT", expr,
8456                    TREE_TYPE (expr), type);
8457         }
8458       expr = error_mark_node;
8459     }
8460   else if (processing_template_decl && conv->kind != ck_identity)
8461     {
8462       /* In a template, we are only concerned about determining the
8463          type of non-dependent expressions, so we do not have to
8464          perform the actual conversion.  But for initializers, we
8465          need to be able to perform it at instantiation
8466          (or fold_non_dependent_expr) time.  */
8467       expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
8468       if (!(flags & LOOKUP_ONLYCONVERTING))
8469         IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
8470     }
8471   else
8472     expr = convert_like (conv, expr, complain);
8473
8474   /* Free all the conversions we allocated.  */
8475   obstack_free (&conversion_obstack, p);
8476
8477   return expr;
8478 }
8479
8480 tree
8481 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
8482 {
8483   return perform_implicit_conversion_flags (type, expr, complain, LOOKUP_IMPLICIT);
8484 }
8485
8486 /* Convert EXPR to TYPE (as a direct-initialization) if that is
8487    permitted.  If the conversion is valid, the converted expression is
8488    returned.  Otherwise, NULL_TREE is returned, except in the case
8489    that TYPE is a class type; in that case, an error is issued.  If
8490    C_CAST_P is true, then this direct-initialization is taking
8491    place as part of a static_cast being attempted as part of a C-style
8492    cast.  */
8493
8494 tree
8495 perform_direct_initialization_if_possible (tree type,
8496                                            tree expr,
8497                                            bool c_cast_p,
8498                                            tsubst_flags_t complain)
8499 {
8500   conversion *conv;
8501   void *p;
8502
8503   if (type == error_mark_node || error_operand_p (expr))
8504     return error_mark_node;
8505   /* [dcl.init]
8506
8507      If the destination type is a (possibly cv-qualified) class type:
8508
8509      -- If the initialization is direct-initialization ...,
8510      constructors are considered. ... If no constructor applies, or
8511      the overload resolution is ambiguous, the initialization is
8512      ill-formed.  */
8513   if (CLASS_TYPE_P (type))
8514     {
8515       VEC(tree,gc) *args = make_tree_vector_single (expr);
8516       expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8517                                         &args, type, LOOKUP_NORMAL, complain);
8518       release_tree_vector (args);
8519       return build_cplus_new (type, expr, complain);
8520     }
8521
8522   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
8523   p = conversion_obstack_alloc (0);
8524
8525   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
8526                               c_cast_p,
8527                               LOOKUP_NORMAL);
8528   if (!conv || conv->bad_p)
8529     expr = NULL_TREE;
8530   else
8531     expr = convert_like_real (conv, expr, NULL_TREE, 0, 0,
8532                               /*issue_conversion_warnings=*/false,
8533                               c_cast_p,
8534                               complain);
8535
8536   /* Free all the conversions we allocated.  */
8537   obstack_free (&conversion_obstack, p);
8538
8539   return expr;
8540 }
8541
8542 /* When initializing a reference that lasts longer than a full-expression,
8543    this special rule applies:
8544
8545      [class.temporary]
8546
8547      The temporary to which the reference is bound or the temporary
8548      that is the complete object to which the reference is bound
8549      persists for the lifetime of the reference.
8550
8551      The temporaries created during the evaluation of the expression
8552      initializing the reference, except the temporary to which the
8553      reference is bound, are destroyed at the end of the
8554      full-expression in which they are created.
8555
8556    In that case, we store the converted expression into a new
8557    VAR_DECL in a new scope.
8558
8559    However, we want to be careful not to create temporaries when
8560    they are not required.  For example, given:
8561
8562      struct B {};
8563      struct D : public B {};
8564      D f();
8565      const B& b = f();
8566
8567    there is no need to copy the return value from "f"; we can just
8568    extend its lifetime.  Similarly, given:
8569
8570      struct S {};
8571      struct T { operator S(); };
8572      T t;
8573      const S& s = t;
8574
8575   we can extend the lifetime of the return value of the conversion
8576   operator.
8577
8578   The next several functions are involved in this lifetime extension.  */
8579
8580 /* DECL is a VAR_DECL whose type is a REFERENCE_TYPE.  The reference
8581    is being bound to a temporary.  Create and return a new VAR_DECL
8582    with the indicated TYPE; this variable will store the value to
8583    which the reference is bound.  */
8584
8585 tree
8586 make_temporary_var_for_ref_to_temp (tree decl, tree type)
8587 {
8588   tree var;
8589
8590   /* Create the variable.  */
8591   var = create_temporary_var (type);
8592
8593   /* Register the variable.  */
8594   if (TREE_STATIC (decl))
8595     {
8596       /* Namespace-scope or local static; give it a mangled name.  */
8597       /* FIXME share comdat with decl?  */
8598       tree name;
8599
8600       TREE_STATIC (var) = 1;
8601       name = mangle_ref_init_variable (decl);
8602       DECL_NAME (var) = name;
8603       SET_DECL_ASSEMBLER_NAME (var, name);
8604       var = pushdecl_top_level (var);
8605     }
8606   else
8607     /* Create a new cleanup level if necessary.  */
8608     maybe_push_cleanup_level (type);
8609
8610   return var;
8611 }
8612
8613 /* EXPR is the initializer for a variable DECL of reference or
8614    std::initializer_list type.  Create, push and return a new VAR_DECL
8615    for the initializer so that it will live as long as DECL.  Any
8616    cleanup for the new variable is returned through CLEANUP, and the
8617    code to initialize the new variable is returned through INITP.  */
8618
8619 static tree
8620 set_up_extended_ref_temp (tree decl, tree expr, VEC(tree,gc) **cleanups,
8621                           tree *initp)
8622 {
8623   tree init;
8624   tree type;
8625   tree var;
8626
8627   /* Create the temporary variable.  */
8628   type = TREE_TYPE (expr);
8629   var = make_temporary_var_for_ref_to_temp (decl, type);
8630   layout_decl (var, 0);
8631   /* If the rvalue is the result of a function call it will be
8632      a TARGET_EXPR.  If it is some other construct (such as a
8633      member access expression where the underlying object is
8634      itself the result of a function call), turn it into a
8635      TARGET_EXPR here.  It is important that EXPR be a
8636      TARGET_EXPR below since otherwise the INIT_EXPR will
8637      attempt to make a bitwise copy of EXPR to initialize
8638      VAR.  */
8639   if (TREE_CODE (expr) != TARGET_EXPR)
8640     expr = get_target_expr (expr);
8641
8642   if (TREE_CODE (decl) == FIELD_DECL
8643       && extra_warnings && !TREE_NO_WARNING (decl))
8644     {
8645       warning (OPT_Wextra, "a temporary bound to %qD only persists "
8646                "until the constructor exits", decl);
8647       TREE_NO_WARNING (decl) = true;
8648     }
8649
8650   /* Recursively extend temps in this initializer.  */
8651   TARGET_EXPR_INITIAL (expr)
8652     = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups);
8653
8654   /* If the initializer is constant, put it in DECL_INITIAL so we get
8655      static initialization and use in constant expressions.  */
8656   init = maybe_constant_init (expr);
8657   if (TREE_CONSTANT (init))
8658     {
8659       if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
8660         {
8661           /* 5.19 says that a constant expression can include an
8662              lvalue-rvalue conversion applied to "a glvalue of literal type
8663              that refers to a non-volatile temporary object initialized
8664              with a constant expression".  Rather than try to communicate
8665              that this VAR_DECL is a temporary, just mark it constexpr.
8666
8667              Currently this is only useful for initializer_list temporaries,
8668              since reference vars can't appear in constant expressions.  */
8669           DECL_DECLARED_CONSTEXPR_P (var) = true;
8670           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
8671           TREE_CONSTANT (var) = true;
8672         }
8673       DECL_INITIAL (var) = init;
8674       init = NULL_TREE;
8675     }
8676   else
8677     /* Create the INIT_EXPR that will initialize the temporary
8678        variable.  */
8679     init = build2 (INIT_EXPR, type, var, expr);
8680   if (at_function_scope_p ())
8681     {
8682       add_decl_expr (var);
8683
8684       if (TREE_STATIC (var))
8685         init = add_stmt_to_compound (init, register_dtor_fn (var));
8686       else
8687         {
8688           tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
8689           if (cleanup)
8690             VEC_safe_push (tree, gc, *cleanups, cleanup);
8691         }
8692
8693       /* We must be careful to destroy the temporary only
8694          after its initialization has taken place.  If the
8695          initialization throws an exception, then the
8696          destructor should not be run.  We cannot simply
8697          transform INIT into something like:
8698
8699          (INIT, ({ CLEANUP_STMT; }))
8700
8701          because emit_local_var always treats the
8702          initializer as a full-expression.  Thus, the
8703          destructor would run too early; it would run at the
8704          end of initializing the reference variable, rather
8705          than at the end of the block enclosing the
8706          reference variable.
8707
8708          The solution is to pass back a cleanup expression
8709          which the caller is responsible for attaching to
8710          the statement tree.  */
8711     }
8712   else
8713     {
8714       rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
8715       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
8716         static_aggregates = tree_cons (NULL_TREE, var,
8717                                        static_aggregates);
8718     }
8719
8720   *initp = init;
8721   return var;
8722 }
8723
8724 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
8725    initializing a variable of that TYPE.  */
8726
8727 tree
8728 initialize_reference (tree type, tree expr,
8729                       int flags, tsubst_flags_t complain)
8730 {
8731   conversion *conv;
8732   void *p;
8733
8734   if (type == error_mark_node || error_operand_p (expr))
8735     return error_mark_node;
8736
8737   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
8738   p = conversion_obstack_alloc (0);
8739
8740   conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
8741                             flags);
8742   if (!conv || conv->bad_p)
8743     {
8744       if (complain & tf_error)
8745         {
8746           if (conv)
8747             convert_like (conv, expr, complain);
8748           else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
8749                    && !TYPE_REF_IS_RVALUE (type)
8750                    && !real_lvalue_p (expr))
8751             error ("invalid initialization of non-const reference of "
8752                    "type %qT from an rvalue of type %qT",
8753                    type, TREE_TYPE (expr));
8754           else
8755             error ("invalid initialization of reference of type "
8756                    "%qT from expression of type %qT", type,
8757                    TREE_TYPE (expr));
8758         }
8759       return error_mark_node;
8760     }
8761
8762   gcc_assert (conv->kind == ck_ref_bind);
8763
8764   /* Perform the conversion.  */
8765   expr = convert_like (conv, expr, complain);
8766
8767   /* Free all the conversions we allocated.  */
8768   obstack_free (&conversion_obstack, p);
8769
8770   return expr;
8771 }
8772
8773 /* Subroutine of extend_ref_init_temps.  Possibly extend one initializer,
8774    which is bound either to a reference or a std::initializer_list.  */
8775
8776 static tree
8777 extend_ref_init_temps_1 (tree decl, tree init, VEC(tree,gc) **cleanups)
8778 {
8779   tree sub = init;
8780   tree *p;
8781   STRIP_NOPS (sub);
8782   if (TREE_CODE (sub) == COMPOUND_EXPR)
8783     {
8784       TREE_OPERAND (sub, 1)
8785         = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups);
8786       return init;
8787     }
8788   if (TREE_CODE (sub) != ADDR_EXPR)
8789     return init;
8790   /* Deal with binding to a subobject.  */
8791   for (p = &TREE_OPERAND (sub, 0); TREE_CODE (*p) == COMPONENT_REF; )
8792     p = &TREE_OPERAND (*p, 0);
8793   if (TREE_CODE (*p) == TARGET_EXPR)
8794     {
8795       tree subinit = NULL_TREE;
8796       *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit);
8797       if (subinit)
8798         init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
8799     }
8800   return init;
8801 }
8802
8803 /* INIT is part of the initializer for DECL.  If there are any
8804    reference or initializer lists being initialized, extend their
8805    lifetime to match that of DECL.  */
8806
8807 tree
8808 extend_ref_init_temps (tree decl, tree init, VEC(tree,gc) **cleanups)
8809 {
8810   tree type = TREE_TYPE (init);
8811   if (processing_template_decl)
8812     return init;
8813   if (TREE_CODE (type) == REFERENCE_TYPE)
8814     init = extend_ref_init_temps_1 (decl, init, cleanups);
8815   else if (is_std_init_list (type))
8816     {
8817       /* The temporary array underlying a std::initializer_list
8818          is handled like a reference temporary.  */
8819       tree ctor = init;
8820       if (TREE_CODE (ctor) == TARGET_EXPR)
8821         ctor = TARGET_EXPR_INITIAL (ctor);
8822       if (TREE_CODE (ctor) == CONSTRUCTOR)
8823         {
8824           tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
8825           array = extend_ref_init_temps_1 (decl, array, cleanups);
8826           CONSTRUCTOR_ELT (ctor, 0)->value = array;
8827         }
8828     }
8829   else if (TREE_CODE (init) == CONSTRUCTOR)
8830     {
8831       unsigned i;
8832       constructor_elt *p;
8833       VEC(constructor_elt,gc) *elts = CONSTRUCTOR_ELTS (init);
8834       FOR_EACH_VEC_ELT (constructor_elt, elts, i, p)
8835         p->value = extend_ref_init_temps (decl, p->value, cleanups);
8836     }
8837
8838   return init;
8839 }
8840
8841 /* Returns true iff an initializer for TYPE could contain temporaries that
8842    need to be extended because they are bound to references or
8843    std::initializer_list.  */
8844
8845 bool
8846 type_has_extended_temps (tree type)
8847 {
8848   type = strip_array_types (type);
8849   if (TREE_CODE (type) == REFERENCE_TYPE)
8850     return true;
8851   if (CLASS_TYPE_P (type))
8852     {
8853       tree f;
8854       if (is_std_init_list (type))
8855         return true;
8856       for (f = next_initializable_field (TYPE_FIELDS (type));
8857            f; f = next_initializable_field (DECL_CHAIN (f)))
8858         if (type_has_extended_temps (TREE_TYPE (f)))
8859           return true;
8860     }
8861   return false;
8862 }
8863
8864 /* Returns true iff TYPE is some variant of std::initializer_list.  */
8865
8866 bool
8867 is_std_init_list (tree type)
8868 {
8869   /* Look through typedefs.  */
8870   if (!TYPE_P (type))
8871     return false;
8872   type = TYPE_MAIN_VARIANT (type);
8873   return (CLASS_TYPE_P (type)
8874           && CP_TYPE_CONTEXT (type) == std_node
8875           && strcmp (TYPE_NAME_STRING (type), "initializer_list") == 0);
8876 }
8877
8878 /* Returns true iff DECL is a list constructor: i.e. a constructor which
8879    will accept an argument list of a single std::initializer_list<T>.  */
8880
8881 bool
8882 is_list_ctor (tree decl)
8883 {
8884   tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
8885   tree arg;
8886
8887   if (!args || args == void_list_node)
8888     return false;
8889
8890   arg = non_reference (TREE_VALUE (args));
8891   if (!is_std_init_list (arg))
8892     return false;
8893
8894   args = TREE_CHAIN (args);
8895
8896   if (args && args != void_list_node && !TREE_PURPOSE (args))
8897     /* There are more non-defaulted parms.  */
8898     return false;
8899
8900   return true;
8901 }
8902
8903 #include "gt-cp-call.h"