Fix cleanup location for try_finally_expr.
[platform/upstream/linaro-gcc.git] / gcc / cp / constexpr.c
1 /* Perform -*- C++ -*- constant expression evaluation, including calls to
2    constexpr functions.  These routines are used both during actual parsing
3    and during the instantiation of template functions.
4
5    Copyright (C) 1998-2016 Free Software Foundation, Inc.
6
7    This file is part of GCC.
8
9    GCC is free software; you can redistribute it and/or modify it
10    under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3, or (at your option)
12    any later version.
13
14    GCC is distributed in the hope that it will be useful, but
15    WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17    General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34
35 static bool verify_constant (tree, bool, bool *, bool *);
36 #define VERIFY_CONSTANT(X)                                              \
37 do {                                                                    \
38   if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
39     return t;                                                           \
40  } while (0)
41
42 /* Returns true iff FUN is an instantiation of a constexpr function
43    template or a defaulted constexpr function.  */
44
45 bool
46 is_instantiation_of_constexpr (tree fun)
47 {
48   return ((DECL_TEMPLOID_INSTANTIATION (fun)
49            && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
50           || (DECL_DEFAULTED_FN (fun)
51               && DECL_DECLARED_CONSTEXPR_P (fun)));
52 }
53
54 /* Return true if T is a literal type.   */
55
56 bool
57 literal_type_p (tree t)
58 {
59   if (SCALAR_TYPE_P (t)
60       || VECTOR_TYPE_P (t)
61       || TREE_CODE (t) == REFERENCE_TYPE
62       || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
63     return true;
64   if (CLASS_TYPE_P (t))
65     {
66       t = complete_type (t);
67       gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
68       return CLASSTYPE_LITERAL_P (t);
69     }
70   if (TREE_CODE (t) == ARRAY_TYPE)
71     return literal_type_p (strip_array_types (t));
72   return false;
73 }
74
75 /* If DECL is a variable declared `constexpr', require its type
76    be literal.  Return the DECL if OK, otherwise NULL.  */
77
78 tree
79 ensure_literal_type_for_constexpr_object (tree decl)
80 {
81   tree type = TREE_TYPE (decl);
82   if (VAR_P (decl)
83       && (DECL_DECLARED_CONSTEXPR_P (decl)
84           || var_in_constexpr_fn (decl))
85       && !processing_template_decl)
86     {
87       tree stype = strip_array_types (type);
88       if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
89         /* Don't complain here, we'll complain about incompleteness
90            when we try to initialize the variable.  */;
91       else if (!literal_type_p (type))
92         {
93           if (DECL_DECLARED_CONSTEXPR_P (decl))
94             {
95               error ("the type %qT of constexpr variable %qD is not literal",
96                      type, decl);
97               explain_non_literal_class (type);
98             }
99           else
100             {
101               if (!DECL_TEMPLATE_INSTANTIATION (current_function_decl))
102                 {
103                   error ("variable %qD of non-literal type %qT in %<constexpr%> "
104                          "function", decl, type);
105                   explain_non_literal_class (type);
106                 }
107               cp_function_chain->invalid_constexpr = true;
108             }
109           return NULL;
110         }
111     }
112   return decl;
113 }
114
115 /* Representation of entries in the constexpr function definition table.  */
116
117 struct GTY((for_user)) constexpr_fundef {
118   tree decl;
119   tree body;
120 };
121
122 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
123 {
124   static hashval_t hash (constexpr_fundef *);
125   static bool equal (constexpr_fundef *, constexpr_fundef *);
126 };
127
128 /* This table holds all constexpr function definitions seen in
129    the current translation unit.  */
130
131 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
132
133 /* Utility function used for managing the constexpr function table.
134    Return true if the entries pointed to by P and Q are for the
135    same constexpr function.  */
136
137 inline bool
138 constexpr_fundef_hasher::equal (constexpr_fundef *lhs, constexpr_fundef *rhs)
139 {
140   return lhs->decl == rhs->decl;
141 }
142
143 /* Utility function used for managing the constexpr function table.
144    Return a hash value for the entry pointed to by Q.  */
145
146 inline hashval_t
147 constexpr_fundef_hasher::hash (constexpr_fundef *fundef)
148 {
149   return DECL_UID (fundef->decl);
150 }
151
152 /* Return a previously saved definition of function FUN.   */
153
154 static constexpr_fundef *
155 retrieve_constexpr_fundef (tree fun)
156 {
157   constexpr_fundef fundef = { NULL, NULL };
158   if (constexpr_fundef_table == NULL)
159     return NULL;
160
161   fundef.decl = fun;
162   return constexpr_fundef_table->find (&fundef);
163 }
164
165 /* Check whether the parameter and return types of FUN are valid for a
166    constexpr function, and complain if COMPLAIN.  */
167
168 static bool
169 is_valid_constexpr_fn (tree fun, bool complain)
170 {
171   bool ret = true;
172
173   if (DECL_INHERITED_CTOR_BASE (fun)
174       && TREE_CODE (fun) == TEMPLATE_DECL)
175     {
176       ret = false;
177       if (complain)
178         error ("inherited constructor %qD is not constexpr",
179                get_inherited_ctor (fun));
180     }
181   else
182     {
183       for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
184            parm != NULL_TREE; parm = TREE_CHAIN (parm))
185         if (!literal_type_p (TREE_TYPE (parm)))
186           {
187             ret = false;
188             if (complain)
189               {
190                 error ("invalid type for parameter %d of constexpr "
191                        "function %q+#D", DECL_PARM_INDEX (parm), fun);
192                 explain_non_literal_class (TREE_TYPE (parm));
193               }
194           }
195     }
196
197   if (!DECL_CONSTRUCTOR_P (fun))
198     {
199       tree rettype = TREE_TYPE (TREE_TYPE (fun));
200       if (!literal_type_p (rettype))
201         {
202           ret = false;
203           if (complain)
204             {
205               error ("invalid return type %qT of constexpr function %q+D",
206                      rettype, fun);
207               explain_non_literal_class (rettype);
208             }
209         }
210
211       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
212           && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
213         {
214           ret = false;
215           if (complain)
216             {
217               error ("enclosing class of constexpr non-static member "
218                      "function %q+#D is not a literal type", fun);
219               explain_non_literal_class (DECL_CONTEXT (fun));
220             }
221         }
222     }
223   else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
224     {
225       ret = false;
226       if (complain)
227         error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
228     }
229
230   return ret;
231 }
232
233 /* Subroutine of build_data_member_initialization.  MEMBER is a COMPONENT_REF
234    for a member of an anonymous aggregate, INIT is the initializer for that
235    member, and VEC_OUTER is the vector of constructor elements for the class
236    whose constructor we are processing.  Add the initializer to the vector
237    and return true to indicate success.  */
238
239 static bool
240 build_anon_member_initialization (tree member, tree init,
241                                   vec<constructor_elt, va_gc> **vec_outer)
242 {
243   /* MEMBER presents the relevant fields from the inside out, but we need
244      to build up the initializer from the outside in so that we can reuse
245      previously built CONSTRUCTORs if this is, say, the second field in an
246      anonymous struct.  So we use a vec as a stack.  */
247   auto_vec<tree, 2> fields;
248   do
249     {
250       fields.safe_push (TREE_OPERAND (member, 1));
251       member = TREE_OPERAND (member, 0);
252     }
253   while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
254          && TREE_CODE (member) == COMPONENT_REF);
255
256   /* VEC has the constructor elements vector for the context of FIELD.
257      If FIELD is an anonymous aggregate, we will push inside it.  */
258   vec<constructor_elt, va_gc> **vec = vec_outer;
259   tree field;
260   while (field = fields.pop(),
261          ANON_AGGR_TYPE_P (TREE_TYPE (field)))
262     {
263       tree ctor;
264       /* If there is already an outer constructor entry for the anonymous
265          aggregate FIELD, use it; otherwise, insert one.  */
266       if (vec_safe_is_empty (*vec)
267           || (*vec)->last().index != field)
268         {
269           ctor = build_constructor (TREE_TYPE (field), NULL);
270           CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
271         }
272       else
273         ctor = (*vec)->last().value;
274       vec = &CONSTRUCTOR_ELTS (ctor);
275     }
276
277   /* Now we're at the innermost field, the one that isn't an anonymous
278      aggregate.  Add its initializer to the CONSTRUCTOR and we're done.  */
279   gcc_assert (fields.is_empty());
280   CONSTRUCTOR_APPEND_ELT (*vec, field, init);
281
282   return true;
283 }
284
285 /* Subroutine of  build_constexpr_constructor_member_initializers.
286    The expression tree T represents a data member initialization
287    in a (constexpr) constructor definition.  Build a pairing of
288    the data member with its initializer, and prepend that pair
289    to the existing initialization pair INITS.  */
290
291 static bool
292 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
293 {
294   tree member, init;
295   if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
296     t = TREE_OPERAND (t, 0);
297   if (TREE_CODE (t) == EXPR_STMT)
298     t = TREE_OPERAND (t, 0);
299   if (t == error_mark_node)
300     return false;
301   if (TREE_CODE (t) == STATEMENT_LIST)
302     {
303       tree_stmt_iterator i;
304       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
305         {
306           if (! build_data_member_initialization (tsi_stmt (i), vec))
307             return false;
308         }
309       return true;
310     }
311   if (TREE_CODE (t) == CLEANUP_STMT)
312     {
313       /* We can't see a CLEANUP_STMT in a constructor for a literal class,
314          but we can in a constexpr constructor for a non-literal class.  Just
315          ignore it; either all the initialization will be constant, in which
316          case the cleanup can't run, or it can't be constexpr.
317          Still recurse into CLEANUP_BODY.  */
318       return build_data_member_initialization (CLEANUP_BODY (t), vec);
319     }
320   if (TREE_CODE (t) == CONVERT_EXPR)
321     t = TREE_OPERAND (t, 0);
322   if (TREE_CODE (t) == INIT_EXPR
323       /* vptr initialization shows up as a MODIFY_EXPR.  In C++14 we only
324          use what this function builds for cx_check_missing_mem_inits, and
325          assignment in the ctor body doesn't count.  */
326       || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
327     {
328       member = TREE_OPERAND (t, 0);
329       init = break_out_target_exprs (TREE_OPERAND (t, 1));
330     }
331   else if (TREE_CODE (t) == CALL_EXPR)
332     {
333       tree fn = get_callee_fndecl (t);
334       if (!fn || !DECL_CONSTRUCTOR_P (fn))
335         /* We're only interested in calls to subobject constructors.  */
336         return true;
337       member = CALL_EXPR_ARG (t, 0);
338       /* We don't use build_cplus_new here because it complains about
339          abstract bases.  Leaving the call unwrapped means that it has the
340          wrong type, but cxx_eval_constant_expression doesn't care.  */
341       init = break_out_target_exprs (t);
342     }
343   else if (TREE_CODE (t) == BIND_EXPR)
344     return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
345   else
346     /* Don't add anything else to the CONSTRUCTOR.  */
347     return true;
348   if (INDIRECT_REF_P (member))
349     member = TREE_OPERAND (member, 0);
350   if (TREE_CODE (member) == NOP_EXPR)
351     {
352       tree op = member;
353       STRIP_NOPS (op);
354       if (TREE_CODE (op) == ADDR_EXPR)
355         {
356           gcc_assert (same_type_ignoring_top_level_qualifiers_p
357                       (TREE_TYPE (TREE_TYPE (op)),
358                        TREE_TYPE (TREE_TYPE (member))));
359           /* Initializing a cv-qualified member; we need to look through
360              the const_cast.  */
361           member = op;
362         }
363       else if (op == current_class_ptr
364                && (same_type_ignoring_top_level_qualifiers_p
365                    (TREE_TYPE (TREE_TYPE (member)),
366                     current_class_type)))
367         /* Delegating constructor.  */
368         member = op;
369       else
370         {
371           /* This is an initializer for an empty base; keep it for now so
372              we can check it in cxx_eval_bare_aggregate.  */
373           gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
374         }
375     }
376   if (TREE_CODE (member) == ADDR_EXPR)
377     member = TREE_OPERAND (member, 0);
378   if (TREE_CODE (member) == COMPONENT_REF)
379     {
380       tree aggr = TREE_OPERAND (member, 0);
381       if (TREE_CODE (aggr) != COMPONENT_REF)
382         /* Normal member initialization.  */
383         member = TREE_OPERAND (member, 1);
384       else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
385         /* Initializing a member of an anonymous union.  */
386         return build_anon_member_initialization (member, init, vec);
387       else
388         /* We're initializing a vtable pointer in a base.  Leave it as
389            COMPONENT_REF so we remember the path to get to the vfield.  */
390         gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
391     }
392
393   /* Value-initialization can produce multiple initializers for the
394      same field; use the last one.  */
395   if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
396     (*vec)->last().value = init;
397   else
398     CONSTRUCTOR_APPEND_ELT (*vec, member, init);
399   return true;
400 }
401
402 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
403    In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a 
404    BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations.  */
405
406 static bool
407 check_constexpr_bind_expr_vars (tree t)
408 {
409   gcc_assert (TREE_CODE (t) == BIND_EXPR);
410
411   for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
412     if (TREE_CODE (var) == TYPE_DECL
413         && DECL_IMPLICIT_TYPEDEF_P (var)
414         && !LAMBDA_TYPE_P (TREE_TYPE (var)))
415       return false;
416   return true;
417 }
418
419 /* Subroutine of check_constexpr_ctor_body.  */
420
421 static bool
422 check_constexpr_ctor_body_1 (tree last, tree list)
423 {
424   switch (TREE_CODE (list))
425     {
426     case DECL_EXPR:
427       if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL)
428         return true;
429       return false;
430
431     case CLEANUP_POINT_EXPR:
432       return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
433                                         /*complain=*/false);
434
435     case BIND_EXPR:
436        if (!check_constexpr_bind_expr_vars (list)
437            || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
438                                           /*complain=*/false))
439          return false;
440        return true;
441
442     case USING_STMT:
443     case STATIC_ASSERT:
444     case STATEMENT_LIST_END:
445       return true;
446
447     default:
448       return false;
449     }
450 }
451
452 /* Make sure that there are no statements after LAST in the constructor
453    body represented by LIST.  */
454
455 bool
456 check_constexpr_ctor_body (tree last, tree list, bool complain)
457 {
458   /* C++14 doesn't require a constexpr ctor to have an empty body.  */
459   if (cxx_dialect >= cxx14)
460     return true;
461
462   bool ok = true;
463   if (TREE_CODE (list) == STATEMENT_LIST)
464     {
465       tree_stmt_iterator i = tsi_last (list);
466       for (; !tsi_end_p (i); tsi_prev (&i))
467         {
468           tree t = tsi_stmt (i);
469           if (t == last)
470             break;
471           if (!check_constexpr_ctor_body_1 (last, t))
472             {
473               ok = false;
474               break;
475             }
476         }
477     }
478   else if (list != last
479            && !check_constexpr_ctor_body_1 (last, list))
480     ok = false;
481   if (!ok)
482     {
483       if (complain)
484         error ("constexpr constructor does not have empty body");
485       DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
486     }
487   return ok;
488 }
489
490 /* V is a vector of constructor elements built up for the base and member
491    initializers of a constructor for TYPE.  They need to be in increasing
492    offset order, which they might not be yet if TYPE has a primary base
493    which is not first in the base-clause or a vptr and at least one base
494    all of which are non-primary.  */
495
496 static vec<constructor_elt, va_gc> *
497 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
498 {
499   tree pri = CLASSTYPE_PRIMARY_BINFO (type);
500   tree field_type;
501   unsigned i;
502   constructor_elt *ce;
503
504   if (pri)
505     field_type = BINFO_TYPE (pri);
506   else if (TYPE_CONTAINS_VPTR_P (type))
507     field_type = vtbl_ptr_type_node;
508   else
509     return v;
510
511   /* Find the element for the primary base or vptr and move it to the
512      beginning of the vec.  */
513   for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
514     if (TREE_TYPE (ce->index) == field_type)
515       break;
516
517   if (i > 0 && i < vec_safe_length (v))
518     {
519       vec<constructor_elt, va_gc> &vref = *v;
520       constructor_elt elt = vref[i];
521       for (; i > 0; --i)
522         vref[i] = vref[i-1];
523       vref[0] = elt;
524     }
525
526   return v;
527 }
528
529 /* Build compile-time evalable representations of member-initializer list
530    for a constexpr constructor.  */
531
532 static tree
533 build_constexpr_constructor_member_initializers (tree type, tree body)
534 {
535   vec<constructor_elt, va_gc> *vec = NULL;
536   bool ok = true;
537   while (true)
538     switch (TREE_CODE (body))
539       {
540       case MUST_NOT_THROW_EXPR:
541       case EH_SPEC_BLOCK:
542         body = TREE_OPERAND (body, 0);
543         break;
544
545       case STATEMENT_LIST:
546         for (tree_stmt_iterator i = tsi_start (body);
547              !tsi_end_p (i); tsi_next (&i))
548           {
549             body = tsi_stmt (i);
550             if (TREE_CODE (body) == BIND_EXPR)
551               break;
552           }
553         break;
554
555       case BIND_EXPR:
556         body = BIND_EXPR_BODY (body);
557         goto found;
558
559       case STATEMENT_LIST_END:
560         break;
561
562       default:
563         gcc_unreachable ();
564     }
565  found:
566   if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
567     {
568       body = TREE_OPERAND (body, 0);
569       if (TREE_CODE (body) == EXPR_STMT)
570         body = TREE_OPERAND (body, 0);
571       if (TREE_CODE (body) == INIT_EXPR
572           && (same_type_ignoring_top_level_qualifiers_p
573               (TREE_TYPE (TREE_OPERAND (body, 0)),
574                current_class_type)))
575         {
576           /* Trivial copy.  */
577           return TREE_OPERAND (body, 1);
578         }
579       ok = build_data_member_initialization (body, &vec);
580     }
581   else if (TREE_CODE (body) == STATEMENT_LIST)
582     {
583       tree_stmt_iterator i;
584       for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
585         {
586           ok = build_data_member_initialization (tsi_stmt (i), &vec);
587           if (!ok)
588             break;
589         }
590     }
591   else if (TREE_CODE (body) == TRY_BLOCK)
592     {
593       error ("body of %<constexpr%> constructor cannot be "
594              "a function-try-block");
595       return error_mark_node;
596     }
597   else if (EXPR_P (body))
598     ok = build_data_member_initialization (body, &vec);
599   else
600     gcc_assert (errorcount > 0);
601   if (ok)
602     {
603       if (vec_safe_length (vec) > 0)
604         {
605           /* In a delegating constructor, return the target.  */
606           constructor_elt *ce = &(*vec)[0];
607           if (ce->index == current_class_ptr)
608             {
609               body = ce->value;
610               vec_free (vec);
611               return body;
612             }
613         }
614       vec = sort_constexpr_mem_initializers (type, vec);
615       return build_constructor (type, vec);
616     }
617   else
618     return error_mark_node;
619 }
620
621 /* Subroutine of register_constexpr_fundef.  BODY is the body of a function
622    declared to be constexpr, or a sub-statement thereof.  Returns the
623    return value if suitable, error_mark_node for a statement not allowed in
624    a constexpr function, or NULL_TREE if no return value was found.  */
625
626 static tree
627 constexpr_fn_retval (tree body)
628 {
629   switch (TREE_CODE (body))
630     {
631     case STATEMENT_LIST:
632       {
633         tree_stmt_iterator i;
634         tree expr = NULL_TREE;
635         for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
636           {
637             tree s = constexpr_fn_retval (tsi_stmt (i));
638             if (s == error_mark_node)
639               return error_mark_node;
640             else if (s == NULL_TREE)
641               /* Keep iterating.  */;
642             else if (expr)
643               /* Multiple return statements.  */
644               return error_mark_node;
645             else
646               expr = s;
647           }
648         return expr;
649       }
650
651     case RETURN_EXPR:
652       return break_out_target_exprs (TREE_OPERAND (body, 0));
653
654     case DECL_EXPR:
655       {
656         tree decl = DECL_EXPR_DECL (body);
657         if (TREE_CODE (decl) == USING_DECL
658             /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__.  */
659             || DECL_ARTIFICIAL (decl))
660           return NULL_TREE;
661         return error_mark_node;
662       }
663
664     case CLEANUP_POINT_EXPR:
665       return constexpr_fn_retval (TREE_OPERAND (body, 0));
666
667     case BIND_EXPR:
668       if (!check_constexpr_bind_expr_vars (body))
669         return error_mark_node;
670       return constexpr_fn_retval (BIND_EXPR_BODY (body));
671
672     case USING_STMT:
673     case STATEMENT_LIST_END:
674       return NULL_TREE;
675
676     default:
677       return error_mark_node;
678     }
679 }
680
681 /* Subroutine of register_constexpr_fundef.  BODY is the DECL_SAVED_TREE of
682    FUN; do the necessary transformations to turn it into a single expression
683    that we can store in the hash table.  */
684
685 static tree
686 massage_constexpr_body (tree fun, tree body)
687 {
688   if (DECL_CONSTRUCTOR_P (fun))
689     body = build_constexpr_constructor_member_initializers
690       (DECL_CONTEXT (fun), body);
691   else if (cxx_dialect < cxx14)
692     {
693       if (TREE_CODE (body) == EH_SPEC_BLOCK)
694         body = EH_SPEC_STMTS (body);
695       if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
696         body = TREE_OPERAND (body, 0);
697       body = constexpr_fn_retval (body);
698     }
699   return body;
700 }
701
702 /* FUN is a constexpr constructor with massaged body BODY.  Return true
703    if some bases/fields are uninitialized, and complain if COMPLAIN.  */
704
705 static bool
706 cx_check_missing_mem_inits (tree fun, tree body, bool complain)
707 {
708   bool bad;
709   tree field;
710   unsigned i, nelts;
711   tree ctype;
712
713   if (TREE_CODE (body) != CONSTRUCTOR)
714     return false;
715
716   nelts = CONSTRUCTOR_NELTS (body);
717   ctype = DECL_CONTEXT (fun);
718   field = TYPE_FIELDS (ctype);
719
720   if (TREE_CODE (ctype) == UNION_TYPE)
721     {
722       if (nelts == 0 && next_initializable_field (field))
723         {
724           if (complain)
725             error ("%<constexpr%> constructor for union %qT must "
726                    "initialize exactly one non-static data member", ctype);
727           return true;
728         }
729       return false;
730     }
731
732   bad = false;
733   for (i = 0; i <= nelts; ++i)
734     {
735       tree index;
736       if (i == nelts)
737         index = NULL_TREE;
738       else
739         {
740           index = CONSTRUCTOR_ELT (body, i)->index;
741           /* Skip base and vtable inits.  */
742           if (TREE_CODE (index) != FIELD_DECL
743               || DECL_ARTIFICIAL (index))
744             continue;
745         }
746       for (; field != index; field = DECL_CHAIN (field))
747         {
748           tree ftype;
749           if (TREE_CODE (field) != FIELD_DECL
750               || (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
751               || DECL_ARTIFICIAL (field))
752             continue;
753           ftype = strip_array_types (TREE_TYPE (field));
754           if (type_has_constexpr_default_constructor (ftype))
755             {
756               /* It's OK to skip a member with a trivial constexpr ctor.
757                  A constexpr ctor that isn't trivial should have been
758                  added in by now.  */
759               gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
760                                    || errorcount != 0);
761               continue;
762             }
763           if (!complain)
764             return true;
765           error ("member %qD must be initialized by mem-initializer "
766                  "in %<constexpr%> constructor", field);
767           inform (DECL_SOURCE_LOCATION (field), "declared here");
768           bad = true;
769         }
770       if (field == NULL_TREE)
771         break;
772       field = DECL_CHAIN (field);
773     }
774
775   return bad;
776 }
777
778 /* We are processing the definition of the constexpr function FUN.
779    Check that its BODY fulfills the propriate requirements and
780    enter it in the constexpr function definition table.
781    For constructor BODY is actually the TREE_LIST of the
782    member-initializer list.  */
783
784 tree
785 register_constexpr_fundef (tree fun, tree body)
786 {
787   constexpr_fundef entry;
788   constexpr_fundef **slot;
789
790   if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
791     return NULL;
792
793   tree massaged = massage_constexpr_body (fun, body);
794   if (massaged == NULL_TREE || massaged == error_mark_node)
795     {
796       if (!DECL_CONSTRUCTOR_P (fun))
797         error ("body of constexpr function %qD not a return-statement", fun);
798       return NULL;
799     }
800
801   if (!potential_rvalue_constant_expression (massaged))
802     {
803       if (!DECL_GENERATED_P (fun))
804         require_potential_rvalue_constant_expression (massaged);
805       return NULL;
806     }
807
808   if (DECL_CONSTRUCTOR_P (fun)
809       && cx_check_missing_mem_inits (fun, massaged, !DECL_GENERATED_P (fun)))
810     return NULL;
811
812   /* Create the constexpr function table if necessary.  */
813   if (constexpr_fundef_table == NULL)
814     constexpr_fundef_table
815       = hash_table<constexpr_fundef_hasher>::create_ggc (101);
816
817   entry.decl = fun;
818   entry.body = body;
819   slot = constexpr_fundef_table->find_slot (&entry, INSERT);
820
821   gcc_assert (*slot == NULL);
822   *slot = ggc_alloc<constexpr_fundef> ();
823   **slot = entry;
824
825   return fun;
826 }
827
828 /* FUN is a non-constexpr function called in a context that requires a
829    constant expression.  If it comes from a constexpr template, explain why
830    the instantiation isn't constexpr.  */
831
832 void
833 explain_invalid_constexpr_fn (tree fun)
834 {
835   static hash_set<tree> *diagnosed;
836   tree body;
837   location_t save_loc;
838   /* Only diagnose defaulted functions or instantiations.  */
839   if (!DECL_DEFAULTED_FN (fun)
840       && !is_instantiation_of_constexpr (fun))
841     return;
842   if (diagnosed == NULL)
843     diagnosed = new hash_set<tree>;
844   if (diagnosed->add (fun))
845     /* Already explained.  */
846     return;
847
848   save_loc = input_location;
849   input_location = DECL_SOURCE_LOCATION (fun);
850   inform (input_location,
851           "%qD is not usable as a constexpr function because:", fun);
852   /* First check the declaration.  */
853   if (is_valid_constexpr_fn (fun, true))
854     {
855       /* Then if it's OK, the body.  */
856       if (!DECL_DECLARED_CONSTEXPR_P (fun))
857         explain_implicit_non_constexpr (fun);
858       else
859         {
860           body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
861           require_potential_rvalue_constant_expression (body);
862           if (DECL_CONSTRUCTOR_P (fun))
863             cx_check_missing_mem_inits (fun, body, true);
864         }
865     }
866   input_location = save_loc;
867 }
868
869 /* Objects of this type represent calls to constexpr functions
870    along with the bindings of parameters to their arguments, for
871    the purpose of compile time evaluation.  */
872
873 struct GTY((for_user)) constexpr_call {
874   /* Description of the constexpr function definition.  */
875   constexpr_fundef *fundef;
876   /* Parameter bindings environment.  A TREE_LIST where each TREE_PURPOSE
877      is a parameter _DECL and the TREE_VALUE is the value of the parameter.
878      Note: This arrangement is made to accommodate the use of
879      iterative_hash_template_arg (see pt.c).  If you change this
880      representation, also change the hash calculation in
881      cxx_eval_call_expression.  */
882   tree bindings;
883   /* Result of the call.
884        NULL means the call is being evaluated.
885        error_mark_node means that the evaluation was erroneous;
886        otherwise, the actuall value of the call.  */
887   tree result;
888   /* The hash of this call; we remember it here to avoid having to
889      recalculate it when expanding the hash table.  */
890   hashval_t hash;
891 };
892
893 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
894 {
895   static hashval_t hash (constexpr_call *);
896   static bool equal (constexpr_call *, constexpr_call *);
897 };
898
899 enum constexpr_switch_state {
900   /* Used when processing a switch for the first time by cxx_eval_switch_expr
901      and default: label for that switch has not been seen yet.  */
902   css_default_not_seen,
903   /* Used when processing a switch for the first time by cxx_eval_switch_expr
904      and default: label for that switch has been seen already.  */
905   css_default_seen,
906   /* Used when processing a switch for the second time by
907      cxx_eval_switch_expr, where default: label should match.  */
908   css_default_processing
909 };
910
911 /* The constexpr expansion context.  CALL is the current function
912    expansion, CTOR is the current aggregate initializer, OBJECT is the
913    object being initialized by CTOR, either a VAR_DECL or a _REF.  VALUES
914    is a map of values of variables initialized within the expression.  */
915
916 struct constexpr_ctx {
917   /* The innermost call we're evaluating.  */
918   constexpr_call *call;
919   /* Values for any temporaries or local variables within the
920      constant-expression. */
921   hash_map<tree,tree> *values;
922   /* SAVE_EXPRs that we've seen within the current LOOP_EXPR.  NULL if we
923      aren't inside a loop.  */
924   hash_set<tree> *save_exprs;
925   /* The CONSTRUCTOR we're currently building up for an aggregate
926      initializer.  */
927   tree ctor;
928   /* The object we're building the CONSTRUCTOR for.  */
929   tree object;
930   /* If inside SWITCH_EXPR.  */
931   constexpr_switch_state *css_state;
932   /* Whether we should error on a non-constant expression or fail quietly.  */
933   bool quiet;
934   /* Whether we are strictly conforming to constant expression rules or
935      trying harder to get a constant value.  */
936   bool strict;
937 };
938
939 /* A table of all constexpr calls that have been evaluated by the
940    compiler in this translation unit.  */
941
942 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
943
944 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
945                                           bool, bool *, bool *, tree * = NULL);
946
947 /* Compute a hash value for a constexpr call representation.  */
948
949 inline hashval_t
950 constexpr_call_hasher::hash (constexpr_call *info)
951 {
952   return info->hash;
953 }
954
955 /* Return true if the objects pointed to by P and Q represent calls
956    to the same constexpr function with the same arguments.
957    Otherwise, return false.  */
958
959 bool
960 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
961 {
962   tree lhs_bindings;
963   tree rhs_bindings;
964   if (lhs == rhs)
965     return 1;
966   if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
967     return 0;
968   lhs_bindings = lhs->bindings;
969   rhs_bindings = rhs->bindings;
970   while (lhs_bindings != NULL && rhs_bindings != NULL)
971     {
972       tree lhs_arg = TREE_VALUE (lhs_bindings);
973       tree rhs_arg = TREE_VALUE (rhs_bindings);
974       gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
975       if (!cp_tree_equal (lhs_arg, rhs_arg))
976         return 0;
977       lhs_bindings = TREE_CHAIN (lhs_bindings);
978       rhs_bindings = TREE_CHAIN (rhs_bindings);
979     }
980   return lhs_bindings == rhs_bindings;
981 }
982
983 /* Initialize the constexpr call table, if needed.  */
984
985 static void
986 maybe_initialize_constexpr_call_table (void)
987 {
988   if (constexpr_call_table == NULL)
989     constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
990 }
991
992 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
993    a function happens to get called recursively, we unshare the callee
994    function's body and evaluate this unshared copy instead of evaluating the
995    original body.
996
997    FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
998    copies.  The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
999    that's keyed off of the original FUNCTION_DECL and whose value is a
1000    TREE_LIST of this function's unused copies awaiting reuse.
1001
1002    This is not GC-deletable to avoid GC affecting UID generation.  */
1003
1004 static GTY(()) hash_map<tree, tree> *fundef_copies_table;
1005
1006 /* Initialize FUNDEF_COPIES_TABLE if it's not initialized.  */
1007
1008 static void
1009 maybe_initialize_fundef_copies_table ()
1010 {
1011   if (fundef_copies_table == NULL)
1012     fundef_copies_table = hash_map<tree,tree>::create_ggc (101);
1013 }
1014
1015 /* Reuse a copy or create a new unshared copy of the function FUN.
1016    Return this copy.  We use a TREE_LIST whose PURPOSE is body, VALUE
1017    is parms, TYPE is result.  */
1018
1019 static tree
1020 get_fundef_copy (tree fun)
1021 {
1022   maybe_initialize_fundef_copies_table ();
1023
1024   tree copy;
1025   bool existed;
1026   tree *slot = &fundef_copies_table->get_or_insert (fun, &existed);
1027
1028   if (!existed)
1029     {
1030       /* There is no cached function available, or in use.  We can use
1031          the function directly.  That the slot is now created records
1032          that this function is now in use.  */
1033       copy = build_tree_list (DECL_SAVED_TREE (fun), DECL_ARGUMENTS (fun));
1034       TREE_TYPE (copy) = DECL_RESULT (fun);
1035     }
1036   else if (*slot == NULL_TREE)
1037     {
1038       /* We've already used the function itself, so make a copy.  */
1039       copy = build_tree_list (NULL, NULL);
1040       TREE_PURPOSE (copy) = copy_fn (fun, TREE_VALUE (copy), TREE_TYPE (copy));
1041     }
1042   else
1043     {
1044       /* We have a cached function available.  */
1045       copy = *slot;
1046       *slot = TREE_CHAIN (copy);
1047     }
1048
1049   return copy;
1050 }
1051
1052 /* Save the copy COPY of function FUN for later reuse by
1053    get_fundef_copy().  By construction, there will always be an entry
1054    to find.  */
1055
1056 static void
1057 save_fundef_copy (tree fun, tree copy)
1058 {
1059   tree *slot = fundef_copies_table->get (fun);
1060   TREE_CHAIN (copy) = *slot;
1061   *slot = copy;
1062 }
1063
1064 /* We have an expression tree T that represents a call, either CALL_EXPR
1065    or AGGR_INIT_EXPR.  If the call is lexically to a named function,
1066    retrun the _DECL for that function.  */
1067
1068 static tree
1069 get_function_named_in_call (tree t)
1070 {
1071   tree fun = NULL;
1072   switch (TREE_CODE (t))
1073     {
1074     case CALL_EXPR:
1075       fun = CALL_EXPR_FN (t);
1076       break;
1077
1078     case AGGR_INIT_EXPR:
1079       fun = AGGR_INIT_EXPR_FN (t);
1080       break;
1081
1082     default:
1083       gcc_unreachable();
1084       break;
1085     }
1086   if (fun && TREE_CODE (fun) == ADDR_EXPR
1087       && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
1088     fun = TREE_OPERAND (fun, 0);
1089   return fun;
1090 }
1091
1092 /* We have an expression tree T that represents a call, either CALL_EXPR
1093    or AGGR_INIT_EXPR.  Return the Nth argument.  */
1094
1095 static inline tree
1096 get_nth_callarg (tree t, int n)
1097 {
1098   switch (TREE_CODE (t))
1099     {
1100     case CALL_EXPR:
1101       return CALL_EXPR_ARG (t, n);
1102
1103     case AGGR_INIT_EXPR:
1104       return AGGR_INIT_EXPR_ARG (t, n);
1105
1106     default:
1107       gcc_unreachable ();
1108       return NULL;
1109     }
1110 }
1111
1112 /* Attempt to evaluate T which represents a call to a builtin function.
1113    We assume here that all builtin functions evaluate to scalar types
1114    represented by _CST nodes.  */
1115
1116 static tree
1117 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1118                                 bool lval,
1119                                 bool *non_constant_p, bool *overflow_p)
1120 {
1121   const int nargs = call_expr_nargs (t);
1122   tree *args = (tree *) alloca (nargs * sizeof (tree));
1123   tree new_call;
1124   int i;
1125
1126   /* Don't fold __builtin_constant_p within a constexpr function.  */
1127   bool bi_const_p = (DECL_FUNCTION_CODE (fun) == BUILT_IN_CONSTANT_P);
1128
1129   if (bi_const_p
1130       && current_function_decl
1131       && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1132     {
1133       *non_constant_p = true;
1134       return t;
1135     }
1136
1137   /* Be permissive for arguments to built-ins; __builtin_constant_p should
1138      return constant false for a non-constant argument.  */
1139   constexpr_ctx new_ctx = *ctx;
1140   new_ctx.quiet = true;
1141   bool dummy1 = false, dummy2 = false;
1142   for (i = 0; i < nargs; ++i)
1143     {
1144       args[i] = cxx_eval_constant_expression (&new_ctx, CALL_EXPR_ARG (t, i),
1145                                               lval, &dummy1, &dummy2);
1146       if (bi_const_p)
1147         /* For __built_in_constant_p, fold all expressions with constant values
1148            even if they aren't C++ constant-expressions.  */
1149         args[i] = cp_fully_fold (args[i]);
1150     }
1151
1152   bool save_ffbcp = force_folding_builtin_constant_p;
1153   force_folding_builtin_constant_p = true;
1154   new_call = fold_build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1155                                         CALL_EXPR_FN (t), nargs, args);
1156   /* Fold away the NOP_EXPR from fold_builtin_n.  */
1157   new_call = fold (new_call);
1158   force_folding_builtin_constant_p = save_ffbcp;
1159   VERIFY_CONSTANT (new_call);
1160   return new_call;
1161 }
1162
1163 /* TEMP is the constant value of a temporary object of type TYPE.  Adjust
1164    the type of the value to match.  */
1165
1166 static tree
1167 adjust_temp_type (tree type, tree temp)
1168 {
1169   if (TREE_TYPE (temp) == type)
1170     return temp;
1171   /* Avoid wrapping an aggregate value in a NOP_EXPR.  */
1172   if (TREE_CODE (temp) == CONSTRUCTOR)
1173     return build_constructor (type, CONSTRUCTOR_ELTS (temp));
1174   gcc_assert (scalarish_type_p (type));
1175   return cp_fold_convert (type, temp);
1176 }
1177
1178 /* Callback for walk_tree used by unshare_constructor.  */
1179
1180 static tree
1181 find_constructor (tree *tp, int *walk_subtrees, void *)
1182 {
1183   if (TYPE_P (*tp))
1184     *walk_subtrees = 0;
1185   if (TREE_CODE (*tp) == CONSTRUCTOR)
1186     return *tp;
1187   return NULL_TREE;
1188 }
1189
1190 /* If T is a CONSTRUCTOR or an expression that has a CONSTRUCTOR node as a
1191    subexpression, return an unshared copy of T.  Otherwise return T.  */
1192
1193 static tree
1194 unshare_constructor (tree t)
1195 {
1196   tree ctor = walk_tree (&t, find_constructor, NULL, NULL);
1197   if (ctor != NULL_TREE)
1198     return unshare_expr (t);
1199   return t;
1200 }
1201
1202 /* Subroutine of cxx_eval_call_expression.
1203    We are processing a call expression (either CALL_EXPR or
1204    AGGR_INIT_EXPR) in the context of CTX.  Evaluate
1205    all arguments and bind their values to correspondings
1206    parameters, making up the NEW_CALL context.  */
1207
1208 static void
1209 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1210                              constexpr_call *new_call,
1211                              bool *non_constant_p, bool *overflow_p,
1212                              bool *non_constant_args)
1213 {
1214   const int nargs = call_expr_nargs (t);
1215   tree fun = new_call->fundef->decl;
1216   tree parms = DECL_ARGUMENTS (fun);
1217   int i;
1218   tree *p = &new_call->bindings;
1219   for (i = 0; i < nargs; ++i)
1220     {
1221       tree x, arg;
1222       tree type = parms ? TREE_TYPE (parms) : void_type_node;
1223       x = get_nth_callarg (t, i);
1224       /* For member function, the first argument is a pointer to the implied
1225          object.  For a constructor, it might still be a dummy object, in
1226          which case we get the real argument from ctx. */
1227       if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1228           && is_dummy_object (x))
1229         {
1230           x = ctx->object;
1231           x = cp_build_addr_expr (x, tf_warning_or_error);
1232         }
1233       bool lval = false;
1234       arg = cxx_eval_constant_expression (ctx, x, lval,
1235                                           non_constant_p, overflow_p);
1236       /* Don't VERIFY_CONSTANT here.  */
1237       if (*non_constant_p && ctx->quiet)
1238         return;
1239       /* Just discard ellipsis args after checking their constantitude.  */
1240       if (!parms)
1241         continue;
1242       if (*non_constant_p)
1243         /* Don't try to adjust the type of non-constant args.  */
1244         goto next;
1245
1246       /* Make sure the binding has the same type as the parm.  */
1247       if (TREE_CODE (type) != REFERENCE_TYPE)
1248         arg = adjust_temp_type (type, arg);
1249       if (!TREE_CONSTANT (arg))
1250         *non_constant_args = true;
1251       *p = build_tree_list (parms, arg);
1252       p = &TREE_CHAIN (*p);
1253     next:
1254       parms = TREE_CHAIN (parms);
1255     }
1256 }
1257
1258 /* Variables and functions to manage constexpr call expansion context.
1259    These do not need to be marked for PCH or GC.  */
1260
1261 /* FIXME remember and print actual constant arguments.  */
1262 static vec<tree> call_stack = vNULL;
1263 static int call_stack_tick;
1264 static int last_cx_error_tick;
1265
1266 static bool
1267 push_cx_call_context (tree call)
1268 {
1269   ++call_stack_tick;
1270   if (!EXPR_HAS_LOCATION (call))
1271     SET_EXPR_LOCATION (call, input_location);
1272   call_stack.safe_push (call);
1273   if (call_stack.length () > (unsigned) max_constexpr_depth)
1274     return false;
1275   return true;
1276 }
1277
1278 static void
1279 pop_cx_call_context (void)
1280 {
1281   ++call_stack_tick;
1282   call_stack.pop ();
1283 }
1284
1285 vec<tree> 
1286 cx_error_context (void)
1287 {
1288   vec<tree> r = vNULL;
1289   if (call_stack_tick != last_cx_error_tick
1290       && !call_stack.is_empty ())
1291     r = call_stack;
1292   last_cx_error_tick = call_stack_tick;
1293   return r;
1294 }
1295
1296 /* Subroutine of cxx_eval_constant_expression.
1297    Evaluate the call expression tree T in the context of OLD_CALL expression
1298    evaluation.  */
1299
1300 static tree
1301 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
1302                           bool lval,
1303                           bool *non_constant_p, bool *overflow_p)
1304 {
1305   location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1306   tree fun = get_function_named_in_call (t);
1307   constexpr_call new_call = { NULL, NULL, NULL, 0 };
1308   bool depth_ok;
1309
1310   if (fun == NULL_TREE)
1311     switch (CALL_EXPR_IFN (t))
1312       {
1313       case IFN_UBSAN_NULL:
1314       case IFN_UBSAN_BOUNDS:
1315       case IFN_UBSAN_VPTR:
1316         return void_node;
1317       default:
1318         if (!ctx->quiet)
1319           error_at (loc, "call to internal function");
1320         *non_constant_p = true;
1321         return t;
1322       }
1323
1324   if (TREE_CODE (fun) != FUNCTION_DECL)
1325     {
1326       /* Might be a constexpr function pointer.  */
1327       fun = cxx_eval_constant_expression (ctx, fun,
1328                                           /*lval*/false, non_constant_p,
1329                                           overflow_p);
1330       STRIP_NOPS (fun);
1331       if (TREE_CODE (fun) == ADDR_EXPR)
1332         fun = TREE_OPERAND (fun, 0);
1333     }
1334   if (TREE_CODE (fun) != FUNCTION_DECL)
1335     {
1336       if (!ctx->quiet && !*non_constant_p)
1337         error_at (loc, "expression %qE does not designate a constexpr "
1338                   "function", fun);
1339       *non_constant_p = true;
1340       return t;
1341     }
1342   if (DECL_CLONED_FUNCTION_P (fun))
1343     fun = DECL_CLONED_FUNCTION (fun);
1344
1345   if (is_ubsan_builtin_p (fun))
1346     return void_node;
1347
1348   if (is_builtin_fn (fun))
1349     return cxx_eval_builtin_function_call (ctx, t, fun,
1350                                            lval, non_constant_p, overflow_p);
1351   if (!DECL_DECLARED_CONSTEXPR_P (fun))
1352     {
1353       if (!ctx->quiet)
1354         {
1355           error_at (loc, "call to non-constexpr function %qD", fun);
1356           explain_invalid_constexpr_fn (fun);
1357         }
1358       *non_constant_p = true;
1359       return t;
1360     }
1361
1362   constexpr_ctx new_ctx = *ctx;
1363   if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
1364       && TREE_CODE (t) == AGGR_INIT_EXPR)
1365     {
1366       /* We want to have an initialization target for an AGGR_INIT_EXPR.
1367          If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT.  */
1368       new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
1369       tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
1370       CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = true;
1371       ctx->values->put (new_ctx.object, ctor);
1372       ctx = &new_ctx;
1373     }
1374
1375   /* Shortcut trivial constructor/op=.  */
1376   if (trivial_fn_p (fun))
1377     {
1378       tree init = NULL_TREE;
1379       if (call_expr_nargs (t) == 2)
1380         init = convert_from_reference (get_nth_callarg (t, 1));
1381       else if (TREE_CODE (t) == AGGR_INIT_EXPR
1382                && AGGR_INIT_ZERO_FIRST (t))
1383         init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
1384       if (init)
1385         {
1386           tree op = get_nth_callarg (t, 0);
1387           if (is_dummy_object (op))
1388             op = ctx->object;
1389           else
1390             op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
1391           tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
1392           return cxx_eval_constant_expression (ctx, set, lval,
1393                                                non_constant_p, overflow_p);
1394         }
1395     }
1396
1397   /* We can't defer instantiating the function any longer.  */
1398   if (!DECL_INITIAL (fun)
1399       && DECL_TEMPLOID_INSTANTIATION (fun))
1400     {
1401       ++function_depth;
1402       instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
1403       --function_depth;
1404     }
1405
1406   /* If in direct recursive call, optimize definition search.  */
1407   if (ctx && ctx->call && ctx->call->fundef->decl == fun)
1408     new_call.fundef = ctx->call->fundef;
1409   else
1410     {
1411       new_call.fundef = retrieve_constexpr_fundef (fun);
1412       if (new_call.fundef == NULL || new_call.fundef->body == NULL
1413           || fun == current_function_decl)
1414         {
1415           if (!ctx->quiet)
1416             {
1417               /* We need to check for current_function_decl here in case we're
1418                  being called during cp_fold_function, because at that point
1419                  DECL_INITIAL is set properly and we have a fundef but we
1420                  haven't lowered invisirefs yet (c++/70344).  */
1421               if (DECL_INITIAL (fun) == error_mark_node
1422                   || fun == current_function_decl)
1423                 error_at (loc, "%qD called in a constant expression before its "
1424                           "definition is complete", fun);
1425               else if (DECL_INITIAL (fun))
1426                 {
1427                   /* The definition of fun was somehow unsuitable.  */
1428                   error_at (loc, "%qD called in a constant expression", fun);
1429                   explain_invalid_constexpr_fn (fun);
1430                 }
1431               else
1432                 error_at (loc, "%qD used before its definition", fun);
1433             }
1434           *non_constant_p = true;
1435           return t;
1436         }
1437     }
1438
1439   bool non_constant_args = false;
1440   cxx_bind_parameters_in_call (ctx, t, &new_call,
1441                                non_constant_p, overflow_p, &non_constant_args);
1442   if (*non_constant_p)
1443     return t;
1444
1445   depth_ok = push_cx_call_context (t);
1446
1447   tree result = NULL_TREE;
1448
1449   constexpr_call *entry = NULL;
1450   if (depth_ok && !non_constant_args)
1451     {
1452       new_call.hash = iterative_hash_template_arg
1453         (new_call.bindings, constexpr_fundef_hasher::hash (new_call.fundef));
1454
1455       /* If we have seen this call before, we are done.  */
1456       maybe_initialize_constexpr_call_table ();
1457       constexpr_call **slot
1458         = constexpr_call_table->find_slot (&new_call, INSERT);
1459       entry = *slot;
1460       if (entry == NULL)
1461         {
1462           /* We need to keep a pointer to the entry, not just the slot, as the
1463              slot can move in the call to cxx_eval_builtin_function_call.  */
1464           *slot = entry = ggc_alloc<constexpr_call> ();
1465           *entry = new_call;
1466         }
1467       /* Calls which are in progress have their result set to NULL
1468          so that we can detect circular dependencies.  */
1469       else if (entry->result == NULL)
1470         {
1471           if (!ctx->quiet)
1472             error ("call has circular dependency");
1473           *non_constant_p = true;
1474           entry->result = result = error_mark_node;
1475         }
1476       else
1477         result = entry->result;
1478     }
1479
1480   if (!depth_ok)
1481     {
1482       if (!ctx->quiet)
1483         error ("constexpr evaluation depth exceeds maximum of %d (use "
1484                "-fconstexpr-depth= to increase the maximum)",
1485                max_constexpr_depth);
1486       *non_constant_p = true;
1487       result = error_mark_node;
1488     }
1489   else
1490     {
1491       if (result && result != error_mark_node)
1492         /* OK */;
1493       else if (!DECL_SAVED_TREE (fun))
1494         {
1495           /* When at_eof >= 2, cgraph has started throwing away
1496              DECL_SAVED_TREE, so fail quietly.  FIXME we get here because of
1497              late code generation for VEC_INIT_EXPR, which needs to be
1498              completely reconsidered.  */
1499           gcc_assert (at_eof >= 2 && ctx->quiet);
1500           *non_constant_p = true;
1501         }
1502       else
1503         {
1504           tree body, parms, res;
1505
1506           /* Reuse or create a new unshared copy of this function's body.  */
1507           tree copy = get_fundef_copy (fun);
1508           body = TREE_PURPOSE (copy);
1509           parms = TREE_VALUE (copy);
1510           res = TREE_TYPE (copy);
1511
1512           /* Associate the bindings with the remapped parms.  */
1513           tree bound = new_call.bindings;
1514           tree remapped = parms;
1515           while (bound)
1516             {
1517               tree oparm = TREE_PURPOSE (bound);
1518               tree arg = TREE_VALUE (bound);
1519               gcc_assert (DECL_NAME (remapped) == DECL_NAME (oparm));
1520               /* Don't share a CONSTRUCTOR that might be changed.  */
1521               arg = unshare_constructor (arg);
1522               ctx->values->put (remapped, arg);
1523               bound = TREE_CHAIN (bound);
1524               remapped = DECL_CHAIN (remapped);
1525             }
1526           /* Add the RESULT_DECL to the values map, too.  */
1527           tree slot = NULL_TREE;
1528           if (DECL_BY_REFERENCE (res))
1529             {
1530               slot = AGGR_INIT_EXPR_SLOT (t);
1531               tree addr = build_address (slot);
1532               addr = build_nop (TREE_TYPE (res), addr);
1533               ctx->values->put (res, addr);
1534               ctx->values->put (slot, NULL_TREE);
1535             }
1536           else
1537             ctx->values->put (res, NULL_TREE);
1538
1539           /* Track the callee's evaluated SAVE_EXPRs so that we can forget
1540              their values after the call.  */
1541           constexpr_ctx ctx_with_save_exprs = *ctx;
1542           hash_set<tree> save_exprs;
1543           ctx_with_save_exprs.save_exprs = &save_exprs;
1544
1545           tree jump_target = NULL_TREE;
1546           cxx_eval_constant_expression (&ctx_with_save_exprs, body,
1547                                         lval, non_constant_p, overflow_p,
1548                                         &jump_target);
1549
1550           if (DECL_CONSTRUCTOR_P (fun))
1551             /* This can be null for a subobject constructor call, in
1552                which case what we care about is the initialization
1553                side-effects rather than the value.  We could get at the
1554                value by evaluating *this, but we don't bother; there's
1555                no need to put such a call in the hash table.  */
1556             result = lval ? ctx->object : ctx->ctor;
1557           else if (VOID_TYPE_P (TREE_TYPE (res)))
1558             result = void_node;
1559           else
1560             {
1561               result = *ctx->values->get (slot ? slot : res);
1562               if (result == NULL_TREE && !*non_constant_p)
1563                 {
1564                   if (!ctx->quiet)
1565                     error ("constexpr call flows off the end "
1566                            "of the function");
1567                   *non_constant_p = true;
1568                 }
1569             }
1570
1571           /* Forget the saved values of the callee's SAVE_EXPRs.  */
1572           for (hash_set<tree>::iterator iter = save_exprs.begin();
1573                iter != save_exprs.end(); ++iter)
1574             ctx_with_save_exprs.values->remove (*iter);
1575
1576           /* Remove the parms/result from the values map.  Is it worth
1577              bothering to do this when the map itself is only live for
1578              one constexpr evaluation?  If so, maybe also clear out
1579              other vars from call, maybe in BIND_EXPR handling?  */
1580           ctx->values->remove (res);
1581           if (slot)
1582             ctx->values->remove (slot);
1583           for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
1584             ctx->values->remove (parm);
1585
1586           /* Make the unshared function copy we used available for re-use.  */
1587           save_fundef_copy (fun, copy);
1588         }
1589
1590       if (result == error_mark_node)
1591         *non_constant_p = true;
1592       if (*non_constant_p || *overflow_p)
1593         result = error_mark_node;
1594       else if (!result)
1595         result = void_node;
1596       if (entry)
1597         entry->result = result;
1598     }
1599
1600   pop_cx_call_context ();
1601   return unshare_constructor (result);
1602 }
1603
1604 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase.  */
1605
1606 bool
1607 reduced_constant_expression_p (tree t)
1608 {
1609   switch (TREE_CODE (t))
1610     {
1611     case PTRMEM_CST:
1612       /* Even if we can't lower this yet, it's constant.  */
1613       return true;
1614
1615     case CONSTRUCTOR:
1616       /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR.  */
1617       tree elt; unsigned HOST_WIDE_INT idx;
1618       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), idx, elt)
1619         if (!reduced_constant_expression_p (elt))
1620           return false;
1621       return true;
1622
1623     default:
1624       /* FIXME are we calling this too much?  */
1625       return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
1626     }
1627 }
1628
1629 /* Some expressions may have constant operands but are not constant
1630    themselves, such as 1/0.  Call this function (or rather, the macro
1631    following it) to check for that condition.
1632
1633    We only call this in places that require an arithmetic constant, not in
1634    places where we might have a non-constant expression that can be a
1635    component of a constant expression, such as the address of a constexpr
1636    variable that might be dereferenced later.  */
1637
1638 static bool
1639 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
1640                  bool *overflow_p)
1641 {
1642   if (!*non_constant_p && !reduced_constant_expression_p (t))
1643     {
1644       if (!allow_non_constant)
1645         error ("%q+E is not a constant expression", t);
1646       *non_constant_p = true;
1647     }
1648   if (TREE_OVERFLOW_P (t))
1649     {
1650       if (!allow_non_constant)
1651         {
1652           permerror (input_location, "overflow in constant expression");
1653           /* If we're being permissive (and are in an enforcing
1654              context), ignore the overflow.  */
1655           if (flag_permissive)
1656             return *non_constant_p;
1657         }
1658       *overflow_p = true;
1659     }
1660   return *non_constant_p;
1661 }
1662
1663 /* Check whether the shift operation with code CODE and type TYPE on LHS
1664    and RHS is undefined.  If it is, give an error with an explanation,
1665    and return true; return false otherwise.  */
1666
1667 static bool
1668 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
1669                         enum tree_code code, tree type, tree lhs, tree rhs)
1670 {
1671   if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
1672       || TREE_CODE (lhs) != INTEGER_CST
1673       || TREE_CODE (rhs) != INTEGER_CST)
1674     return false;
1675
1676   tree lhstype = TREE_TYPE (lhs);
1677   unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
1678
1679   /* [expr.shift] The behavior is undefined if the right operand
1680      is negative, or greater than or equal to the length in bits
1681      of the promoted left operand.  */
1682   if (tree_int_cst_sgn (rhs) == -1)
1683     {
1684       if (!ctx->quiet)
1685         permerror (loc, "right operand of shift expression %q+E is negative",
1686                    build2_loc (loc, code, type, lhs, rhs));
1687       return (!flag_permissive || ctx->quiet);
1688     }
1689   if (compare_tree_int (rhs, uprec) >= 0)
1690     {
1691       if (!ctx->quiet)
1692         permerror (loc, "right operand of shift expression %q+E is >= than "
1693                    "the precision of the left operand",
1694                    build2_loc (loc, code, type, lhs, rhs));
1695       return (!flag_permissive || ctx->quiet);
1696     }
1697
1698   /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
1699      if E1 has a signed type and non-negative value, and E1x2^E2 is
1700      representable in the corresponding unsigned type of the result type,
1701      then that value, converted to the result type, is the resulting value;
1702      otherwise, the behavior is undefined.  */
1703   if (code == LSHIFT_EXPR && !TYPE_UNSIGNED (lhstype)
1704       && (cxx_dialect >= cxx11))
1705     {
1706       if (tree_int_cst_sgn (lhs) == -1)
1707         {
1708           if (!ctx->quiet)
1709             permerror (loc,
1710                        "left operand of shift expression %q+E is negative",
1711                        build2_loc (loc, code, type, lhs, rhs));
1712           return (!flag_permissive || ctx->quiet);
1713         }
1714       /* For signed x << y the following:
1715          (unsigned) x >> ((prec (lhs) - 1) - y)
1716          if > 1, is undefined.  The right-hand side of this formula
1717          is the highest bit of the LHS that can be set (starting from 0),
1718          so that the shift doesn't overflow.  We then right-shift the LHS
1719          to see whether any other bit is set making the original shift
1720          undefined -- the result is not representable in the corresponding
1721          unsigned type.  */
1722       tree t = build_int_cst (unsigned_type_node, uprec - 1);
1723       t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
1724       tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
1725       t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
1726       if (tree_int_cst_lt (integer_one_node, t))
1727         {
1728           if (!ctx->quiet)
1729             permerror (loc, "shift expression %q+E overflows",
1730                        build2_loc (loc, code, type, lhs, rhs));
1731           return (!flag_permissive || ctx->quiet);
1732         }
1733     }
1734   return false;
1735 }
1736
1737 /* Subroutine of cxx_eval_constant_expression.
1738    Attempt to reduce the unary expression tree T to a compile time value.
1739    If successful, return the value.  Otherwise issue a diagnostic
1740    and return error_mark_node.  */
1741
1742 static tree
1743 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
1744                            bool /*lval*/,
1745                            bool *non_constant_p, bool *overflow_p)
1746 {
1747   tree r;
1748   tree orig_arg = TREE_OPERAND (t, 0);
1749   tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
1750                                            non_constant_p, overflow_p);
1751   VERIFY_CONSTANT (arg);
1752   location_t loc = EXPR_LOCATION (t);
1753   enum tree_code code = TREE_CODE (t);
1754   tree type = TREE_TYPE (t);
1755   r = fold_unary_loc (loc, code, type, arg);
1756   if (r == NULL_TREE)
1757     {
1758       if (arg == orig_arg)
1759         r = t;
1760       else
1761         r = build1_loc (loc, code, type, arg);
1762     }
1763   VERIFY_CONSTANT (r);
1764   return r;
1765 }
1766
1767 /* Helper function for cxx_eval_binary_expression.  Try to optimize
1768    original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
1769    generic folding should be used.  */
1770
1771 static tree
1772 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
1773                                   tree lhs, tree rhs, bool *non_constant_p,
1774                                   bool *overflow_p)
1775 {
1776   STRIP_NOPS (lhs);
1777   if (TREE_CODE (lhs) != ADDR_EXPR)
1778     return NULL_TREE;
1779
1780   lhs = TREE_OPERAND (lhs, 0);
1781
1782   /* &A[i] p+ j => &A[i + j] */
1783   if (TREE_CODE (lhs) == ARRAY_REF
1784       && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
1785       && TREE_CODE (rhs) == INTEGER_CST
1786       && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
1787       && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
1788     {
1789       tree orig_type = TREE_TYPE (t);
1790       location_t loc = EXPR_LOCATION (t);
1791       tree type = TREE_TYPE (lhs);
1792
1793       t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
1794       tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
1795       nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
1796                                             overflow_p);
1797       if (*non_constant_p)
1798         return NULL_TREE;
1799       /* Don't fold an out-of-bound access.  */
1800       if (!tree_int_cst_le (t, nelts))
1801         return NULL_TREE;
1802       rhs = cp_fold_convert (ssizetype, rhs);
1803       /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
1804          constexpr int A[1]; ... (char *)&A[0] + 1 */
1805       if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
1806                                            rhs, TYPE_SIZE_UNIT (type))))
1807         return NULL_TREE;
1808       /* Make sure to treat the second operand of POINTER_PLUS_EXPR
1809          as signed.  */
1810       rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
1811                              TYPE_SIZE_UNIT (type));
1812       t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
1813       t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
1814                       t, NULL_TREE, NULL_TREE);
1815       t = cp_build_addr_expr (t, tf_warning_or_error);
1816       t = cp_fold_convert (orig_type, t);
1817       return cxx_eval_constant_expression (ctx, t, /*lval*/false,
1818                                            non_constant_p, overflow_p);
1819     }
1820
1821   return NULL_TREE;
1822 }
1823
1824 /* Subroutine of cxx_eval_constant_expression.
1825    Like cxx_eval_unary_expression, except for binary expressions.  */
1826
1827 static tree
1828 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
1829                             bool /*lval*/,
1830                             bool *non_constant_p, bool *overflow_p)
1831 {
1832   tree r = NULL_TREE;
1833   tree orig_lhs = TREE_OPERAND (t, 0);
1834   tree orig_rhs = TREE_OPERAND (t, 1);
1835   tree lhs, rhs;
1836   lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
1837                                       non_constant_p, overflow_p);
1838   /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
1839      subtraction.  */
1840   if (*non_constant_p)
1841     return t;
1842   rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
1843                                       non_constant_p, overflow_p);
1844   if (*non_constant_p)
1845     return t;
1846
1847   location_t loc = EXPR_LOCATION (t);
1848   enum tree_code code = TREE_CODE (t);
1849   tree type = TREE_TYPE (t);
1850
1851   if (code == EQ_EXPR || code == NE_EXPR)
1852     {
1853       bool is_code_eq = (code == EQ_EXPR);
1854
1855       if (TREE_CODE (lhs) == PTRMEM_CST
1856           && TREE_CODE (rhs) == PTRMEM_CST)
1857         r = constant_boolean_node (cp_tree_equal (lhs, rhs) == is_code_eq,
1858                                    type);
1859       else if ((TREE_CODE (lhs) == PTRMEM_CST
1860                 || TREE_CODE (rhs) == PTRMEM_CST)
1861                && (null_member_pointer_value_p (lhs)
1862                    || null_member_pointer_value_p (rhs)))
1863         r = constant_boolean_node (!is_code_eq, type);
1864       else if (TREE_CODE (lhs) == PTRMEM_CST)
1865         lhs = cplus_expand_constant (lhs);
1866       else if (TREE_CODE (rhs) == PTRMEM_CST)
1867         rhs = cplus_expand_constant (rhs);
1868     }
1869   else if (code == POINTER_PLUS_EXPR)
1870     r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
1871                                           overflow_p);
1872
1873   if (r == NULL_TREE)
1874     r = fold_binary_loc (loc, code, type, lhs, rhs);
1875
1876   if (r == NULL_TREE)
1877     {
1878       if (lhs == orig_lhs && rhs == orig_rhs)
1879         r = t;
1880       else
1881         r = build2_loc (loc, code, type, lhs, rhs);
1882     }
1883   else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
1884     *non_constant_p = true;
1885   /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
1886      a local array in a constexpr function.  */
1887   bool ptr = POINTER_TYPE_P (TREE_TYPE (lhs));
1888   if (!ptr)
1889     VERIFY_CONSTANT (r);
1890   return r;
1891 }
1892
1893 /* Subroutine of cxx_eval_constant_expression.
1894    Attempt to evaluate condition expressions.  Dead branches are not
1895    looked into.  */
1896
1897 static tree
1898 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
1899                                  bool lval,
1900                                  bool *non_constant_p, bool *overflow_p,
1901                                  tree *jump_target)
1902 {
1903   tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
1904                                            /*lval*/false,
1905                                            non_constant_p, overflow_p);
1906   VERIFY_CONSTANT (val);
1907   /* Don't VERIFY_CONSTANT the other operands.  */
1908   if (integer_zerop (val))
1909     return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
1910                                          lval,
1911                                          non_constant_p, overflow_p,
1912                                          jump_target);
1913   return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
1914                                        lval,
1915                                        non_constant_p, overflow_p,
1916                                        jump_target);
1917 }
1918
1919 /* Returns less than, equal to, or greater than zero if KEY is found to be
1920    less than, to match, or to be greater than the constructor_elt's INDEX.  */
1921
1922 static int
1923 array_index_cmp (tree key, tree index)
1924 {
1925   gcc_assert (TREE_CODE (key) == INTEGER_CST);
1926
1927   switch (TREE_CODE (index))
1928     {
1929     case INTEGER_CST:
1930       return tree_int_cst_compare (key, index);
1931     case RANGE_EXPR:
1932       {
1933         tree lo = TREE_OPERAND (index, 0);
1934         tree hi = TREE_OPERAND (index, 1);
1935         if (tree_int_cst_lt (key, lo))
1936           return -1;
1937         else if (tree_int_cst_lt (hi, key))
1938           return 1;
1939         else
1940           return 0;
1941       }
1942     default:
1943       gcc_unreachable ();
1944     }
1945 }
1946
1947 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
1948    if none.  If INSERT is true, insert a matching element rather than fail.  */
1949
1950 static HOST_WIDE_INT
1951 find_array_ctor_elt (tree ary, tree dindex, bool insert = false)
1952 {
1953   if (tree_int_cst_sgn (dindex) < 0)
1954     return -1;
1955
1956   unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
1957   vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
1958   unsigned HOST_WIDE_INT len = vec_safe_length (elts);
1959
1960   unsigned HOST_WIDE_INT end = len;
1961   unsigned HOST_WIDE_INT begin = 0;
1962
1963   /* If the last element of the CONSTRUCTOR has its own index, we can assume
1964      that the same is true of the other elements and index directly.  */
1965   if (end > 0)
1966     {
1967       tree cindex = (*elts)[end-1].index;
1968       if (TREE_CODE (cindex) == INTEGER_CST
1969           && compare_tree_int (cindex, end-1) == 0)
1970         {
1971           if (i < end)
1972             return i;
1973           else
1974             begin = end;
1975         }
1976     }
1977
1978   /* Otherwise, find a matching index by means of a binary search.  */
1979   while (begin != end)
1980     {
1981       unsigned HOST_WIDE_INT middle = (begin + end) / 2;
1982       constructor_elt &elt = (*elts)[middle];
1983       tree idx = elt.index;
1984
1985       int cmp = array_index_cmp (dindex, idx);
1986       if (cmp < 0)
1987         end = middle;
1988       else if (cmp > 0)
1989         begin = middle + 1;
1990       else
1991         {
1992           if (insert && TREE_CODE (idx) == RANGE_EXPR)
1993             {
1994               /* We need to split the range.  */
1995               constructor_elt e;
1996               tree lo = TREE_OPERAND (idx, 0);
1997               tree hi = TREE_OPERAND (idx, 1);
1998               if (tree_int_cst_lt (lo, dindex))
1999                 {
2000                   /* There are still some lower elts; shorten the range.  */
2001                   tree new_hi = int_const_binop (MINUS_EXPR, dindex,
2002                                                  size_one_node);
2003                   if (tree_int_cst_equal (lo, new_hi))
2004                     /* Only one element left, no longer a range.  */
2005                     elt.index = lo;
2006                   else
2007                     TREE_OPERAND (idx, 1) = new_hi;
2008                   /* Append the element we want to insert.  */
2009                   ++middle;
2010                   e.index = dindex;
2011                   e.value = unshare_constructor (elt.value);
2012                   vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
2013                 }
2014               else
2015                 /* No lower elts, the range elt is now ours.  */
2016                 elt.index = dindex;
2017
2018               if (tree_int_cst_lt (dindex, hi))
2019                 {
2020                   /* There are still some higher elts; append a range.  */
2021                   tree new_lo = int_const_binop (PLUS_EXPR, dindex,
2022                                                  size_one_node);
2023                   if (tree_int_cst_equal (new_lo, hi))
2024                     e.index = hi;
2025                   else
2026                     e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
2027                   e.value = unshare_constructor (elt.value);
2028                   vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle+1, e);
2029                 }
2030             }
2031           return middle;
2032         }
2033     }
2034
2035   if (insert)
2036     {
2037       constructor_elt e = { dindex, NULL_TREE };
2038       vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
2039       return end;
2040     }
2041
2042   return -1;
2043 }
2044
2045 /* Under the control of CTX, issue a detailed diagnostic for
2046    an out-of-bounds subscript INDEX into the expression ARRAY.  */
2047
2048 static void
2049 diag_array_subscript (const constexpr_ctx *ctx, tree array, tree index)
2050 {
2051   if (!ctx->quiet)
2052     {
2053       tree arraytype = TREE_TYPE (array);
2054
2055       /* Convert the unsigned array subscript to a signed integer to avoid
2056          printing huge numbers for small negative values.  */
2057       tree sidx = fold_convert (ssizetype, index);
2058       if (DECL_P (array))
2059         {
2060           error ("array subscript value %qE is outside the bounds "
2061                  "of array %qD of type %qT", sidx, array, arraytype);
2062           inform (DECL_SOURCE_LOCATION (array), "declared here");
2063         }
2064       else
2065         error ("array subscript value %qE is outside the bounds "
2066                "of array type %qT", sidx, arraytype);
2067     }
2068 }
2069
2070 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
2071    STRING_CST STRING.  */
2072
2073 static tree
2074 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
2075 {
2076   tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
2077   tree r;
2078
2079   if (chars_per_elt == 1)
2080     r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
2081   else
2082     {
2083       const unsigned char *ptr
2084         = ((const unsigned char *)TREE_STRING_POINTER (string)
2085            + index * chars_per_elt);
2086       r = native_interpret_expr (type, ptr, chars_per_elt);
2087     }
2088   return r;
2089 }
2090
2091 /* Subroutine of cxx_eval_constant_expression.
2092    Attempt to reduce a reference to an array slot.  */
2093
2094 static tree
2095 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
2096                           bool lval,
2097                           bool *non_constant_p, bool *overflow_p)
2098 {
2099   tree oldary = TREE_OPERAND (t, 0);
2100   tree ary = cxx_eval_constant_expression (ctx, oldary,
2101                                            lval,
2102                                            non_constant_p, overflow_p);
2103   tree index, oldidx;
2104   HOST_WIDE_INT i;
2105   tree elem_type;
2106   unsigned len, elem_nchars = 1;
2107   if (*non_constant_p)
2108     return t;
2109   oldidx = TREE_OPERAND (t, 1);
2110   index = cxx_eval_constant_expression (ctx, oldidx,
2111                                         false,
2112                                         non_constant_p, overflow_p);
2113   VERIFY_CONSTANT (index);
2114   if (lval && ary == oldary && index == oldidx)
2115     return t;
2116   else if (lval)
2117     return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
2118   elem_type = TREE_TYPE (TREE_TYPE (ary));
2119   if (TREE_CODE (ary) == CONSTRUCTOR)
2120     len = CONSTRUCTOR_NELTS (ary);
2121   else if (TREE_CODE (ary) == STRING_CST)
2122     {
2123       elem_nchars = (TYPE_PRECISION (elem_type)
2124                      / TYPE_PRECISION (char_type_node));
2125       len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
2126     }
2127   else
2128     {
2129       /* We can't do anything with other tree codes, so use
2130          VERIFY_CONSTANT to complain and fail.  */
2131       VERIFY_CONSTANT (ary);
2132       gcc_unreachable ();
2133     }
2134
2135   if (!tree_fits_shwi_p (index)
2136       || (i = tree_to_shwi (index)) < 0)
2137     {
2138       diag_array_subscript (ctx, ary, index);
2139       *non_constant_p = true;
2140       return t;
2141     }
2142
2143   tree nelts = array_type_nelts_top (TREE_TYPE (ary));
2144   /* For VLAs, the number of elements won't be an integer constant.  */
2145   nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
2146                                         overflow_p);
2147   VERIFY_CONSTANT (nelts);
2148   if (!tree_int_cst_lt (index, nelts))
2149     {
2150       diag_array_subscript (ctx, ary, index);
2151       *non_constant_p = true;
2152       return t;
2153     }
2154
2155   bool found;
2156   if (TREE_CODE (ary) == CONSTRUCTOR)
2157     {
2158       HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
2159       found = (ix >= 0);
2160       if (found)
2161         i = ix;
2162     }
2163   else
2164     found = (i < len);
2165
2166   if (found)
2167     {
2168       tree r;
2169       if (TREE_CODE (ary) == CONSTRUCTOR)
2170         r = (*CONSTRUCTOR_ELTS (ary))[i].value;
2171       else
2172         r = extract_string_elt (ary, elem_nchars, i);
2173
2174       if (r)
2175         /* Don't VERIFY_CONSTANT here.  */
2176         return r;
2177
2178       /* Otherwise the element doesn't have a value yet.  */
2179     }
2180
2181   /* Not found.  */
2182
2183   if (TREE_CODE (ary) == CONSTRUCTOR
2184       && CONSTRUCTOR_NO_IMPLICIT_ZERO (ary))
2185     {
2186       /* 'ary' is part of the aggregate initializer we're currently
2187          building; if there's no initializer for this element yet,
2188          that's an error.  */
2189       if (!ctx->quiet)
2190         error ("accessing uninitialized array element");
2191       *non_constant_p = true;
2192       return t;
2193     }
2194
2195   /* If it's within the array bounds but doesn't have an explicit
2196      initializer, it's value-initialized.  */
2197   tree val = build_value_init (elem_type, tf_warning_or_error);
2198   return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
2199                                        overflow_p);
2200 }
2201
2202 /* Subroutine of cxx_eval_constant_expression.
2203    Attempt to reduce a field access of a value of class type.  */
2204
2205 static tree
2206 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
2207                               bool lval,
2208                               bool *non_constant_p, bool *overflow_p)
2209 {
2210   unsigned HOST_WIDE_INT i;
2211   tree field;
2212   tree value;
2213   tree part = TREE_OPERAND (t, 1);
2214   tree orig_whole = TREE_OPERAND (t, 0);
2215   tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2216                                              lval,
2217                                              non_constant_p, overflow_p);
2218   if (TREE_CODE (whole) == PTRMEM_CST)
2219     whole = cplus_expand_constant (whole);
2220   if (whole == orig_whole)
2221     return t;
2222   if (lval)
2223     return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
2224                         whole, part, NULL_TREE);
2225   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2226      CONSTRUCTOR.  */
2227   if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
2228     {
2229       if (!ctx->quiet)
2230         error ("%qE is not a constant expression", orig_whole);
2231       *non_constant_p = true;
2232     }
2233   if (DECL_MUTABLE_P (part))
2234     {
2235       if (!ctx->quiet)
2236         error ("mutable %qD is not usable in a constant expression", part);
2237       *non_constant_p = true;
2238     }
2239   if (*non_constant_p)
2240     return t;
2241   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2242     {
2243       if (field == part)
2244         {
2245           if (value)
2246             return value;
2247           else
2248             /* We're in the middle of initializing it.  */
2249             break;
2250         }
2251     }
2252   if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
2253       && CONSTRUCTOR_NELTS (whole) > 0)
2254     {
2255       /* DR 1188 says we don't have to deal with this.  */
2256       if (!ctx->quiet)
2257         error ("accessing %qD member instead of initialized %qD member in "
2258                "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
2259       *non_constant_p = true;
2260       return t;
2261     }
2262
2263   /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
2264      classes never get represented; throw together a value now.  */
2265   if (is_really_empty_class (TREE_TYPE (t)))
2266     return build_constructor (TREE_TYPE (t), NULL);
2267
2268   if (CONSTRUCTOR_NO_IMPLICIT_ZERO (whole))
2269     {
2270       /* 'whole' is part of the aggregate initializer we're currently
2271          building; if there's no initializer for this member yet, that's an
2272          error.  */
2273       if (!ctx->quiet)
2274         error ("accessing uninitialized member %qD", part);
2275       *non_constant_p = true;
2276       return t;
2277     }
2278
2279   /* If there's no explicit init for this field, it's value-initialized.  */
2280   value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
2281   return cxx_eval_constant_expression (ctx, value,
2282                                        lval,
2283                                        non_constant_p, overflow_p);
2284 }
2285
2286 /* Subroutine of cxx_eval_constant_expression.
2287    Attempt to reduce a field access of a value of class type that is
2288    expressed as a BIT_FIELD_REF.  */
2289
2290 static tree
2291 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
2292                         bool lval,
2293                         bool *non_constant_p, bool *overflow_p)
2294 {
2295   tree orig_whole = TREE_OPERAND (t, 0);
2296   tree retval, fldval, utype, mask;
2297   bool fld_seen = false;
2298   HOST_WIDE_INT istart, isize;
2299   tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2300                                              lval,
2301                                              non_constant_p, overflow_p);
2302   tree start, field, value;
2303   unsigned HOST_WIDE_INT i;
2304
2305   if (whole == orig_whole)
2306     return t;
2307   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2308      CONSTRUCTOR.  */
2309   if (!*non_constant_p
2310       && TREE_CODE (whole) != VECTOR_CST
2311       && TREE_CODE (whole) != CONSTRUCTOR)
2312     {
2313       if (!ctx->quiet)
2314         error ("%qE is not a constant expression", orig_whole);
2315       *non_constant_p = true;
2316     }
2317   if (*non_constant_p)
2318     return t;
2319
2320   if (TREE_CODE (whole) == VECTOR_CST)
2321     return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
2322                          TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
2323
2324   start = TREE_OPERAND (t, 2);
2325   istart = tree_to_shwi (start);
2326   isize = tree_to_shwi (TREE_OPERAND (t, 1));
2327   utype = TREE_TYPE (t);
2328   if (!TYPE_UNSIGNED (utype))
2329     utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
2330   retval = build_int_cst (utype, 0);
2331   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2332     {
2333       tree bitpos = bit_position (field);
2334       if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
2335         return value;
2336       if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
2337           && TREE_CODE (value) == INTEGER_CST
2338           && tree_fits_shwi_p (bitpos)
2339           && tree_fits_shwi_p (DECL_SIZE (field)))
2340         {
2341           HOST_WIDE_INT bit = tree_to_shwi (bitpos);
2342           HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
2343           HOST_WIDE_INT shift;
2344           if (bit >= istart && bit + sz <= istart + isize)
2345             {
2346               fldval = fold_convert (utype, value);
2347               mask = build_int_cst_type (utype, -1);
2348               mask = fold_build2 (LSHIFT_EXPR, utype, mask,
2349                                   size_int (TYPE_PRECISION (utype) - sz));
2350               mask = fold_build2 (RSHIFT_EXPR, utype, mask,
2351                                   size_int (TYPE_PRECISION (utype) - sz));
2352               fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
2353               shift = bit - istart;
2354               if (BYTES_BIG_ENDIAN)
2355                 shift = TYPE_PRECISION (utype) - shift - sz;
2356               fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
2357                                     size_int (shift));
2358               retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
2359               fld_seen = true;
2360             }
2361         }
2362     }
2363   if (fld_seen)
2364     return fold_convert (TREE_TYPE (t), retval);
2365   gcc_unreachable ();
2366   return error_mark_node;
2367 }
2368
2369 /* Subroutine of cxx_eval_constant_expression.
2370    Evaluate a short-circuited logical expression T in the context
2371    of a given constexpr CALL.  BAILOUT_VALUE is the value for
2372    early return.  CONTINUE_VALUE is used here purely for
2373    sanity check purposes.  */
2374
2375 static tree
2376 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
2377                              tree bailout_value, tree continue_value,
2378                              bool lval,
2379                              bool *non_constant_p, bool *overflow_p)
2380 {
2381   tree r;
2382   tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2383                                            lval,
2384                                            non_constant_p, overflow_p);
2385   VERIFY_CONSTANT (lhs);
2386   if (tree_int_cst_equal (lhs, bailout_value))
2387     return lhs;
2388   gcc_assert (tree_int_cst_equal (lhs, continue_value));
2389   r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2390                                     lval, non_constant_p,
2391                                     overflow_p);
2392   VERIFY_CONSTANT (r);
2393   return r;
2394 }
2395
2396 /* REF is a COMPONENT_REF designating a particular field.  V is a vector of
2397    CONSTRUCTOR elements to initialize (part of) an object containing that
2398    field.  Return a pointer to the constructor_elt corresponding to the
2399    initialization of the field.  */
2400
2401 static constructor_elt *
2402 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
2403 {
2404   tree aggr = TREE_OPERAND (ref, 0);
2405   tree field = TREE_OPERAND (ref, 1);
2406   HOST_WIDE_INT i;
2407   constructor_elt *ce;
2408
2409   gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
2410
2411   if (TREE_CODE (aggr) == COMPONENT_REF)
2412     {
2413       constructor_elt *base_ce
2414         = base_field_constructor_elt (v, aggr);
2415       v = CONSTRUCTOR_ELTS (base_ce->value);
2416     }
2417
2418   for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
2419     if (ce->index == field)
2420       return ce;
2421
2422   gcc_unreachable ();
2423   return NULL;
2424 }
2425
2426 /* Some of the expressions fed to the constexpr mechanism are calls to
2427    constructors, which have type void.  In that case, return the type being
2428    initialized by the constructor.  */
2429
2430 static tree
2431 initialized_type (tree t)
2432 {
2433   if (TYPE_P (t))
2434     return t;
2435   tree type = cv_unqualified (TREE_TYPE (t));
2436   if (TREE_CODE (t) == CALL_EXPR || TREE_CODE (t) == AGGR_INIT_EXPR)
2437     {
2438       /* A constructor call has void type, so we need to look deeper.  */
2439       tree fn = get_function_named_in_call (t);
2440       if (fn && TREE_CODE (fn) == FUNCTION_DECL
2441           && DECL_CXX_CONSTRUCTOR_P (fn))
2442         type = DECL_CONTEXT (fn);
2443     }
2444   return type;
2445 }
2446
2447 /* We're about to initialize element INDEX of an array or class from VALUE.
2448    Set up NEW_CTX appropriately by adjusting .object to refer to the
2449    subobject and creating a new CONSTRUCTOR if the element is itself
2450    a class or array.  */
2451
2452 static void
2453 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
2454                tree index, tree &value)
2455 {
2456   new_ctx = *ctx;
2457
2458   if (index && TREE_CODE (index) != INTEGER_CST
2459       && TREE_CODE (index) != FIELD_DECL)
2460     /* This won't have an element in the new CONSTRUCTOR.  */
2461     return;
2462
2463   tree type = initialized_type (value);
2464   if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
2465     /* A non-aggregate member doesn't get its own CONSTRUCTOR.  */
2466     return;
2467
2468   /* The sub-aggregate initializer might contain a placeholder;
2469      update object to refer to the subobject and ctor to refer to
2470      the (newly created) sub-initializer.  */
2471   if (ctx->object)
2472     new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
2473   tree elt = build_constructor (type, NULL);
2474   CONSTRUCTOR_NO_IMPLICIT_ZERO (elt) = true;
2475   new_ctx.ctor = elt;
2476
2477   if (TREE_CODE (value) == TARGET_EXPR)
2478     /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR.  */
2479     value = TARGET_EXPR_INITIAL (value);
2480 }
2481
2482 /* We're about to process an initializer for a class or array TYPE.  Make
2483    sure that CTX is set up appropriately.  */
2484
2485 static void
2486 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
2487 {
2488   /* We don't bother building a ctor for an empty base subobject.  */
2489   if (is_empty_class (type))
2490     return;
2491
2492   /* We're in the middle of an initializer that might involve placeholders;
2493      our caller should have created a CONSTRUCTOR for us to put the
2494      initializer into.  We will either return that constructor or T.  */
2495   gcc_assert (ctx->ctor);
2496   gcc_assert (same_type_ignoring_top_level_qualifiers_p
2497               (type, TREE_TYPE (ctx->ctor)));
2498   /* We used to check that ctx->ctor was empty, but that isn't the case when
2499      the object is zero-initialized before calling the constructor.  */
2500   if (ctx->object)
2501     gcc_assert (same_type_ignoring_top_level_qualifiers_p
2502                 (type, TREE_TYPE (ctx->object)));
2503   gcc_assert (!ctx->object || !DECL_P (ctx->object)
2504               || *(ctx->values->get (ctx->object)) == ctx->ctor);
2505 }
2506
2507 /* Subroutine of cxx_eval_constant_expression.
2508    The expression tree T denotes a C-style array or a C-style
2509    aggregate.  Reduce it to a constant expression.  */
2510
2511 static tree
2512 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
2513                          bool lval,
2514                          bool *non_constant_p, bool *overflow_p)
2515 {
2516   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
2517   bool changed = false;
2518   gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
2519   tree type = TREE_TYPE (t);
2520
2521   constexpr_ctx new_ctx;
2522   if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
2523     {
2524       /* We don't really need the ctx->ctor business for a PMF or
2525          vector, but it's simpler to use the same code.  */
2526       new_ctx = *ctx;
2527       new_ctx.ctor = build_constructor (type, NULL);
2528       new_ctx.object = NULL_TREE;
2529       ctx = &new_ctx;
2530     };
2531   verify_ctor_sanity (ctx, type);
2532   vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2533   vec_alloc (*p, vec_safe_length (v));
2534
2535   unsigned i;
2536   tree index, value;
2537   bool constant_p = true;
2538   bool side_effects_p = false;
2539   FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
2540     {
2541       tree orig_value = value;
2542       init_subob_ctx (ctx, new_ctx, index, value);
2543       if (new_ctx.ctor != ctx->ctor)
2544         /* If we built a new CONSTRUCTOR, attach it now so that other
2545            initializers can refer to it.  */
2546         CONSTRUCTOR_APPEND_ELT (*p, index, new_ctx.ctor);
2547       tree elt = cxx_eval_constant_expression (&new_ctx, value,
2548                                                lval,
2549                                                non_constant_p, overflow_p);
2550       /* Don't VERIFY_CONSTANT here.  */
2551       if (ctx->quiet && *non_constant_p)
2552         break;
2553       if (elt != orig_value)
2554         changed = true;
2555
2556       if (!TREE_CONSTANT (elt))
2557         constant_p = false;
2558       if (TREE_SIDE_EFFECTS (elt))
2559         side_effects_p = true;
2560       if (index && TREE_CODE (index) == COMPONENT_REF)
2561         {
2562           /* This is an initialization of a vfield inside a base
2563              subaggregate that we already initialized; push this
2564              initialization into the previous initialization.  */
2565           constructor_elt *inner = base_field_constructor_elt (*p, index);
2566           inner->value = elt;
2567           changed = true;
2568         }
2569       else if (index
2570                && (TREE_CODE (index) == NOP_EXPR
2571                    || TREE_CODE (index) == POINTER_PLUS_EXPR))
2572         {
2573           /* This is an initializer for an empty base; now that we've
2574              checked that it's constant, we can ignore it.  */
2575           gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
2576           changed = true;
2577         }
2578       else if (new_ctx.ctor != ctx->ctor)
2579         {
2580           /* We appended this element above; update the value.  */
2581           gcc_assert ((*p)->last().index == index);
2582           (*p)->last().value = elt;
2583         }
2584       else
2585         CONSTRUCTOR_APPEND_ELT (*p, index, elt);
2586     }
2587   if (*non_constant_p || !changed)
2588     return t;
2589   t = ctx->ctor;
2590   /* We're done building this CONSTRUCTOR, so now we can interpret an
2591      element without an explicit initializer as value-initialized.  */
2592   CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
2593   TREE_CONSTANT (t) = constant_p;
2594   TREE_SIDE_EFFECTS (t) = side_effects_p;
2595   if (VECTOR_TYPE_P (type))
2596     t = fold (t);
2597   return t;
2598 }
2599
2600 /* Subroutine of cxx_eval_constant_expression.
2601    The expression tree T is a VEC_INIT_EXPR which denotes the desired
2602    initialization of a non-static data member of array type.  Reduce it to a
2603    CONSTRUCTOR.
2604
2605    Note that apart from value-initialization (when VALUE_INIT is true),
2606    this is only intended to support value-initialization and the
2607    initializations done by defaulted constructors for classes with
2608    non-static data members of array type.  In this case, VEC_INIT_EXPR_INIT
2609    will either be NULL_TREE for the default constructor, or a COMPONENT_REF
2610    for the copy/move constructor.  */
2611
2612 static tree
2613 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
2614                      bool value_init, bool lval,
2615                      bool *non_constant_p, bool *overflow_p)
2616 {
2617   tree elttype = TREE_TYPE (atype);
2618   unsigned HOST_WIDE_INT max = tree_to_uhwi (array_type_nelts_top (atype));
2619   verify_ctor_sanity (ctx, atype);
2620   vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2621   vec_alloc (*p, max + 1);
2622   bool pre_init = false;
2623   unsigned HOST_WIDE_INT i;
2624
2625   /* For the default constructor, build up a call to the default
2626      constructor of the element type.  We only need to handle class types
2627      here, as for a constructor to be constexpr, all members must be
2628      initialized, which for a defaulted default constructor means they must
2629      be of a class type with a constexpr default constructor.  */
2630   if (TREE_CODE (elttype) == ARRAY_TYPE)
2631     /* We only do this at the lowest level.  */;
2632   else if (value_init)
2633     {
2634       init = build_value_init (elttype, tf_warning_or_error);
2635       pre_init = true;
2636     }
2637   else if (!init)
2638     {
2639       vec<tree, va_gc> *argvec = make_tree_vector ();
2640       init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2641                                         &argvec, elttype, LOOKUP_NORMAL,
2642                                         tf_warning_or_error);
2643       release_tree_vector (argvec);
2644       init = build_aggr_init_expr (TREE_TYPE (init), init);
2645       pre_init = true;
2646     }
2647
2648   for (i = 0; i < max; ++i)
2649     {
2650       tree idx = build_int_cst (size_type_node, i);
2651       tree eltinit;
2652       bool reuse = false;
2653       constexpr_ctx new_ctx;
2654       init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
2655       if (new_ctx.ctor != ctx->ctor)
2656         CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
2657       if (TREE_CODE (elttype) == ARRAY_TYPE)
2658         {
2659           /* A multidimensional array; recurse.  */
2660           if (value_init || init == NULL_TREE)
2661             {
2662               eltinit = NULL_TREE;
2663               reuse = i == 0;
2664             }
2665           else
2666             eltinit = cp_build_array_ref (input_location, init, idx,
2667                                           tf_warning_or_error);
2668           eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
2669                                          lval,
2670                                          non_constant_p, overflow_p);
2671         }
2672       else if (pre_init)
2673         {
2674           /* Initializing an element using value or default initialization
2675              we just pre-built above.  */
2676           eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
2677                                                   non_constant_p, overflow_p);
2678           reuse = i == 0;
2679         }
2680       else
2681         {
2682           /* Copying an element.  */
2683           gcc_assert (same_type_ignoring_top_level_qualifiers_p
2684                       (atype, TREE_TYPE (init)));
2685           eltinit = cp_build_array_ref (input_location, init, idx,
2686                                         tf_warning_or_error);
2687           if (!real_lvalue_p (init))
2688             eltinit = move (eltinit);
2689           eltinit = force_rvalue (eltinit, tf_warning_or_error);
2690           eltinit = (cxx_eval_constant_expression
2691                      (&new_ctx, eltinit, lval,
2692                       non_constant_p, overflow_p));
2693         }
2694       if (*non_constant_p && !ctx->quiet)
2695         break;
2696       if (new_ctx.ctor != ctx->ctor)
2697         {
2698           /* We appended this element above; update the value.  */
2699           gcc_assert ((*p)->last().index == idx);
2700           (*p)->last().value = eltinit;
2701         }
2702       else
2703         CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
2704       /* Reuse the result of cxx_eval_constant_expression call
2705           from the first iteration to all others if it is a constant
2706           initializer that doesn't require relocations.  */
2707       if (reuse
2708           && max > 1
2709           && (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
2710               == null_pointer_node))
2711         {
2712           if (new_ctx.ctor != ctx->ctor)
2713             eltinit = new_ctx.ctor;
2714           for (i = 1; i < max; ++i)
2715             {
2716               idx = build_int_cst (size_type_node, i);
2717               CONSTRUCTOR_APPEND_ELT (*p, idx, unshare_constructor (eltinit));
2718             }
2719           break;
2720         }
2721     }
2722
2723   if (!*non_constant_p)
2724     {
2725       init = ctx->ctor;
2726       CONSTRUCTOR_NO_IMPLICIT_ZERO (init) = false;
2727     }
2728   return init;
2729 }
2730
2731 static tree
2732 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
2733                    bool lval,
2734                    bool *non_constant_p, bool *overflow_p)
2735 {
2736   tree atype = TREE_TYPE (t);
2737   tree init = VEC_INIT_EXPR_INIT (t);
2738   tree r = cxx_eval_vec_init_1 (ctx, atype, init,
2739                                 VEC_INIT_EXPR_VALUE_INIT (t),
2740                                 lval, non_constant_p, overflow_p);
2741   if (*non_constant_p)
2742     return t;
2743   else
2744     return r;
2745 }
2746
2747 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
2748    match.  We want to be less strict for simple *& folding; if we have a
2749    non-const temporary that we access through a const pointer, that should
2750    work.  We handle this here rather than change fold_indirect_ref_1
2751    because we're dealing with things like ADDR_EXPR of INTEGER_CST which
2752    don't really make sense outside of constant expression evaluation.  Also
2753    we want to allow folding to COMPONENT_REF, which could cause trouble
2754    with TBAA in fold_indirect_ref_1.
2755
2756    Try to keep this function synced with fold_indirect_ref_1.  */
2757
2758 static tree
2759 cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
2760 {
2761   tree sub, subtype;
2762
2763   sub = op0;
2764   STRIP_NOPS (sub);
2765   subtype = TREE_TYPE (sub);
2766   if (!POINTER_TYPE_P (subtype))
2767     return NULL_TREE;
2768
2769   if (TREE_CODE (sub) == ADDR_EXPR)
2770     {
2771       tree op = TREE_OPERAND (sub, 0);
2772       tree optype = TREE_TYPE (op);
2773
2774       /* *&CONST_DECL -> to the value of the const decl.  */
2775       if (TREE_CODE (op) == CONST_DECL)
2776         return DECL_INITIAL (op);
2777       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
2778       if (same_type_ignoring_top_level_qualifiers_p (optype, type)
2779           /* Also handle the case where the desired type is an array of unknown
2780              bounds because the variable has had its bounds deduced since the
2781              ADDR_EXPR was created.  */
2782           || (TREE_CODE (type) == ARRAY_TYPE
2783               && TREE_CODE (optype) == ARRAY_TYPE
2784               && TYPE_DOMAIN (type) == NULL_TREE
2785               && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (optype),
2786                                                             TREE_TYPE (type))))
2787         {
2788           tree fop = fold_read_from_constant_string (op);
2789           if (fop)
2790             return fop;
2791           else
2792             return op;
2793         }
2794       /* *(foo *)&fooarray => fooarray[0] */
2795       else if (TREE_CODE (optype) == ARRAY_TYPE
2796                && (same_type_ignoring_top_level_qualifiers_p
2797                    (type, TREE_TYPE (optype))))
2798         {
2799           tree type_domain = TYPE_DOMAIN (optype);
2800           tree min_val = size_zero_node;
2801           if (type_domain && TYPE_MIN_VALUE (type_domain))
2802             min_val = TYPE_MIN_VALUE (type_domain);
2803           return build4_loc (loc, ARRAY_REF, type, op, min_val,
2804                              NULL_TREE, NULL_TREE);
2805         }
2806       /* *(foo *)&complexfoo => __real__ complexfoo */
2807       else if (TREE_CODE (optype) == COMPLEX_TYPE
2808                && (same_type_ignoring_top_level_qualifiers_p
2809                    (type, TREE_TYPE (optype))))
2810         return fold_build1_loc (loc, REALPART_EXPR, type, op);
2811       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
2812       else if (VECTOR_TYPE_P (optype)
2813                && (same_type_ignoring_top_level_qualifiers_p
2814                    (type, TREE_TYPE (optype))))
2815         {
2816           tree part_width = TYPE_SIZE (type);
2817           tree index = bitsize_int (0);
2818           return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
2819         }
2820       /* Also handle conversion to an empty base class, which
2821          is represented with a NOP_EXPR.  */
2822       else if (is_empty_class (type)
2823                && CLASS_TYPE_P (optype)
2824                && DERIVED_FROM_P (type, optype))
2825         {
2826           *empty_base = true;
2827           return op;
2828         }
2829       /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
2830       else if (RECORD_OR_UNION_TYPE_P (optype))
2831         {
2832           tree field = TYPE_FIELDS (optype);
2833           for (; field; field = DECL_CHAIN (field))
2834             if (TREE_CODE (field) == FIELD_DECL
2835                 && integer_zerop (byte_position (field))
2836                 && (same_type_ignoring_top_level_qualifiers_p
2837                     (TREE_TYPE (field), type)))
2838               {
2839                 return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
2840                 break;
2841               }
2842         }
2843     }
2844   else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
2845            && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
2846     {
2847       tree op00 = TREE_OPERAND (sub, 0);
2848       tree op01 = TREE_OPERAND (sub, 1);
2849
2850       STRIP_NOPS (op00);
2851       if (TREE_CODE (op00) == ADDR_EXPR)
2852         {
2853           tree op00type;
2854           op00 = TREE_OPERAND (op00, 0);
2855           op00type = TREE_TYPE (op00);
2856
2857           /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
2858           if (VECTOR_TYPE_P (op00type)
2859               && (same_type_ignoring_top_level_qualifiers_p
2860                   (type, TREE_TYPE (op00type))))
2861             {
2862               HOST_WIDE_INT offset = tree_to_shwi (op01);
2863               tree part_width = TYPE_SIZE (type);
2864               unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
2865               unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
2866               tree index = bitsize_int (indexi);
2867
2868               if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
2869                 return fold_build3_loc (loc,
2870                                         BIT_FIELD_REF, type, op00,
2871                                         part_width, index);
2872
2873             }
2874           /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
2875           else if (TREE_CODE (op00type) == COMPLEX_TYPE
2876                    && (same_type_ignoring_top_level_qualifiers_p
2877                        (type, TREE_TYPE (op00type))))
2878             {
2879               tree size = TYPE_SIZE_UNIT (type);
2880               if (tree_int_cst_equal (size, op01))
2881                 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
2882             }
2883           /* ((foo *)&fooarray)[1] => fooarray[1] */
2884           else if (TREE_CODE (op00type) == ARRAY_TYPE
2885                    && (same_type_ignoring_top_level_qualifiers_p
2886                        (type, TREE_TYPE (op00type))))
2887             {
2888               tree type_domain = TYPE_DOMAIN (op00type);
2889               tree min_val = size_zero_node;
2890               if (type_domain && TYPE_MIN_VALUE (type_domain))
2891                 min_val = TYPE_MIN_VALUE (type_domain);
2892               op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
2893                                      TYPE_SIZE_UNIT (type));
2894               op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
2895               return build4_loc (loc, ARRAY_REF, type, op00, op01,
2896                                  NULL_TREE, NULL_TREE);
2897             }
2898           /* Also handle conversion to an empty base class, which
2899              is represented with a NOP_EXPR.  */
2900           else if (is_empty_class (type)
2901                    && CLASS_TYPE_P (op00type)
2902                    && DERIVED_FROM_P (type, op00type))
2903             {
2904               *empty_base = true;
2905               return op00;
2906             }
2907           /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
2908           else if (RECORD_OR_UNION_TYPE_P (op00type))
2909             {
2910               tree field = TYPE_FIELDS (op00type);
2911               for (; field; field = DECL_CHAIN (field))
2912                 if (TREE_CODE (field) == FIELD_DECL
2913                     && tree_int_cst_equal (byte_position (field), op01)
2914                     && (same_type_ignoring_top_level_qualifiers_p
2915                         (TREE_TYPE (field), type)))
2916                   {
2917                     return fold_build3 (COMPONENT_REF, type, op00,
2918                                         field, NULL_TREE);
2919                     break;
2920                   }
2921             }
2922         }
2923     }
2924   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
2925   else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
2926            && (same_type_ignoring_top_level_qualifiers_p
2927                (type, TREE_TYPE (TREE_TYPE (subtype)))))
2928     {
2929       tree type_domain;
2930       tree min_val = size_zero_node;
2931       tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
2932       if (newsub)
2933         sub = newsub;
2934       else
2935         sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
2936       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
2937       if (type_domain && TYPE_MIN_VALUE (type_domain))
2938         min_val = TYPE_MIN_VALUE (type_domain);
2939       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
2940                          NULL_TREE);
2941     }
2942
2943   return NULL_TREE;
2944 }
2945
2946 static tree
2947 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
2948                        bool lval,
2949                        bool *non_constant_p, bool *overflow_p)
2950 {
2951   tree orig_op0 = TREE_OPERAND (t, 0);
2952   bool empty_base = false;
2953
2954   /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
2955      operand is an integer-zero.  Otherwise reject the MEM_REF for now.  */
2956
2957   if (TREE_CODE (t) == MEM_REF
2958       && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
2959     {
2960       gcc_assert (ctx->quiet);
2961       *non_constant_p = true;
2962       return t;
2963     }
2964
2965   /* First try to simplify it directly.  */
2966   tree r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), orig_op0,
2967                                   &empty_base);
2968   if (!r)
2969     {
2970       /* If that didn't work, evaluate the operand first.  */
2971       tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
2972                                                /*lval*/false, non_constant_p,
2973                                                overflow_p);
2974       /* Don't VERIFY_CONSTANT here.  */
2975       if (*non_constant_p)
2976         return t;
2977
2978       r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
2979                                  &empty_base);
2980       if (r == NULL_TREE)
2981         {
2982           /* We couldn't fold to a constant value.  Make sure it's not
2983              something we should have been able to fold.  */
2984           tree sub = op0;
2985           STRIP_NOPS (sub);
2986           if (TREE_CODE (sub) == ADDR_EXPR)
2987             {
2988               gcc_assert (!same_type_ignoring_top_level_qualifiers_p
2989                           (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
2990               /* DR 1188 says we don't have to deal with this.  */
2991               if (!ctx->quiet)
2992                 error ("accessing value of %qE through a %qT glvalue in a "
2993                        "constant expression", build_fold_indirect_ref (sub),
2994                        TREE_TYPE (t));
2995               *non_constant_p = true;
2996               return t;
2997             }
2998
2999           if (lval && op0 != orig_op0)
3000             return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
3001           if (!lval)
3002             VERIFY_CONSTANT (t);
3003           return t;
3004         }
3005     }
3006
3007   r = cxx_eval_constant_expression (ctx, r,
3008                                     lval, non_constant_p, overflow_p);
3009   if (*non_constant_p)
3010     return t;
3011
3012   /* If we're pulling out the value of an empty base, make sure
3013      that the whole object is constant and then return an empty
3014      CONSTRUCTOR.  */
3015   if (empty_base && !lval)
3016     {
3017       VERIFY_CONSTANT (r);
3018       r = build_constructor (TREE_TYPE (t), NULL);
3019       TREE_CONSTANT (r) = true;
3020     }
3021
3022   return r;
3023 }
3024
3025 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
3026    Shared between potential_constant_expression and
3027    cxx_eval_constant_expression.  */
3028
3029 static void
3030 non_const_var_error (tree r)
3031 {
3032   tree type = TREE_TYPE (r);
3033   error ("the value of %qD is not usable in a constant "
3034          "expression", r);
3035   /* Avoid error cascade.  */
3036   if (DECL_INITIAL (r) == error_mark_node)
3037     return;
3038   if (DECL_DECLARED_CONSTEXPR_P (r))
3039     inform (DECL_SOURCE_LOCATION (r),
3040             "%qD used in its own initializer", r);
3041   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
3042     {
3043       if (!CP_TYPE_CONST_P (type))
3044         inform (DECL_SOURCE_LOCATION (r),
3045                 "%q#D is not const", r);
3046       else if (CP_TYPE_VOLATILE_P (type))
3047         inform (DECL_SOURCE_LOCATION (r),
3048                 "%q#D is volatile", r);
3049       else if (!DECL_INITIAL (r)
3050                || !TREE_CONSTANT (DECL_INITIAL (r))
3051                || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
3052         inform (DECL_SOURCE_LOCATION (r),
3053                 "%qD was not initialized with a constant "
3054                 "expression", r);
3055       else
3056         gcc_unreachable ();
3057     }
3058   else
3059     {
3060       if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
3061         inform (DECL_SOURCE_LOCATION (r),
3062                 "%qD was not declared %<constexpr%>", r);
3063       else
3064         inform (DECL_SOURCE_LOCATION (r),
3065                 "%qD does not have integral or enumeration type",
3066                 r);
3067     }
3068 }
3069
3070 /* Subroutine of cxx_eval_constant_expression.
3071    Like cxx_eval_unary_expression, except for trinary expressions.  */
3072
3073 static tree
3074 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
3075                              bool lval,
3076                              bool *non_constant_p, bool *overflow_p)
3077 {
3078   int i;
3079   tree args[3];
3080   tree val;
3081
3082   for (i = 0; i < 3; i++)
3083     {
3084       args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
3085                                               lval,
3086                                               non_constant_p, overflow_p);
3087       VERIFY_CONSTANT (args[i]);
3088     }
3089
3090   val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
3091                           args[0], args[1], args[2]);
3092   if (val == NULL_TREE)
3093     return t;
3094   VERIFY_CONSTANT (val);
3095   return val;
3096 }
3097
3098 bool
3099 var_in_constexpr_fn (tree t)
3100 {
3101   tree ctx = DECL_CONTEXT (t);
3102   return (cxx_dialect >= cxx14 && ctx && TREE_CODE (ctx) == FUNCTION_DECL
3103           && DECL_DECLARED_CONSTEXPR_P (ctx));
3104 }
3105
3106 /* Evaluate an INIT_EXPR or MODIFY_EXPR.  */
3107
3108 static tree
3109 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
3110                            bool lval,
3111                            bool *non_constant_p, bool *overflow_p)
3112 {
3113   constexpr_ctx new_ctx = *ctx;
3114
3115   tree init = TREE_OPERAND (t, 1);
3116   if (TREE_CLOBBER_P (init))
3117     /* Just ignore clobbers.  */
3118     return void_node;
3119
3120   /* First we figure out where we're storing to.  */
3121   tree target = TREE_OPERAND (t, 0);
3122   tree type = TREE_TYPE (target);
3123   target = cxx_eval_constant_expression (ctx, target,
3124                                          true,
3125                                          non_constant_p, overflow_p);
3126   if (*non_constant_p)
3127     return t;
3128
3129   if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (target), type))
3130     {
3131       /* For initialization of an empty base, the original target will be
3132          *(base*)this, which the above evaluation resolves to the object
3133          argument, which has the derived type rather than the base type.  In
3134          this situation, just evaluate the initializer and return, since
3135          there's no actual data to store.  */
3136       gcc_assert (is_empty_class (type));
3137       return cxx_eval_constant_expression (ctx, init, false,
3138                                            non_constant_p, overflow_p);
3139     }
3140
3141   /* And then find the underlying variable.  */
3142   vec<tree,va_gc> *refs = make_tree_vector();
3143   tree object = NULL_TREE;
3144   for (tree probe = target; object == NULL_TREE; )
3145     {
3146       switch (TREE_CODE (probe))
3147         {
3148         case BIT_FIELD_REF:
3149         case COMPONENT_REF:
3150         case ARRAY_REF:
3151           vec_safe_push (refs, TREE_OPERAND (probe, 1));
3152           vec_safe_push (refs, TREE_TYPE (probe));
3153           probe = TREE_OPERAND (probe, 0);
3154           break;
3155
3156         default:
3157           object = probe;
3158         }
3159     }
3160
3161   /* And then find/build up our initializer for the path to the subobject
3162      we're initializing.  */
3163   tree *valp;
3164   if (DECL_P (object))
3165     valp = ctx->values->get (object);
3166   else
3167     valp = NULL;
3168   if (!valp)
3169     {
3170       /* A constant-expression cannot modify objects from outside the
3171          constant-expression.  */
3172       if (!ctx->quiet)
3173         error ("modification of %qE is not a constant-expression", object);
3174       *non_constant_p = true;
3175       return t;
3176     }
3177   type = TREE_TYPE (object);
3178   bool no_zero_init = true;
3179
3180   vec<tree,va_gc> *ctors = make_tree_vector ();
3181   while (!refs->is_empty())
3182     {
3183       if (*valp == NULL_TREE)
3184         {
3185           *valp = build_constructor (type, NULL);
3186           CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3187         }
3188       else if (TREE_CODE (*valp) == STRING_CST)
3189         {
3190           /* An array was initialized with a string constant, and now
3191              we're writing into one of its elements.  Explode the
3192              single initialization into a set of element
3193              initializations.  */
3194           gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
3195
3196           tree string = *valp;
3197           tree elt_type = TREE_TYPE (type);
3198           unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
3199                                     / TYPE_PRECISION (char_type_node));
3200           unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
3201           tree ary_ctor = build_constructor (type, NULL);
3202
3203           vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
3204           for (unsigned ix = 0; ix != num_elts; ix++)
3205             {
3206               constructor_elt elt = 
3207                 {
3208                   build_int_cst (size_type_node, ix),
3209                   extract_string_elt (string, chars_per_elt, ix)
3210                 };
3211               CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
3212             }
3213           
3214           *valp = ary_ctor;
3215         }
3216
3217       /* If the value of object is already zero-initialized, any new ctors for
3218          subobjects will also be zero-initialized.  */
3219       no_zero_init = CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp);
3220
3221       vec_safe_push (ctors, *valp);
3222
3223       enum tree_code code = TREE_CODE (type);
3224       type = refs->pop();
3225       tree index = refs->pop();
3226
3227       constructor_elt *cep = NULL;
3228       if (code == ARRAY_TYPE)
3229         {
3230           HOST_WIDE_INT i
3231             = find_array_ctor_elt (*valp, index, /*insert*/true);
3232           gcc_assert (i >= 0);
3233           cep = CONSTRUCTOR_ELT (*valp, i);
3234           gcc_assert (TREE_CODE (cep->index) != RANGE_EXPR);
3235         }
3236       else
3237         {
3238           gcc_assert (TREE_CODE (index) == FIELD_DECL);
3239
3240           /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3241              Usually we meet initializers in that order, but it is
3242              possible for base types to be placed not in program
3243              order.  */
3244           tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3245           unsigned HOST_WIDE_INT idx;
3246
3247           for (idx = 0;
3248                vec_safe_iterate (CONSTRUCTOR_ELTS (*valp), idx, &cep);
3249                idx++, fields = DECL_CHAIN (fields))
3250             {
3251               if (index == cep->index)
3252                 goto found;
3253
3254               /* The field we're initializing must be on the field
3255                  list.  Look to see if it is present before the
3256                  field the current ELT initializes.  */
3257               for (; fields != cep->index; fields = DECL_CHAIN (fields))
3258                 if (index == fields)
3259                   goto insert;
3260             }
3261
3262           /* We fell off the end of the CONSTRUCTOR, so insert a new
3263              entry at the end.  */
3264         insert:
3265           {
3266             constructor_elt ce = { index, NULL_TREE };
3267
3268             vec_safe_insert (CONSTRUCTOR_ELTS (*valp), idx, ce);
3269             cep = CONSTRUCTOR_ELT (*valp, idx);
3270           }
3271         found:;
3272         }
3273       valp = &cep->value;
3274     }
3275   release_tree_vector (refs);
3276
3277   if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
3278     {
3279       /* Create a new CONSTRUCTOR in case evaluation of the initializer
3280          wants to modify it.  */
3281       if (*valp == NULL_TREE)
3282         {
3283           *valp = new_ctx.ctor = build_constructor (type, NULL);
3284           CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = no_zero_init;
3285         }
3286       else
3287         new_ctx.ctor = *valp;
3288       new_ctx.object = target;
3289     }
3290
3291   init = cxx_eval_constant_expression (&new_ctx, init, false,
3292                                        non_constant_p, overflow_p);
3293   /* Don't share a CONSTRUCTOR that might be changed later.  */
3294   init = unshare_constructor (init);
3295   if (target == object)
3296     /* The hash table might have moved since the get earlier.  */
3297     valp = ctx->values->get (object);
3298
3299   if (TREE_CODE (init) == CONSTRUCTOR)
3300     {
3301       /* An outer ctx->ctor might be pointing to *valp, so replace
3302          its contents.  */
3303       CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
3304       TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
3305       TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
3306       CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp)
3307         = CONSTRUCTOR_NO_IMPLICIT_ZERO (init);
3308     }
3309   else
3310     *valp = init;
3311
3312   /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
3313      CONSTRUCTORs, if any.  */
3314   tree elt;
3315   unsigned i;
3316   bool c = TREE_CONSTANT (init);
3317   bool s = TREE_SIDE_EFFECTS (init);
3318   if (!c || s)
3319     FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
3320       {
3321         if (!c)
3322           TREE_CONSTANT (elt) = false;
3323         if (s)
3324           TREE_SIDE_EFFECTS (elt) = true;
3325       }
3326   release_tree_vector (ctors);
3327
3328   if (*non_constant_p)
3329     return t;
3330   else if (lval)
3331     return target;
3332   else
3333     return init;
3334 }
3335
3336 /* Evaluate a ++ or -- expression.  */
3337
3338 static tree
3339 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
3340                               bool lval,
3341                               bool *non_constant_p, bool *overflow_p)
3342 {
3343   enum tree_code code = TREE_CODE (t);
3344   tree type = TREE_TYPE (t);
3345   tree op = TREE_OPERAND (t, 0);
3346   tree offset = TREE_OPERAND (t, 1);
3347   gcc_assert (TREE_CONSTANT (offset));
3348
3349   /* The operand as an lvalue.  */
3350   op = cxx_eval_constant_expression (ctx, op, true,
3351                                      non_constant_p, overflow_p);
3352
3353   /* The operand as an rvalue.  */
3354   tree val = rvalue (op);
3355   val = cxx_eval_constant_expression (ctx, val, false,
3356                                       non_constant_p, overflow_p);
3357   /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3358      a local array in a constexpr function.  */
3359   bool ptr = POINTER_TYPE_P (TREE_TYPE (val));
3360   if (!ptr)
3361     VERIFY_CONSTANT (val);
3362
3363   /* The modified value.  */
3364   bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
3365   tree mod;
3366   if (POINTER_TYPE_P (type))
3367     {
3368       /* The middle end requires pointers to use POINTER_PLUS_EXPR.  */
3369       offset = convert_to_ptrofftype (offset);
3370       if (!inc)
3371         offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
3372       mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
3373     }
3374   else
3375     mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
3376   if (!ptr)
3377     VERIFY_CONSTANT (mod);
3378
3379   /* Storing the modified value.  */
3380   tree store = build2 (MODIFY_EXPR, type, op, mod);
3381   cxx_eval_constant_expression (ctx, store,
3382                                 true, non_constant_p, overflow_p);
3383
3384   /* And the value of the expression.  */
3385   if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
3386     {
3387       /* Prefix ops are lvalues.  */
3388       if (lval)
3389         return op;
3390       else
3391         /* But we optimize when the caller wants an rvalue.  */
3392         return mod;
3393     }
3394   else
3395     /* Postfix ops are rvalues.  */
3396     return val;
3397 }
3398
3399 /* Predicates for the meaning of *jump_target.  */
3400
3401 static bool
3402 returns (tree *jump_target)
3403 {
3404   return *jump_target
3405     && TREE_CODE (*jump_target) == RETURN_EXPR;
3406 }
3407
3408 static bool
3409 breaks (tree *jump_target)
3410 {
3411   return *jump_target
3412     && TREE_CODE (*jump_target) == LABEL_DECL
3413     && LABEL_DECL_BREAK (*jump_target);
3414 }
3415
3416 static bool
3417 continues (tree *jump_target)
3418 {
3419   return *jump_target
3420     && TREE_CODE (*jump_target) == LABEL_DECL
3421     && LABEL_DECL_CONTINUE (*jump_target);
3422 }
3423
3424 static bool
3425 switches (tree *jump_target)
3426 {
3427   return *jump_target
3428     && TREE_CODE (*jump_target) == INTEGER_CST;
3429 }
3430
3431 /* Subroutine of cxx_eval_statement_list.  Determine whether the statement
3432    STMT matches *jump_target.  If we're looking for a case label and we see
3433    the default label, note it in ctx->css_state.  */
3434
3435 static bool
3436 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
3437 {
3438   switch (TREE_CODE (*jump_target))
3439     {
3440     case LABEL_DECL:
3441       if (TREE_CODE (stmt) == LABEL_EXPR
3442           && LABEL_EXPR_LABEL (stmt) == *jump_target)
3443         return true;
3444       break;
3445
3446     case INTEGER_CST:
3447       if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
3448         {
3449           gcc_assert (ctx->css_state != NULL);
3450           if (!CASE_LOW (stmt))
3451             {
3452               /* default: should appear just once in a SWITCH_EXPR
3453                  body (excluding nested SWITCH_EXPR).  */
3454               gcc_assert (*ctx->css_state != css_default_seen);
3455               /* When evaluating SWITCH_EXPR body for the second time,
3456                  return true for the default: label.  */
3457               if (*ctx->css_state == css_default_processing)
3458                 return true;
3459               *ctx->css_state = css_default_seen;
3460             }
3461           else if (CASE_HIGH (stmt))
3462             {
3463               if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
3464                   && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
3465                 return true;
3466             }
3467           else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
3468             return true;
3469         }
3470       break;
3471
3472     default:
3473       gcc_unreachable ();
3474     }
3475   return false;
3476 }
3477
3478 /* Evaluate a STATEMENT_LIST for side-effects.  Handles various jump
3479    semantics, for switch, break, continue, and return.  */
3480
3481 static tree
3482 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
3483                          bool *non_constant_p, bool *overflow_p,
3484                          tree *jump_target)
3485 {
3486   tree_stmt_iterator i;
3487   tree local_target;
3488   /* In a statement-expression we want to return the last value.  */
3489   tree r = NULL_TREE;
3490   if (!jump_target)
3491     {
3492       local_target = NULL_TREE;
3493       jump_target = &local_target;
3494     }
3495   for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3496     {
3497       tree stmt = tsi_stmt (i);
3498       r = cxx_eval_constant_expression (ctx, stmt, false,
3499                                         non_constant_p, overflow_p,
3500                                         jump_target);
3501       if (*non_constant_p)
3502         break;
3503       if (returns (jump_target) || breaks (jump_target))
3504         break;
3505     }
3506   return r;
3507 }
3508
3509 /* Evaluate a LOOP_EXPR for side-effects.  Handles break and return
3510    semantics; continue semantics are covered by cxx_eval_statement_list.  */
3511
3512 static tree
3513 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
3514                     bool *non_constant_p, bool *overflow_p,
3515                     tree *jump_target)
3516 {
3517   constexpr_ctx new_ctx = *ctx;
3518
3519   tree body = TREE_OPERAND (t, 0);
3520   do
3521     {
3522       hash_set<tree> save_exprs;
3523       new_ctx.save_exprs = &save_exprs;
3524
3525       cxx_eval_statement_list (&new_ctx, body,
3526                                non_constant_p, overflow_p, jump_target);
3527
3528       /* Forget saved values of SAVE_EXPRs.  */
3529       for (hash_set<tree>::iterator iter = save_exprs.begin();
3530            iter != save_exprs.end(); ++iter)
3531         new_ctx.values->remove (*iter);
3532     }
3533   while (!returns (jump_target)
3534          && !breaks (jump_target)
3535          && !switches (jump_target)
3536          && !*non_constant_p);
3537
3538   if (breaks (jump_target))
3539     *jump_target = NULL_TREE;
3540
3541   return NULL_TREE;
3542 }
3543
3544 /* Evaluate a SWITCH_EXPR for side-effects.  Handles switch and break jump
3545    semantics.  */
3546
3547 static tree
3548 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
3549                       bool *non_constant_p, bool *overflow_p,
3550                       tree *jump_target)
3551 {
3552   tree cond = TREE_OPERAND (t, 0);
3553   cond = cxx_eval_constant_expression (ctx, cond, false,
3554                                        non_constant_p, overflow_p);
3555   VERIFY_CONSTANT (cond);
3556   *jump_target = cond;
3557
3558   tree body = TREE_OPERAND (t, 1);
3559   constexpr_ctx new_ctx = *ctx;
3560   constexpr_switch_state css = css_default_not_seen;
3561   new_ctx.css_state = &css;
3562   cxx_eval_constant_expression (&new_ctx, body, false,
3563                                 non_constant_p, overflow_p, jump_target);
3564   if (switches (jump_target) && css == css_default_seen)
3565     {
3566       /* If the SWITCH_EXPR body has default: label, process it once again,
3567          this time instructing label_matches to return true for default:
3568          label on switches (jump_target).  */
3569       css = css_default_processing;
3570       cxx_eval_constant_expression (&new_ctx, body, false,
3571                                     non_constant_p, overflow_p, jump_target);
3572     }
3573   if (breaks (jump_target) || switches (jump_target))
3574     *jump_target = NULL_TREE;
3575   return NULL_TREE;
3576 }
3577
3578 /* Attempt to reduce the expression T to a constant value.
3579    On failure, issue diagnostic and return error_mark_node.  */
3580 /* FIXME unify with c_fully_fold */
3581 /* FIXME overflow_p is too global */
3582
3583 static tree
3584 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
3585                               bool lval,
3586                               bool *non_constant_p, bool *overflow_p,
3587                               tree *jump_target)
3588 {
3589   constexpr_ctx new_ctx;
3590   tree r = t;
3591
3592   if (jump_target && *jump_target)
3593     {
3594       /* If we are jumping, ignore all statements/expressions except those
3595          that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies.  */
3596       switch (TREE_CODE (t))
3597         {
3598         case BIND_EXPR:
3599         case STATEMENT_LIST:
3600         case LOOP_EXPR:
3601         case COND_EXPR:
3602           break;
3603         case LABEL_EXPR:
3604         case CASE_LABEL_EXPR:
3605           if (label_matches (ctx, jump_target, t))
3606             /* Found it.  */
3607             *jump_target = NULL_TREE;
3608           return NULL_TREE;
3609         default:
3610           return NULL_TREE;
3611         }
3612     }
3613   if (t == error_mark_node)
3614     {
3615       *non_constant_p = true;
3616       return t;
3617     }
3618   if (CONSTANT_CLASS_P (t))
3619     {
3620       if (TREE_OVERFLOW (t))
3621         {
3622           if (!ctx->quiet)
3623             permerror (input_location, "overflow in constant expression");
3624           if (!flag_permissive || ctx->quiet)
3625             *overflow_p = true;
3626         }
3627       return t;
3628     }
3629
3630   switch (TREE_CODE (t))
3631     {
3632     case RESULT_DECL:
3633       if (lval)
3634         return t;
3635       /* We ask for an rvalue for the RESULT_DECL when indirecting
3636          through an invisible reference, or in named return value
3637          optimization.  */
3638       return (*ctx->values->get (t));
3639
3640     case VAR_DECL:
3641     case CONST_DECL:
3642       /* We used to not check lval for CONST_DECL, but darwin.c uses
3643          CONST_DECL for aggregate constants.  */
3644       if (lval)
3645         return t;
3646       if (ctx->strict)
3647         r = decl_really_constant_value (t);
3648       else
3649         r = decl_constant_value (t);
3650       if (TREE_CODE (r) == TARGET_EXPR
3651           && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
3652         r = TARGET_EXPR_INITIAL (r);
3653       if (VAR_P (r))
3654         if (tree *p = ctx->values->get (r))
3655           if (*p != NULL_TREE)
3656             r = *p;
3657       if (DECL_P (r))
3658         {
3659           if (!ctx->quiet)
3660             non_const_var_error (r);
3661           *non_constant_p = true;
3662         }
3663       break;
3664
3665     case FUNCTION_DECL:
3666     case TEMPLATE_DECL:
3667     case LABEL_DECL:
3668     case LABEL_EXPR:
3669     case CASE_LABEL_EXPR:
3670     case PREDICT_EXPR:
3671       return t;
3672
3673     case PARM_DECL:
3674       if (lval && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
3675         /* glvalue use.  */;
3676       else if (tree *p = ctx->values->get (r))
3677         r = *p;
3678       else if (lval)
3679         /* Defer in case this is only used for its type.  */;
3680       else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
3681         /* Defer, there's no lvalue->rvalue conversion.  */;
3682       else if (is_empty_class (TREE_TYPE (t)))
3683         {
3684           /* If the class is empty, we aren't actually loading anything.  */
3685           r = build_constructor (TREE_TYPE (t), NULL);
3686           TREE_CONSTANT (r) = true;
3687         }
3688       else
3689         {
3690           if (!ctx->quiet)
3691             error ("%qE is not a constant expression", t);
3692           *non_constant_p = true;
3693         }
3694       break;
3695
3696     case CALL_EXPR:
3697     case AGGR_INIT_EXPR:
3698       r = cxx_eval_call_expression (ctx, t, lval,
3699                                     non_constant_p, overflow_p);
3700       break;
3701
3702     case DECL_EXPR:
3703       {
3704         r = DECL_EXPR_DECL (t);
3705         if (AGGREGATE_TYPE_P (TREE_TYPE (r))
3706             || VECTOR_TYPE_P (TREE_TYPE (r)))
3707           {
3708             new_ctx = *ctx;
3709             new_ctx.object = r;
3710             new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
3711             CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
3712             new_ctx.values->put (r, new_ctx.ctor);
3713             ctx = &new_ctx;
3714           }
3715
3716         if (tree init = DECL_INITIAL (r))
3717           {
3718             init = cxx_eval_constant_expression (ctx, init,
3719                                                  false,
3720                                                  non_constant_p, overflow_p);
3721             /* Don't share a CONSTRUCTOR that might be changed.  */
3722             init = unshare_constructor (init);
3723             ctx->values->put (r, init);
3724           }
3725         else if (ctx == &new_ctx)
3726           /* We gave it a CONSTRUCTOR above.  */;
3727         else
3728           ctx->values->put (r, NULL_TREE);
3729       }
3730       break;
3731
3732     case TARGET_EXPR:
3733       if (!literal_type_p (TREE_TYPE (t)))
3734         {
3735           if (!ctx->quiet)
3736             {
3737               error ("temporary of non-literal type %qT in a "
3738                      "constant expression", TREE_TYPE (t));
3739               explain_non_literal_class (TREE_TYPE (t));
3740             }
3741           *non_constant_p = true;
3742           break;
3743         }
3744       if ((AGGREGATE_TYPE_P (TREE_TYPE (t)) || VECTOR_TYPE_P (TREE_TYPE (t))))
3745         {
3746           /* We're being expanded without an explicit target, so start
3747              initializing a new object; expansion with an explicit target
3748              strips the TARGET_EXPR before we get here.  */
3749           new_ctx = *ctx;
3750           new_ctx.ctor = build_constructor (TREE_TYPE (t), NULL);
3751           CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
3752           new_ctx.object = TARGET_EXPR_SLOT (t);
3753           ctx->values->put (new_ctx.object, new_ctx.ctor);
3754           ctx = &new_ctx;
3755         }
3756       /* Pass false for 'lval' because this indicates
3757          initialization of a temporary.  */
3758       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3759                                         false,
3760                                         non_constant_p, overflow_p);
3761       if (!*non_constant_p)
3762         /* Adjust the type of the result to the type of the temporary.  */
3763         r = adjust_temp_type (TREE_TYPE (t), r);
3764       if (lval)
3765         {
3766           tree slot = TARGET_EXPR_SLOT (t);
3767           r = unshare_constructor (r);
3768           ctx->values->put (slot, r);
3769           return slot;
3770         }
3771       break;
3772
3773     case INIT_EXPR:
3774     case MODIFY_EXPR:
3775       gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
3776       r = cxx_eval_store_expression (ctx, t, lval,
3777                                      non_constant_p, overflow_p);
3778       break;
3779
3780     case SCOPE_REF:
3781       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3782                                         lval,
3783                                         non_constant_p, overflow_p);
3784       break;
3785
3786     case RETURN_EXPR:
3787       if (TREE_OPERAND (t, 0) != NULL_TREE)
3788         r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3789                                           lval,
3790                                           non_constant_p, overflow_p);
3791       *jump_target = t;
3792       break;
3793
3794     case SAVE_EXPR:
3795       /* Avoid evaluating a SAVE_EXPR more than once.  */
3796       if (tree *p = ctx->values->get (t))
3797         r = *p;
3798       else
3799         {
3800           r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
3801                                             non_constant_p, overflow_p);
3802           ctx->values->put (t, r);
3803           if (ctx->save_exprs)
3804             ctx->save_exprs->add (t);
3805         }
3806       break;
3807
3808     case NON_LVALUE_EXPR:
3809     case TRY_CATCH_EXPR:
3810     case TRY_BLOCK:
3811     case CLEANUP_POINT_EXPR:
3812     case MUST_NOT_THROW_EXPR:
3813     case EXPR_STMT:
3814     case EH_SPEC_BLOCK:
3815       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3816                                         lval,
3817                                         non_constant_p, overflow_p,
3818                                         jump_target);
3819       break;
3820
3821     case TRY_FINALLY_EXPR:
3822       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
3823                                         non_constant_p, overflow_p,
3824                                         jump_target);
3825       if (!*non_constant_p)
3826         /* Also evaluate the cleanup.  */
3827         cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
3828                                       non_constant_p, overflow_p,
3829                                       jump_target);
3830       break;
3831
3832       /* These differ from cxx_eval_unary_expression in that this doesn't
3833          check for a constant operand or result; an address can be
3834          constant without its operand being, and vice versa.  */
3835     case MEM_REF:
3836     case INDIRECT_REF:
3837       r = cxx_eval_indirect_ref (ctx, t, lval,
3838                                  non_constant_p, overflow_p);
3839       break;
3840
3841     case ADDR_EXPR:
3842       {
3843         tree oldop = TREE_OPERAND (t, 0);
3844         tree op = cxx_eval_constant_expression (ctx, oldop,
3845                                                 /*lval*/true,
3846                                                 non_constant_p, overflow_p);
3847         /* Don't VERIFY_CONSTANT here.  */
3848         if (*non_constant_p)
3849           return t;
3850         gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
3851         /* This function does more aggressive folding than fold itself.  */
3852         r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
3853         if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
3854           return t;
3855         break;
3856       }
3857
3858     case REALPART_EXPR:
3859     case IMAGPART_EXPR:
3860       if (lval)
3861         {
3862           r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
3863                                             non_constant_p, overflow_p);
3864           if (r == error_mark_node)
3865             ;
3866           else if (r == TREE_OPERAND (t, 0))
3867             r = t;
3868           else
3869             r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
3870           break;
3871         }
3872       /* FALLTHRU */
3873     case CONJ_EXPR:
3874     case FIX_TRUNC_EXPR:
3875     case FLOAT_EXPR:
3876     case NEGATE_EXPR:
3877     case ABS_EXPR:
3878     case BIT_NOT_EXPR:
3879     case TRUTH_NOT_EXPR:
3880     case FIXED_CONVERT_EXPR:
3881       r = cxx_eval_unary_expression (ctx, t, lval,
3882                                      non_constant_p, overflow_p);
3883       break;
3884
3885     case SIZEOF_EXPR:
3886       r = fold_sizeof_expr (t);
3887       VERIFY_CONSTANT (r);
3888       break;
3889
3890     case COMPOUND_EXPR:
3891       {
3892         /* check_return_expr sometimes wraps a TARGET_EXPR in a
3893            COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
3894            introduced by build_call_a.  */
3895         tree op0 = TREE_OPERAND (t, 0);
3896         tree op1 = TREE_OPERAND (t, 1);
3897         STRIP_NOPS (op1);
3898         if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
3899             || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
3900           r = cxx_eval_constant_expression (ctx, op0,
3901                                             lval, non_constant_p, overflow_p,
3902                                             jump_target);
3903         else
3904           {
3905             /* Check that the LHS is constant and then discard it.  */
3906             cxx_eval_constant_expression (ctx, op0,
3907                                           true, non_constant_p, overflow_p,
3908                                           jump_target);
3909             op1 = TREE_OPERAND (t, 1);
3910             r = cxx_eval_constant_expression (ctx, op1,
3911                                               lval, non_constant_p, overflow_p,
3912                                               jump_target);
3913           }
3914       }
3915       break;
3916
3917     case POINTER_PLUS_EXPR:
3918     case PLUS_EXPR:
3919     case MINUS_EXPR:
3920     case MULT_EXPR:
3921     case TRUNC_DIV_EXPR:
3922     case CEIL_DIV_EXPR:
3923     case FLOOR_DIV_EXPR:
3924     case ROUND_DIV_EXPR:
3925     case TRUNC_MOD_EXPR:
3926     case CEIL_MOD_EXPR:
3927     case ROUND_MOD_EXPR:
3928     case RDIV_EXPR:
3929     case EXACT_DIV_EXPR:
3930     case MIN_EXPR:
3931     case MAX_EXPR:
3932     case LSHIFT_EXPR:
3933     case RSHIFT_EXPR:
3934     case LROTATE_EXPR:
3935     case RROTATE_EXPR:
3936     case BIT_IOR_EXPR:
3937     case BIT_XOR_EXPR:
3938     case BIT_AND_EXPR:
3939     case TRUTH_XOR_EXPR:
3940     case LT_EXPR:
3941     case LE_EXPR:
3942     case GT_EXPR:
3943     case GE_EXPR:
3944     case EQ_EXPR:
3945     case NE_EXPR:
3946     case UNORDERED_EXPR:
3947     case ORDERED_EXPR:
3948     case UNLT_EXPR:
3949     case UNLE_EXPR:
3950     case UNGT_EXPR:
3951     case UNGE_EXPR:
3952     case UNEQ_EXPR:
3953     case LTGT_EXPR:
3954     case RANGE_EXPR:
3955     case COMPLEX_EXPR:
3956       r = cxx_eval_binary_expression (ctx, t, lval,
3957                                       non_constant_p, overflow_p);
3958       break;
3959
3960       /* fold can introduce non-IF versions of these; still treat them as
3961          short-circuiting.  */
3962     case TRUTH_AND_EXPR:
3963     case TRUTH_ANDIF_EXPR:
3964       r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
3965                                        boolean_true_node,
3966                                        lval,
3967                                        non_constant_p, overflow_p);
3968       break;
3969
3970     case TRUTH_OR_EXPR:
3971     case TRUTH_ORIF_EXPR:
3972       r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
3973                                        boolean_false_node,
3974                                        lval,
3975                                        non_constant_p, overflow_p);
3976       break;
3977
3978     case ARRAY_REF:
3979       r = cxx_eval_array_reference (ctx, t, lval,
3980                                     non_constant_p, overflow_p);
3981       break;
3982
3983     case COMPONENT_REF:
3984       if (is_overloaded_fn (t))
3985         {
3986           /* We can only get here in checking mode via 
3987              build_non_dependent_expr,  because any expression that
3988              calls or takes the address of the function will have
3989              pulled a FUNCTION_DECL out of the COMPONENT_REF.  */
3990           gcc_checking_assert (ctx->quiet || errorcount);
3991           *non_constant_p = true;
3992           return t;
3993         }
3994       r = cxx_eval_component_reference (ctx, t, lval,
3995                                         non_constant_p, overflow_p);
3996       break;
3997
3998     case BIT_FIELD_REF:
3999       r = cxx_eval_bit_field_ref (ctx, t, lval,
4000                                   non_constant_p, overflow_p);
4001       break;
4002
4003     case COND_EXPR:
4004       if (jump_target && *jump_target)
4005         {
4006           /* When jumping to a label, the label might be either in the
4007              then or else blocks, so process then block first in skipping
4008              mode first, and if we are still in the skipping mode at its end,
4009              process the else block too.  */
4010           r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4011                                             lval, non_constant_p, overflow_p,
4012                                             jump_target);
4013           if (*jump_target)
4014             r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
4015                                               lval, non_constant_p, overflow_p,
4016                                               jump_target);
4017           break;
4018         }
4019       /* FALLTHRU */
4020     case VEC_COND_EXPR:
4021       r = cxx_eval_conditional_expression (ctx, t, lval,
4022                                            non_constant_p, overflow_p,
4023                                            jump_target);
4024       break;
4025
4026     case CONSTRUCTOR:
4027       if (TREE_CONSTANT (t))
4028         {
4029           /* Don't re-process a constant CONSTRUCTOR, but do fold it to
4030              VECTOR_CST if applicable.  */
4031           /* FIXME after GCC 6 branches, make the verify unconditional.  */
4032           if (CHECKING_P)
4033             verify_constructor_flags (t);
4034           else
4035             recompute_constructor_flags (t);
4036           if (TREE_CONSTANT (t))
4037             return fold (t);
4038         }
4039       r = cxx_eval_bare_aggregate (ctx, t, lval,
4040                                    non_constant_p, overflow_p);
4041       break;
4042
4043     case VEC_INIT_EXPR:
4044       /* We can get this in a defaulted constructor for a class with a
4045          non-static data member of array type.  Either the initializer will
4046          be NULL, meaning default-initialization, or it will be an lvalue
4047          or xvalue of the same type, meaning direct-initialization from the
4048          corresponding member.  */
4049       r = cxx_eval_vec_init (ctx, t, lval,
4050                              non_constant_p, overflow_p);
4051       break;
4052
4053     case FMA_EXPR:
4054     case VEC_PERM_EXPR:
4055       r = cxx_eval_trinary_expression (ctx, t, lval,
4056                                        non_constant_p, overflow_p);
4057       break;
4058
4059     case CONVERT_EXPR:
4060     case VIEW_CONVERT_EXPR:
4061     case NOP_EXPR:
4062     case UNARY_PLUS_EXPR:
4063       {
4064         enum tree_code tcode = TREE_CODE (t);
4065         tree oldop = TREE_OPERAND (t, 0);
4066
4067         tree op = cxx_eval_constant_expression (ctx, oldop,
4068                                                 lval,
4069                                                 non_constant_p, overflow_p);
4070         if (*non_constant_p)
4071           return t;
4072         tree type = TREE_TYPE (t);
4073         if (TREE_CODE (op) == PTRMEM_CST
4074             && !TYPE_PTRMEM_P (type))
4075           op = cplus_expand_constant (op);
4076         if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
4077           {
4078             if (same_type_ignoring_top_level_qualifiers_p (type,
4079                                                            TREE_TYPE (op)))
4080               return cp_fold_convert (type, op);
4081             else
4082               {
4083                 if (!ctx->quiet)
4084                   error_at (EXPR_LOC_OR_LOC (t, input_location),
4085                             "a reinterpret_cast is not a constant-expression");
4086                 *non_constant_p = true;
4087                 return t;
4088               }
4089           }
4090         if (POINTER_TYPE_P (type)
4091             && TREE_CODE (op) == INTEGER_CST
4092             && !integer_zerop (op))
4093           {
4094             if (!ctx->quiet)
4095               error_at (EXPR_LOC_OR_LOC (t, input_location),
4096                         "reinterpret_cast from integer to pointer");
4097             *non_constant_p = true;
4098             return t;
4099           }
4100         if (op == oldop && tcode != UNARY_PLUS_EXPR)
4101           /* We didn't fold at the top so we could check for ptr-int
4102              conversion.  */
4103           return fold (t);
4104         if (tcode == UNARY_PLUS_EXPR)
4105           r = fold_convert (TREE_TYPE (t), op);
4106         else
4107           r = fold_build1 (tcode, type, op);
4108         /* Conversion of an out-of-range value has implementation-defined
4109            behavior; the language considers it different from arithmetic
4110            overflow, which is undefined.  */
4111         if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
4112           TREE_OVERFLOW (r) = false;
4113       }
4114       break;
4115
4116     case EMPTY_CLASS_EXPR:
4117     case STATEMENT_LIST_END:
4118       /* This is good enough for a function argument that might not get
4119          used, and they can't do anything with it, so just return it.  */
4120       return t;
4121
4122     case STATEMENT_LIST:
4123       new_ctx = *ctx;
4124       new_ctx.ctor = new_ctx.object = NULL_TREE;
4125       return cxx_eval_statement_list (&new_ctx, t,
4126                                       non_constant_p, overflow_p, jump_target);
4127
4128     case BIND_EXPR:
4129       return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
4130                                            lval,
4131                                            non_constant_p, overflow_p,
4132                                            jump_target);
4133
4134     case PREINCREMENT_EXPR:
4135     case POSTINCREMENT_EXPR:
4136     case PREDECREMENT_EXPR:
4137     case POSTDECREMENT_EXPR:
4138       return cxx_eval_increment_expression (ctx, t,
4139                                             lval, non_constant_p, overflow_p);
4140
4141     case LAMBDA_EXPR:
4142     case NEW_EXPR:
4143     case VEC_NEW_EXPR:
4144     case DELETE_EXPR:
4145     case VEC_DELETE_EXPR:
4146     case THROW_EXPR:
4147     case MODOP_EXPR:
4148       /* GCC internal stuff.  */
4149     case VA_ARG_EXPR:
4150     case OBJ_TYPE_REF:
4151     case WITH_CLEANUP_EXPR:
4152     case NON_DEPENDENT_EXPR:
4153     case BASELINK:
4154     case OFFSET_REF:
4155       if (!ctx->quiet)
4156         error_at (EXPR_LOC_OR_LOC (t, input_location),
4157                   "expression %qE is not a constant-expression", t);
4158       *non_constant_p = true;
4159       break;
4160
4161     case PLACEHOLDER_EXPR:
4162       if (!ctx || !ctx->ctor || (lval && !ctx->object)
4163           || !(same_type_ignoring_top_level_qualifiers_p
4164                (TREE_TYPE (t), TREE_TYPE (ctx->ctor))))
4165         {
4166           /* A placeholder without a referent.  We can get here when
4167              checking whether NSDMIs are noexcept, or in massage_init_elt;
4168              just say it's non-constant for now.  */
4169           gcc_assert (ctx->quiet);
4170           *non_constant_p = true;
4171           break;
4172         }
4173       else
4174         {
4175           /* Use of the value or address of the current object.  We could
4176              use ctx->object unconditionally, but using ctx->ctor when we
4177              can is a minor optimization.  */
4178           tree ctor = lval ? ctx->object : ctx->ctor;
4179           return cxx_eval_constant_expression
4180             (ctx, ctor, lval,
4181              non_constant_p, overflow_p);
4182         }
4183       break;
4184
4185     case GOTO_EXPR:
4186       *jump_target = TREE_OPERAND (t, 0);
4187       gcc_assert (breaks (jump_target) || continues (jump_target));
4188       break;
4189
4190     case LOOP_EXPR:
4191       cxx_eval_loop_expr (ctx, t,
4192                           non_constant_p, overflow_p, jump_target);
4193       break;
4194
4195     case SWITCH_EXPR:
4196       cxx_eval_switch_expr (ctx, t,
4197                             non_constant_p, overflow_p, jump_target);
4198       break;
4199
4200     case REQUIRES_EXPR:
4201       /* It's possible to get a requires-expression in a constant
4202          expression. For example:
4203
4204              template<typename T> concept bool C() {
4205                return requires (T t) { t; };
4206              }
4207
4208              template<typename T> requires !C<T>() void f(T);
4209
4210          Normalization leaves f with the associated constraint
4211          '!requires (T t) { ... }' which is not transformed into
4212          a constraint.  */
4213       if (!processing_template_decl)
4214         return evaluate_constraint_expression (t, NULL_TREE);
4215       else
4216         *non_constant_p = true;
4217       return t;
4218
4219     default:
4220       if (STATEMENT_CODE_P (TREE_CODE (t)))
4221         {
4222           /* This function doesn't know how to deal with pre-genericize
4223              statements; this can only happen with statement-expressions,
4224              so for now just fail.  */
4225           if (!ctx->quiet)
4226             error_at (EXPR_LOCATION (t),
4227                       "statement is not a constant-expression");
4228         }
4229       else
4230         internal_error ("unexpected expression %qE of kind %s", t,
4231                         get_tree_code_name (TREE_CODE (t)));
4232       *non_constant_p = true;
4233       break;
4234     }
4235
4236   if (r == error_mark_node)
4237     *non_constant_p = true;
4238
4239   if (*non_constant_p)
4240     return t;
4241   else
4242     return r;
4243 }
4244
4245 static tree
4246 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
4247                                   bool strict = true, tree object = NULL_TREE)
4248 {
4249   bool non_constant_p = false;
4250   bool overflow_p = false;
4251   hash_map<tree,tree> map;
4252
4253   constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL,
4254                         allow_non_constant, strict };
4255
4256   tree type = initialized_type (t);
4257   tree r = t;
4258   if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4259     {
4260       /* In C++14 an NSDMI can participate in aggregate initialization,
4261          and can refer to the address of the object being initialized, so
4262          we need to pass in the relevant VAR_DECL if we want to do the
4263          evaluation in a single pass.  The evaluation will dynamically
4264          update ctx.values for the VAR_DECL.  We use the same strategy
4265          for C++11 constexpr constructors that refer to the object being
4266          initialized.  */
4267       ctx.ctor = build_constructor (type, NULL);
4268       CONSTRUCTOR_NO_IMPLICIT_ZERO (ctx.ctor) = true;
4269       if (!object)
4270         {
4271           if (TREE_CODE (t) == TARGET_EXPR)
4272             object = TARGET_EXPR_SLOT (t);
4273           else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4274             object = AGGR_INIT_EXPR_SLOT (t);
4275         }
4276       ctx.object = object;
4277       if (object)
4278         gcc_assert (same_type_ignoring_top_level_qualifiers_p
4279                     (type, TREE_TYPE (object)));
4280       if (object && DECL_P (object))
4281         map.put (object, ctx.ctor);
4282       if (TREE_CODE (r) == TARGET_EXPR)
4283         /* Avoid creating another CONSTRUCTOR when we expand the
4284            TARGET_EXPR.  */
4285         r = TARGET_EXPR_INITIAL (r);
4286     }
4287
4288   r = cxx_eval_constant_expression (&ctx, r,
4289                                     false, &non_constant_p, &overflow_p);
4290
4291   verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
4292
4293   /* Mutable logic is a bit tricky: we want to allow initialization of
4294      constexpr variables with mutable members, but we can't copy those
4295      members to another constexpr variable.  */
4296   if (TREE_CODE (r) == CONSTRUCTOR
4297       && CONSTRUCTOR_MUTABLE_POISON (r))
4298     {
4299       if (!allow_non_constant)
4300         error ("%qE is not a constant expression because it refers to "
4301                "mutable subobjects of %qT", t, type);
4302       non_constant_p = true;
4303     }
4304
4305   /* Technically we should check this for all subexpressions, but that
4306      runs into problems with our internal representation of pointer
4307      subtraction and the 5.19 rules are still in flux.  */
4308   if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
4309       && ARITHMETIC_TYPE_P (TREE_TYPE (r))
4310       && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
4311     {
4312       if (!allow_non_constant)
4313         error ("conversion from pointer type %qT "
4314                "to arithmetic type %qT in a constant-expression",
4315                TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
4316       non_constant_p = true;
4317     }
4318
4319   if (!non_constant_p && overflow_p)
4320     non_constant_p = true;
4321
4322   /* Unshare the result unless it's a CONSTRUCTOR in which case it's already
4323      unshared.  */
4324   bool should_unshare = true;
4325   if (r == t || TREE_CODE (r) == CONSTRUCTOR)
4326     should_unshare = false;
4327
4328   if (non_constant_p && !allow_non_constant)
4329     return error_mark_node;
4330   else if (non_constant_p && TREE_CONSTANT (r))
4331     {
4332       /* This isn't actually constant, so unset TREE_CONSTANT.  */
4333       if (EXPR_P (r))
4334         r = copy_node (r);
4335       else if (TREE_CODE (r) == CONSTRUCTOR)
4336         r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
4337       else
4338         r = build_nop (TREE_TYPE (r), r);
4339       TREE_CONSTANT (r) = false;
4340     }
4341   else if (non_constant_p || r == t)
4342     return t;
4343
4344   if (should_unshare)
4345     r = unshare_expr (r);
4346
4347   if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
4348     {
4349       if (TREE_CODE (t) == TARGET_EXPR
4350           && TARGET_EXPR_INITIAL (t) == r)
4351         return t;
4352       else
4353         {
4354           r = get_target_expr (r);
4355           TREE_CONSTANT (r) = true;
4356           return r;
4357         }
4358     }
4359   else
4360     return r;
4361 }
4362
4363 /* Returns true if T is a valid subexpression of a constant expression,
4364    even if it isn't itself a constant expression.  */
4365
4366 bool
4367 is_sub_constant_expr (tree t)
4368 {
4369   bool non_constant_p = false;
4370   bool overflow_p = false;
4371   hash_map <tree, tree> map;
4372
4373   constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL, true, true };
4374
4375   cxx_eval_constant_expression (&ctx, t, false, &non_constant_p,
4376                                 &overflow_p);
4377   return !non_constant_p && !overflow_p;
4378 }
4379
4380 /* If T represents a constant expression returns its reduced value.
4381    Otherwise return error_mark_node.  If T is dependent, then
4382    return NULL.  */
4383
4384 tree
4385 cxx_constant_value (tree t, tree decl)
4386 {
4387   return cxx_eval_outermost_constant_expr (t, false, true, decl);
4388 }
4389
4390 /* Helper routine for fold_simple function.  Either return simplified
4391    expression T, otherwise NULL_TREE.
4392    In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
4393    even if we are within template-declaration.  So be careful on call, as in
4394    such case types can be undefined.  */
4395
4396 static tree
4397 fold_simple_1 (tree t)
4398 {
4399   tree op1;
4400   enum tree_code code = TREE_CODE (t);
4401
4402   switch (code)
4403     {
4404     case INTEGER_CST:
4405     case REAL_CST:
4406     case VECTOR_CST:
4407     case FIXED_CST:
4408     case COMPLEX_CST:
4409       return t;
4410
4411     case SIZEOF_EXPR:
4412       return fold_sizeof_expr (t);
4413
4414     case ABS_EXPR:
4415     case CONJ_EXPR:
4416     case REALPART_EXPR:
4417     case IMAGPART_EXPR:
4418     case NEGATE_EXPR:
4419     case BIT_NOT_EXPR:
4420     case TRUTH_NOT_EXPR:
4421     case NOP_EXPR:
4422     case VIEW_CONVERT_EXPR:
4423     case CONVERT_EXPR:
4424     case FLOAT_EXPR:
4425     case FIX_TRUNC_EXPR:
4426     case FIXED_CONVERT_EXPR:
4427     case ADDR_SPACE_CONVERT_EXPR:
4428
4429       op1 = TREE_OPERAND (t, 0);
4430
4431       t = const_unop (code, TREE_TYPE (t), op1);
4432       if (!t)
4433         return NULL_TREE;
4434
4435       if (CONVERT_EXPR_CODE_P (code)
4436           && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
4437         TREE_OVERFLOW (t) = false;
4438       return t;
4439
4440     default:
4441       return NULL_TREE;
4442     }
4443 }
4444
4445 /* If T is a simple constant expression, returns its simplified value.
4446    Otherwise returns T.  In contrast to maybe_constant_value do we
4447    simplify only few operations on constant-expressions, and we don't
4448    try to simplify constexpressions.  */
4449
4450 tree
4451 fold_simple (tree t)
4452 {
4453   tree r = NULL_TREE;
4454   if (processing_template_decl)
4455     return t;
4456
4457   r = fold_simple_1 (t);
4458   if (!r)
4459     r = t;
4460
4461   return r;
4462 }
4463
4464 /* If T is a constant expression, returns its reduced value.
4465    Otherwise, if T does not have TREE_CONSTANT set, returns T.
4466    Otherwise, returns a version of T without TREE_CONSTANT.  */
4467
4468 static tree
4469 maybe_constant_value_1 (tree t, tree decl)
4470 {
4471   tree r;
4472
4473   if (!potential_nondependent_constant_expression (t))
4474     {
4475       if (TREE_OVERFLOW_P (t))
4476         {
4477           t = build_nop (TREE_TYPE (t), t);
4478           TREE_CONSTANT (t) = false;
4479         }
4480       return t;
4481     }
4482
4483   r = cxx_eval_outermost_constant_expr (t, true, true, decl);
4484   gcc_checking_assert (r == t
4485                        || CONVERT_EXPR_P (t)
4486                        || TREE_CODE (t) == VIEW_CONVERT_EXPR
4487                        || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4488                        || !cp_tree_equal (r, t));
4489   return r;
4490 }
4491
4492 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
4493
4494 /* If T is a constant expression, returns its reduced value.
4495    Otherwise, if T does not have TREE_CONSTANT set, returns T.
4496    Otherwise, returns a version of T without TREE_CONSTANT.  */
4497
4498 tree
4499 maybe_constant_value (tree t, tree decl)
4500 {
4501   if (cv_cache == NULL)
4502     cv_cache = hash_map<tree, tree>::create_ggc (101);
4503
4504   if (tree *cached = cv_cache->get (t))
4505     return *cached;
4506
4507   tree ret = maybe_constant_value_1 (t, decl);
4508   cv_cache->put (t, ret);
4509   return ret;
4510 }
4511
4512 /* Dispose of the whole CV_CACHE.  */
4513
4514 static void
4515 clear_cv_cache (void)
4516 {
4517   if (cv_cache != NULL)
4518     cv_cache->empty ();
4519 }
4520
4521 /* Dispose of the whole CV_CACHE and FOLD_CACHE.  */
4522
4523 void
4524 clear_cv_and_fold_caches (void)
4525 {
4526   clear_cv_cache ();
4527   clear_fold_cache ();
4528 }
4529
4530 /* Like maybe_constant_value but first fully instantiate the argument.
4531
4532    Note: this is equivalent to instantiate_non_dependent_expr_sfinae
4533    (t, tf_none) followed by maybe_constant_value but is more efficient,
4534    because calls instantiation_dependent_expression_p and
4535    potential_constant_expression at most once.  */
4536
4537 tree
4538 fold_non_dependent_expr (tree t)
4539 {
4540   if (t == NULL_TREE)
4541     return NULL_TREE;
4542
4543   /* If we're in a template, but T isn't value dependent, simplify
4544      it.  We're supposed to treat:
4545
4546        template <typename T> void f(T[1 + 1]);
4547        template <typename T> void f(T[2]);
4548
4549      as two declarations of the same function, for example.  */
4550   if (processing_template_decl)
4551     {
4552       if (potential_nondependent_constant_expression (t))
4553         {
4554           processing_template_decl_sentinel s;
4555           t = instantiate_non_dependent_expr_internal (t, tf_none);
4556
4557           if (type_unknown_p (t)
4558               || BRACE_ENCLOSED_INITIALIZER_P (t))
4559             {
4560               if (TREE_OVERFLOW_P (t))
4561                 {
4562                   t = build_nop (TREE_TYPE (t), t);
4563                   TREE_CONSTANT (t) = false;
4564                 }
4565               return t;
4566             }
4567
4568           tree r = cxx_eval_outermost_constant_expr (t, true, true, NULL_TREE);
4569           /* cp_tree_equal looks through NOPs, so allow them.  */
4570           gcc_checking_assert (r == t
4571                                || CONVERT_EXPR_P (t)
4572                                || TREE_CODE (t) == VIEW_CONVERT_EXPR
4573                                || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4574                                || !cp_tree_equal (r, t));
4575           return r;
4576         }
4577       else if (TREE_OVERFLOW_P (t))
4578         {
4579           t = build_nop (TREE_TYPE (t), t);
4580           TREE_CONSTANT (t) = false;
4581         }
4582       return t;
4583     }
4584
4585   return maybe_constant_value (t);
4586 }
4587
4588 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
4589    than wrapped in a TARGET_EXPR.  */
4590
4591 tree
4592 maybe_constant_init (tree t, tree decl)
4593 {
4594   if (!t)
4595     return t;
4596   if (TREE_CODE (t) == EXPR_STMT)
4597     t = TREE_OPERAND (t, 0);
4598   if (TREE_CODE (t) == CONVERT_EXPR
4599       && VOID_TYPE_P (TREE_TYPE (t)))
4600     t = TREE_OPERAND (t, 0);
4601   if (TREE_CODE (t) == INIT_EXPR)
4602     t = TREE_OPERAND (t, 1);
4603   if (!potential_nondependent_static_init_expression (t))
4604     /* Don't try to evaluate it.  */;
4605   else
4606     t = cxx_eval_outermost_constant_expr (t, true, false, decl);
4607   if (TREE_CODE (t) == TARGET_EXPR)
4608     {
4609       tree init = TARGET_EXPR_INITIAL (t);
4610       if (TREE_CODE (init) == CONSTRUCTOR)
4611         t = init;
4612     }
4613   return t;
4614 }
4615
4616 #if 0
4617 /* FIXME see ADDR_EXPR section in potential_constant_expression_1.  */
4618 /* Return true if the object referred to by REF has automatic or thread
4619    local storage.  */
4620
4621 enum { ck_ok, ck_bad, ck_unknown };
4622 static int
4623 check_automatic_or_tls (tree ref)
4624 {
4625   machine_mode mode;
4626   HOST_WIDE_INT bitsize, bitpos;
4627   tree offset;
4628   int volatilep = 0, unsignedp = 0;
4629   tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
4630                                    &mode, &unsignedp, &volatilep, false);
4631   duration_kind dk;
4632
4633   /* If there isn't a decl in the middle, we don't know the linkage here,
4634      and this isn't a constant expression anyway.  */
4635   if (!DECL_P (decl))
4636     return ck_unknown;
4637   dk = decl_storage_duration (decl);
4638   return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
4639 }
4640 #endif
4641
4642 /* Return true if T denotes a potentially constant expression.  Issue
4643    diagnostic as appropriate under control of FLAGS.  If WANT_RVAL is true,
4644    an lvalue-rvalue conversion is implied.
4645
4646    C++0x [expr.const] used to say
4647
4648    6 An expression is a potential constant expression if it is
4649      a constant expression where all occurrences of function
4650      parameters are replaced by arbitrary constant expressions
4651      of the appropriate type.
4652
4653    2  A conditional expression is a constant expression unless it
4654       involves one of the following as a potentially evaluated
4655       subexpression (3.2), but subexpressions of logical AND (5.14),
4656       logical OR (5.15), and conditional (5.16) operations that are
4657       not evaluated are not considered.   */
4658
4659 static bool
4660 potential_constant_expression_1 (tree t, bool want_rval, bool strict,
4661                                  tsubst_flags_t flags)
4662 {
4663 #define RECUR(T,RV) potential_constant_expression_1 ((T), (RV), strict, flags)
4664   enum { any = false, rval = true };
4665   int i;
4666   tree tmp;
4667
4668   if (t == error_mark_node)
4669     return false;
4670   if (t == NULL_TREE)
4671     return true;
4672   if (TREE_THIS_VOLATILE (t) && !DECL_P (t))
4673     {
4674       if (flags & tf_error)
4675         error ("expression %qE has side-effects", t);
4676       return false;
4677     }
4678   if (CONSTANT_CLASS_P (t))
4679     return true;
4680
4681   switch (TREE_CODE (t))
4682     {
4683     case FUNCTION_DECL:
4684     case BASELINK:
4685     case TEMPLATE_DECL:
4686     case OVERLOAD:
4687     case TEMPLATE_ID_EXPR:
4688     case LABEL_DECL:
4689     case LABEL_EXPR:
4690     case CASE_LABEL_EXPR:
4691     case CONST_DECL:
4692     case SIZEOF_EXPR:
4693     case ALIGNOF_EXPR:
4694     case OFFSETOF_EXPR:
4695     case NOEXCEPT_EXPR:
4696     case TEMPLATE_PARM_INDEX:
4697     case TRAIT_EXPR:
4698     case IDENTIFIER_NODE:
4699     case USERDEF_LITERAL:
4700       /* We can see a FIELD_DECL in a pointer-to-member expression.  */
4701     case FIELD_DECL:
4702     case PARM_DECL:
4703     case RESULT_DECL:
4704     case USING_DECL:
4705     case USING_STMT:
4706     case PLACEHOLDER_EXPR:
4707     case BREAK_STMT:
4708     case CONTINUE_STMT:
4709     case REQUIRES_EXPR:
4710       return true;
4711
4712     case AGGR_INIT_EXPR:
4713     case CALL_EXPR:
4714       /* -- an invocation of a function other than a constexpr function
4715             or a constexpr constructor.  */
4716       {
4717         tree fun = get_function_named_in_call (t);
4718         const int nargs = call_expr_nargs (t);
4719         i = 0;
4720
4721         if (fun == NULL_TREE)
4722           {
4723             if (TREE_CODE (t) == CALL_EXPR
4724                 && CALL_EXPR_FN (t) == NULL_TREE)
4725               switch (CALL_EXPR_IFN (t))
4726                 {
4727                 /* These should be ignored, they are optimized away from
4728                    constexpr functions.  */
4729                 case IFN_UBSAN_NULL:
4730                 case IFN_UBSAN_BOUNDS:
4731                 case IFN_UBSAN_VPTR:
4732                   return true;
4733                 default:
4734                   break;
4735                 }
4736             /* fold_call_expr can't do anything with IFN calls.  */
4737             if (flags & tf_error)
4738               error_at (EXPR_LOC_OR_LOC (t, input_location),
4739                         "call to internal function");
4740             return false;
4741           }
4742         if (is_overloaded_fn (fun))
4743           {
4744             if (TREE_CODE (fun) == FUNCTION_DECL)
4745               {
4746                 if (builtin_valid_in_constant_expr_p (fun))
4747                   return true;
4748                 if (!DECL_DECLARED_CONSTEXPR_P (fun)
4749                     /* Allow any built-in function; if the expansion
4750                        isn't constant, we'll deal with that then.  */
4751                     && !is_builtin_fn (fun))
4752                   {
4753                     if (flags & tf_error)
4754                       {
4755                         error_at (EXPR_LOC_OR_LOC (t, input_location),
4756                                   "call to non-constexpr function %qD", fun);
4757                         explain_invalid_constexpr_fn (fun);
4758                       }
4759                     return false;
4760                   }
4761                 /* A call to a non-static member function takes the address
4762                    of the object as the first argument.  But in a constant
4763                    expression the address will be folded away, so look
4764                    through it now.  */
4765                 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
4766                     && !DECL_CONSTRUCTOR_P (fun))
4767                   {
4768                     tree x = get_nth_callarg (t, 0);
4769                     if (is_this_parameter (x))
4770                       return true;
4771                     else if (!RECUR (x, rval))
4772                       return false;
4773                     i = 1;
4774                   }
4775               }
4776             else
4777               {
4778                 if (!RECUR (fun, true))
4779                   return false;
4780                 fun = get_first_fn (fun);
4781               }
4782             /* Skip initial arguments to base constructors.  */
4783             if (DECL_BASE_CONSTRUCTOR_P (fun))
4784               i = num_artificial_parms_for (fun);
4785             fun = DECL_ORIGIN (fun);
4786           }
4787         else
4788           {
4789             if (RECUR (fun, rval))
4790               /* Might end up being a constant function pointer.  */;
4791             else
4792               return false;
4793           }
4794         for (; i < nargs; ++i)
4795           {
4796             tree x = get_nth_callarg (t, i);
4797             /* In a template, reference arguments haven't been converted to
4798                REFERENCE_TYPE and we might not even know if the parameter
4799                is a reference, so accept lvalue constants too.  */
4800             bool rv = processing_template_decl ? any : rval;
4801             if (!RECUR (x, rv))
4802               return false;
4803           }
4804         return true;
4805       }
4806
4807     case NON_LVALUE_EXPR:
4808       /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
4809             -- an lvalue of integral type that refers to a non-volatile
4810                const variable or static data member initialized with
4811                constant expressions, or
4812
4813             -- an lvalue of literal type that refers to non-volatile
4814                object defined with constexpr, or that refers to a
4815                sub-object of such an object;  */
4816       return RECUR (TREE_OPERAND (t, 0), rval);
4817
4818     case VAR_DECL:
4819       if (want_rval
4820           && !decl_constant_var_p (t)
4821           && (strict
4822               || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
4823               || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t))
4824           && !var_in_constexpr_fn (t)
4825           && !type_dependent_expression_p (t))
4826         {
4827           if (flags & tf_error)
4828             non_const_var_error (t);
4829           return false;
4830         }
4831       return true;
4832
4833     case NOP_EXPR:
4834     case CONVERT_EXPR:
4835     case VIEW_CONVERT_EXPR:
4836       /* -- a reinterpret_cast.  FIXME not implemented, and this rule
4837          may change to something more specific to type-punning (DR 1312).  */
4838       {
4839         tree from = TREE_OPERAND (t, 0);
4840         if (POINTER_TYPE_P (TREE_TYPE (t))
4841             && TREE_CODE (from) == INTEGER_CST
4842             && !integer_zerop (from))
4843           {
4844             if (flags & tf_error)
4845               error_at (EXPR_LOC_OR_LOC (t, input_location),
4846                         "reinterpret_cast from integer to pointer");
4847             return false;
4848           }
4849         return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
4850       }
4851
4852     case ADDR_EXPR:
4853       /* -- a unary operator & that is applied to an lvalue that
4854             designates an object with thread or automatic storage
4855             duration;  */
4856       t = TREE_OPERAND (t, 0);
4857
4858       if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
4859         /* A pointer-to-member constant.  */
4860         return true;
4861
4862 #if 0
4863       /* FIXME adjust when issue 1197 is fully resolved.  For now don't do
4864          any checking here, as we might dereference the pointer later.  If
4865          we remove this code, also remove check_automatic_or_tls.  */
4866       i = check_automatic_or_tls (t);
4867       if (i == ck_ok)
4868         return true;
4869       if (i == ck_bad)
4870         {
4871           if (flags & tf_error)
4872             error ("address-of an object %qE with thread local or "
4873                    "automatic storage is not a constant expression", t);
4874           return false;
4875         }
4876 #endif
4877       return RECUR (t, any);
4878
4879     case COMPONENT_REF:
4880     case BIT_FIELD_REF:
4881     case ARROW_EXPR:
4882     case OFFSET_REF:
4883       /* -- a class member access unless its postfix-expression is
4884             of literal type or of pointer to literal type.  */
4885       /* This test would be redundant, as it follows from the
4886          postfix-expression being a potential constant expression.  */
4887       if (type_unknown_p (t))
4888         return true;
4889       return RECUR (TREE_OPERAND (t, 0), want_rval);
4890
4891     case EXPR_PACK_EXPANSION:
4892       return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
4893
4894     case INDIRECT_REF:
4895       {
4896         tree x = TREE_OPERAND (t, 0);
4897         STRIP_NOPS (x);
4898         if (is_this_parameter (x))
4899           {
4900             if (DECL_CONTEXT (x)
4901                 && !DECL_DECLARED_CONSTEXPR_P (DECL_CONTEXT (x)))
4902               {
4903                 if (flags & tf_error)
4904                   error ("use of %<this%> in a constant expression");
4905                 return false;
4906               }
4907             return true;
4908           }
4909         return RECUR (x, rval);
4910       }
4911
4912     case STATEMENT_LIST:
4913       {
4914         tree_stmt_iterator i;
4915         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
4916           {
4917             if (!RECUR (tsi_stmt (i), any))
4918               return false;
4919           }
4920         return true;
4921       }
4922       break;
4923
4924     case MODIFY_EXPR:
4925       if (cxx_dialect < cxx14)
4926         goto fail;
4927       if (!RECUR (TREE_OPERAND (t, 0), any))
4928         return false;
4929       if (!RECUR (TREE_OPERAND (t, 1), rval))
4930         return false;
4931       return true;
4932
4933     case MODOP_EXPR:
4934       if (cxx_dialect < cxx14)
4935         goto fail;
4936       if (!RECUR (TREE_OPERAND (t, 0), rval))
4937         return false;
4938       if (!RECUR (TREE_OPERAND (t, 2), rval))
4939         return false;
4940       return true;
4941
4942     case DO_STMT:
4943       if (!RECUR (DO_COND (t), rval))
4944         return false;
4945       if (!RECUR (DO_BODY (t), any))
4946         return false;
4947       return true;
4948
4949     case FOR_STMT:
4950       if (!RECUR (FOR_INIT_STMT (t), any))
4951         return false;
4952       if (!RECUR (FOR_COND (t), rval))
4953         return false;
4954       if (!RECUR (FOR_EXPR (t), any))
4955         return false;
4956       if (!RECUR (FOR_BODY (t), any))
4957         return false;
4958       return true;
4959
4960     case WHILE_STMT:
4961       if (!RECUR (WHILE_COND (t), rval))
4962         return false;
4963       if (!RECUR (WHILE_BODY (t), any))
4964         return false;
4965       return true;
4966
4967     case SWITCH_STMT:
4968       if (!RECUR (SWITCH_STMT_COND (t), rval))
4969         return false;
4970       /* FIXME we don't check SWITCH_STMT_BODY currently, because even
4971          unreachable labels would be checked.  */
4972       return true;
4973
4974     case STMT_EXPR:
4975       return RECUR (STMT_EXPR_STMT (t), rval);
4976
4977     case LAMBDA_EXPR:
4978     case DYNAMIC_CAST_EXPR:
4979     case PSEUDO_DTOR_EXPR:
4980     case NEW_EXPR:
4981     case VEC_NEW_EXPR:
4982     case DELETE_EXPR:
4983     case VEC_DELETE_EXPR:
4984     case THROW_EXPR:
4985     case OMP_ATOMIC:
4986     case OMP_ATOMIC_READ:
4987     case OMP_ATOMIC_CAPTURE_OLD:
4988     case OMP_ATOMIC_CAPTURE_NEW:
4989       /* GCC internal stuff.  */
4990     case VA_ARG_EXPR:
4991     case OBJ_TYPE_REF:
4992     case TRANSACTION_EXPR:
4993     case ASM_EXPR:
4994     case AT_ENCODE_EXPR:
4995     fail:
4996       if (flags & tf_error)
4997         error ("expression %qE is not a constant-expression", t);
4998       return false;
4999
5000     case TYPEID_EXPR:
5001       /* -- a typeid expression whose operand is of polymorphic
5002             class type;  */
5003       {
5004         tree e = TREE_OPERAND (t, 0);
5005         if (!TYPE_P (e) && !type_dependent_expression_p (e)
5006             && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
5007           {
5008             if (flags & tf_error)
5009               error ("typeid-expression is not a constant expression "
5010                      "because %qE is of polymorphic type", e);
5011             return false;
5012           }
5013         return true;
5014       }
5015
5016     case MINUS_EXPR:
5017       want_rval = true;
5018       goto binary;
5019
5020     case LT_EXPR:
5021     case LE_EXPR:
5022     case GT_EXPR:
5023     case GE_EXPR:
5024     case EQ_EXPR:
5025     case NE_EXPR:
5026       want_rval = true;
5027       goto binary;
5028
5029     case PREINCREMENT_EXPR:
5030     case POSTINCREMENT_EXPR:
5031     case PREDECREMENT_EXPR:
5032     case POSTDECREMENT_EXPR:
5033       if (cxx_dialect < cxx14)
5034         goto fail;
5035       goto unary;
5036
5037     case BIT_NOT_EXPR:
5038       /* A destructor.  */
5039       if (TYPE_P (TREE_OPERAND (t, 0)))
5040         return true;
5041       /* else fall through.  */
5042
5043     case REALPART_EXPR:
5044     case IMAGPART_EXPR:
5045     case CONJ_EXPR:
5046     case SAVE_EXPR:
5047     case FIX_TRUNC_EXPR:
5048     case FLOAT_EXPR:
5049     case NEGATE_EXPR:
5050     case ABS_EXPR:
5051     case TRUTH_NOT_EXPR:
5052     case FIXED_CONVERT_EXPR:
5053     case UNARY_PLUS_EXPR:
5054     case UNARY_LEFT_FOLD_EXPR:
5055     case UNARY_RIGHT_FOLD_EXPR:
5056     unary:
5057       return RECUR (TREE_OPERAND (t, 0), rval);
5058
5059     case CAST_EXPR:
5060     case CONST_CAST_EXPR:
5061     case STATIC_CAST_EXPR:
5062     case REINTERPRET_CAST_EXPR:
5063     case IMPLICIT_CONV_EXPR:
5064       if (cxx_dialect < cxx11
5065           && !dependent_type_p (TREE_TYPE (t))
5066           && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
5067         /* In C++98, a conversion to non-integral type can't be part of a
5068            constant expression.  */
5069         {
5070           if (flags & tf_error)
5071             error ("cast to non-integral type %qT in a constant expression",
5072                    TREE_TYPE (t));
5073           return false;
5074         }
5075
5076       return (RECUR (TREE_OPERAND (t, 0),
5077                      TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE));
5078
5079     case BIND_EXPR:
5080       return RECUR (BIND_EXPR_BODY (t), want_rval);
5081
5082     case WITH_CLEANUP_EXPR:
5083     case CLEANUP_POINT_EXPR:
5084     case MUST_NOT_THROW_EXPR:
5085     case TRY_CATCH_EXPR:
5086     case TRY_BLOCK:
5087     case EH_SPEC_BLOCK:
5088     case EXPR_STMT:
5089     case PAREN_EXPR:
5090     case DECL_EXPR:
5091     case NON_DEPENDENT_EXPR:
5092       /* For convenience.  */
5093     case RETURN_EXPR:
5094     case LOOP_EXPR:
5095     case EXIT_EXPR:
5096       return RECUR (TREE_OPERAND (t, 0), want_rval);
5097
5098     case TRY_FINALLY_EXPR:
5099       return (RECUR (TREE_OPERAND (t, 0), want_rval)
5100               && RECUR (TREE_OPERAND (t, 1), any));
5101
5102     case SCOPE_REF:
5103       return RECUR (TREE_OPERAND (t, 1), want_rval);
5104
5105     case TARGET_EXPR:
5106       if (!literal_type_p (TREE_TYPE (t)))
5107         {
5108           if (flags & tf_error)
5109             {
5110               error ("temporary of non-literal type %qT in a "
5111                      "constant expression", TREE_TYPE (t));
5112               explain_non_literal_class (TREE_TYPE (t));
5113             }
5114           return false;
5115         }
5116     case INIT_EXPR:
5117       return RECUR (TREE_OPERAND (t, 1), rval);
5118
5119     case CONSTRUCTOR:
5120       {
5121         vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5122         constructor_elt *ce;
5123         for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5124           if (!RECUR (ce->value, want_rval))
5125             return false;
5126         return true;
5127       }
5128
5129     case TREE_LIST:
5130       {
5131         gcc_assert (TREE_PURPOSE (t) == NULL_TREE
5132                     || DECL_P (TREE_PURPOSE (t)));
5133         if (!RECUR (TREE_VALUE (t), want_rval))
5134           return false;
5135         if (TREE_CHAIN (t) == NULL_TREE)
5136           return true;
5137         return RECUR (TREE_CHAIN (t), want_rval);
5138       }
5139
5140     case TRUNC_DIV_EXPR:
5141     case CEIL_DIV_EXPR:
5142     case FLOOR_DIV_EXPR:
5143     case ROUND_DIV_EXPR:
5144     case TRUNC_MOD_EXPR:
5145     case CEIL_MOD_EXPR:
5146     case ROUND_MOD_EXPR:
5147       {
5148         tree denom = TREE_OPERAND (t, 1);
5149         if (!RECUR (denom, rval))
5150           return false;
5151         /* We can't call cxx_eval_outermost_constant_expr on an expression
5152            that hasn't been through instantiate_non_dependent_expr yet.  */
5153         if (!processing_template_decl)
5154           denom = cxx_eval_outermost_constant_expr (denom, true);
5155         if (integer_zerop (denom))
5156           {
5157             if (flags & tf_error)
5158               error ("division by zero is not a constant-expression");
5159             return false;
5160           }
5161         else
5162           {
5163             want_rval = true;
5164             return RECUR (TREE_OPERAND (t, 0), want_rval);
5165           }
5166       }
5167
5168     case COMPOUND_EXPR:
5169       {
5170         /* check_return_expr sometimes wraps a TARGET_EXPR in a
5171            COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
5172            introduced by build_call_a.  */
5173         tree op0 = TREE_OPERAND (t, 0);
5174         tree op1 = TREE_OPERAND (t, 1);
5175         STRIP_NOPS (op1);
5176         if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
5177             || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
5178           return RECUR (op0, want_rval);
5179         else
5180           goto binary;
5181       }
5182
5183       /* If the first operand is the non-short-circuit constant, look at
5184          the second operand; otherwise we only care about the first one for
5185          potentiality.  */
5186     case TRUTH_AND_EXPR:
5187     case TRUTH_ANDIF_EXPR:
5188       tmp = boolean_true_node;
5189       goto truth;
5190     case TRUTH_OR_EXPR:
5191     case TRUTH_ORIF_EXPR:
5192       tmp = boolean_false_node;
5193     truth:
5194       {
5195         tree op = TREE_OPERAND (t, 0);
5196         if (!RECUR (op, rval))
5197           return false;
5198         if (!processing_template_decl)
5199           op = cxx_eval_outermost_constant_expr (op, true);
5200         if (tree_int_cst_equal (op, tmp))
5201           return RECUR (TREE_OPERAND (t, 1), rval);
5202         else
5203           return true;
5204       }
5205
5206     case PLUS_EXPR:
5207     case MULT_EXPR:
5208     case POINTER_PLUS_EXPR:
5209     case RDIV_EXPR:
5210     case EXACT_DIV_EXPR:
5211     case MIN_EXPR:
5212     case MAX_EXPR:
5213     case LSHIFT_EXPR:
5214     case RSHIFT_EXPR:
5215     case LROTATE_EXPR:
5216     case RROTATE_EXPR:
5217     case BIT_IOR_EXPR:
5218     case BIT_XOR_EXPR:
5219     case BIT_AND_EXPR:
5220     case TRUTH_XOR_EXPR:
5221     case UNORDERED_EXPR:
5222     case ORDERED_EXPR:
5223     case UNLT_EXPR:
5224     case UNLE_EXPR:
5225     case UNGT_EXPR:
5226     case UNGE_EXPR:
5227     case UNEQ_EXPR:
5228     case LTGT_EXPR:
5229     case RANGE_EXPR:
5230     case COMPLEX_EXPR:
5231       want_rval = true;
5232       /* Fall through.  */
5233     case ARRAY_REF:
5234     case ARRAY_RANGE_REF:
5235     case MEMBER_REF:
5236     case DOTSTAR_EXPR:
5237     case MEM_REF:
5238     case BINARY_LEFT_FOLD_EXPR:
5239     case BINARY_RIGHT_FOLD_EXPR:
5240     binary:
5241       for (i = 0; i < 2; ++i)
5242         if (!RECUR (TREE_OPERAND (t, i), want_rval))
5243           return false;
5244       return true;
5245
5246     case CILK_SYNC_STMT:
5247     case CILK_SPAWN_STMT:
5248     case ARRAY_NOTATION_REF:
5249       return false;
5250
5251     case FMA_EXPR:
5252     case VEC_PERM_EXPR:
5253      for (i = 0; i < 3; ++i)
5254       if (!RECUR (TREE_OPERAND (t, i), true))
5255         return false;
5256      return true;
5257
5258     case COND_EXPR:
5259       if (COND_EXPR_IS_VEC_DELETE (t))
5260         {
5261           if (flags & tf_error)
5262             error_at (location_of (t),
5263                       "%<delete[]%> is not a constant-expression");
5264           return false;
5265         }
5266       /* Fall through.  */
5267     case IF_STMT:
5268     case VEC_COND_EXPR:
5269       /* If the condition is a known constant, we know which of the legs we
5270          care about; otherwise we only require that the condition and
5271          either of the legs be potentially constant.  */
5272       tmp = TREE_OPERAND (t, 0);
5273       if (!RECUR (tmp, rval))
5274         return false;
5275       if (!processing_template_decl)
5276         tmp = cxx_eval_outermost_constant_expr (tmp, true);
5277       if (integer_zerop (tmp))
5278         return RECUR (TREE_OPERAND (t, 2), want_rval);
5279       else if (TREE_CODE (tmp) == INTEGER_CST)
5280         return RECUR (TREE_OPERAND (t, 1), want_rval);
5281       for (i = 1; i < 3; ++i)
5282         if (potential_constant_expression_1 (TREE_OPERAND (t, i),
5283                                              want_rval, strict, tf_none))
5284           return true;
5285       if (flags & tf_error)
5286         error ("expression %qE is not a constant-expression", t);
5287       return false;
5288
5289     case VEC_INIT_EXPR:
5290       if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
5291         return true;
5292       if (flags & tf_error)
5293         {
5294           error ("non-constant array initialization");
5295           diagnose_non_constexpr_vec_init (t);
5296         }
5297       return false;
5298
5299     case TYPE_DECL:
5300     case TAG_DEFN:
5301     case STATEMENT_LIST_END:
5302       /* We can see these in statement-expressions.  */
5303       return true;
5304
5305     case CLEANUP_STMT:
5306     case EMPTY_CLASS_EXPR:
5307       return false;
5308
5309     case GOTO_EXPR:
5310       {
5311         tree *target = &TREE_OPERAND (t, 0);
5312         /* Gotos representing break and continue are OK.  */
5313         if (breaks (target) || continues (target))
5314           return true;
5315         if (flags & tf_error)
5316           error ("%<goto%> is not a constant-expression");
5317         return false;
5318       }
5319
5320     default:
5321       if (objc_is_property_ref (t))
5322         return false;
5323
5324       sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
5325       gcc_unreachable ();
5326       return false;
5327     }
5328 #undef RECUR
5329 }
5330
5331 /* The main entry point to the above.  */
5332
5333 bool
5334 potential_constant_expression (tree t)
5335 {
5336   return potential_constant_expression_1 (t, false, true, tf_none);
5337 }
5338
5339 bool
5340 potential_static_init_expression (tree t)
5341 {
5342   return potential_constant_expression_1 (t, false, false, tf_none);
5343 }
5344
5345 /* As above, but require a constant rvalue.  */
5346
5347 bool
5348 potential_rvalue_constant_expression (tree t)
5349 {
5350   return potential_constant_expression_1 (t, true, true, tf_none);
5351 }
5352
5353 /* Like above, but complain about non-constant expressions.  */
5354
5355 bool
5356 require_potential_constant_expression (tree t)
5357 {
5358   return potential_constant_expression_1 (t, false, true, tf_warning_or_error);
5359 }
5360
5361 /* Cross product of the above.  */
5362
5363 bool
5364 require_potential_rvalue_constant_expression (tree t)
5365 {
5366   return potential_constant_expression_1 (t, true, true, tf_warning_or_error);
5367 }
5368
5369 /* Returns true if T is a potential constant expression that is not
5370    instantiation-dependent, and therefore a candidate for constant folding even
5371    in a template.  */
5372
5373 bool
5374 potential_nondependent_constant_expression (tree t)
5375 {
5376   return (!type_unknown_p (t)
5377           && !BRACE_ENCLOSED_INITIALIZER_P (t)
5378           && potential_constant_expression (t)
5379           && !instantiation_dependent_expression_p (t));
5380 }
5381
5382 /* Returns true if T is a potential static initializer expression that is not
5383    instantiation-dependent.  */
5384
5385 bool
5386 potential_nondependent_static_init_expression (tree t)
5387 {
5388   return (!type_unknown_p (t)
5389           && !BRACE_ENCLOSED_INITIALIZER_P (t)
5390           && potential_static_init_expression (t)
5391           && !instantiation_dependent_expression_p (t));
5392 }
5393
5394 /* Finalize constexpr processing after parsing.  */
5395
5396 void
5397 fini_constexpr (void)
5398 {
5399   /* The contexpr call and fundef copies tables are no longer needed.  */
5400   constexpr_call_table = NULL;
5401   fundef_copies_table = NULL;
5402 }
5403
5404 #include "gt-cp-constexpr.h"