e9d4cae57051aa36327c07c9d3abd09b0d8d92c1
[dragonfly.git] / contrib / gcc-5.0 / gcc / cp / typeck.c
1 /* Build expressions with type checking for C++ compiler.
2    Copyright (C) 1987-2015 Free Software Foundation, Inc.
3    Hacked by Michael Tiemann (tiemann@cygnus.com)
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21
22 /* This file is part of the C++ front end.
23    It contains routines to build C++ expressions given their operands,
24    including computing the types of the result, C and C++ specific error
25    checks, and some optimization.  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "hash-set.h"
32 #include "machmode.h"
33 #include "vec.h"
34 #include "double-int.h"
35 #include "input.h"
36 #include "alias.h"
37 #include "symtab.h"
38 #include "wide-int.h"
39 #include "inchash.h"
40 #include "tree.h"
41 #include "fold-const.h"
42 #include "stor-layout.h"
43 #include "varasm.h"
44 #include "cp-tree.h"
45 #include "flags.h"
46 #include "diagnostic.h"
47 #include "intl.h"
48 #include "target.h"
49 #include "convert.h"
50 #include "c-family/c-common.h"
51 #include "c-family/c-objc.h"
52 #include "c-family/c-ubsan.h"
53 #include "params.h"
54
55 static tree cp_build_addr_expr_strict (tree, tsubst_flags_t);
56 static tree cp_build_function_call (tree, tree, tsubst_flags_t);
57 static tree pfn_from_ptrmemfunc (tree);
58 static tree delta_from_ptrmemfunc (tree);
59 static tree convert_for_assignment (tree, tree, impl_conv_rhs, tree, int,
60                                     tsubst_flags_t, int);
61 static tree cp_pointer_int_sum (enum tree_code, tree, tree, tsubst_flags_t);
62 static tree rationalize_conditional_expr (enum tree_code, tree, 
63                                           tsubst_flags_t);
64 static int comp_ptr_ttypes_real (tree, tree, int);
65 static bool comp_except_types (tree, tree, bool);
66 static bool comp_array_types (const_tree, const_tree, bool);
67 static tree pointer_diff (tree, tree, tree, tsubst_flags_t);
68 static tree get_delta_difference (tree, tree, bool, bool, tsubst_flags_t);
69 static void casts_away_constness_r (tree *, tree *, tsubst_flags_t);
70 static bool casts_away_constness (tree, tree, tsubst_flags_t);
71 static bool maybe_warn_about_returning_address_of_local (tree);
72 static tree lookup_destructor (tree, tree, tree, tsubst_flags_t);
73 static void warn_args_num (location_t, tree, bool);
74 static int convert_arguments (tree, vec<tree, va_gc> **, tree, int,
75                               tsubst_flags_t);
76
77 /* Do `exp = require_complete_type (exp);' to make sure exp
78    does not have an incomplete type.  (That includes void types.)
79    Returns error_mark_node if the VALUE does not have
80    complete type when this function returns.  */
81
82 tree
83 require_complete_type_sfinae (tree value, tsubst_flags_t complain)
84 {
85   tree type;
86
87   if (processing_template_decl || value == error_mark_node)
88     return value;
89
90   if (TREE_CODE (value) == OVERLOAD)
91     type = unknown_type_node;
92   else
93     type = TREE_TYPE (value);
94
95   if (type == error_mark_node)
96     return error_mark_node;
97
98   /* First, detect a valid value with a complete type.  */
99   if (COMPLETE_TYPE_P (type))
100     return value;
101
102   if (complete_type_or_maybe_complain (type, value, complain))
103     return value;
104   else
105     return error_mark_node;
106 }
107
108 tree
109 require_complete_type (tree value)
110 {
111   return require_complete_type_sfinae (value, tf_warning_or_error);
112 }
113
114 /* Try to complete TYPE, if it is incomplete.  For example, if TYPE is
115    a template instantiation, do the instantiation.  Returns TYPE,
116    whether or not it could be completed, unless something goes
117    horribly wrong, in which case the error_mark_node is returned.  */
118
119 tree
120 complete_type (tree type)
121 {
122   if (type == NULL_TREE)
123     /* Rather than crash, we return something sure to cause an error
124        at some point.  */
125     return error_mark_node;
126
127   if (type == error_mark_node || COMPLETE_TYPE_P (type))
128     ;
129   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
130     {
131       tree t = complete_type (TREE_TYPE (type));
132       unsigned int needs_constructing, has_nontrivial_dtor;
133       if (COMPLETE_TYPE_P (t) && !dependent_type_p (type))
134         layout_type (type);
135       needs_constructing
136         = TYPE_NEEDS_CONSTRUCTING (TYPE_MAIN_VARIANT (t));
137       has_nontrivial_dtor
138         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TYPE_MAIN_VARIANT (t));
139       for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
140         {
141           TYPE_NEEDS_CONSTRUCTING (t) = needs_constructing;
142           TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) = has_nontrivial_dtor;
143         }
144     }
145   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INSTANTIATION (type))
146     instantiate_class_template (TYPE_MAIN_VARIANT (type));
147
148   return type;
149 }
150
151 /* Like complete_type, but issue an error if the TYPE cannot be completed.
152    VALUE is used for informative diagnostics.
153    Returns NULL_TREE if the type cannot be made complete.  */
154
155 tree
156 complete_type_or_maybe_complain (tree type, tree value, tsubst_flags_t complain)
157 {
158   type = complete_type (type);
159   if (type == error_mark_node)
160     /* We already issued an error.  */
161     return NULL_TREE;
162   else if (!COMPLETE_TYPE_P (type))
163     {
164       if (complain & tf_error)
165         cxx_incomplete_type_diagnostic (value, type, DK_ERROR);
166       return NULL_TREE;
167     }
168   else
169     return type;
170 }
171
172 tree
173 complete_type_or_else (tree type, tree value)
174 {
175   return complete_type_or_maybe_complain (type, value, tf_warning_or_error);
176 }
177
178 /* Return truthvalue of whether type of EXP is instantiated.  */
179
180 int
181 type_unknown_p (const_tree exp)
182 {
183   return (TREE_CODE (exp) == TREE_LIST
184           || TREE_TYPE (exp) == unknown_type_node);
185 }
186
187 \f
188 /* Return the common type of two parameter lists.
189    We assume that comptypes has already been done and returned 1;
190    if that isn't so, this may crash.
191
192    As an optimization, free the space we allocate if the parameter
193    lists are already common.  */
194
195 static tree
196 commonparms (tree p1, tree p2)
197 {
198   tree oldargs = p1, newargs, n;
199   int i, len;
200   int any_change = 0;
201
202   len = list_length (p1);
203   newargs = tree_last (p1);
204
205   if (newargs == void_list_node)
206     i = 1;
207   else
208     {
209       i = 0;
210       newargs = 0;
211     }
212
213   for (; i < len; i++)
214     newargs = tree_cons (NULL_TREE, NULL_TREE, newargs);
215
216   n = newargs;
217
218   for (i = 0; p1;
219        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2), n = TREE_CHAIN (n), i++)
220     {
221       if (TREE_PURPOSE (p1) && !TREE_PURPOSE (p2))
222         {
223           TREE_PURPOSE (n) = TREE_PURPOSE (p1);
224           any_change = 1;
225         }
226       else if (! TREE_PURPOSE (p1))
227         {
228           if (TREE_PURPOSE (p2))
229             {
230               TREE_PURPOSE (n) = TREE_PURPOSE (p2);
231               any_change = 1;
232             }
233         }
234       else
235         {
236           if (1 != simple_cst_equal (TREE_PURPOSE (p1), TREE_PURPOSE (p2)))
237             any_change = 1;
238           TREE_PURPOSE (n) = TREE_PURPOSE (p2);
239         }
240       if (TREE_VALUE (p1) != TREE_VALUE (p2))
241         {
242           any_change = 1;
243           TREE_VALUE (n) = merge_types (TREE_VALUE (p1), TREE_VALUE (p2));
244         }
245       else
246         TREE_VALUE (n) = TREE_VALUE (p1);
247     }
248   if (! any_change)
249     return oldargs;
250
251   return newargs;
252 }
253
254 /* Given a type, perhaps copied for a typedef,
255    find the "original" version of it.  */
256 static tree
257 original_type (tree t)
258 {
259   int quals = cp_type_quals (t);
260   while (t != error_mark_node
261          && TYPE_NAME (t) != NULL_TREE)
262     {
263       tree x = TYPE_NAME (t);
264       if (TREE_CODE (x) != TYPE_DECL)
265         break;
266       x = DECL_ORIGINAL_TYPE (x);
267       if (x == NULL_TREE)
268         break;
269       t = x;
270     }
271   return cp_build_qualified_type (t, quals);
272 }
273
274 /* Return the common type for two arithmetic types T1 and T2 under the
275    usual arithmetic conversions.  The default conversions have already
276    been applied, and enumerated types converted to their compatible
277    integer types.  */
278
279 static tree
280 cp_common_type (tree t1, tree t2)
281 {
282   enum tree_code code1 = TREE_CODE (t1);
283   enum tree_code code2 = TREE_CODE (t2);
284   tree attributes;
285   int i;
286
287
288   /* In what follows, we slightly generalize the rules given in [expr] so
289      as to deal with `long long' and `complex'.  First, merge the
290      attributes.  */
291   attributes = (*targetm.merge_type_attributes) (t1, t2);
292
293   if (SCOPED_ENUM_P (t1) || SCOPED_ENUM_P (t2))
294     {
295       if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
296         return build_type_attribute_variant (t1, attributes);
297       else
298         return NULL_TREE;
299     }
300
301   /* FIXME: Attributes.  */
302   gcc_assert (ARITHMETIC_TYPE_P (t1)
303               || TREE_CODE (t1) == VECTOR_TYPE
304               || UNSCOPED_ENUM_P (t1));
305   gcc_assert (ARITHMETIC_TYPE_P (t2)
306               || TREE_CODE (t2) == VECTOR_TYPE
307               || UNSCOPED_ENUM_P (t2));
308
309   /* If one type is complex, form the common type of the non-complex
310      components, then make that complex.  Use T1 or T2 if it is the
311      required type.  */
312   if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE)
313     {
314       tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1;
315       tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2;
316       tree subtype
317         = type_after_usual_arithmetic_conversions (subtype1, subtype2);
318
319       if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype)
320         return build_type_attribute_variant (t1, attributes);
321       else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype)
322         return build_type_attribute_variant (t2, attributes);
323       else
324         return build_type_attribute_variant (build_complex_type (subtype),
325                                              attributes);
326     }
327
328   if (code1 == VECTOR_TYPE)
329     {
330       /* When we get here we should have two vectors of the same size.
331          Just prefer the unsigned one if present.  */
332       if (TYPE_UNSIGNED (t1))
333         return build_type_attribute_variant (t1, attributes);
334       else
335         return build_type_attribute_variant (t2, attributes);
336     }
337
338   /* If only one is real, use it as the result.  */
339   if (code1 == REAL_TYPE && code2 != REAL_TYPE)
340     return build_type_attribute_variant (t1, attributes);
341   if (code2 == REAL_TYPE && code1 != REAL_TYPE)
342     return build_type_attribute_variant (t2, attributes);
343
344   /* Both real or both integers; use the one with greater precision.  */
345   if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2))
346     return build_type_attribute_variant (t1, attributes);
347   else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1))
348     return build_type_attribute_variant (t2, attributes);
349
350   /* The types are the same; no need to do anything fancy.  */
351   if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
352     return build_type_attribute_variant (t1, attributes);
353
354   if (code1 != REAL_TYPE)
355     {
356       /* If one is unsigned long long, then convert the other to unsigned
357          long long.  */
358       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_unsigned_type_node)
359           || same_type_p (TYPE_MAIN_VARIANT (t2), long_long_unsigned_type_node))
360         return build_type_attribute_variant (long_long_unsigned_type_node,
361                                              attributes);
362       /* If one is a long long, and the other is an unsigned long, and
363          long long can represent all the values of an unsigned long, then
364          convert to a long long.  Otherwise, convert to an unsigned long
365          long.  Otherwise, if either operand is long long, convert the
366          other to long long.
367
368          Since we're here, we know the TYPE_PRECISION is the same;
369          therefore converting to long long cannot represent all the values
370          of an unsigned long, so we choose unsigned long long in that
371          case.  */
372       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_integer_type_node)
373           || same_type_p (TYPE_MAIN_VARIANT (t2), long_long_integer_type_node))
374         {
375           tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
376                     ? long_long_unsigned_type_node
377                     : long_long_integer_type_node);
378           return build_type_attribute_variant (t, attributes);
379         }
380
381       /* Go through the same procedure, but for longs.  */
382       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_unsigned_type_node)
383           || same_type_p (TYPE_MAIN_VARIANT (t2), long_unsigned_type_node))
384         return build_type_attribute_variant (long_unsigned_type_node,
385                                              attributes);
386       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_integer_type_node)
387           || same_type_p (TYPE_MAIN_VARIANT (t2), long_integer_type_node))
388         {
389           tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
390                     ? long_unsigned_type_node : long_integer_type_node);
391           return build_type_attribute_variant (t, attributes);
392         }
393
394       /* For __intN types, either the type is __int128 (and is lower
395          priority than the types checked above, but higher than other
396          128-bit types) or it's known to not be the same size as other
397          types (enforced in toplev.c).  Prefer the unsigned type. */
398       for (i = 0; i < NUM_INT_N_ENTS; i ++)
399         {
400           if (int_n_enabled_p [i]
401               && (same_type_p (TYPE_MAIN_VARIANT (t1), int_n_trees[i].signed_type)
402                   || same_type_p (TYPE_MAIN_VARIANT (t2), int_n_trees[i].signed_type)
403                   || same_type_p (TYPE_MAIN_VARIANT (t1), int_n_trees[i].unsigned_type)
404                   || same_type_p (TYPE_MAIN_VARIANT (t2), int_n_trees[i].unsigned_type)))
405             {
406               tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
407                         ? int_n_trees[i].unsigned_type
408                         : int_n_trees[i].signed_type);
409               return build_type_attribute_variant (t, attributes);
410             }
411         }
412
413       /* Otherwise prefer the unsigned one.  */
414       if (TYPE_UNSIGNED (t1))
415         return build_type_attribute_variant (t1, attributes);
416       else
417         return build_type_attribute_variant (t2, attributes);
418     }
419   else
420     {
421       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_double_type_node)
422           || same_type_p (TYPE_MAIN_VARIANT (t2), long_double_type_node))
423         return build_type_attribute_variant (long_double_type_node,
424                                              attributes);
425       if (same_type_p (TYPE_MAIN_VARIANT (t1), double_type_node)
426           || same_type_p (TYPE_MAIN_VARIANT (t2), double_type_node))
427         return build_type_attribute_variant (double_type_node,
428                                              attributes);
429       if (same_type_p (TYPE_MAIN_VARIANT (t1), float_type_node)
430           || same_type_p (TYPE_MAIN_VARIANT (t2), float_type_node))
431         return build_type_attribute_variant (float_type_node,
432                                              attributes);
433
434       /* Two floating-point types whose TYPE_MAIN_VARIANTs are none of
435          the standard C++ floating-point types.  Logic earlier in this
436          function has already eliminated the possibility that
437          TYPE_PRECISION (t2) != TYPE_PRECISION (t1), so there's no
438          compelling reason to choose one or the other.  */
439       return build_type_attribute_variant (t1, attributes);
440     }
441 }
442
443 /* T1 and T2 are arithmetic or enumeration types.  Return the type
444    that will result from the "usual arithmetic conversions" on T1 and
445    T2 as described in [expr].  */
446
447 tree
448 type_after_usual_arithmetic_conversions (tree t1, tree t2)
449 {
450   gcc_assert (ARITHMETIC_TYPE_P (t1)
451               || TREE_CODE (t1) == VECTOR_TYPE
452               || UNSCOPED_ENUM_P (t1));
453   gcc_assert (ARITHMETIC_TYPE_P (t2)
454               || TREE_CODE (t2) == VECTOR_TYPE
455               || UNSCOPED_ENUM_P (t2));
456
457   /* Perform the integral promotions.  We do not promote real types here.  */
458   if (INTEGRAL_OR_ENUMERATION_TYPE_P (t1)
459       && INTEGRAL_OR_ENUMERATION_TYPE_P (t2))
460     {
461       t1 = type_promotes_to (t1);
462       t2 = type_promotes_to (t2);
463     }
464
465   return cp_common_type (t1, t2);
466 }
467
468 static void
469 composite_pointer_error (diagnostic_t kind, tree t1, tree t2,
470                          composite_pointer_operation operation)
471 {
472   switch (operation)
473     {
474     case CPO_COMPARISON:
475       emit_diagnostic (kind, input_location, 0,
476                        "comparison between "
477                        "distinct pointer types %qT and %qT lacks a cast",
478                        t1, t2);
479       break;
480     case CPO_CONVERSION:
481       emit_diagnostic (kind, input_location, 0,
482                        "conversion between "
483                        "distinct pointer types %qT and %qT lacks a cast",
484                        t1, t2);
485       break;
486     case CPO_CONDITIONAL_EXPR:
487       emit_diagnostic (kind, input_location, 0,
488                        "conditional expression between "
489                        "distinct pointer types %qT and %qT lacks a cast",
490                        t1, t2);
491       break;
492     default:
493       gcc_unreachable ();
494     }
495 }
496
497 /* Subroutine of composite_pointer_type to implement the recursive
498    case.  See that function for documentation of the parameters.  */
499
500 static tree
501 composite_pointer_type_r (tree t1, tree t2, 
502                           composite_pointer_operation operation,
503                           tsubst_flags_t complain)
504 {
505   tree pointee1;
506   tree pointee2;
507   tree result_type;
508   tree attributes;
509
510   /* Determine the types pointed to by T1 and T2.  */
511   if (TYPE_PTR_P (t1))
512     {
513       pointee1 = TREE_TYPE (t1);
514       pointee2 = TREE_TYPE (t2);
515     }
516   else
517     {
518       pointee1 = TYPE_PTRMEM_POINTED_TO_TYPE (t1);
519       pointee2 = TYPE_PTRMEM_POINTED_TO_TYPE (t2);
520     }
521
522   /* [expr.rel]
523
524      Otherwise, the composite pointer type is a pointer type
525      similar (_conv.qual_) to the type of one of the operands,
526      with a cv-qualification signature (_conv.qual_) that is the
527      union of the cv-qualification signatures of the operand
528      types.  */
529   if (same_type_ignoring_top_level_qualifiers_p (pointee1, pointee2))
530     result_type = pointee1;
531   else if ((TYPE_PTR_P (pointee1) && TYPE_PTR_P (pointee2))
532            || (TYPE_PTRMEM_P (pointee1) && TYPE_PTRMEM_P (pointee2)))
533     {
534       result_type = composite_pointer_type_r (pointee1, pointee2, operation,
535                                               complain);
536       if (result_type == error_mark_node)
537         return error_mark_node;
538     }
539   else
540     {
541       if (complain & tf_error)
542         composite_pointer_error (DK_PERMERROR, t1, t2, operation);
543       else
544         return error_mark_node;
545       result_type = void_type_node;
546     }
547   result_type = cp_build_qualified_type (result_type,
548                                          (cp_type_quals (pointee1)
549                                           | cp_type_quals (pointee2)));
550   /* If the original types were pointers to members, so is the
551      result.  */
552   if (TYPE_PTRMEM_P (t1))
553     {
554       if (!same_type_p (TYPE_PTRMEM_CLASS_TYPE (t1),
555                         TYPE_PTRMEM_CLASS_TYPE (t2)))
556         {
557           if (complain & tf_error)
558             composite_pointer_error (DK_PERMERROR, t1, t2, operation);
559           else
560             return error_mark_node;
561         }
562       result_type = build_ptrmem_type (TYPE_PTRMEM_CLASS_TYPE (t1),
563                                        result_type);
564     }
565   else
566     result_type = build_pointer_type (result_type);
567
568   /* Merge the attributes.  */
569   attributes = (*targetm.merge_type_attributes) (t1, t2);
570   return build_type_attribute_variant (result_type, attributes);
571 }
572
573 /* Return the composite pointer type (see [expr.rel]) for T1 and T2.
574    ARG1 and ARG2 are the values with those types.  The OPERATION is to
575    describe the operation between the pointer types,
576    in case an error occurs.
577
578    This routine also implements the computation of a common type for
579    pointers-to-members as per [expr.eq].  */
580
581 tree
582 composite_pointer_type (tree t1, tree t2, tree arg1, tree arg2,
583                         composite_pointer_operation operation, 
584                         tsubst_flags_t complain)
585 {
586   tree class1;
587   tree class2;
588
589   /* [expr.rel]
590
591      If one operand is a null pointer constant, the composite pointer
592      type is the type of the other operand.  */
593   if (null_ptr_cst_p (arg1))
594     return t2;
595   if (null_ptr_cst_p (arg2))
596     return t1;
597
598   /* We have:
599
600        [expr.rel]
601
602        If one of the operands has type "pointer to cv1 void*", then
603        the other has type "pointer to cv2T", and the composite pointer
604        type is "pointer to cv12 void", where cv12 is the union of cv1
605        and cv2.
606
607     If either type is a pointer to void, make sure it is T1.  */
608   if (TYPE_PTR_P (t2) && VOID_TYPE_P (TREE_TYPE (t2)))
609     {
610       tree t;
611       t = t1;
612       t1 = t2;
613       t2 = t;
614     }
615
616   /* Now, if T1 is a pointer to void, merge the qualifiers.  */
617   if (TYPE_PTR_P (t1) && VOID_TYPE_P (TREE_TYPE (t1)))
618     {
619       tree attributes;
620       tree result_type;
621
622       if (TYPE_PTRFN_P (t2))
623         {
624           if (complain & tf_error)
625             {
626               switch (operation)
627                 {
628                 case CPO_COMPARISON:
629                   pedwarn (input_location, OPT_Wpedantic, 
630                            "ISO C++ forbids comparison between pointer "
631                            "of type %<void *%> and pointer-to-function");
632                   break;
633                 case CPO_CONVERSION:
634                   pedwarn (input_location, OPT_Wpedantic,
635                            "ISO C++ forbids conversion between pointer "
636                            "of type %<void *%> and pointer-to-function");
637                   break;
638                 case CPO_CONDITIONAL_EXPR:
639                   pedwarn (input_location, OPT_Wpedantic,
640                            "ISO C++ forbids conditional expression between "
641                            "pointer of type %<void *%> and "
642                            "pointer-to-function");
643                   break;
644                 default:
645                   gcc_unreachable ();
646                 }
647             }
648           else
649             return error_mark_node;
650         }
651       result_type
652         = cp_build_qualified_type (void_type_node,
653                                    (cp_type_quals (TREE_TYPE (t1))
654                                     | cp_type_quals (TREE_TYPE (t2))));
655       result_type = build_pointer_type (result_type);
656       /* Merge the attributes.  */
657       attributes = (*targetm.merge_type_attributes) (t1, t2);
658       return build_type_attribute_variant (result_type, attributes);
659     }
660
661   if (c_dialect_objc () && TYPE_PTR_P (t1)
662       && TYPE_PTR_P (t2))
663     {
664       if (objc_have_common_type (t1, t2, -3, NULL_TREE))
665         return objc_common_type (t1, t2);
666     }
667
668   /* [expr.eq] permits the application of a pointer conversion to
669      bring the pointers to a common type.  */
670   if (TYPE_PTR_P (t1) && TYPE_PTR_P (t2)
671       && CLASS_TYPE_P (TREE_TYPE (t1))
672       && CLASS_TYPE_P (TREE_TYPE (t2))
673       && !same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (t1),
674                                                      TREE_TYPE (t2)))
675     {
676       class1 = TREE_TYPE (t1);
677       class2 = TREE_TYPE (t2);
678
679       if (DERIVED_FROM_P (class1, class2))
680         t2 = (build_pointer_type
681               (cp_build_qualified_type (class1, cp_type_quals (class2))));
682       else if (DERIVED_FROM_P (class2, class1))
683         t1 = (build_pointer_type
684               (cp_build_qualified_type (class2, cp_type_quals (class1))));
685       else
686         {
687           if (complain & tf_error)
688             composite_pointer_error (DK_ERROR, t1, t2, operation);
689           return error_mark_node;
690         }
691     }
692   /* [expr.eq] permits the application of a pointer-to-member
693      conversion to change the class type of one of the types.  */
694   else if (TYPE_PTRMEM_P (t1)
695            && !same_type_p (TYPE_PTRMEM_CLASS_TYPE (t1),
696                             TYPE_PTRMEM_CLASS_TYPE (t2)))
697     {
698       class1 = TYPE_PTRMEM_CLASS_TYPE (t1);
699       class2 = TYPE_PTRMEM_CLASS_TYPE (t2);
700
701       if (DERIVED_FROM_P (class1, class2))
702         t1 = build_ptrmem_type (class2, TYPE_PTRMEM_POINTED_TO_TYPE (t1));
703       else if (DERIVED_FROM_P (class2, class1))
704         t2 = build_ptrmem_type (class1, TYPE_PTRMEM_POINTED_TO_TYPE (t2));
705       else
706         {
707           if (complain & tf_error)
708             switch (operation)
709               {
710               case CPO_COMPARISON:
711                 error ("comparison between distinct "
712                        "pointer-to-member types %qT and %qT lacks a cast",
713                        t1, t2);
714                 break;
715               case CPO_CONVERSION:
716                 error ("conversion between distinct "
717                        "pointer-to-member types %qT and %qT lacks a cast",
718                        t1, t2);
719                 break;
720               case CPO_CONDITIONAL_EXPR:
721                 error ("conditional expression between distinct "
722                        "pointer-to-member types %qT and %qT lacks a cast",
723                        t1, t2);
724                 break;
725               default:
726                 gcc_unreachable ();
727               }
728           return error_mark_node;
729         }
730     }
731
732   return composite_pointer_type_r (t1, t2, operation, complain);
733 }
734
735 /* Return the merged type of two types.
736    We assume that comptypes has already been done and returned 1;
737    if that isn't so, this may crash.
738
739    This just combines attributes and default arguments; any other
740    differences would cause the two types to compare unalike.  */
741
742 tree
743 merge_types (tree t1, tree t2)
744 {
745   enum tree_code code1;
746   enum tree_code code2;
747   tree attributes;
748
749   /* Save time if the two types are the same.  */
750   if (t1 == t2)
751     return t1;
752   if (original_type (t1) == original_type (t2))
753     return t1;
754
755   /* If one type is nonsense, use the other.  */
756   if (t1 == error_mark_node)
757     return t2;
758   if (t2 == error_mark_node)
759     return t1;
760
761   /* Handle merging an auto redeclaration with a previous deduced
762      return type.  */
763   if (is_auto (t1))
764     return t2;
765
766   /* Merge the attributes.  */
767   attributes = (*targetm.merge_type_attributes) (t1, t2);
768
769   if (TYPE_PTRMEMFUNC_P (t1))
770     t1 = TYPE_PTRMEMFUNC_FN_TYPE (t1);
771   if (TYPE_PTRMEMFUNC_P (t2))
772     t2 = TYPE_PTRMEMFUNC_FN_TYPE (t2);
773
774   code1 = TREE_CODE (t1);
775   code2 = TREE_CODE (t2);
776   if (code1 != code2)
777     {
778       gcc_assert (code1 == TYPENAME_TYPE || code2 == TYPENAME_TYPE);
779       if (code1 == TYPENAME_TYPE)
780         {
781           t1 = resolve_typename_type (t1, /*only_current_p=*/true);
782           code1 = TREE_CODE (t1);
783         }
784       else
785         {
786           t2 = resolve_typename_type (t2, /*only_current_p=*/true);
787           code2 = TREE_CODE (t2);
788         }
789     }
790
791   switch (code1)
792     {
793     case POINTER_TYPE:
794     case REFERENCE_TYPE:
795       /* For two pointers, do this recursively on the target type.  */
796       {
797         tree target = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
798         int quals = cp_type_quals (t1);
799
800         if (code1 == POINTER_TYPE)
801           t1 = build_pointer_type (target);
802         else
803           t1 = cp_build_reference_type (target, TYPE_REF_IS_RVALUE (t1));
804         t1 = build_type_attribute_variant (t1, attributes);
805         t1 = cp_build_qualified_type (t1, quals);
806
807         if (TREE_CODE (target) == METHOD_TYPE)
808           t1 = build_ptrmemfunc_type (t1);
809
810         return t1;
811       }
812
813     case OFFSET_TYPE:
814       {
815         int quals;
816         tree pointee;
817         quals = cp_type_quals (t1);
818         pointee = merge_types (TYPE_PTRMEM_POINTED_TO_TYPE (t1),
819                                TYPE_PTRMEM_POINTED_TO_TYPE (t2));
820         t1 = build_ptrmem_type (TYPE_PTRMEM_CLASS_TYPE (t1),
821                                 pointee);
822         t1 = cp_build_qualified_type (t1, quals);
823         break;
824       }
825
826     case ARRAY_TYPE:
827       {
828         tree elt = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
829         /* Save space: see if the result is identical to one of the args.  */
830         if (elt == TREE_TYPE (t1) && TYPE_DOMAIN (t1))
831           return build_type_attribute_variant (t1, attributes);
832         if (elt == TREE_TYPE (t2) && TYPE_DOMAIN (t2))
833           return build_type_attribute_variant (t2, attributes);
834         /* Merge the element types, and have a size if either arg has one.  */
835         t1 = build_cplus_array_type
836           (elt, TYPE_DOMAIN (TYPE_DOMAIN (t1) ? t1 : t2));
837         break;
838       }
839
840     case FUNCTION_TYPE:
841       /* Function types: prefer the one that specified arg types.
842          If both do, merge the arg types.  Also merge the return types.  */
843       {
844         tree valtype = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
845         tree p1 = TYPE_ARG_TYPES (t1);
846         tree p2 = TYPE_ARG_TYPES (t2);
847         tree parms;
848         tree rval, raises;
849         bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t1);
850
851         /* Save space: see if the result is identical to one of the args.  */
852         if (valtype == TREE_TYPE (t1) && ! p2)
853           return cp_build_type_attribute_variant (t1, attributes);
854         if (valtype == TREE_TYPE (t2) && ! p1)
855           return cp_build_type_attribute_variant (t2, attributes);
856
857         /* Simple way if one arg fails to specify argument types.  */
858         if (p1 == NULL_TREE || TREE_VALUE (p1) == void_type_node)
859           parms = p2;
860         else if (p2 == NULL_TREE || TREE_VALUE (p2) == void_type_node)
861           parms = p1;
862         else
863           parms = commonparms (p1, p2);
864
865         rval = build_function_type (valtype, parms);
866         gcc_assert (type_memfn_quals (t1) == type_memfn_quals (t2));
867         gcc_assert (type_memfn_rqual (t1) == type_memfn_rqual (t2));
868         rval = apply_memfn_quals (rval,
869                                   type_memfn_quals (t1),
870                                   type_memfn_rqual (t1));
871         raises = merge_exception_specifiers (TYPE_RAISES_EXCEPTIONS (t1),
872                                              TYPE_RAISES_EXCEPTIONS (t2));
873         t1 = build_exception_variant (rval, raises);
874         if (late_return_type_p)
875           TYPE_HAS_LATE_RETURN_TYPE (t1) = 1;
876         break;
877       }
878
879     case METHOD_TYPE:
880       {
881         /* Get this value the long way, since TYPE_METHOD_BASETYPE
882            is just the main variant of this.  */
883         tree basetype = class_of_this_parm (t2);
884         tree raises = merge_exception_specifiers (TYPE_RAISES_EXCEPTIONS (t1),
885                                                   TYPE_RAISES_EXCEPTIONS (t2));
886         cp_ref_qualifier rqual = type_memfn_rqual (t1);
887         tree t3;
888         bool late_return_type_1_p = TYPE_HAS_LATE_RETURN_TYPE (t1);
889         bool late_return_type_2_p = TYPE_HAS_LATE_RETURN_TYPE (t2);
890
891         /* If this was a member function type, get back to the
892            original type of type member function (i.e., without
893            the class instance variable up front.  */
894         t1 = build_function_type (TREE_TYPE (t1),
895                                   TREE_CHAIN (TYPE_ARG_TYPES (t1)));
896         t2 = build_function_type (TREE_TYPE (t2),
897                                   TREE_CHAIN (TYPE_ARG_TYPES (t2)));
898         t3 = merge_types (t1, t2);
899         t3 = build_method_type_directly (basetype, TREE_TYPE (t3),
900                                          TYPE_ARG_TYPES (t3));
901         t1 = build_exception_variant (t3, raises);
902         t1 = build_ref_qualified_type (t1, rqual);
903         if (late_return_type_1_p)
904           TYPE_HAS_LATE_RETURN_TYPE (t1) = 1;
905         if (late_return_type_2_p)
906           TYPE_HAS_LATE_RETURN_TYPE (t2) = 1;
907         break;
908       }
909
910     case TYPENAME_TYPE:
911       /* There is no need to merge attributes into a TYPENAME_TYPE.
912          When the type is instantiated it will have whatever
913          attributes result from the instantiation.  */
914       return t1;
915
916     default:;
917     }
918
919   if (attribute_list_equal (TYPE_ATTRIBUTES (t1), attributes))
920     return t1;
921   else if (attribute_list_equal (TYPE_ATTRIBUTES (t2), attributes))
922     return t2;
923   else
924     return cp_build_type_attribute_variant (t1, attributes);
925 }
926
927 /* Return the ARRAY_TYPE type without its domain.  */
928
929 tree
930 strip_array_domain (tree type)
931 {
932   tree t2;
933   gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
934   if (TYPE_DOMAIN (type) == NULL_TREE)
935     return type;
936   t2 = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
937   return cp_build_type_attribute_variant (t2, TYPE_ATTRIBUTES (type));
938 }
939
940 /* Wrapper around cp_common_type that is used by c-common.c and other
941    front end optimizations that remove promotions.  
942
943    Return the common type for two arithmetic types T1 and T2 under the
944    usual arithmetic conversions.  The default conversions have already
945    been applied, and enumerated types converted to their compatible
946    integer types.  */
947
948 tree
949 common_type (tree t1, tree t2)
950 {
951   /* If one type is nonsense, use the other  */
952   if (t1 == error_mark_node)
953     return t2;
954   if (t2 == error_mark_node)
955     return t1;
956
957   return cp_common_type (t1, t2);
958 }
959
960 /* Return the common type of two pointer types T1 and T2.  This is the
961    type for the result of most arithmetic operations if the operands
962    have the given two types.
963  
964    We assume that comp_target_types has already been done and returned
965    nonzero; if that isn't so, this may crash.  */
966
967 tree
968 common_pointer_type (tree t1, tree t2)
969 {
970   gcc_assert ((TYPE_PTR_P (t1) && TYPE_PTR_P (t2))
971               || (TYPE_PTRDATAMEM_P (t1) && TYPE_PTRDATAMEM_P (t2))
972               || (TYPE_PTRMEMFUNC_P (t1) && TYPE_PTRMEMFUNC_P (t2)));
973
974   return composite_pointer_type (t1, t2, error_mark_node, error_mark_node,
975                                  CPO_CONVERSION, tf_warning_or_error);
976 }
977 \f
978 /* Compare two exception specifier types for exactness or subsetness, if
979    allowed. Returns false for mismatch, true for match (same, or
980    derived and !exact).
981
982    [except.spec] "If a class X ... objects of class X or any class publicly
983    and unambiguously derived from X. Similarly, if a pointer type Y * ...
984    exceptions of type Y * or that are pointers to any type publicly and
985    unambiguously derived from Y. Otherwise a function only allows exceptions
986    that have the same type ..."
987    This does not mention cv qualifiers and is different to what throw
988    [except.throw] and catch [except.catch] will do. They will ignore the
989    top level cv qualifiers, and allow qualifiers in the pointer to class
990    example.
991
992    We implement the letter of the standard.  */
993
994 static bool
995 comp_except_types (tree a, tree b, bool exact)
996 {
997   if (same_type_p (a, b))
998     return true;
999   else if (!exact)
1000     {
1001       if (cp_type_quals (a) || cp_type_quals (b))
1002         return false;
1003
1004       if (TYPE_PTR_P (a) && TYPE_PTR_P (b))
1005         {
1006           a = TREE_TYPE (a);
1007           b = TREE_TYPE (b);
1008           if (cp_type_quals (a) || cp_type_quals (b))
1009             return false;
1010         }
1011
1012       if (TREE_CODE (a) != RECORD_TYPE
1013           || TREE_CODE (b) != RECORD_TYPE)
1014         return false;
1015
1016       if (publicly_uniquely_derived_p (a, b))
1017         return true;
1018     }
1019   return false;
1020 }
1021
1022 /* Return true if TYPE1 and TYPE2 are equivalent exception specifiers.
1023    If EXACT is ce_derived, T2 can be stricter than T1 (according to 15.4/5).
1024    If EXACT is ce_normal, the compatibility rules in 15.4/3 apply.
1025    If EXACT is ce_exact, the specs must be exactly the same. Exception lists
1026    are unordered, but we've already filtered out duplicates. Most lists will
1027    be in order, we should try to make use of that.  */
1028
1029 bool
1030 comp_except_specs (const_tree t1, const_tree t2, int exact)
1031 {
1032   const_tree probe;
1033   const_tree base;
1034   int  length = 0;
1035
1036   if (t1 == t2)
1037     return true;
1038
1039   /* First handle noexcept.  */
1040   if (exact < ce_exact)
1041     {
1042       /* noexcept(false) is compatible with no exception-specification,
1043          and stricter than any spec.  */
1044       if (t1 == noexcept_false_spec)
1045         return t2 == NULL_TREE || exact == ce_derived;
1046       /* Even a derived noexcept(false) is compatible with no
1047          exception-specification.  */
1048       if (t2 == noexcept_false_spec)
1049         return t1 == NULL_TREE;
1050
1051       /* Otherwise, if we aren't looking for an exact match, noexcept is
1052          equivalent to throw().  */
1053       if (t1 == noexcept_true_spec)
1054         t1 = empty_except_spec;
1055       if (t2 == noexcept_true_spec)
1056         t2 = empty_except_spec;
1057     }
1058
1059   /* If any noexcept is left, it is only comparable to itself;
1060      either we're looking for an exact match or we're redeclaring a
1061      template with dependent noexcept.  */
1062   if ((t1 && TREE_PURPOSE (t1))
1063       || (t2 && TREE_PURPOSE (t2)))
1064     return (t1 && t2
1065             && cp_tree_equal (TREE_PURPOSE (t1), TREE_PURPOSE (t2)));
1066
1067   if (t1 == NULL_TREE)                     /* T1 is ...  */
1068     return t2 == NULL_TREE || exact == ce_derived;
1069   if (!TREE_VALUE (t1))                    /* t1 is EMPTY */
1070     return t2 != NULL_TREE && !TREE_VALUE (t2);
1071   if (t2 == NULL_TREE)                     /* T2 is ...  */
1072     return false;
1073   if (TREE_VALUE (t1) && !TREE_VALUE (t2)) /* T2 is EMPTY, T1 is not */
1074     return exact == ce_derived;
1075
1076   /* Neither set is ... or EMPTY, make sure each part of T2 is in T1.
1077      Count how many we find, to determine exactness. For exact matching and
1078      ordered T1, T2, this is an O(n) operation, otherwise its worst case is
1079      O(nm).  */
1080   for (base = t1; t2 != NULL_TREE; t2 = TREE_CHAIN (t2))
1081     {
1082       for (probe = base; probe != NULL_TREE; probe = TREE_CHAIN (probe))
1083         {
1084           tree a = TREE_VALUE (probe);
1085           tree b = TREE_VALUE (t2);
1086
1087           if (comp_except_types (a, b, exact))
1088             {
1089               if (probe == base && exact > ce_derived)
1090                 base = TREE_CHAIN (probe);
1091               length++;
1092               break;
1093             }
1094         }
1095       if (probe == NULL_TREE)
1096         return false;
1097     }
1098   return exact == ce_derived || base == NULL_TREE || length == list_length (t1);
1099 }
1100
1101 /* Compare the array types T1 and T2.  ALLOW_REDECLARATION is true if
1102    [] can match [size].  */
1103
1104 static bool
1105 comp_array_types (const_tree t1, const_tree t2, bool allow_redeclaration)
1106 {
1107   tree d1;
1108   tree d2;
1109   tree max1, max2;
1110
1111   if (t1 == t2)
1112     return true;
1113
1114   /* The type of the array elements must be the same.  */
1115   if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1116     return false;
1117
1118   d1 = TYPE_DOMAIN (t1);
1119   d2 = TYPE_DOMAIN (t2);
1120
1121   if (d1 == d2)
1122     return true;
1123
1124   /* If one of the arrays is dimensionless, and the other has a
1125      dimension, they are of different types.  However, it is valid to
1126      write:
1127
1128        extern int a[];
1129        int a[3];
1130
1131      by [basic.link]:
1132
1133        declarations for an array object can specify
1134        array types that differ by the presence or absence of a major
1135        array bound (_dcl.array_).  */
1136   if (!d1 || !d2)
1137     return allow_redeclaration;
1138
1139   /* Check that the dimensions are the same.  */
1140
1141   if (!cp_tree_equal (TYPE_MIN_VALUE (d1), TYPE_MIN_VALUE (d2)))
1142     return false;
1143   max1 = TYPE_MAX_VALUE (d1);
1144   max2 = TYPE_MAX_VALUE (d2);
1145
1146   if (!cp_tree_equal (max1, max2))
1147     return false;
1148
1149   return true;
1150 }
1151
1152 /* Compare the relative position of T1 and T2 into their respective
1153    template parameter list.
1154    T1 and T2 must be template parameter types.
1155    Return TRUE if T1 and T2 have the same position, FALSE otherwise.  */
1156
1157 static bool
1158 comp_template_parms_position (tree t1, tree t2)
1159 {
1160   tree index1, index2;
1161   gcc_assert (t1 && t2
1162               && TREE_CODE (t1) == TREE_CODE (t2)
1163               && (TREE_CODE (t1) == BOUND_TEMPLATE_TEMPLATE_PARM
1164                   || TREE_CODE (t1) == TEMPLATE_TEMPLATE_PARM
1165                   || TREE_CODE (t1) == TEMPLATE_TYPE_PARM));
1166
1167   index1 = TEMPLATE_TYPE_PARM_INDEX (TYPE_MAIN_VARIANT (t1));
1168   index2 = TEMPLATE_TYPE_PARM_INDEX (TYPE_MAIN_VARIANT (t2));
1169
1170   /* Then compare their relative position.  */
1171   if (TEMPLATE_PARM_IDX (index1) != TEMPLATE_PARM_IDX (index2)
1172       || TEMPLATE_PARM_LEVEL (index1) != TEMPLATE_PARM_LEVEL (index2)
1173       || (TEMPLATE_PARM_PARAMETER_PACK (index1)
1174           != TEMPLATE_PARM_PARAMETER_PACK (index2)))
1175     return false;
1176
1177   /* In C++14 we can end up comparing 'auto' to a normal template
1178      parameter.  Don't confuse them.  */
1179   if (cxx_dialect >= cxx14 && (is_auto (t1) || is_auto (t2)))
1180     return TYPE_IDENTIFIER (t1) == TYPE_IDENTIFIER (t2);
1181
1182   return true;
1183 }
1184
1185 /* Subroutine in comptypes.  */
1186
1187 static bool
1188 structural_comptypes (tree t1, tree t2, int strict)
1189 {
1190   if (t1 == t2)
1191     return true;
1192
1193   /* Suppress errors caused by previously reported errors.  */
1194   if (t1 == error_mark_node || t2 == error_mark_node)
1195     return false;
1196
1197   gcc_assert (TYPE_P (t1) && TYPE_P (t2));
1198
1199   /* TYPENAME_TYPEs should be resolved if the qualifying scope is the
1200      current instantiation.  */
1201   if (TREE_CODE (t1) == TYPENAME_TYPE)
1202     t1 = resolve_typename_type (t1, /*only_current_p=*/true);
1203
1204   if (TREE_CODE (t2) == TYPENAME_TYPE)
1205     t2 = resolve_typename_type (t2, /*only_current_p=*/true);
1206
1207   if (TYPE_PTRMEMFUNC_P (t1))
1208     t1 = TYPE_PTRMEMFUNC_FN_TYPE (t1);
1209   if (TYPE_PTRMEMFUNC_P (t2))
1210     t2 = TYPE_PTRMEMFUNC_FN_TYPE (t2);
1211
1212   /* Different classes of types can't be compatible.  */
1213   if (TREE_CODE (t1) != TREE_CODE (t2))
1214     return false;
1215
1216   /* Qualifiers must match.  For array types, we will check when we
1217      recur on the array element types.  */
1218   if (TREE_CODE (t1) != ARRAY_TYPE
1219       && cp_type_quals (t1) != cp_type_quals (t2))
1220     return false;
1221   if (TREE_CODE (t1) == FUNCTION_TYPE
1222       && type_memfn_quals (t1) != type_memfn_quals (t2))
1223     return false;
1224   /* Need to check this before TYPE_MAIN_VARIANT.
1225      FIXME function qualifiers should really change the main variant.  */
1226   if ((TREE_CODE (t1) == FUNCTION_TYPE
1227        || TREE_CODE (t1) == METHOD_TYPE)
1228       && type_memfn_rqual (t1) != type_memfn_rqual (t2))
1229     return false;
1230   if (TYPE_FOR_JAVA (t1) != TYPE_FOR_JAVA (t2))
1231     return false;
1232
1233   /* Allow for two different type nodes which have essentially the same
1234      definition.  Note that we already checked for equality of the type
1235      qualifiers (just above).  */
1236
1237   if (TREE_CODE (t1) != ARRAY_TYPE
1238       && TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
1239     return true;
1240
1241
1242   /* Compare the types.  Break out if they could be the same.  */
1243   switch (TREE_CODE (t1))
1244     {
1245     case VOID_TYPE:
1246     case BOOLEAN_TYPE:
1247       /* All void and bool types are the same.  */
1248       break;
1249
1250     case INTEGER_TYPE:
1251     case FIXED_POINT_TYPE:
1252     case REAL_TYPE:
1253       /* With these nodes, we can't determine type equivalence by
1254          looking at what is stored in the nodes themselves, because
1255          two nodes might have different TYPE_MAIN_VARIANTs but still
1256          represent the same type.  For example, wchar_t and int could
1257          have the same properties (TYPE_PRECISION, TYPE_MIN_VALUE,
1258          TYPE_MAX_VALUE, etc.), but have different TYPE_MAIN_VARIANTs
1259          and are distinct types. On the other hand, int and the
1260          following typedef
1261
1262            typedef int INT __attribute((may_alias));
1263
1264          have identical properties, different TYPE_MAIN_VARIANTs, but
1265          represent the same type.  The canonical type system keeps
1266          track of equivalence in this case, so we fall back on it.  */
1267       return TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2);
1268
1269     case TEMPLATE_TEMPLATE_PARM:
1270     case BOUND_TEMPLATE_TEMPLATE_PARM:
1271       if (!comp_template_parms_position (t1, t2))
1272         return false;
1273       if (!comp_template_parms
1274           (DECL_TEMPLATE_PARMS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t1)),
1275            DECL_TEMPLATE_PARMS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t2))))
1276         return false;
1277       if (TREE_CODE (t1) == TEMPLATE_TEMPLATE_PARM)
1278         break;
1279       /* Don't check inheritance.  */
1280       strict = COMPARE_STRICT;
1281       /* Fall through.  */
1282
1283     case RECORD_TYPE:
1284     case UNION_TYPE:
1285       if (TYPE_TEMPLATE_INFO (t1) && TYPE_TEMPLATE_INFO (t2)
1286           && (TYPE_TI_TEMPLATE (t1) == TYPE_TI_TEMPLATE (t2)
1287               || TREE_CODE (t1) == BOUND_TEMPLATE_TEMPLATE_PARM)
1288           && comp_template_args (TYPE_TI_ARGS (t1), TYPE_TI_ARGS (t2)))
1289         break;
1290
1291       if ((strict & COMPARE_BASE) && DERIVED_FROM_P (t1, t2))
1292         break;
1293       else if ((strict & COMPARE_DERIVED) && DERIVED_FROM_P (t2, t1))
1294         break;
1295
1296       return false;
1297
1298     case OFFSET_TYPE:
1299       if (!comptypes (TYPE_OFFSET_BASETYPE (t1), TYPE_OFFSET_BASETYPE (t2),
1300                       strict & ~COMPARE_REDECLARATION))
1301         return false;
1302       if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1303         return false;
1304       break;
1305
1306     case REFERENCE_TYPE:
1307       if (TYPE_REF_IS_RVALUE (t1) != TYPE_REF_IS_RVALUE (t2))
1308         return false;
1309       /* fall through to checks for pointer types */
1310
1311     case POINTER_TYPE:
1312       if (TYPE_MODE (t1) != TYPE_MODE (t2)
1313           || TYPE_REF_CAN_ALIAS_ALL (t1) != TYPE_REF_CAN_ALIAS_ALL (t2)
1314           || !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1315         return false;
1316       break;
1317
1318     case METHOD_TYPE:
1319     case FUNCTION_TYPE:
1320       if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1321         return false;
1322       if (!compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2)))
1323         return false;
1324       break;
1325
1326     case ARRAY_TYPE:
1327       /* Target types must match incl. qualifiers.  */
1328       if (!comp_array_types (t1, t2, !!(strict & COMPARE_REDECLARATION)))
1329         return false;
1330       break;
1331
1332     case TEMPLATE_TYPE_PARM:
1333       /* If T1 and T2 don't have the same relative position in their
1334          template parameters set, they can't be equal.  */
1335       if (!comp_template_parms_position (t1, t2))
1336         return false;
1337       break;
1338
1339     case TYPENAME_TYPE:
1340       if (!cp_tree_equal (TYPENAME_TYPE_FULLNAME (t1),
1341                           TYPENAME_TYPE_FULLNAME (t2)))
1342         return false;
1343       /* Qualifiers don't matter on scopes.  */
1344       if (!same_type_ignoring_top_level_qualifiers_p (TYPE_CONTEXT (t1),
1345                                                       TYPE_CONTEXT (t2)))
1346         return false;
1347       break;
1348
1349     case UNBOUND_CLASS_TEMPLATE:
1350       if (!cp_tree_equal (TYPE_IDENTIFIER (t1), TYPE_IDENTIFIER (t2)))
1351         return false;
1352       if (!same_type_p (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2)))
1353         return false;
1354       break;
1355
1356     case COMPLEX_TYPE:
1357       if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1358         return false;
1359       break;
1360
1361     case VECTOR_TYPE:
1362       if (TYPE_VECTOR_SUBPARTS (t1) != TYPE_VECTOR_SUBPARTS (t2)
1363           || !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1364         return false;
1365       break;
1366
1367     case TYPE_PACK_EXPANSION:
1368       return (same_type_p (PACK_EXPANSION_PATTERN (t1),
1369                            PACK_EXPANSION_PATTERN (t2))
1370               && comp_template_args (PACK_EXPANSION_EXTRA_ARGS (t1),
1371                                      PACK_EXPANSION_EXTRA_ARGS (t2)));
1372
1373     case DECLTYPE_TYPE:
1374       if (DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t1)
1375           != DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t2)
1376           || (DECLTYPE_FOR_LAMBDA_CAPTURE (t1)
1377               != DECLTYPE_FOR_LAMBDA_CAPTURE (t2))
1378           || (DECLTYPE_FOR_LAMBDA_PROXY (t1)
1379               != DECLTYPE_FOR_LAMBDA_PROXY (t2))
1380           || !cp_tree_equal (DECLTYPE_TYPE_EXPR (t1), 
1381                              DECLTYPE_TYPE_EXPR (t2)))
1382         return false;
1383       break;
1384
1385     case UNDERLYING_TYPE:
1386       return same_type_p (UNDERLYING_TYPE_TYPE (t1), 
1387                           UNDERLYING_TYPE_TYPE (t2));
1388
1389     default:
1390       return false;
1391     }
1392
1393   /* If we get here, we know that from a target independent POV the
1394      types are the same.  Make sure the target attributes are also
1395      the same.  */
1396   return comp_type_attributes (t1, t2);
1397 }
1398
1399 /* Return true if T1 and T2 are related as allowed by STRICT.  STRICT
1400    is a bitwise-or of the COMPARE_* flags.  */
1401
1402 bool
1403 comptypes (tree t1, tree t2, int strict)
1404 {
1405   if (strict == COMPARE_STRICT)
1406     {
1407       if (t1 == t2)
1408         return true;
1409
1410       if (t1 == error_mark_node || t2 == error_mark_node)
1411         return false;
1412
1413       if (TYPE_STRUCTURAL_EQUALITY_P (t1) || TYPE_STRUCTURAL_EQUALITY_P (t2))
1414         /* At least one of the types requires structural equality, so
1415            perform a deep check. */
1416         return structural_comptypes (t1, t2, strict);
1417
1418 #ifdef ENABLE_CHECKING
1419       if (USE_CANONICAL_TYPES)
1420         {
1421           bool result = structural_comptypes (t1, t2, strict);
1422           
1423           if (result && TYPE_CANONICAL (t1) != TYPE_CANONICAL (t2))
1424             /* The two types are structurally equivalent, but their
1425                canonical types were different. This is a failure of the
1426                canonical type propagation code.*/
1427             internal_error 
1428               ("canonical types differ for identical types %T and %T", 
1429                t1, t2);
1430           else if (!result && TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2))
1431             /* Two types are structurally different, but the canonical
1432                types are the same. This means we were over-eager in
1433                assigning canonical types. */
1434             internal_error 
1435               ("same canonical type node for different types %T and %T",
1436                t1, t2);
1437           
1438           return result;
1439         }
1440 #else
1441       if (USE_CANONICAL_TYPES)
1442         return TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2);
1443 #endif
1444       else
1445         return structural_comptypes (t1, t2, strict);
1446     }
1447   else if (strict == COMPARE_STRUCTURAL)
1448     return structural_comptypes (t1, t2, COMPARE_STRICT);
1449   else
1450     return structural_comptypes (t1, t2, strict);
1451 }
1452
1453 /* Returns nonzero iff TYPE1 and TYPE2 are the same type, ignoring
1454    top-level qualifiers.  */
1455
1456 bool
1457 same_type_ignoring_top_level_qualifiers_p (tree type1, tree type2)
1458 {
1459   if (type1 == error_mark_node || type2 == error_mark_node)
1460     return false;
1461
1462   return same_type_p (TYPE_MAIN_VARIANT (type1), TYPE_MAIN_VARIANT (type2));
1463 }
1464
1465 /* Returns 1 if TYPE1 is at least as qualified as TYPE2.  */
1466
1467 bool
1468 at_least_as_qualified_p (const_tree type1, const_tree type2)
1469 {
1470   int q1 = cp_type_quals (type1);
1471   int q2 = cp_type_quals (type2);
1472
1473   /* All qualifiers for TYPE2 must also appear in TYPE1.  */
1474   return (q1 & q2) == q2;
1475 }
1476
1477 /* Returns 1 if TYPE1 is more cv-qualified than TYPE2, -1 if TYPE2 is
1478    more cv-qualified that TYPE1, and 0 otherwise.  */
1479
1480 int
1481 comp_cv_qualification (int q1, int q2)
1482 {
1483   if (q1 == q2)
1484     return 0;
1485
1486   if ((q1 & q2) == q2)
1487     return 1;
1488   else if ((q1 & q2) == q1)
1489     return -1;
1490
1491   return 0;
1492 }
1493
1494 int
1495 comp_cv_qualification (const_tree type1, const_tree type2)
1496 {
1497   int q1 = cp_type_quals (type1);
1498   int q2 = cp_type_quals (type2);
1499   return comp_cv_qualification (q1, q2);
1500 }
1501
1502 /* Returns 1 if the cv-qualification signature of TYPE1 is a proper
1503    subset of the cv-qualification signature of TYPE2, and the types
1504    are similar.  Returns -1 if the other way 'round, and 0 otherwise.  */
1505
1506 int
1507 comp_cv_qual_signature (tree type1, tree type2)
1508 {
1509   if (comp_ptr_ttypes_real (type2, type1, -1))
1510     return 1;
1511   else if (comp_ptr_ttypes_real (type1, type2, -1))
1512     return -1;
1513   else
1514     return 0;
1515 }
1516 \f
1517 /* Subroutines of `comptypes'.  */
1518
1519 /* Return true if two parameter type lists PARMS1 and PARMS2 are
1520    equivalent in the sense that functions with those parameter types
1521    can have equivalent types.  The two lists must be equivalent,
1522    element by element.  */
1523
1524 bool
1525 compparms (const_tree parms1, const_tree parms2)
1526 {
1527   const_tree t1, t2;
1528
1529   /* An unspecified parmlist matches any specified parmlist
1530      whose argument types don't need default promotions.  */
1531
1532   for (t1 = parms1, t2 = parms2;
1533        t1 || t2;
1534        t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1535     {
1536       /* If one parmlist is shorter than the other,
1537          they fail to match.  */
1538       if (!t1 || !t2)
1539         return false;
1540       if (!same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1541         return false;
1542     }
1543   return true;
1544 }
1545
1546 \f
1547 /* Process a sizeof or alignof expression where the operand is a
1548    type.  */
1549
1550 tree
1551 cxx_sizeof_or_alignof_type (tree type, enum tree_code op, bool complain)
1552 {
1553   tree value;
1554   bool dependent_p;
1555
1556   gcc_assert (op == SIZEOF_EXPR || op == ALIGNOF_EXPR);
1557   if (type == error_mark_node)
1558     return error_mark_node;
1559
1560   type = non_reference (type);
1561   if (TREE_CODE (type) == METHOD_TYPE)
1562     {
1563       if (complain)
1564         pedwarn (input_location, OPT_Wpointer_arith, 
1565                  "invalid application of %qs to a member function", 
1566                  operator_name_info[(int) op].name);
1567       else
1568         return error_mark_node;
1569       value = size_one_node;
1570     }
1571
1572   dependent_p = dependent_type_p (type);
1573   if (!dependent_p)
1574     complete_type (type);
1575   if (dependent_p
1576       /* VLA types will have a non-constant size.  In the body of an
1577          uninstantiated template, we don't need to try to compute the
1578          value, because the sizeof expression is not an integral
1579          constant expression in that case.  And, if we do try to
1580          compute the value, we'll likely end up with SAVE_EXPRs, which
1581          the template substitution machinery does not expect to see.  */
1582       || (processing_template_decl 
1583           && COMPLETE_TYPE_P (type)
1584           && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
1585     {
1586       value = build_min (op, size_type_node, type);
1587       TREE_READONLY (value) = 1;
1588       return value;
1589     }
1590
1591   return c_sizeof_or_alignof_type (input_location, complete_type (type),
1592                                    op == SIZEOF_EXPR, false,
1593                                    complain);
1594 }
1595
1596 /* Return the size of the type, without producing any warnings for
1597    types whose size cannot be taken.  This routine should be used only
1598    in some other routine that has already produced a diagnostic about
1599    using the size of such a type.  */
1600 tree 
1601 cxx_sizeof_nowarn (tree type)
1602 {
1603   if (TREE_CODE (type) == FUNCTION_TYPE
1604       || VOID_TYPE_P (type)
1605       || TREE_CODE (type) == ERROR_MARK)
1606     return size_one_node;
1607   else if (!COMPLETE_TYPE_P (type))
1608     return size_zero_node;
1609   else
1610     return cxx_sizeof_or_alignof_type (type, SIZEOF_EXPR, false);
1611 }
1612
1613 /* Process a sizeof expression where the operand is an expression.  */
1614
1615 static tree
1616 cxx_sizeof_expr (tree e, tsubst_flags_t complain)
1617 {
1618   if (e == error_mark_node)
1619     return error_mark_node;
1620
1621   if (processing_template_decl)
1622     {
1623       e = build_min (SIZEOF_EXPR, size_type_node, e);
1624       TREE_SIDE_EFFECTS (e) = 0;
1625       TREE_READONLY (e) = 1;
1626
1627       return e;
1628     }
1629
1630   /* To get the size of a static data member declared as an array of
1631      unknown bound, we need to instantiate it.  */
1632   if (VAR_P (e)
1633       && VAR_HAD_UNKNOWN_BOUND (e)
1634       && DECL_TEMPLATE_INSTANTIATION (e))
1635     instantiate_decl (e, /*defer_ok*/true, /*expl_inst_mem*/false);
1636
1637   if (TREE_CODE (e) == PARM_DECL
1638       && DECL_ARRAY_PARAMETER_P (e)
1639       && (complain & tf_warning))
1640     {
1641       if (warning (OPT_Wsizeof_array_argument, "%<sizeof%> on array function "
1642                    "parameter %qE will return size of %qT", e, TREE_TYPE (e)))
1643         inform (DECL_SOURCE_LOCATION (e), "declared here");
1644     }
1645
1646   e = mark_type_use (e);
1647
1648   if (TREE_CODE (e) == COMPONENT_REF
1649       && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL
1650       && DECL_C_BIT_FIELD (TREE_OPERAND (e, 1)))
1651     {
1652       if (complain & tf_error)
1653         error ("invalid application of %<sizeof%> to a bit-field");
1654       else
1655         return error_mark_node;
1656       e = char_type_node;
1657     }
1658   else if (is_overloaded_fn (e))
1659     {
1660       if (complain & tf_error)
1661         permerror (input_location, "ISO C++ forbids applying %<sizeof%> to an expression of "
1662                    "function type");
1663       else
1664         return error_mark_node;
1665       e = char_type_node;
1666     }
1667   else if (type_unknown_p (e))
1668     {
1669       if (complain & tf_error)
1670         cxx_incomplete_type_error (e, TREE_TYPE (e));
1671       else
1672         return error_mark_node;
1673       e = char_type_node;
1674     }
1675   else
1676     e = TREE_TYPE (e);
1677
1678   return cxx_sizeof_or_alignof_type (e, SIZEOF_EXPR, complain & tf_error);
1679 }
1680
1681 /* Implement the __alignof keyword: Return the minimum required
1682    alignment of E, measured in bytes.  For VAR_DECL's and
1683    FIELD_DECL's return DECL_ALIGN (which can be set from an
1684    "aligned" __attribute__ specification).  */
1685
1686 static tree
1687 cxx_alignof_expr (tree e, tsubst_flags_t complain)
1688 {
1689   tree t;
1690
1691   if (e == error_mark_node)
1692     return error_mark_node;
1693
1694   if (processing_template_decl)
1695     {
1696       e = build_min (ALIGNOF_EXPR, size_type_node, e);
1697       TREE_SIDE_EFFECTS (e) = 0;
1698       TREE_READONLY (e) = 1;
1699
1700       return e;
1701     }
1702
1703   e = mark_type_use (e);
1704
1705   if (VAR_P (e))
1706     t = size_int (DECL_ALIGN_UNIT (e));
1707   else if (TREE_CODE (e) == COMPONENT_REF
1708            && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL
1709            && DECL_C_BIT_FIELD (TREE_OPERAND (e, 1)))
1710     {
1711       if (complain & tf_error)
1712         error ("invalid application of %<__alignof%> to a bit-field");
1713       else
1714         return error_mark_node;
1715       t = size_one_node;
1716     }
1717   else if (TREE_CODE (e) == COMPONENT_REF
1718            && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL)
1719     t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (e, 1)));
1720   else if (is_overloaded_fn (e))
1721     {
1722       if (complain & tf_error)
1723         permerror (input_location, "ISO C++ forbids applying %<__alignof%> to an expression of "
1724                    "function type");
1725       else
1726         return error_mark_node;
1727       if (TREE_CODE (e) == FUNCTION_DECL)
1728         t = size_int (DECL_ALIGN_UNIT (e));
1729       else
1730         t = size_one_node;
1731     }
1732   else if (type_unknown_p (e))
1733     {
1734       if (complain & tf_error)
1735         cxx_incomplete_type_error (e, TREE_TYPE (e));
1736       else
1737         return error_mark_node;
1738       t = size_one_node;
1739     }
1740   else
1741     return cxx_sizeof_or_alignof_type (TREE_TYPE (e), ALIGNOF_EXPR, 
1742                                        complain & tf_error);
1743
1744   return fold_convert (size_type_node, t);
1745 }
1746
1747 /* Process a sizeof or alignof expression E with code OP where the operand
1748    is an expression.  */
1749
1750 tree
1751 cxx_sizeof_or_alignof_expr (tree e, enum tree_code op, bool complain)
1752 {
1753   if (op == SIZEOF_EXPR)
1754     return cxx_sizeof_expr (e, complain? tf_warning_or_error : tf_none);
1755   else
1756     return cxx_alignof_expr (e, complain? tf_warning_or_error : tf_none);
1757 }
1758
1759 /*  Build a representation of an expression 'alignas(E).'  Return the
1760     folded integer value of E if it is an integral constant expression
1761     that resolves to a valid alignment.  If E depends on a template
1762     parameter, return a syntactic representation tree of kind
1763     ALIGNOF_EXPR.  Otherwise, return an error_mark_node if the
1764     expression is ill formed, or NULL_TREE if E is NULL_TREE.  */
1765
1766 tree
1767 cxx_alignas_expr (tree e)
1768 {
1769   if (e == NULL_TREE || e == error_mark_node
1770       || (!TYPE_P (e) && !require_potential_rvalue_constant_expression (e)))
1771     return e;
1772   
1773   if (TYPE_P (e))
1774     /* [dcl.align]/3:
1775        
1776            When the alignment-specifier is of the form
1777            alignas(type-id ), it shall have the same effect as
1778            alignas(alignof(type-id )).  */
1779
1780     return cxx_sizeof_or_alignof_type (e, ALIGNOF_EXPR, false);
1781   
1782   /* If we reach this point, it means the alignas expression if of
1783      the form "alignas(assignment-expression)", so we should follow
1784      what is stated by [dcl.align]/2.  */
1785
1786   if (value_dependent_expression_p (e))
1787     /* Leave value-dependent expression alone for now. */
1788     return e;
1789
1790   e = instantiate_non_dependent_expr (e);
1791   e = mark_rvalue_use (e);
1792
1793   /* [dcl.align]/2 says:
1794
1795          the assignment-expression shall be an integral constant
1796          expression.  */
1797   
1798   return cxx_constant_value (e);
1799 }
1800
1801 \f
1802 /* EXPR is being used in a context that is not a function call.
1803    Enforce:
1804
1805      [expr.ref]
1806
1807      The expression can be used only as the left-hand operand of a
1808      member function call.
1809
1810      [expr.mptr.operator]
1811
1812      If the result of .* or ->* is a function, then that result can be
1813      used only as the operand for the function call operator ().
1814
1815    by issuing an error message if appropriate.  Returns true iff EXPR
1816    violates these rules.  */
1817
1818 bool
1819 invalid_nonstatic_memfn_p (tree expr, tsubst_flags_t complain)
1820 {
1821   if (expr == NULL_TREE)
1822     return false;
1823   /* Don't enforce this in MS mode.  */
1824   if (flag_ms_extensions)
1825     return false;
1826   if (is_overloaded_fn (expr) && !really_overloaded_fn (expr))
1827     expr = get_first_fn (expr);
1828   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (expr))
1829     {
1830       if (complain & tf_error)
1831         error ("invalid use of non-static member function");
1832       return true;
1833     }
1834   return false;
1835 }
1836
1837 /* If EXP is a reference to a bitfield, and the type of EXP does not
1838    match the declared type of the bitfield, return the declared type
1839    of the bitfield.  Otherwise, return NULL_TREE.  */
1840
1841 tree
1842 is_bitfield_expr_with_lowered_type (const_tree exp)
1843 {
1844   switch (TREE_CODE (exp))
1845     {
1846     case COND_EXPR:
1847       if (!is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 1)
1848                                                ? TREE_OPERAND (exp, 1)
1849                                                : TREE_OPERAND (exp, 0)))
1850         return NULL_TREE;
1851       return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 2));
1852
1853     case COMPOUND_EXPR:
1854       return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 1));
1855
1856     case MODIFY_EXPR:
1857     case SAVE_EXPR:
1858       return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 0));
1859
1860     case COMPONENT_REF:
1861       {
1862         tree field;
1863         
1864         field = TREE_OPERAND (exp, 1);
1865         if (TREE_CODE (field) != FIELD_DECL || !DECL_BIT_FIELD_TYPE (field))
1866           return NULL_TREE;
1867         if (same_type_ignoring_top_level_qualifiers_p
1868             (TREE_TYPE (exp), DECL_BIT_FIELD_TYPE (field)))
1869           return NULL_TREE;
1870         return DECL_BIT_FIELD_TYPE (field);
1871       }
1872
1873     CASE_CONVERT:
1874       if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (exp, 0)))
1875           == TYPE_MAIN_VARIANT (TREE_TYPE (exp)))
1876         return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 0));
1877       /* Fallthrough.  */
1878
1879     default:
1880       return NULL_TREE;
1881     }
1882 }
1883
1884 /* Like is_bitfield_with_lowered_type, except that if EXP is not a
1885    bitfield with a lowered type, the type of EXP is returned, rather
1886    than NULL_TREE.  */
1887
1888 tree
1889 unlowered_expr_type (const_tree exp)
1890 {
1891   tree type;
1892   tree etype = TREE_TYPE (exp);
1893
1894   type = is_bitfield_expr_with_lowered_type (exp);
1895   if (type)
1896     type = cp_build_qualified_type (type, cp_type_quals (etype));
1897   else
1898     type = etype;
1899
1900   return type;
1901 }
1902
1903 /* Perform the conversions in [expr] that apply when an lvalue appears
1904    in an rvalue context: the lvalue-to-rvalue, array-to-pointer, and
1905    function-to-pointer conversions.  In addition, manifest constants
1906    are replaced by their values, and bitfield references are converted
1907    to their declared types. Note that this function does not perform the
1908    lvalue-to-rvalue conversion for class types. If you need that conversion
1909    to for class types, then you probably need to use force_rvalue.
1910
1911    Although the returned value is being used as an rvalue, this
1912    function does not wrap the returned expression in a
1913    NON_LVALUE_EXPR; the caller is expected to be mindful of the fact
1914    that the return value is no longer an lvalue.  */
1915
1916 tree
1917 decay_conversion (tree exp, tsubst_flags_t complain)
1918 {
1919   tree type;
1920   enum tree_code code;
1921   location_t loc = EXPR_LOC_OR_LOC (exp, input_location);
1922
1923   type = TREE_TYPE (exp);
1924   if (type == error_mark_node)
1925     return error_mark_node;
1926
1927   exp = mark_rvalue_use (exp);
1928
1929   exp = resolve_nondeduced_context (exp);
1930   if (type_unknown_p (exp))
1931     {
1932       if (complain & tf_error)
1933         cxx_incomplete_type_error (exp, TREE_TYPE (exp));
1934       return error_mark_node;
1935     }
1936
1937   code = TREE_CODE (type);
1938
1939   /* FIXME remove for delayed folding.  */
1940   exp = scalar_constant_value (exp);
1941   if (error_operand_p (exp))
1942     return error_mark_node;
1943
1944   if (NULLPTR_TYPE_P (type) && !TREE_SIDE_EFFECTS (exp))
1945     return nullptr_node;
1946
1947   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
1948      Leave such NOP_EXPRs, since RHS is being used in non-lvalue context.  */
1949   if (code == VOID_TYPE)
1950     {
1951       if (complain & tf_error)
1952         error_at (loc, "void value not ignored as it ought to be");
1953       return error_mark_node;
1954     }
1955   if (invalid_nonstatic_memfn_p (exp, complain))
1956     return error_mark_node;
1957   if (code == FUNCTION_TYPE || is_overloaded_fn (exp))
1958     return cp_build_addr_expr (exp, complain);
1959   if (code == ARRAY_TYPE)
1960     {
1961       tree adr;
1962       tree ptrtype;
1963
1964       if (INDIRECT_REF_P (exp))
1965         return build_nop (build_pointer_type (TREE_TYPE (type)),
1966                           TREE_OPERAND (exp, 0));
1967
1968       if (TREE_CODE (exp) == COMPOUND_EXPR)
1969         {
1970           tree op1 = decay_conversion (TREE_OPERAND (exp, 1), complain);
1971           if (op1 == error_mark_node)
1972             return error_mark_node;
1973           return build2 (COMPOUND_EXPR, TREE_TYPE (op1),
1974                          TREE_OPERAND (exp, 0), op1);
1975         }
1976
1977       if (!lvalue_p (exp)
1978           && ! (TREE_CODE (exp) == CONSTRUCTOR && TREE_STATIC (exp)))
1979         {
1980           if (complain & tf_error)
1981             error_at (loc, "invalid use of non-lvalue array");
1982           return error_mark_node;
1983         }
1984
1985       /* Don't let an array compound literal decay to a pointer.  It can
1986          still be used to initialize an array or bind to a reference.  */
1987       if (TREE_CODE (exp) == TARGET_EXPR)
1988         {
1989           if (complain & tf_error)
1990             error_at (loc, "taking address of temporary array");
1991           return error_mark_node;
1992         }
1993
1994       ptrtype = build_pointer_type (TREE_TYPE (type));
1995
1996       if (VAR_P (exp))
1997         {
1998           if (!cxx_mark_addressable (exp))
1999             return error_mark_node;
2000           adr = build_nop (ptrtype, build_address (exp));
2001           return adr;
2002         }
2003       /* This way is better for a COMPONENT_REF since it can
2004          simplify the offset for a component.  */
2005       adr = cp_build_addr_expr (exp, complain);
2006       return cp_convert (ptrtype, adr, complain);
2007     }
2008
2009   /* If a bitfield is used in a context where integral promotion
2010      applies, then the caller is expected to have used
2011      default_conversion.  That function promotes bitfields correctly
2012      before calling this function.  At this point, if we have a
2013      bitfield referenced, we may assume that is not subject to
2014      promotion, and that, therefore, the type of the resulting rvalue
2015      is the declared type of the bitfield.  */
2016   exp = convert_bitfield_to_declared_type (exp);
2017
2018   /* We do not call rvalue() here because we do not want to wrap EXP
2019      in a NON_LVALUE_EXPR.  */
2020
2021   /* [basic.lval]
2022
2023      Non-class rvalues always have cv-unqualified types.  */
2024   type = TREE_TYPE (exp);
2025   if (!CLASS_TYPE_P (type) && cv_qualified_p (type))
2026     exp = build_nop (cv_unqualified (type), exp);
2027
2028   return exp;
2029 }
2030
2031 /* Perform preparatory conversions, as part of the "usual arithmetic
2032    conversions".  In particular, as per [expr]:
2033
2034      Whenever an lvalue expression appears as an operand of an
2035      operator that expects the rvalue for that operand, the
2036      lvalue-to-rvalue, array-to-pointer, or function-to-pointer
2037      standard conversions are applied to convert the expression to an
2038      rvalue.
2039
2040    In addition, we perform integral promotions here, as those are
2041    applied to both operands to a binary operator before determining
2042    what additional conversions should apply.  */
2043
2044 static tree
2045 cp_default_conversion (tree exp, tsubst_flags_t complain)
2046 {
2047   /* Check for target-specific promotions.  */
2048   tree promoted_type = targetm.promoted_type (TREE_TYPE (exp));
2049   if (promoted_type)
2050     exp = cp_convert (promoted_type, exp, complain);
2051   /* Perform the integral promotions first so that bitfield
2052      expressions (which may promote to "int", even if the bitfield is
2053      declared "unsigned") are promoted correctly.  */
2054   else if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (exp)))
2055     exp = cp_perform_integral_promotions (exp, complain);
2056   /* Perform the other conversions.  */
2057   exp = decay_conversion (exp, complain);
2058
2059   return exp;
2060 }
2061
2062 /* C version.  */
2063
2064 tree
2065 default_conversion (tree exp)
2066 {
2067   return cp_default_conversion (exp, tf_warning_or_error);
2068 }
2069
2070 /* EXPR is an expression with an integral or enumeration type.
2071    Perform the integral promotions in [conv.prom], and return the
2072    converted value.  */
2073
2074 tree
2075 cp_perform_integral_promotions (tree expr, tsubst_flags_t complain)
2076 {
2077   tree type;
2078   tree promoted_type;
2079
2080   expr = mark_rvalue_use (expr);
2081
2082   /* [conv.prom]
2083
2084      If the bitfield has an enumerated type, it is treated as any
2085      other value of that type for promotion purposes.  */
2086   type = is_bitfield_expr_with_lowered_type (expr);
2087   if (!type || TREE_CODE (type) != ENUMERAL_TYPE)
2088     type = TREE_TYPE (expr);
2089   gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
2090   /* Scoped enums don't promote.  */
2091   if (SCOPED_ENUM_P (type))
2092     return expr;
2093   promoted_type = type_promotes_to (type);
2094   if (type != promoted_type)
2095     expr = cp_convert (promoted_type, expr, complain);
2096   return expr;
2097 }
2098
2099 /* C version.  */
2100
2101 tree
2102 perform_integral_promotions (tree expr)
2103 {
2104   return cp_perform_integral_promotions (expr, tf_warning_or_error);
2105 }
2106
2107 /* Returns nonzero iff exp is a STRING_CST or the result of applying
2108    decay_conversion to one.  */
2109
2110 int
2111 string_conv_p (const_tree totype, const_tree exp, int warn)
2112 {
2113   tree t;
2114
2115   if (!TYPE_PTR_P (totype))
2116     return 0;
2117
2118   t = TREE_TYPE (totype);
2119   if (!same_type_p (t, char_type_node)
2120       && !same_type_p (t, char16_type_node)
2121       && !same_type_p (t, char32_type_node)
2122       && !same_type_p (t, wchar_type_node))
2123     return 0;
2124
2125   if (TREE_CODE (exp) == STRING_CST)
2126     {
2127       /* Make sure that we don't try to convert between char and wide chars.  */
2128       if (!same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (exp))), t))
2129         return 0;
2130     }
2131   else
2132     {
2133       /* Is this a string constant which has decayed to 'const char *'?  */
2134       t = build_pointer_type (cp_build_qualified_type (t, TYPE_QUAL_CONST));
2135       if (!same_type_p (TREE_TYPE (exp), t))
2136         return 0;
2137       STRIP_NOPS (exp);
2138       if (TREE_CODE (exp) != ADDR_EXPR
2139           || TREE_CODE (TREE_OPERAND (exp, 0)) != STRING_CST)
2140         return 0;
2141     }
2142   if (warn)
2143     {
2144       if (cxx_dialect >= cxx11)
2145         pedwarn (input_location,
2146                  pedantic ? OPT_Wpedantic : OPT_Wwrite_strings,
2147                  "ISO C++ forbids converting a string constant to %qT",
2148                  totype);
2149       else
2150         warning (OPT_Wwrite_strings,
2151                  "deprecated conversion from string constant to %qT",
2152                  totype);
2153     }
2154
2155   return 1;
2156 }
2157
2158 /* Given a COND_EXPR, MIN_EXPR, or MAX_EXPR in T, return it in a form that we
2159    can, for example, use as an lvalue.  This code used to be in
2160    unary_complex_lvalue, but we needed it to deal with `a = (d == c) ? b : c'
2161    expressions, where we're dealing with aggregates.  But now it's again only
2162    called from unary_complex_lvalue.  The case (in particular) that led to
2163    this was with CODE == ADDR_EXPR, since it's not an lvalue when we'd
2164    get it there.  */
2165
2166 static tree
2167 rationalize_conditional_expr (enum tree_code code, tree t,
2168                               tsubst_flags_t complain)
2169 {
2170   location_t loc = EXPR_LOC_OR_LOC (t, input_location);
2171
2172   /* For MIN_EXPR or MAX_EXPR, fold-const.c has arranged things so that
2173      the first operand is always the one to be used if both operands
2174      are equal, so we know what conditional expression this used to be.  */
2175   if (TREE_CODE (t) == MIN_EXPR || TREE_CODE (t) == MAX_EXPR)
2176     {
2177       tree op0 = TREE_OPERAND (t, 0);
2178       tree op1 = TREE_OPERAND (t, 1);
2179
2180       /* The following code is incorrect if either operand side-effects.  */
2181       gcc_assert (!TREE_SIDE_EFFECTS (op0)
2182                   && !TREE_SIDE_EFFECTS (op1));
2183       return
2184         build_conditional_expr (loc,
2185                                 build_x_binary_op (loc,
2186                                                    (TREE_CODE (t) == MIN_EXPR
2187                                                     ? LE_EXPR : GE_EXPR),
2188                                                    op0, TREE_CODE (op0),
2189                                                    op1, TREE_CODE (op1),
2190                                                    /*overload=*/NULL,
2191                                                    complain),
2192                                 cp_build_unary_op (code, op0, 0, complain),
2193                                 cp_build_unary_op (code, op1, 0, complain),
2194                                 complain);
2195     }
2196
2197   return
2198     build_conditional_expr (loc, TREE_OPERAND (t, 0),
2199                             cp_build_unary_op (code, TREE_OPERAND (t, 1), 0,
2200                                                complain),
2201                             cp_build_unary_op (code, TREE_OPERAND (t, 2), 0,
2202                                                complain),
2203                             complain);
2204 }
2205
2206 /* Given the TYPE of an anonymous union field inside T, return the
2207    FIELD_DECL for the field.  If not found return NULL_TREE.  Because
2208    anonymous unions can nest, we must also search all anonymous unions
2209    that are directly reachable.  */
2210
2211 tree
2212 lookup_anon_field (tree t, tree type)
2213 {
2214   tree field;
2215
2216   t = TYPE_MAIN_VARIANT (t);
2217
2218   for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
2219     {
2220       if (TREE_STATIC (field))
2221         continue;
2222       if (TREE_CODE (field) != FIELD_DECL || DECL_ARTIFICIAL (field))
2223         continue;
2224
2225       /* If we find it directly, return the field.  */
2226       if (DECL_NAME (field) == NULL_TREE
2227           && type == TYPE_MAIN_VARIANT (TREE_TYPE (field)))
2228         {
2229           return field;
2230         }
2231
2232       /* Otherwise, it could be nested, search harder.  */
2233       if (DECL_NAME (field) == NULL_TREE
2234           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2235         {
2236           tree subfield = lookup_anon_field (TREE_TYPE (field), type);
2237           if (subfield)
2238             return subfield;
2239         }
2240     }
2241   return NULL_TREE;
2242 }
2243
2244 /* Build an expression representing OBJECT.MEMBER.  OBJECT is an
2245    expression; MEMBER is a DECL or baselink.  If ACCESS_PATH is
2246    non-NULL, it indicates the path to the base used to name MEMBER.
2247    If PRESERVE_REFERENCE is true, the expression returned will have
2248    REFERENCE_TYPE if the MEMBER does.  Otherwise, the expression
2249    returned will have the type referred to by the reference.
2250
2251    This function does not perform access control; that is either done
2252    earlier by the parser when the name of MEMBER is resolved to MEMBER
2253    itself, or later when overload resolution selects one of the
2254    functions indicated by MEMBER.  */
2255
2256 tree
2257 build_class_member_access_expr (tree object, tree member,
2258                                 tree access_path, bool preserve_reference,
2259                                 tsubst_flags_t complain)
2260 {
2261   tree object_type;
2262   tree member_scope;
2263   tree result = NULL_TREE;
2264   tree using_decl = NULL_TREE;
2265
2266   if (error_operand_p (object) || error_operand_p (member))
2267     return error_mark_node;
2268
2269   gcc_assert (DECL_P (member) || BASELINK_P (member));
2270
2271   /* [expr.ref]
2272
2273      The type of the first expression shall be "class object" (of a
2274      complete type).  */
2275   object_type = TREE_TYPE (object);
2276   if (!currently_open_class (object_type)
2277       && !complete_type_or_maybe_complain (object_type, object, complain))
2278     return error_mark_node;
2279   if (!CLASS_TYPE_P (object_type))
2280     {
2281       if (complain & tf_error)
2282         {
2283           if (POINTER_TYPE_P (object_type)
2284               && CLASS_TYPE_P (TREE_TYPE (object_type)))
2285             error ("request for member %qD in %qE, which is of pointer "
2286                    "type %qT (maybe you meant to use %<->%> ?)",
2287                    member, object, object_type);
2288           else
2289             error ("request for member %qD in %qE, which is of non-class "
2290                    "type %qT", member, object, object_type);
2291         }
2292       return error_mark_node;
2293     }
2294
2295   /* The standard does not seem to actually say that MEMBER must be a
2296      member of OBJECT_TYPE.  However, that is clearly what is
2297      intended.  */
2298   if (DECL_P (member))
2299     {
2300       member_scope = DECL_CLASS_CONTEXT (member);
2301       mark_used (member);
2302       if (TREE_DEPRECATED (member))
2303         warn_deprecated_use (member, NULL_TREE);
2304     }
2305   else
2306     member_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (member));
2307   /* If MEMBER is from an anonymous aggregate, MEMBER_SCOPE will
2308      presently be the anonymous union.  Go outwards until we find a
2309      type related to OBJECT_TYPE.  */
2310   while ((ANON_AGGR_TYPE_P (member_scope) || UNSCOPED_ENUM_P (member_scope))
2311          && !same_type_ignoring_top_level_qualifiers_p (member_scope,
2312                                                         object_type))
2313     member_scope = TYPE_CONTEXT (member_scope);
2314   if (!member_scope || !DERIVED_FROM_P (member_scope, object_type))
2315     {
2316       if (complain & tf_error)
2317         {
2318           if (TREE_CODE (member) == FIELD_DECL)
2319             error ("invalid use of nonstatic data member %qE", member);
2320           else
2321             error ("%qD is not a member of %qT", member, object_type);
2322         }
2323       return error_mark_node;
2324     }
2325
2326   /* Transform `(a, b).x' into `(*(a, &b)).x', `(a ? b : c).x' into
2327      `(*(a ?  &b : &c)).x', and so on.  A COND_EXPR is only an lvalue
2328      in the front end; only _DECLs and _REFs are lvalues in the back end.  */
2329   {
2330     tree temp = unary_complex_lvalue (ADDR_EXPR, object);
2331     if (temp)
2332       object = cp_build_indirect_ref (temp, RO_NULL, complain);
2333   }
2334
2335   /* In [expr.ref], there is an explicit list of the valid choices for
2336      MEMBER.  We check for each of those cases here.  */
2337   if (VAR_P (member))
2338     {
2339       /* A static data member.  */
2340       result = member;
2341       mark_exp_read (object);
2342       /* If OBJECT has side-effects, they are supposed to occur.  */
2343       if (TREE_SIDE_EFFECTS (object))
2344         result = build2 (COMPOUND_EXPR, TREE_TYPE (result), object, result);
2345     }
2346   else if (TREE_CODE (member) == FIELD_DECL)
2347     {
2348       /* A non-static data member.  */
2349       bool null_object_p;
2350       int type_quals;
2351       tree member_type;
2352
2353       null_object_p = (INDIRECT_REF_P (object)
2354                        && integer_zerop (TREE_OPERAND (object, 0)));
2355
2356       /* Convert OBJECT to the type of MEMBER.  */
2357       if (!same_type_p (TYPE_MAIN_VARIANT (object_type),
2358                         TYPE_MAIN_VARIANT (member_scope)))
2359         {
2360           tree binfo;
2361           base_kind kind;
2362
2363           binfo = lookup_base (access_path ? access_path : object_type,
2364                                member_scope, ba_unique, &kind, complain);
2365           if (binfo == error_mark_node)
2366             return error_mark_node;
2367
2368           /* It is invalid to try to get to a virtual base of a
2369              NULL object.  The most common cause is invalid use of
2370              offsetof macro.  */
2371           if (null_object_p && kind == bk_via_virtual)
2372             {
2373               if (complain & tf_error)
2374                 {
2375                   error ("invalid access to non-static data member %qD in "
2376                          "virtual base of NULL object", member);
2377                 }
2378               return error_mark_node;
2379             }
2380
2381           /* Convert to the base.  */
2382           object = build_base_path (PLUS_EXPR, object, binfo,
2383                                     /*nonnull=*/1, complain);
2384           /* If we found the base successfully then we should be able
2385              to convert to it successfully.  */
2386           gcc_assert (object != error_mark_node);
2387         }
2388
2389       /* If MEMBER is from an anonymous aggregate, we have converted
2390          OBJECT so that it refers to the class containing the
2391          anonymous union.  Generate a reference to the anonymous union
2392          itself, and recur to find MEMBER.  */
2393       if (ANON_AGGR_TYPE_P (DECL_CONTEXT (member))
2394           /* When this code is called from build_field_call, the
2395              object already has the type of the anonymous union.
2396              That is because the COMPONENT_REF was already
2397              constructed, and was then disassembled before calling
2398              build_field_call.  After the function-call code is
2399              cleaned up, this waste can be eliminated.  */
2400           && (!same_type_ignoring_top_level_qualifiers_p
2401               (TREE_TYPE (object), DECL_CONTEXT (member))))
2402         {
2403           tree anonymous_union;
2404
2405           anonymous_union = lookup_anon_field (TREE_TYPE (object),
2406                                                DECL_CONTEXT (member));
2407           object = build_class_member_access_expr (object,
2408                                                    anonymous_union,
2409                                                    /*access_path=*/NULL_TREE,
2410                                                    preserve_reference,
2411                                                    complain);
2412         }
2413
2414       /* Compute the type of the field, as described in [expr.ref].  */
2415       type_quals = TYPE_UNQUALIFIED;
2416       member_type = TREE_TYPE (member);
2417       if (TREE_CODE (member_type) != REFERENCE_TYPE)
2418         {
2419           type_quals = (cp_type_quals (member_type)
2420                         | cp_type_quals (object_type));
2421
2422           /* A field is const (volatile) if the enclosing object, or the
2423              field itself, is const (volatile).  But, a mutable field is
2424              not const, even within a const object.  */
2425           if (DECL_MUTABLE_P (member))
2426             type_quals &= ~TYPE_QUAL_CONST;
2427           member_type = cp_build_qualified_type (member_type, type_quals);
2428         }
2429
2430       result = build3_loc (input_location, COMPONENT_REF, member_type,
2431                            object, member, NULL_TREE);
2432       result = fold_if_not_in_template (result);
2433
2434       /* Mark the expression const or volatile, as appropriate.  Even
2435          though we've dealt with the type above, we still have to mark the
2436          expression itself.  */
2437       if (type_quals & TYPE_QUAL_CONST)
2438         TREE_READONLY (result) = 1;
2439       if (type_quals & TYPE_QUAL_VOLATILE)
2440         TREE_THIS_VOLATILE (result) = 1;
2441     }
2442   else if (BASELINK_P (member))
2443     {
2444       /* The member is a (possibly overloaded) member function.  */
2445       tree functions;
2446       tree type;
2447
2448       /* If the MEMBER is exactly one static member function, then we
2449          know the type of the expression.  Otherwise, we must wait
2450          until overload resolution has been performed.  */
2451       functions = BASELINK_FUNCTIONS (member);
2452       if (TREE_CODE (functions) == FUNCTION_DECL
2453           && DECL_STATIC_FUNCTION_P (functions))
2454         type = TREE_TYPE (functions);
2455       else
2456         type = unknown_type_node;
2457       /* Note that we do not convert OBJECT to the BASELINK_BINFO
2458          base.  That will happen when the function is called.  */
2459       result = build3 (COMPONENT_REF, type, object, member, NULL_TREE);
2460     }
2461   else if (TREE_CODE (member) == CONST_DECL)
2462     {
2463       /* The member is an enumerator.  */
2464       result = member;
2465       /* If OBJECT has side-effects, they are supposed to occur.  */
2466       if (TREE_SIDE_EFFECTS (object))
2467         result = build2 (COMPOUND_EXPR, TREE_TYPE (result),
2468                          object, result);
2469     }
2470   else if ((using_decl = strip_using_decl (member)) != member)
2471     result = build_class_member_access_expr (object,
2472                                              using_decl,
2473                                              access_path, preserve_reference,
2474                                              complain);
2475   else
2476     {
2477       if (complain & tf_error)
2478         error ("invalid use of %qD", member);
2479       return error_mark_node;
2480     }
2481
2482   if (!preserve_reference)
2483     /* [expr.ref]
2484
2485        If E2 is declared to have type "reference to T", then ... the
2486        type of E1.E2 is T.  */
2487     result = convert_from_reference (result);
2488
2489   return result;
2490 }
2491
2492 /* Return the destructor denoted by OBJECT.SCOPE::DTOR_NAME, or, if
2493    SCOPE is NULL, by OBJECT.DTOR_NAME, where DTOR_NAME is ~type.  */
2494
2495 static tree
2496 lookup_destructor (tree object, tree scope, tree dtor_name,
2497                    tsubst_flags_t complain)
2498 {
2499   tree object_type = TREE_TYPE (object);
2500   tree dtor_type = TREE_OPERAND (dtor_name, 0);
2501   tree expr;
2502
2503   /* We've already complained about this destructor.  */
2504   if (dtor_type == error_mark_node)
2505     return error_mark_node;
2506
2507   if (scope && !check_dtor_name (scope, dtor_type))
2508     {
2509       if (complain & tf_error)
2510         error ("qualified type %qT does not match destructor name ~%qT",
2511                scope, dtor_type);
2512       return error_mark_node;
2513     }
2514   if (is_auto (dtor_type))
2515     dtor_type = object_type;
2516   else if (identifier_p (dtor_type))
2517     {
2518       /* In a template, names we can't find a match for are still accepted
2519          destructor names, and we check them here.  */
2520       if (check_dtor_name (object_type, dtor_type))
2521         dtor_type = object_type;
2522       else
2523         {
2524           if (complain & tf_error)
2525             error ("object type %qT does not match destructor name ~%qT",
2526                    object_type, dtor_type);
2527           return error_mark_node;
2528         }
2529       
2530     }
2531   else if (!DERIVED_FROM_P (dtor_type, TYPE_MAIN_VARIANT (object_type)))
2532     {
2533       if (complain & tf_error)
2534         error ("the type being destroyed is %qT, but the destructor "
2535                "refers to %qT", TYPE_MAIN_VARIANT (object_type), dtor_type);
2536       return error_mark_node;
2537     }
2538   expr = lookup_member (dtor_type, complete_dtor_identifier,
2539                         /*protect=*/1, /*want_type=*/false,
2540                         tf_warning_or_error);
2541   if (!expr)
2542     {
2543       if (complain & tf_error)
2544         cxx_incomplete_type_error (dtor_name, dtor_type);
2545       return error_mark_node;
2546     }
2547   expr = (adjust_result_of_qualified_name_lookup
2548           (expr, dtor_type, object_type));
2549   if (scope == NULL_TREE)
2550     /* We need to call adjust_result_of_qualified_name_lookup in case the
2551        destructor names a base class, but we unset BASELINK_QUALIFIED_P so
2552        that we still get virtual function binding.  */
2553     BASELINK_QUALIFIED_P (expr) = false;
2554   return expr;
2555 }
2556
2557 /* An expression of the form "A::template B" has been resolved to
2558    DECL.  Issue a diagnostic if B is not a template or template
2559    specialization.  */
2560
2561 void
2562 check_template_keyword (tree decl)
2563 {
2564   /* The standard says:
2565
2566       [temp.names]
2567
2568       If a name prefixed by the keyword template is not a member
2569       template, the program is ill-formed.
2570
2571      DR 228 removed the restriction that the template be a member
2572      template.
2573
2574      DR 96, if accepted would add the further restriction that explicit
2575      template arguments must be provided if the template keyword is
2576      used, but, as of 2005-10-16, that DR is still in "drafting".  If
2577      this DR is accepted, then the semantic checks here can be
2578      simplified, as the entity named must in fact be a template
2579      specialization, rather than, as at present, a set of overloaded
2580      functions containing at least one template function.  */
2581   if (TREE_CODE (decl) != TEMPLATE_DECL
2582       && TREE_CODE (decl) != TEMPLATE_ID_EXPR)
2583     {
2584       if (!is_overloaded_fn (decl))
2585         permerror (input_location, "%qD is not a template", decl);
2586       else
2587         {
2588           tree fns;
2589           fns = decl;
2590           if (BASELINK_P (fns))
2591             fns = BASELINK_FUNCTIONS (fns);
2592           while (fns)
2593             {
2594               tree fn = OVL_CURRENT (fns);
2595               if (TREE_CODE (fn) == TEMPLATE_DECL
2596                   || TREE_CODE (fn) == TEMPLATE_ID_EXPR)
2597                 break;
2598               if (TREE_CODE (fn) == FUNCTION_DECL
2599                   && DECL_USE_TEMPLATE (fn)
2600                   && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
2601                 break;
2602               fns = OVL_NEXT (fns);
2603             }
2604           if (!fns)
2605             permerror (input_location, "%qD is not a template", decl);
2606         }
2607     }
2608 }
2609
2610 /* This function is called by the parser to process a class member
2611    access expression of the form OBJECT.NAME.  NAME is a node used by
2612    the parser to represent a name; it is not yet a DECL.  It may,
2613    however, be a BASELINK where the BASELINK_FUNCTIONS is a
2614    TEMPLATE_ID_EXPR.  Templates must be looked up by the parser, and
2615    there is no reason to do the lookup twice, so the parser keeps the
2616    BASELINK.  TEMPLATE_P is true iff NAME was explicitly declared to
2617    be a template via the use of the "A::template B" syntax.  */
2618
2619 tree
2620 finish_class_member_access_expr (tree object, tree name, bool template_p,
2621                                  tsubst_flags_t complain)
2622 {
2623   tree expr;
2624   tree object_type;
2625   tree member;
2626   tree access_path = NULL_TREE;
2627   tree orig_object = object;
2628   tree orig_name = name;
2629
2630   if (object == error_mark_node || name == error_mark_node)
2631     return error_mark_node;
2632
2633   /* If OBJECT is an ObjC class instance, we must obey ObjC access rules.  */
2634   if (!objc_is_public (object, name))
2635     return error_mark_node;
2636
2637   object_type = TREE_TYPE (object);
2638
2639   if (processing_template_decl)
2640     {
2641       if (/* If OBJECT_TYPE is dependent, so is OBJECT.NAME.  */
2642           dependent_type_p (object_type)
2643           /* If NAME is just an IDENTIFIER_NODE, then the expression
2644              is dependent.  */
2645           || identifier_p (object)
2646           /* If NAME is "f<args>", where either 'f' or 'args' is
2647              dependent, then the expression is dependent.  */
2648           || (TREE_CODE (name) == TEMPLATE_ID_EXPR
2649               && dependent_template_id_p (TREE_OPERAND (name, 0),
2650                                           TREE_OPERAND (name, 1)))
2651           /* If NAME is "T::X" where "T" is dependent, then the
2652              expression is dependent.  */
2653           || (TREE_CODE (name) == SCOPE_REF
2654               && TYPE_P (TREE_OPERAND (name, 0))
2655               && dependent_type_p (TREE_OPERAND (name, 0))))
2656         return build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF,
2657                                  object, name, NULL_TREE);
2658       object = build_non_dependent_expr (object);
2659     }
2660   else if (c_dialect_objc ()
2661            && identifier_p (name)
2662            && (expr = objc_maybe_build_component_ref (object, name)))
2663     return expr;
2664     
2665   /* [expr.ref]
2666
2667      The type of the first expression shall be "class object" (of a
2668      complete type).  */
2669   if (!currently_open_class (object_type)
2670       && !complete_type_or_maybe_complain (object_type, object, complain))
2671     return error_mark_node;
2672   if (!CLASS_TYPE_P (object_type))
2673     {
2674       if (complain & tf_error)
2675         {
2676           if (POINTER_TYPE_P (object_type)
2677               && CLASS_TYPE_P (TREE_TYPE (object_type)))
2678             error ("request for member %qD in %qE, which is of pointer "
2679                    "type %qT (maybe you meant to use %<->%> ?)",
2680                    name, object, object_type);
2681           else
2682             error ("request for member %qD in %qE, which is of non-class "
2683                    "type %qT", name, object, object_type);
2684         }
2685       return error_mark_node;
2686     }
2687
2688   if (BASELINK_P (name))
2689     /* A member function that has already been looked up.  */
2690     member = name;
2691   else
2692     {
2693       bool is_template_id = false;
2694       tree template_args = NULL_TREE;
2695       tree scope;
2696
2697       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
2698         {
2699           is_template_id = true;
2700           template_args = TREE_OPERAND (name, 1);
2701           name = TREE_OPERAND (name, 0);
2702
2703           if (TREE_CODE (name) == OVERLOAD)
2704             name = DECL_NAME (get_first_fn (name));
2705           else if (DECL_P (name))
2706             name = DECL_NAME (name);
2707         }
2708
2709       if (TREE_CODE (name) == SCOPE_REF)
2710         {
2711           /* A qualified name.  The qualifying class or namespace `S'
2712              has already been looked up; it is either a TYPE or a
2713              NAMESPACE_DECL.  */
2714           scope = TREE_OPERAND (name, 0);
2715           name = TREE_OPERAND (name, 1);
2716
2717           /* If SCOPE is a namespace, then the qualified name does not
2718              name a member of OBJECT_TYPE.  */
2719           if (TREE_CODE (scope) == NAMESPACE_DECL)
2720             {
2721               if (complain & tf_error)
2722                 error ("%<%D::%D%> is not a member of %qT",
2723                        scope, name, object_type);
2724               return error_mark_node;
2725             }
2726
2727           if (TREE_CODE (scope) == ENUMERAL_TYPE)
2728             {
2729               /* Looking up a member enumerator (c++/56793).  */
2730               if (!TYPE_CLASS_SCOPE_P (scope)
2731                   || !DERIVED_FROM_P (TYPE_CONTEXT (scope), object_type))
2732                 {
2733                   if (complain & tf_error)
2734                     error ("%<%D::%D%> is not a member of %qT",
2735                            scope, name, object_type);
2736                   return error_mark_node;
2737                 }
2738               tree val = lookup_enumerator (scope, name);
2739               if (TREE_SIDE_EFFECTS (object))
2740                 val = build2 (COMPOUND_EXPR, TREE_TYPE (val), object, val);
2741               return val;
2742             }
2743
2744           gcc_assert (CLASS_TYPE_P (scope));
2745           gcc_assert (identifier_p (name) || TREE_CODE (name) == BIT_NOT_EXPR);
2746
2747           if (constructor_name_p (name, scope))
2748             {
2749               if (complain & tf_error)
2750                 error ("cannot call constructor %<%T::%D%> directly",
2751                        scope, name);
2752               return error_mark_node;
2753             }
2754
2755           /* Find the base of OBJECT_TYPE corresponding to SCOPE.  */
2756           access_path = lookup_base (object_type, scope, ba_check,
2757                                      NULL, complain);
2758           if (access_path == error_mark_node)
2759             return error_mark_node;
2760           if (!access_path)
2761             {
2762               if (complain & tf_error)
2763                 error ("%qT is not a base of %qT", scope, object_type);
2764               return error_mark_node;
2765             }
2766         }
2767       else
2768         {
2769           scope = NULL_TREE;
2770           access_path = object_type;
2771         }
2772
2773       if (TREE_CODE (name) == BIT_NOT_EXPR)
2774         member = lookup_destructor (object, scope, name, complain);
2775       else
2776         {
2777           /* Look up the member.  */
2778           member = lookup_member (access_path, name, /*protect=*/1,
2779                                   /*want_type=*/false, complain);
2780           if (member == NULL_TREE)
2781             {
2782               if (complain & tf_error)
2783                 error ("%q#T has no member named %qE",
2784                        TREE_CODE (access_path) == TREE_BINFO
2785                        ? TREE_TYPE (access_path) : object_type, name);
2786               return error_mark_node;
2787             }
2788           if (member == error_mark_node)
2789             return error_mark_node;
2790         }
2791
2792       if (is_template_id)
2793         {
2794           tree templ = member;
2795
2796           if (BASELINK_P (templ))
2797             templ = lookup_template_function (templ, template_args);
2798           else
2799             {
2800               if (complain & tf_error)
2801                 error ("%qD is not a member template function", name);
2802               return error_mark_node;
2803             }
2804         }
2805     }
2806
2807   if (TREE_DEPRECATED (member))
2808     warn_deprecated_use (member, NULL_TREE);
2809
2810   if (template_p)
2811     check_template_keyword (member);
2812
2813   expr = build_class_member_access_expr (object, member, access_path,
2814                                          /*preserve_reference=*/false,
2815                                          complain);
2816   if (processing_template_decl && expr != error_mark_node)
2817     {
2818       if (BASELINK_P (member))
2819         {
2820           if (TREE_CODE (orig_name) == SCOPE_REF)
2821             BASELINK_QUALIFIED_P (member) = 1;
2822           orig_name = member;
2823         }
2824       return build_min_non_dep (COMPONENT_REF, expr,
2825                                 orig_object, orig_name,
2826                                 NULL_TREE);
2827     }
2828
2829   return expr;
2830 }
2831
2832 /* Build a COMPONENT_REF of OBJECT and MEMBER with the appropriate
2833    type.  */
2834
2835 tree
2836 build_simple_component_ref (tree object, tree member)
2837 {
2838   tree type = cp_build_qualified_type (TREE_TYPE (member),
2839                                        cp_type_quals (TREE_TYPE (object)));
2840   return fold_build3_loc (input_location,
2841                           COMPONENT_REF, type,
2842                           object, member, NULL_TREE);
2843 }
2844
2845 /* Return an expression for the MEMBER_NAME field in the internal
2846    representation of PTRMEM, a pointer-to-member function.  (Each
2847    pointer-to-member function type gets its own RECORD_TYPE so it is
2848    more convenient to access the fields by name than by FIELD_DECL.)
2849    This routine converts the NAME to a FIELD_DECL and then creates the
2850    node for the complete expression.  */
2851
2852 tree
2853 build_ptrmemfunc_access_expr (tree ptrmem, tree member_name)
2854 {
2855   tree ptrmem_type;
2856   tree member;
2857
2858   /* This code is a stripped down version of
2859      build_class_member_access_expr.  It does not work to use that
2860      routine directly because it expects the object to be of class
2861      type.  */
2862   ptrmem_type = TREE_TYPE (ptrmem);
2863   gcc_assert (TYPE_PTRMEMFUNC_P (ptrmem_type));
2864   for (member = TYPE_FIELDS (ptrmem_type); member;
2865        member = DECL_CHAIN (member))
2866     if (DECL_NAME (member) == member_name)
2867       break;
2868   return build_simple_component_ref (ptrmem, member);
2869 }
2870
2871 /* Given an expression PTR for a pointer, return an expression
2872    for the value pointed to.
2873    ERRORSTRING is the name of the operator to appear in error messages.
2874
2875    This function may need to overload OPERATOR_FNNAME.
2876    Must also handle REFERENCE_TYPEs for C++.  */
2877
2878 tree
2879 build_x_indirect_ref (location_t loc, tree expr, ref_operator errorstring, 
2880                       tsubst_flags_t complain)
2881 {
2882   tree orig_expr = expr;
2883   tree rval;
2884
2885   if (processing_template_decl)
2886     {
2887       /* Retain the type if we know the operand is a pointer.  */
2888       if (TREE_TYPE (expr) && POINTER_TYPE_P (TREE_TYPE (expr)))
2889         return build_min (INDIRECT_REF, TREE_TYPE (TREE_TYPE (expr)), expr);
2890       if (type_dependent_expression_p (expr))
2891         return build_min_nt_loc (loc, INDIRECT_REF, expr);
2892       expr = build_non_dependent_expr (expr);
2893     }
2894
2895   rval = build_new_op (loc, INDIRECT_REF, LOOKUP_NORMAL, expr,
2896                        NULL_TREE, NULL_TREE, /*overload=*/NULL, complain);
2897   if (!rval)
2898     rval = cp_build_indirect_ref (expr, errorstring, complain);
2899
2900   if (processing_template_decl && rval != error_mark_node)
2901     return build_min_non_dep (INDIRECT_REF, rval, orig_expr);
2902   else
2903     return rval;
2904 }
2905
2906 /* Helper function called from c-common.  */
2907 tree
2908 build_indirect_ref (location_t /*loc*/,
2909                     tree ptr, ref_operator errorstring)
2910 {
2911   return cp_build_indirect_ref (ptr, errorstring, tf_warning_or_error);
2912 }
2913
2914 tree
2915 cp_build_indirect_ref (tree ptr, ref_operator errorstring, 
2916                        tsubst_flags_t complain)
2917 {
2918   tree pointer, type;
2919
2920   if (ptr == current_class_ptr
2921       || (TREE_CODE (ptr) == NOP_EXPR
2922           && TREE_OPERAND (ptr, 0) == current_class_ptr
2923           && (same_type_ignoring_top_level_qualifiers_p
2924               (TREE_TYPE (ptr), TREE_TYPE (current_class_ptr)))))
2925     return current_class_ref;
2926
2927   pointer = (TREE_CODE (TREE_TYPE (ptr)) == REFERENCE_TYPE
2928              ? ptr : decay_conversion (ptr, complain));
2929   if (pointer == error_mark_node)
2930     return error_mark_node;
2931
2932   type = TREE_TYPE (pointer);
2933
2934   if (POINTER_TYPE_P (type))
2935     {
2936       /* [expr.unary.op]
2937
2938          If the type of the expression is "pointer to T," the type
2939          of  the  result  is  "T."  */
2940       tree t = TREE_TYPE (type);
2941
2942       if ((CONVERT_EXPR_P (ptr)
2943            || TREE_CODE (ptr) == VIEW_CONVERT_EXPR)
2944           && (!CLASS_TYPE_P (t) || !CLASSTYPE_EMPTY_P (t)))
2945         {
2946           /* If a warning is issued, mark it to avoid duplicates from
2947              the backend.  This only needs to be done at
2948              warn_strict_aliasing > 2.  */
2949           if (warn_strict_aliasing > 2)
2950             if (strict_aliasing_warning (TREE_TYPE (TREE_OPERAND (ptr, 0)),
2951                                          type, TREE_OPERAND (ptr, 0)))
2952               TREE_NO_WARNING (ptr) = 1;
2953         }
2954
2955       if (VOID_TYPE_P (t))
2956         {
2957           /* A pointer to incomplete type (other than cv void) can be
2958              dereferenced [expr.unary.op]/1  */
2959           if (complain & tf_error)
2960             error ("%qT is not a pointer-to-object type", type);
2961           return error_mark_node;
2962         }
2963       else if (TREE_CODE (pointer) == ADDR_EXPR
2964                && same_type_p (t, TREE_TYPE (TREE_OPERAND (pointer, 0))))
2965         /* The POINTER was something like `&x'.  We simplify `*&x' to
2966            `x'.  */
2967         return TREE_OPERAND (pointer, 0);
2968       else
2969         {
2970           tree ref = build1 (INDIRECT_REF, t, pointer);
2971
2972           /* We *must* set TREE_READONLY when dereferencing a pointer to const,
2973              so that we get the proper error message if the result is used
2974              to assign to.  Also, &* is supposed to be a no-op.  */
2975           TREE_READONLY (ref) = CP_TYPE_CONST_P (t);
2976           TREE_THIS_VOLATILE (ref) = CP_TYPE_VOLATILE_P (t);
2977           TREE_SIDE_EFFECTS (ref)
2978             = (TREE_THIS_VOLATILE (ref) || TREE_SIDE_EFFECTS (pointer));
2979           return ref;
2980         }
2981     }
2982   else if (!(complain & tf_error))
2983     /* Don't emit any errors; we'll just return ERROR_MARK_NODE later.  */
2984     ;
2985   /* `pointer' won't be an error_mark_node if we were given a
2986      pointer to member, so it's cool to check for this here.  */
2987   else if (TYPE_PTRMEM_P (type))
2988     switch (errorstring)
2989       {
2990          case RO_ARRAY_INDEXING:
2991            error ("invalid use of array indexing on pointer to member");
2992            break;
2993          case RO_UNARY_STAR:
2994            error ("invalid use of unary %<*%> on pointer to member");
2995            break;
2996          case RO_IMPLICIT_CONVERSION:
2997            error ("invalid use of implicit conversion on pointer to member");
2998            break;
2999          case RO_ARROW_STAR:
3000            error ("left hand operand of %<->*%> must be a pointer to class, "
3001                   "but is a pointer to member of type %qT", type);
3002            break;
3003          default:
3004            gcc_unreachable ();
3005       }
3006   else if (pointer != error_mark_node)
3007     invalid_indirection_error (input_location, type, errorstring);
3008
3009   return error_mark_node;
3010 }
3011
3012 /* This handles expressions of the form "a[i]", which denotes
3013    an array reference.
3014
3015    This is logically equivalent in C to *(a+i), but we may do it differently.
3016    If A is a variable or a member, we generate a primitive ARRAY_REF.
3017    This avoids forcing the array out of registers, and can work on
3018    arrays that are not lvalues (for example, members of structures returned
3019    by functions).
3020
3021    If INDEX is of some user-defined type, it must be converted to
3022    integer type.  Otherwise, to make a compatible PLUS_EXPR, it
3023    will inherit the type of the array, which will be some pointer type.
3024    
3025    LOC is the location to use in building the array reference.  */
3026
3027 tree
3028 cp_build_array_ref (location_t loc, tree array, tree idx,
3029                     tsubst_flags_t complain)
3030 {
3031   tree ret;
3032
3033   if (idx == 0)
3034     {
3035       if (complain & tf_error)
3036         error_at (loc, "subscript missing in array reference");
3037       return error_mark_node;
3038     }
3039
3040   /* If an array's index is an array notation, then its rank cannot be
3041      greater than one.  */ 
3042   if (flag_cilkplus && contains_array_notation_expr (idx))
3043     {
3044       size_t rank = 0;
3045
3046       /* If find_rank returns false, then it should have reported an error,
3047          thus it is unnecessary for repetition.  */
3048       if (!find_rank (loc, idx, idx, true, &rank))
3049         return error_mark_node;
3050       if (rank > 1)
3051         {
3052           error_at (loc, "rank of the array%'s index is greater than 1");
3053           return error_mark_node;
3054         }
3055     }
3056   if (TREE_TYPE (array) == error_mark_node
3057       || TREE_TYPE (idx) == error_mark_node)
3058     return error_mark_node;
3059
3060   /* If ARRAY is a COMPOUND_EXPR or COND_EXPR, move our reference
3061      inside it.  */
3062   switch (TREE_CODE (array))
3063     {
3064     case COMPOUND_EXPR:
3065       {
3066         tree value = cp_build_array_ref (loc, TREE_OPERAND (array, 1), idx,
3067                                          complain);
3068         ret = build2 (COMPOUND_EXPR, TREE_TYPE (value),
3069                       TREE_OPERAND (array, 0), value);
3070         SET_EXPR_LOCATION (ret, loc);
3071         return ret;
3072       }
3073
3074     case COND_EXPR:
3075       ret = build_conditional_expr
3076                (loc, TREE_OPERAND (array, 0),
3077                cp_build_array_ref (loc, TREE_OPERAND (array, 1), idx,
3078                                    complain),
3079                cp_build_array_ref (loc, TREE_OPERAND (array, 2), idx,
3080                                    complain),
3081                complain);
3082       protected_set_expr_location (ret, loc);
3083       return ret;
3084
3085     default:
3086       break;
3087     }
3088
3089   bool non_lvalue
3090     = convert_vector_to_pointer_for_subscript (loc, &array, idx);
3091
3092   if (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE)
3093     {
3094       tree rval, type;
3095
3096       warn_array_subscript_with_type_char (loc, idx);
3097
3098       if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (idx)))
3099         {
3100           if (complain & tf_error)
3101             error_at (loc, "array subscript is not an integer");
3102           return error_mark_node;
3103         }
3104
3105       /* Apply integral promotions *after* noticing character types.
3106          (It is unclear why we do these promotions -- the standard
3107          does not say that we should.  In fact, the natural thing would
3108          seem to be to convert IDX to ptrdiff_t; we're performing
3109          pointer arithmetic.)  */
3110       idx = cp_perform_integral_promotions (idx, complain);
3111
3112       /* An array that is indexed by a non-constant
3113          cannot be stored in a register; we must be able to do
3114          address arithmetic on its address.
3115          Likewise an array of elements of variable size.  */
3116       if (TREE_CODE (idx) != INTEGER_CST
3117           || (COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (array)))
3118               && (TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (array))))
3119                   != INTEGER_CST)))
3120         {
3121           if (!cxx_mark_addressable (array))
3122             return error_mark_node;
3123         }
3124
3125       /* An array that is indexed by a constant value which is not within
3126          the array bounds cannot be stored in a register either; because we
3127          would get a crash in store_bit_field/extract_bit_field when trying
3128          to access a non-existent part of the register.  */
3129       if (TREE_CODE (idx) == INTEGER_CST
3130           && TYPE_DOMAIN (TREE_TYPE (array))
3131           && ! int_fits_type_p (idx, TYPE_DOMAIN (TREE_TYPE (array))))
3132         {
3133           if (!cxx_mark_addressable (array))
3134             return error_mark_node;
3135         }
3136
3137       if (!lvalue_p (array))
3138         {
3139           if (complain & tf_error)
3140             pedwarn (loc, OPT_Wpedantic, 
3141                      "ISO C++ forbids subscripting non-lvalue array");
3142           else
3143             return error_mark_node;
3144         }
3145
3146       /* Note in C++ it is valid to subscript a `register' array, since
3147          it is valid to take the address of something with that
3148          storage specification.  */
3149       if (extra_warnings)
3150         {
3151           tree foo = array;
3152           while (TREE_CODE (foo) == COMPONENT_REF)
3153             foo = TREE_OPERAND (foo, 0);
3154           if (VAR_P (foo) && DECL_REGISTER (foo)
3155               && (complain & tf_warning))
3156             warning_at (loc, OPT_Wextra,
3157                         "subscripting array declared %<register%>");
3158         }
3159
3160       type = TREE_TYPE (TREE_TYPE (array));
3161       rval = build4 (ARRAY_REF, type, array, idx, NULL_TREE, NULL_TREE);
3162       /* Array ref is const/volatile if the array elements are
3163          or if the array is..  */
3164       TREE_READONLY (rval)
3165         |= (CP_TYPE_CONST_P (type) | TREE_READONLY (array));
3166       TREE_SIDE_EFFECTS (rval)
3167         |= (CP_TYPE_VOLATILE_P (type) | TREE_SIDE_EFFECTS (array));
3168       TREE_THIS_VOLATILE (rval)
3169         |= (CP_TYPE_VOLATILE_P (type) | TREE_THIS_VOLATILE (array));
3170       ret = require_complete_type_sfinae (fold_if_not_in_template (rval),
3171                                           complain);
3172       protected_set_expr_location (ret, loc);
3173       if (non_lvalue)
3174         ret = non_lvalue_loc (loc, ret);
3175       return ret;
3176     }
3177
3178   {
3179     tree ar = cp_default_conversion (array, complain);
3180     tree ind = cp_default_conversion (idx, complain);
3181
3182     /* Put the integer in IND to simplify error checking.  */
3183     if (TREE_CODE (TREE_TYPE (ar)) == INTEGER_TYPE)
3184       {
3185         tree temp = ar;
3186         ar = ind;
3187         ind = temp;
3188       }
3189
3190     if (ar == error_mark_node || ind == error_mark_node)
3191       return error_mark_node;
3192
3193     if (!TYPE_PTR_P (TREE_TYPE (ar)))
3194       {
3195         if (complain & tf_error)
3196           error_at (loc, "subscripted value is neither array nor pointer");
3197         return error_mark_node;
3198       }
3199     if (TREE_CODE (TREE_TYPE (ind)) != INTEGER_TYPE)
3200       {
3201         if (complain & tf_error)
3202           error_at (loc, "array subscript is not an integer");
3203         return error_mark_node;
3204       }
3205
3206     warn_array_subscript_with_type_char (loc, idx);
3207
3208     ret = cp_build_indirect_ref (cp_build_binary_op (input_location,
3209                                                      PLUS_EXPR, ar, ind,
3210                                                      complain),
3211                                  RO_ARRAY_INDEXING,
3212                                  complain);
3213     protected_set_expr_location (ret, loc);
3214     if (non_lvalue)
3215       ret = non_lvalue_loc (loc, ret);
3216     return ret;
3217   }
3218 }
3219
3220 /* Entry point for Obj-C++.  */
3221
3222 tree
3223 build_array_ref (location_t loc, tree array, tree idx)
3224 {
3225   return cp_build_array_ref (loc, array, idx, tf_warning_or_error);
3226 }
3227 \f
3228 /* Resolve a pointer to member function.  INSTANCE is the object
3229    instance to use, if the member points to a virtual member.
3230
3231    This used to avoid checking for virtual functions if basetype
3232    has no virtual functions, according to an earlier ANSI draft.
3233    With the final ISO C++ rules, such an optimization is
3234    incorrect: A pointer to a derived member can be static_cast
3235    to pointer-to-base-member, as long as the dynamic object
3236    later has the right member.  So now we only do this optimization
3237    when we know the dynamic type of the object.  */
3238
3239 tree
3240 get_member_function_from_ptrfunc (tree *instance_ptrptr, tree function,
3241                                   tsubst_flags_t complain)
3242 {
3243   if (TREE_CODE (function) == OFFSET_REF)
3244     function = TREE_OPERAND (function, 1);
3245
3246   if (TYPE_PTRMEMFUNC_P (TREE_TYPE (function)))
3247     {
3248       tree idx, delta, e1, e2, e3, vtbl;
3249       bool nonvirtual;
3250       tree fntype = TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (function));
3251       tree basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (fntype));
3252
3253       tree instance_ptr = *instance_ptrptr;
3254       tree instance_save_expr = 0;
3255       if (instance_ptr == error_mark_node)
3256         {
3257           if (TREE_CODE (function) == PTRMEM_CST)
3258             {
3259               /* Extracting the function address from a pmf is only
3260                  allowed with -Wno-pmf-conversions. It only works for
3261                  pmf constants.  */
3262               e1 = build_addr_func (PTRMEM_CST_MEMBER (function), complain);
3263               e1 = convert (fntype, e1);
3264               return e1;
3265             }
3266           else
3267             {
3268               if (complain & tf_error)
3269                 error ("object missing in use of %qE", function);
3270               return error_mark_node;
3271             }
3272         }
3273
3274       /* True if we know that the dynamic type of the object doesn't have
3275          virtual functions, so we can assume the PFN field is a pointer.  */
3276       nonvirtual = (COMPLETE_TYPE_P (basetype)
3277                     && !TYPE_POLYMORPHIC_P (basetype)
3278                     && resolves_to_fixed_type_p (instance_ptr, 0));
3279
3280       /* If we don't really have an object (i.e. in an ill-formed
3281          conversion from PMF to pointer), we can't resolve virtual
3282          functions anyway.  */
3283       if (!nonvirtual && is_dummy_object (instance_ptr))
3284         nonvirtual = true;
3285
3286       if (TREE_SIDE_EFFECTS (instance_ptr))
3287         instance_ptr = instance_save_expr = save_expr (instance_ptr);
3288
3289       if (TREE_SIDE_EFFECTS (function))
3290         function = save_expr (function);
3291
3292       /* Start by extracting all the information from the PMF itself.  */
3293       e3 = pfn_from_ptrmemfunc (function);
3294       delta = delta_from_ptrmemfunc (function);
3295       idx = build1 (NOP_EXPR, vtable_index_type, e3);
3296       switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
3297         {
3298         case ptrmemfunc_vbit_in_pfn:
3299           e1 = cp_build_binary_op (input_location,
3300                                    BIT_AND_EXPR, idx, integer_one_node,
3301                                    complain);
3302           idx = cp_build_binary_op (input_location,
3303                                     MINUS_EXPR, idx, integer_one_node,
3304                                     complain);
3305           if (idx == error_mark_node)
3306             return error_mark_node;
3307           break;
3308
3309         case ptrmemfunc_vbit_in_delta:
3310           e1 = cp_build_binary_op (input_location,
3311                                    BIT_AND_EXPR, delta, integer_one_node,
3312                                    complain);
3313           delta = cp_build_binary_op (input_location,
3314                                       RSHIFT_EXPR, delta, integer_one_node,
3315                                       complain);
3316           if (delta == error_mark_node)
3317             return error_mark_node;
3318           break;
3319
3320         default:
3321           gcc_unreachable ();
3322         }
3323
3324       if (e1 == error_mark_node)
3325         return error_mark_node;
3326
3327       /* Convert down to the right base before using the instance.  A
3328          special case is that in a pointer to member of class C, C may
3329          be incomplete.  In that case, the function will of course be
3330          a member of C, and no conversion is required.  In fact,
3331          lookup_base will fail in that case, because incomplete
3332          classes do not have BINFOs.  */
3333       if (!same_type_ignoring_top_level_qualifiers_p
3334           (basetype, TREE_TYPE (TREE_TYPE (instance_ptr))))
3335         {
3336           basetype = lookup_base (TREE_TYPE (TREE_TYPE (instance_ptr)),
3337                                   basetype, ba_check, NULL, complain);
3338           instance_ptr = build_base_path (PLUS_EXPR, instance_ptr, basetype,
3339                                           1, complain);
3340           if (instance_ptr == error_mark_node)
3341             return error_mark_node;
3342         }
3343       /* ...and then the delta in the PMF.  */
3344       instance_ptr = fold_build_pointer_plus (instance_ptr, delta);
3345
3346       /* Hand back the adjusted 'this' argument to our caller.  */
3347       *instance_ptrptr = instance_ptr;
3348
3349       if (nonvirtual)
3350         /* Now just return the pointer.  */
3351         return e3;
3352
3353       /* Next extract the vtable pointer from the object.  */
3354       vtbl = build1 (NOP_EXPR, build_pointer_type (vtbl_ptr_type_node),
3355                      instance_ptr);
3356       vtbl = cp_build_indirect_ref (vtbl, RO_NULL, complain);
3357       if (vtbl == error_mark_node)
3358         return error_mark_node;
3359
3360       /* Finally, extract the function pointer from the vtable.  */
3361       e2 = fold_build_pointer_plus_loc (input_location, vtbl, idx);
3362       e2 = cp_build_indirect_ref (e2, RO_NULL, complain);
3363       if (e2 == error_mark_node)
3364         return error_mark_node;
3365       TREE_CONSTANT (e2) = 1;
3366
3367       /* When using function descriptors, the address of the
3368          vtable entry is treated as a function pointer.  */
3369       if (TARGET_VTABLE_USES_DESCRIPTORS)
3370         e2 = build1 (NOP_EXPR, TREE_TYPE (e2),
3371                      cp_build_addr_expr (e2, complain));
3372
3373       e2 = fold_convert (TREE_TYPE (e3), e2);
3374       e1 = build_conditional_expr (input_location, e1, e2, e3, complain);
3375       if (e1 == error_mark_node)
3376         return error_mark_node;
3377
3378       /* Make sure this doesn't get evaluated first inside one of the
3379          branches of the COND_EXPR.  */
3380       if (instance_save_expr)
3381         e1 = build2 (COMPOUND_EXPR, TREE_TYPE (e1),
3382                      instance_save_expr, e1);
3383
3384       function = e1;
3385     }
3386   return function;
3387 }
3388
3389 /* Used by the C-common bits.  */
3390 tree
3391 build_function_call (location_t /*loc*/, 
3392                      tree function, tree params)
3393 {
3394   return cp_build_function_call (function, params, tf_warning_or_error);
3395 }
3396
3397 /* Used by the C-common bits.  */
3398 tree
3399 build_function_call_vec (location_t /*loc*/, vec<location_t> /*arg_loc*/,
3400                          tree function, vec<tree, va_gc> *params,
3401                          vec<tree, va_gc> * /*origtypes*/)
3402 {
3403   vec<tree, va_gc> *orig_params = params;
3404   tree ret = cp_build_function_call_vec (function, &params,
3405                                          tf_warning_or_error);
3406
3407   /* cp_build_function_call_vec can reallocate PARAMS by adding
3408      default arguments.  That should never happen here.  Verify
3409      that.  */
3410   gcc_assert (params == orig_params);
3411
3412   return ret;
3413 }
3414
3415 /* Build a function call using a tree list of arguments.  */
3416
3417 static tree
3418 cp_build_function_call (tree function, tree params, tsubst_flags_t complain)
3419 {
3420   vec<tree, va_gc> *vec;
3421   tree ret;
3422
3423   vec = make_tree_vector ();
3424   for (; params != NULL_TREE; params = TREE_CHAIN (params))
3425     vec_safe_push (vec, TREE_VALUE (params));
3426   ret = cp_build_function_call_vec (function, &vec, complain);
3427   release_tree_vector (vec);
3428   return ret;
3429 }
3430
3431 /* Build a function call using varargs.  */
3432
3433 tree
3434 cp_build_function_call_nary (tree function, tsubst_flags_t complain, ...)
3435 {
3436   vec<tree, va_gc> *vec;
3437   va_list args;
3438   tree ret, t;
3439
3440   vec = make_tree_vector ();
3441   va_start (args, complain);
3442   for (t = va_arg (args, tree); t != NULL_TREE; t = va_arg (args, tree))
3443     vec_safe_push (vec, t);
3444   va_end (args);
3445   ret = cp_build_function_call_vec (function, &vec, complain);
3446   release_tree_vector (vec);
3447   return ret;
3448 }
3449
3450 /* Build a function call using a vector of arguments.  PARAMS may be
3451    NULL if there are no parameters.  This changes the contents of
3452    PARAMS.  */
3453
3454 tree
3455 cp_build_function_call_vec (tree function, vec<tree, va_gc> **params,
3456                             tsubst_flags_t complain)
3457 {
3458   tree fntype, fndecl;
3459   int is_method;
3460   tree original = function;
3461   int nargs;
3462   tree *argarray;
3463   tree parm_types;
3464   vec<tree, va_gc> *allocated = NULL;
3465   tree ret;
3466
3467   /* For Objective-C, convert any calls via a cast to OBJC_TYPE_REF
3468      expressions, like those used for ObjC messenger dispatches.  */
3469   if (params != NULL && !vec_safe_is_empty (*params))
3470     function = objc_rewrite_function_call (function, (**params)[0]);
3471
3472   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
3473      Strip such NOP_EXPRs, since FUNCTION is used in non-lvalue context.  */
3474   if (TREE_CODE (function) == NOP_EXPR
3475       && TREE_TYPE (function) == TREE_TYPE (TREE_OPERAND (function, 0)))
3476     function = TREE_OPERAND (function, 0);
3477
3478   if (TREE_CODE (function) == FUNCTION_DECL)
3479     {
3480       mark_used (function);
3481       fndecl = function;
3482
3483       /* Convert anything with function type to a pointer-to-function.  */
3484       if (DECL_MAIN_P (function))
3485         {
3486           if (complain & tf_error)
3487             pedwarn (input_location, OPT_Wpedantic, 
3488                      "ISO C++ forbids calling %<::main%> from within program");
3489           else
3490             return error_mark_node;
3491         }
3492       function = build_addr_func (function, complain);
3493     }
3494   else
3495     {
3496       fndecl = NULL_TREE;
3497
3498       function = build_addr_func (function, complain);
3499     }
3500
3501   if (function == error_mark_node)
3502     return error_mark_node;
3503
3504   fntype = TREE_TYPE (function);
3505
3506   if (TYPE_PTRMEMFUNC_P (fntype))
3507     {
3508       if (complain & tf_error)
3509         error ("must use %<.*%> or %<->*%> to call pointer-to-member "
3510                "function in %<%E (...)%>, e.g. %<(... ->* %E) (...)%>",
3511                original, original);
3512       return error_mark_node;
3513     }
3514
3515   is_method = (TYPE_PTR_P (fntype)
3516                && TREE_CODE (TREE_TYPE (fntype)) == METHOD_TYPE);
3517
3518   if (!(TYPE_PTRFN_P (fntype)
3519         || is_method
3520         || TREE_CODE (function) == TEMPLATE_ID_EXPR))
3521     {
3522       if (complain & tf_error)
3523         {
3524           if (!flag_diagnostics_show_caret)
3525             error_at (input_location,
3526                       "%qE cannot be used as a function", original);
3527           else if (DECL_P (original))
3528             error_at (input_location,
3529                       "%qD cannot be used as a function", original);
3530           else 
3531             error_at (input_location,
3532                       "expression cannot be used as a function");
3533         }
3534
3535       return error_mark_node;
3536     }
3537
3538   /* fntype now gets the type of function pointed to.  */
3539   fntype = TREE_TYPE (fntype);
3540   parm_types = TYPE_ARG_TYPES (fntype);
3541
3542   if (params == NULL)
3543     {
3544       allocated = make_tree_vector ();
3545       params = &allocated;
3546     }
3547
3548     nargs = convert_arguments (parm_types, params, fndecl, LOOKUP_NORMAL,
3549                                complain);
3550   if (nargs < 0)
3551     return error_mark_node;
3552
3553   argarray = (*params)->address ();
3554
3555   /* Check for errors in format strings and inappropriately
3556      null parameters.  */
3557   check_function_arguments (fntype, nargs, argarray);
3558
3559   ret = build_cxx_call (function, nargs, argarray, complain);
3560
3561   if (allocated != NULL)
3562     release_tree_vector (allocated);
3563
3564   return ret;
3565 }
3566 \f
3567 /* Subroutine of convert_arguments.
3568    Warn about wrong number of args are genereted. */
3569
3570 static void
3571 warn_args_num (location_t loc, tree fndecl, bool too_many_p)
3572 {
3573   if (fndecl)
3574     {
3575       if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE)
3576         {
3577           if (DECL_NAME (fndecl) == NULL_TREE
3578               || IDENTIFIER_HAS_TYPE_VALUE (DECL_NAME (fndecl)))
3579             error_at (loc,
3580                       too_many_p
3581                       ? G_("too many arguments to constructor %q#D")
3582                       : G_("too few arguments to constructor %q#D"),
3583                       fndecl);
3584           else
3585             error_at (loc,
3586                       too_many_p
3587                       ? G_("too many arguments to member function %q#D")
3588                       : G_("too few arguments to member function %q#D"),
3589                       fndecl);
3590         }
3591       else
3592         error_at (loc,
3593                   too_many_p
3594                   ? G_("too many arguments to function %q#D")
3595                   : G_("too few arguments to function %q#D"),
3596                   fndecl);
3597       inform (DECL_SOURCE_LOCATION (fndecl),
3598               "declared here");
3599     }
3600   else
3601     {
3602       if (c_dialect_objc ()  &&  objc_message_selector ())
3603         error_at (loc,
3604                   too_many_p 
3605                   ? G_("too many arguments to method %q#D")
3606                   : G_("too few arguments to method %q#D"),
3607                   objc_message_selector ());
3608       else
3609         error_at (loc, too_many_p ? G_("too many arguments to function")
3610                                   : G_("too few arguments to function"));
3611     }
3612 }
3613
3614 /* Convert the actual parameter expressions in the list VALUES to the
3615    types in the list TYPELIST.  The converted expressions are stored
3616    back in the VALUES vector.
3617    If parmdecls is exhausted, or when an element has NULL as its type,
3618    perform the default conversions.
3619
3620    NAME is an IDENTIFIER_NODE or 0.  It is used only for error messages.
3621
3622    This is also where warnings about wrong number of args are generated.
3623
3624    Returns the actual number of arguments processed (which might be less
3625    than the length of the vector), or -1 on error.
3626
3627    In C++, unspecified trailing parameters can be filled in with their
3628    default arguments, if such were specified.  Do so here.  */
3629
3630 static int
3631 convert_arguments (tree typelist, vec<tree, va_gc> **values, tree fndecl,
3632                    int flags, tsubst_flags_t complain)
3633 {
3634   tree typetail;
3635   unsigned int i;
3636
3637   /* Argument passing is always copy-initialization.  */
3638   flags |= LOOKUP_ONLYCONVERTING;
3639
3640   for (i = 0, typetail = typelist;
3641        i < vec_safe_length (*values);
3642        i++)
3643     {
3644       tree type = typetail ? TREE_VALUE (typetail) : 0;
3645       tree val = (**values)[i];
3646
3647       if (val == error_mark_node || type == error_mark_node)
3648         return -1;
3649
3650       if (type == void_type_node)
3651         {
3652           if (complain & tf_error)
3653             {
3654               warn_args_num (input_location, fndecl, /*too_many_p=*/true);
3655               return i;
3656             }
3657           else
3658             return -1;
3659         }
3660
3661       /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
3662          Strip such NOP_EXPRs, since VAL is used in non-lvalue context.  */
3663       if (TREE_CODE (val) == NOP_EXPR
3664           && TREE_TYPE (val) == TREE_TYPE (TREE_OPERAND (val, 0))
3665           && (type == 0 || TREE_CODE (type) != REFERENCE_TYPE))
3666         val = TREE_OPERAND (val, 0);
3667
3668       if (type == 0 || TREE_CODE (type) != REFERENCE_TYPE)
3669         {
3670           if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE
3671               || TREE_CODE (TREE_TYPE (val)) == FUNCTION_TYPE
3672               || TREE_CODE (TREE_TYPE (val)) == METHOD_TYPE)
3673             val = decay_conversion (val, complain);
3674         }
3675
3676       if (val == error_mark_node)
3677         return -1;
3678
3679       if (type != 0)
3680         {
3681           /* Formal parm type is specified by a function prototype.  */
3682           tree parmval;
3683
3684           if (!COMPLETE_TYPE_P (complete_type (type)))
3685             {
3686               if (complain & tf_error)
3687                 {
3688                   if (fndecl)
3689                     error ("parameter %P of %qD has incomplete type %qT",
3690                            i, fndecl, type);
3691                   else
3692                     error ("parameter %P has incomplete type %qT", i, type);
3693                 }
3694               parmval = error_mark_node;
3695             }
3696           else
3697             {
3698               parmval = convert_for_initialization
3699                 (NULL_TREE, type, val, flags,
3700                  ICR_ARGPASS, fndecl, i, complain);
3701               parmval = convert_for_arg_passing (type, parmval, complain);
3702             }
3703
3704           if (parmval == error_mark_node)
3705             return -1;
3706
3707           (**values)[i] = parmval;
3708         }
3709       else
3710         {
3711           if (fndecl && magic_varargs_p (fndecl))
3712             /* Don't do ellipsis conversion for __built_in_constant_p
3713                as this will result in spurious errors for non-trivial
3714                types.  */
3715             val = require_complete_type_sfinae (val, complain);
3716           else
3717             val = convert_arg_to_ellipsis (val, complain);
3718
3719           (**values)[i] = val;
3720         }
3721
3722       if (typetail)
3723         typetail = TREE_CHAIN (typetail);
3724     }
3725
3726   if (typetail != 0 && typetail != void_list_node)
3727     {
3728       /* See if there are default arguments that can be used.  Because
3729          we hold default arguments in the FUNCTION_TYPE (which is so
3730          wrong), we can see default parameters here from deduced
3731          contexts (and via typeof) for indirect function calls.
3732          Fortunately we know whether we have a function decl to
3733          provide default arguments in a language conformant
3734          manner.  */
3735       if (fndecl && TREE_PURPOSE (typetail)
3736           && TREE_CODE (TREE_PURPOSE (typetail)) != DEFAULT_ARG)
3737         {
3738           for (; typetail != void_list_node; ++i)
3739             {
3740               tree parmval
3741                 = convert_default_arg (TREE_VALUE (typetail),
3742                                        TREE_PURPOSE (typetail),
3743                                        fndecl, i, complain);
3744
3745               if (parmval == error_mark_node)
3746                 return -1;
3747
3748               vec_safe_push (*values, parmval);
3749               typetail = TREE_CHAIN (typetail);
3750               /* ends with `...'.  */
3751               if (typetail == NULL_TREE)
3752                 break;
3753             }
3754         }
3755       else
3756         {
3757           if (complain & tf_error)
3758             warn_args_num (input_location, fndecl, /*too_many_p=*/false);
3759           return -1;
3760         }
3761     }
3762
3763   return (int) i;
3764 }
3765 \f
3766 /* Build a binary-operation expression, after performing default
3767    conversions on the operands.  CODE is the kind of expression to
3768    build.  ARG1 and ARG2 are the arguments.  ARG1_CODE and ARG2_CODE
3769    are the tree codes which correspond to ARG1 and ARG2 when issuing
3770    warnings about possibly misplaced parentheses.  They may differ
3771    from the TREE_CODE of ARG1 and ARG2 if the parser has done constant
3772    folding (e.g., if the parser sees "a | 1 + 1", it may call this
3773    routine with ARG2 being an INTEGER_CST and ARG2_CODE == PLUS_EXPR).
3774    To avoid issuing any parentheses warnings, pass ARG1_CODE and/or
3775    ARG2_CODE as ERROR_MARK.  */
3776
3777 tree
3778 build_x_binary_op (location_t loc, enum tree_code code, tree arg1,
3779                    enum tree_code arg1_code, tree arg2,
3780                    enum tree_code arg2_code, tree *overload,
3781                    tsubst_flags_t complain)
3782 {
3783   tree orig_arg1;
3784   tree orig_arg2;
3785   tree expr;
3786
3787   orig_arg1 = arg1;
3788   orig_arg2 = arg2;
3789
3790   if (processing_template_decl)
3791     {
3792       if (type_dependent_expression_p (arg1)
3793           || type_dependent_expression_p (arg2))
3794         return build_min_nt_loc (loc, code, arg1, arg2);
3795       arg1 = build_non_dependent_expr (arg1);
3796       arg2 = build_non_dependent_expr (arg2);
3797     }
3798
3799   if (code == DOTSTAR_EXPR)
3800     expr = build_m_component_ref (arg1, arg2, complain);
3801   else
3802     expr = build_new_op (loc, code, LOOKUP_NORMAL, arg1, arg2, NULL_TREE,
3803                          overload, complain);
3804
3805   /* Check for cases such as x+y<<z which users are likely to
3806      misinterpret.  But don't warn about obj << x + y, since that is a
3807      common idiom for I/O.  */
3808   if (warn_parentheses
3809       && (complain & tf_warning)
3810       && !processing_template_decl
3811       && !error_operand_p (arg1)
3812       && !error_operand_p (arg2)
3813       && (code != LSHIFT_EXPR
3814           || !CLASS_TYPE_P (TREE_TYPE (arg1))))
3815     warn_about_parentheses (loc, code, arg1_code, orig_arg1,
3816                             arg2_code, orig_arg2);
3817
3818   if (processing_template_decl && expr != error_mark_node)
3819     return build_min_non_dep (code, expr, orig_arg1, orig_arg2);
3820
3821   return expr;
3822 }
3823
3824 /* Build and return an ARRAY_REF expression.  */
3825
3826 tree
3827 build_x_array_ref (location_t loc, tree arg1, tree arg2,
3828                    tsubst_flags_t complain)
3829 {
3830   tree orig_arg1 = arg1;
3831   tree orig_arg2 = arg2;
3832   tree expr;
3833
3834   if (processing_template_decl)
3835     {
3836       if (type_dependent_expression_p (arg1)
3837           || type_dependent_expression_p (arg2))
3838         return build_min_nt_loc (loc, ARRAY_REF, arg1, arg2,
3839                                  NULL_TREE, NULL_TREE);
3840       arg1 = build_non_dependent_expr (arg1);
3841       arg2 = build_non_dependent_expr (arg2);
3842     }
3843
3844   expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, arg1, arg2,
3845                        NULL_TREE, /*overload=*/NULL, complain);
3846
3847   if (processing_template_decl && expr != error_mark_node)
3848     return build_min_non_dep (ARRAY_REF, expr, orig_arg1, orig_arg2,
3849                               NULL_TREE, NULL_TREE);
3850   return expr;
3851 }
3852
3853 /* Return whether OP is an expression of enum type cast to integer
3854    type.  In C++ even unsigned enum types are cast to signed integer
3855    types.  We do not want to issue warnings about comparisons between
3856    signed and unsigned types when one of the types is an enum type.
3857    Those warnings are always false positives in practice.  */
3858
3859 static bool
3860 enum_cast_to_int (tree op)
3861 {
3862   if (CONVERT_EXPR_P (op)
3863       && TREE_TYPE (op) == integer_type_node
3864       && TREE_CODE (TREE_TYPE (TREE_OPERAND (op, 0))) == ENUMERAL_TYPE
3865       && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op, 0))))
3866     return true;
3867
3868   /* The cast may have been pushed into a COND_EXPR.  */
3869   if (TREE_CODE (op) == COND_EXPR)
3870     return (enum_cast_to_int (TREE_OPERAND (op, 1))
3871             || enum_cast_to_int (TREE_OPERAND (op, 2)));
3872
3873   return false;
3874 }
3875
3876 /* For the c-common bits.  */
3877 tree
3878 build_binary_op (location_t location, enum tree_code code, tree op0, tree op1,
3879                  int /*convert_p*/)
3880 {
3881   return cp_build_binary_op (location, code, op0, op1, tf_warning_or_error);
3882 }
3883
3884
3885 /* Build a binary-operation expression without default conversions.
3886    CODE is the kind of expression to build.
3887    LOCATION is the location_t of the operator in the source code.
3888    This function differs from `build' in several ways:
3889    the data type of the result is computed and recorded in it,
3890    warnings are generated if arg data types are invalid,
3891    special handling for addition and subtraction of pointers is known,
3892    and some optimization is done (operations on narrow ints
3893    are done in the narrower type when that gives the same result).
3894    Constant folding is also done before the result is returned.
3895
3896    Note that the operands will never have enumeral types
3897    because either they have just had the default conversions performed
3898    or they have both just been converted to some other type in which
3899    the arithmetic is to be done.
3900
3901    C++: must do special pointer arithmetic when implementing
3902    multiple inheritance, and deal with pointer to member functions.  */
3903
3904 tree
3905 cp_build_binary_op (location_t location,
3906                     enum tree_code code, tree orig_op0, tree orig_op1,
3907                     tsubst_flags_t complain)
3908 {
3909   tree op0, op1;
3910   enum tree_code code0, code1;
3911   tree type0, type1;
3912   const char *invalid_op_diag;
3913
3914   /* Expression code to give to the expression when it is built.
3915      Normally this is CODE, which is what the caller asked for,
3916      but in some special cases we change it.  */
3917   enum tree_code resultcode = code;
3918
3919   /* Data type in which the computation is to be performed.
3920      In the simplest cases this is the common type of the arguments.  */
3921   tree result_type = NULL;
3922
3923   /* Nonzero means operands have already been type-converted
3924      in whatever way is necessary.
3925      Zero means they need to be converted to RESULT_TYPE.  */
3926   int converted = 0;
3927
3928   /* Nonzero means create the expression with this type, rather than
3929      RESULT_TYPE.  */
3930   tree build_type = 0;
3931
3932   /* Nonzero means after finally constructing the expression
3933      convert it to this type.  */
3934   tree final_type = 0;
3935
3936   tree result;
3937   tree orig_type = NULL;
3938
3939   /* Nonzero if this is an operation like MIN or MAX which can
3940      safely be computed in short if both args are promoted shorts.
3941      Also implies COMMON.
3942      -1 indicates a bitwise operation; this makes a difference
3943      in the exact conditions for when it is safe to do the operation
3944      in a narrower mode.  */
3945   int shorten = 0;
3946
3947   /* Nonzero if this is a comparison operation;
3948      if both args are promoted shorts, compare the original shorts.
3949      Also implies COMMON.  */
3950   int short_compare = 0;
3951
3952   /* Nonzero means set RESULT_TYPE to the common type of the args.  */
3953   int common = 0;
3954
3955   /* True if both operands have arithmetic type.  */
3956   bool arithmetic_types_p;
3957
3958   /* Apply default conversions.  */
3959   op0 = orig_op0;
3960   op1 = orig_op1;
3961
3962   /* Remember whether we're doing / or %.  */
3963   bool doing_div_or_mod = false;
3964
3965   /* Remember whether we're doing << or >>.  */
3966   bool doing_shift = false;
3967
3968   /* Tree holding instrumentation expression.  */
3969   tree instrument_expr = NULL;
3970
3971   if (code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR
3972       || code == TRUTH_OR_EXPR || code == TRUTH_ORIF_EXPR
3973       || code == TRUTH_XOR_EXPR)
3974     {
3975       if (!really_overloaded_fn (op0) && !VOID_TYPE_P (TREE_TYPE (op0)))
3976         op0 = decay_conversion (op0, complain);
3977       if (!really_overloaded_fn (op1) && !VOID_TYPE_P (TREE_TYPE (op1)))
3978         op1 = decay_conversion (op1, complain);
3979     }
3980   else
3981     {
3982       if (!really_overloaded_fn (op0) && !VOID_TYPE_P (TREE_TYPE (op0)))
3983         op0 = cp_default_conversion (op0, complain);
3984       if (!really_overloaded_fn (op1) && !VOID_TYPE_P (TREE_TYPE (op1)))
3985         op1 = cp_default_conversion (op1, complain);
3986     }
3987
3988   /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue.  */
3989   STRIP_TYPE_NOPS (op0);
3990   STRIP_TYPE_NOPS (op1);
3991
3992   /* DTRT if one side is an overloaded function, but complain about it.  */
3993   if (type_unknown_p (op0))
3994     {
3995       tree t = instantiate_type (TREE_TYPE (op1), op0, tf_none);
3996       if (t != error_mark_node)
3997         {
3998           if (complain & tf_error)
3999             permerror (input_location, "assuming cast to type %qT from overloaded function",
4000                        TREE_TYPE (t));
4001           op0 = t;
4002         }
4003     }
4004   if (type_unknown_p (op1))
4005     {
4006       tree t = instantiate_type (TREE_TYPE (op0), op1, tf_none);
4007       if (t != error_mark_node)
4008         {
4009           if (complain & tf_error)
4010             permerror (input_location, "assuming cast to type %qT from overloaded function",
4011                        TREE_TYPE (t));
4012           op1 = t;
4013         }
4014     }
4015
4016   type0 = TREE_TYPE (op0); 
4017   type1 = TREE_TYPE (op1);
4018
4019   /* The expression codes of the data types of the arguments tell us
4020      whether the arguments are integers, floating, pointers, etc.  */
4021   code0 = TREE_CODE (type0);
4022   code1 = TREE_CODE (type1);
4023
4024   /* If an error was already reported for one of the arguments,
4025      avoid reporting another error.  */
4026   if (code0 == ERROR_MARK || code1 == ERROR_MARK)
4027     return error_mark_node;
4028
4029   if ((invalid_op_diag
4030        = targetm.invalid_binary_op (code, type0, type1)))
4031     {
4032       if (complain & tf_error)
4033         error (invalid_op_diag);
4034       return error_mark_node;
4035     }
4036
4037   /* Issue warnings about peculiar, but valid, uses of NULL.  */
4038   if ((orig_op0 == null_node || orig_op1 == null_node)
4039       /* It's reasonable to use pointer values as operands of &&
4040          and ||, so NULL is no exception.  */
4041       && code != TRUTH_ANDIF_EXPR && code != TRUTH_ORIF_EXPR 
4042       && ( /* Both are NULL (or 0) and the operation was not a
4043               comparison or a pointer subtraction.  */
4044           (null_ptr_cst_p (orig_op0) && null_ptr_cst_p (orig_op1) 
4045            && code != EQ_EXPR && code != NE_EXPR && code != MINUS_EXPR) 
4046           /* Or if one of OP0 or OP1 is neither a pointer nor NULL.  */
4047           || (!null_ptr_cst_p (orig_op0)
4048               && !TYPE_PTR_OR_PTRMEM_P (type0))
4049           || (!null_ptr_cst_p (orig_op1) 
4050               && !TYPE_PTR_OR_PTRMEM_P (type1)))
4051       && (complain & tf_warning))
4052     {
4053       source_location loc =
4054         expansion_point_location_if_in_system_header (input_location);
4055
4056       warning_at (loc, OPT_Wpointer_arith, "NULL used in arithmetic");
4057     }
4058
4059   /* In case when one of the operands of the binary operation is
4060      a vector and another is a scalar -- convert scalar to vector.  */
4061   if ((code0 == VECTOR_TYPE) != (code1 == VECTOR_TYPE))
4062     {
4063       enum stv_conv convert_flag = scalar_to_vector (location, code, op0, op1,
4064                                                      complain & tf_error);
4065
4066       switch (convert_flag)
4067         {
4068           case stv_error:
4069             return error_mark_node;
4070           case stv_firstarg:
4071             {
4072               op0 = convert (TREE_TYPE (type1), op0);
4073               op0 = save_expr (op0);
4074               op0 = build_vector_from_val (type1, op0);
4075               type0 = TREE_TYPE (op0);
4076               code0 = TREE_CODE (type0);
4077               converted = 1;
4078               break;
4079             }
4080           case stv_secondarg:
4081             {
4082               op1 = convert (TREE_TYPE (type0), op1);
4083               op1 = save_expr (op1);
4084               op1 = build_vector_from_val (type0, op1);
4085               type1 = TREE_TYPE (op1);
4086               code1 = TREE_CODE (type1);
4087               converted = 1;
4088               break;
4089             }
4090           default:
4091             break;
4092         }
4093     }
4094
4095   switch (code)
4096     {
4097     case MINUS_EXPR:
4098       /* Subtraction of two similar pointers.
4099          We must subtract them as integers, then divide by object size.  */
4100       if (code0 == POINTER_TYPE && code1 == POINTER_TYPE
4101           && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type0),
4102                                                         TREE_TYPE (type1)))
4103         return pointer_diff (op0, op1, common_pointer_type (type0, type1),
4104                              complain);
4105       /* In all other cases except pointer - int, the usual arithmetic
4106          rules apply.  */
4107       else if (!(code0 == POINTER_TYPE && code1 == INTEGER_TYPE))
4108         {
4109           common = 1;
4110           break;
4111         }
4112       /* The pointer - int case is just like pointer + int; fall
4113          through.  */
4114     case PLUS_EXPR:
4115       if ((code0 == POINTER_TYPE || code1 == POINTER_TYPE)
4116           && (code0 == INTEGER_TYPE || code1 == INTEGER_TYPE))
4117         {
4118           tree ptr_operand;
4119           tree int_operand;
4120           ptr_operand = ((code0 == POINTER_TYPE) ? op0 : op1);
4121           int_operand = ((code0 == INTEGER_TYPE) ? op0 : op1);
4122           if (processing_template_decl)
4123             {
4124               result_type = TREE_TYPE (ptr_operand);
4125               break;
4126             }
4127           return cp_pointer_int_sum (code,
4128                                      ptr_operand, 
4129                                      int_operand,
4130                                      complain);
4131         }
4132       common = 1;
4133       break;
4134
4135     case MULT_EXPR:
4136       common = 1;
4137       break;
4138
4139     case TRUNC_DIV_EXPR:
4140     case CEIL_DIV_EXPR:
4141     case FLOOR_DIV_EXPR:
4142     case ROUND_DIV_EXPR:
4143     case EXACT_DIV_EXPR:
4144       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
4145            || code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE)
4146           && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
4147               || code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE))
4148         {
4149           enum tree_code tcode0 = code0, tcode1 = code1;
4150           tree cop1 = fold_non_dependent_expr (op1);
4151           doing_div_or_mod = true;
4152           warn_for_div_by_zero (location, cop1);
4153
4154           if (tcode0 == COMPLEX_TYPE || tcode0 == VECTOR_TYPE)
4155             tcode0 = TREE_CODE (TREE_TYPE (TREE_TYPE (op0)));
4156           if (tcode1 == COMPLEX_TYPE || tcode1 == VECTOR_TYPE)
4157             tcode1 = TREE_CODE (TREE_TYPE (TREE_TYPE (op1)));
4158
4159           if (!(tcode0 == INTEGER_TYPE && tcode1 == INTEGER_TYPE))
4160             resultcode = RDIV_EXPR;
4161           else
4162             /* When dividing two signed integers, we have to promote to int.
4163                unless we divide by a constant != -1.  Note that default
4164                conversion will have been performed on the operands at this
4165                point, so we have to dig out the original type to find out if
4166                it was unsigned.  */
4167             shorten = ((TREE_CODE (op0) == NOP_EXPR
4168                         && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op0, 0))))
4169                        || (TREE_CODE (op1) == INTEGER_CST
4170                            && ! integer_all_onesp (op1)));
4171
4172           common = 1;
4173         }
4174       break;
4175
4176     case BIT_AND_EXPR:
4177     case BIT_IOR_EXPR:
4178     case BIT_XOR_EXPR:
4179       if ((code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
4180           || (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
4181               && !VECTOR_FLOAT_TYPE_P (type0)
4182               && !VECTOR_FLOAT_TYPE_P (type1)))
4183         shorten = -1;
4184       break;
4185
4186     case TRUNC_MOD_EXPR:
4187     case FLOOR_MOD_EXPR:
4188       {
4189         tree cop1 = fold_non_dependent_expr (op1);
4190         doing_div_or_mod = true;
4191         warn_for_div_by_zero (location, cop1);
4192       }
4193
4194       if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
4195           && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE
4196           && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
4197         common = 1;
4198       else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
4199         {
4200           /* Although it would be tempting to shorten always here, that loses
4201              on some targets, since the modulo instruction is undefined if the
4202              quotient can't be represented in the computation mode.  We shorten
4203              only if unsigned or if dividing by something we know != -1.  */
4204           shorten = ((TREE_CODE (op0) == NOP_EXPR
4205                       && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op0, 0))))
4206                      || (TREE_CODE (op1) == INTEGER_CST
4207                          && ! integer_all_onesp (op1)));
4208           common = 1;
4209         }
4210       break;
4211
4212     case TRUTH_ANDIF_EXPR:
4213     case TRUTH_ORIF_EXPR:
4214     case TRUTH_AND_EXPR:
4215     case TRUTH_OR_EXPR:
4216       if (!VECTOR_TYPE_P (type0) && VECTOR_TYPE_P (type1))
4217         {
4218           if (!COMPARISON_CLASS_P (op1))
4219             op1 = cp_build_binary_op (EXPR_LOCATION (op1), NE_EXPR, op1,
4220                                       build_zero_cst (type1), complain);
4221           if (code == TRUTH_ANDIF_EXPR)
4222             {
4223               tree z = build_zero_cst (TREE_TYPE (op1));
4224               return build_conditional_expr (location, op0, op1, z, complain);
4225             }
4226           else if (code == TRUTH_ORIF_EXPR)
4227             {
4228               tree m1 = build_all_ones_cst (TREE_TYPE (op1));
4229               return build_conditional_expr (location, op0, m1, op1, complain);
4230             }
4231           else
4232             gcc_unreachable ();
4233         }
4234       if (VECTOR_TYPE_P (type0))
4235         {
4236           if (!COMPARISON_CLASS_P (op0))
4237             op0 = cp_build_binary_op (EXPR_LOCATION (op0), NE_EXPR, op0,
4238                                       build_zero_cst (type0), complain);
4239           if (!VECTOR_TYPE_P (type1))
4240             {
4241               tree m1 = build_all_ones_cst (TREE_TYPE (op0));
4242               tree z = build_zero_cst (TREE_TYPE (op0));
4243               op1 = build_conditional_expr (location, op1, z, m1, complain);
4244             }
4245           else if (!COMPARISON_CLASS_P (op1))
4246             op1 = cp_build_binary_op (EXPR_LOCATION (op1), NE_EXPR, op1,
4247                                       build_zero_cst (type1), complain);
4248
4249           if (code == TRUTH_ANDIF_EXPR)
4250             code = BIT_AND_EXPR;
4251           else if (code == TRUTH_ORIF_EXPR)
4252             code = BIT_IOR_EXPR;
4253           else
4254             gcc_unreachable ();
4255
4256           return cp_build_binary_op (location, code, op0, op1, complain);
4257         }
4258
4259       result_type = boolean_type_node;
4260       break;
4261
4262       /* Shift operations: result has same type as first operand;
4263          always convert second operand to int.
4264          Also set SHORT_SHIFT if shifting rightward.  */
4265
4266     case RSHIFT_EXPR:
4267       if (code0 == VECTOR_TYPE && code1 == INTEGER_TYPE
4268           && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE)
4269         {
4270           result_type = type0;
4271           converted = 1;
4272         }
4273       else if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
4274           && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE
4275           && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE
4276           && TYPE_VECTOR_SUBPARTS (type0) == TYPE_VECTOR_SUBPARTS (type1))
4277         {
4278           result_type = type0;
4279           converted = 1;
4280         }
4281       else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
4282         {
4283           tree const_op1 = fold_non_dependent_expr (op1);
4284           if (TREE_CODE (const_op1) != INTEGER_CST)
4285             const_op1 = op1;
4286           result_type = type0;
4287           doing_shift = true;
4288           if (TREE_CODE (const_op1) == INTEGER_CST)
4289             {
4290               if (tree_int_cst_lt (const_op1, integer_zero_node))
4291                 {
4292                   if ((complain & tf_warning)
4293                       && c_inhibit_evaluation_warnings == 0)
4294                     warning (OPT_Wshift_count_negative,
4295                              "right shift count is negative");
4296                 }
4297               else
4298                 {
4299                   if (compare_tree_int (const_op1, TYPE_PRECISION (type0)) >= 0
4300                       && (complain & tf_warning)
4301                       && c_inhibit_evaluation_warnings == 0)
4302                     warning (OPT_Wshift_count_overflow,
4303                              "right shift count >= width of type");
4304                 }
4305             }
4306           /* Avoid converting op1 to result_type later.  */
4307           converted = 1;
4308         }
4309       break;
4310
4311     case LSHIFT_EXPR:
4312       if (code0 == VECTOR_TYPE && code1 == INTEGER_TYPE
4313           && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE)
4314         {
4315           result_type = type0;
4316           converted = 1;
4317         }
4318       else if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
4319           && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE
4320           && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE
4321           && TYPE_VECTOR_SUBPARTS (type0) == TYPE_VECTOR_SUBPARTS (type1))
4322         {
4323           result_type = type0;
4324           converted = 1;
4325         }
4326       else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
4327         {
4328           tree const_op1 = fold_non_dependent_expr (op1);
4329           if (TREE_CODE (const_op1) != INTEGER_CST)
4330             const_op1 = op1;
4331           result_type = type0;
4332           doing_shift = true;
4333           if (TREE_CODE (const_op1) == INTEGER_CST)
4334             {
4335               if (tree_int_cst_lt (const_op1, integer_zero_node))
4336                 {
4337                   if ((complain & tf_warning)
4338                       && c_inhibit_evaluation_warnings == 0)
4339                     warning (OPT_Wshift_count_negative,
4340                              "left shift count is negative");
4341                 }
4342               else if (compare_tree_int (const_op1,
4343                                          TYPE_PRECISION (type0)) >= 0)
4344                 {
4345                   if ((complain & tf_warning)
4346                       && c_inhibit_evaluation_warnings == 0)
4347                     warning (OPT_Wshift_count_overflow,
4348                              "left shift count >= width of type");
4349                 }
4350             }
4351           /* Avoid converting op1 to result_type later.  */
4352           converted = 1;
4353         }
4354       break;
4355
4356     case RROTATE_EXPR:
4357     case LROTATE_EXPR:
4358       if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
4359         {
4360           result_type = type0;
4361           if (TREE_CODE (op1) == INTEGER_CST)
4362             {
4363               if (tree_int_cst_lt (op1, integer_zero_node))
4364                 {
4365                   if (complain & tf_warning)
4366                     warning (0, (code == LROTATE_EXPR)
4367                                   ? G_("left rotate count is negative")
4368                                   : G_("right rotate count is negative"));
4369                 }
4370               else if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0)
4371                 {
4372                   if (complain & tf_warning)
4373                     warning (0, (code == LROTATE_EXPR) 
4374                                   ? G_("left rotate count >= width of type")
4375                                   : G_("right rotate count >= width of type"));
4376                 }
4377             }
4378           /* Convert the shift-count to an integer, regardless of
4379              size of value being shifted.  */
4380           if (TYPE_MAIN_VARIANT (TREE_TYPE (op1)) != integer_type_node)
4381             op1 = cp_convert (integer_type_node, op1, complain);
4382         }
4383       break;
4384
4385     case EQ_EXPR:
4386     case NE_EXPR:
4387       if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE)
4388         goto vector_compare;
4389       if ((complain & tf_warning)
4390           && (FLOAT_TYPE_P (type0) || FLOAT_TYPE_P (type1)))
4391         warning (OPT_Wfloat_equal,
4392                  "comparing floating point with == or != is unsafe");
4393       if ((complain & tf_warning)
4394           && ((TREE_CODE (orig_op0) == STRING_CST && !integer_zerop (op1))
4395               || (TREE_CODE (orig_op1) == STRING_CST && !integer_zerop (op0))))
4396         warning (OPT_Waddress, "comparison with string literal results in unspecified behaviour");
4397
4398       build_type = boolean_type_node;
4399       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
4400            || code0 == COMPLEX_TYPE || code0 == ENUMERAL_TYPE)
4401           && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
4402               || code1 == COMPLEX_TYPE || code1 == ENUMERAL_TYPE))
4403         short_compare = 1;
4404       else if (((code0 == POINTER_TYPE || TYPE_PTRDATAMEM_P (type0))
4405                 && null_ptr_cst_p (op1))
4406                /* Handle, eg, (void*)0 (c++/43906), and more.  */
4407                || (code0 == POINTER_TYPE
4408                    && TYPE_PTR_P (type1) && integer_zerop (op1)))
4409         {
4410           if (TYPE_PTR_P (type1))
4411             result_type = composite_pointer_type (type0, type1, op0, op1,
4412                                                   CPO_COMPARISON, complain);
4413           else
4414             result_type = type0;
4415
4416           if (TREE_CODE (op0) == ADDR_EXPR
4417               && decl_with_nonnull_addr_p (TREE_OPERAND (op0, 0)))
4418             {
4419               if ((complain & tf_warning)
4420                   && c_inhibit_evaluation_warnings == 0
4421                   && !TREE_NO_WARNING (op0))
4422                 warning (OPT_Waddress, "the address of %qD will never be NULL",
4423                          TREE_OPERAND (op0, 0));
4424             }
4425         }
4426       else if (((code1 == POINTER_TYPE || TYPE_PTRDATAMEM_P (type1))
4427                 && null_ptr_cst_p (op0))
4428                /* Handle, eg, (void*)0 (c++/43906), and more.  */
4429                || (code1 == POINTER_TYPE
4430                    && TYPE_PTR_P (type0) && integer_zerop (op0)))
4431         {
4432           if (TYPE_PTR_P (type0))
4433             result_type = composite_pointer_type (type0, type1, op0, op1,
4434                                                   CPO_COMPARISON, complain);
4435           else
4436             result_type = type1;
4437
4438           if (TREE_CODE (op1) == ADDR_EXPR 
4439               && decl_with_nonnull_addr_p (TREE_OPERAND (op1, 0)))
4440             {
4441               if ((complain & tf_warning)
4442                   && c_inhibit_evaluation_warnings == 0
4443                   && !TREE_NO_WARNING (op1))
4444                 warning (OPT_Waddress, "the address of %qD will never be NULL",
4445                          TREE_OPERAND (op1, 0));
4446             }
4447         }
4448       else if ((code0 == POINTER_TYPE && code1 == POINTER_TYPE)
4449                || (TYPE_PTRDATAMEM_P (type0) && TYPE_PTRDATAMEM_P (type1)))
4450         result_type = composite_pointer_type (type0, type1, op0, op1,
4451                                               CPO_COMPARISON, complain);
4452       else if (null_ptr_cst_p (op0) && null_ptr_cst_p (op1))
4453         /* One of the operands must be of nullptr_t type.  */
4454         result_type = TREE_TYPE (nullptr_node);
4455       else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
4456         {
4457           result_type = type0;
4458           if (complain & tf_error) 
4459             permerror (input_location, "ISO C++ forbids comparison between pointer and integer");
4460           else
4461             return error_mark_node;
4462         }
4463       else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
4464         {
4465           result_type = type1;
4466           if (complain & tf_error)
4467             permerror (input_location, "ISO C++ forbids comparison between pointer and integer");
4468           else
4469             return error_mark_node;
4470         }
4471       else if (TYPE_PTRMEMFUNC_P (type0) && null_ptr_cst_p (op1))
4472         {
4473           if (TARGET_PTRMEMFUNC_VBIT_LOCATION
4474               == ptrmemfunc_vbit_in_delta)
4475             {
4476               tree pfn0, delta0, e1, e2;
4477
4478               if (TREE_SIDE_EFFECTS (op0))
4479                 op0 = save_expr (op0);
4480
4481               pfn0 = pfn_from_ptrmemfunc (op0);
4482               delta0 = delta_from_ptrmemfunc (op0);
4483               e1 = cp_build_binary_op (location,
4484                                        EQ_EXPR,
4485                                        pfn0,
4486                                        build_zero_cst (TREE_TYPE (pfn0)),
4487                                        complain);
4488               e2 = cp_build_binary_op (location,
4489                                        BIT_AND_EXPR,
4490                                        delta0,
4491                                        integer_one_node,
4492                                        complain);
4493
4494               if (complain & tf_warning)
4495                 maybe_warn_zero_as_null_pointer_constant (op1, input_location);
4496
4497               e2 = cp_build_binary_op (location,
4498                                        EQ_EXPR, e2, integer_zero_node,
4499                                        complain);
4500               op0 = cp_build_binary_op (location,
4501                                         TRUTH_ANDIF_EXPR, e1, e2,
4502                                         complain);
4503               op1 = cp_convert (TREE_TYPE (op0), integer_one_node, complain); 
4504             }
4505           else 
4506             {
4507               op0 = build_ptrmemfunc_access_expr (op0, pfn_identifier);
4508               op1 = cp_convert (TREE_TYPE (op0), op1, complain);
4509             }
4510           result_type = TREE_TYPE (op0);
4511         }
4512       else if (TYPE_PTRMEMFUNC_P (type1) && null_ptr_cst_p (op0))
4513         return cp_build_binary_op (location, code, op1, op0, complain);
4514       else if (TYPE_PTRMEMFUNC_P (type0) && TYPE_PTRMEMFUNC_P (type1))
4515         {
4516           tree type;
4517           /* E will be the final comparison.  */
4518           tree e;
4519           /* E1 and E2 are for scratch.  */
4520           tree e1;
4521           tree e2;
4522           tree pfn0;
4523           tree pfn1;
4524           tree delta0;
4525           tree delta1;
4526
4527           type = composite_pointer_type (type0, type1, op0, op1, 
4528                                          CPO_COMPARISON, complain);
4529
4530           if (!same_type_p (TREE_TYPE (op0), type))
4531             op0 = cp_convert_and_check (type, op0, complain);
4532           if (!same_type_p (TREE_TYPE (op1), type))
4533             op1 = cp_convert_and_check (type, op1, complain);
4534
4535           if (op0 == error_mark_node || op1 == error_mark_node)
4536             return error_mark_node;
4537
4538           if (TREE_SIDE_EFFECTS (op0))
4539             op0 = save_expr (op0);
4540           if (TREE_SIDE_EFFECTS (op1))
4541             op1 = save_expr (op1);
4542
4543           pfn0 = pfn_from_ptrmemfunc (op0);
4544           /* Avoid -Waddress warnings (c++/64877).  */
4545           if (TREE_CODE (pfn0) == ADDR_EXPR)
4546             TREE_NO_WARNING (pfn0) = 1;
4547           pfn1 = pfn_from_ptrmemfunc (op1);
4548           delta0 = delta_from_ptrmemfunc (op0);
4549           delta1 = delta_from_ptrmemfunc (op1);
4550           if (TARGET_PTRMEMFUNC_VBIT_LOCATION
4551               == ptrmemfunc_vbit_in_delta)
4552             {
4553               /* We generate:
4554
4555                  (op0.pfn == op1.pfn
4556                   && ((op0.delta == op1.delta)
4557                        || (!op0.pfn && op0.delta & 1 == 0 
4558                            && op1.delta & 1 == 0))
4559
4560                  The reason for the `!op0.pfn' bit is that a NULL
4561                  pointer-to-member is any member with a zero PFN and
4562                  LSB of the DELTA field is 0.  */
4563
4564               e1 = cp_build_binary_op (location, BIT_AND_EXPR,
4565                                        delta0, 
4566                                        integer_one_node,
4567                                        complain);
4568               e1 = cp_build_binary_op (location,
4569                                        EQ_EXPR, e1, integer_zero_node,
4570                                        complain);
4571               e2 = cp_build_binary_op (location, BIT_AND_EXPR,
4572                                        delta1,
4573                                        integer_one_node,
4574                                        complain);
4575               e2 = cp_build_binary_op (location,
4576                                        EQ_EXPR, e2, integer_zero_node,
4577                                        complain);
4578               e1 = cp_build_binary_op (location,
4579                                        TRUTH_ANDIF_EXPR, e2, e1,
4580                                        complain);
4581               e2 = cp_build_binary_op (location, EQ_EXPR,
4582                                        pfn0,
4583                                        build_zero_cst (TREE_TYPE (pfn0)),
4584                                        complain);
4585               e2 = cp_build_binary_op (location,
4586                                        TRUTH_ANDIF_EXPR, e2, e1, complain);
4587               e1 = cp_build_binary_op (location,
4588                                        EQ_EXPR, delta0, delta1, complain);
4589               e1 = cp_build_binary_op (location,
4590                                        TRUTH_ORIF_EXPR, e1, e2, complain);
4591             }
4592           else
4593             {
4594               /* We generate:
4595
4596                  (op0.pfn == op1.pfn
4597                  && (!op0.pfn || op0.delta == op1.delta))
4598
4599                  The reason for the `!op0.pfn' bit is that a NULL
4600                  pointer-to-member is any member with a zero PFN; the
4601                  DELTA field is unspecified.  */
4602  
4603               e1 = cp_build_binary_op (location,
4604                                        EQ_EXPR, delta0, delta1, complain);
4605               e2 = cp_build_binary_op (location,
4606                                        EQ_EXPR,
4607                                        pfn0,
4608                                        build_zero_cst (TREE_TYPE (pfn0)),
4609                                        complain);
4610               e1 = cp_build_binary_op (location,
4611                                        TRUTH_ORIF_EXPR, e1, e2, complain);
4612             }
4613           e2 = build2 (EQ_EXPR, boolean_type_node, pfn0, pfn1);
4614           e = cp_build_binary_op (location,
4615                                   TRUTH_ANDIF_EXPR, e2, e1, complain);
4616           if (code == EQ_EXPR)
4617             return e;
4618           return cp_build_binary_op (location,
4619                                      EQ_EXPR, e, integer_zero_node, complain);
4620         }
4621       else
4622         {
4623           gcc_assert (!TYPE_PTRMEMFUNC_P (type0)
4624                       || !same_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type0),
4625                                        type1));
4626           gcc_assert (!TYPE_PTRMEMFUNC_P (type1)
4627                       || !same_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type1),
4628                                        type0));
4629         }
4630
4631       break;
4632
4633     case MAX_EXPR:
4634     case MIN_EXPR:
4635       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE)
4636            && (code1 == INTEGER_TYPE || code1 == REAL_TYPE))
4637         shorten = 1;
4638       else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
4639         result_type = composite_pointer_type (type0, type1, op0, op1,
4640                                               CPO_COMPARISON, complain);
4641       break;
4642
4643     case LE_EXPR:
4644     case GE_EXPR:
4645     case LT_EXPR:
4646     case GT_EXPR:
4647       if (TREE_CODE (orig_op0) == STRING_CST
4648           || TREE_CODE (orig_op1) == STRING_CST)
4649         {
4650           if (complain & tf_warning)
4651             warning (OPT_Waddress, "comparison with string literal results in unspecified behaviour");
4652         }
4653
4654       if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE)
4655         {
4656         vector_compare:
4657           tree intt;
4658           if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type0),
4659                                                           TREE_TYPE (type1))
4660               && !vector_types_compatible_elements_p (type0, type1))
4661             {
4662               if (complain & tf_error)
4663                 {
4664                   error_at (location, "comparing vectors with different "
4665                                       "element types");
4666                   inform (location, "operand types are %qT and %qT",
4667                           type0, type1);
4668                 }
4669               return error_mark_node;
4670             }
4671
4672           if (TYPE_VECTOR_SUBPARTS (type0) != TYPE_VECTOR_SUBPARTS (type1))
4673             {
4674               if (complain & tf_error)
4675                 {
4676                   error_at (location, "comparing vectors with different "
4677                                       "number of elements");
4678                   inform (location, "operand types are %qT and %qT",
4679                           type0, type1);
4680                 }
4681               return error_mark_node;
4682             }
4683
4684           /* Always construct signed integer vector type.  */
4685           intt = c_common_type_for_size (GET_MODE_BITSIZE
4686                                            (TYPE_MODE (TREE_TYPE (type0))), 0);
4687           if (!intt)
4688             {
4689               if (complain & tf_error)
4690                 error_at (location, "could not find an integer type "
4691                           "of the same size as %qT", TREE_TYPE (type0));
4692               return error_mark_node;
4693             }
4694           result_type = build_opaque_vector_type (intt,
4695                                                   TYPE_VECTOR_SUBPARTS (type0));
4696           converted = 1;
4697           break;
4698         }
4699       build_type = boolean_type_node;
4700       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
4701            || code0 == ENUMERAL_TYPE)
4702            && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
4703                || code1 == ENUMERAL_TYPE))
4704         short_compare = 1;
4705       else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
4706         result_type = composite_pointer_type (type0, type1, op0, op1,
4707                                               CPO_COMPARISON, complain);
4708       else if (code0 == POINTER_TYPE && null_ptr_cst_p (op1))
4709         {
4710           result_type = type0;
4711           if (extra_warnings && (complain & tf_warning))
4712             warning (OPT_Wextra,
4713                      "ordered comparison of pointer with integer zero");
4714         }
4715       else if (code1 == POINTER_TYPE && null_ptr_cst_p (op0))
4716         {
4717           result_type = type1;
4718           if (extra_warnings && (complain & tf_warning))
4719             warning (OPT_Wextra,
4720                      "ordered comparison of pointer with integer zero");
4721         }
4722       else if (null_ptr_cst_p (op0) && null_ptr_cst_p (op1))
4723         /* One of the operands must be of nullptr_t type.  */
4724         result_type = TREE_TYPE (nullptr_node);
4725       else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
4726         {
4727           result_type = type0;
4728           if (complain & tf_error)
4729             permerror (input_location, "ISO C++ forbids comparison between pointer and integer");
4730           else
4731             return error_mark_node;
4732         }
4733       else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
4734         {
4735           result_type = type1;
4736           if (complain & tf_error)
4737             permerror (input_location, "ISO C++ forbids comparison between pointer and integer");
4738           else
4739             return error_mark_node;
4740         }
4741       break;
4742
4743     case UNORDERED_EXPR:
4744     case ORDERED_EXPR:
4745     case UNLT_EXPR:
4746     case UNLE_EXPR:
4747     case UNGT_EXPR:
4748     case UNGE_EXPR:
4749     case UNEQ_EXPR:
4750       build_type = integer_type_node;
4751       if (code0 != REAL_TYPE || code1 != REAL_TYPE)
4752         {
4753           if (complain & tf_error)
4754             error ("unordered comparison on non-floating point argument");
4755           return error_mark_node;
4756         }
4757       common = 1;
4758       break;
4759
4760     default:
4761       break;
4762     }
4763
4764   if (((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE
4765         || code0 == ENUMERAL_TYPE)
4766        && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
4767            || code1 == COMPLEX_TYPE || code1 == ENUMERAL_TYPE)))
4768     arithmetic_types_p = 1;
4769   else
4770     {
4771       arithmetic_types_p = 0;
4772       /* Vector arithmetic is only allowed when both sides are vectors.  */
4773       if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE)
4774         {
4775           if (!tree_int_cst_equal (TYPE_SIZE (type0), TYPE_SIZE (type1))
4776               || !vector_types_compatible_elements_p (type0, type1))
4777             {
4778               if (complain & tf_error)
4779                 binary_op_error (location, code, type0, type1);
4780               return error_mark_node;
4781             }
4782           arithmetic_types_p = 1;
4783         }
4784     }
4785   /* Determine the RESULT_TYPE, if it is not already known.  */
4786   if (!result_type
4787       && arithmetic_types_p
4788       && (shorten || common || short_compare))
4789     {
4790       result_type = cp_common_type (type0, type1);
4791       if (complain & tf_warning)
4792         do_warn_double_promotion (result_type, type0, type1,
4793                                   "implicit conversion from %qT to %qT "
4794                                   "to match other operand of binary "
4795                                   "expression",
4796                                   location);
4797     }
4798
4799   if (!result_type)
4800     {
4801       if (complain & tf_error)
4802         error ("invalid operands of types %qT and %qT to binary %qO",
4803                TREE_TYPE (orig_op0), TREE_TYPE (orig_op1), code);
4804       return error_mark_node;
4805     }
4806
4807   /* If we're in a template, the only thing we need to know is the
4808      RESULT_TYPE.  */
4809   if (processing_template_decl)
4810     {
4811       /* Since the middle-end checks the type when doing a build2, we
4812          need to build the tree in pieces.  This built tree will never
4813          get out of the front-end as we replace it when instantiating
4814          the template.  */
4815       tree tmp = build2 (resultcode,
4816                          build_type ? build_type : result_type,
4817                          NULL_TREE, op1);
4818       TREE_OPERAND (tmp, 0) = op0;
4819       return tmp;
4820     }
4821
4822   if (arithmetic_types_p)
4823     {
4824       bool first_complex = (code0 == COMPLEX_TYPE);
4825       bool second_complex = (code1 == COMPLEX_TYPE);
4826       int none_complex = (!first_complex && !second_complex);
4827
4828       /* Adapted from patch for c/24581.  */
4829       if (first_complex != second_complex
4830           && (code == PLUS_EXPR
4831               || code == MINUS_EXPR
4832               || code == MULT_EXPR
4833               || (code == TRUNC_DIV_EXPR && first_complex))
4834           && TREE_CODE (TREE_TYPE (result_type)) == REAL_TYPE
4835           && flag_signed_zeros)
4836         {
4837           /* An operation on mixed real/complex operands must be
4838              handled specially, but the language-independent code can
4839              more easily optimize the plain complex arithmetic if
4840              -fno-signed-zeros.  */
4841           tree real_type = TREE_TYPE (result_type);
4842           tree real, imag;
4843           if (first_complex)
4844             {
4845               if (TREE_TYPE (op0) != result_type)
4846                 op0 = cp_convert_and_check (result_type, op0, complain);
4847               if (TREE_TYPE (op1) != real_type)
4848                 op1 = cp_convert_and_check (real_type, op1, complain);
4849             }
4850           else
4851             {
4852               if (TREE_TYPE (op0) != real_type)
4853                 op0 = cp_convert_and_check (real_type, op0, complain);
4854               if (TREE_TYPE (op1) != result_type)
4855                 op1 = cp_convert_and_check (result_type, op1, complain);
4856             }
4857           if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK)
4858             return error_mark_node;
4859           if (first_complex)
4860             {
4861               op0 = save_expr (op0);
4862               real = cp_build_unary_op (REALPART_EXPR, op0, 1, complain);
4863               imag = cp_build_unary_op (IMAGPART_EXPR, op0, 1, complain);
4864               switch (code)
4865                 {
4866                 case MULT_EXPR:
4867                 case TRUNC_DIV_EXPR:
4868                   op1 = save_expr (op1);
4869                   imag = build2 (resultcode, real_type, imag, op1);
4870                   /* Fall through.  */
4871                 case PLUS_EXPR:
4872                 case MINUS_EXPR:
4873                   real = build2 (resultcode, real_type, real, op1);
4874                   break;
4875                 default:
4876                   gcc_unreachable();
4877                 }
4878             }
4879           else
4880             {
4881               op1 = save_expr (op1);
4882               real = cp_build_unary_op (REALPART_EXPR, op1, 1, complain);
4883               imag = cp_build_unary_op (IMAGPART_EXPR, op1, 1, complain);
4884               switch (code)
4885                 {
4886                 case MULT_EXPR:
4887                   op0 = save_expr (op0);
4888                   imag = build2 (resultcode, real_type, op0, imag);
4889                   /* Fall through.  */
4890                 case PLUS_EXPR:
4891                   real = build2 (resultcode, real_type, op0, real);
4892                   break;
4893                 case MINUS_EXPR:
4894                   real = build2 (resultcode, real_type, op0, real);
4895                   imag = build1 (NEGATE_EXPR, real_type, imag);
4896                   break;
4897                 default:
4898                   gcc_unreachable();
4899                 }
4900             }
4901           real = fold_if_not_in_template (real);
4902           imag = fold_if_not_in_template (imag);
4903           result = build2 (COMPLEX_EXPR, result_type, real, imag);
4904           result = fold_if_not_in_template (result);
4905           return result;
4906         }
4907
4908       /* For certain operations (which identify themselves by shorten != 0)
4909          if both args were extended from the same smaller type,
4910          do the arithmetic in that type and then extend.
4911
4912          shorten !=0 and !=1 indicates a bitwise operation.
4913          For them, this optimization is safe only if
4914          both args are zero-extended or both are sign-extended.
4915          Otherwise, we might change the result.
4916          E.g., (short)-1 | (unsigned short)-1 is (int)-1
4917          but calculated in (unsigned short) it would be (unsigned short)-1.  */
4918
4919       if (shorten && none_complex)
4920         {
4921           orig_type = result_type;
4922           final_type = result_type;
4923           result_type = shorten_binary_op (result_type, op0, op1,
4924                                            shorten == -1);
4925         }
4926
4927       /* Comparison operations are shortened too but differently.
4928          They identify themselves by setting short_compare = 1.  */
4929
4930       if (short_compare)
4931         {
4932           /* Don't write &op0, etc., because that would prevent op0
4933              from being kept in a register.
4934              Instead, make copies of the our local variables and
4935              pass the copies by reference, then copy them back afterward.  */
4936           tree xop0 = op0, xop1 = op1, xresult_type = result_type;
4937           enum tree_code xresultcode = resultcode;
4938           tree val
4939             = shorten_compare (location, &xop0, &xop1, &xresult_type,
4940                                &xresultcode);
4941           if (val != 0)
4942             return cp_convert (boolean_type_node, val, complain);
4943           op0 = xop0, op1 = xop1;
4944           converted = 1;
4945           resultcode = xresultcode;
4946         }
4947
4948       if ((short_compare || code == MIN_EXPR || code == MAX_EXPR)
4949           && warn_sign_compare
4950           /* Do not warn until the template is instantiated; we cannot
4951              bound the ranges of the arguments until that point.  */
4952           && !processing_template_decl
4953           && (complain & tf_warning)
4954           && c_inhibit_evaluation_warnings == 0
4955           /* Even unsigned enum types promote to signed int.  We don't
4956              want to issue -Wsign-compare warnings for this case.  */
4957           && !enum_cast_to_int (orig_op0)
4958           && !enum_cast_to_int (orig_op1))
4959         {
4960           tree oop0 = maybe_constant_value (orig_op0);
4961           tree oop1 = maybe_constant_value (orig_op1);
4962
4963           if (TREE_CODE (oop0) != INTEGER_CST)
4964             oop0 = orig_op0;
4965           if (TREE_CODE (oop1) != INTEGER_CST)
4966             oop1 = orig_op1;
4967           warn_for_sign_compare (location, oop0, oop1, op0, op1, 
4968                                  result_type, resultcode);
4969         }
4970     }
4971
4972   /* If CONVERTED is zero, both args will be converted to type RESULT_TYPE.
4973      Then the expression will be built.
4974      It will be given type FINAL_TYPE if that is nonzero;
4975      otherwise, it will be given type RESULT_TYPE.  */
4976   if (! converted)
4977     {
4978       if (TREE_TYPE (op0) != result_type)
4979         op0 = cp_convert_and_check (result_type, op0, complain);
4980       if (TREE_TYPE (op1) != result_type)
4981         op1 = cp_convert_and_check (result_type, op1, complain);
4982
4983       if (op0 == error_mark_node || op1 == error_mark_node)
4984         return error_mark_node;
4985     }
4986
4987   if (build_type == NULL_TREE)
4988     build_type = result_type;
4989
4990   if ((flag_sanitize & (SANITIZE_SHIFT | SANITIZE_DIVIDE
4991                         | SANITIZE_FLOAT_DIVIDE))
4992       && !processing_template_decl
4993       && do_ubsan_in_current_function ()
4994       && (doing_div_or_mod || doing_shift))
4995     {
4996       /* OP0 and/or OP1 might have side-effects.  */
4997       op0 = cp_save_expr (op0);
4998       op1 = cp_save_expr (op1);
4999       op0 = fold_non_dependent_expr (op0);
5000       op1 = fold_non_dependent_expr (op1);
5001       if (doing_div_or_mod && (flag_sanitize & (SANITIZE_DIVIDE
5002                                                 | SANITIZE_FLOAT_DIVIDE)))
5003         {
5004           /* For diagnostics we want to use the promoted types without
5005              shorten_binary_op.  So convert the arguments to the
5006              original result_type.  */
5007           tree cop0 = op0;
5008           tree cop1 = op1;
5009           if (orig_type != NULL && result_type != orig_type)
5010             {
5011               cop0 = cp_convert (orig_type, op0, complain);
5012               cop1 = cp_convert (orig_type, op1, complain);
5013             }
5014           instrument_expr = ubsan_instrument_division (location, cop0, cop1);
5015         }
5016       else if (doing_shift && (flag_sanitize & SANITIZE_SHIFT))
5017         instrument_expr = ubsan_instrument_shift (location, code, op0, op1);
5018     }
5019
5020   result = build2 (resultcode, build_type, op0, op1);
5021   result = fold_if_not_in_template (result);
5022   if (final_type != 0)
5023     result = cp_convert (final_type, result, complain);
5024
5025   if (TREE_OVERFLOW_P (result) 
5026       && !TREE_OVERFLOW_P (op0) 
5027       && !TREE_OVERFLOW_P (op1))
5028     overflow_warning (location, result);
5029
5030   if (instrument_expr != NULL)
5031     result = fold_build2 (COMPOUND_EXPR, TREE_TYPE (result),
5032                           instrument_expr, result);
5033
5034   return result;
5035 }
5036
5037 /* Build a VEC_PERM_EXPR.
5038    This is a simple wrapper for c_build_vec_perm_expr.  */
5039 tree
5040 build_x_vec_perm_expr (location_t loc,
5041                         tree arg0, tree arg1, tree arg2,
5042                         tsubst_flags_t complain)
5043 {
5044   tree orig_arg0 = arg0;
5045   tree orig_arg1 = arg1;
5046   tree orig_arg2 = arg2;
5047   if (processing_template_decl)
5048     {
5049       if (type_dependent_expression_p (arg0)
5050           || type_dependent_expression_p (arg1)
5051           || type_dependent_expression_p (arg2))
5052         return build_min_nt_loc (loc, VEC_PERM_EXPR, arg0, arg1, arg2);
5053       arg0 = build_non_dependent_expr (arg0);
5054       if (arg1)
5055         arg1 = build_non_dependent_expr (arg1);
5056       arg2 = build_non_dependent_expr (arg2);
5057     }
5058   tree exp = c_build_vec_perm_expr (loc, arg0, arg1, arg2, complain & tf_error);
5059   if (processing_template_decl && exp != error_mark_node)
5060     return build_min_non_dep (VEC_PERM_EXPR, exp, orig_arg0,
5061                               orig_arg1, orig_arg2);
5062   return exp;
5063 }
5064 \f
5065 /* Return a tree for the sum or difference (RESULTCODE says which)
5066    of pointer PTROP and integer INTOP.  */
5067
5068 static tree
5069 cp_pointer_int_sum (enum tree_code resultcode, tree ptrop, tree intop,
5070                     tsubst_flags_t complain)
5071 {
5072   tree res_type = TREE_TYPE (ptrop);
5073
5074   /* pointer_int_sum() uses size_in_bytes() on the TREE_TYPE(res_type)
5075      in certain circumstance (when it's valid to do so).  So we need
5076      to make sure it's complete.  We don't need to check here, if we
5077      can actually complete it at all, as those checks will be done in
5078      pointer_int_sum() anyway.  */
5079   complete_type (TREE_TYPE (res_type));
5080
5081   return pointer_int_sum (input_location, resultcode, ptrop,
5082                           fold_if_not_in_template (intop),
5083                           complain & tf_warning_or_error);
5084 }
5085
5086 /* Return a tree for the difference of pointers OP0 and OP1.
5087    The resulting tree has type int.  */
5088
5089 static tree
5090 pointer_diff (tree op0, tree op1, tree ptrtype, tsubst_flags_t complain)
5091 {
5092   tree result;
5093   tree restype = ptrdiff_type_node;
5094   tree target_type = TREE_TYPE (ptrtype);
5095
5096   if (!complete_type_or_else (target_type, NULL_TREE))
5097     return error_mark_node;
5098
5099   if (VOID_TYPE_P (target_type))
5100     {
5101       if (complain & tf_error)
5102         permerror (input_location, "ISO C++ forbids using pointer of "
5103                    "type %<void *%> in subtraction");
5104       else
5105         return error_mark_node;
5106     }
5107   if (TREE_CODE (target_type) == FUNCTION_TYPE)
5108     {
5109       if (complain & tf_error)
5110         permerror (input_location, "ISO C++ forbids using pointer to "
5111                    "a function in subtraction");
5112       else
5113         return error_mark_node;
5114     }
5115   if (TREE_CODE (target_type) == METHOD_TYPE)
5116     {
5117       if (complain & tf_error)
5118         permerror (input_location, "ISO C++ forbids using pointer to "
5119                    "a method in subtraction");
5120       else
5121         return error_mark_node;
5122     }
5123
5124   /* First do the subtraction as integers;
5125      then drop through to build the divide operator.  */
5126
5127   op0 = cp_build_binary_op (input_location,
5128                             MINUS_EXPR,
5129                             cp_convert (restype, op0, complain),
5130                             cp_convert (restype, op1, complain),
5131                             complain);
5132
5133   /* This generates an error if op1 is a pointer to an incomplete type.  */
5134   if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (op1))))
5135     {
5136       if (complain & tf_error)
5137         error ("invalid use of a pointer to an incomplete type in "
5138                "pointer arithmetic");
5139       else
5140         return error_mark_node;
5141     }
5142
5143   if (pointer_to_zero_sized_aggr_p (TREE_TYPE (op1)))
5144     {
5145       if (complain & tf_error)
5146         error ("arithmetic on pointer to an empty aggregate");
5147       else
5148         return error_mark_node;
5149     }
5150
5151   op1 = (TYPE_PTROB_P (ptrtype)
5152          ? size_in_bytes (target_type)
5153          : integer_one_node);
5154
5155   /* Do the division.  */
5156
5157   result = build2 (EXACT_DIV_EXPR, restype, op0,
5158                    cp_convert (restype, op1, complain));
5159   return fold_if_not_in_template (result);
5160 }
5161 \f
5162 /* Construct and perhaps optimize a tree representation
5163    for a unary operation.  CODE, a tree_code, specifies the operation
5164    and XARG is the operand.  */
5165
5166 tree
5167 build_x_unary_op (location_t loc, enum tree_code code, tree xarg,
5168                   tsubst_flags_t complain)
5169 {
5170   tree orig_expr = xarg;
5171   tree exp;
5172   int ptrmem = 0;
5173
5174   if (processing_template_decl)
5175     {
5176       if (type_dependent_expression_p (xarg))
5177         return build_min_nt_loc (loc, code, xarg, NULL_TREE);
5178
5179       xarg = build_non_dependent_expr (xarg);
5180     }
5181
5182   exp = NULL_TREE;
5183
5184   /* [expr.unary.op] says:
5185
5186        The address of an object of incomplete type can be taken.
5187
5188      (And is just the ordinary address operator, not an overloaded
5189      "operator &".)  However, if the type is a template
5190      specialization, we must complete the type at this point so that
5191      an overloaded "operator &" will be available if required.  */
5192   if (code == ADDR_EXPR
5193       && TREE_CODE (xarg) != TEMPLATE_ID_EXPR
5194       && ((CLASS_TYPE_P (TREE_TYPE (xarg))
5195            && !COMPLETE_TYPE_P (complete_type (TREE_TYPE (xarg))))
5196           || (TREE_CODE (xarg) == OFFSET_REF)))
5197     /* Don't look for a function.  */;
5198   else
5199     exp = build_new_op (loc, code, LOOKUP_NORMAL, xarg, NULL_TREE,
5200                         NULL_TREE, /*overload=*/NULL, complain);
5201   if (!exp && code == ADDR_EXPR)
5202     {
5203       if (is_overloaded_fn (xarg))
5204         {
5205           tree fn = get_first_fn (xarg);
5206           if (DECL_CONSTRUCTOR_P (fn) || DECL_DESTRUCTOR_P (fn))
5207             {
5208               if (complain & tf_error)
5209                 error (DECL_CONSTRUCTOR_P (fn)
5210                        ? G_("taking address of constructor %qE")
5211                        : G_("taking address of destructor %qE"),
5212                        xarg);
5213               return error_mark_node;
5214             }
5215         }
5216
5217       /* A pointer to member-function can be formed only by saying
5218          &X::mf.  */
5219       if (!flag_ms_extensions && TREE_CODE (TREE_TYPE (xarg)) == METHOD_TYPE
5220           && (TREE_CODE (xarg) != OFFSET_REF || !PTRMEM_OK_P (xarg)))
5221         {
5222           if (TREE_CODE (xarg) != OFFSET_REF
5223               || !TYPE_P (TREE_OPERAND (xarg, 0)))
5224             {
5225               if (complain & tf_error)
5226                 {
5227                   error ("invalid use of %qE to form a "
5228                          "pointer-to-member-function", xarg);
5229                   if (TREE_CODE (xarg) != OFFSET_REF)
5230                     inform (input_location, "  a qualified-id is required");
5231                 }
5232               return error_mark_node;
5233             }
5234           else
5235             {
5236               if (complain & tf_error)
5237                 error ("parentheses around %qE cannot be used to form a"
5238                        " pointer-to-member-function",
5239                        xarg);
5240               else
5241                 return error_mark_node;
5242               PTRMEM_OK_P (xarg) = 1;
5243             }
5244         }
5245
5246       if (TREE_CODE (xarg) == OFFSET_REF)
5247         {
5248           ptrmem = PTRMEM_OK_P (xarg);
5249
5250           if (!ptrmem && !flag_ms_extensions
5251               && TREE_CODE (TREE_TYPE (TREE_OPERAND (xarg, 1))) == METHOD_TYPE)
5252             {
5253               /* A single non-static member, make sure we don't allow a
5254                  pointer-to-member.  */
5255               xarg = build2 (OFFSET_REF, TREE_TYPE (xarg),
5256                              TREE_OPERAND (xarg, 0),
5257                              ovl_cons (TREE_OPERAND (xarg, 1), NULL_TREE));
5258               PTRMEM_OK_P (xarg) = ptrmem;
5259             }
5260         }
5261
5262       exp = cp_build_addr_expr_strict (xarg, complain);
5263     }
5264
5265   if (processing_template_decl && exp != error_mark_node)
5266     exp = build_min_non_dep (code, exp, orig_expr,
5267                              /*For {PRE,POST}{INC,DEC}REMENT_EXPR*/NULL_TREE);
5268   if (TREE_CODE (exp) == ADDR_EXPR)
5269     PTRMEM_OK_P (exp) = ptrmem;
5270   return exp;
5271 }
5272
5273 /* Like c_common_truthvalue_conversion, but handle pointer-to-member
5274    constants, where a null value is represented by an INTEGER_CST of
5275    -1.  */
5276
5277 tree
5278 cp_truthvalue_conversion (tree expr)
5279 {
5280   tree type = TREE_TYPE (expr);
5281   if (TYPE_PTRDATAMEM_P (type)
5282       /* Avoid ICE on invalid use of non-static member function.  */
5283       || TREE_CODE (expr) == FUNCTION_DECL)
5284     return build_binary_op (EXPR_LOCATION (expr),
5285                             NE_EXPR, expr, nullptr_node, 1);
5286   else if (TYPE_PTR_P (type) || TYPE_PTRMEMFUNC_P (type))
5287     {
5288       /* With -Wzero-as-null-pointer-constant do not warn for an
5289          'if (p)' or a 'while (!p)', where p is a pointer.  */
5290       tree ret;
5291       ++c_inhibit_evaluation_warnings;
5292       ret = c_common_truthvalue_conversion (input_location, expr);
5293       --c_inhibit_evaluation_warnings;
5294       return ret;
5295     }
5296   else
5297     return c_common_truthvalue_conversion (input_location, expr);
5298 }
5299
5300 /* Just like cp_truthvalue_conversion, but we want a CLEANUP_POINT_EXPR.  */
5301
5302 tree
5303 condition_conversion (tree expr)
5304 {
5305   tree t;
5306   if (processing_template_decl)
5307     return expr;
5308   t = perform_implicit_conversion_flags (boolean_type_node, expr,
5309                                          tf_warning_or_error, LOOKUP_NORMAL);
5310   t = fold_build_cleanup_point_expr (boolean_type_node, t);
5311   return t;
5312 }
5313
5314 /* Returns the address of T.  This function will fold away
5315    ADDR_EXPR of INDIRECT_REF.  */
5316
5317 tree
5318 build_address (tree t)
5319 {
5320   if (error_operand_p (t) || !cxx_mark_addressable (t))
5321     return error_mark_node;
5322   gcc_checking_assert (TREE_CODE (t) != CONSTRUCTOR);
5323   t = build_fold_addr_expr (t);
5324   if (TREE_CODE (t) != ADDR_EXPR)
5325     t = rvalue (t);
5326   return t;
5327 }
5328
5329 /* Return a NOP_EXPR converting EXPR to TYPE.  */
5330
5331 tree
5332 build_nop (tree type, tree expr)
5333 {
5334   if (type == error_mark_node || error_operand_p (expr))
5335     return expr;
5336   return build1 (NOP_EXPR, type, expr);
5337 }
5338
5339 /* Take the address of ARG, whatever that means under C++ semantics.
5340    If STRICT_LVALUE is true, require an lvalue; otherwise, allow xvalues
5341    and class rvalues as well.
5342
5343    Nothing should call this function directly; instead, callers should use
5344    cp_build_addr_expr or cp_build_addr_expr_strict.  */
5345
5346 static tree
5347 cp_build_addr_expr_1 (tree arg, bool strict_lvalue, tsubst_flags_t complain)
5348 {
5349   tree argtype;
5350   tree val;
5351
5352   if (!arg || error_operand_p (arg))
5353     return error_mark_node;
5354
5355   arg = mark_lvalue_use (arg);
5356   argtype = lvalue_type (arg);
5357
5358   gcc_assert (!identifier_p (arg) || !IDENTIFIER_OPNAME_P (arg));
5359
5360   if (TREE_CODE (arg) == COMPONENT_REF && type_unknown_p (arg)
5361       && !really_overloaded_fn (TREE_OPERAND (arg, 1)))
5362     {
5363       /* They're trying to take the address of a unique non-static
5364          member function.  This is ill-formed (except in MS-land),
5365          but let's try to DTRT.
5366          Note: We only handle unique functions here because we don't
5367          want to complain if there's a static overload; non-unique
5368          cases will be handled by instantiate_type.  But we need to
5369          handle this case here to allow casts on the resulting PMF.
5370          We could defer this in non-MS mode, but it's easier to give
5371          a useful error here.  */
5372
5373       /* Inside constant member functions, the `this' pointer
5374          contains an extra const qualifier.  TYPE_MAIN_VARIANT
5375          is used here to remove this const from the diagnostics
5376          and the created OFFSET_REF.  */
5377       tree base = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (arg, 0)));
5378       tree fn = get_first_fn (TREE_OPERAND (arg, 1));
5379       mark_used (fn);
5380
5381       if (! flag_ms_extensions)
5382         {
5383           tree name = DECL_NAME (fn);
5384           if (!(complain & tf_error))
5385             return error_mark_node;
5386           else if (current_class_type
5387                    && TREE_OPERAND (arg, 0) == current_class_ref)
5388             /* An expression like &memfn.  */
5389             permerror (input_location, "ISO C++ forbids taking the address of an unqualified"
5390                        " or parenthesized non-static member function to form"
5391                        " a pointer to member function.  Say %<&%T::%D%>",
5392                        base, name);
5393           else
5394             permerror (input_location, "ISO C++ forbids taking the address of a bound member"
5395                        " function to form a pointer to member function."
5396                        "  Say %<&%T::%D%>",
5397                        base, name);
5398         }
5399       arg = build_offset_ref (base, fn, /*address_p=*/true, complain);
5400     }
5401
5402   /* Uninstantiated types are all functions.  Taking the
5403      address of a function is a no-op, so just return the
5404      argument.  */
5405   if (type_unknown_p (arg))
5406     return build1 (ADDR_EXPR, unknown_type_node, arg);
5407
5408   if (TREE_CODE (arg) == OFFSET_REF)
5409     /* We want a pointer to member; bypass all the code for actually taking
5410        the address of something.  */
5411     goto offset_ref;
5412
5413   /* Anything not already handled and not a true memory reference
5414      is an error.  */
5415   if (TREE_CODE (argtype) != FUNCTION_TYPE
5416       && TREE_CODE (argtype) != METHOD_TYPE)
5417     {
5418       cp_lvalue_kind kind = lvalue_kind (arg);
5419       if (kind == clk_none)
5420         {
5421           if (complain & tf_error)
5422             lvalue_error (input_location, lv_addressof);
5423           return error_mark_node;
5424         }
5425       if (strict_lvalue && (kind & (clk_rvalueref|clk_class)))
5426         {
5427           if (!(complain & tf_error))
5428             return error_mark_node;
5429           if (kind & clk_class)
5430             /* Make this a permerror because we used to accept it.  */
5431             permerror (input_location, "taking address of temporary");
5432           else
5433             error ("taking address of xvalue (rvalue reference)");
5434         }
5435     }
5436
5437   if (TREE_CODE (argtype) == REFERENCE_TYPE)
5438     {
5439       tree type = build_pointer_type (TREE_TYPE (argtype));
5440       arg = build1 (CONVERT_EXPR, type, arg);
5441       return arg;
5442     }
5443   else if (pedantic && DECL_MAIN_P (arg))
5444     {
5445       /* ARM $3.4 */
5446       /* Apparently a lot of autoconf scripts for C++ packages do this,
5447          so only complain if -Wpedantic.  */
5448       if (complain & (flag_pedantic_errors ? tf_error : tf_warning))
5449         pedwarn (input_location, OPT_Wpedantic,
5450                  "ISO C++ forbids taking address of function %<::main%>");
5451       else if (flag_pedantic_errors)
5452         return error_mark_node;
5453     }
5454
5455   /* Let &* cancel out to simplify resulting code.  */
5456   if (INDIRECT_REF_P (arg))
5457     {
5458       /* We don't need to have `current_class_ptr' wrapped in a
5459          NON_LVALUE_EXPR node.  */
5460       if (arg == current_class_ref)
5461         return current_class_ptr;
5462
5463       arg = TREE_OPERAND (arg, 0);
5464       if (TREE_CODE (TREE_TYPE (arg)) == REFERENCE_TYPE)
5465         {
5466           tree type = build_pointer_type (TREE_TYPE (TREE_TYPE (arg)));
5467           arg = build1 (CONVERT_EXPR, type, arg);
5468         }
5469       else
5470         /* Don't let this be an lvalue.  */
5471         arg = rvalue (arg);
5472       return arg;
5473     }
5474
5475   /* ??? Cope with user tricks that amount to offsetof.  */
5476   if (TREE_CODE (argtype) != FUNCTION_TYPE
5477       && TREE_CODE (argtype) != METHOD_TYPE
5478       && argtype != unknown_type_node
5479       && (val = get_base_address (arg))
5480       && COMPLETE_TYPE_P (TREE_TYPE (val))
5481       && INDIRECT_REF_P (val)
5482       && TREE_CONSTANT (TREE_OPERAND (val, 0)))
5483     {
5484       tree type = build_pointer_type (argtype);
5485       return fold_convert (type, fold_offsetof_1 (arg));
5486     }
5487
5488   /* Handle complex lvalues (when permitted)
5489      by reduction to simpler cases.  */
5490   val = unary_complex_lvalue (ADDR_EXPR, arg);
5491   if (val != 0)
5492     return val;
5493
5494   switch (TREE_CODE (arg))
5495     {
5496     CASE_CONVERT:
5497     case FLOAT_EXPR:
5498     case FIX_TRUNC_EXPR:
5499       /* Even if we're not being pedantic, we cannot allow this
5500          extension when we're instantiating in a SFINAE
5501          context.  */
5502       if (! lvalue_p (arg) && complain == tf_none)
5503         {
5504           if (complain & tf_error)
5505             permerror (input_location, "ISO C++ forbids taking the address of a cast to a non-lvalue expression");
5506           else
5507             return error_mark_node;
5508         }
5509       break;
5510
5511     case BASELINK:
5512       arg = BASELINK_FUNCTIONS (arg);
5513       /* Fall through.  */
5514
5515     case OVERLOAD:
5516       arg = OVL_CURRENT (arg);
5517       break;
5518
5519     case OFFSET_REF:
5520     offset_ref:
5521       /* Turn a reference to a non-static data member into a
5522          pointer-to-member.  */
5523       {
5524         tree type;
5525         tree t;
5526
5527         gcc_assert (PTRMEM_OK_P (arg));
5528
5529         t = TREE_OPERAND (arg, 1);
5530         if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
5531           {
5532             if (complain & tf_error)
5533               error ("cannot create pointer to reference member %qD", t);
5534             return error_mark_node;
5535           }
5536
5537         type = build_ptrmem_type (context_for_name_lookup (t),
5538                                   TREE_TYPE (t));
5539         t = make_ptrmem_cst (type, TREE_OPERAND (arg, 1));
5540         return t;
5541       }
5542
5543     default:
5544       break;
5545     }
5546
5547   if (argtype != error_mark_node)
5548     argtype = build_pointer_type (argtype);
5549
5550   /* In a template, we are processing a non-dependent expression
5551      so we can just form an ADDR_EXPR with the correct type.  */
5552   if (processing_template_decl || TREE_CODE (arg) != COMPONENT_REF)
5553     {
5554       val = build_address (arg);
5555       if (TREE_CODE (arg) == OFFSET_REF)
5556         PTRMEM_OK_P (val) = PTRMEM_OK_P (arg);
5557     }
5558   else if (BASELINK_P (TREE_OPERAND (arg, 1)))
5559     {
5560       tree fn = BASELINK_FUNCTIONS (TREE_OPERAND (arg, 1));
5561
5562       /* We can only get here with a single static member
5563          function.  */
5564       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
5565                   && DECL_STATIC_FUNCTION_P (fn));
5566       mark_used (fn);
5567       val = build_address (fn);
5568       if (TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
5569         /* Do not lose object's side effects.  */
5570         val = build2 (COMPOUND_EXPR, TREE_TYPE (val),
5571                       TREE_OPERAND (arg, 0), val);
5572     }
5573   else if (DECL_C_BIT_FIELD (TREE_OPERAND (arg, 1)))
5574     {
5575       if (complain & tf_error)
5576         error ("attempt to take address of bit-field structure member %qD",
5577                TREE_OPERAND (arg, 1));
5578       return error_mark_node;
5579     }
5580   else
5581     {
5582       tree object = TREE_OPERAND (arg, 0);
5583       tree field = TREE_OPERAND (arg, 1);
5584       gcc_assert (same_type_ignoring_top_level_qualifiers_p
5585                   (TREE_TYPE (object), decl_type_context (field)));
5586       val = build_address (arg);
5587     }
5588
5589   if (TYPE_PTR_P (argtype)
5590       && TREE_CODE (TREE_TYPE (argtype)) == METHOD_TYPE)
5591     {
5592       build_ptrmemfunc_type (argtype);
5593       val = build_ptrmemfunc (argtype, val, 0,
5594                               /*c_cast_p=*/false,
5595                               complain);
5596     }
5597
5598   return val;
5599 }
5600
5601 /* Take the address of ARG if it has one, even if it's an rvalue.  */
5602
5603 tree
5604 cp_build_addr_expr (tree arg, tsubst_flags_t complain)
5605 {
5606   return cp_build_addr_expr_1 (arg, 0, complain);
5607 }
5608
5609 /* Take the address of ARG, but only if it's an lvalue.  */
5610
5611 static tree
5612 cp_build_addr_expr_strict (tree arg, tsubst_flags_t complain)
5613 {
5614   return cp_build_addr_expr_1 (arg, 1, complain);
5615 }
5616
5617 /* C++: Must handle pointers to members.
5618
5619    Perhaps type instantiation should be extended to handle conversion
5620    from aggregates to types we don't yet know we want?  (Or are those
5621    cases typically errors which should be reported?)
5622
5623    NOCONVERT nonzero suppresses the default promotions
5624    (such as from short to int).  */
5625
5626 tree
5627 cp_build_unary_op (enum tree_code code, tree xarg, int noconvert, 
5628                    tsubst_flags_t complain)
5629 {
5630   /* No default_conversion here.  It causes trouble for ADDR_EXPR.  */
5631   tree arg = xarg;
5632   tree argtype = 0;
5633   const char *errstring = NULL;
5634   tree val;
5635   const char *invalid_op_diag;
5636
5637   if (!arg || error_operand_p (arg))
5638     return error_mark_node;
5639
5640   if ((invalid_op_diag
5641        = targetm.invalid_unary_op ((code == UNARY_PLUS_EXPR
5642                                     ? CONVERT_EXPR
5643                                     : code),
5644                                    TREE_TYPE (xarg))))
5645     {
5646       if (complain & tf_error)
5647         error (invalid_op_diag);
5648       return error_mark_node;
5649     }
5650
5651   switch (code)
5652     {
5653     case UNARY_PLUS_EXPR:
5654     case NEGATE_EXPR:
5655       {
5656         int flags = WANT_ARITH | WANT_ENUM;
5657         /* Unary plus (but not unary minus) is allowed on pointers.  */
5658         if (code == UNARY_PLUS_EXPR)
5659           flags |= WANT_POINTER;
5660         arg = build_expr_type_conversion (flags, arg, true);
5661         if (!arg)
5662           errstring = (code == NEGATE_EXPR
5663                        ? _("wrong type argument to unary minus")
5664                        : _("wrong type argument to unary plus"));
5665         else
5666           {
5667             if (!noconvert && CP_INTEGRAL_TYPE_P (TREE_TYPE (arg)))
5668               arg = cp_perform_integral_promotions (arg, complain);
5669
5670             /* Make sure the result is not an lvalue: a unary plus or minus
5671                expression is always a rvalue.  */
5672             arg = rvalue (arg);
5673           }
5674       }
5675       break;
5676
5677     case BIT_NOT_EXPR:
5678       if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
5679         {
5680           code = CONJ_EXPR;
5681           if (!noconvert)
5682             {
5683               arg = cp_default_conversion (arg, complain);
5684               if (arg == error_mark_node)
5685                 return error_mark_node;
5686             }
5687         }
5688       else if (!(arg = build_expr_type_conversion (WANT_INT | WANT_ENUM
5689                                                    | WANT_VECTOR_OR_COMPLEX,
5690                                                    arg, true)))
5691         errstring = _("wrong type argument to bit-complement");
5692       else if (!noconvert && CP_INTEGRAL_TYPE_P (TREE_TYPE (arg)))
5693         arg = cp_perform_integral_promotions (arg, complain);
5694       break;
5695
5696     case ABS_EXPR:
5697       if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_ENUM, arg, true)))
5698         errstring = _("wrong type argument to abs");
5699       else if (!noconvert)
5700         {
5701           arg = cp_default_conversion (arg, complain);
5702           if (arg == error_mark_node)
5703             return error_mark_node;
5704         }
5705       break;
5706
5707     case CONJ_EXPR:
5708       /* Conjugating a real value is a no-op, but allow it anyway.  */
5709       if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_ENUM, arg, true)))
5710         errstring = _("wrong type argument to conjugation");
5711       else if (!noconvert)
5712         {
5713           arg = cp_default_conversion (arg, complain);
5714           if (arg == error_mark_node)
5715             return error_mark_node;
5716         }
5717       break;
5718
5719     case TRUTH_NOT_EXPR:
5720       if (VECTOR_TYPE_P (TREE_TYPE (arg)))
5721         return cp_build_binary_op (input_location, EQ_EXPR, arg,
5722                                    build_zero_cst (TREE_TYPE (arg)), complain);
5723       arg = perform_implicit_conversion (boolean_type_node, arg,
5724                                          complain);
5725       val = invert_truthvalue_loc (input_location, arg);
5726       if (arg != error_mark_node)
5727         return val;
5728       errstring = _("in argument to unary !");
5729       break;
5730
5731     case NOP_EXPR:
5732       break;
5733
5734     case REALPART_EXPR:
5735     case IMAGPART_EXPR:
5736       arg = build_real_imag_expr (input_location, code, arg);
5737       if (arg == error_mark_node)
5738         return arg;
5739       else
5740         return fold_if_not_in_template (arg);
5741
5742     case PREINCREMENT_EXPR:
5743     case POSTINCREMENT_EXPR:
5744     case PREDECREMENT_EXPR:
5745     case POSTDECREMENT_EXPR:
5746       /* Handle complex lvalues (when permitted)
5747          by reduction to simpler cases.  */
5748
5749       val = unary_complex_lvalue (code, arg);
5750       if (val != 0)
5751         return val;
5752
5753       arg = mark_lvalue_use (arg);
5754
5755       /* Increment or decrement the real part of the value,
5756          and don't change the imaginary part.  */
5757       if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
5758         {
5759           tree real, imag;
5760
5761           arg = stabilize_reference (arg);
5762           real = cp_build_unary_op (REALPART_EXPR, arg, 1, complain);
5763           imag = cp_build_unary_op (IMAGPART_EXPR, arg, 1, complain);
5764           real = cp_build_unary_op (code, real, 1, complain);
5765           if (real == error_mark_node || imag == error_mark_node)
5766             return error_mark_node;
5767           return build2 (COMPLEX_EXPR, TREE_TYPE (arg),
5768                          real, imag);
5769         }
5770
5771       /* Report invalid types.  */
5772
5773       if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_POINTER,
5774                                               arg, true)))
5775         {
5776           if (code == PREINCREMENT_EXPR)
5777             errstring = _("no pre-increment operator for type");
5778           else if (code == POSTINCREMENT_EXPR)
5779             errstring = _("no post-increment operator for type");
5780           else if (code == PREDECREMENT_EXPR)
5781             errstring = _("no pre-decrement operator for type");
5782           else
5783             errstring = _("no post-decrement operator for type");
5784           break;
5785         }
5786       else if (arg == error_mark_node)
5787         return error_mark_node;
5788
5789       /* Report something read-only.  */
5790
5791       if (CP_TYPE_CONST_P (TREE_TYPE (arg))
5792           || TREE_READONLY (arg)) 
5793         {
5794           if (complain & tf_error)
5795             cxx_readonly_error (arg, ((code == PREINCREMENT_EXPR
5796                                       || code == POSTINCREMENT_EXPR)
5797                                      ? lv_increment : lv_decrement));
5798           else
5799             return error_mark_node;
5800         }
5801
5802       {
5803         tree inc;
5804         tree declared_type = unlowered_expr_type (arg);
5805
5806         argtype = TREE_TYPE (arg);
5807
5808         /* ARM $5.2.5 last annotation says this should be forbidden.  */
5809         if (TREE_CODE (argtype) == ENUMERAL_TYPE)
5810           {
5811             if (complain & tf_error)
5812               permerror (input_location, (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR)
5813                          ? G_("ISO C++ forbids incrementing an enum")
5814                          : G_("ISO C++ forbids decrementing an enum"));
5815             else
5816               return error_mark_node;
5817           }
5818
5819         /* Compute the increment.  */
5820
5821         if (TYPE_PTR_P (argtype))
5822           {
5823             tree type = complete_type (TREE_TYPE (argtype));
5824
5825             if (!COMPLETE_OR_VOID_TYPE_P (type))
5826               {
5827                 if (complain & tf_error)
5828                   error (((code == PREINCREMENT_EXPR
5829                            || code == POSTINCREMENT_EXPR))
5830                          ? G_("cannot increment a pointer to incomplete type %qT")
5831                          : G_("cannot decrement a pointer to incomplete type %qT"),
5832                          TREE_TYPE (argtype));
5833                 else
5834                   return error_mark_node;
5835               }
5836             else if (!TYPE_PTROB_P (argtype)) 
5837               {
5838                 if (complain & tf_error)
5839                   pedwarn (input_location, OPT_Wpointer_arith,
5840                            (code == PREINCREMENT_EXPR
5841                               || code == POSTINCREMENT_EXPR)
5842                            ? G_("ISO C++ forbids incrementing a pointer of type %qT")
5843                            : G_("ISO C++ forbids decrementing a pointer of type %qT"),
5844                            argtype);
5845                 else
5846                   return error_mark_node;
5847               }
5848
5849             inc = cxx_sizeof_nowarn (TREE_TYPE (argtype));
5850           }
5851         else
5852           inc = VECTOR_TYPE_P (argtype)
5853             ? build_one_cst (argtype)
5854             : integer_one_node;
5855
5856         inc = cp_convert (argtype, inc, complain);
5857
5858         /* If 'arg' is an Objective-C PROPERTY_REF expression, then we
5859            need to ask Objective-C to build the increment or decrement
5860            expression for it.  */
5861         if (objc_is_property_ref (arg))
5862           return objc_build_incr_expr_for_property_ref (input_location, code, 
5863                                                         arg, inc);      
5864
5865         /* Complain about anything else that is not a true lvalue.  */
5866         if (!lvalue_or_else (arg, ((code == PREINCREMENT_EXPR
5867                                     || code == POSTINCREMENT_EXPR)
5868                                    ? lv_increment : lv_decrement),
5869                              complain))
5870           return error_mark_node;
5871
5872         /* Forbid using -- on `bool'.  */
5873         if (TREE_CODE (declared_type) == BOOLEAN_TYPE)
5874           {
5875             if (code == POSTDECREMENT_EXPR || code == PREDECREMENT_EXPR)
5876               {
5877                 if (complain & tf_error)
5878                   error ("invalid use of Boolean expression as operand "
5879                          "to %<operator--%>");
5880                 return error_mark_node;
5881               }
5882             val = boolean_increment (code, arg);
5883           }
5884         else if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
5885           /* An rvalue has no cv-qualifiers.  */
5886           val = build2 (code, cv_unqualified (TREE_TYPE (arg)), arg, inc);
5887         else
5888           val = build2 (code, TREE_TYPE (arg), arg, inc);
5889
5890         TREE_SIDE_EFFECTS (val) = 1;
5891         return val;
5892       }
5893
5894     case ADDR_EXPR:
5895       /* Note that this operation never does default_conversion
5896          regardless of NOCONVERT.  */
5897       return cp_build_addr_expr (arg, complain);
5898
5899     default:
5900       break;
5901     }
5902
5903   if (!errstring)
5904     {
5905       if (argtype == 0)
5906         argtype = TREE_TYPE (arg);
5907       return fold_if_not_in_template (build1 (code, argtype, arg));
5908     }
5909
5910   if (complain & tf_error)
5911     error ("%s", errstring);
5912   return error_mark_node;
5913 }
5914
5915 /* Hook for the c-common bits that build a unary op.  */
5916 tree
5917 build_unary_op (location_t /*location*/,
5918                 enum tree_code code, tree xarg, int noconvert)
5919 {
5920   return cp_build_unary_op (code, xarg, noconvert, tf_warning_or_error);
5921 }
5922
5923 /* Apply unary lvalue-demanding operator CODE to the expression ARG
5924    for certain kinds of expressions which are not really lvalues
5925    but which we can accept as lvalues.
5926
5927    If ARG is not a kind of expression we can handle, return
5928    NULL_TREE.  */
5929
5930 tree
5931 unary_complex_lvalue (enum tree_code code, tree arg)
5932 {
5933   /* Inside a template, making these kinds of adjustments is
5934      pointless; we are only concerned with the type of the
5935      expression.  */
5936   if (processing_template_decl)
5937     return NULL_TREE;
5938
5939   /* Handle (a, b) used as an "lvalue".  */
5940   if (TREE_CODE (arg) == COMPOUND_EXPR)
5941     {
5942       tree real_result = cp_build_unary_op (code, TREE_OPERAND (arg, 1), 0,
5943                                             tf_warning_or_error);
5944       return build2 (COMPOUND_EXPR, TREE_TYPE (real_result),
5945                      TREE_OPERAND (arg, 0), real_result);
5946     }
5947
5948   /* Handle (a ? b : c) used as an "lvalue".  */
5949   if (TREE_CODE (arg) == COND_EXPR
5950       || TREE_CODE (arg) == MIN_EXPR || TREE_CODE (arg) == MAX_EXPR)
5951     return rationalize_conditional_expr (code, arg, tf_warning_or_error);
5952
5953   /* Handle (a = b), (++a), and (--a) used as an "lvalue".  */
5954   if (TREE_CODE (arg) == MODIFY_EXPR
5955       || TREE_CODE (arg) == PREINCREMENT_EXPR
5956       || TREE_CODE (arg) == PREDECREMENT_EXPR)
5957     {
5958       tree lvalue = TREE_OPERAND (arg, 0);
5959       if (TREE_SIDE_EFFECTS (lvalue))
5960         {
5961           lvalue = stabilize_reference (lvalue);
5962           arg = build2 (TREE_CODE (arg), TREE_TYPE (arg),
5963                         lvalue, TREE_OPERAND (arg, 1));
5964         }
5965       return unary_complex_lvalue
5966         (code, build2 (COMPOUND_EXPR, TREE_TYPE (lvalue), arg, lvalue));
5967     }
5968
5969   if (code != ADDR_EXPR)
5970     return NULL_TREE;
5971
5972   /* Handle (a = b) used as an "lvalue" for `&'.  */
5973   if (TREE_CODE (arg) == MODIFY_EXPR
5974       || TREE_CODE (arg) == INIT_EXPR)
5975     {
5976       tree real_result = cp_build_unary_op (code, TREE_OPERAND (arg, 0), 0,
5977                                             tf_warning_or_error);
5978       arg = build2 (COMPOUND_EXPR, TREE_TYPE (real_result),
5979                     arg, real_result);
5980       TREE_NO_WARNING (arg) = 1;
5981       return arg;
5982     }
5983
5984   if (TREE_CODE (TREE_TYPE (arg)) == FUNCTION_TYPE
5985       || TREE_CODE (TREE_TYPE (arg)) == METHOD_TYPE
5986       || TREE_CODE (arg) == OFFSET_REF)
5987     return NULL_TREE;
5988
5989   /* We permit compiler to make function calls returning
5990      objects of aggregate type look like lvalues.  */
5991   {
5992     tree targ = arg;
5993
5994     if (TREE_CODE (targ) == SAVE_EXPR)
5995       targ = TREE_OPERAND (targ, 0);
5996
5997     if (TREE_CODE (targ) == CALL_EXPR && MAYBE_CLASS_TYPE_P (TREE_TYPE (targ)))
5998       {
5999         if (TREE_CODE (arg) == SAVE_EXPR)
6000           targ = arg;
6001         else
6002           targ = build_cplus_new (TREE_TYPE (arg), arg, tf_warning_or_error);
6003         return build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (arg)), targ);
6004       }
6005
6006     if (TREE_CODE (arg) == SAVE_EXPR && INDIRECT_REF_P (targ))
6007       return build3 (SAVE_EXPR, build_pointer_type (TREE_TYPE (arg)),
6008                      TREE_OPERAND (targ, 0), current_function_decl, NULL);
6009   }
6010
6011   /* Don't let anything else be handled specially.  */
6012   return NULL_TREE;
6013 }
6014 \f
6015 /* Mark EXP saying that we need to be able to take the
6016    address of it; it should not be allocated in a register.
6017    Value is true if successful.
6018
6019    C++: we do not allow `current_class_ptr' to be addressable.  */
6020
6021 bool
6022 cxx_mark_addressable (tree exp)
6023 {
6024   tree x = exp;
6025
6026   while (1)
6027     switch (TREE_CODE (x))
6028       {
6029       case ADDR_EXPR:
6030       case COMPONENT_REF:
6031       case ARRAY_REF:
6032       case REALPART_EXPR:
6033       case IMAGPART_EXPR:
6034         x = TREE_OPERAND (x, 0);
6035         break;
6036
6037       case PARM_DECL:
6038         if (x == current_class_ptr)
6039           {
6040             error ("cannot take the address of %<this%>, which is an rvalue expression");
6041             TREE_ADDRESSABLE (x) = 1; /* so compiler doesn't die later.  */
6042             return true;
6043           }
6044         /* Fall through.  */
6045
6046       case VAR_DECL:
6047         /* Caller should not be trying to mark initialized
6048            constant fields addressable.  */
6049         gcc_assert (DECL_LANG_SPECIFIC (x) == 0
6050                     || DECL_IN_AGGR_P (x) == 0
6051                     || TREE_STATIC (x)
6052                     || DECL_EXTERNAL (x));
6053         /* Fall through.  */
6054
6055       case RESULT_DECL:
6056         if (DECL_REGISTER (x) && !TREE_ADDRESSABLE (x)
6057             && !DECL_ARTIFICIAL (x))
6058           {
6059             if (VAR_P (x) && DECL_HARD_REGISTER (x))
6060               {
6061                 error
6062                   ("address of explicit register variable %qD requested", x);
6063                 return false;
6064               }
6065             else if (extra_warnings)
6066               warning
6067                 (OPT_Wextra, "address requested for %qD, which is declared %<register%>", x);
6068           }
6069         TREE_ADDRESSABLE (x) = 1;
6070         return true;
6071
6072       case CONST_DECL:
6073       case FUNCTION_DECL:
6074         TREE_ADDRESSABLE (x) = 1;
6075         return true;
6076
6077       case CONSTRUCTOR:
6078         TREE_ADDRESSABLE (x) = 1;
6079         return true;
6080
6081       case TARGET_EXPR:
6082         TREE_ADDRESSABLE (x) = 1;
6083         cxx_mark_addressable (TREE_OPERAND (x, 0));
6084         return true;
6085
6086       default:
6087         return true;
6088     }
6089 }
6090 \f
6091 /* Build and return a conditional expression IFEXP ? OP1 : OP2.  */
6092
6093 tree
6094 build_x_conditional_expr (location_t loc, tree ifexp, tree op1, tree op2, 
6095                           tsubst_flags_t complain)
6096 {
6097   tree orig_ifexp = ifexp;
6098   tree orig_op1 = op1;
6099   tree orig_op2 = op2;
6100   tree expr;
6101
6102   if (processing_template_decl)
6103     {
6104       /* The standard says that the expression is type-dependent if
6105          IFEXP is type-dependent, even though the eventual type of the
6106          expression doesn't dependent on IFEXP.  */
6107       if (type_dependent_expression_p (ifexp)
6108           /* As a GNU extension, the middle operand may be omitted.  */
6109           || (op1 && type_dependent_expression_p (op1))
6110           || type_dependent_expression_p (op2))
6111         return build_min_nt_loc (loc, COND_EXPR, ifexp, op1, op2);
6112       ifexp = build_non_dependent_expr (ifexp);
6113       if (op1)
6114         op1 = build_non_dependent_expr (op1);
6115       op2 = build_non_dependent_expr (op2);
6116     }
6117
6118   expr = build_conditional_expr (loc, ifexp, op1, op2, complain);
6119   if (processing_template_decl && expr != error_mark_node
6120       && TREE_CODE (expr) != VEC_COND_EXPR)
6121     {
6122       tree min = build_min_non_dep (COND_EXPR, expr,
6123                                     orig_ifexp, orig_op1, orig_op2);
6124       /* In C++11, remember that the result is an lvalue or xvalue.
6125          In C++98, lvalue_kind can just assume lvalue in a template.  */
6126       if (cxx_dialect >= cxx11
6127           && lvalue_or_rvalue_with_address_p (expr)
6128           && !lvalue_or_rvalue_with_address_p (min))
6129         TREE_TYPE (min) = cp_build_reference_type (TREE_TYPE (min),
6130                                                    !real_lvalue_p (expr));
6131       expr = convert_from_reference (min);
6132     }
6133   return expr;
6134 }
6135 \f
6136 /* Given a list of expressions, return a compound expression
6137    that performs them all and returns the value of the last of them.  */
6138
6139 tree
6140 build_x_compound_expr_from_list (tree list, expr_list_kind exp,
6141                                  tsubst_flags_t complain)
6142 {
6143   tree expr = TREE_VALUE (list);
6144
6145   if (BRACE_ENCLOSED_INITIALIZER_P (expr)
6146       && !CONSTRUCTOR_IS_DIRECT_INIT (expr))
6147     {
6148       if (complain & tf_error)
6149         pedwarn (EXPR_LOC_OR_LOC (expr, input_location), 0,
6150                  "list-initializer for non-class type must not "
6151                  "be parenthesized");
6152       else
6153         return error_mark_node;
6154     }
6155
6156   if (TREE_CHAIN (list))
6157     {
6158       if (complain & tf_error)
6159         switch (exp)
6160           {
6161           case ELK_INIT:
6162             permerror (input_location, "expression list treated as compound "
6163                                        "expression in initializer");
6164             break;
6165           case ELK_MEM_INIT:
6166             permerror (input_location, "expression list treated as compound "
6167                                        "expression in mem-initializer");
6168             break;
6169           case ELK_FUNC_CAST:
6170             permerror (input_location, "expression list treated as compound "
6171                                        "expression in functional cast");
6172             break;
6173           default:
6174             gcc_unreachable ();
6175           }
6176       else
6177         return error_mark_node;
6178
6179       for (list = TREE_CHAIN (list); list; list = TREE_CHAIN (list))
6180         expr = build_x_compound_expr (EXPR_LOCATION (TREE_VALUE (list)),
6181                                       expr, TREE_VALUE (list), complain);
6182     }
6183
6184   return expr;
6185 }
6186
6187 /* Like build_x_compound_expr_from_list, but using a VEC.  */
6188
6189 tree
6190 build_x_compound_expr_from_vec (vec<tree, va_gc> *vec, const char *msg,
6191                                 tsubst_flags_t complain)
6192 {
6193   if (vec_safe_is_empty (vec))
6194     return NULL_TREE;
6195   else if (vec->length () == 1)
6196     return (*vec)[0];
6197   else
6198     {
6199       tree expr;
6200       unsigned int ix;
6201       tree t;
6202
6203       if (msg != NULL)
6204         {
6205           if (complain & tf_error)
6206             permerror (input_location,
6207                        "%s expression list treated as compound expression",
6208                        msg);
6209           else
6210             return error_mark_node;
6211         }
6212
6213       expr = (*vec)[0];
6214       for (ix = 1; vec->iterate (ix, &t); ++ix)
6215         expr = build_x_compound_expr (EXPR_LOCATION (t), expr,
6216                                       t, complain);
6217
6218       return expr;
6219     }
6220 }
6221
6222 /* Handle overloading of the ',' operator when needed.  */
6223
6224 tree
6225 build_x_compound_expr (location_t loc, tree op1, tree op2,
6226                        tsubst_flags_t complain)
6227 {
6228   tree result;
6229   tree orig_op1 = op1;
6230   tree orig_op2 = op2;
6231
6232   if (processing_template_decl)
6233     {
6234       if (type_dependent_expression_p (op1)
6235           || type_dependent_expression_p (op2))
6236         return build_min_nt_loc (loc, COMPOUND_EXPR, op1, op2);
6237       op1 = build_non_dependent_expr (op1);
6238       op2 = build_non_dependent_expr (op2);
6239     }
6240
6241   result = build_new_op (loc, COMPOUND_EXPR, LOOKUP_NORMAL, op1, op2,
6242                          NULL_TREE, /*overload=*/NULL, complain);
6243   if (!result)
6244     result = cp_build_compound_expr (op1, op2, complain);
6245
6246   if (processing_template_decl && result != error_mark_node)
6247     return build_min_non_dep (COMPOUND_EXPR, result, orig_op1, orig_op2);
6248
6249   return result;
6250 }
6251
6252 /* Like cp_build_compound_expr, but for the c-common bits.  */
6253
6254 tree
6255 build_compound_expr (location_t /*loc*/, tree lhs, tree rhs)
6256 {
6257   return cp_build_compound_expr (lhs, rhs, tf_warning_or_error);
6258 }
6259
6260 /* Build a compound expression.  */
6261
6262 tree
6263 cp_build_compound_expr (tree lhs, tree rhs, tsubst_flags_t complain)
6264 {
6265   lhs = convert_to_void (lhs, ICV_LEFT_OF_COMMA, complain);
6266
6267   if (lhs == error_mark_node || rhs == error_mark_node)
6268     return error_mark_node;
6269
6270   if (flag_cilkplus
6271       && (TREE_CODE (lhs) == CILK_SPAWN_STMT
6272           || TREE_CODE (rhs) == CILK_SPAWN_STMT))
6273     {
6274       location_t loc = (EXPR_HAS_LOCATION (lhs) ? EXPR_LOCATION (lhs)
6275                         : EXPR_LOCATION (rhs));
6276       error_at (loc,
6277                 "spawned function call cannot be part of a comma expression");
6278       return error_mark_node;
6279     }
6280
6281   if (TREE_CODE (rhs) == TARGET_EXPR)
6282     {
6283       /* If the rhs is a TARGET_EXPR, then build the compound
6284          expression inside the target_expr's initializer. This
6285          helps the compiler to eliminate unnecessary temporaries.  */
6286       tree init = TREE_OPERAND (rhs, 1);
6287
6288       init = build2 (COMPOUND_EXPR, TREE_TYPE (init), lhs, init);
6289       TREE_OPERAND (rhs, 1) = init;
6290
6291       return rhs;
6292     }
6293
6294   if (type_unknown_p (rhs))
6295     {
6296       if (complain & tf_error)
6297         error ("no context to resolve type of %qE", rhs);
6298       return error_mark_node;
6299     }
6300   
6301   return build2 (COMPOUND_EXPR, TREE_TYPE (rhs), lhs, rhs);
6302 }
6303
6304 /* Issue a diagnostic message if casting from SRC_TYPE to DEST_TYPE
6305    casts away constness.  CAST gives the type of cast.  Returns true
6306    if the cast is ill-formed, false if it is well-formed.
6307
6308    ??? This function warns for casting away any qualifier not just
6309    const.  We would like to specify exactly what qualifiers are casted
6310    away.
6311 */
6312
6313 static bool
6314 check_for_casting_away_constness (tree src_type, tree dest_type,
6315                                   enum tree_code cast, tsubst_flags_t complain)
6316 {
6317   /* C-style casts are allowed to cast away constness.  With
6318      WARN_CAST_QUAL, we still want to issue a warning.  */
6319   if (cast == CAST_EXPR && !warn_cast_qual)
6320     return false;
6321   
6322   if (!casts_away_constness (src_type, dest_type, complain))
6323     return false;
6324
6325   switch (cast)
6326     {
6327     case CAST_EXPR:
6328       if (complain & tf_warning)
6329         warning (OPT_Wcast_qual,
6330                  "cast from type %qT to type %qT casts away qualifiers",
6331                  src_type, dest_type);
6332       return false;
6333       
6334     case STATIC_CAST_EXPR:
6335       if (complain & tf_error)
6336         error ("static_cast from type %qT to type %qT casts away qualifiers",
6337                src_type, dest_type);
6338       return true;
6339       
6340     case REINTERPRET_CAST_EXPR:
6341       if (complain & tf_error)
6342         error ("reinterpret_cast from type %qT to type %qT casts away qualifiers",
6343                src_type, dest_type);
6344       return true;
6345
6346     default:
6347       gcc_unreachable();
6348     }
6349 }
6350
6351 /*
6352   Warns if the cast from expression EXPR to type TYPE is useless.
6353  */
6354 void
6355 maybe_warn_about_useless_cast (tree type, tree expr, tsubst_flags_t complain)
6356 {
6357   if (warn_useless_cast
6358       && complain & tf_warning)
6359     {
6360       if ((TREE_CODE (type) == REFERENCE_TYPE
6361            && (TYPE_REF_IS_RVALUE (type)
6362                ? xvalue_p (expr) : real_lvalue_p (expr))
6363            && same_type_p (TREE_TYPE (expr), TREE_TYPE (type)))
6364           || same_type_p (TREE_TYPE (expr), type))
6365         warning (OPT_Wuseless_cast, "useless cast to type %qT", type);
6366     }
6367 }
6368
6369 /* Convert EXPR (an expression with pointer-to-member type) to TYPE
6370    (another pointer-to-member type in the same hierarchy) and return
6371    the converted expression.  If ALLOW_INVERSE_P is permitted, a
6372    pointer-to-derived may be converted to pointer-to-base; otherwise,
6373    only the other direction is permitted.  If C_CAST_P is true, this
6374    conversion is taking place as part of a C-style cast.  */
6375
6376 tree
6377 convert_ptrmem (tree type, tree expr, bool allow_inverse_p,
6378                 bool c_cast_p, tsubst_flags_t complain)
6379 {
6380   if (TYPE_PTRDATAMEM_P (type))
6381     {
6382       tree delta;
6383
6384       if (TREE_CODE (expr) == PTRMEM_CST)
6385         expr = cplus_expand_constant (expr);
6386       delta = get_delta_difference (TYPE_PTRMEM_CLASS_TYPE (TREE_TYPE (expr)),
6387                                     TYPE_PTRMEM_CLASS_TYPE (type),
6388                                     allow_inverse_p,
6389                                     c_cast_p, complain);
6390       if (delta == error_mark_node)
6391         return error_mark_node;
6392
6393       if (!integer_zerop (delta))
6394         {
6395           tree cond, op1, op2;
6396
6397           cond = cp_build_binary_op (input_location,
6398                                      EQ_EXPR,
6399                                      expr,
6400                                      build_int_cst (TREE_TYPE (expr), -1),
6401                                      complain);
6402           op1 = build_nop (ptrdiff_type_node, expr);
6403           op2 = cp_build_binary_op (input_location,
6404                                     PLUS_EXPR, op1, delta,
6405                                     complain);
6406
6407           expr = fold_build3_loc (input_location,
6408                               COND_EXPR, ptrdiff_type_node, cond, op1, op2);
6409                          
6410         }
6411
6412       return build_nop (type, expr);
6413     }
6414   else
6415     return build_ptrmemfunc (TYPE_PTRMEMFUNC_FN_TYPE (type), expr,
6416                              allow_inverse_p, c_cast_p, complain);
6417 }
6418
6419 /* Perform a static_cast from EXPR to TYPE.  When C_CAST_P is true,
6420    this static_cast is being attempted as one of the possible casts
6421    allowed by a C-style cast.  (In that case, accessibility of base
6422    classes is not considered, and it is OK to cast away
6423    constness.)  Return the result of the cast.  *VALID_P is set to
6424    indicate whether or not the cast was valid.  */
6425
6426 static tree
6427 build_static_cast_1 (tree type, tree expr, bool c_cast_p,
6428                      bool *valid_p, tsubst_flags_t complain)
6429 {
6430   tree intype;
6431   tree result;
6432   cp_lvalue_kind clk;
6433
6434   /* Assume the cast is valid.  */
6435   *valid_p = true;
6436
6437   intype = unlowered_expr_type (expr);
6438
6439   /* Save casted types in the function's used types hash table.  */
6440   used_types_insert (type);
6441
6442   /* [expr.static.cast]
6443
6444      An lvalue of type "cv1 B", where B is a class type, can be cast
6445      to type "reference to cv2 D", where D is a class derived (clause
6446      _class.derived_) from B, if a valid standard conversion from
6447      "pointer to D" to "pointer to B" exists (_conv.ptr_), cv2 is the
6448      same cv-qualification as, or greater cv-qualification than, cv1,
6449      and B is not a virtual base class of D.  */
6450   /* We check this case before checking the validity of "TYPE t =
6451      EXPR;" below because for this case:
6452
6453        struct B {};
6454        struct D : public B { D(const B&); };
6455        extern B& b;
6456        void f() { static_cast<const D&>(b); }
6457
6458      we want to avoid constructing a new D.  The standard is not
6459      completely clear about this issue, but our interpretation is
6460      consistent with other compilers.  */
6461   if (TREE_CODE (type) == REFERENCE_TYPE
6462       && CLASS_TYPE_P (TREE_TYPE (type))
6463       && CLASS_TYPE_P (intype)
6464       && (TYPE_REF_IS_RVALUE (type) || real_lvalue_p (expr))
6465       && DERIVED_FROM_P (intype, TREE_TYPE (type))
6466       && can_convert (build_pointer_type (TYPE_MAIN_VARIANT (intype)),
6467                       build_pointer_type (TYPE_MAIN_VARIANT
6468                                           (TREE_TYPE (type))),
6469                       complain)
6470       && (c_cast_p
6471           || at_least_as_qualified_p (TREE_TYPE (type), intype)))
6472     {
6473       tree base;
6474
6475       /* There is a standard conversion from "D*" to "B*" even if "B"
6476          is ambiguous or inaccessible.  If this is really a
6477          static_cast, then we check both for inaccessibility and
6478          ambiguity.  However, if this is a static_cast being performed
6479          because the user wrote a C-style cast, then accessibility is
6480          not considered.  */
6481       base = lookup_base (TREE_TYPE (type), intype,
6482                           c_cast_p ? ba_unique : ba_check,
6483                           NULL, complain);
6484       expr = build_address (expr);
6485
6486       if (flag_sanitize & SANITIZE_VPTR)
6487         {
6488           tree ubsan_check
6489             = cp_ubsan_maybe_instrument_downcast (input_location, type, expr);
6490           if (ubsan_check)
6491             expr = ubsan_check;
6492         }
6493
6494       /* Convert from "B*" to "D*".  This function will check that "B"
6495          is not a virtual base of "D".  */
6496       expr = build_base_path (MINUS_EXPR, expr, base, /*nonnull=*/false,
6497                               complain);
6498
6499       /* Convert the pointer to a reference -- but then remember that
6500          there are no expressions with reference type in C++.
6501
6502          We call rvalue so that there's an actual tree code
6503          (NON_LVALUE_EXPR) for the static_cast; otherwise, if the operand
6504          is a variable with the same type, the conversion would get folded
6505          away, leaving just the variable and causing lvalue_kind to give
6506          the wrong answer.  */
6507       return convert_from_reference (rvalue (cp_fold_convert (type, expr)));
6508     }
6509
6510   /* "A glvalue of type cv1 T1 can be cast to type rvalue reference to
6511      cv2 T2 if cv2 T2 is reference-compatible with cv1 T1 (8.5.3)."  */
6512   if (TREE_CODE (type) == REFERENCE_TYPE
6513       && TYPE_REF_IS_RVALUE (type)
6514       && (clk = real_lvalue_p (expr))
6515       && reference_related_p (TREE_TYPE (type), intype)
6516       && (c_cast_p || at_least_as_qualified_p (TREE_TYPE (type), intype)))
6517     {
6518       if (clk == clk_ordinary)
6519         {
6520           /* Handle the (non-bit-field) lvalue case here by casting to
6521              lvalue reference and then changing it to an rvalue reference.
6522              Casting an xvalue to rvalue reference will be handled by the
6523              main code path.  */
6524           tree lref = cp_build_reference_type (TREE_TYPE (type), false);
6525           result = (perform_direct_initialization_if_possible
6526                     (lref, expr, c_cast_p, complain));
6527           result = cp_fold_convert (type, result);
6528           /* Make sure we don't fold back down to a named rvalue reference,
6529              because that would be an lvalue.  */
6530           if (DECL_P (result))
6531             result = build1 (NON_LVALUE_EXPR, type, result);
6532           return convert_from_reference (result);
6533         }
6534       else
6535         /* For a bit-field or packed field, bind to a temporary.  */
6536         expr = rvalue (expr);
6537     }
6538
6539   /* Resolve overloaded address here rather than once in
6540      implicit_conversion and again in the inverse code below.  */
6541   if (TYPE_PTRMEMFUNC_P (type) && type_unknown_p (expr))
6542     {
6543       expr = instantiate_type (type, expr, complain);
6544       intype = TREE_TYPE (expr);
6545     }
6546
6547   /* [expr.static.cast]
6548
6549      Any expression can be explicitly converted to type cv void.  */
6550   if (VOID_TYPE_P (type))
6551     return convert_to_void (expr, ICV_CAST, complain);
6552
6553   /* [class.abstract]
6554      An abstract class shall not be used ... as the type of an explicit
6555      conversion.  */
6556   if (abstract_virtuals_error_sfinae (ACU_CAST, type, complain))
6557     return error_mark_node;
6558
6559   /* [expr.static.cast]
6560
6561      An expression e can be explicitly converted to a type T using a
6562      static_cast of the form static_cast<T>(e) if the declaration T
6563      t(e);" is well-formed, for some invented temporary variable
6564      t.  */
6565   result = perform_direct_initialization_if_possible (type, expr,
6566                                                       c_cast_p, complain);
6567   if (result)
6568     {
6569       result = convert_from_reference (result);
6570
6571       /* [expr.static.cast]
6572
6573          If T is a reference type, the result is an lvalue; otherwise,
6574          the result is an rvalue.  */
6575       if (TREE_CODE (type) != REFERENCE_TYPE)
6576         result = rvalue (result);
6577       return result;
6578     }
6579
6580   /* [expr.static.cast]
6581
6582      The inverse of any standard conversion sequence (clause _conv_),
6583      other than the lvalue-to-rvalue (_conv.lval_), array-to-pointer
6584      (_conv.array_), function-to-pointer (_conv.func_), and boolean
6585      (_conv.bool_) conversions, can be performed explicitly using
6586      static_cast subject to the restriction that the explicit
6587      conversion does not cast away constness (_expr.const.cast_), and
6588      the following additional rules for specific cases:  */
6589   /* For reference, the conversions not excluded are: integral
6590      promotions, floating point promotion, integral conversions,
6591      floating point conversions, floating-integral conversions,
6592      pointer conversions, and pointer to member conversions.  */
6593   /* DR 128
6594
6595      A value of integral _or enumeration_ type can be explicitly
6596      converted to an enumeration type.  */
6597   /* The effect of all that is that any conversion between any two
6598      types which are integral, floating, or enumeration types can be
6599      performed.  */
6600   if ((INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6601        || SCALAR_FLOAT_TYPE_P (type))
6602       && (INTEGRAL_OR_ENUMERATION_TYPE_P (intype)
6603           || SCALAR_FLOAT_TYPE_P (intype)))
6604     return ocp_convert (type, expr, CONV_C_CAST, LOOKUP_NORMAL, complain);
6605
6606   if (TYPE_PTR_P (type) && TYPE_PTR_P (intype)
6607       && CLASS_TYPE_P (TREE_TYPE (type))
6608       && CLASS_TYPE_P (TREE_TYPE (intype))
6609       && can_convert (build_pointer_type (TYPE_MAIN_VARIANT
6610                                           (TREE_TYPE (intype))),
6611                       build_pointer_type (TYPE_MAIN_VARIANT
6612                                           (TREE_TYPE (type))),
6613                       complain))
6614     {
6615       tree base;
6616
6617       if (!c_cast_p
6618           && check_for_casting_away_constness (intype, type, STATIC_CAST_EXPR,
6619                                                complain))
6620         return error_mark_node;
6621       base = lookup_base (TREE_TYPE (type), TREE_TYPE (intype),
6622                           c_cast_p ? ba_unique : ba_check,
6623                           NULL, complain);
6624       expr = build_base_path (MINUS_EXPR, expr, base, /*nonnull=*/false,
6625                               complain);
6626
6627       if (flag_sanitize & SANITIZE_VPTR)
6628         {
6629           tree ubsan_check
6630             = cp_ubsan_maybe_instrument_downcast (input_location, type, expr);
6631           if (ubsan_check)
6632             expr = ubsan_check;
6633         }
6634
6635       return cp_fold_convert (type, expr);
6636     }
6637
6638   if ((TYPE_PTRDATAMEM_P (type) && TYPE_PTRDATAMEM_P (intype))
6639       || (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype)))
6640     {
6641       tree c1;
6642       tree c2;
6643       tree t1;
6644       tree t2;
6645
6646       c1 = TYPE_PTRMEM_CLASS_TYPE (intype);
6647       c2 = TYPE_PTRMEM_CLASS_TYPE (type);
6648
6649       if (TYPE_PTRDATAMEM_P (type))
6650         {
6651           t1 = (build_ptrmem_type
6652                 (c1,
6653                  TYPE_MAIN_VARIANT (TYPE_PTRMEM_POINTED_TO_TYPE (intype))));
6654           t2 = (build_ptrmem_type
6655                 (c2,
6656                  TYPE_MAIN_VARIANT (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
6657         }
6658       else
6659         {
6660           t1 = intype;
6661           t2 = type;
6662         }
6663       if (can_convert (t1, t2, complain) || can_convert (t2, t1, complain))
6664         {
6665           if (!c_cast_p
6666               && check_for_casting_away_constness (intype, type,
6667                                                    STATIC_CAST_EXPR,
6668                                                    complain))
6669             return error_mark_node;
6670           return convert_ptrmem (type, expr, /*allow_inverse_p=*/1,
6671                                  c_cast_p, complain);
6672         }
6673     }
6674
6675   /* [expr.static.cast]
6676
6677      An rvalue of type "pointer to cv void" can be explicitly
6678      converted to a pointer to object type.  A value of type pointer
6679      to object converted to "pointer to cv void" and back to the
6680      original pointer type will have its original value.  */
6681   if (TYPE_PTR_P (intype)
6682       && VOID_TYPE_P (TREE_TYPE (intype))
6683       && TYPE_PTROB_P (type))
6684     {
6685       if (!c_cast_p
6686           && check_for_casting_away_constness (intype, type, STATIC_CAST_EXPR,
6687                                                complain))
6688         return error_mark_node;
6689       return build_nop (type, expr);
6690     }
6691
6692   *valid_p = false;
6693   return error_mark_node;
6694 }
6695
6696 /* Return an expression representing static_cast<TYPE>(EXPR).  */
6697
6698 tree
6699 build_static_cast (tree type, tree expr, tsubst_flags_t complain)
6700 {
6701   tree result;
6702   bool valid_p;
6703
6704   if (type == error_mark_node || expr == error_mark_node)
6705     return error_mark_node;
6706
6707   if (processing_template_decl)
6708     {
6709       expr = build_min (STATIC_CAST_EXPR, type, expr);
6710       /* We don't know if it will or will not have side effects.  */
6711       TREE_SIDE_EFFECTS (expr) = 1;
6712       return convert_from_reference (expr);
6713     }
6714
6715   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
6716      Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
6717   if (TREE_CODE (type) != REFERENCE_TYPE
6718       && TREE_CODE (expr) == NOP_EXPR
6719       && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
6720     expr = TREE_OPERAND (expr, 0);
6721
6722   result = build_static_cast_1 (type, expr, /*c_cast_p=*/false, &valid_p,
6723                                 complain);
6724   if (valid_p)
6725     {
6726       if (result != error_mark_node)
6727         maybe_warn_about_useless_cast (type, expr, complain);
6728       return result;
6729     }
6730
6731   if (complain & tf_error)
6732     error ("invalid static_cast from type %qT to type %qT",
6733            TREE_TYPE (expr), type);
6734   return error_mark_node;
6735 }
6736
6737 /* EXPR is an expression with member function or pointer-to-member
6738    function type.  TYPE is a pointer type.  Converting EXPR to TYPE is
6739    not permitted by ISO C++, but we accept it in some modes.  If we
6740    are not in one of those modes, issue a diagnostic.  Return the
6741    converted expression.  */
6742
6743 tree
6744 convert_member_func_to_ptr (tree type, tree expr, tsubst_flags_t complain)
6745 {
6746   tree intype;
6747   tree decl;
6748
6749   intype = TREE_TYPE (expr);
6750   gcc_assert (TYPE_PTRMEMFUNC_P (intype)
6751               || TREE_CODE (intype) == METHOD_TYPE);
6752
6753   if (!(complain & tf_warning_or_error))
6754     return error_mark_node;
6755
6756   if (pedantic || warn_pmf2ptr)
6757     pedwarn (input_location, pedantic ? OPT_Wpedantic : OPT_Wpmf_conversions,
6758              "converting from %qT to %qT", intype, type);
6759
6760   if (TREE_CODE (intype) == METHOD_TYPE)
6761     expr = build_addr_func (expr, complain);
6762   else if (TREE_CODE (expr) == PTRMEM_CST)
6763     expr = build_address (PTRMEM_CST_MEMBER (expr));
6764   else
6765     {
6766       decl = maybe_dummy_object (TYPE_PTRMEM_CLASS_TYPE (intype), 0);
6767       decl = build_address (decl);
6768       expr = get_member_function_from_ptrfunc (&decl, expr, complain);
6769     }
6770
6771   if (expr == error_mark_node)
6772     return error_mark_node;
6773
6774   return build_nop (type, expr);
6775 }
6776
6777 /* Return a representation for a reinterpret_cast from EXPR to TYPE.
6778    If C_CAST_P is true, this reinterpret cast is being done as part of
6779    a C-style cast.  If VALID_P is non-NULL, *VALID_P is set to
6780    indicate whether or not reinterpret_cast was valid.  */
6781
6782 static tree
6783 build_reinterpret_cast_1 (tree type, tree expr, bool c_cast_p,
6784                           bool *valid_p, tsubst_flags_t complain)
6785 {
6786   tree intype;
6787
6788   /* Assume the cast is invalid.  */
6789   if (valid_p)
6790     *valid_p = true;
6791
6792   if (type == error_mark_node || error_operand_p (expr))
6793     return error_mark_node;
6794
6795   intype = TREE_TYPE (expr);
6796
6797   /* Save casted types in the function's used types hash table.  */
6798   used_types_insert (type);
6799
6800   /* [expr.reinterpret.cast]
6801      An lvalue expression of type T1 can be cast to the type
6802      "reference to T2" if an expression of type "pointer to T1" can be
6803      explicitly converted to the type "pointer to T2" using a
6804      reinterpret_cast.  */
6805   if (TREE_CODE (type) == REFERENCE_TYPE)
6806     {
6807       if (! real_lvalue_p (expr))
6808         {
6809           if (complain & tf_error)
6810             error ("invalid cast of an rvalue expression of type "
6811                    "%qT to type %qT",
6812                    intype, type);
6813           return error_mark_node;
6814         }
6815
6816       /* Warn about a reinterpret_cast from "A*" to "B&" if "A" and
6817          "B" are related class types; the reinterpret_cast does not
6818          adjust the pointer.  */
6819       if (TYPE_PTR_P (intype)
6820           && (complain & tf_warning)
6821           && (comptypes (TREE_TYPE (intype), TREE_TYPE (type),
6822                          COMPARE_BASE | COMPARE_DERIVED)))
6823         warning (0, "casting %qT to %qT does not dereference pointer",
6824                  intype, type);
6825
6826       expr = cp_build_addr_expr (expr, complain);
6827
6828       if (warn_strict_aliasing > 2)
6829         strict_aliasing_warning (TREE_TYPE (expr), type, expr);
6830
6831       if (expr != error_mark_node)
6832         expr = build_reinterpret_cast_1
6833           (build_pointer_type (TREE_TYPE (type)), expr, c_cast_p,
6834            valid_p, complain);
6835       if (expr != error_mark_node)
6836         /* cp_build_indirect_ref isn't right for rvalue refs.  */
6837         expr = convert_from_reference (fold_convert (type, expr));
6838       return expr;
6839     }
6840
6841   /* As a G++ extension, we consider conversions from member
6842      functions, and pointers to member functions to
6843      pointer-to-function and pointer-to-void types.  If
6844      -Wno-pmf-conversions has not been specified,
6845      convert_member_func_to_ptr will issue an error message.  */
6846   if ((TYPE_PTRMEMFUNC_P (intype)
6847        || TREE_CODE (intype) == METHOD_TYPE)
6848       && TYPE_PTR_P (type)
6849       && (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE
6850           || VOID_TYPE_P (TREE_TYPE (type))))
6851     return convert_member_func_to_ptr (type, expr, complain);
6852
6853   /* If the cast is not to a reference type, the lvalue-to-rvalue,
6854      array-to-pointer, and function-to-pointer conversions are
6855      performed.  */
6856   expr = decay_conversion (expr, complain);
6857
6858   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
6859      Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
6860   if (TREE_CODE (expr) == NOP_EXPR
6861       && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
6862     expr = TREE_OPERAND (expr, 0);
6863
6864   if (error_operand_p (expr))
6865     return error_mark_node;
6866
6867   intype = TREE_TYPE (expr);
6868
6869   /* [expr.reinterpret.cast]
6870      A pointer can be converted to any integral type large enough to
6871      hold it. ... A value of type std::nullptr_t can be converted to
6872      an integral type; the conversion has the same meaning and
6873      validity as a conversion of (void*)0 to the integral type.  */
6874   if (CP_INTEGRAL_TYPE_P (type)
6875       && (TYPE_PTR_P (intype) || NULLPTR_TYPE_P (intype)))
6876     {
6877       if (TYPE_PRECISION (type) < TYPE_PRECISION (intype))
6878         {
6879           if (complain & tf_error)
6880             permerror (input_location, "cast from %qT to %qT loses precision",
6881                        intype, type);
6882           else
6883             return error_mark_node;
6884         }
6885       if (NULLPTR_TYPE_P (intype))
6886         return build_int_cst (type, 0);
6887     }
6888   /* [expr.reinterpret.cast]
6889      A value of integral or enumeration type can be explicitly
6890      converted to a pointer.  */
6891   else if (TYPE_PTR_P (type) && INTEGRAL_OR_ENUMERATION_TYPE_P (intype))
6892     /* OK */
6893     ;
6894   else if ((INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6895             || TYPE_PTR_OR_PTRMEM_P (type))
6896            && same_type_p (type, intype))
6897     /* DR 799 */
6898     return rvalue (expr);
6899   else if ((TYPE_PTRFN_P (type) && TYPE_PTRFN_P (intype))
6900            || (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype)))
6901     return fold_if_not_in_template (build_nop (type, expr));
6902   else if ((TYPE_PTRDATAMEM_P (type) && TYPE_PTRDATAMEM_P (intype))
6903            || (TYPE_PTROBV_P (type) && TYPE_PTROBV_P (intype)))
6904     {
6905       tree sexpr = expr;
6906
6907       if (!c_cast_p
6908           && check_for_casting_away_constness (intype, type,
6909                                                REINTERPRET_CAST_EXPR,
6910                                                complain))
6911         return error_mark_node;
6912       /* Warn about possible alignment problems.  */
6913       if (STRICT_ALIGNMENT && warn_cast_align
6914           && (complain & tf_warning)
6915           && !VOID_TYPE_P (type)
6916           && TREE_CODE (TREE_TYPE (intype)) != FUNCTION_TYPE
6917           && COMPLETE_TYPE_P (TREE_TYPE (type))
6918           && COMPLETE_TYPE_P (TREE_TYPE (intype))
6919           && TYPE_ALIGN (TREE_TYPE (type)) > TYPE_ALIGN (TREE_TYPE (intype)))
6920         warning (OPT_Wcast_align, "cast from %qT to %qT "
6921                  "increases required alignment of target type", intype, type);
6922
6923       /* We need to strip nops here, because the front end likes to
6924          create (int *)&a for array-to-pointer decay, instead of &a[0].  */
6925       STRIP_NOPS (sexpr);
6926       if (warn_strict_aliasing <= 2)
6927         strict_aliasing_warning (intype, type, sexpr);
6928
6929       return fold_if_not_in_template (build_nop (type, expr));
6930     }
6931   else if ((TYPE_PTRFN_P (type) && TYPE_PTROBV_P (intype))
6932            || (TYPE_PTRFN_P (intype) && TYPE_PTROBV_P (type)))
6933     {
6934       if (complain & tf_warning)
6935         /* C++11 5.2.10 p8 says that "Converting a function pointer to an
6936            object pointer type or vice versa is conditionally-supported."  */
6937         warning (OPT_Wconditionally_supported,
6938                  "casting between pointer-to-function and pointer-to-object "
6939                  "is conditionally-supported");
6940       return fold_if_not_in_template (build_nop (type, expr));
6941     }
6942   else if (TREE_CODE (type) == VECTOR_TYPE)
6943     return fold_if_not_in_template (convert_to_vector (type, expr));
6944   else if (TREE_CODE (intype) == VECTOR_TYPE
6945            && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6946     return fold_if_not_in_template (convert_to_integer (type, expr));
6947   else
6948     {
6949       if (valid_p)
6950         *valid_p = false;
6951       if (complain & tf_error)
6952         error ("invalid cast from type %qT to type %qT", intype, type);
6953       return error_mark_node;
6954     }
6955
6956   return cp_convert (type, expr, complain);
6957 }
6958
6959 tree
6960 build_reinterpret_cast (tree type, tree expr, tsubst_flags_t complain)
6961 {
6962   tree r;
6963
6964   if (type == error_mark_node || expr == error_mark_node)
6965     return error_mark_node;
6966
6967   if (processing_template_decl)
6968     {
6969       tree t = build_min (REINTERPRET_CAST_EXPR, type, expr);
6970
6971       if (!TREE_SIDE_EFFECTS (t)
6972           && type_dependent_expression_p (expr))
6973         /* There might turn out to be side effects inside expr.  */
6974         TREE_SIDE_EFFECTS (t) = 1;
6975       return convert_from_reference (t);
6976     }
6977
6978   r = build_reinterpret_cast_1 (type, expr, /*c_cast_p=*/false,
6979                                 /*valid_p=*/NULL, complain);
6980   if (r != error_mark_node)
6981     maybe_warn_about_useless_cast (type, expr, complain);
6982   return r;
6983 }
6984
6985 /* Perform a const_cast from EXPR to TYPE.  If the cast is valid,
6986    return an appropriate expression.  Otherwise, return
6987    error_mark_node.  If the cast is not valid, and COMPLAIN is true,
6988    then a diagnostic will be issued.  If VALID_P is non-NULL, we are
6989    performing a C-style cast, its value upon return will indicate
6990    whether or not the conversion succeeded.  */
6991
6992 static tree
6993 build_const_cast_1 (tree dst_type, tree expr, tsubst_flags_t complain,
6994                     bool *valid_p)
6995 {
6996   tree src_type;
6997   tree reference_type;
6998
6999   /* Callers are responsible for handling error_mark_node as a
7000      destination type.  */
7001   gcc_assert (dst_type != error_mark_node);
7002   /* In a template, callers should be building syntactic
7003      representations of casts, not using this machinery.  */
7004   gcc_assert (!processing_template_decl);
7005
7006   /* Assume the conversion is invalid.  */
7007   if (valid_p)
7008     *valid_p = false;
7009
7010   if (!POINTER_TYPE_P (dst_type) && !TYPE_PTRDATAMEM_P (dst_type))
7011     {
7012       if (complain & tf_error)
7013         error ("invalid use of const_cast with type %qT, "
7014                "which is not a pointer, "
7015                "reference, nor a pointer-to-data-member type", dst_type);
7016       return error_mark_node;
7017     }
7018
7019   if (TREE_CODE (TREE_TYPE (dst_type)) == FUNCTION_TYPE)
7020     {
7021       if (complain & tf_error)
7022         error ("invalid use of const_cast with type %qT, which is a pointer "
7023                "or reference to a function type", dst_type);
7024       return error_mark_node;
7025     }
7026
7027   /* Save casted types in the function's used types hash table.  */
7028   used_types_insert (dst_type);
7029
7030   src_type = TREE_TYPE (expr);
7031   /* Expressions do not really have reference types.  */
7032   if (TREE_CODE (src_type) == REFERENCE_TYPE)
7033     src_type = TREE_TYPE (src_type);
7034
7035   /* [expr.const.cast]
7036
7037      For two object types T1 and T2, if a pointer to T1 can be explicitly
7038      converted to the type "pointer to T2" using a const_cast, then the
7039      following conversions can also be made:
7040
7041      -- an lvalue of type T1 can be explicitly converted to an lvalue of
7042      type T2 using the cast const_cast<T2&>;
7043
7044      -- a glvalue of type T1 can be explicitly converted to an xvalue of
7045      type T2 using the cast const_cast<T2&&>; and
7046
7047      -- if T1 is a class type, a prvalue of type T1 can be explicitly
7048      converted to an xvalue of type T2 using the cast const_cast<T2&&>.  */
7049
7050   if (TREE_CODE (dst_type) == REFERENCE_TYPE)
7051     {
7052       reference_type = dst_type;
7053       if (!TYPE_REF_IS_RVALUE (dst_type)
7054           ? real_lvalue_p (expr)
7055           : (CLASS_TYPE_P (TREE_TYPE (dst_type))
7056              ? lvalue_p (expr)
7057              : lvalue_or_rvalue_with_address_p (expr)))
7058         /* OK.  */;
7059       else
7060         {
7061           if (complain & tf_error)
7062             error ("invalid const_cast of an rvalue of type %qT to type %qT",
7063                    src_type, dst_type);
7064           return error_mark_node;
7065         }
7066       dst_type = build_pointer_type (TREE_TYPE (dst_type));
7067       src_type = build_pointer_type (src_type);
7068     }
7069   else
7070     {
7071       reference_type = NULL_TREE;
7072       /* If the destination type is not a reference type, the
7073          lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7074          conversions are performed.  */
7075       src_type = type_decays_to (src_type);
7076       if (src_type == error_mark_node)
7077         return error_mark_node;
7078     }
7079
7080   if (TYPE_PTR_P (src_type) || TYPE_PTRDATAMEM_P (src_type))
7081     {
7082       if (comp_ptr_ttypes_const (dst_type, src_type))
7083         {
7084           if (valid_p)
7085             {
7086               *valid_p = true;
7087               /* This cast is actually a C-style cast.  Issue a warning if
7088                  the user is making a potentially unsafe cast.  */
7089               check_for_casting_away_constness (src_type, dst_type,
7090                                                 CAST_EXPR, complain);
7091             }
7092           if (reference_type)
7093             {
7094               expr = cp_build_addr_expr (expr, complain);
7095               if (expr == error_mark_node)
7096                 return error_mark_node;
7097               expr = build_nop (reference_type, expr);
7098               return convert_from_reference (expr);
7099             }
7100           else
7101             {
7102               expr = decay_conversion (expr, complain);
7103               if (expr == error_mark_node)
7104                 return error_mark_node;
7105
7106               /* build_c_cast puts on a NOP_EXPR to make the result not an
7107                  lvalue.  Strip such NOP_EXPRs if VALUE is being used in
7108                  non-lvalue context.  */
7109               if (TREE_CODE (expr) == NOP_EXPR
7110                   && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
7111                 expr = TREE_OPERAND (expr, 0);
7112               return build_nop (dst_type, expr);
7113             }
7114         }
7115       else if (valid_p
7116                && !at_least_as_qualified_p (TREE_TYPE (dst_type),
7117                                             TREE_TYPE (src_type)))
7118         check_for_casting_away_constness (src_type, dst_type, CAST_EXPR,
7119                                           complain);
7120     }
7121
7122   if (complain & tf_error)
7123     error ("invalid const_cast from type %qT to type %qT",
7124            src_type, dst_type);
7125   return error_mark_node;
7126 }
7127
7128 tree
7129 build_const_cast (tree type, tree expr, tsubst_flags_t complain)
7130 {
7131   tree r;
7132
7133   if (type == error_mark_node || error_operand_p (expr))
7134     return error_mark_node;
7135
7136   if (processing_template_decl)
7137     {
7138       tree t = build_min (CONST_CAST_EXPR, type, expr);
7139
7140       if (!TREE_SIDE_EFFECTS (t)
7141           && type_dependent_expression_p (expr))
7142         /* There might turn out to be side effects inside expr.  */
7143         TREE_SIDE_EFFECTS (t) = 1;
7144       return convert_from_reference (t);
7145     }
7146
7147   r = build_const_cast_1 (type, expr, complain, /*valid_p=*/NULL);
7148   if (r != error_mark_node)
7149     maybe_warn_about_useless_cast (type, expr, complain);
7150   return r;
7151 }
7152
7153 /* Like cp_build_c_cast, but for the c-common bits.  */
7154
7155 tree
7156 build_c_cast (location_t /*loc*/, tree type, tree expr)
7157 {
7158   return cp_build_c_cast (type, expr, tf_warning_or_error);
7159 }
7160
7161 /* Build an expression representing an explicit C-style cast to type
7162    TYPE of expression EXPR.  */
7163
7164 tree
7165 cp_build_c_cast (tree type, tree expr, tsubst_flags_t complain)
7166 {
7167   tree value = expr;
7168   tree result;
7169   bool valid_p;
7170
7171   if (type == error_mark_node || error_operand_p (expr))
7172     return error_mark_node;
7173
7174   if (processing_template_decl)
7175     {
7176       tree t = build_min (CAST_EXPR, type,
7177                           tree_cons (NULL_TREE, value, NULL_TREE));
7178       /* We don't know if it will or will not have side effects.  */
7179       TREE_SIDE_EFFECTS (t) = 1;
7180       return convert_from_reference (t);
7181     }
7182
7183   /* Casts to a (pointer to a) specific ObjC class (or 'id' or
7184      'Class') should always be retained, because this information aids
7185      in method lookup.  */
7186   if (objc_is_object_ptr (type)
7187       && objc_is_object_ptr (TREE_TYPE (expr)))
7188     return build_nop (type, expr);
7189
7190   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
7191      Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
7192   if (TREE_CODE (type) != REFERENCE_TYPE
7193       && TREE_CODE (value) == NOP_EXPR
7194       && TREE_TYPE (value) == TREE_TYPE (TREE_OPERAND (value, 0)))
7195     value = TREE_OPERAND (value, 0);
7196
7197   if (TREE_CODE (type) == ARRAY_TYPE)
7198     {
7199       /* Allow casting from T1* to T2[] because Cfront allows it.
7200          NIHCL uses it. It is not valid ISO C++ however.  */
7201       if (TYPE_PTR_P (TREE_TYPE (expr)))
7202         {
7203           if (complain & tf_error)
7204             permerror (input_location, "ISO C++ forbids casting to an array type %qT", type);
7205           else
7206             return error_mark_node;
7207           type = build_pointer_type (TREE_TYPE (type));
7208         }
7209       else
7210         {
7211           if (complain & tf_error)
7212             error ("ISO C++ forbids casting to an array type %qT", type);
7213           return error_mark_node;
7214         }
7215     }
7216
7217   if (TREE_CODE (type) == FUNCTION_TYPE
7218       || TREE_CODE (type) == METHOD_TYPE)
7219     {
7220       if (complain & tf_error)
7221         error ("invalid cast to function type %qT", type);
7222       return error_mark_node;
7223     }
7224
7225   if (TYPE_PTR_P (type)
7226       && TREE_CODE (TREE_TYPE (value)) == INTEGER_TYPE
7227       /* Casting to an integer of smaller size is an error detected elsewhere.  */
7228       && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (value))
7229       /* Don't warn about converting any constant.  */
7230       && !TREE_CONSTANT (value))
7231     warning_at (input_location, OPT_Wint_to_pointer_cast, 
7232                 "cast to pointer from integer of different size");
7233
7234   /* A C-style cast can be a const_cast.  */
7235   result = build_const_cast_1 (type, value, complain & tf_warning,
7236                                &valid_p);
7237   if (valid_p)
7238     {
7239       if (result != error_mark_node)
7240         maybe_warn_about_useless_cast (type, value, complain);
7241       return result;
7242     }
7243
7244   /* Or a static cast.  */
7245   result = build_static_cast_1 (type, value, /*c_cast_p=*/true,
7246                                 &valid_p, complain);
7247   /* Or a reinterpret_cast.  */
7248   if (!valid_p)
7249     result = build_reinterpret_cast_1 (type, value, /*c_cast_p=*/true,
7250                                        &valid_p, complain);
7251   /* The static_cast or reinterpret_cast may be followed by a
7252      const_cast.  */
7253   if (valid_p
7254       /* A valid cast may result in errors if, for example, a
7255          conversion to an ambiguous base class is required.  */
7256       && !error_operand_p (result))
7257     {
7258       tree result_type;
7259
7260       maybe_warn_about_useless_cast (type, value, complain);
7261
7262       /* Non-class rvalues always have cv-unqualified type.  */
7263       if (!CLASS_TYPE_P (type))
7264         type = TYPE_MAIN_VARIANT (type);
7265       result_type = TREE_TYPE (result);
7266       if (!CLASS_TYPE_P (result_type) && TREE_CODE (type) != REFERENCE_TYPE)
7267         result_type = TYPE_MAIN_VARIANT (result_type);
7268       /* If the type of RESULT does not match TYPE, perform a
7269          const_cast to make it match.  If the static_cast or
7270          reinterpret_cast succeeded, we will differ by at most
7271          cv-qualification, so the follow-on const_cast is guaranteed
7272          to succeed.  */
7273       if (!same_type_p (non_reference (type), non_reference (result_type)))
7274         {
7275           result = build_const_cast_1 (type, result, false, &valid_p);
7276           gcc_assert (valid_p);
7277         }
7278       return result;
7279     }
7280
7281   return error_mark_node;
7282 }
7283 \f
7284 /* For use from the C common bits.  */
7285 tree
7286 build_modify_expr (location_t /*location*/,
7287                    tree lhs, tree /*lhs_origtype*/,
7288                    enum tree_code modifycode, 
7289                    location_t /*rhs_location*/, tree rhs,
7290                    tree /*rhs_origtype*/)
7291 {
7292   return cp_build_modify_expr (lhs, modifycode, rhs, tf_warning_or_error);
7293 }
7294
7295 /* Build an assignment expression of lvalue LHS from value RHS.
7296    MODIFYCODE is the code for a binary operator that we use
7297    to combine the old value of LHS with RHS to get the new value.
7298    Or else MODIFYCODE is NOP_EXPR meaning do a simple assignment.
7299
7300    C++: If MODIFYCODE is INIT_EXPR, then leave references unbashed.  */
7301
7302 tree
7303 cp_build_modify_expr (tree lhs, enum tree_code modifycode, tree rhs,
7304                       tsubst_flags_t complain)
7305 {
7306   tree result;
7307   tree newrhs = rhs;
7308   tree lhstype = TREE_TYPE (lhs);
7309   tree olhstype = lhstype;
7310   bool plain_assign = (modifycode == NOP_EXPR);
7311
7312   /* Avoid duplicate error messages from operands that had errors.  */
7313   if (error_operand_p (lhs) || error_operand_p (rhs))
7314     return error_mark_node;
7315
7316   /* Handle control structure constructs used as "lvalues".  */
7317   switch (TREE_CODE (lhs))
7318     {
7319       /* Handle --foo = 5; as these are valid constructs in C++.  */
7320     case PREDECREMENT_EXPR:
7321     case PREINCREMENT_EXPR:
7322       if (TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0)))
7323         lhs = build2 (TREE_CODE (lhs), TREE_TYPE (lhs),
7324                       stabilize_reference (TREE_OPERAND (lhs, 0)),
7325                       TREE_OPERAND (lhs, 1));
7326       newrhs = cp_build_modify_expr (TREE_OPERAND (lhs, 0),
7327                                      modifycode, rhs, complain);
7328       if (newrhs == error_mark_node)
7329         return error_mark_node;
7330       return build2 (COMPOUND_EXPR, lhstype, lhs, newrhs);
7331
7332       /* Handle (a, b) used as an "lvalue".  */
7333     case COMPOUND_EXPR:
7334       newrhs = cp_build_modify_expr (TREE_OPERAND (lhs, 1),
7335                                      modifycode, rhs, complain);
7336       if (newrhs == error_mark_node)
7337         return error_mark_node;
7338       return build2 (COMPOUND_EXPR, lhstype,
7339                      TREE_OPERAND (lhs, 0), newrhs);
7340
7341     case MODIFY_EXPR:
7342       if (TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0)))
7343         lhs = build2 (TREE_CODE (lhs), TREE_TYPE (lhs),
7344                       stabilize_reference (TREE_OPERAND (lhs, 0)),
7345                       TREE_OPERAND (lhs, 1));
7346       newrhs = cp_build_modify_expr (TREE_OPERAND (lhs, 0), modifycode, rhs,
7347                                      complain);
7348       if (newrhs == error_mark_node)
7349         return error_mark_node;
7350       return build2 (COMPOUND_EXPR, lhstype, lhs, newrhs);
7351
7352     case MIN_EXPR:
7353     case MAX_EXPR:
7354       /* MIN_EXPR and MAX_EXPR are currently only permitted as lvalues,
7355          when neither operand has side-effects.  */
7356       if (!lvalue_or_else (lhs, lv_assign, complain))
7357         return error_mark_node;
7358
7359       gcc_assert (!TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0))
7360                   && !TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 1)));
7361
7362       lhs = build3 (COND_EXPR, TREE_TYPE (lhs),
7363                     build2 (TREE_CODE (lhs) == MIN_EXPR ? LE_EXPR : GE_EXPR,
7364                             boolean_type_node,
7365                             TREE_OPERAND (lhs, 0),
7366                             TREE_OPERAND (lhs, 1)),
7367                     TREE_OPERAND (lhs, 0),
7368                     TREE_OPERAND (lhs, 1));
7369       /* Fall through.  */
7370
7371       /* Handle (a ? b : c) used as an "lvalue".  */
7372     case COND_EXPR:
7373       {
7374         /* Produce (a ? (b = rhs) : (c = rhs))
7375            except that the RHS goes through a save-expr
7376            so the code to compute it is only emitted once.  */
7377         tree cond;
7378         tree preeval = NULL_TREE;
7379
7380         if (VOID_TYPE_P (TREE_TYPE (rhs)))
7381           {
7382             if (complain & tf_error)
7383               error ("void value not ignored as it ought to be");
7384             return error_mark_node;
7385           }
7386
7387         rhs = stabilize_expr (rhs, &preeval);
7388
7389         /* Check this here to avoid odd errors when trying to convert
7390            a throw to the type of the COND_EXPR.  */
7391         if (!lvalue_or_else (lhs, lv_assign, complain))
7392           return error_mark_node;
7393
7394         cond = build_conditional_expr
7395           (input_location, TREE_OPERAND (lhs, 0),
7396            cp_build_modify_expr (TREE_OPERAND (lhs, 1),
7397                                  modifycode, rhs, complain),
7398            cp_build_modify_expr (TREE_OPERAND (lhs, 2),
7399                                  modifycode, rhs, complain),
7400            complain);
7401
7402         if (cond == error_mark_node)
7403           return cond;
7404         /* Make sure the code to compute the rhs comes out
7405            before the split.  */
7406         if (preeval)
7407           cond = build2 (COMPOUND_EXPR, TREE_TYPE (lhs), preeval, cond);
7408         return cond;
7409       }
7410
7411     default:
7412       break;
7413     }
7414
7415   if (modifycode == INIT_EXPR)
7416     {
7417       if (BRACE_ENCLOSED_INITIALIZER_P (rhs))
7418         /* Do the default thing.  */;
7419       else if (TREE_CODE (rhs) == CONSTRUCTOR)
7420         {
7421           /* Compound literal.  */
7422           if (! same_type_p (TREE_TYPE (rhs), lhstype))
7423             /* Call convert to generate an error; see PR 11063.  */
7424             rhs = convert (lhstype, rhs);
7425           result = build2 (INIT_EXPR, lhstype, lhs, rhs);
7426           TREE_SIDE_EFFECTS (result) = 1;
7427           return result;
7428         }
7429       else if (! MAYBE_CLASS_TYPE_P (lhstype))
7430         /* Do the default thing.  */;
7431       else
7432         {
7433           vec<tree, va_gc> *rhs_vec = make_tree_vector_single (rhs);
7434           result = build_special_member_call (lhs, complete_ctor_identifier,
7435                                               &rhs_vec, lhstype, LOOKUP_NORMAL,
7436                                               complain);
7437           release_tree_vector (rhs_vec);
7438           if (result == NULL_TREE)
7439             return error_mark_node;
7440           return result;
7441         }
7442     }
7443   else
7444     {
7445       lhs = require_complete_type_sfinae (lhs, complain);
7446       if (lhs == error_mark_node)
7447         return error_mark_node;
7448
7449       if (modifycode == NOP_EXPR)
7450         {
7451           if (c_dialect_objc ())
7452             {
7453               result = objc_maybe_build_modify_expr (lhs, rhs);
7454               if (result)
7455                 return result;
7456             }
7457
7458           /* `operator=' is not an inheritable operator.  */
7459           if (! MAYBE_CLASS_TYPE_P (lhstype))
7460             /* Do the default thing.  */;
7461           else
7462             {
7463               result = build_new_op (input_location, MODIFY_EXPR,
7464                                      LOOKUP_NORMAL, lhs, rhs,
7465                                      make_node (NOP_EXPR), /*overload=*/NULL,
7466                                      complain);
7467               if (result == NULL_TREE)
7468                 return error_mark_node;
7469               return result;
7470             }
7471           lhstype = olhstype;
7472         }
7473       else
7474         {
7475           tree init = NULL_TREE;
7476
7477           /* A binary op has been requested.  Combine the old LHS
7478              value with the RHS producing the value we should actually
7479              store into the LHS.  */
7480           gcc_assert (!((TREE_CODE (lhstype) == REFERENCE_TYPE
7481                          && MAYBE_CLASS_TYPE_P (TREE_TYPE (lhstype)))
7482                         || MAYBE_CLASS_TYPE_P (lhstype)));
7483
7484           /* Preevaluate the RHS to make sure its evaluation is complete
7485              before the lvalue-to-rvalue conversion of the LHS:
7486
7487              [expr.ass] With respect to an indeterminately-sequenced
7488              function call, the operation of a compound assignment is a
7489              single evaluation. [ Note: Therefore, a function call shall
7490              not intervene between the lvalue-to-rvalue conversion and the
7491              side effect associated with any single compound assignment
7492              operator. -- end note ]  */
7493           lhs = stabilize_reference (lhs);
7494           rhs = rvalue (rhs);
7495           rhs = stabilize_expr (rhs, &init);
7496           newrhs = cp_build_binary_op (input_location,
7497                                        modifycode, lhs, rhs,
7498                                        complain);
7499           if (newrhs == error_mark_node)
7500             {
7501               if (complain & tf_error)
7502                 error ("  in evaluation of %<%Q(%#T, %#T)%>", modifycode,
7503                        TREE_TYPE (lhs), TREE_TYPE (rhs));
7504               return error_mark_node;
7505             }
7506
7507           if (init)
7508             newrhs = build2 (COMPOUND_EXPR, TREE_TYPE (newrhs), init, newrhs);
7509
7510           /* Now it looks like a plain assignment.  */
7511           modifycode = NOP_EXPR;
7512           if (c_dialect_objc ())
7513             {
7514               result = objc_maybe_build_modify_expr (lhs, newrhs);
7515               if (result)
7516                 return result;
7517             }
7518         }
7519       gcc_assert (TREE_CODE (lhstype) != REFERENCE_TYPE);
7520       gcc_assert (TREE_CODE (TREE_TYPE (newrhs)) != REFERENCE_TYPE);
7521     }
7522
7523   /* The left-hand side must be an lvalue.  */
7524   if (!lvalue_or_else (lhs, lv_assign, complain))
7525     return error_mark_node;
7526
7527   /* Warn about modifying something that is `const'.  Don't warn if
7528      this is initialization.  */
7529   if (modifycode != INIT_EXPR
7530       && (TREE_READONLY (lhs) || CP_TYPE_CONST_P (lhstype)
7531           /* Functions are not modifiable, even though they are
7532              lvalues.  */
7533           || TREE_CODE (TREE_TYPE (lhs)) == FUNCTION_TYPE
7534           || TREE_CODE (TREE_TYPE (lhs)) == METHOD_TYPE
7535           /* If it's an aggregate and any field is const, then it is
7536              effectively const.  */
7537           || (CLASS_TYPE_P (lhstype)
7538               && C_TYPE_FIELDS_READONLY (lhstype))))
7539     {
7540       if (complain & tf_error)
7541         cxx_readonly_error (lhs, lv_assign);
7542       else
7543         return error_mark_node;
7544     }
7545
7546   /* If storing into a structure or union member, it may have been given a
7547      lowered bitfield type.  We need to convert to the declared type first,
7548      so retrieve it now.  */
7549
7550   olhstype = unlowered_expr_type (lhs);
7551
7552   /* Convert new value to destination type.  */
7553
7554   if (TREE_CODE (lhstype) == ARRAY_TYPE)
7555     {
7556       int from_array;
7557
7558       if (BRACE_ENCLOSED_INITIALIZER_P (newrhs))
7559         {
7560           if (modifycode != INIT_EXPR)
7561             {
7562               if (complain & tf_error)
7563                 error ("assigning to an array from an initializer list");
7564               return error_mark_node;
7565             }
7566           if (check_array_initializer (lhs, lhstype, newrhs))
7567             return error_mark_node;
7568           newrhs = digest_init (lhstype, newrhs, complain);
7569           if (newrhs == error_mark_node)
7570             return error_mark_node;
7571         }
7572
7573       /* C++11 8.5/17: "If the destination type is an array of characters,
7574          an array of char16_t, an array of char32_t, or an array of wchar_t,
7575          and the initializer is a string literal...".  */
7576       else if (TREE_CODE (newrhs) == STRING_CST
7577                && char_type_p (TREE_TYPE (TYPE_MAIN_VARIANT (lhstype)))
7578                && modifycode == INIT_EXPR)
7579         {
7580           newrhs = digest_init (lhstype, newrhs, complain);
7581           if (newrhs == error_mark_node)
7582             return error_mark_node;
7583         }
7584
7585       else if (!same_or_base_type_p (TYPE_MAIN_VARIANT (lhstype),
7586                                      TYPE_MAIN_VARIANT (TREE_TYPE (newrhs))))
7587         {
7588           if (complain & tf_error)
7589             error ("incompatible types in assignment of %qT to %qT",
7590                    TREE_TYPE (rhs), lhstype);
7591           return error_mark_node;
7592         }
7593
7594       /* Allow array assignment in compiler-generated code.  */
7595       else if (!current_function_decl
7596                || !DECL_DEFAULTED_FN (current_function_decl))
7597         {
7598           /* This routine is used for both initialization and assignment.
7599              Make sure the diagnostic message differentiates the context.  */
7600           if (complain & tf_error)
7601             {
7602               if (modifycode == INIT_EXPR)
7603                 error ("array used as initializer");
7604               else
7605                 error ("invalid array assignment");
7606             }
7607           return error_mark_node;
7608         }
7609
7610       from_array = TREE_CODE (TREE_TYPE (newrhs)) == ARRAY_TYPE
7611                    ? 1 + (modifycode != INIT_EXPR): 0;
7612       return build_vec_init (lhs, NULL_TREE, newrhs,
7613                              /*explicit_value_init_p=*/false,
7614                              from_array, complain);
7615     }
7616
7617   if (modifycode == INIT_EXPR)
7618     /* Calls with INIT_EXPR are all direct-initialization, so don't set
7619        LOOKUP_ONLYCONVERTING.  */
7620     newrhs = convert_for_initialization (lhs, olhstype, newrhs, LOOKUP_NORMAL,
7621                                          ICR_INIT, NULL_TREE, 0,
7622                                          complain);
7623   else
7624     newrhs = convert_for_assignment (olhstype, newrhs, ICR_ASSIGN,
7625                                      NULL_TREE, 0, complain, LOOKUP_IMPLICIT);
7626
7627   if (!same_type_p (lhstype, olhstype))
7628     newrhs = cp_convert_and_check (lhstype, newrhs, complain);
7629
7630   if (modifycode != INIT_EXPR)
7631     {
7632       if (TREE_CODE (newrhs) == CALL_EXPR
7633           && TYPE_NEEDS_CONSTRUCTING (lhstype))
7634         newrhs = build_cplus_new (lhstype, newrhs, complain);
7635
7636       /* Can't initialize directly from a TARGET_EXPR, since that would
7637          cause the lhs to be constructed twice, and possibly result in
7638          accidental self-initialization.  So we force the TARGET_EXPR to be
7639          expanded without a target.  */
7640       if (TREE_CODE (newrhs) == TARGET_EXPR)
7641         newrhs = build2 (COMPOUND_EXPR, TREE_TYPE (newrhs), newrhs,
7642                          TREE_OPERAND (newrhs, 0));
7643     }
7644
7645   if (newrhs == error_mark_node)
7646     return error_mark_node;
7647
7648   if (c_dialect_objc () && flag_objc_gc)
7649     {
7650       result = objc_generate_write_barrier (lhs, modifycode, newrhs);
7651
7652       if (result)
7653         return result;
7654     }
7655
7656   result = build2 (modifycode == NOP_EXPR ? MODIFY_EXPR : INIT_EXPR,
7657                    lhstype, lhs, newrhs);
7658
7659   TREE_SIDE_EFFECTS (result) = 1;
7660   if (!plain_assign)
7661     TREE_NO_WARNING (result) = 1;
7662
7663   return result;
7664 }
7665
7666 tree
7667 build_x_modify_expr (location_t loc, tree lhs, enum tree_code modifycode,
7668                      tree rhs, tsubst_flags_t complain)
7669 {
7670   if (processing_template_decl)
7671     return build_min_nt_loc (loc, MODOP_EXPR, lhs,
7672                              build_min_nt_loc (loc, modifycode, NULL_TREE,
7673                                                NULL_TREE), rhs);
7674
7675   if (modifycode != NOP_EXPR)
7676     {
7677       tree rval = build_new_op (loc, MODIFY_EXPR, LOOKUP_NORMAL, lhs, rhs,
7678                                 make_node (modifycode), /*overload=*/NULL,
7679                                 complain);
7680       if (rval)
7681         {
7682           TREE_NO_WARNING (rval) = 1;
7683           return rval;
7684         }
7685     }
7686   return cp_build_modify_expr (lhs, modifycode, rhs, complain);
7687 }
7688
7689 /* Helper function for get_delta_difference which assumes FROM is a base
7690    class of TO.  Returns a delta for the conversion of pointer-to-member
7691    of FROM to pointer-to-member of TO.  If the conversion is invalid and 
7692    tf_error is not set in COMPLAIN returns error_mark_node, otherwise
7693    returns zero.  If FROM is not a base class of TO, returns NULL_TREE.
7694    If C_CAST_P is true, this conversion is taking place as part of a 
7695    C-style cast.  */
7696
7697 static tree
7698 get_delta_difference_1 (tree from, tree to, bool c_cast_p,
7699                         tsubst_flags_t complain)
7700 {
7701   tree binfo;
7702   base_kind kind;
7703
7704   binfo = lookup_base (to, from, c_cast_p ? ba_unique : ba_check,
7705                        &kind, complain);
7706
7707   if (binfo == error_mark_node)
7708     {
7709       if (!(complain & tf_error))
7710         return error_mark_node;
7711
7712       error ("   in pointer to member function conversion");
7713       return size_zero_node;
7714     }
7715   else if (binfo)
7716     {
7717       if (kind != bk_via_virtual)
7718         return BINFO_OFFSET (binfo);
7719       else
7720         /* FROM is a virtual base class of TO.  Issue an error or warning
7721            depending on whether or not this is a reinterpret cast.  */
7722         {
7723           if (!(complain & tf_error))
7724             return error_mark_node;
7725
7726           error ("pointer to member conversion via virtual base %qT",
7727                  BINFO_TYPE (binfo_from_vbase (binfo)));
7728
7729           return size_zero_node;
7730         }
7731       }
7732   else
7733     return NULL_TREE;
7734 }
7735
7736 /* Get difference in deltas for different pointer to member function
7737    types.  If the conversion is invalid and tf_error is not set in
7738    COMPLAIN, returns error_mark_node, otherwise returns an integer
7739    constant of type PTRDIFF_TYPE_NODE and its value is zero if the
7740    conversion is invalid.  If ALLOW_INVERSE_P is true, then allow reverse
7741    conversions as well.  If C_CAST_P is true this conversion is taking
7742    place as part of a C-style cast.
7743
7744    Note that the naming of FROM and TO is kind of backwards; the return
7745    value is what we add to a TO in order to get a FROM.  They are named
7746    this way because we call this function to find out how to convert from
7747    a pointer to member of FROM to a pointer to member of TO.  */
7748
7749 static tree
7750 get_delta_difference (tree from, tree to,
7751                       bool allow_inverse_p,
7752                       bool c_cast_p, tsubst_flags_t complain)
7753 {
7754   tree result;
7755
7756   if (same_type_ignoring_top_level_qualifiers_p (from, to))
7757     /* Pointer to member of incomplete class is permitted*/
7758     result = size_zero_node;
7759   else
7760     result = get_delta_difference_1 (from, to, c_cast_p, complain);
7761
7762   if (result == error_mark_node)
7763     return error_mark_node;
7764
7765   if (!result)
7766   {
7767     if (!allow_inverse_p)
7768       {
7769         if (!(complain & tf_error))
7770           return error_mark_node;
7771
7772         error_not_base_type (from, to);
7773         error ("   in pointer to member conversion");
7774         result = size_zero_node;
7775       }
7776     else
7777       {
7778         result = get_delta_difference_1 (to, from, c_cast_p, complain);
7779
7780         if (result == error_mark_node)
7781           return error_mark_node;
7782
7783         if (result)
7784           result = size_diffop_loc (input_location,
7785                                     size_zero_node, result);
7786         else
7787           {
7788             if (!(complain & tf_error))
7789               return error_mark_node;
7790
7791             error_not_base_type (from, to);
7792             error ("   in pointer to member conversion");
7793             result = size_zero_node;
7794           }
7795       }
7796   }
7797
7798   return fold_if_not_in_template (convert_to_integer (ptrdiff_type_node,
7799                                                       result));
7800 }
7801
7802 /* Return a constructor for the pointer-to-member-function TYPE using
7803    the other components as specified.  */
7804
7805 tree
7806 build_ptrmemfunc1 (tree type, tree delta, tree pfn)
7807 {
7808   tree u = NULL_TREE;
7809   tree delta_field;
7810   tree pfn_field;
7811   vec<constructor_elt, va_gc> *v;
7812
7813   /* Pull the FIELD_DECLs out of the type.  */
7814   pfn_field = TYPE_FIELDS (type);
7815   delta_field = DECL_CHAIN (pfn_field);
7816
7817   /* Make sure DELTA has the type we want.  */
7818   delta = convert_and_check (input_location, delta_type_node, delta);
7819
7820   /* Convert to the correct target type if necessary.  */
7821   pfn = fold_convert (TREE_TYPE (pfn_field), pfn);
7822
7823   /* Finish creating the initializer.  */
7824   vec_alloc (v, 2);
7825   CONSTRUCTOR_APPEND_ELT(v, pfn_field, pfn);
7826   CONSTRUCTOR_APPEND_ELT(v, delta_field, delta);
7827   u = build_constructor (type, v);
7828   TREE_CONSTANT (u) = TREE_CONSTANT (pfn) & TREE_CONSTANT (delta);
7829   TREE_STATIC (u) = (TREE_CONSTANT (u)
7830                      && (initializer_constant_valid_p (pfn, TREE_TYPE (pfn))
7831                          != NULL_TREE)
7832                      && (initializer_constant_valid_p (delta, TREE_TYPE (delta))
7833                          != NULL_TREE));
7834   return u;
7835 }
7836
7837 /* Build a constructor for a pointer to member function.  It can be
7838    used to initialize global variables, local variable, or used
7839    as a value in expressions.  TYPE is the POINTER to METHOD_TYPE we
7840    want to be.
7841
7842    If FORCE is nonzero, then force this conversion, even if
7843    we would rather not do it.  Usually set when using an explicit
7844    cast.  A C-style cast is being processed iff C_CAST_P is true.
7845
7846    Return error_mark_node, if something goes wrong.  */
7847
7848 tree
7849 build_ptrmemfunc (tree type, tree pfn, int force, bool c_cast_p,
7850                   tsubst_flags_t complain)
7851 {
7852   tree fn;
7853   tree pfn_type;
7854   tree to_type;
7855
7856   if (error_operand_p (pfn))
7857     return error_mark_node;
7858
7859   pfn_type = TREE_TYPE (pfn);
7860   to_type = build_ptrmemfunc_type (type);
7861
7862   /* Handle multiple conversions of pointer to member functions.  */
7863   if (TYPE_PTRMEMFUNC_P (pfn_type))
7864     {
7865       tree delta = NULL_TREE;
7866       tree npfn = NULL_TREE;
7867       tree n;
7868
7869       if (!force
7870           && !can_convert_arg (to_type, TREE_TYPE (pfn), pfn,
7871                                LOOKUP_NORMAL, complain))
7872         {
7873           if (complain & tf_error)
7874             error ("invalid conversion to type %qT from type %qT",
7875                    to_type, pfn_type);
7876           else
7877             return error_mark_node;
7878         }
7879
7880       n = get_delta_difference (TYPE_PTRMEMFUNC_OBJECT_TYPE (pfn_type),
7881                                 TYPE_PTRMEMFUNC_OBJECT_TYPE (to_type),
7882                                 force,
7883                                 c_cast_p, complain);
7884       if (n == error_mark_node)
7885         return error_mark_node;
7886
7887       /* We don't have to do any conversion to convert a
7888          pointer-to-member to its own type.  But, we don't want to
7889          just return a PTRMEM_CST if there's an explicit cast; that
7890          cast should make the expression an invalid template argument.  */
7891       if (TREE_CODE (pfn) != PTRMEM_CST)
7892         {
7893           if (same_type_p (to_type, pfn_type))
7894             return pfn;
7895           else if (integer_zerop (n))
7896             return build_reinterpret_cast (to_type, pfn, 
7897                                            complain);
7898         }
7899
7900       if (TREE_SIDE_EFFECTS (pfn))
7901         pfn = save_expr (pfn);
7902
7903       /* Obtain the function pointer and the current DELTA.  */
7904       if (TREE_CODE (pfn) == PTRMEM_CST)
7905         expand_ptrmemfunc_cst (pfn, &delta, &npfn);
7906       else
7907         {
7908           npfn = build_ptrmemfunc_access_expr (pfn, pfn_identifier);
7909           delta = build_ptrmemfunc_access_expr (pfn, delta_identifier);
7910         }
7911
7912       /* Just adjust the DELTA field.  */
7913       gcc_assert  (same_type_ignoring_top_level_qualifiers_p
7914                    (TREE_TYPE (delta), ptrdiff_type_node));
7915       if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_delta)
7916         n = cp_build_binary_op (input_location,
7917                                 LSHIFT_EXPR, n, integer_one_node,
7918                                 complain);
7919       delta = cp_build_binary_op (input_location,
7920                                   PLUS_EXPR, delta, n, complain);
7921       return build_ptrmemfunc1 (to_type, delta, npfn);
7922     }
7923
7924   /* Handle null pointer to member function conversions.  */
7925   if (null_ptr_cst_p (pfn))
7926     {
7927       pfn = cp_build_c_cast (type, pfn, complain);
7928       return build_ptrmemfunc1 (to_type,
7929                                 integer_zero_node,
7930                                 pfn);
7931     }
7932
7933   if (type_unknown_p (pfn))
7934     return instantiate_type (type, pfn, complain);
7935
7936   fn = TREE_OPERAND (pfn, 0);
7937   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
7938               /* In a template, we will have preserved the
7939                  OFFSET_REF.  */
7940               || (processing_template_decl && TREE_CODE (fn) == OFFSET_REF));
7941   return make_ptrmem_cst (to_type, fn);
7942 }
7943
7944 /* Return the DELTA, IDX, PFN, and DELTA2 values for the PTRMEM_CST
7945    given by CST.
7946
7947    ??? There is no consistency as to the types returned for the above
7948    values.  Some code acts as if it were a sizetype and some as if it were
7949    integer_type_node.  */
7950
7951 void
7952 expand_ptrmemfunc_cst (tree cst, tree *delta, tree *pfn)
7953 {
7954   tree type = TREE_TYPE (cst);
7955   tree fn = PTRMEM_CST_MEMBER (cst);
7956   tree ptr_class, fn_class;
7957
7958   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7959
7960   /* The class that the function belongs to.  */
7961   fn_class = DECL_CONTEXT (fn);
7962
7963   /* The class that we're creating a pointer to member of.  */
7964   ptr_class = TYPE_PTRMEMFUNC_OBJECT_TYPE (type);
7965
7966   /* First, calculate the adjustment to the function's class.  */
7967   *delta = get_delta_difference (fn_class, ptr_class, /*force=*/0,
7968                                  /*c_cast_p=*/0, tf_warning_or_error);
7969
7970   if (!DECL_VIRTUAL_P (fn))
7971     *pfn = convert (TYPE_PTRMEMFUNC_FN_TYPE (type),
7972                     build_addr_func (fn, tf_warning_or_error));
7973   else
7974     {
7975       /* If we're dealing with a virtual function, we have to adjust 'this'
7976          again, to point to the base which provides the vtable entry for
7977          fn; the call will do the opposite adjustment.  */
7978       tree orig_class = DECL_CONTEXT (fn);
7979       tree binfo = binfo_or_else (orig_class, fn_class);
7980       *delta = build2 (PLUS_EXPR, TREE_TYPE (*delta),
7981                        *delta, BINFO_OFFSET (binfo));
7982       *delta = fold_if_not_in_template (*delta);
7983
7984       /* We set PFN to the vtable offset at which the function can be
7985          found, plus one (unless ptrmemfunc_vbit_in_delta, in which
7986          case delta is shifted left, and then incremented).  */
7987       *pfn = DECL_VINDEX (fn);
7988       *pfn = build2 (MULT_EXPR, integer_type_node, *pfn,
7989                      TYPE_SIZE_UNIT (vtable_entry_type));
7990       *pfn = fold_if_not_in_template (*pfn);
7991
7992       switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
7993         {
7994         case ptrmemfunc_vbit_in_pfn:
7995           *pfn = build2 (PLUS_EXPR, integer_type_node, *pfn,
7996                          integer_one_node);
7997           *pfn = fold_if_not_in_template (*pfn);
7998           break;
7999
8000         case ptrmemfunc_vbit_in_delta:
8001           *delta = build2 (LSHIFT_EXPR, TREE_TYPE (*delta),
8002                            *delta, integer_one_node);
8003           *delta = fold_if_not_in_template (*delta);
8004           *delta = build2 (PLUS_EXPR, TREE_TYPE (*delta),
8005                            *delta, integer_one_node);
8006           *delta = fold_if_not_in_template (*delta);
8007           break;
8008
8009         default:
8010           gcc_unreachable ();
8011         }
8012
8013       *pfn = build_nop (TYPE_PTRMEMFUNC_FN_TYPE (type), *pfn);
8014       *pfn = fold_if_not_in_template (*pfn);
8015     }
8016 }
8017
8018 /* Return an expression for PFN from the pointer-to-member function
8019    given by T.  */
8020
8021 static tree
8022 pfn_from_ptrmemfunc (tree t)
8023 {
8024   if (TREE_CODE (t) == PTRMEM_CST)
8025     {
8026       tree delta;
8027       tree pfn;
8028
8029       expand_ptrmemfunc_cst (t, &delta, &pfn);
8030       if (pfn)
8031         return pfn;
8032     }
8033
8034   return build_ptrmemfunc_access_expr (t, pfn_identifier);
8035 }
8036
8037 /* Return an expression for DELTA from the pointer-to-member function
8038    given by T.  */
8039
8040 static tree
8041 delta_from_ptrmemfunc (tree t)
8042 {
8043   if (TREE_CODE (t) == PTRMEM_CST)
8044     {
8045       tree delta;
8046       tree pfn;
8047
8048       expand_ptrmemfunc_cst (t, &delta, &pfn);
8049       if (delta)
8050         return delta;
8051     }
8052
8053   return build_ptrmemfunc_access_expr (t, delta_identifier);
8054 }
8055
8056 /* Convert value RHS to type TYPE as preparation for an assignment to
8057    an lvalue of type TYPE.  ERRTYPE indicates what kind of error the
8058    implicit conversion is.  If FNDECL is non-NULL, we are doing the
8059    conversion in order to pass the PARMNUMth argument of FNDECL.
8060    If FNDECL is NULL, we are doing the conversion in function pointer
8061    argument passing, conversion in initialization, etc. */
8062
8063 static tree
8064 convert_for_assignment (tree type, tree rhs,
8065                         impl_conv_rhs errtype, tree fndecl, int parmnum,
8066                         tsubst_flags_t complain, int flags)
8067 {
8068   tree rhstype;
8069   enum tree_code coder;
8070
8071   /* Strip NON_LVALUE_EXPRs since we aren't using as an lvalue.  */
8072   if (TREE_CODE (rhs) == NON_LVALUE_EXPR)
8073     rhs = TREE_OPERAND (rhs, 0);
8074
8075   rhstype = TREE_TYPE (rhs);
8076   coder = TREE_CODE (rhstype);
8077
8078   if (TREE_CODE (type) == VECTOR_TYPE && coder == VECTOR_TYPE
8079       && vector_types_convertible_p (type, rhstype, true))
8080     {
8081       rhs = mark_rvalue_use (rhs);
8082       return convert (type, rhs);
8083     }
8084
8085   if (rhs == error_mark_node || rhstype == error_mark_node)
8086     return error_mark_node;
8087   if (TREE_CODE (rhs) == TREE_LIST && TREE_VALUE (rhs) == error_mark_node)
8088     return error_mark_node;
8089
8090   /* The RHS of an assignment cannot have void type.  */
8091   if (coder == VOID_TYPE)
8092     {
8093       if (complain & tf_error)
8094         error ("void value not ignored as it ought to be");
8095       return error_mark_node;
8096     }
8097
8098   if (c_dialect_objc ())
8099     {
8100       int parmno;
8101       tree selector;
8102       tree rname = fndecl;
8103
8104       switch (errtype)
8105         {
8106           case ICR_ASSIGN:
8107             parmno = -1;
8108             break;
8109           case ICR_INIT:
8110             parmno = -2;
8111             break;
8112           default:
8113             selector = objc_message_selector ();
8114             parmno = parmnum;
8115             if (selector && parmno > 1)
8116               {
8117                 rname = selector;
8118                 parmno -= 1;
8119               }
8120         }
8121
8122       if (objc_compare_types (type, rhstype, parmno, rname))
8123         {
8124           rhs = mark_rvalue_use (rhs);
8125           return convert (type, rhs);
8126         }
8127     }
8128
8129   /* [expr.ass]
8130
8131      The expression is implicitly converted (clause _conv_) to the
8132      cv-unqualified type of the left operand.
8133
8134      We allow bad conversions here because by the time we get to this point
8135      we are committed to doing the conversion.  If we end up doing a bad
8136      conversion, convert_like will complain.  */
8137   if (!can_convert_arg_bad (type, rhstype, rhs, flags, complain))
8138     {
8139       /* When -Wno-pmf-conversions is use, we just silently allow
8140          conversions from pointers-to-members to plain pointers.  If
8141          the conversion doesn't work, cp_convert will complain.  */
8142       if (!warn_pmf2ptr
8143           && TYPE_PTR_P (type)
8144           && TYPE_PTRMEMFUNC_P (rhstype))
8145         rhs = cp_convert (strip_top_quals (type), rhs, complain);
8146       else
8147         {
8148           if (complain & tf_error)
8149             {
8150               /* If the right-hand side has unknown type, then it is an
8151                  overloaded function.  Call instantiate_type to get error
8152                  messages.  */
8153               if (rhstype == unknown_type_node)
8154                 instantiate_type (type, rhs, tf_warning_or_error);
8155               else if (fndecl)
8156                 error ("cannot convert %qT to %qT for argument %qP to %qD",
8157                        rhstype, type, parmnum, fndecl);
8158               else
8159                 switch (errtype)
8160                   {
8161                     case ICR_DEFAULT_ARGUMENT:
8162                       error ("cannot convert %qT to %qT in default argument",
8163                              rhstype, type);
8164                       break;
8165                     case ICR_ARGPASS:
8166                       error ("cannot convert %qT to %qT in argument passing",
8167                              rhstype, type);
8168                       break;
8169                     case ICR_CONVERTING:
8170                       error ("cannot convert %qT to %qT",
8171                              rhstype, type);
8172                       break;
8173                     case ICR_INIT:
8174                       error ("cannot convert %qT to %qT in initialization",
8175                              rhstype, type);
8176                       break;
8177                     case ICR_RETURN:
8178                       error ("cannot convert %qT to %qT in return",
8179                              rhstype, type);
8180                       break;
8181                     case ICR_ASSIGN:
8182                       error ("cannot convert %qT to %qT in assignment",
8183                              rhstype, type);
8184                       break;
8185                     default:
8186                       gcc_unreachable();
8187                   }
8188               if (TYPE_PTR_P (rhstype)
8189                   && TYPE_PTR_P (type)
8190                   && CLASS_TYPE_P (TREE_TYPE (rhstype))
8191                   && CLASS_TYPE_P (TREE_TYPE (type))
8192                   && !COMPLETE_TYPE_P (TREE_TYPE (rhstype)))
8193                 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL
8194                                               (TREE_TYPE (rhstype))),
8195                         "class type %qT is incomplete", TREE_TYPE (rhstype));
8196             }
8197           return error_mark_node;
8198         }
8199     }
8200   if (warn_suggest_attribute_format)
8201     {
8202       const enum tree_code codel = TREE_CODE (type);
8203       if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
8204           && coder == codel
8205           && check_missing_format_attribute (type, rhstype)
8206           && (complain & tf_warning))
8207         switch (errtype)
8208           {
8209             case ICR_ARGPASS:
8210             case ICR_DEFAULT_ARGUMENT:
8211               if (fndecl)
8212                 warning (OPT_Wsuggest_attribute_format,
8213                          "parameter %qP of %qD might be a candidate "
8214                          "for a format attribute", parmnum, fndecl);
8215               else
8216                 warning (OPT_Wsuggest_attribute_format,
8217                          "parameter might be a candidate "
8218                          "for a format attribute");
8219               break;
8220             case ICR_CONVERTING:
8221               warning (OPT_Wsuggest_attribute_format,
8222                        "target of conversion might be a candidate "
8223                        "for a format attribute");
8224               break;
8225             case ICR_INIT:
8226               warning (OPT_Wsuggest_attribute_format,
8227                        "target of initialization might be a candidate "
8228                        "for a format attribute");
8229               break;
8230             case ICR_RETURN:
8231               warning (OPT_Wsuggest_attribute_format,
8232                        "return type might be a candidate "
8233                        "for a format attribute");
8234               break;
8235             case ICR_ASSIGN:
8236               warning (OPT_Wsuggest_attribute_format,
8237                        "left-hand side of assignment might be a candidate "
8238                        "for a format attribute");
8239               break;
8240             default:
8241               gcc_unreachable();
8242           }
8243     }
8244
8245   /* If -Wparentheses, warn about a = b = c when a has type bool and b
8246      does not.  */
8247   if (warn_parentheses
8248       && TREE_CODE (type) == BOOLEAN_TYPE
8249       && TREE_CODE (rhs) == MODIFY_EXPR
8250       && !TREE_NO_WARNING (rhs)
8251       && TREE_CODE (TREE_TYPE (rhs)) != BOOLEAN_TYPE
8252       && (complain & tf_warning))
8253     {
8254       location_t loc = EXPR_LOC_OR_LOC (rhs, input_location);
8255
8256       warning_at (loc, OPT_Wparentheses,
8257                   "suggest parentheses around assignment used as truth value");
8258       TREE_NO_WARNING (rhs) = 1;
8259     }
8260
8261   return perform_implicit_conversion_flags (strip_top_quals (type), rhs,
8262                                             complain, flags);
8263 }
8264
8265 /* Convert RHS to be of type TYPE.
8266    If EXP is nonzero, it is the target of the initialization.
8267    ERRTYPE indicates what kind of error the implicit conversion is.
8268
8269    Two major differences between the behavior of
8270    `convert_for_assignment' and `convert_for_initialization'
8271    are that references are bashed in the former, while
8272    copied in the latter, and aggregates are assigned in
8273    the former (operator=) while initialized in the
8274    latter (X(X&)).
8275
8276    If using constructor make sure no conversion operator exists, if one does
8277    exist, an ambiguity exists.  */
8278
8279 tree
8280 convert_for_initialization (tree exp, tree type, tree rhs, int flags,
8281                             impl_conv_rhs errtype, tree fndecl, int parmnum,
8282                             tsubst_flags_t complain)
8283 {
8284   enum tree_code codel = TREE_CODE (type);
8285   tree rhstype;
8286   enum tree_code coder;
8287
8288   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
8289      Strip such NOP_EXPRs, since RHS is used in non-lvalue context.  */
8290   if (TREE_CODE (rhs) == NOP_EXPR
8291       && TREE_TYPE (rhs) == TREE_TYPE (TREE_OPERAND (rhs, 0))
8292       && codel != REFERENCE_TYPE)
8293     rhs = TREE_OPERAND (rhs, 0);
8294
8295   if (type == error_mark_node
8296       || rhs == error_mark_node
8297       || (TREE_CODE (rhs) == TREE_LIST && TREE_VALUE (rhs) == error_mark_node))
8298     return error_mark_node;
8299
8300   if ((TREE_CODE (TREE_TYPE (rhs)) == ARRAY_TYPE
8301        && TREE_CODE (type) != ARRAY_TYPE
8302        && (TREE_CODE (type) != REFERENCE_TYPE
8303            || TREE_CODE (TREE_TYPE (type)) != ARRAY_TYPE))
8304       || (TREE_CODE (TREE_TYPE (rhs)) == FUNCTION_TYPE
8305           && !TYPE_REFFN_P (type))
8306       || TREE_CODE (TREE_TYPE (rhs)) == METHOD_TYPE)
8307     rhs = decay_conversion (rhs, complain);
8308
8309   rhstype = TREE_TYPE (rhs);
8310   coder = TREE_CODE (rhstype);
8311
8312   if (coder == ERROR_MARK)
8313     return error_mark_node;
8314
8315   /* We accept references to incomplete types, so we can
8316      return here before checking if RHS is of complete type.  */
8317
8318   if (codel == REFERENCE_TYPE)
8319     {
8320       /* This should eventually happen in convert_arguments.  */
8321       int savew = 0, savee = 0;
8322
8323       if (fndecl)
8324         savew = warningcount + werrorcount, savee = errorcount;
8325       rhs = initialize_reference (type, rhs, flags, complain);
8326
8327       if (fndecl
8328           && (warningcount + werrorcount > savew || errorcount > savee))
8329         inform (input_location,
8330                 "in passing argument %P of %q+D", parmnum, fndecl);
8331
8332       return rhs;
8333     }
8334
8335   if (exp != 0)
8336     exp = require_complete_type_sfinae (exp, complain);
8337   if (exp == error_mark_node)
8338     return error_mark_node;
8339
8340   rhstype = non_reference (rhstype);
8341
8342   type = complete_type (type);
8343
8344   if (DIRECT_INIT_EXPR_P (type, rhs))
8345     /* Don't try to do copy-initialization if we already have
8346        direct-initialization.  */
8347     return rhs;
8348
8349   if (MAYBE_CLASS_TYPE_P (type))
8350     return perform_implicit_conversion_flags (type, rhs, complain, flags);
8351
8352   return convert_for_assignment (type, rhs, errtype, fndecl, parmnum,
8353                                  complain, flags);
8354 }
8355 \f
8356 /* If RETVAL is the address of, or a reference to, a local variable or
8357    temporary give an appropriate warning and return true.  */
8358
8359 static bool
8360 maybe_warn_about_returning_address_of_local (tree retval)
8361 {
8362   tree valtype = TREE_TYPE (DECL_RESULT (current_function_decl));
8363   tree whats_returned = retval;
8364
8365   for (;;)
8366     {
8367       if (TREE_CODE (whats_returned) == COMPOUND_EXPR)
8368         whats_returned = TREE_OPERAND (whats_returned, 1);
8369       else if (CONVERT_EXPR_P (whats_returned)
8370                || TREE_CODE (whats_returned) == NON_LVALUE_EXPR)
8371         whats_returned = TREE_OPERAND (whats_returned, 0);
8372       else
8373         break;
8374     }
8375
8376   if (TREE_CODE (whats_returned) != ADDR_EXPR)
8377     return false;
8378   whats_returned = TREE_OPERAND (whats_returned, 0);
8379
8380   while (TREE_CODE (whats_returned) == COMPONENT_REF
8381          || TREE_CODE (whats_returned) == ARRAY_REF)
8382     whats_returned = TREE_OPERAND (whats_returned, 0);
8383
8384   if (TREE_CODE (valtype) == REFERENCE_TYPE)
8385     {
8386       if (TREE_CODE (whats_returned) == AGGR_INIT_EXPR
8387           || TREE_CODE (whats_returned) == TARGET_EXPR)
8388         {
8389           warning (OPT_Wreturn_local_addr, "returning reference to temporary");
8390           return true;
8391         }
8392       if (VAR_P (whats_returned)
8393           && DECL_NAME (whats_returned)
8394           && TEMP_NAME_P (DECL_NAME (whats_returned)))
8395         {
8396           warning (OPT_Wreturn_local_addr, "reference to non-lvalue returned");
8397           return true;
8398         }
8399     }
8400
8401   if (DECL_P (whats_returned)
8402       && DECL_NAME (whats_returned)
8403       && DECL_FUNCTION_SCOPE_P (whats_returned)
8404       && !is_capture_proxy (whats_returned)
8405       && !(TREE_STATIC (whats_returned)
8406            || TREE_PUBLIC (whats_returned)))
8407     {
8408       if (TREE_CODE (valtype) == REFERENCE_TYPE)
8409         warning (OPT_Wreturn_local_addr, "reference to local variable %q+D returned",
8410                  whats_returned);
8411       else if (TREE_CODE (whats_returned) == LABEL_DECL)
8412         warning (OPT_Wreturn_local_addr, "address of label %q+D returned",
8413                  whats_returned);
8414       else
8415         warning (OPT_Wreturn_local_addr, "address of local variable %q+D "
8416                  "returned", whats_returned);
8417       return true;
8418     }
8419
8420   return false;
8421 }
8422
8423 /* Check that returning RETVAL from the current function is valid.
8424    Return an expression explicitly showing all conversions required to
8425    change RETVAL into the function return type, and to assign it to
8426    the DECL_RESULT for the function.  Set *NO_WARNING to true if
8427    code reaches end of non-void function warning shouldn't be issued
8428    on this RETURN_EXPR.  */
8429
8430 tree
8431 check_return_expr (tree retval, bool *no_warning)
8432 {
8433   tree result;
8434   /* The type actually returned by the function.  */
8435   tree valtype;
8436   /* The type the function is declared to return, or void if
8437      the declared type is incomplete.  */
8438   tree functype;
8439   int fn_returns_value_p;
8440   bool named_return_value_okay_p;
8441
8442   *no_warning = false;
8443
8444   if (flag_cilkplus && retval && contains_cilk_spawn_stmt (retval))
8445     {
8446       error_at (EXPR_LOCATION (retval), "use of %<_Cilk_spawn%> in a return "
8447                 "statement is not allowed");
8448       return NULL_TREE;
8449     }
8450
8451   /* A `volatile' function is one that isn't supposed to return, ever.
8452      (This is a G++ extension, used to get better code for functions
8453      that call the `volatile' function.)  */
8454   if (TREE_THIS_VOLATILE (current_function_decl))
8455     warning (0, "function declared %<noreturn%> has a %<return%> statement");
8456
8457   /* Check for various simple errors.  */
8458   if (DECL_DESTRUCTOR_P (current_function_decl))
8459     {
8460       if (retval)
8461         error ("returning a value from a destructor");
8462       return NULL_TREE;
8463     }
8464   else if (DECL_CONSTRUCTOR_P (current_function_decl))
8465     {
8466       if (in_function_try_handler)
8467         /* If a return statement appears in a handler of the
8468            function-try-block of a constructor, the program is ill-formed.  */
8469         error ("cannot return from a handler of a function-try-block of a constructor");
8470       else if (retval)
8471         /* You can't return a value from a constructor.  */
8472         error ("returning a value from a constructor");
8473       return NULL_TREE;
8474     }
8475
8476   if (processing_template_decl)
8477     {
8478       current_function_returns_value = 1;
8479       if (check_for_bare_parameter_packs (retval))
8480         retval = error_mark_node;
8481       return retval;
8482     }
8483
8484   functype = TREE_TYPE (TREE_TYPE (current_function_decl));
8485
8486   /* Deduce auto return type from a return statement.  */
8487   if (current_function_auto_return_pattern)
8488     {
8489       tree auto_node;
8490       tree type;
8491
8492       if (!retval && !is_auto (current_function_auto_return_pattern))
8493         {
8494           /* Give a helpful error message.  */
8495           error ("return-statement with no value, in function returning %qT",
8496                  current_function_auto_return_pattern);
8497           inform (input_location, "only plain %<auto%> return type can be "
8498                   "deduced to %<void%>");
8499           type = error_mark_node;
8500         }
8501       else if (retval && BRACE_ENCLOSED_INITIALIZER_P (retval))
8502         {
8503           error ("returning initializer list");
8504           type = error_mark_node;
8505         }
8506       else
8507         {
8508           if (!retval)
8509             retval = void_node;
8510           auto_node = type_uses_auto (current_function_auto_return_pattern);
8511           type = do_auto_deduction (current_function_auto_return_pattern,
8512                                     retval, auto_node);
8513         }
8514
8515       if (type == error_mark_node)
8516         /* Leave it.  */;
8517       else if (functype == current_function_auto_return_pattern)
8518         apply_deduced_return_type (current_function_decl, type);
8519       else
8520         /* A mismatch should have been diagnosed in do_auto_deduction.  */
8521         gcc_assert (same_type_p (type, functype));
8522       functype = type;
8523     }
8524
8525   /* When no explicit return-value is given in a function with a named
8526      return value, the named return value is used.  */
8527   result = DECL_RESULT (current_function_decl);
8528   valtype = TREE_TYPE (result);
8529   gcc_assert (valtype != NULL_TREE);
8530   fn_returns_value_p = !VOID_TYPE_P (valtype);
8531   if (!retval && DECL_NAME (result) && fn_returns_value_p)
8532     retval = result;
8533
8534   /* Check for a return statement with no return value in a function
8535      that's supposed to return a value.  */
8536   if (!retval && fn_returns_value_p)
8537     {
8538       if (functype != error_mark_node)
8539         permerror (input_location, "return-statement with no value, in "
8540                    "function returning %qT", valtype);
8541       /* Remember that this function did return.  */
8542       current_function_returns_value = 1;
8543       /* And signal caller that TREE_NO_WARNING should be set on the
8544          RETURN_EXPR to avoid control reaches end of non-void function
8545          warnings in tree-cfg.c.  */
8546       *no_warning = true;
8547     }
8548   /* Check for a return statement with a value in a function that
8549      isn't supposed to return a value.  */
8550   else if (retval && !fn_returns_value_p)
8551     {
8552       if (VOID_TYPE_P (TREE_TYPE (retval)))
8553         /* You can return a `void' value from a function of `void'
8554            type.  In that case, we have to evaluate the expression for
8555            its side-effects.  */
8556           finish_expr_stmt (retval);
8557       else
8558         permerror (input_location, "return-statement with a value, in function "
8559                    "returning 'void'");
8560       current_function_returns_null = 1;
8561
8562       /* There's really no value to return, after all.  */
8563       return NULL_TREE;
8564     }
8565   else if (!retval)
8566     /* Remember that this function can sometimes return without a
8567        value.  */
8568     current_function_returns_null = 1;
8569   else
8570     /* Remember that this function did return a value.  */
8571     current_function_returns_value = 1;
8572
8573   /* Check for erroneous operands -- but after giving ourselves a
8574      chance to provide an error about returning a value from a void
8575      function.  */
8576   if (error_operand_p (retval))
8577     {
8578       current_function_return_value = error_mark_node;
8579       return error_mark_node;
8580     }
8581
8582   /* Only operator new(...) throw(), can return NULL [expr.new/13].  */
8583   if ((DECL_OVERLOADED_OPERATOR_P (current_function_decl) == NEW_EXPR
8584        || DECL_OVERLOADED_OPERATOR_P (current_function_decl) == VEC_NEW_EXPR)
8585       && !TYPE_NOTHROW_P (TREE_TYPE (current_function_decl))
8586       && ! flag_check_new
8587       && retval && null_ptr_cst_p (retval))
8588     warning (0, "%<operator new%> must not return NULL unless it is "
8589              "declared %<throw()%> (or -fcheck-new is in effect)");
8590
8591   /* Effective C++ rule 15.  See also start_function.  */
8592   if (warn_ecpp
8593       && DECL_NAME (current_function_decl) == ansi_assopname(NOP_EXPR))
8594     {
8595       bool warn = true;
8596
8597       /* The function return type must be a reference to the current
8598         class.  */
8599       if (TREE_CODE (valtype) == REFERENCE_TYPE
8600           && same_type_ignoring_top_level_qualifiers_p
8601               (TREE_TYPE (valtype), TREE_TYPE (current_class_ref)))
8602         {
8603           /* Returning '*this' is obviously OK.  */
8604           if (retval == current_class_ref)
8605             warn = false;
8606           /* If we are calling a function whose return type is the same of
8607              the current class reference, it is ok.  */
8608           else if (INDIRECT_REF_P (retval)
8609                    && TREE_CODE (TREE_OPERAND (retval, 0)) == CALL_EXPR)
8610             warn = false;
8611         }
8612
8613       if (warn)
8614         warning (OPT_Weffc__, "%<operator=%> should return a reference to %<*this%>");
8615     }
8616
8617   /* The fabled Named Return Value optimization, as per [class.copy]/15:
8618
8619      [...]      For  a function with a class return type, if the expression
8620      in the return statement is the name of a local  object,  and  the  cv-
8621      unqualified  type  of  the  local  object  is the same as the function
8622      return type, an implementation is permitted to omit creating the  tem-
8623      porary  object  to  hold  the function return value [...]
8624
8625      So, if this is a value-returning function that always returns the same
8626      local variable, remember it.
8627
8628      It might be nice to be more flexible, and choose the first suitable
8629      variable even if the function sometimes returns something else, but
8630      then we run the risk of clobbering the variable we chose if the other
8631      returned expression uses the chosen variable somehow.  And people expect
8632      this restriction, anyway.  (jason 2000-11-19)
8633
8634      See finish_function and finalize_nrv for the rest of this optimization.  */
8635
8636   named_return_value_okay_p = 
8637     (retval != NULL_TREE
8638      /* Must be a local, automatic variable.  */
8639      && VAR_P (retval)
8640      && DECL_CONTEXT (retval) == current_function_decl
8641      && ! TREE_STATIC (retval)
8642      /* And not a lambda or anonymous union proxy.  */
8643      && !DECL_HAS_VALUE_EXPR_P (retval)
8644      && (DECL_ALIGN (retval) <= DECL_ALIGN (result))
8645      /* The cv-unqualified type of the returned value must be the
8646         same as the cv-unqualified return type of the
8647         function.  */
8648      && same_type_p ((TYPE_MAIN_VARIANT (TREE_TYPE (retval))),
8649                      (TYPE_MAIN_VARIANT (functype)))
8650      /* And the returned value must be non-volatile.  */
8651      && ! TYPE_VOLATILE (TREE_TYPE (retval)));
8652      
8653   if (fn_returns_value_p && flag_elide_constructors)
8654     {
8655       if (named_return_value_okay_p
8656           && (current_function_return_value == NULL_TREE
8657               || current_function_return_value == retval))
8658         current_function_return_value = retval;
8659       else
8660         current_function_return_value = error_mark_node;
8661     }
8662
8663   /* We don't need to do any conversions when there's nothing being
8664      returned.  */
8665   if (!retval)
8666     return NULL_TREE;
8667
8668   /* Do any required conversions.  */
8669   if (retval == result || DECL_CONSTRUCTOR_P (current_function_decl))
8670     /* No conversions are required.  */
8671     ;
8672   else
8673     {
8674       int flags = LOOKUP_NORMAL | LOOKUP_ONLYCONVERTING;
8675
8676       /* The functype's return type will have been set to void, if it
8677          was an incomplete type.  Just treat this as 'return;' */
8678       if (VOID_TYPE_P (functype))
8679         return error_mark_node;
8680
8681       /* If we had an id-expression obfuscated by force_paren_expr, we need
8682          to undo it so we can try to treat it as an rvalue below.  */
8683       if (cxx_dialect >= cxx14
8684           && INDIRECT_REF_P (retval)
8685           && REF_PARENTHESIZED_P (retval))
8686         {
8687           retval = TREE_OPERAND (retval, 0);
8688           while (TREE_CODE (retval) == NON_LVALUE_EXPR
8689                  || TREE_CODE (retval) == NOP_EXPR)
8690             retval = TREE_OPERAND (retval, 0);
8691           gcc_assert (TREE_CODE (retval) == ADDR_EXPR);
8692           retval = TREE_OPERAND (retval, 0);
8693         }
8694
8695       /* Under C++11 [12.8/32 class.copy], a returned lvalue is sometimes
8696          treated as an rvalue for the purposes of overload resolution to
8697          favor move constructors over copy constructors.
8698
8699          Note that these conditions are similar to, but not as strict as,
8700          the conditions for the named return value optimization.  */
8701       if ((cxx_dialect != cxx98)
8702           && ((VAR_P (retval) && !DECL_HAS_VALUE_EXPR_P (retval))
8703               || TREE_CODE (retval) == PARM_DECL)
8704           && DECL_CONTEXT (retval) == current_function_decl
8705           && !TREE_STATIC (retval)
8706           /* This is only interesting for class type.  */
8707           && CLASS_TYPE_P (functype))
8708         flags = flags | LOOKUP_PREFER_RVALUE;
8709
8710       /* First convert the value to the function's return type, then
8711          to the type of return value's location to handle the
8712          case that functype is smaller than the valtype.  */
8713       retval = convert_for_initialization
8714         (NULL_TREE, functype, retval, flags, ICR_RETURN, NULL_TREE, 0,
8715          tf_warning_or_error);
8716       retval = convert (valtype, retval);
8717
8718       /* If the conversion failed, treat this just like `return;'.  */
8719       if (retval == error_mark_node)
8720         return retval;
8721       /* We can't initialize a register from a AGGR_INIT_EXPR.  */
8722       else if (! cfun->returns_struct
8723                && TREE_CODE (retval) == TARGET_EXPR
8724                && TREE_CODE (TREE_OPERAND (retval, 1)) == AGGR_INIT_EXPR)
8725         retval = build2 (COMPOUND_EXPR, TREE_TYPE (retval), retval,
8726                          TREE_OPERAND (retval, 0));
8727       else if (maybe_warn_about_returning_address_of_local (retval))
8728         retval = build2 (COMPOUND_EXPR, TREE_TYPE (retval), retval,
8729                          build_zero_cst (TREE_TYPE (retval)));
8730     }
8731
8732   /* Actually copy the value returned into the appropriate location.  */
8733   if (retval && retval != result)
8734     retval = build2 (INIT_EXPR, TREE_TYPE (result), result, retval);
8735
8736   return retval;
8737 }
8738
8739 \f
8740 /* Returns nonzero if the pointer-type FROM can be converted to the
8741    pointer-type TO via a qualification conversion.  If CONSTP is -1,
8742    then we return nonzero if the pointers are similar, and the
8743    cv-qualification signature of FROM is a proper subset of that of TO.
8744
8745    If CONSTP is positive, then all outer pointers have been
8746    const-qualified.  */
8747
8748 static int
8749 comp_ptr_ttypes_real (tree to, tree from, int constp)
8750 {
8751   bool to_more_cv_qualified = false;
8752   bool is_opaque_pointer = false;
8753
8754   for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
8755     {
8756       if (TREE_CODE (to) != TREE_CODE (from))
8757         return 0;
8758
8759       if (TREE_CODE (from) == OFFSET_TYPE
8760           && !same_type_p (TYPE_OFFSET_BASETYPE (from),
8761                            TYPE_OFFSET_BASETYPE (to)))
8762         return 0;
8763
8764       /* Const and volatile mean something different for function types,
8765          so the usual checks are not appropriate.  */
8766       if (TREE_CODE (to) != FUNCTION_TYPE && TREE_CODE (to) != METHOD_TYPE)
8767         {
8768           if (!at_least_as_qualified_p (to, from))
8769             return 0;
8770
8771           if (!at_least_as_qualified_p (from, to))
8772             {
8773               if (constp == 0)
8774                 return 0;
8775               to_more_cv_qualified = true;
8776             }
8777
8778           if (constp > 0)
8779             constp &= TYPE_READONLY (to);
8780         }
8781
8782       if (TREE_CODE (to) == VECTOR_TYPE)
8783         is_opaque_pointer = vector_targets_convertible_p (to, from);
8784
8785       if (!TYPE_PTR_P (to) && !TYPE_PTRDATAMEM_P (to))
8786         return ((constp >= 0 || to_more_cv_qualified)
8787                 && (is_opaque_pointer
8788                     || same_type_ignoring_top_level_qualifiers_p (to, from)));
8789     }
8790 }
8791
8792 /* When comparing, say, char ** to char const **, this function takes
8793    the 'char *' and 'char const *'.  Do not pass non-pointer/reference
8794    types to this function.  */
8795
8796 int
8797 comp_ptr_ttypes (tree to, tree from)
8798 {
8799   return comp_ptr_ttypes_real (to, from, 1);
8800 }
8801
8802 /* Returns true iff FNTYPE is a non-class type that involves
8803    error_mark_node.  We can get FUNCTION_TYPE with buried error_mark_node
8804    if a parameter type is ill-formed.  */
8805
8806 bool
8807 error_type_p (const_tree type)
8808 {
8809   tree t;
8810
8811   switch (TREE_CODE (type))
8812     {
8813     case ERROR_MARK:
8814       return true;
8815
8816     case POINTER_TYPE:
8817     case REFERENCE_TYPE:
8818     case OFFSET_TYPE:
8819       return error_type_p (TREE_TYPE (type));
8820
8821     case FUNCTION_TYPE:
8822     case METHOD_TYPE:
8823       if (error_type_p (TREE_TYPE (type)))
8824         return true;
8825       for (t = TYPE_ARG_TYPES (type); t; t = TREE_CHAIN (t))
8826         if (error_type_p (TREE_VALUE (t)))
8827           return true;
8828       return false;
8829
8830     case RECORD_TYPE:
8831       if (TYPE_PTRMEMFUNC_P (type))
8832         return error_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type));
8833       return false;
8834
8835     default:
8836       return false;
8837     }
8838 }
8839
8840 /* Returns true if to and from are (possibly multi-level) pointers to the same
8841    type or inheritance-related types, regardless of cv-quals.  */
8842
8843 bool
8844 ptr_reasonably_similar (const_tree to, const_tree from)
8845 {
8846   for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
8847     {
8848       /* Any target type is similar enough to void.  */
8849       if (VOID_TYPE_P (to))
8850         return !error_type_p (from);
8851       if (VOID_TYPE_P (from))
8852         return !error_type_p (to);
8853
8854       if (TREE_CODE (to) != TREE_CODE (from))
8855         return false;
8856
8857       if (TREE_CODE (from) == OFFSET_TYPE
8858           && comptypes (TYPE_OFFSET_BASETYPE (to),
8859                         TYPE_OFFSET_BASETYPE (from),
8860                         COMPARE_BASE | COMPARE_DERIVED))
8861         continue;
8862
8863       if (TREE_CODE (to) == VECTOR_TYPE
8864           && vector_types_convertible_p (to, from, false))
8865         return true;
8866
8867       if (TREE_CODE (to) == INTEGER_TYPE
8868           && TYPE_PRECISION (to) == TYPE_PRECISION (from))
8869         return true;
8870
8871       if (TREE_CODE (to) == FUNCTION_TYPE)
8872         return !error_type_p (to) && !error_type_p (from);
8873
8874       if (!TYPE_PTR_P (to))
8875         {
8876           /* When either type is incomplete avoid DERIVED_FROM_P,
8877              which may call complete_type (c++/57942).  */
8878           bool b = !COMPLETE_TYPE_P (to) || !COMPLETE_TYPE_P (from);
8879           return comptypes
8880             (TYPE_MAIN_VARIANT (to), TYPE_MAIN_VARIANT (from),
8881              b ? COMPARE_STRICT : COMPARE_BASE | COMPARE_DERIVED);
8882         }
8883     }
8884 }
8885
8886 /* Return true if TO and FROM (both of which are POINTER_TYPEs or
8887    pointer-to-member types) are the same, ignoring cv-qualification at
8888    all levels.  */
8889
8890 bool
8891 comp_ptr_ttypes_const (tree to, tree from)
8892 {
8893   bool is_opaque_pointer = false;
8894
8895   for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
8896     {
8897       if (TREE_CODE (to) != TREE_CODE (from))
8898         return false;
8899
8900       if (TREE_CODE (from) == OFFSET_TYPE
8901           && same_type_p (TYPE_OFFSET_BASETYPE (from),
8902                           TYPE_OFFSET_BASETYPE (to)))
8903           continue;
8904
8905       if (TREE_CODE (to) == VECTOR_TYPE)
8906         is_opaque_pointer = vector_targets_convertible_p (to, from);
8907
8908       if (!TYPE_PTR_P (to))
8909         return (is_opaque_pointer
8910                 || same_type_ignoring_top_level_qualifiers_p (to, from));
8911     }
8912 }
8913
8914 /* Returns the type qualifiers for this type, including the qualifiers on the
8915    elements for an array type.  */
8916
8917 int
8918 cp_type_quals (const_tree type)
8919 {
8920   int quals;
8921   /* This CONST_CAST is okay because strip_array_types returns its
8922      argument unmodified and we assign it to a const_tree.  */
8923   type = strip_array_types (CONST_CAST_TREE (type));
8924   if (type == error_mark_node
8925       /* Quals on a FUNCTION_TYPE are memfn quals.  */
8926       || TREE_CODE (type) == FUNCTION_TYPE)
8927     return TYPE_UNQUALIFIED;
8928   quals = TYPE_QUALS (type);
8929   /* METHOD and REFERENCE_TYPEs should never have quals.  */
8930   gcc_assert ((TREE_CODE (type) != METHOD_TYPE
8931                && TREE_CODE (type) != REFERENCE_TYPE)
8932               || ((quals & (TYPE_QUAL_CONST|TYPE_QUAL_VOLATILE))
8933                   == TYPE_UNQUALIFIED));
8934   return quals;
8935 }
8936
8937 /* Returns the function-ref-qualifier for TYPE */
8938
8939 cp_ref_qualifier
8940 type_memfn_rqual (const_tree type)
8941 {
8942   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE
8943               || TREE_CODE (type) == METHOD_TYPE);
8944
8945   if (!FUNCTION_REF_QUALIFIED (type))
8946     return REF_QUAL_NONE;
8947   else if (FUNCTION_RVALUE_QUALIFIED (type))
8948     return REF_QUAL_RVALUE;
8949   else
8950     return REF_QUAL_LVALUE;
8951 }
8952
8953 /* Returns the function-cv-quals for TYPE, which must be a FUNCTION_TYPE or
8954    METHOD_TYPE.  */
8955
8956 int
8957 type_memfn_quals (const_tree type)
8958 {
8959   if (TREE_CODE (type) == FUNCTION_TYPE)
8960     return TYPE_QUALS (type);
8961   else if (TREE_CODE (type) == METHOD_TYPE)
8962     return cp_type_quals (class_of_this_parm (type));
8963   else
8964     gcc_unreachable ();
8965 }
8966
8967 /* Returns the FUNCTION_TYPE TYPE with its function-cv-quals changed to
8968    MEMFN_QUALS and its ref-qualifier to RQUAL. */
8969
8970 tree
8971 apply_memfn_quals (tree type, cp_cv_quals memfn_quals, cp_ref_qualifier rqual)
8972 {
8973   /* Could handle METHOD_TYPE here if necessary.  */
8974   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
8975   if (TYPE_QUALS (type) == memfn_quals
8976       && type_memfn_rqual (type) == rqual)
8977     return type;
8978
8979   /* This should really have a different TYPE_MAIN_VARIANT, but that gets
8980      complex.  */
8981   tree result = build_qualified_type (type, memfn_quals);
8982   if (tree canon = TYPE_CANONICAL (result))
8983     if (canon != result)
8984       /* check_qualified_type doesn't check the ref-qualifier, so make sure
8985          TYPE_CANONICAL is correct.  */
8986       TYPE_CANONICAL (result)
8987         = build_ref_qualified_type (canon, type_memfn_rqual (result));
8988   result = build_exception_variant (result, TYPE_RAISES_EXCEPTIONS (type));
8989   return build_ref_qualified_type (result, rqual);
8990 }
8991
8992 /* Returns nonzero if TYPE is const or volatile.  */
8993
8994 bool
8995 cv_qualified_p (const_tree type)
8996 {
8997   int quals = cp_type_quals (type);
8998   return (quals & (TYPE_QUAL_CONST|TYPE_QUAL_VOLATILE)) != 0;
8999 }
9000
9001 /* Returns nonzero if the TYPE contains a mutable member.  */
9002
9003 bool
9004 cp_has_mutable_p (const_tree type)
9005 {
9006   /* This CONST_CAST is okay because strip_array_types returns its
9007      argument unmodified and we assign it to a const_tree.  */
9008   type = strip_array_types (CONST_CAST_TREE(type));
9009
9010   return CLASS_TYPE_P (type) && CLASSTYPE_HAS_MUTABLE (type);
9011 }
9012
9013 /* Set TREE_READONLY and TREE_VOLATILE on DECL as indicated by the
9014    TYPE_QUALS.  For a VAR_DECL, this may be an optimistic
9015    approximation.  In particular, consider:
9016
9017      int f();
9018      struct S { int i; };
9019      const S s = { f(); }
9020
9021    Here, we will make "s" as TREE_READONLY (because it is declared
9022    "const") -- only to reverse ourselves upon seeing that the
9023    initializer is non-constant.  */
9024
9025 void
9026 cp_apply_type_quals_to_decl (int type_quals, tree decl)
9027 {
9028   tree type = TREE_TYPE (decl);
9029
9030   if (type == error_mark_node)
9031     return;
9032
9033   if (TREE_CODE (decl) == TYPE_DECL)
9034     return;
9035
9036   gcc_assert (!(TREE_CODE (type) == FUNCTION_TYPE
9037                 && type_quals != TYPE_UNQUALIFIED));
9038
9039   /* Avoid setting TREE_READONLY incorrectly.  */
9040   /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
9041      constructor can produce constant init, so rely on cp_finish_decl to
9042      clear TREE_READONLY if the variable has non-constant init.  */
9043
9044   /* If the type has (or might have) a mutable component, that component
9045      might be modified.  */
9046   if (TYPE_HAS_MUTABLE_P (type) || !COMPLETE_TYPE_P (type))
9047     type_quals &= ~TYPE_QUAL_CONST;
9048
9049   c_apply_type_quals_to_decl (type_quals, decl);
9050 }
9051
9052 /* Subroutine of casts_away_constness.  Make T1 and T2 point at
9053    exemplar types such that casting T1 to T2 is casting away constness
9054    if and only if there is no implicit conversion from T1 to T2.  */
9055
9056 static void
9057 casts_away_constness_r (tree *t1, tree *t2, tsubst_flags_t complain)
9058 {
9059   int quals1;
9060   int quals2;
9061
9062   /* [expr.const.cast]
9063
9064      For multi-level pointer to members and multi-level mixed pointers
9065      and pointers to members (conv.qual), the "member" aspect of a
9066      pointer to member level is ignored when determining if a const
9067      cv-qualifier has been cast away.  */
9068   /* [expr.const.cast]
9069
9070      For  two  pointer types:
9071
9072             X1 is T1cv1,1 * ... cv1,N *   where T1 is not a pointer type
9073             X2 is T2cv2,1 * ... cv2,M *   where T2 is not a pointer type
9074             K is min(N,M)
9075
9076      casting from X1 to X2 casts away constness if, for a non-pointer
9077      type T there does not exist an implicit conversion (clause
9078      _conv_) from:
9079
9080             Tcv1,(N-K+1) * cv1,(N-K+2) * ... cv1,N *
9081
9082      to
9083
9084             Tcv2,(M-K+1) * cv2,(M-K+2) * ... cv2,M *.  */
9085   if ((!TYPE_PTR_P (*t1) && !TYPE_PTRDATAMEM_P (*t1))
9086       || (!TYPE_PTR_P (*t2) && !TYPE_PTRDATAMEM_P (*t2)))
9087     {
9088       *t1 = cp_build_qualified_type (void_type_node,
9089                                      cp_type_quals (*t1));
9090       *t2 = cp_build_qualified_type (void_type_node,
9091                                      cp_type_quals (*t2));
9092       return;
9093     }
9094
9095   quals1 = cp_type_quals (*t1);
9096   quals2 = cp_type_quals (*t2);
9097
9098   if (TYPE_PTRDATAMEM_P (*t1))
9099     *t1 = TYPE_PTRMEM_POINTED_TO_TYPE (*t1);
9100   else
9101     *t1 = TREE_TYPE (*t1);
9102   if (TYPE_PTRDATAMEM_P (*t2))
9103     *t2 = TYPE_PTRMEM_POINTED_TO_TYPE (*t2);
9104   else
9105     *t2 = TREE_TYPE (*t2);
9106
9107   casts_away_constness_r (t1, t2, complain);
9108   *t1 = build_pointer_type (*t1);
9109   *t2 = build_pointer_type (*t2);
9110   *t1 = cp_build_qualified_type (*t1, quals1);
9111   *t2 = cp_build_qualified_type (*t2, quals2);
9112 }
9113
9114 /* Returns nonzero if casting from TYPE1 to TYPE2 casts away
9115    constness.  
9116
9117    ??? This function returns non-zero if casting away qualifiers not
9118    just const.  We would like to return to the caller exactly which
9119    qualifiers are casted away to give more accurate diagnostics.
9120 */
9121
9122 static bool
9123 casts_away_constness (tree t1, tree t2, tsubst_flags_t complain)
9124 {
9125   if (TREE_CODE (t2) == REFERENCE_TYPE)
9126     {
9127       /* [expr.const.cast]
9128
9129          Casting from an lvalue of type T1 to an lvalue of type T2
9130          using a reference cast casts away constness if a cast from an
9131          rvalue of type "pointer to T1" to the type "pointer to T2"
9132          casts away constness.  */
9133       t1 = (TREE_CODE (t1) == REFERENCE_TYPE ? TREE_TYPE (t1) : t1);
9134       return casts_away_constness (build_pointer_type (t1),
9135                                    build_pointer_type (TREE_TYPE (t2)),
9136                                    complain);
9137     }
9138
9139   if (TYPE_PTRDATAMEM_P (t1) && TYPE_PTRDATAMEM_P (t2))
9140     /* [expr.const.cast]
9141
9142        Casting from an rvalue of type "pointer to data member of X
9143        of type T1" to the type "pointer to data member of Y of type
9144        T2" casts away constness if a cast from an rvalue of type
9145        "pointer to T1" to the type "pointer to T2" casts away
9146        constness.  */
9147     return casts_away_constness
9148       (build_pointer_type (TYPE_PTRMEM_POINTED_TO_TYPE (t1)),
9149        build_pointer_type (TYPE_PTRMEM_POINTED_TO_TYPE (t2)),
9150        complain);
9151
9152   /* Casting away constness is only something that makes sense for
9153      pointer or reference types.  */
9154   if (!TYPE_PTR_P (t1) || !TYPE_PTR_P (t2))
9155     return false;
9156
9157   /* Top-level qualifiers don't matter.  */
9158   t1 = TYPE_MAIN_VARIANT (t1);
9159   t2 = TYPE_MAIN_VARIANT (t2);
9160   casts_away_constness_r (&t1, &t2, complain);
9161   if (!can_convert (t2, t1, complain))
9162     return true;
9163
9164   return false;
9165 }
9166
9167 /* If T is a REFERENCE_TYPE return the type to which T refers.
9168    Otherwise, return T itself.  */
9169
9170 tree
9171 non_reference (tree t)
9172 {
9173   if (t && TREE_CODE (t) == REFERENCE_TYPE)
9174     t = TREE_TYPE (t);
9175   return t;
9176 }
9177
9178
9179 /* Return nonzero if REF is an lvalue valid for this language;
9180    otherwise, print an error message and return zero.  USE says
9181    how the lvalue is being used and so selects the error message.  */
9182
9183 int
9184 lvalue_or_else (tree ref, enum lvalue_use use, tsubst_flags_t complain)
9185 {
9186   cp_lvalue_kind kind = lvalue_kind (ref);
9187
9188   if (kind == clk_none)
9189     {
9190       if (complain & tf_error)
9191         lvalue_error (input_location, use);
9192       return 0;
9193     }
9194   else if (kind & (clk_rvalueref|clk_class))
9195     {
9196       if (!(complain & tf_error))
9197         return 0;
9198       if (kind & clk_class)
9199         /* Make this a permerror because we used to accept it.  */
9200         permerror (input_location, "using temporary as lvalue");
9201       else
9202         error ("using xvalue (rvalue reference) as lvalue");
9203     }
9204   return 1;
9205 }
9206
9207 /* Return true if a user-defined literal operator is a raw operator.  */
9208
9209 bool
9210 check_raw_literal_operator (const_tree decl)
9211 {
9212   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
9213   tree argtype;
9214   int arity;
9215   bool maybe_raw_p = false;
9216
9217   /* Count the number and type of arguments and check for ellipsis.  */
9218   for (argtype = argtypes, arity = 0;
9219        argtype && argtype != void_list_node;
9220        ++arity, argtype = TREE_CHAIN (argtype))
9221     {
9222       tree t = TREE_VALUE (argtype);
9223
9224       if (same_type_p (t, const_string_type_node))
9225         maybe_raw_p = true;
9226     }
9227   if (!argtype)
9228     return false; /* Found ellipsis.  */
9229
9230   if (!maybe_raw_p || arity != 1)
9231     return false;
9232
9233   return true;
9234 }
9235
9236
9237 /* Return true if a user-defined literal operator has one of the allowed
9238    argument types.  */
9239
9240 bool
9241 check_literal_operator_args (const_tree decl,
9242                              bool *long_long_unsigned_p, bool *long_double_p)
9243 {
9244   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
9245
9246   *long_long_unsigned_p = false;
9247   *long_double_p = false;
9248   if (processing_template_decl || processing_specialization)
9249     return argtypes == void_list_node;
9250   else
9251     {
9252       tree argtype;
9253       int arity;
9254       int max_arity = 2;
9255
9256       /* Count the number and type of arguments and check for ellipsis.  */
9257       for (argtype = argtypes, arity = 0;
9258            argtype && argtype != void_list_node;
9259            argtype = TREE_CHAIN (argtype))
9260         {
9261           tree t = TREE_VALUE (argtype);
9262           ++arity;
9263
9264           if (TYPE_PTR_P (t))
9265             {
9266               bool maybe_raw_p = false;
9267               t = TREE_TYPE (t);
9268               if (cp_type_quals (t) != TYPE_QUAL_CONST)
9269                 return false;
9270               t = TYPE_MAIN_VARIANT (t);
9271               if ((maybe_raw_p = same_type_p (t, char_type_node))
9272                   || same_type_p (t, wchar_type_node)
9273                   || same_type_p (t, char16_type_node)
9274                   || same_type_p (t, char32_type_node))
9275                 {
9276                   argtype = TREE_CHAIN (argtype);
9277                   if (!argtype)
9278                     return false;
9279                   t = TREE_VALUE (argtype);
9280                   if (maybe_raw_p && argtype == void_list_node)
9281                     return true;
9282                   else if (same_type_p (t, size_type_node))
9283                     {
9284                       ++arity;
9285                       continue;
9286                     }
9287                   else
9288                     return false;
9289                 }
9290             }
9291           else if (same_type_p (t, long_long_unsigned_type_node))
9292             {
9293               max_arity = 1;
9294               *long_long_unsigned_p = true;
9295             }
9296           else if (same_type_p (t, long_double_type_node))
9297             {
9298               max_arity = 1;
9299               *long_double_p = true;
9300             }
9301           else if (same_type_p (t, char_type_node))
9302             max_arity = 1;
9303           else if (same_type_p (t, wchar_type_node))
9304             max_arity = 1;
9305           else if (same_type_p (t, char16_type_node))
9306             max_arity = 1;
9307           else if (same_type_p (t, char32_type_node))
9308             max_arity = 1;
9309           else
9310             return false;
9311         }
9312       if (!argtype)
9313         return false; /* Found ellipsis.  */
9314
9315       if (arity != max_arity)
9316         return false;
9317
9318       return true;
9319     }
9320 }