OSDN Git Service

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