OSDN Git Service

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