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-2020 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 #include "gimple-fold.h"
35 #include "timevar.h"
36 #include "fold-const-call.h"
37 #include "stor-layout.h"
38 #include "cgraph.h"
39 
40 static bool verify_constant (tree, bool, bool *, bool *);
41 #define VERIFY_CONSTANT(X)						\
42 do {									\
43   if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
44     return t;								\
45  } while (0)
46 
47 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
48 					  bool insert = false);
49 
50 /* Returns true iff FUN is an instantiation of a constexpr function
51    template or a defaulted constexpr function.  */
52 
53 bool
is_instantiation_of_constexpr(tree fun)54 is_instantiation_of_constexpr (tree fun)
55 {
56   return ((DECL_TEMPLOID_INSTANTIATION (fun)
57 	   && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
58 	  || (DECL_DEFAULTED_FN (fun)
59 	      && DECL_DECLARED_CONSTEXPR_P (fun)));
60 }
61 
62 /* Return true if T is a literal type.   */
63 
64 bool
literal_type_p(tree t)65 literal_type_p (tree t)
66 {
67   if (SCALAR_TYPE_P (t)
68       || VECTOR_TYPE_P (t)
69       || TYPE_REF_P (t)
70       || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
71     return true;
72   if (CLASS_TYPE_P (t))
73     {
74       t = complete_type (t);
75       gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
76       return CLASSTYPE_LITERAL_P (t);
77     }
78   if (TREE_CODE (t) == ARRAY_TYPE)
79     return literal_type_p (strip_array_types (t));
80   return false;
81 }
82 
83 /* If DECL is a variable declared `constexpr', require its type
84    be literal.  Return error_mark_node if we give an error, the
85    DECL otherwise.  */
86 
87 tree
ensure_literal_type_for_constexpr_object(tree decl)88 ensure_literal_type_for_constexpr_object (tree decl)
89 {
90   tree type = TREE_TYPE (decl);
91   if (VAR_P (decl)
92       && (DECL_DECLARED_CONSTEXPR_P (decl)
93 	  || var_in_constexpr_fn (decl))
94       && !processing_template_decl)
95     {
96       tree stype = strip_array_types (type);
97       if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
98 	/* Don't complain here, we'll complain about incompleteness
99 	   when we try to initialize the variable.  */;
100       else if (type_uses_auto (type))
101 	/* We don't know the actual type yet.  */;
102       else if (!literal_type_p (type))
103 	{
104 	  if (DECL_DECLARED_CONSTEXPR_P (decl))
105 	    {
106 	      auto_diagnostic_group d;
107 	      error_at (DECL_SOURCE_LOCATION (decl),
108 			"the type %qT of %<constexpr%> variable %qD "
109 			"is not literal", type, decl);
110 	      explain_non_literal_class (type);
111 	      decl = error_mark_node;
112 	    }
113 	  else
114 	    {
115 	      if (!is_instantiation_of_constexpr (current_function_decl))
116 		{
117 		  auto_diagnostic_group d;
118 		  error_at (DECL_SOURCE_LOCATION (decl),
119 			    "variable %qD of non-literal type %qT in "
120 			    "%<constexpr%> function", decl, type);
121 		  explain_non_literal_class (type);
122 		  decl = error_mark_node;
123 		}
124 	      cp_function_chain->invalid_constexpr = true;
125 	    }
126 	}
127       else if (DECL_DECLARED_CONSTEXPR_P (decl)
128 	       && variably_modified_type_p (type, NULL_TREE))
129 	{
130 	  error_at (DECL_SOURCE_LOCATION (decl),
131 		    "%<constexpr%> variable %qD has variably-modified "
132 		    "type %qT", decl, type);
133 	  decl = error_mark_node;
134 	}
135     }
136   return decl;
137 }
138 
139 /* Representation of entries in the constexpr function definition table.  */
140 
141 struct GTY((for_user)) constexpr_fundef {
142   tree decl;
143   tree body;
144   tree parms;
145   tree result;
146 };
147 
148 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
149 {
150   static hashval_t hash (constexpr_fundef *);
151   static bool equal (constexpr_fundef *, constexpr_fundef *);
152 };
153 
154 /* This table holds all constexpr function definitions seen in
155    the current translation unit.  */
156 
157 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
158 
159 /* Utility function used for managing the constexpr function table.
160    Return true if the entries pointed to by P and Q are for the
161    same constexpr function.  */
162 
163 inline bool
equal(constexpr_fundef * lhs,constexpr_fundef * rhs)164 constexpr_fundef_hasher::equal (constexpr_fundef *lhs, constexpr_fundef *rhs)
165 {
166   return lhs->decl == rhs->decl;
167 }
168 
169 /* Utility function used for managing the constexpr function table.
170    Return a hash value for the entry pointed to by Q.  */
171 
172 inline hashval_t
hash(constexpr_fundef * fundef)173 constexpr_fundef_hasher::hash (constexpr_fundef *fundef)
174 {
175   return DECL_UID (fundef->decl);
176 }
177 
178 /* Return a previously saved definition of function FUN.   */
179 
180 static constexpr_fundef *
retrieve_constexpr_fundef(tree fun)181 retrieve_constexpr_fundef (tree fun)
182 {
183   if (constexpr_fundef_table == NULL)
184     return NULL;
185 
186   constexpr_fundef fundef = { fun, NULL, NULL, NULL };
187   return constexpr_fundef_table->find (&fundef);
188 }
189 
190 /* Check whether the parameter and return types of FUN are valid for a
191    constexpr function, and complain if COMPLAIN.  */
192 
193 bool
is_valid_constexpr_fn(tree fun,bool complain)194 is_valid_constexpr_fn (tree fun, bool complain)
195 {
196   bool ret = true;
197 
198   if (DECL_INHERITED_CTOR (fun)
199       && TREE_CODE (fun) == TEMPLATE_DECL)
200     {
201       ret = false;
202       if (complain)
203 	error ("inherited constructor %qD is not %<constexpr%>",
204 	       DECL_INHERITED_CTOR (fun));
205     }
206   else
207     {
208       for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
209 	   parm != NULL_TREE; parm = TREE_CHAIN (parm))
210 	if (!literal_type_p (TREE_TYPE (parm)))
211 	  {
212 	    ret = false;
213 	    if (complain)
214 	      {
215 		auto_diagnostic_group d;
216 		error ("invalid type for parameter %d of %<constexpr%> "
217 		       "function %q+#D", DECL_PARM_INDEX (parm), fun);
218 		explain_non_literal_class (TREE_TYPE (parm));
219 	      }
220 	  }
221     }
222 
223   if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
224     {
225       ret = false;
226       if (complain)
227 	inform (DECL_SOURCE_LOCATION (fun),
228 		"lambdas are implicitly %<constexpr%> only in C++17 and later");
229     }
230   else if (!DECL_CONSTRUCTOR_P (fun))
231     {
232       tree rettype = TREE_TYPE (TREE_TYPE (fun));
233       if (!literal_type_p (rettype))
234 	{
235 	  ret = false;
236 	  if (complain)
237 	    {
238 	      auto_diagnostic_group d;
239 	      error ("invalid return type %qT of %<constexpr%> function %q+D",
240 		     rettype, fun);
241 	      explain_non_literal_class (rettype);
242 	    }
243 	}
244 
245       /* C++14 DR 1684 removed this restriction.  */
246       if (cxx_dialect < cxx14
247 	  && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
248 	  && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
249 	{
250 	  ret = false;
251 	  if (complain)
252 	    {
253 	      auto_diagnostic_group d;
254 	      if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
255 			     "enclosing class of %<constexpr%> non-static"
256 			     " member function %q+#D is not a literal type",
257 			     fun))
258 		explain_non_literal_class (DECL_CONTEXT (fun));
259 	    }
260 	}
261     }
262   else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
263     {
264       ret = false;
265       if (complain)
266 	error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
267     }
268 
269   return ret;
270 }
271 
272 /* Subroutine of build_data_member_initialization.  MEMBER is a COMPONENT_REF
273    for a member of an anonymous aggregate, INIT is the initializer for that
274    member, and VEC_OUTER is the vector of constructor elements for the class
275    whose constructor we are processing.  Add the initializer to the vector
276    and return true to indicate success.  */
277 
278 static bool
build_anon_member_initialization(tree member,tree init,vec<constructor_elt,va_gc> ** vec_outer)279 build_anon_member_initialization (tree member, tree init,
280 				  vec<constructor_elt, va_gc> **vec_outer)
281 {
282   /* MEMBER presents the relevant fields from the inside out, but we need
283      to build up the initializer from the outside in so that we can reuse
284      previously built CONSTRUCTORs if this is, say, the second field in an
285      anonymous struct.  So we use a vec as a stack.  */
286   auto_vec<tree, 2> fields;
287   do
288     {
289       fields.safe_push (TREE_OPERAND (member, 1));
290       member = TREE_OPERAND (member, 0);
291     }
292   while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
293 	 && TREE_CODE (member) == COMPONENT_REF);
294 
295   /* VEC has the constructor elements vector for the context of FIELD.
296      If FIELD is an anonymous aggregate, we will push inside it.  */
297   vec<constructor_elt, va_gc> **vec = vec_outer;
298   tree field;
299   while (field = fields.pop(),
300 	 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
301     {
302       tree ctor;
303       /* If there is already an outer constructor entry for the anonymous
304 	 aggregate FIELD, use it; otherwise, insert one.  */
305       if (vec_safe_is_empty (*vec)
306 	  || (*vec)->last().index != field)
307 	{
308 	  ctor = build_constructor (TREE_TYPE (field), NULL);
309 	  CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
310 	}
311       else
312 	ctor = (*vec)->last().value;
313       vec = &CONSTRUCTOR_ELTS (ctor);
314     }
315 
316   /* Now we're at the innermost field, the one that isn't an anonymous
317      aggregate.  Add its initializer to the CONSTRUCTOR and we're done.  */
318   gcc_assert (fields.is_empty());
319   CONSTRUCTOR_APPEND_ELT (*vec, field, init);
320 
321   return true;
322 }
323 
324 /* Subroutine of  build_constexpr_constructor_member_initializers.
325    The expression tree T represents a data member initialization
326    in a (constexpr) constructor definition.  Build a pairing of
327    the data member with its initializer, and prepend that pair
328    to the existing initialization pair INITS.  */
329 
330 static bool
build_data_member_initialization(tree t,vec<constructor_elt,va_gc> ** vec)331 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
332 {
333   tree member, init;
334   if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
335     t = TREE_OPERAND (t, 0);
336   if (TREE_CODE (t) == EXPR_STMT)
337     t = TREE_OPERAND (t, 0);
338   if (t == error_mark_node)
339     return false;
340   if (TREE_CODE (t) == STATEMENT_LIST)
341     {
342       tree_stmt_iterator i;
343       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
344 	{
345 	  if (! build_data_member_initialization (tsi_stmt (i), vec))
346 	    return false;
347 	}
348       return true;
349     }
350   if (TREE_CODE (t) == CLEANUP_STMT)
351     {
352       /* We can't see a CLEANUP_STMT in a constructor for a literal class,
353 	 but we can in a constexpr constructor for a non-literal class.  Just
354 	 ignore it; either all the initialization will be constant, in which
355 	 case the cleanup can't run, or it can't be constexpr.
356 	 Still recurse into CLEANUP_BODY.  */
357       return build_data_member_initialization (CLEANUP_BODY (t), vec);
358     }
359   if (TREE_CODE (t) == CONVERT_EXPR)
360     t = TREE_OPERAND (t, 0);
361   if (TREE_CODE (t) == INIT_EXPR
362       /* vptr initialization shows up as a MODIFY_EXPR.  In C++14 we only
363 	 use what this function builds for cx_check_missing_mem_inits, and
364 	 assignment in the ctor body doesn't count.  */
365       || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
366     {
367       member = TREE_OPERAND (t, 0);
368       init = break_out_target_exprs (TREE_OPERAND (t, 1));
369     }
370   else if (TREE_CODE (t) == CALL_EXPR)
371     {
372       tree fn = get_callee_fndecl (t);
373       if (!fn || !DECL_CONSTRUCTOR_P (fn))
374 	/* We're only interested in calls to subobject constructors.  */
375 	return true;
376       member = CALL_EXPR_ARG (t, 0);
377       /* We don't use build_cplus_new here because it complains about
378 	 abstract bases.  Leaving the call unwrapped means that it has the
379 	 wrong type, but cxx_eval_constant_expression doesn't care.  */
380       init = break_out_target_exprs (t);
381     }
382   else if (TREE_CODE (t) == BIND_EXPR)
383     return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
384   else
385     /* Don't add anything else to the CONSTRUCTOR.  */
386     return true;
387   if (INDIRECT_REF_P (member))
388     member = TREE_OPERAND (member, 0);
389   if (TREE_CODE (member) == NOP_EXPR)
390     {
391       tree op = member;
392       STRIP_NOPS (op);
393       if (TREE_CODE (op) == ADDR_EXPR)
394 	{
395 	  gcc_assert (same_type_ignoring_top_level_qualifiers_p
396 		      (TREE_TYPE (TREE_TYPE (op)),
397 		       TREE_TYPE (TREE_TYPE (member))));
398 	  /* Initializing a cv-qualified member; we need to look through
399 	     the const_cast.  */
400 	  member = op;
401 	}
402       else if (op == current_class_ptr
403 	       && (same_type_ignoring_top_level_qualifiers_p
404 		   (TREE_TYPE (TREE_TYPE (member)),
405 		    current_class_type)))
406 	/* Delegating constructor.  */
407 	member = op;
408       else
409 	{
410 	  /* This is an initializer for an empty base; keep it for now so
411 	     we can check it in cxx_eval_bare_aggregate.  */
412 	  gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
413 	}
414     }
415   if (TREE_CODE (member) == ADDR_EXPR)
416     member = TREE_OPERAND (member, 0);
417   if (TREE_CODE (member) == COMPONENT_REF)
418     {
419       tree aggr = TREE_OPERAND (member, 0);
420       if (TREE_CODE (aggr) == VAR_DECL)
421 	/* Initializing a local variable, don't add anything.  */
422 	return true;
423       if (TREE_CODE (aggr) != COMPONENT_REF)
424 	/* Normal member initialization.  */
425 	member = TREE_OPERAND (member, 1);
426       else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
427 	/* Initializing a member of an anonymous union.  */
428 	return build_anon_member_initialization (member, init, vec);
429       else
430 	/* We're initializing a vtable pointer in a base.  Leave it as
431 	   COMPONENT_REF so we remember the path to get to the vfield.  */
432 	gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
433     }
434 
435   /* Value-initialization can produce multiple initializers for the
436      same field; use the last one.  */
437   if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
438     (*vec)->last().value = init;
439   else
440     CONSTRUCTOR_APPEND_ELT (*vec, member, init);
441   return true;
442 }
443 
444 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
445    In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
446    BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations.  */
447 
448 static bool
check_constexpr_bind_expr_vars(tree t)449 check_constexpr_bind_expr_vars (tree t)
450 {
451   gcc_assert (TREE_CODE (t) == BIND_EXPR);
452 
453   for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
454     if (TREE_CODE (var) == TYPE_DECL
455 	&& DECL_IMPLICIT_TYPEDEF_P (var)
456 	&& !LAMBDA_TYPE_P (TREE_TYPE (var)))
457       return false;
458   return true;
459 }
460 
461 /* Subroutine of check_constexpr_ctor_body.  */
462 
463 static bool
check_constexpr_ctor_body_1(tree last,tree list)464 check_constexpr_ctor_body_1 (tree last, tree list)
465 {
466   switch (TREE_CODE (list))
467     {
468     case DECL_EXPR:
469       if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
470 	  || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
471 	return true;
472       return false;
473 
474     case CLEANUP_POINT_EXPR:
475       return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
476 					/*complain=*/false);
477 
478     case BIND_EXPR:
479        if (!check_constexpr_bind_expr_vars (list)
480 	   || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
481 					  /*complain=*/false))
482 	 return false;
483        return true;
484 
485     case USING_STMT:
486     case STATIC_ASSERT:
487     case DEBUG_BEGIN_STMT:
488       return true;
489 
490     default:
491       return false;
492     }
493 }
494 
495 /* Make sure that there are no statements after LAST in the constructor
496    body represented by LIST.  */
497 
498 bool
check_constexpr_ctor_body(tree last,tree list,bool complain)499 check_constexpr_ctor_body (tree last, tree list, bool complain)
500 {
501   /* C++14 doesn't require a constexpr ctor to have an empty body.  */
502   if (cxx_dialect >= cxx14)
503     return true;
504 
505   bool ok = true;
506   if (TREE_CODE (list) == STATEMENT_LIST)
507     {
508       tree_stmt_iterator i = tsi_last (list);
509       for (; !tsi_end_p (i); tsi_prev (&i))
510 	{
511 	  tree t = tsi_stmt (i);
512 	  if (t == last)
513 	    break;
514 	  if (!check_constexpr_ctor_body_1 (last, t))
515 	    {
516 	      ok = false;
517 	      break;
518 	    }
519 	}
520     }
521   else if (list != last
522 	   && !check_constexpr_ctor_body_1 (last, list))
523     ok = false;
524   if (!ok)
525     {
526       if (complain)
527 	error ("%<constexpr%> constructor does not have empty body");
528       DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
529     }
530   return ok;
531 }
532 
533 /* V is a vector of constructor elements built up for the base and member
534    initializers of a constructor for TYPE.  They need to be in increasing
535    offset order, which they might not be yet if TYPE has a primary base
536    which is not first in the base-clause or a vptr and at least one base
537    all of which are non-primary.  */
538 
539 static vec<constructor_elt, va_gc> *
sort_constexpr_mem_initializers(tree type,vec<constructor_elt,va_gc> * v)540 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
541 {
542   tree pri = CLASSTYPE_PRIMARY_BINFO (type);
543   tree field_type;
544   unsigned i;
545   constructor_elt *ce;
546 
547   if (pri)
548     field_type = BINFO_TYPE (pri);
549   else if (TYPE_CONTAINS_VPTR_P (type))
550     field_type = vtbl_ptr_type_node;
551   else
552     return v;
553 
554   /* Find the element for the primary base or vptr and move it to the
555      beginning of the vec.  */
556   for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
557     if (TREE_TYPE (ce->index) == field_type)
558       break;
559 
560   if (i > 0 && i < vec_safe_length (v))
561     {
562       vec<constructor_elt, va_gc> &vref = *v;
563       constructor_elt elt = vref[i];
564       for (; i > 0; --i)
565 	vref[i] = vref[i-1];
566       vref[0] = elt;
567     }
568 
569   return v;
570 }
571 
572 /* Build compile-time evalable representations of member-initializer list
573    for a constexpr constructor.  */
574 
575 static tree
build_constexpr_constructor_member_initializers(tree type,tree body)576 build_constexpr_constructor_member_initializers (tree type, tree body)
577 {
578   vec<constructor_elt, va_gc> *vec = NULL;
579   bool ok = true;
580   while (true)
581     switch (TREE_CODE (body))
582       {
583       case MUST_NOT_THROW_EXPR:
584       case EH_SPEC_BLOCK:
585 	body = TREE_OPERAND (body, 0);
586 	break;
587 
588       case STATEMENT_LIST:
589 	for (tree_stmt_iterator i = tsi_start (body);
590 	     !tsi_end_p (i); tsi_next (&i))
591 	  {
592 	    body = tsi_stmt (i);
593 	    if (TREE_CODE (body) == BIND_EXPR)
594 	      break;
595 	  }
596 	break;
597 
598       case BIND_EXPR:
599 	body = BIND_EXPR_BODY (body);
600 	goto found;
601 
602       default:
603 	gcc_unreachable ();
604     }
605  found:
606   if (TREE_CODE (body) == TRY_BLOCK)
607     {
608       body = TREE_OPERAND (body, 0);
609       if (TREE_CODE (body) == BIND_EXPR)
610 	body = BIND_EXPR_BODY (body);
611     }
612   if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
613     {
614       body = TREE_OPERAND (body, 0);
615       if (TREE_CODE (body) == EXPR_STMT)
616 	body = TREE_OPERAND (body, 0);
617       if (TREE_CODE (body) == INIT_EXPR
618 	  && (same_type_ignoring_top_level_qualifiers_p
619 	      (TREE_TYPE (TREE_OPERAND (body, 0)),
620 	       current_class_type)))
621 	{
622 	  /* Trivial copy.  */
623 	  return TREE_OPERAND (body, 1);
624 	}
625       ok = build_data_member_initialization (body, &vec);
626     }
627   else if (TREE_CODE (body) == STATEMENT_LIST)
628     {
629       tree_stmt_iterator i;
630       for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
631 	{
632 	  ok = build_data_member_initialization (tsi_stmt (i), &vec);
633 	  if (!ok)
634 	    break;
635 	}
636     }
637   else if (EXPR_P (body))
638     ok = build_data_member_initialization (body, &vec);
639   else
640     gcc_assert (errorcount > 0);
641   if (ok)
642     {
643       if (vec_safe_length (vec) > 0)
644 	{
645 	  /* In a delegating constructor, return the target.  */
646 	  constructor_elt *ce = &(*vec)[0];
647 	  if (ce->index == current_class_ptr)
648 	    {
649 	      body = ce->value;
650 	      vec_free (vec);
651 	      return body;
652 	    }
653 	}
654       vec = sort_constexpr_mem_initializers (type, vec);
655       return build_constructor (type, vec);
656     }
657   else
658     return error_mark_node;
659 }
660 
661 /* We have an expression tree T that represents a call, either CALL_EXPR
662    or AGGR_INIT_EXPR.  If the call is lexically to a named function,
663    retrun the _DECL for that function.  */
664 
665 static tree
get_function_named_in_call(tree t)666 get_function_named_in_call (tree t)
667 {
668   tree fun = cp_get_callee (t);
669   if (fun && TREE_CODE (fun) == ADDR_EXPR
670       && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
671     fun = TREE_OPERAND (fun, 0);
672   return fun;
673 }
674 
675 /* Subroutine of register_constexpr_fundef.  BODY is the body of a function
676    declared to be constexpr, or a sub-statement thereof.  Returns the
677    return value if suitable, error_mark_node for a statement not allowed in
678    a constexpr function, or NULL_TREE if no return value was found.  */
679 
680 tree
constexpr_fn_retval(tree body)681 constexpr_fn_retval (tree body)
682 {
683   switch (TREE_CODE (body))
684     {
685     case STATEMENT_LIST:
686       {
687 	tree_stmt_iterator i;
688 	tree expr = NULL_TREE;
689 	for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
690 	  {
691 	    tree s = constexpr_fn_retval (tsi_stmt (i));
692 	    if (s == error_mark_node)
693 	      return error_mark_node;
694 	    else if (s == NULL_TREE)
695 	      /* Keep iterating.  */;
696 	    else if (expr)
697 	      /* Multiple return statements.  */
698 	      return error_mark_node;
699 	    else
700 	      expr = s;
701 	  }
702 	return expr;
703       }
704 
705     case RETURN_EXPR:
706       return break_out_target_exprs (TREE_OPERAND (body, 0));
707 
708     case DECL_EXPR:
709       {
710 	tree decl = DECL_EXPR_DECL (body);
711 	if (TREE_CODE (decl) == USING_DECL
712 	    /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__.  */
713 	    || DECL_ARTIFICIAL (decl))
714 	  return NULL_TREE;
715 	return error_mark_node;
716       }
717 
718     case CLEANUP_POINT_EXPR:
719       return constexpr_fn_retval (TREE_OPERAND (body, 0));
720 
721     case BIND_EXPR:
722       if (!check_constexpr_bind_expr_vars (body))
723 	return error_mark_node;
724       return constexpr_fn_retval (BIND_EXPR_BODY (body));
725 
726     case USING_STMT:
727     case DEBUG_BEGIN_STMT:
728       return NULL_TREE;
729 
730     case CALL_EXPR:
731 	{
732 	  tree fun = get_function_named_in_call (body);
733 	  if (fun != NULL_TREE
734 	      && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
735 	    return NULL_TREE;
736 	}
737       /* Fallthru.  */
738 
739     default:
740       return error_mark_node;
741     }
742 }
743 
744 /* Subroutine of register_constexpr_fundef.  BODY is the DECL_SAVED_TREE of
745    FUN; do the necessary transformations to turn it into a single expression
746    that we can store in the hash table.  */
747 
748 static tree
massage_constexpr_body(tree fun,tree body)749 massage_constexpr_body (tree fun, tree body)
750 {
751   if (DECL_CONSTRUCTOR_P (fun))
752     body = build_constexpr_constructor_member_initializers
753       (DECL_CONTEXT (fun), body);
754   else if (cxx_dialect < cxx14)
755     {
756       if (TREE_CODE (body) == EH_SPEC_BLOCK)
757         body = EH_SPEC_STMTS (body);
758       if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
759 	body = TREE_OPERAND (body, 0);
760       body = constexpr_fn_retval (body);
761     }
762   return body;
763 }
764 
765 /* CTYPE is a type constructed from BODY.  Return true if some
766    bases/fields are uninitialized, and complain if COMPLAIN.  */
767 
768 static bool
cx_check_missing_mem_inits(tree ctype,tree body,bool complain)769 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
770 {
771   /* We allow uninitialized bases/fields in C++20.  */
772   if (cxx_dialect >= cxx2a)
773     return false;
774 
775   unsigned nelts = 0;
776 
777   if (body)
778     {
779       if (TREE_CODE (body) != CONSTRUCTOR)
780 	return false;
781       nelts = CONSTRUCTOR_NELTS (body);
782     }
783   tree field = TYPE_FIELDS (ctype);
784 
785   if (TREE_CODE (ctype) == UNION_TYPE)
786     {
787       if (nelts == 0 && next_initializable_field (field))
788 	{
789 	  if (complain)
790 	    error ("%<constexpr%> constructor for union %qT must "
791 		   "initialize exactly one non-static data member", ctype);
792 	  return true;
793 	}
794       return false;
795     }
796 
797   /* Iterate over the CONSTRUCTOR, checking any missing fields don't
798      need an explicit initialization.  */
799   bool bad = false;
800   for (unsigned i = 0; i <= nelts; ++i)
801     {
802       tree index = NULL_TREE;
803       if (i < nelts)
804 	{
805 	  index = CONSTRUCTOR_ELT (body, i)->index;
806 	  /* Skip base and vtable inits.  */
807 	  if (TREE_CODE (index) != FIELD_DECL
808 	      || DECL_ARTIFICIAL (index))
809 	    continue;
810 	}
811 
812       for (; field != index; field = DECL_CHAIN (field))
813 	{
814 	  tree ftype;
815 	  if (TREE_CODE (field) != FIELD_DECL)
816 	    continue;
817 	  if (DECL_UNNAMED_BIT_FIELD (field))
818 	    continue;
819 	  if (DECL_ARTIFICIAL (field))
820 	    continue;
821 	  if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
822 	    {
823 	      /* Recurse to check the anonymous aggregate member.  */
824 	      bad |= cx_check_missing_mem_inits
825 		(TREE_TYPE (field), NULL_TREE, complain);
826 	      if (bad && !complain)
827 		return true;
828 	      continue;
829 	    }
830 	  ftype = TREE_TYPE (field);
831 	  if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
832 	    /* A flexible array can't be intialized here, so don't complain
833 	       that it isn't.  */
834 	    continue;
835 	  if (DECL_SIZE (field) && integer_zerop (DECL_SIZE (field)))
836 	    /* An empty field doesn't need an initializer.  */
837 	    continue;
838 	  ftype = strip_array_types (ftype);
839 	  if (type_has_constexpr_default_constructor (ftype))
840 	    {
841 	      /* It's OK to skip a member with a trivial constexpr ctor.
842 	         A constexpr ctor that isn't trivial should have been
843 	         added in by now.  */
844 	      gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
845 				   || errorcount != 0);
846 	      continue;
847 	    }
848 	  if (!complain)
849 	    return true;
850 	  auto_diagnostic_group d;
851 	  error ("member %qD must be initialized by mem-initializer "
852 		 "in %<constexpr%> constructor", field);
853 	  inform (DECL_SOURCE_LOCATION (field), "declared here");
854 	  bad = true;
855 	}
856       if (field == NULL_TREE)
857 	break;
858 
859       if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
860 	{
861 	  /* Check the anonymous aggregate initializer is valid.  */
862 	  bad |= cx_check_missing_mem_inits
863 	    (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
864 	  if (bad && !complain)
865 	    return true;
866 	}
867       field = DECL_CHAIN (field);
868     }
869 
870   return bad;
871 }
872 
873 /* We are processing the definition of the constexpr function FUN.
874    Check that its BODY fulfills the propriate requirements and
875    enter it in the constexpr function definition table.
876    For constructor BODY is actually the TREE_LIST of the
877    member-initializer list.  */
878 
879 tree
register_constexpr_fundef(tree fun,tree body)880 register_constexpr_fundef (tree fun, tree body)
881 {
882   constexpr_fundef entry;
883   constexpr_fundef **slot;
884 
885   if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
886     return NULL;
887 
888   tree massaged = massage_constexpr_body (fun, body);
889   if (massaged == NULL_TREE || massaged == error_mark_node)
890     {
891       if (!DECL_CONSTRUCTOR_P (fun))
892 	error ("body of %<constexpr%> function %qD not a return-statement",
893 	       fun);
894       return NULL;
895     }
896 
897   bool potential = potential_rvalue_constant_expression (massaged);
898   if (!potential && !DECL_GENERATED_P (fun))
899     require_potential_rvalue_constant_expression (massaged);
900 
901   if (DECL_CONSTRUCTOR_P (fun)
902       && cx_check_missing_mem_inits (DECL_CONTEXT (fun),
903 				     massaged, !DECL_GENERATED_P (fun)))
904     potential = false;
905 
906   if (!potential && !DECL_GENERATED_P (fun))
907     return NULL;
908 
909   /* Create the constexpr function table if necessary.  */
910   if (constexpr_fundef_table == NULL)
911     constexpr_fundef_table
912       = hash_table<constexpr_fundef_hasher>::create_ggc (101);
913 
914   entry.decl = fun;
915   tree saved_fn = current_function_decl;
916   bool clear_ctx = false;
917   current_function_decl = fun;
918   if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
919     {
920       clear_ctx = true;
921       DECL_CONTEXT (DECL_RESULT (fun)) = fun;
922     }
923   entry.body = copy_fn (fun, entry.parms, entry.result);
924   current_function_decl = saved_fn;
925   slot = constexpr_fundef_table->find_slot (&entry, INSERT);
926   if (clear_ctx)
927     DECL_CONTEXT (DECL_RESULT (fun)) = NULL_TREE;
928 
929   if (!potential)
930     /* For a template instantiation, we want to remember the pre-generic body
931        for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
932        that it doesn't need to bother trying to expand the function.  */
933     entry.result = error_mark_node;
934 
935   gcc_assert (*slot == NULL);
936   *slot = ggc_alloc<constexpr_fundef> ();
937   **slot = entry;
938 
939   return fun;
940 }
941 
942 /* FUN is a non-constexpr function called in a context that requires a
943    constant expression.  If it comes from a constexpr template, explain why
944    the instantiation isn't constexpr.  */
945 
946 void
explain_invalid_constexpr_fn(tree fun)947 explain_invalid_constexpr_fn (tree fun)
948 {
949   static hash_set<tree> *diagnosed;
950   tree body;
951   location_t save_loc;
952   /* Only diagnose defaulted functions, lambdas, or instantiations.  */
953   if (!DECL_DEFAULTED_FN (fun)
954       && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
955       && !is_instantiation_of_constexpr (fun))
956     {
957       inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
958       return;
959     }
960   if (diagnosed == NULL)
961     diagnosed = new hash_set<tree>;
962   if (diagnosed->add (fun))
963     /* Already explained.  */
964     return;
965 
966   save_loc = input_location;
967   if (!lambda_static_thunk_p (fun))
968     {
969       /* Diagnostics should completely ignore the static thunk, so leave
970 	 input_location set to our caller's location.  */
971       input_location = DECL_SOURCE_LOCATION (fun);
972       inform (input_location,
973 	      "%qD is not usable as a %<constexpr%> function because:", fun);
974     }
975   /* First check the declaration.  */
976   if (is_valid_constexpr_fn (fun, true))
977     {
978       /* Then if it's OK, the body.  */
979       if (!DECL_DECLARED_CONSTEXPR_P (fun)
980 	  && DECL_DEFAULTED_FN (fun))
981 	explain_implicit_non_constexpr (fun);
982       else
983 	{
984 	  if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
985 	    body = fd->body;
986 	  else
987 	    body = DECL_SAVED_TREE (fun);
988 	  body = massage_constexpr_body (fun, body);
989 	  require_potential_rvalue_constant_expression (body);
990 	  if (DECL_CONSTRUCTOR_P (fun))
991 	    cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
992 	}
993     }
994   input_location = save_loc;
995 }
996 
997 /* Objects of this type represent calls to constexpr functions
998    along with the bindings of parameters to their arguments, for
999    the purpose of compile time evaluation.  */
1000 
1001 struct GTY((for_user)) constexpr_call {
1002   /* Description of the constexpr function definition.  */
1003   constexpr_fundef *fundef;
1004   /* Parameter bindings environment.  A TREE_VEC of arguments.  */
1005   tree bindings;
1006   /* Result of the call.
1007        NULL means the call is being evaluated.
1008        error_mark_node means that the evaluation was erroneous;
1009        otherwise, the actuall value of the call.  */
1010   tree result;
1011   /* The hash of this call; we remember it here to avoid having to
1012      recalculate it when expanding the hash table.  */
1013   hashval_t hash;
1014   /* Whether __builtin_is_constant_evaluated() should evaluate to true.  */
1015   bool manifestly_const_eval;
1016 };
1017 
1018 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1019 {
1020   static hashval_t hash (constexpr_call *);
1021   static bool equal (constexpr_call *, constexpr_call *);
1022 };
1023 
1024 enum constexpr_switch_state {
1025   /* Used when processing a switch for the first time by cxx_eval_switch_expr
1026      and default: label for that switch has not been seen yet.  */
1027   css_default_not_seen,
1028   /* Used when processing a switch for the first time by cxx_eval_switch_expr
1029      and default: label for that switch has been seen already.  */
1030   css_default_seen,
1031   /* Used when processing a switch for the second time by
1032      cxx_eval_switch_expr, where default: label should match.  */
1033   css_default_processing
1034 };
1035 
1036 /* The constexpr expansion context part which needs one instance per
1037    cxx_eval_outermost_constant_expr invocation.  VALUES is a map of values of
1038    variables initialized within the expression.  */
1039 
1040 struct constexpr_global_ctx {
1041   /* Values for any temporaries or local variables within the
1042      constant-expression. */
1043   hash_map<tree,tree> values;
1044   /* Number of cxx_eval_constant_expression calls (except skipped ones,
1045      on simple constants or location wrappers) encountered during current
1046      cxx_eval_outermost_constant_expr call.  */
1047   HOST_WIDE_INT constexpr_ops_count;
1048   /* Heap VAR_DECLs created during the evaluation of the outermost constant
1049      expression.  */
1050   auto_vec<tree, 16> heap_vars;
1051   /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR.  */
1052   vec<tree> *cleanups;
1053   /* Number of heap VAR_DECL deallocations.  */
1054   unsigned heap_dealloc_count;
1055   /* Constructor.  */
constexpr_global_ctxconstexpr_global_ctx1056   constexpr_global_ctx ()
1057     : constexpr_ops_count (0), cleanups (NULL), heap_dealloc_count (0) {}
1058 };
1059 
1060 /* The constexpr expansion context.  CALL is the current function
1061    expansion, CTOR is the current aggregate initializer, OBJECT is the
1062    object being initialized by CTOR, either a VAR_DECL or a _REF.    */
1063 
1064 struct constexpr_ctx {
1065   /* The part of the context that needs to be unique to the whole
1066      cxx_eval_outermost_constant_expr invocation.  */
1067   constexpr_global_ctx *global;
1068   /* The innermost call we're evaluating.  */
1069   constexpr_call *call;
1070   /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1071      within the current LOOP_EXPR.  NULL if we aren't inside a loop.  */
1072   vec<tree> *save_exprs;
1073   /* The CONSTRUCTOR we're currently building up for an aggregate
1074      initializer.  */
1075   tree ctor;
1076   /* The object we're building the CONSTRUCTOR for.  */
1077   tree object;
1078   /* If inside SWITCH_EXPR.  */
1079   constexpr_switch_state *css_state;
1080   /* The aggregate initialization context inside which this one is nested.  This
1081      is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs.  */
1082   const constexpr_ctx *parent;
1083 
1084   /* Whether we should error on a non-constant expression or fail quietly.
1085      This flag needs to be here, but some of the others could move to global
1086      if they get larger than a word.  */
1087   bool quiet;
1088   /* Whether we are strictly conforming to constant expression rules or
1089      trying harder to get a constant value.  */
1090   bool strict;
1091   /* Whether __builtin_is_constant_evaluated () should be true.  */
1092   bool manifestly_const_eval;
1093   /* Whether we want to avoid doing anything that will cause extra DECL_UID
1094      generation.  */
1095   bool uid_sensitive;
1096 };
1097 
1098 /* A table of all constexpr calls that have been evaluated by the
1099    compiler in this translation unit.  */
1100 
1101 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1102 
1103 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1104 					  bool, bool *, bool *, tree * = NULL);
1105 
1106 /* Compute a hash value for a constexpr call representation.  */
1107 
1108 inline hashval_t
hash(constexpr_call * info)1109 constexpr_call_hasher::hash (constexpr_call *info)
1110 {
1111   return info->hash;
1112 }
1113 
1114 /* Return true if the objects pointed to by P and Q represent calls
1115    to the same constexpr function with the same arguments.
1116    Otherwise, return false.  */
1117 
1118 bool
equal(constexpr_call * lhs,constexpr_call * rhs)1119 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1120 {
1121   if (lhs == rhs)
1122     return true;
1123   if (lhs->hash != rhs->hash)
1124     return false;
1125   if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1126     return false;
1127   if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1128     return false;
1129   return cp_tree_equal (lhs->bindings, rhs->bindings);
1130 }
1131 
1132 /* Initialize the constexpr call table, if needed.  */
1133 
1134 static void
maybe_initialize_constexpr_call_table(void)1135 maybe_initialize_constexpr_call_table (void)
1136 {
1137   if (constexpr_call_table == NULL)
1138     constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1139 }
1140 
1141 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1142    a function happens to get called recursively, we unshare the callee
1143    function's body and evaluate this unshared copy instead of evaluating the
1144    original body.
1145 
1146    FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1147    copies.  The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1148    that's keyed off of the original FUNCTION_DECL and whose value is a
1149    TREE_LIST of this function's unused copies awaiting reuse.
1150 
1151    This is not GC-deletable to avoid GC affecting UID generation.  */
1152 
1153 static GTY(()) decl_tree_map *fundef_copies_table;
1154 
1155 /* Reuse a copy or create a new unshared copy of the function FUN.
1156    Return this copy.  We use a TREE_LIST whose PURPOSE is body, VALUE
1157    is parms, TYPE is result.  */
1158 
1159 static tree
get_fundef_copy(const constexpr_ctx * ctx,constexpr_fundef * fundef)1160 get_fundef_copy (const constexpr_ctx *ctx, constexpr_fundef *fundef)
1161 {
1162   tree copy;
1163   bool existed;
1164   tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1165 		 (fundef_copies_table, fundef->decl, &existed, 127));
1166 
1167   if (!existed)
1168     {
1169       /* There is no cached function available, or in use.  We can use
1170 	 the function directly.  That the slot is now created records
1171 	 that this function is now in use.  */
1172       copy = build_tree_list (fundef->body, fundef->parms);
1173       TREE_TYPE (copy) = fundef->result;
1174     }
1175   else if (*slot == NULL_TREE)
1176     {
1177       if (ctx->uid_sensitive)
1178 	return NULL_TREE;
1179 
1180       /* We've already used the function itself, so make a copy.  */
1181       copy = build_tree_list (NULL, NULL);
1182       tree saved_body = DECL_SAVED_TREE (fundef->decl);
1183       tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1184       tree saved_result = DECL_RESULT (fundef->decl);
1185       tree saved_fn = current_function_decl;
1186       DECL_SAVED_TREE (fundef->decl) = fundef->body;
1187       DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1188       DECL_RESULT (fundef->decl) = fundef->result;
1189       current_function_decl = fundef->decl;
1190       TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1191 				     TREE_TYPE (copy));
1192       current_function_decl = saved_fn;
1193       DECL_RESULT (fundef->decl) = saved_result;
1194       DECL_ARGUMENTS (fundef->decl) = saved_parms;
1195       DECL_SAVED_TREE (fundef->decl) = saved_body;
1196     }
1197   else
1198     {
1199       /* We have a cached function available.  */
1200       copy = *slot;
1201       *slot = TREE_CHAIN (copy);
1202     }
1203 
1204   return copy;
1205 }
1206 
1207 /* Save the copy COPY of function FUN for later reuse by
1208    get_fundef_copy().  By construction, there will always be an entry
1209    to find.  */
1210 
1211 static void
save_fundef_copy(tree fun,tree copy)1212 save_fundef_copy (tree fun, tree copy)
1213 {
1214   tree *slot = fundef_copies_table->get (fun);
1215   TREE_CHAIN (copy) = *slot;
1216   *slot = copy;
1217 }
1218 
1219 /* We have an expression tree T that represents a call, either CALL_EXPR
1220    or AGGR_INIT_EXPR.  Return the Nth argument.  */
1221 
1222 static inline tree
get_nth_callarg(tree t,int n)1223 get_nth_callarg (tree t, int n)
1224 {
1225   switch (TREE_CODE (t))
1226     {
1227     case CALL_EXPR:
1228       return CALL_EXPR_ARG (t, n);
1229 
1230     case AGGR_INIT_EXPR:
1231       return AGGR_INIT_EXPR_ARG (t, n);
1232 
1233     default:
1234       gcc_unreachable ();
1235       return NULL;
1236     }
1237 }
1238 
1239 /* Attempt to evaluate T which represents a call to a builtin function.
1240    We assume here that all builtin functions evaluate to scalar types
1241    represented by _CST nodes.  */
1242 
1243 static tree
cxx_eval_builtin_function_call(const constexpr_ctx * ctx,tree t,tree fun,bool lval,bool * non_constant_p,bool * overflow_p)1244 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1245 				bool lval,
1246 				bool *non_constant_p, bool *overflow_p)
1247 {
1248   const int nargs = call_expr_nargs (t);
1249   tree *args = (tree *) alloca (nargs * sizeof (tree));
1250   tree new_call;
1251   int i;
1252 
1253   /* Don't fold __builtin_constant_p within a constexpr function.  */
1254   bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1255 
1256   /* If we aren't requiring a constant expression, defer __builtin_constant_p
1257      in a constexpr function until we have values for the parameters.  */
1258   if (bi_const_p
1259       && !ctx->manifestly_const_eval
1260       && current_function_decl
1261       && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1262     {
1263       *non_constant_p = true;
1264       return t;
1265     }
1266 
1267   /* For __builtin_is_constant_evaluated, defer it if not
1268      ctx->manifestly_const_eval, otherwise fold it to true.  */
1269   if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1270 			 BUILT_IN_FRONTEND))
1271     {
1272       if (!ctx->manifestly_const_eval)
1273 	{
1274 	  *non_constant_p = true;
1275 	  return t;
1276 	}
1277       return boolean_true_node;
1278     }
1279 
1280   if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1281     return fold_builtin_source_location (EXPR_LOCATION (t));
1282 
1283   int strops = 0;
1284   int strret = 0;
1285   if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1286     switch (DECL_FUNCTION_CODE (fun))
1287       {
1288       case BUILT_IN_STRLEN:
1289       case BUILT_IN_STRNLEN:
1290 	strops = 1;
1291 	break;
1292       case BUILT_IN_MEMCHR:
1293       case BUILT_IN_STRCHR:
1294       case BUILT_IN_STRRCHR:
1295 	strops = 1;
1296 	strret = 1;
1297 	break;
1298       case BUILT_IN_MEMCMP:
1299       case BUILT_IN_STRCMP:
1300 	strops = 2;
1301 	break;
1302       case BUILT_IN_STRSTR:
1303 	strops = 2;
1304 	strret = 1;
1305 	break;
1306       case BUILT_IN_ASAN_POINTER_COMPARE:
1307       case BUILT_IN_ASAN_POINTER_SUBTRACT:
1308 	/* These builtins shall be ignored during constant expression
1309 	   evaluation.  */
1310 	return void_node;
1311       default:
1312 	break;
1313       }
1314 
1315   /* Be permissive for arguments to built-ins; __builtin_constant_p should
1316      return constant false for a non-constant argument.  */
1317   constexpr_ctx new_ctx = *ctx;
1318   new_ctx.quiet = true;
1319   for (i = 0; i < nargs; ++i)
1320     {
1321       tree arg = CALL_EXPR_ARG (t, i);
1322       tree oarg = arg;
1323 
1324       /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1325 	 expand_builtin doesn't know how to look in the values table.  */
1326       bool strop = i < strops;
1327       if (strop)
1328 	{
1329 	  STRIP_NOPS (arg);
1330 	  if (TREE_CODE (arg) == ADDR_EXPR)
1331 	    arg = TREE_OPERAND (arg, 0);
1332 	  else
1333 	    strop = false;
1334 	}
1335 
1336       /* If builtin_valid_in_constant_expr_p is true,
1337 	 potential_constant_expression_1 has not recursed into the arguments
1338 	 of the builtin, verify it here.  */
1339       if (!builtin_valid_in_constant_expr_p (fun)
1340 	  || potential_constant_expression (arg))
1341 	{
1342 	  bool dummy1 = false, dummy2 = false;
1343 	  arg = cxx_eval_constant_expression (&new_ctx, arg, false,
1344 					      &dummy1, &dummy2);
1345 	}
1346 
1347       if (bi_const_p)
1348 	/* For __builtin_constant_p, fold all expressions with constant values
1349 	   even if they aren't C++ constant-expressions.  */
1350 	arg = cp_fold_rvalue (arg);
1351       else if (strop)
1352 	{
1353 	  if (TREE_CODE (arg) == CONSTRUCTOR)
1354 	    arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1355 	  if (TREE_CODE (arg) == STRING_CST)
1356 	    arg = build_address (arg);
1357 	  else
1358 	    arg = oarg;
1359 	}
1360 
1361       args[i] = arg;
1362     }
1363 
1364   bool save_ffbcp = force_folding_builtin_constant_p;
1365   force_folding_builtin_constant_p |= ctx->manifestly_const_eval;
1366   tree save_cur_fn = current_function_decl;
1367   /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION ().  */
1368   if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1369       && ctx->call
1370       && ctx->call->fundef)
1371     current_function_decl = ctx->call->fundef->decl;
1372   new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1373 				      CALL_EXPR_FN (t), nargs, args);
1374   current_function_decl = save_cur_fn;
1375   force_folding_builtin_constant_p = save_ffbcp;
1376   if (new_call == NULL)
1377     {
1378       if (!*non_constant_p && !ctx->quiet)
1379 	{
1380 	  /* Do not allow__builtin_unreachable in constexpr function.
1381 	     The __builtin_unreachable call with BUILTINS_LOCATION
1382 	     comes from cp_maybe_instrument_return.  */
1383 	  if (fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE)
1384 	      && EXPR_LOCATION (t) == BUILTINS_LOCATION)
1385 	    error ("%<constexpr%> call flows off the end of the function");
1386 	  else
1387 	    {
1388 	      new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1389 					       CALL_EXPR_FN (t), nargs, args);
1390 	      error ("%q+E is not a constant expression", new_call);
1391 	    }
1392 	}
1393       *non_constant_p = true;
1394       return t;
1395     }
1396 
1397   if (!potential_constant_expression (new_call))
1398     {
1399       if (!*non_constant_p && !ctx->quiet)
1400 	error ("%q+E is not a constant expression", new_call);
1401       *non_constant_p = true;
1402       return t;
1403     }
1404 
1405   if (strret)
1406     {
1407       /* memchr returns a pointer into the first argument, but we replaced the
1408 	 argument above with a STRING_CST; put it back it now.  */
1409       tree op = CALL_EXPR_ARG (t, strret-1);
1410       STRIP_NOPS (new_call);
1411       if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1412 	TREE_OPERAND (new_call, 0) = op;
1413       else if (TREE_CODE (new_call) == ADDR_EXPR)
1414 	new_call = op;
1415     }
1416 
1417   return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1418 				       non_constant_p, overflow_p);
1419 }
1420 
1421 /* TEMP is the constant value of a temporary object of type TYPE.  Adjust
1422    the type of the value to match.  */
1423 
1424 static tree
adjust_temp_type(tree type,tree temp)1425 adjust_temp_type (tree type, tree temp)
1426 {
1427   if (same_type_p (TREE_TYPE (temp), type))
1428     return temp;
1429   /* Avoid wrapping an aggregate value in a NOP_EXPR.  */
1430   if (TREE_CODE (temp) == CONSTRUCTOR)
1431     {
1432       /* build_constructor wouldn't retain various CONSTRUCTOR flags.  */
1433       tree t = copy_node (temp);
1434       TREE_TYPE (t) = type;
1435       return t;
1436     }
1437   if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1438     return build0 (EMPTY_CLASS_EXPR, type);
1439   gcc_assert (scalarish_type_p (type));
1440   /* Now we know we're dealing with a scalar, and a prvalue of non-class
1441      type is cv-unqualified.  */
1442   return cp_fold_convert (cv_unqualified (type), temp);
1443 }
1444 
1445 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1446    sub-CONSTRUCTORs.  Otherwise return T.
1447 
1448    We use this whenever we initialize an object as a whole, whether it's a
1449    parameter, a local variable, or a subobject, so that subsequent
1450    modifications don't affect other places where it was used.  */
1451 
1452 tree
unshare_constructor(tree t MEM_STAT_DECL)1453 unshare_constructor (tree t MEM_STAT_DECL)
1454 {
1455   if (!t || TREE_CODE (t) != CONSTRUCTOR)
1456     return t;
1457   auto_vec <tree*, 4> ptrs;
1458   ptrs.safe_push (&t);
1459   while (!ptrs.is_empty ())
1460     {
1461       tree *p = ptrs.pop ();
1462       tree n = copy_node (*p PASS_MEM_STAT);
1463       CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1464       *p = n;
1465       vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1466       constructor_elt *ce;
1467       for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1468 	if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1469 	  ptrs.safe_push (&ce->value);
1470     }
1471   return t;
1472 }
1473 
1474 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs.  */
1475 
1476 static void
free_constructor(tree t)1477 free_constructor (tree t)
1478 {
1479   if (!t || TREE_CODE (t) != CONSTRUCTOR)
1480     return;
1481   releasing_vec ctors;
1482   vec_safe_push (ctors, t);
1483   while (!ctors->is_empty ())
1484     {
1485       tree c = ctors->pop ();
1486       if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1487 	{
1488 	  constructor_elt *ce;
1489 	  for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1490 	    if (TREE_CODE (ce->value) == CONSTRUCTOR)
1491 	      vec_safe_push (ctors, ce->value);
1492 	  ggc_free (elts);
1493 	}
1494       ggc_free (c);
1495     }
1496 }
1497 
1498 /* Subroutine of cxx_eval_call_expression.
1499    We are processing a call expression (either CALL_EXPR or
1500    AGGR_INIT_EXPR) in the context of CTX.  Evaluate
1501    all arguments and bind their values to correspondings
1502    parameters, making up the NEW_CALL context.  */
1503 
1504 static void
cxx_bind_parameters_in_call(const constexpr_ctx * ctx,tree t,constexpr_call * new_call,bool * non_constant_p,bool * overflow_p,bool * non_constant_args)1505 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1506                              constexpr_call *new_call,
1507 			     bool *non_constant_p, bool *overflow_p,
1508 			     bool *non_constant_args)
1509 {
1510   const int nargs = call_expr_nargs (t);
1511   tree fun = new_call->fundef->decl;
1512   tree parms = new_call->fundef->parms;
1513   int i;
1514   /* We don't record ellipsis args below.  */
1515   int nparms = list_length (parms);
1516   int nbinds = nargs < nparms ? nargs : nparms;
1517   tree binds = new_call->bindings = make_tree_vec (nbinds);
1518   for (i = 0; i < nargs; ++i)
1519     {
1520       tree x, arg;
1521       tree type = parms ? TREE_TYPE (parms) : void_type_node;
1522       x = get_nth_callarg (t, i);
1523       /* For member function, the first argument is a pointer to the implied
1524          object.  For a constructor, it might still be a dummy object, in
1525          which case we get the real argument from ctx. */
1526       if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1527 	  && is_dummy_object (x))
1528 	{
1529 	  x = ctx->object;
1530 	  x = build_address (x);
1531 	}
1532       if (TREE_ADDRESSABLE (type))
1533 	/* Undo convert_for_arg_passing work here.  */
1534 	x = convert_from_reference (x);
1535       arg = cxx_eval_constant_expression (ctx, x, /*lval=*/false,
1536 					  non_constant_p, overflow_p);
1537       /* Don't VERIFY_CONSTANT here.  */
1538       if (*non_constant_p && ctx->quiet)
1539 	return;
1540       /* Just discard ellipsis args after checking their constantitude.  */
1541       if (!parms)
1542 	continue;
1543 
1544       if (!*non_constant_p)
1545 	{
1546 	  /* Make sure the binding has the same type as the parm.  But
1547 	     only for constant args.  */
1548 	  if (!TYPE_REF_P (type))
1549 	    arg = adjust_temp_type (type, arg);
1550 	  if (!TREE_CONSTANT (arg))
1551 	    *non_constant_args = true;
1552 	  /* For virtual calls, adjust the this argument, so that it is
1553 	     the object on which the method is called, rather than
1554 	     one of its bases.  */
1555 	  if (i == 0 && DECL_VIRTUAL_P (fun))
1556 	    {
1557 	      tree addr = arg;
1558 	      STRIP_NOPS (addr);
1559 	      if (TREE_CODE (addr) == ADDR_EXPR)
1560 		{
1561 		  tree obj = TREE_OPERAND (addr, 0);
1562 		  while (TREE_CODE (obj) == COMPONENT_REF
1563 			 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1564 			 && !same_type_ignoring_top_level_qualifiers_p
1565 					(TREE_TYPE (obj), DECL_CONTEXT (fun)))
1566 		    obj = TREE_OPERAND (obj, 0);
1567 		  if (obj != TREE_OPERAND (addr, 0))
1568 		    arg = build_fold_addr_expr_with_type (obj,
1569 							  TREE_TYPE (arg));
1570 		}
1571 	    }
1572 	  TREE_VEC_ELT (binds, i) = arg;
1573 	}
1574       parms = TREE_CHAIN (parms);
1575     }
1576 }
1577 
1578 /* Variables and functions to manage constexpr call expansion context.
1579    These do not need to be marked for PCH or GC.  */
1580 
1581 /* FIXME remember and print actual constant arguments.  */
1582 static vec<tree> call_stack;
1583 static int call_stack_tick;
1584 static int last_cx_error_tick;
1585 
1586 static int
push_cx_call_context(tree call)1587 push_cx_call_context (tree call)
1588 {
1589   ++call_stack_tick;
1590   if (!EXPR_HAS_LOCATION (call))
1591     SET_EXPR_LOCATION (call, input_location);
1592   call_stack.safe_push (call);
1593   int len = call_stack.length ();
1594   if (len > max_constexpr_depth)
1595     return false;
1596   return len;
1597 }
1598 
1599 static void
pop_cx_call_context(void)1600 pop_cx_call_context (void)
1601 {
1602   ++call_stack_tick;
1603   call_stack.pop ();
1604 }
1605 
1606 vec<tree>
cx_error_context(void)1607 cx_error_context (void)
1608 {
1609   vec<tree> r = vNULL;
1610   if (call_stack_tick != last_cx_error_tick
1611       && !call_stack.is_empty ())
1612     r = call_stack;
1613   last_cx_error_tick = call_stack_tick;
1614   return r;
1615 }
1616 
1617 /* Evaluate a call T to a GCC internal function when possible and return
1618    the evaluated result or, under the control of CTX, give an error, set
1619    NON_CONSTANT_P, and return the unevaluated call T otherwise.  */
1620 
1621 static tree
cxx_eval_internal_function(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)1622 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1623 			    bool lval,
1624 			    bool *non_constant_p, bool *overflow_p)
1625 {
1626   enum tree_code opcode = ERROR_MARK;
1627 
1628   switch (CALL_EXPR_IFN (t))
1629     {
1630     case IFN_UBSAN_NULL:
1631     case IFN_UBSAN_BOUNDS:
1632     case IFN_UBSAN_VPTR:
1633     case IFN_FALLTHROUGH:
1634       return void_node;
1635 
1636     case IFN_ADD_OVERFLOW:
1637       opcode = PLUS_EXPR;
1638       break;
1639     case IFN_SUB_OVERFLOW:
1640       opcode = MINUS_EXPR;
1641       break;
1642     case IFN_MUL_OVERFLOW:
1643       opcode = MULT_EXPR;
1644       break;
1645 
1646     case IFN_LAUNDER:
1647       return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1648 					   false, non_constant_p, overflow_p);
1649 
1650     case IFN_VEC_CONVERT:
1651       {
1652 	tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1653 						 false, non_constant_p,
1654 						 overflow_p);
1655 	if (TREE_CODE (arg) == VECTOR_CST)
1656 	  return fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg);
1657 	else
1658 	  {
1659 	    *non_constant_p = true;
1660 	    return t;
1661 	  }
1662       }
1663 
1664     default:
1665       if (!ctx->quiet)
1666 	error_at (cp_expr_loc_or_input_loc (t),
1667 		  "call to internal function %qE", t);
1668       *non_constant_p = true;
1669       return t;
1670     }
1671 
1672   /* Evaluate constant arguments using OPCODE and return a complex
1673      number containing the result and the overflow bit.  */
1674   tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
1675 					    non_constant_p, overflow_p);
1676   tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
1677 					    non_constant_p, overflow_p);
1678 
1679   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1680     {
1681       location_t loc = cp_expr_loc_or_input_loc (t);
1682       tree type = TREE_TYPE (TREE_TYPE (t));
1683       tree result = fold_binary_loc (loc, opcode, type,
1684 				     fold_convert_loc (loc, type, arg0),
1685 				     fold_convert_loc (loc, type, arg1));
1686       tree ovf
1687 	= build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
1688       /* Reset TREE_OVERFLOW to avoid warnings for the overflow.  */
1689       if (TREE_OVERFLOW (result))
1690 	TREE_OVERFLOW (result) = 0;
1691 
1692       return build_complex (TREE_TYPE (t), result, ovf);
1693     }
1694 
1695   *non_constant_p = true;
1696   return t;
1697 }
1698 
1699 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates.  */
1700 
1701 static void
clear_no_implicit_zero(tree ctor)1702 clear_no_implicit_zero (tree ctor)
1703 {
1704   if (CONSTRUCTOR_NO_CLEARING (ctor))
1705     {
1706       CONSTRUCTOR_NO_CLEARING (ctor) = false;
1707       tree elt; unsigned HOST_WIDE_INT idx;
1708       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, elt)
1709 	if (TREE_CODE (elt) == CONSTRUCTOR)
1710 	  clear_no_implicit_zero (elt);
1711     }
1712 }
1713 
1714 /* Complain about a const object OBJ being modified in a constant expression.
1715    EXPR is the MODIFY_EXPR expression performing the modification.  */
1716 
1717 static void
modifying_const_object_error(tree expr,tree obj)1718 modifying_const_object_error (tree expr, tree obj)
1719 {
1720   location_t loc = cp_expr_loc_or_input_loc (expr);
1721   auto_diagnostic_group d;
1722   error_at (loc, "modifying a const object %qE is not allowed in "
1723 	    "a constant expression", TREE_OPERAND (expr, 0));
1724   inform (location_of (obj), "originally declared %<const%> here");
1725 }
1726 
1727 /* Return true if FNDECL is a replaceable global allocation function that
1728    should be useable during constant expression evaluation.  */
1729 
1730 static inline bool
cxx_replaceable_global_alloc_fn(tree fndecl)1731 cxx_replaceable_global_alloc_fn (tree fndecl)
1732 {
1733   return (cxx_dialect >= cxx2a
1734 	  && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
1735 	  && CP_DECL_CONTEXT (fndecl) == global_namespace
1736 	  && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
1737 	      || DECL_IS_OPERATOR_DELETE_P (fndecl)));
1738 }
1739 
1740 /* Return true if FNDECL is a placement new function that should be
1741    useable during constant expression evaluation of std::construct_at.  */
1742 
1743 static inline bool
cxx_placement_new_fn(tree fndecl)1744 cxx_placement_new_fn (tree fndecl)
1745 {
1746   if (cxx_dialect >= cxx2a
1747       && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
1748       && CP_DECL_CONTEXT (fndecl) == global_namespace
1749       && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
1750       && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
1751     {
1752       tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
1753       if (TREE_VALUE (first_arg) == ptr_type_node
1754 	  && TREE_CHAIN (first_arg) == void_list_node)
1755 	return true;
1756     }
1757   return false;
1758 }
1759 
1760 /* Return true if FNDECL is std::construct_at.  */
1761 
1762 static inline bool
is_std_construct_at(tree fndecl)1763 is_std_construct_at (tree fndecl)
1764 {
1765   if (!decl_in_std_namespace_p (fndecl))
1766     return false;
1767 
1768   tree name = DECL_NAME (fndecl);
1769   return name && id_equal (name, "construct_at");
1770 }
1771 
1772 /* Return true if FNDECL is std::allocator<T>::{,de}allocate.  */
1773 
1774 static inline bool
is_std_allocator_allocate(tree fndecl)1775 is_std_allocator_allocate (tree fndecl)
1776 {
1777   tree name = DECL_NAME (fndecl);
1778   if (name == NULL_TREE
1779       || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
1780     return false;
1781 
1782   tree ctx = DECL_CONTEXT (fndecl);
1783   if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
1784     return false;
1785 
1786   tree decl = TYPE_MAIN_DECL (ctx);
1787   name = DECL_NAME (decl);
1788   if (name == NULL_TREE || !id_equal (name, "allocator"))
1789     return false;
1790 
1791   return decl_in_std_namespace_p (decl);
1792 }
1793 
1794 /* Return true if FNDECL is __dynamic_cast.  */
1795 
1796 static inline bool
cxx_dynamic_cast_fn_p(tree fndecl)1797 cxx_dynamic_cast_fn_p (tree fndecl)
1798 {
1799   return (cxx_dialect >= cxx2a
1800 	  && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
1801 	  && CP_DECL_CONTEXT (fndecl) == global_namespace);
1802 }
1803 
1804 /* Often, we have an expression in the form of address + offset, e.g.
1805    "&_ZTV1A + 16".  Extract the object from it, i.e. "_ZTV1A".  */
1806 
1807 static tree
extract_obj_from_addr_offset(tree expr)1808 extract_obj_from_addr_offset (tree expr)
1809 {
1810   if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
1811     expr = TREE_OPERAND (expr, 0);
1812   STRIP_NOPS (expr);
1813   if (TREE_CODE (expr) == ADDR_EXPR)
1814     expr = TREE_OPERAND (expr, 0);
1815   return expr;
1816 }
1817 
1818 /* Given a PATH like
1819 
1820      g.D.2181.D.2154.D.2102.D.2093
1821 
1822    find a component with type TYPE.  Return NULL_TREE if not found, and
1823    error_mark_node if the component is not accessible.  If STOP is non-null,
1824    this function will return NULL_TREE if STOP is found before TYPE.  */
1825 
1826 static tree
get_component_with_type(tree path,tree type,tree stop)1827 get_component_with_type (tree path, tree type, tree stop)
1828 {
1829   while (true)
1830     {
1831       if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
1832 	/* Found it.  */
1833 	return path;
1834       else if (stop
1835 	       && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
1836 							      stop)))
1837 	return NULL_TREE;
1838       else if (TREE_CODE (path) == COMPONENT_REF
1839 	       && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
1840 	{
1841 	  /* We need to check that the component we're accessing is in fact
1842 	     accessible.  */
1843 	  if (TREE_PRIVATE (TREE_OPERAND (path, 1))
1844 	      || TREE_PROTECTED (TREE_OPERAND (path, 1)))
1845 	    return error_mark_node;
1846 	  path = TREE_OPERAND (path, 0);
1847 	}
1848       else
1849 	return NULL_TREE;
1850     }
1851 }
1852 
1853 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
1854 
1855    The declaration of __dynamic_cast is:
1856 
1857    void* __dynamic_cast (const void* __src_ptr,
1858 			 const __class_type_info* __src_type,
1859 			 const __class_type_info* __dst_type,
1860 			 ptrdiff_t __src2dst);
1861 
1862    where src2dst has the following possible values
1863 
1864    >-1: src_type is a unique public non-virtual base of dst_type
1865 	dst_ptr + src2dst == src_ptr
1866    -1: unspecified relationship
1867    -2: src_type is not a public base of dst_type
1868    -3: src_type is a multiple public non-virtual base of dst_type
1869 
1870   Since literal types can't have virtual bases, we only expect hint >=0,
1871   -2, or -3.  */
1872 
1873 static tree
cxx_eval_dynamic_cast_fn(const constexpr_ctx * ctx,tree call,bool * non_constant_p,bool * overflow_p)1874 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
1875 			  bool *non_constant_p, bool *overflow_p)
1876 {
1877   /* T will be something like
1878       __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
1879      dismantle it.  */
1880   gcc_assert (call_expr_nargs (call) == 4);
1881   tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
1882   tree obj = CALL_EXPR_ARG (call, 0);
1883   tree type = CALL_EXPR_ARG (call, 2);
1884   HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
1885   location_t loc = cp_expr_loc_or_input_loc (call);
1886 
1887   /* Get the target type of the dynamic_cast.  */
1888   gcc_assert (TREE_CODE (type) == ADDR_EXPR);
1889   type = TREE_OPERAND (type, 0);
1890   type = TREE_TYPE (DECL_NAME (type));
1891 
1892   /* TYPE can only be either T* or T&.  We can't know which of these it
1893      is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
1894      and something like "(T*)(T&)(T*) x" in the second case.  */
1895   bool reference_p = false;
1896   while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
1897     {
1898       reference_p |= TYPE_REF_P (TREE_TYPE (obj));
1899       obj = TREE_OPERAND (obj, 0);
1900     }
1901 
1902   /* Evaluate the object so that we know its dynamic type.  */
1903   obj = cxx_eval_constant_expression (ctx, obj, /*lval*/false, non_constant_p,
1904 				      overflow_p);
1905   if (*non_constant_p)
1906     return call;
1907 
1908   /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
1909      but when HINT is > 0, it can also be something like
1910      &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET.  */
1911   obj = extract_obj_from_addr_offset (obj);
1912   const tree objtype = TREE_TYPE (obj);
1913   /* If OBJ doesn't refer to a base field, we're done.  */
1914   if (tree t = (TREE_CODE (obj) == COMPONENT_REF
1915 		? TREE_OPERAND (obj, 1) : obj))
1916     if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
1917       {
1918 	if (reference_p)
1919 	  {
1920 	    if (!ctx->quiet)
1921 	      {
1922 		error_at (loc, "reference %<dynamic_cast%> failed");
1923 		inform (loc, "dynamic type %qT of its operand does "
1924 			"not have a base class of type %qT",
1925 			objtype, type);
1926 	      }
1927 	    *non_constant_p = true;
1928 	  }
1929 	return integer_zero_node;
1930       }
1931 
1932   /* [class.cdtor] When a dynamic_cast is used in a constructor ...
1933      or in a destructor ... if the operand of the dynamic_cast refers
1934      to the object under construction or destruction, this object is
1935      considered to be a most derived object that has the type of the
1936      constructor or destructor's class.  */
1937   tree vtable = build_vfield_ref (obj, objtype);
1938   vtable = cxx_eval_constant_expression (ctx, vtable, /*lval*/false,
1939 					 non_constant_p, overflow_p);
1940   if (*non_constant_p)
1941     return call;
1942   /* With -fsanitize=vptr, we initialize all vtable pointers to null,
1943      so it's possible that we got a null pointer now.  */
1944   if (integer_zerop (vtable))
1945     {
1946       if (!ctx->quiet)
1947 	error_at (loc, "virtual table pointer is used uninitialized");
1948       *non_constant_p = true;
1949       return integer_zero_node;
1950     }
1951   /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A.  */
1952   vtable = extract_obj_from_addr_offset (vtable);
1953   const tree mdtype = DECL_CONTEXT (vtable);
1954 
1955   /* Given dynamic_cast<T>(v),
1956 
1957      [expr.dynamic.cast] If C is the class type to which T points or refers,
1958      the runtime check logically executes as follows:
1959 
1960      If, in the most derived object pointed (referred) to by v, v points
1961      (refers) to a public base class subobject of a C object, and if only
1962      one object of type C is derived from the subobject pointed (referred)
1963      to by v the result points (refers) to that C object.
1964 
1965      In this case, HINT >= 0 or -3.  */
1966   if (hint >= 0 || hint == -3)
1967     {
1968       /* Look for a component with type TYPE.  */
1969       tree t = get_component_with_type (obj, type, mdtype);
1970       /* If not accessible, give an error.  */
1971       if (t == error_mark_node)
1972 	{
1973 	  if (reference_p)
1974 	    {
1975 	      if (!ctx->quiet)
1976 		{
1977 		  error_at (loc, "reference %<dynamic_cast%> failed");
1978 		  inform (loc, "static type %qT of its operand is a "
1979 			  "non-public base class of dynamic type %qT",
1980 			  objtype, type);
1981 
1982 		}
1983 	      *non_constant_p = true;
1984 	    }
1985 	  return integer_zero_node;
1986 	}
1987       else if (t)
1988 	/* The result points to the TYPE object.  */
1989 	return cp_build_addr_expr (t, complain);
1990       /* Else, TYPE was not found, because the HINT turned out to be wrong.
1991 	 Fall through to the normal processing.  */
1992     }
1993 
1994   /* Otherwise, if v points (refers) to a public base class subobject of the
1995      most derived object, and the type of the most derived object has a base
1996      class, of type C, that is unambiguous and public, the result points
1997      (refers) to the C subobject of the most derived object.
1998 
1999      But it can also be an invalid case.  */
2000 
2001   /* Get the most derived object.  */
2002   obj = get_component_with_type (obj, mdtype, NULL_TREE);
2003   if (obj == error_mark_node)
2004     {
2005       if (reference_p)
2006 	{
2007 	  if (!ctx->quiet)
2008 	    {
2009 	      error_at (loc, "reference %<dynamic_cast%> failed");
2010 	      inform (loc, "static type %qT of its operand is a non-public"
2011 		      " base class of dynamic type %qT", objtype, mdtype);
2012 	    }
2013 	  *non_constant_p = true;
2014 	}
2015       return integer_zero_node;
2016     }
2017   else
2018     gcc_assert (obj);
2019 
2020   /* Check that the type of the most derived object has a base class
2021      of type TYPE that is unambiguous and public.  */
2022   base_kind b_kind;
2023   tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2024   if (!binfo || binfo == error_mark_node)
2025     {
2026       if (reference_p)
2027 	{
2028 	  if (!ctx->quiet)
2029 	    {
2030 	      error_at (loc, "reference %<dynamic_cast%> failed");
2031 	      if (b_kind == bk_ambig)
2032 		inform (loc, "%qT is an ambiguous base class of dynamic "
2033 			"type %qT of its operand", type, mdtype);
2034 	      else
2035 		inform (loc, "dynamic type %qT of its operand does not "
2036 			"have an unambiguous public base class %qT",
2037 			mdtype, type);
2038 	    }
2039 	  *non_constant_p = true;
2040 	}
2041       return integer_zero_node;
2042     }
2043   /* If so, return the TYPE subobject of the most derived object.  */
2044   obj = convert_to_base_statically (obj, binfo);
2045   return cp_build_addr_expr (obj, complain);
2046 }
2047 
2048 /* Data structure used by replace_result_decl and replace_result_decl_r.  */
2049 
2050 struct replace_result_decl_data
2051 {
2052   /* The RESULT_DECL we want to replace.  */
2053   tree decl;
2054   /* The replacement for DECL.  */
2055   tree replacement;
2056   /* Whether we've performed any replacements.  */
2057   bool changed;
2058 };
2059 
2060 /* Helper function for replace_result_decl, called through cp_walk_tree.  */
2061 
2062 static tree
replace_result_decl_r(tree * tp,int * walk_subtrees,void * data)2063 replace_result_decl_r (tree *tp, int *walk_subtrees, void *data)
2064 {
2065   replace_result_decl_data *d = (replace_result_decl_data *) data;
2066 
2067   if (*tp == d->decl)
2068     {
2069       *tp = unshare_expr (d->replacement);
2070       d->changed = true;
2071       *walk_subtrees = 0;
2072     }
2073   else if (TYPE_P (*tp))
2074     *walk_subtrees = 0;
2075 
2076   return NULL_TREE;
2077 }
2078 
2079 /* Replace every occurrence of DECL, a RESULT_DECL, with (an unshared copy of)
2080    REPLACEMENT within the reduced constant expression *TP.  Returns true iff a
2081    replacement was performed.  */
2082 
2083 static bool
replace_result_decl(tree * tp,tree decl,tree replacement)2084 replace_result_decl (tree *tp, tree decl, tree replacement)
2085 {
2086   gcc_checking_assert (TREE_CODE (decl) == RESULT_DECL
2087 		       && (same_type_ignoring_top_level_qualifiers_p
2088 			   (TREE_TYPE (decl), TREE_TYPE (replacement))));
2089   replace_result_decl_data data = { decl, replacement, false };
2090   cp_walk_tree_without_duplicates (tp, replace_result_decl_r, &data);
2091   return data.changed;
2092 }
2093 
2094 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2095    its TREE_READONLY flag according to READONLY_P.  Used for constexpr
2096    'tors to detect modifying const objects in a constexpr context.  */
2097 
2098 static void
cxx_set_object_constness(const constexpr_ctx * ctx,tree object,bool readonly_p,bool * non_constant_p,bool * overflow_p)2099 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2100 			  bool readonly_p, bool *non_constant_p,
2101 			  bool *overflow_p)
2102 {
2103   if (CLASS_TYPE_P (TREE_TYPE (object))
2104       && CP_TYPE_CONST_P (TREE_TYPE (object)))
2105     {
2106       /* Subobjects might not be stored in ctx->global->values but we
2107 	 can get its CONSTRUCTOR by evaluating *this.  */
2108       tree e = cxx_eval_constant_expression (ctx, object, /*lval*/false,
2109 					     non_constant_p, overflow_p);
2110       if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2111 	TREE_READONLY (e) = readonly_p;
2112     }
2113 }
2114 
2115 /* Subroutine of cxx_eval_constant_expression.
2116    Evaluate the call expression tree T in the context of OLD_CALL expression
2117    evaluation.  */
2118 
2119 static tree
cxx_eval_call_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)2120 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2121 			  bool lval,
2122 			  bool *non_constant_p, bool *overflow_p)
2123 {
2124   /* Handle concept checks separately.  */
2125   if (concept_check_p (t))
2126     return evaluate_concept_check (t, tf_warning_or_error);
2127 
2128   location_t loc = cp_expr_loc_or_input_loc (t);
2129   tree fun = get_function_named_in_call (t);
2130   constexpr_call new_call
2131     = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2132   int depth_ok;
2133 
2134   if (fun == NULL_TREE)
2135     return cxx_eval_internal_function (ctx, t, lval,
2136 				       non_constant_p, overflow_p);
2137 
2138   if (TREE_CODE (fun) != FUNCTION_DECL)
2139     {
2140       /* Might be a constexpr function pointer.  */
2141       fun = cxx_eval_constant_expression (ctx, fun,
2142 					  /*lval*/false, non_constant_p,
2143 					  overflow_p);
2144       STRIP_NOPS (fun);
2145       if (TREE_CODE (fun) == ADDR_EXPR)
2146 	fun = TREE_OPERAND (fun, 0);
2147       /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2148 	 indirection, the called expression is a pointer into the
2149 	 virtual table which should contain FDESC_EXPR.  Extract the
2150 	 FUNCTION_DECL from there.  */
2151       else if (TARGET_VTABLE_USES_DESCRIPTORS
2152 	       && TREE_CODE (fun) == POINTER_PLUS_EXPR
2153 	       && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2154 	       && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2155 	{
2156 	  tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2157 	  if (VAR_P (d)
2158 	      && DECL_VTABLE_OR_VTT_P (d)
2159 	      && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2160 	      && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2161 	      && DECL_INITIAL (d)
2162 	      && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2163 	    {
2164 	      tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2165 					TYPE_SIZE_UNIT (vtable_entry_type));
2166 	      HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2167 	      if (idx >= 0)
2168 		{
2169 		  tree fdesc
2170 		    = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2171 		  if (TREE_CODE (fdesc) == FDESC_EXPR
2172 		      && integer_zerop (TREE_OPERAND (fdesc, 1)))
2173 		    fun = TREE_OPERAND (fdesc, 0);
2174 		}
2175 	    }
2176 	}
2177     }
2178   if (TREE_CODE (fun) != FUNCTION_DECL)
2179     {
2180       if (!ctx->quiet && !*non_constant_p)
2181 	error_at (loc, "expression %qE does not designate a %<constexpr%> "
2182 		  "function", fun);
2183       *non_constant_p = true;
2184       return t;
2185     }
2186   if (DECL_CLONED_FUNCTION_P (fun))
2187     fun = DECL_CLONED_FUNCTION (fun);
2188 
2189   if (is_ubsan_builtin_p (fun))
2190     return void_node;
2191 
2192   if (fndecl_built_in_p (fun))
2193     return cxx_eval_builtin_function_call (ctx, t, fun,
2194 					   lval, non_constant_p, overflow_p);
2195   if (!DECL_DECLARED_CONSTEXPR_P (fun))
2196     {
2197       if (TREE_CODE (t) == CALL_EXPR
2198 	  && cxx_replaceable_global_alloc_fn (fun)
2199 	  && (CALL_FROM_NEW_OR_DELETE_P (t)
2200 	      || (ctx->call
2201 		  && ctx->call->fundef
2202 		  && is_std_allocator_allocate (ctx->call->fundef->decl))))
2203 	{
2204 	  const int nargs = call_expr_nargs (t);
2205 	  tree arg0 = NULL_TREE;
2206 	  for (int i = 0; i < nargs; ++i)
2207 	    {
2208 	      tree arg = CALL_EXPR_ARG (t, i);
2209 	      arg = cxx_eval_constant_expression (ctx, arg, false,
2210 						  non_constant_p, overflow_p);
2211 	      VERIFY_CONSTANT (arg);
2212 	      if (i == 0)
2213 		arg0 = arg;
2214 	    }
2215 	  gcc_assert (arg0);
2216 	  if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2217 	    {
2218 	      tree type = build_array_type_nelts (char_type_node,
2219 						  tree_to_uhwi (arg0));
2220 	      tree var = build_decl (loc, VAR_DECL, heap_uninit_identifier,
2221 				     type);
2222 	      DECL_ARTIFICIAL (var) = 1;
2223 	      TREE_STATIC (var) = 1;
2224 	      // Temporarily register the artificial var in varpool,
2225 	      // so that comparisons of its address against NULL are folded
2226 	      // through nonzero_address even with
2227 	      // -fno-delete-null-pointer-checks or that comparison of
2228 	      // addresses of different heap artificial vars is folded too.
2229 	      // See PR98988 and PR99031.
2230 	      varpool_node::finalize_decl (var);
2231 	      ctx->global->heap_vars.safe_push (var);
2232 	      ctx->global->values.put (var, NULL_TREE);
2233 	      return fold_convert (ptr_type_node, build_address (var));
2234 	    }
2235 	  else
2236 	    {
2237 	      STRIP_NOPS (arg0);
2238 	      if (TREE_CODE (arg0) == ADDR_EXPR
2239 		  && VAR_P (TREE_OPERAND (arg0, 0)))
2240 		{
2241 		  tree var = TREE_OPERAND (arg0, 0);
2242 		  if (DECL_NAME (var) == heap_uninit_identifier
2243 		      || DECL_NAME (var) == heap_identifier)
2244 		    {
2245 		      DECL_NAME (var) = heap_deleted_identifier;
2246 		      ctx->global->values.remove (var);
2247 		      ctx->global->heap_dealloc_count++;
2248 		      return void_node;
2249 		    }
2250 		  else if (DECL_NAME (var) == heap_deleted_identifier)
2251 		    {
2252 		      if (!ctx->quiet)
2253 			error_at (loc, "deallocation of already deallocated "
2254 				       "storage");
2255 		      *non_constant_p = true;
2256 		      return t;
2257 		    }
2258 		}
2259 	      if (!ctx->quiet)
2260 		error_at (loc, "deallocation of storage that was "
2261 			       "not previously allocated");
2262 	      *non_constant_p = true;
2263 	      return t;
2264 	    }
2265 	}
2266       /* Allow placement new in std::construct_at, just return the second
2267 	 argument.  */
2268       if (TREE_CODE (t) == CALL_EXPR
2269 	  && cxx_placement_new_fn (fun)
2270 	  && ctx->call
2271 	  && ctx->call->fundef
2272 	  && is_std_construct_at (ctx->call->fundef->decl))
2273 	{
2274 	  const int nargs = call_expr_nargs (t);
2275 	  tree arg1 = NULL_TREE;
2276 	  for (int i = 0; i < nargs; ++i)
2277 	    {
2278 	      tree arg = CALL_EXPR_ARG (t, i);
2279 	      arg = cxx_eval_constant_expression (ctx, arg, false,
2280 						  non_constant_p, overflow_p);
2281 	      if (i == 1)
2282 		arg1 = arg;
2283 	      else
2284 		VERIFY_CONSTANT (arg);
2285 	    }
2286 	  gcc_assert (arg1);
2287 	  return arg1;
2288 	}
2289       else if (cxx_dynamic_cast_fn_p (fun))
2290 	return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2291 
2292       if (!ctx->quiet)
2293 	{
2294 	  if (!lambda_static_thunk_p (fun))
2295 	    error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2296 	  explain_invalid_constexpr_fn (fun);
2297 	}
2298       *non_constant_p = true;
2299       return t;
2300     }
2301 
2302   constexpr_ctx new_ctx = *ctx;
2303   if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2304       && TREE_CODE (t) == AGGR_INIT_EXPR)
2305     {
2306       /* We want to have an initialization target for an AGGR_INIT_EXPR.
2307 	 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT.  */
2308       new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2309       tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2310       CONSTRUCTOR_NO_CLEARING (ctor) = true;
2311       ctx->global->values.put (new_ctx.object, ctor);
2312       ctx = &new_ctx;
2313     }
2314 
2315   /* Shortcut trivial constructor/op=.  */
2316   if (trivial_fn_p (fun))
2317     {
2318       tree init = NULL_TREE;
2319       if (call_expr_nargs (t) == 2)
2320 	init = convert_from_reference (get_nth_callarg (t, 1));
2321       else if (TREE_CODE (t) == AGGR_INIT_EXPR
2322 	       && AGGR_INIT_ZERO_FIRST (t))
2323 	init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
2324       if (init)
2325 	{
2326 	  tree op = get_nth_callarg (t, 0);
2327 	  if (is_dummy_object (op))
2328 	    op = ctx->object;
2329 	  else
2330 	    op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
2331 	  tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
2332 	  new_ctx.call = &new_call;
2333 	  return cxx_eval_constant_expression (&new_ctx, set, lval,
2334 					       non_constant_p, overflow_p);
2335 	}
2336     }
2337 
2338   /* We can't defer instantiating the function any longer.  */
2339   if (!DECL_INITIAL (fun)
2340       && !ctx->uid_sensitive
2341       && DECL_TEMPLOID_INSTANTIATION (fun))
2342     {
2343       location_t save_loc = input_location;
2344       input_location = loc;
2345       ++function_depth;
2346       instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
2347       --function_depth;
2348       input_location = save_loc;
2349     }
2350 
2351   /* If in direct recursive call, optimize definition search.  */
2352   if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
2353     new_call.fundef = ctx->call->fundef;
2354   else
2355     {
2356       new_call.fundef = retrieve_constexpr_fundef (fun);
2357       if (new_call.fundef == NULL || new_call.fundef->body == NULL
2358 	  || new_call.fundef->result == error_mark_node
2359 	  || fun == current_function_decl)
2360         {
2361 	  if (!ctx->quiet)
2362 	    {
2363 	      /* We need to check for current_function_decl here in case we're
2364 		 being called during cp_fold_function, because at that point
2365 		 DECL_INITIAL is set properly and we have a fundef but we
2366 		 haven't lowered invisirefs yet (c++/70344).  */
2367 	      if (DECL_INITIAL (fun) == error_mark_node
2368 		  || fun == current_function_decl)
2369 		error_at (loc, "%qD called in a constant expression before its "
2370 			  "definition is complete", fun);
2371 	      else if (DECL_INITIAL (fun))
2372 		{
2373 		  /* The definition of fun was somehow unsuitable.  But pretend
2374 		     that lambda static thunks don't exist.  */
2375 		  if (!lambda_static_thunk_p (fun))
2376 		    error_at (loc, "%qD called in a constant expression", fun);
2377 		  explain_invalid_constexpr_fn (fun);
2378 		}
2379 	      else
2380 		error_at (loc, "%qD used before its definition", fun);
2381 	    }
2382 	  *non_constant_p = true;
2383           return t;
2384         }
2385     }
2386 
2387   bool non_constant_args = false;
2388   cxx_bind_parameters_in_call (ctx, t, &new_call,
2389 			       non_constant_p, overflow_p, &non_constant_args);
2390 
2391   /* We build up the bindings list before we know whether we already have this
2392      call cached.  If we don't end up saving these bindings, ggc_free them when
2393      this function exits.  */
2394   class free_bindings
2395   {
2396     tree *bindings;
2397   public:
2398     free_bindings (tree &b): bindings (&b) { }
2399     ~free_bindings () { if (bindings) ggc_free (*bindings); }
2400     void preserve () { bindings = NULL; }
2401   } fb (new_call.bindings);
2402 
2403   if (*non_constant_p)
2404     return t;
2405 
2406   depth_ok = push_cx_call_context (t);
2407 
2408   /* Remember the object we are constructing or destructing.  */
2409   tree new_obj = NULL_TREE;
2410   if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
2411     {
2412       /* In a cdtor, it should be the first `this' argument.
2413 	 At this point it has already been evaluated in the call
2414 	 to cxx_bind_parameters_in_call.  */
2415       new_obj = TREE_VEC_ELT (new_call.bindings, 0);
2416       STRIP_NOPS (new_obj);
2417       if (TREE_CODE (new_obj) == ADDR_EXPR)
2418 	new_obj = TREE_OPERAND (new_obj, 0);
2419 
2420       if (ctx->call && ctx->call->fundef
2421 	  && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
2422 	{
2423 	  tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
2424 	  STRIP_NOPS (cur_obj);
2425 	  if (TREE_CODE (cur_obj) == ADDR_EXPR)
2426 	    cur_obj = TREE_OPERAND (cur_obj, 0);
2427 	  if (new_obj == cur_obj)
2428 	    /* We're calling the target constructor of a delegating
2429 	       constructor, or accessing a base subobject through a
2430 	       NOP_EXPR as part of a call to a base constructor, so
2431 	       there is no new (sub)object.  */
2432 	    new_obj = NULL_TREE;
2433 	}
2434     }
2435 
2436   tree result = NULL_TREE;
2437 
2438   constexpr_call *entry = NULL;
2439   if (depth_ok && !non_constant_args && ctx->strict)
2440     {
2441       new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
2442       new_call.hash
2443 	= iterative_hash_template_arg (new_call.bindings, new_call.hash);
2444       new_call.hash
2445 	= iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
2446 
2447       /* If we have seen this call before, we are done.  */
2448       maybe_initialize_constexpr_call_table ();
2449       constexpr_call **slot
2450 	= constexpr_call_table->find_slot (&new_call, INSERT);
2451       entry = *slot;
2452       if (entry == NULL)
2453 	{
2454 	  /* Only cache up to constexpr_cache_depth to limit memory use.  */
2455 	  if (depth_ok < constexpr_cache_depth)
2456 	    {
2457 	      /* We need to keep a pointer to the entry, not just the slot, as
2458 		 the slot can move during evaluation of the body.  */
2459 	      *slot = entry = ggc_alloc<constexpr_call> ();
2460 	      *entry = new_call;
2461 	      fb.preserve ();
2462 	    }
2463 	}
2464       /* Calls that are in progress have their result set to NULL, so that we
2465 	 can detect circular dependencies.  Now that we only cache up to
2466 	 constexpr_cache_depth this won't catch circular dependencies that
2467 	 start deeper, but they'll hit the recursion or ops limit.  */
2468       else if (entry->result == NULL)
2469 	{
2470 	  if (!ctx->quiet)
2471 	    error ("call has circular dependency");
2472 	  *non_constant_p = true;
2473 	  entry->result = result = error_mark_node;
2474 	}
2475       else
2476 	result = entry->result;
2477     }
2478 
2479   if (!depth_ok)
2480     {
2481       if (!ctx->quiet)
2482 	error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
2483 	       "%<-fconstexpr-depth=%> to increase the maximum)",
2484 	       max_constexpr_depth);
2485       *non_constant_p = true;
2486       result = error_mark_node;
2487     }
2488   else
2489     {
2490       bool cacheable = true;
2491       if (result && result != error_mark_node)
2492 	/* OK */;
2493       else if (!DECL_SAVED_TREE (fun))
2494 	{
2495 	  /* When at_eof >= 2, cgraph has started throwing away
2496 	     DECL_SAVED_TREE, so fail quietly.  FIXME we get here because of
2497 	     late code generation for VEC_INIT_EXPR, which needs to be
2498 	     completely reconsidered.  */
2499 	  gcc_assert (at_eof >= 2 && ctx->quiet);
2500 	  *non_constant_p = true;
2501 	}
2502       else if (tree copy = get_fundef_copy (ctx, new_call.fundef))
2503 	{
2504 	  tree body, parms, res;
2505 	  releasing_vec ctors;
2506 
2507 	  /* Reuse or create a new unshared copy of this function's body.  */
2508 	  body = TREE_PURPOSE (copy);
2509 	  parms = TREE_VALUE (copy);
2510 	  res = TREE_TYPE (copy);
2511 
2512 	  /* Associate the bindings with the remapped parms.  */
2513 	  tree bound = new_call.bindings;
2514 	  tree remapped = parms;
2515 	  for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
2516 	    {
2517 	      tree arg = TREE_VEC_ELT (bound, i);
2518 	      if (entry)
2519 		{
2520 		  /* Unshare args going into the hash table to separate them
2521 		     from the caller's context, for better GC and to avoid
2522 		     problems with verify_gimple.  */
2523 		  arg = unshare_expr_without_location (arg);
2524 		  TREE_VEC_ELT (bound, i) = arg;
2525 		}
2526 	      /* Don't share a CONSTRUCTOR that might be changed.  This is not
2527 		 redundant with the unshare just above; we also don't want to
2528 		 change the argument values in the hash table.  XXX Could we
2529 		 unshare lazily in cxx_eval_store_expression?  */
2530 	      arg = unshare_constructor (arg);
2531 	      if (TREE_CODE (arg) == CONSTRUCTOR)
2532 		vec_safe_push (ctors, arg);
2533 	      ctx->global->values.put (remapped, arg);
2534 	      remapped = DECL_CHAIN (remapped);
2535 	    }
2536 	  /* Add the RESULT_DECL to the values map, too.  */
2537 	  gcc_assert (!DECL_BY_REFERENCE (res));
2538 	  ctx->global->values.put (res, NULL_TREE);
2539 
2540 	  /* Track the callee's evaluated SAVE_EXPRs and TARGET_EXPRs so that
2541 	     we can forget their values after the call.  */
2542 	  constexpr_ctx ctx_with_save_exprs = *ctx;
2543 	  auto_vec<tree, 10> save_exprs;
2544 	  ctx_with_save_exprs.save_exprs = &save_exprs;
2545 	  ctx_with_save_exprs.call = &new_call;
2546 	  unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
2547 	  unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
2548 
2549 	  /* If this is a constexpr destructor, the object's const and volatile
2550 	     semantics are no longer in effect; see [class.dtor]p5.  */
2551 	  if (new_obj && DECL_DESTRUCTOR_P (fun))
2552 	    cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
2553 				      non_constant_p, overflow_p);
2554 
2555 	  tree jump_target = NULL_TREE;
2556 	  cxx_eval_constant_expression (&ctx_with_save_exprs, body,
2557 					lval, non_constant_p, overflow_p,
2558 					&jump_target);
2559 
2560 	  if (DECL_CONSTRUCTOR_P (fun))
2561 	    /* This can be null for a subobject constructor call, in
2562 	       which case what we care about is the initialization
2563 	       side-effects rather than the value.  We could get at the
2564 	       value by evaluating *this, but we don't bother; there's
2565 	       no need to put such a call in the hash table.  */
2566 	    result = lval ? ctx->object : ctx->ctor;
2567 	  else if (VOID_TYPE_P (TREE_TYPE (res)))
2568 	    result = void_node;
2569 	  else
2570 	    {
2571 	      result = *ctx->global->values.get (res);
2572 	      if (result == NULL_TREE && !*non_constant_p)
2573 		{
2574 		  if (!ctx->quiet)
2575 		    error ("%<constexpr%> call flows off the end "
2576 			   "of the function");
2577 		  *non_constant_p = true;
2578 		}
2579 	    }
2580 
2581 	  /* At this point, the object's constructor will have run, so
2582 	     the object is no longer under construction, and its possible
2583 	     'const' semantics now apply.  Make a note of this fact by
2584 	     marking the CONSTRUCTOR TREE_READONLY.  */
2585 	  if (new_obj && DECL_CONSTRUCTOR_P (fun))
2586 	    cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
2587 				      non_constant_p, overflow_p);
2588 
2589 	  /* Forget the saved values of the callee's SAVE_EXPRs and
2590 	     TARGET_EXPRs.  */
2591 	  unsigned int i;
2592 	  tree save_expr;
2593 	  FOR_EACH_VEC_ELT (save_exprs, i, save_expr)
2594 	    ctx->global->values.remove (save_expr);
2595 
2596 	  /* Remove the parms/result from the values map.  Is it worth
2597 	     bothering to do this when the map itself is only live for
2598 	     one constexpr evaluation?  If so, maybe also clear out
2599 	     other vars from call, maybe in BIND_EXPR handling?  */
2600 	  ctx->global->values.remove (res);
2601 	  for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
2602 	    ctx->global->values.remove (parm);
2603 
2604 	  /* Free any parameter CONSTRUCTORs we aren't returning directly.  */
2605 	  while (!ctors->is_empty ())
2606 	    {
2607 	      tree c = ctors->pop ();
2608 	      if (c != result)
2609 		free_constructor (c);
2610 	    }
2611 
2612 	  /* Make the unshared function copy we used available for re-use.  */
2613 	  save_fundef_copy (fun, copy);
2614 
2615 	  /* If the call allocated some heap object that hasn't been
2616 	     deallocated during the call, or if it deallocated some heap
2617 	     object it has not allocated, the call isn't really stateless
2618 	     for the constexpr evaluation and should not be cached.
2619 	     It is fine if the call allocates something and deallocates it
2620 	     too.  */
2621 	  if (entry
2622 	      && (save_heap_alloc_count != ctx->global->heap_vars.length ()
2623 		  || (save_heap_dealloc_count
2624 		      != ctx->global->heap_dealloc_count)))
2625 	    {
2626 	      tree heap_var;
2627 	      unsigned int i;
2628 	      if ((ctx->global->heap_vars.length ()
2629 		   - ctx->global->heap_dealloc_count)
2630 		  != save_heap_alloc_count - save_heap_dealloc_count)
2631 		cacheable = false;
2632 	      else
2633 		FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
2634 				       save_heap_alloc_count)
2635 		  if (DECL_NAME (heap_var) != heap_deleted_identifier)
2636 		    {
2637 		      cacheable = false;
2638 		      break;
2639 		    }
2640 	    }
2641 
2642 	    /* Rewrite all occurrences of the function's RESULT_DECL with the
2643 	       current object under construction.  */
2644 	    if (!*non_constant_p && ctx->object
2645 		&& CLASS_TYPE_P (TREE_TYPE (res))
2646 		&& !is_empty_class (TREE_TYPE (res)))
2647 	      if (replace_result_decl (&result, res, ctx->object))
2648 		cacheable = false;
2649 	}
2650       else
2651 	/* Couldn't get a function copy to evaluate.  */
2652 	*non_constant_p = true;
2653 
2654       if (result == error_mark_node)
2655 	*non_constant_p = true;
2656       if (*non_constant_p || *overflow_p)
2657 	result = error_mark_node;
2658       else if (!result)
2659 	result = void_node;
2660       if (entry)
2661 	entry->result = cacheable ? result : error_mark_node;
2662     }
2663 
2664   /* The result of a constexpr function must be completely initialized.
2665 
2666      However, in C++20, a constexpr constructor doesn't necessarily have
2667      to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
2668      in order to detect reading an unitialized object in constexpr instead
2669      of value-initializing it.  (reduced_constant_expression_p is expected to
2670      take care of clearing the flag.)  */
2671   if (TREE_CODE (result) == CONSTRUCTOR
2672       && (cxx_dialect < cxx2a
2673 	  || !DECL_CONSTRUCTOR_P (fun)))
2674     clear_no_implicit_zero (result);
2675 
2676   pop_cx_call_context ();
2677   return result;
2678 }
2679 
2680 /* Return true if T is a valid constant initializer.  If a CONSTRUCTOR
2681    initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
2682    cleared.
2683    FIXME speed this up, it's taking 16% of compile time on sieve testcase.  */
2684 
2685 bool
reduced_constant_expression_p(tree t)2686 reduced_constant_expression_p (tree t)
2687 {
2688   if (t == NULL_TREE)
2689     return false;
2690 
2691   switch (TREE_CODE (t))
2692     {
2693     case PTRMEM_CST:
2694       /* Even if we can't lower this yet, it's constant.  */
2695       return true;
2696 
2697     case CONSTRUCTOR:
2698       /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR.  */
2699       tree idx, val, field; unsigned HOST_WIDE_INT i;
2700       if (CONSTRUCTOR_NO_CLEARING (t))
2701 	{
2702 	  if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
2703 	    /* An initialized vector would have a VECTOR_CST.  */
2704 	    return false;
2705 	  else if (cxx_dialect >= cxx2a
2706 		   /* An ARRAY_TYPE doesn't have any TYPE_FIELDS.  */
2707 		   && TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
2708 	    field = NULL_TREE;
2709 	  else if (cxx_dialect >= cxx2a
2710 		   && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
2711 	    {
2712 	      if (CONSTRUCTOR_NELTS (t) == 0)
2713 		/* An initialized union has a constructor element.  */
2714 		return false;
2715 	      /* And it only initializes one member.  */
2716 	      field = NULL_TREE;
2717 	    }
2718 	  else
2719 	    field = next_initializable_field (TYPE_FIELDS (TREE_TYPE (t)));
2720 	}
2721       else
2722 	field = NULL_TREE;
2723       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, idx, val)
2724 	{
2725 	  /* If VAL is null, we're in the middle of initializing this
2726 	     element.  */
2727 	  if (!reduced_constant_expression_p (val))
2728 	    return false;
2729 	  /* Empty class field may or may not have an initializer.  */
2730 	  for (; field && idx != field;
2731 	       field = next_initializable_field (DECL_CHAIN (field)))
2732 	    if (!is_really_empty_class (TREE_TYPE (field),
2733 					/*ignore_vptr*/false))
2734 	      return false;
2735 	  if (field)
2736 	    field = next_initializable_field (DECL_CHAIN (field));
2737 	}
2738       /* There could be a non-empty field at the end.  */
2739       for (; field; field = next_initializable_field (DECL_CHAIN (field)))
2740 	if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
2741 	  return false;
2742       if (CONSTRUCTOR_NO_CLEARING (t))
2743 	/* All the fields are initialized.  */
2744 	CONSTRUCTOR_NO_CLEARING (t) = false;
2745       return true;
2746 
2747     default:
2748       /* FIXME are we calling this too much?  */
2749       return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
2750     }
2751 }
2752 
2753 /* Some expressions may have constant operands but are not constant
2754    themselves, such as 1/0.  Call this function to check for that
2755    condition.
2756 
2757    We only call this in places that require an arithmetic constant, not in
2758    places where we might have a non-constant expression that can be a
2759    component of a constant expression, such as the address of a constexpr
2760    variable that might be dereferenced later.  */
2761 
2762 static bool
verify_constant(tree t,bool allow_non_constant,bool * non_constant_p,bool * overflow_p)2763 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
2764 		 bool *overflow_p)
2765 {
2766   if (!*non_constant_p && !reduced_constant_expression_p (t)
2767       && t != void_node)
2768     {
2769       if (!allow_non_constant)
2770 	error ("%q+E is not a constant expression", t);
2771       *non_constant_p = true;
2772     }
2773   if (TREE_OVERFLOW_P (t))
2774     {
2775       if (!allow_non_constant)
2776 	{
2777 	  permerror (input_location, "overflow in constant expression");
2778 	  /* If we're being permissive (and are in an enforcing
2779 	     context), ignore the overflow.  */
2780 	  if (flag_permissive)
2781 	    return *non_constant_p;
2782 	}
2783       *overflow_p = true;
2784     }
2785   return *non_constant_p;
2786 }
2787 
2788 /* Check whether the shift operation with code CODE and type TYPE on LHS
2789    and RHS is undefined.  If it is, give an error with an explanation,
2790    and return true; return false otherwise.  */
2791 
2792 static bool
cxx_eval_check_shift_p(location_t loc,const constexpr_ctx * ctx,enum tree_code code,tree type,tree lhs,tree rhs)2793 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
2794 			enum tree_code code, tree type, tree lhs, tree rhs)
2795 {
2796   if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
2797       || TREE_CODE (lhs) != INTEGER_CST
2798       || TREE_CODE (rhs) != INTEGER_CST)
2799     return false;
2800 
2801   tree lhstype = TREE_TYPE (lhs);
2802   unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
2803 
2804   /* [expr.shift] The behavior is undefined if the right operand
2805      is negative, or greater than or equal to the length in bits
2806      of the promoted left operand.  */
2807   if (tree_int_cst_sgn (rhs) == -1)
2808     {
2809       if (!ctx->quiet)
2810 	permerror (loc, "right operand of shift expression %q+E is negative",
2811 		   build2_loc (loc, code, type, lhs, rhs));
2812       return (!flag_permissive || ctx->quiet);
2813     }
2814   if (compare_tree_int (rhs, uprec) >= 0)
2815     {
2816       if (!ctx->quiet)
2817 	permerror (loc, "right operand of shift expression %q+E is greater "
2818 		   "than or equal to the precision %wu of the left operand",
2819 		   build2_loc (loc, code, type, lhs, rhs), uprec);
2820       return (!flag_permissive || ctx->quiet);
2821     }
2822 
2823   /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
2824      if E1 has a signed type and non-negative value, and E1x2^E2 is
2825      representable in the corresponding unsigned type of the result type,
2826      then that value, converted to the result type, is the resulting value;
2827      otherwise, the behavior is undefined.
2828      For C++2a:
2829      The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
2830      2^N, where N is the range exponent of the type of the result.  */
2831   if (code == LSHIFT_EXPR
2832       && !TYPE_UNSIGNED (lhstype)
2833       && cxx_dialect >= cxx11
2834       && cxx_dialect < cxx2a)
2835     {
2836       if (tree_int_cst_sgn (lhs) == -1)
2837 	{
2838 	  if (!ctx->quiet)
2839 	    permerror (loc,
2840 		       "left operand of shift expression %q+E is negative",
2841 		       build2_loc (loc, code, type, lhs, rhs));
2842 	  return (!flag_permissive || ctx->quiet);
2843 	}
2844       /* For signed x << y the following:
2845 	 (unsigned) x >> ((prec (lhs) - 1) - y)
2846 	 if > 1, is undefined.  The right-hand side of this formula
2847 	 is the highest bit of the LHS that can be set (starting from 0),
2848 	 so that the shift doesn't overflow.  We then right-shift the LHS
2849 	 to see whether any other bit is set making the original shift
2850 	 undefined -- the result is not representable in the corresponding
2851 	 unsigned type.  */
2852       tree t = build_int_cst (unsigned_type_node, uprec - 1);
2853       t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
2854       tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
2855       t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
2856       if (tree_int_cst_lt (integer_one_node, t))
2857 	{
2858 	  if (!ctx->quiet)
2859 	    permerror (loc, "shift expression %q+E overflows",
2860 		       build2_loc (loc, code, type, lhs, rhs));
2861 	  return (!flag_permissive || ctx->quiet);
2862 	}
2863     }
2864   return false;
2865 }
2866 
2867 /* Subroutine of cxx_eval_constant_expression.
2868    Attempt to reduce the unary expression tree T to a compile time value.
2869    If successful, return the value.  Otherwise issue a diagnostic
2870    and return error_mark_node.  */
2871 
2872 static tree
cxx_eval_unary_expression(const constexpr_ctx * ctx,tree t,bool,bool * non_constant_p,bool * overflow_p)2873 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
2874 			   bool /*lval*/,
2875 			   bool *non_constant_p, bool *overflow_p)
2876 {
2877   tree r;
2878   tree orig_arg = TREE_OPERAND (t, 0);
2879   tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
2880 					   non_constant_p, overflow_p);
2881   VERIFY_CONSTANT (arg);
2882   location_t loc = EXPR_LOCATION (t);
2883   enum tree_code code = TREE_CODE (t);
2884   tree type = TREE_TYPE (t);
2885   r = fold_unary_loc (loc, code, type, arg);
2886   if (r == NULL_TREE)
2887     {
2888       if (arg == orig_arg)
2889 	r = t;
2890       else
2891 	r = build1_loc (loc, code, type, arg);
2892     }
2893   VERIFY_CONSTANT (r);
2894   return r;
2895 }
2896 
2897 /* Helper function for cxx_eval_binary_expression.  Try to optimize
2898    original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
2899    generic folding should be used.  */
2900 
2901 static tree
cxx_fold_pointer_plus_expression(const constexpr_ctx * ctx,tree t,tree lhs,tree rhs,bool * non_constant_p,bool * overflow_p)2902 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
2903 				  tree lhs, tree rhs, bool *non_constant_p,
2904 				  bool *overflow_p)
2905 {
2906   STRIP_NOPS (lhs);
2907   if (TREE_CODE (lhs) != ADDR_EXPR)
2908     return NULL_TREE;
2909 
2910   lhs = TREE_OPERAND (lhs, 0);
2911 
2912   /* &A[i] p+ j => &A[i + j] */
2913   if (TREE_CODE (lhs) == ARRAY_REF
2914       && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
2915       && TREE_CODE (rhs) == INTEGER_CST
2916       && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
2917       && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
2918     {
2919       tree orig_type = TREE_TYPE (t);
2920       location_t loc = EXPR_LOCATION (t);
2921       tree type = TREE_TYPE (lhs);
2922 
2923       t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
2924       tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
2925       nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
2926 					    overflow_p);
2927       if (*non_constant_p)
2928 	return NULL_TREE;
2929       /* Don't fold an out-of-bound access.  */
2930       if (!tree_int_cst_le (t, nelts))
2931 	return NULL_TREE;
2932       rhs = cp_fold_convert (ssizetype, rhs);
2933       /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
2934 	 constexpr int A[1]; ... (char *)&A[0] + 1 */
2935       if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
2936 					   rhs, TYPE_SIZE_UNIT (type))))
2937 	return NULL_TREE;
2938       /* Make sure to treat the second operand of POINTER_PLUS_EXPR
2939 	 as signed.  */
2940       rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
2941 			     TYPE_SIZE_UNIT (type));
2942       t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
2943       t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
2944 		      t, NULL_TREE, NULL_TREE);
2945       t = cp_build_addr_expr (t, tf_warning_or_error);
2946       t = cp_fold_convert (orig_type, t);
2947       return cxx_eval_constant_expression (ctx, t, /*lval*/false,
2948 					   non_constant_p, overflow_p);
2949     }
2950 
2951   return NULL_TREE;
2952 }
2953 
2954 /* Subroutine of cxx_eval_constant_expression.
2955    Like cxx_eval_unary_expression, except for binary expressions.  */
2956 
2957 static tree
cxx_eval_binary_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)2958 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
2959 			    bool lval,
2960 			    bool *non_constant_p, bool *overflow_p)
2961 {
2962   tree r = NULL_TREE;
2963   tree orig_lhs = TREE_OPERAND (t, 0);
2964   tree orig_rhs = TREE_OPERAND (t, 1);
2965   tree lhs, rhs;
2966   lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
2967 				      non_constant_p, overflow_p);
2968   /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
2969      subtraction.  */
2970   if (*non_constant_p)
2971     return t;
2972   rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
2973 				      non_constant_p, overflow_p);
2974   if (*non_constant_p)
2975     return t;
2976 
2977   location_t loc = EXPR_LOCATION (t);
2978   enum tree_code code = TREE_CODE (t);
2979   tree type = TREE_TYPE (t);
2980 
2981   if (code == EQ_EXPR || code == NE_EXPR)
2982     {
2983       bool is_code_eq = (code == EQ_EXPR);
2984 
2985       if (TREE_CODE (lhs) == PTRMEM_CST
2986 	  && TREE_CODE (rhs) == PTRMEM_CST)
2987 	{
2988 	  tree lmem = PTRMEM_CST_MEMBER (lhs);
2989 	  tree rmem = PTRMEM_CST_MEMBER (rhs);
2990 	  bool eq;
2991 	  if (TREE_CODE (lmem) == TREE_CODE (rmem)
2992 	      && TREE_CODE (lmem) == FIELD_DECL
2993 	      && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
2994 	      && same_type_p (DECL_CONTEXT (lmem),
2995 			      DECL_CONTEXT (rmem)))
2996 	    /* If both refer to (possibly different) members of the same union
2997 	       (12.3), they compare equal. */
2998 	    eq = true;
2999 	  else
3000 	    eq = cp_tree_equal (lhs, rhs);
3001 	  r = constant_boolean_node (eq == is_code_eq, type);
3002 	}
3003       else if ((TREE_CODE (lhs) == PTRMEM_CST
3004 		|| TREE_CODE (rhs) == PTRMEM_CST)
3005 	       && (null_member_pointer_value_p (lhs)
3006 		   || null_member_pointer_value_p (rhs)))
3007 	r = constant_boolean_node (!is_code_eq, type);
3008       else if (TREE_CODE (lhs) == PTRMEM_CST)
3009 	lhs = cplus_expand_constant (lhs);
3010       else if (TREE_CODE (rhs) == PTRMEM_CST)
3011 	rhs = cplus_expand_constant (rhs);
3012     }
3013   if (code == POINTER_PLUS_EXPR && !*non_constant_p
3014       && integer_zerop (lhs) && !integer_zerop (rhs))
3015     {
3016       if (!ctx->quiet)
3017 	error ("arithmetic involving a null pointer in %qE", lhs);
3018       *non_constant_p = true;
3019       return t;
3020     }
3021   else if (code == POINTER_PLUS_EXPR)
3022     r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3023 					  overflow_p);
3024   else if (code == SPACESHIP_EXPR)
3025     {
3026       r = genericize_spaceship (type, lhs, rhs);
3027       return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3028 					   overflow_p);
3029     }
3030 
3031   if (r == NULL_TREE)
3032     r = fold_binary_loc (loc, code, type, lhs, rhs);
3033 
3034   if (r == NULL_TREE)
3035     {
3036       if (lhs == orig_lhs && rhs == orig_rhs)
3037 	r = t;
3038       else
3039 	r = build2_loc (loc, code, type, lhs, rhs);
3040     }
3041   else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3042     *non_constant_p = true;
3043   /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3044      a local array in a constexpr function.  */
3045   bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3046   if (!ptr)
3047     VERIFY_CONSTANT (r);
3048   return r;
3049 }
3050 
3051 /* Subroutine of cxx_eval_constant_expression.
3052    Attempt to evaluate condition expressions.  Dead branches are not
3053    looked into.  */
3054 
3055 static tree
cxx_eval_conditional_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p,tree * jump_target)3056 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3057 				 bool lval,
3058 				 bool *non_constant_p, bool *overflow_p,
3059 				 tree *jump_target)
3060 {
3061   tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3062 					   /*lval*/false,
3063 					   non_constant_p, overflow_p);
3064   VERIFY_CONSTANT (val);
3065   /* Don't VERIFY_CONSTANT the other operands.  */
3066   if (integer_zerop (val))
3067     val = TREE_OPERAND (t, 2);
3068   else
3069     val = TREE_OPERAND (t, 1);
3070   if (TREE_CODE (t) == IF_STMT && !val)
3071     val = void_node;
3072   return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3073 				       overflow_p, jump_target);
3074 }
3075 
3076 /* Subroutine of cxx_eval_constant_expression.
3077    Attempt to evaluate vector condition expressions.  Unlike
3078    cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3079    ternary arithmetics operation, where all 3 arguments have to be
3080    evaluated as constants and then folding computes the result from
3081    them.  */
3082 
3083 static tree
cxx_eval_vector_conditional_expression(const constexpr_ctx * ctx,tree t,bool * non_constant_p,bool * overflow_p)3084 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3085 					bool *non_constant_p, bool *overflow_p)
3086 {
3087   tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3088 					    /*lval*/false,
3089 					    non_constant_p, overflow_p);
3090   VERIFY_CONSTANT (arg1);
3091   tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3092 					    /*lval*/false,
3093 					    non_constant_p, overflow_p);
3094   VERIFY_CONSTANT (arg2);
3095   tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3096 					    /*lval*/false,
3097 					    non_constant_p, overflow_p);
3098   VERIFY_CONSTANT (arg3);
3099   location_t loc = EXPR_LOCATION (t);
3100   tree type = TREE_TYPE (t);
3101   tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3102   if (r == NULL_TREE)
3103     {
3104       if (arg1 == TREE_OPERAND (t, 0)
3105 	  && arg2 == TREE_OPERAND (t, 1)
3106 	  && arg3 == TREE_OPERAND (t, 2))
3107 	r = t;
3108       else
3109 	r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3110     }
3111   VERIFY_CONSTANT (r);
3112   return r;
3113 }
3114 
3115 /* Returns less than, equal to, or greater than zero if KEY is found to be
3116    less than, to match, or to be greater than the constructor_elt's INDEX.  */
3117 
3118 static int
array_index_cmp(tree key,tree index)3119 array_index_cmp (tree key, tree index)
3120 {
3121   gcc_assert (TREE_CODE (key) == INTEGER_CST);
3122 
3123   switch (TREE_CODE (index))
3124     {
3125     case INTEGER_CST:
3126       return tree_int_cst_compare (key, index);
3127     case RANGE_EXPR:
3128       {
3129 	tree lo = TREE_OPERAND (index, 0);
3130 	tree hi = TREE_OPERAND (index, 1);
3131 	if (tree_int_cst_lt (key, lo))
3132 	  return -1;
3133 	else if (tree_int_cst_lt (hi, key))
3134 	  return 1;
3135 	else
3136 	  return 0;
3137       }
3138     default:
3139       gcc_unreachable ();
3140     }
3141 }
3142 
3143 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3144    if none.  If INSERT is true, insert a matching element rather than fail.  */
3145 
3146 static HOST_WIDE_INT
find_array_ctor_elt(tree ary,tree dindex,bool insert)3147 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3148 {
3149   if (tree_int_cst_sgn (dindex) < 0)
3150     return -1;
3151 
3152   unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
3153   vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
3154   unsigned HOST_WIDE_INT len = vec_safe_length (elts);
3155 
3156   unsigned HOST_WIDE_INT end = len;
3157   unsigned HOST_WIDE_INT begin = 0;
3158 
3159   /* If the last element of the CONSTRUCTOR has its own index, we can assume
3160      that the same is true of the other elements and index directly.  */
3161   if (end > 0)
3162     {
3163       tree cindex = (*elts)[end - 1].index;
3164       if (cindex == NULL_TREE)
3165 	{
3166 	  /* Verify that if the last index is missing, all indexes
3167 	     are missing.  */
3168 	  if (flag_checking)
3169 	    for (unsigned int j = 0; j < len - 1; ++j)
3170 	      gcc_assert ((*elts)[j].index == NULL_TREE);
3171 	  if (i < end)
3172 	    return i;
3173 	  else
3174 	    {
3175 	      begin = end;
3176 	      if (i == end)
3177 		/* If the element is to be added right at the end,
3178 		   make sure it is added with cleared index too.  */
3179 		dindex = NULL_TREE;
3180 	      else if (insert)
3181 		/* Otherwise, in order not to break the assumption
3182 		   that CONSTRUCTOR either has all indexes or none,
3183 		   we need to add indexes to all elements.  */
3184 		for (unsigned int j = 0; j < len; ++j)
3185 		  (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
3186 	    }
3187 	}
3188       else if (TREE_CODE (cindex) == INTEGER_CST
3189 	       && compare_tree_int (cindex, end - 1) == 0)
3190 	{
3191 	  if (i < end)
3192 	    return i;
3193 	  else
3194 	    begin = end;
3195 	}
3196     }
3197 
3198   /* Otherwise, find a matching index by means of a binary search.  */
3199   while (begin != end)
3200     {
3201       unsigned HOST_WIDE_INT middle = (begin + end) / 2;
3202       constructor_elt &elt = (*elts)[middle];
3203       tree idx = elt.index;
3204 
3205       int cmp = array_index_cmp (dindex, idx);
3206       if (cmp < 0)
3207 	end = middle;
3208       else if (cmp > 0)
3209 	begin = middle + 1;
3210       else
3211 	{
3212 	  if (insert && TREE_CODE (idx) == RANGE_EXPR)
3213 	    {
3214 	      /* We need to split the range.  */
3215 	      constructor_elt e;
3216 	      tree lo = TREE_OPERAND (idx, 0);
3217 	      tree hi = TREE_OPERAND (idx, 1);
3218 	      tree value = elt.value;
3219 	      dindex = fold_convert (sizetype, dindex);
3220 	      if (tree_int_cst_lt (lo, dindex))
3221 		{
3222 		  /* There are still some lower elts; shorten the range.  */
3223 		  tree new_hi = int_const_binop (MINUS_EXPR, dindex,
3224 						 size_one_node);
3225 		  if (tree_int_cst_equal (lo, new_hi))
3226 		    /* Only one element left, no longer a range.  */
3227 		    elt.index = lo;
3228 		  else
3229 		    TREE_OPERAND (idx, 1) = new_hi;
3230 		  /* Append the element we want to insert.  */
3231 		  ++middle;
3232 		  e.index = dindex;
3233 		  e.value = unshare_constructor (value);
3234 		  vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
3235 		}
3236 	      else
3237 		/* No lower elts, the range elt is now ours.  */
3238 		elt.index = dindex;
3239 
3240 	      if (tree_int_cst_lt (dindex, hi))
3241 		{
3242 		  /* There are still some higher elts; append a range.  */
3243 		  tree new_lo = int_const_binop (PLUS_EXPR, dindex,
3244 						 size_one_node);
3245 		  if (tree_int_cst_equal (new_lo, hi))
3246 		    e.index = hi;
3247 		  else
3248 		    e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
3249 		  e.value = unshare_constructor (value);
3250 		  vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
3251 		}
3252 	    }
3253 	  return middle;
3254 	}
3255     }
3256 
3257   if (insert)
3258     {
3259       constructor_elt e = { dindex, NULL_TREE };
3260       vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
3261       return end;
3262     }
3263 
3264   return -1;
3265 }
3266 
3267 /* Return a pointer to the constructor_elt of CTOR which matches INDEX.  If no
3268    matching constructor_elt exists, then add one to CTOR.
3269 
3270    As an optimization, if POS_HINT is non-negative then it is used as a guess
3271    for the (integer) index of the matching constructor_elt within CTOR.  */
3272 
3273 static constructor_elt *
3274 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
3275 {
3276   /* Check the hint first.  */
3277   if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
3278       && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
3279     return CONSTRUCTOR_ELT (ctor, pos_hint);
3280 
3281   tree type = TREE_TYPE (ctor);
3282   if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
3283     {
3284       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
3285       return &CONSTRUCTOR_ELTS (ctor)->last();
3286     }
3287   else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
3288     {
3289       if (TREE_CODE (index) == RANGE_EXPR)
3290 	{
3291 	  /* Support for RANGE_EXPR index lookups is currently limited to
3292 	     accessing an existing element via POS_HINT, or appending a new
3293 	     element to the end of CTOR.  ??? Support for other access
3294 	     patterns may also be needed.  */
3295 	  vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
3296 	  if (vec_safe_length (elts))
3297 	    {
3298 	      tree lo = TREE_OPERAND (index, 0);
3299 	      gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
3300 	    }
3301 	  CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
3302 	  return &elts->last();
3303 	}
3304 
3305       HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
3306       gcc_assert (i >= 0);
3307       constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
3308       gcc_assert (cep->index == NULL_TREE
3309 		  || TREE_CODE (cep->index) != RANGE_EXPR);
3310       return cep;
3311     }
3312   else
3313     {
3314       gcc_assert (TREE_CODE (index) == FIELD_DECL
3315 		  && (same_type_ignoring_top_level_qualifiers_p
3316 		      (DECL_CONTEXT (index), TREE_TYPE (ctor))));
3317 
3318       /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3319 	 Usually we meet initializers in that order, but it is
3320 	 possible for base types to be placed not in program
3321 	 order.  */
3322       tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3323       unsigned HOST_WIDE_INT idx = 0;
3324       constructor_elt *cep = NULL;
3325 
3326       /* Check if we're changing the active member of a union.  */
3327       if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
3328 	  && CONSTRUCTOR_ELT (ctor, 0)->index != index)
3329 	vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
3330       /* If the bit offset of INDEX is larger than that of the last
3331 	 constructor_elt, then we can just immediately append a new
3332 	 constructor_elt to the end of CTOR.  */
3333       else if (CONSTRUCTOR_NELTS (ctor)
3334 	       && tree_int_cst_compare (bit_position (index),
3335 					bit_position (CONSTRUCTOR_ELTS (ctor)
3336 						      ->last().index)) > 0)
3337 	{
3338 	  idx = CONSTRUCTOR_NELTS (ctor);
3339 	  goto insert;
3340 	}
3341 
3342       /* Otherwise, we need to iterate over CTOR to find or insert INDEX
3343 	 appropriately.  */
3344 
3345       for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
3346 	   idx++, fields = DECL_CHAIN (fields))
3347 	{
3348 	  if (index == cep->index)
3349 	    goto found;
3350 
3351 	  /* The field we're initializing must be on the field
3352 	     list.  Look to see if it is present before the
3353 	     field the current ELT initializes.  */
3354 	  for (; fields != cep->index; fields = DECL_CHAIN (fields))
3355 	    if (index == fields)
3356 	      goto insert;
3357 	}
3358       /* We fell off the end of the CONSTRUCTOR, so insert a new
3359 	 entry at the end.  */
3360 
3361     insert:
3362       {
3363 	constructor_elt ce = { index, NULL_TREE };
3364 
3365 	vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
3366 	cep = CONSTRUCTOR_ELT (ctor, idx);
3367       }
3368     found:;
3369 
3370       return cep;
3371     }
3372 }
3373 
3374 /* Under the control of CTX, issue a detailed diagnostic for
3375    an out-of-bounds subscript INDEX into the expression ARRAY.  */
3376 
3377 static void
diag_array_subscript(location_t loc,const constexpr_ctx * ctx,tree array,tree index)3378 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
3379 {
3380   if (!ctx->quiet)
3381     {
3382       tree arraytype = TREE_TYPE (array);
3383 
3384       /* Convert the unsigned array subscript to a signed integer to avoid
3385 	 printing huge numbers for small negative values.  */
3386       tree sidx = fold_convert (ssizetype, index);
3387       STRIP_ANY_LOCATION_WRAPPER (array);
3388       if (DECL_P (array))
3389 	{
3390 	  if (TYPE_DOMAIN (arraytype))
3391 	    error_at (loc, "array subscript value %qE is outside the bounds "
3392 		      "of array %qD of type %qT", sidx, array, arraytype);
3393 	  else
3394 	    error_at (loc, "nonzero array subscript %qE is used with array %qD of "
3395 		      "type %qT with unknown bounds", sidx, array, arraytype);
3396 	  inform (DECL_SOURCE_LOCATION (array), "declared here");
3397 	}
3398       else if (TYPE_DOMAIN (arraytype))
3399 	error_at (loc, "array subscript value %qE is outside the bounds "
3400 		  "of array type %qT", sidx, arraytype);
3401       else
3402 	error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
3403 		  "with unknown bounds", sidx, arraytype);
3404     }
3405 }
3406 
3407 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
3408    a VECTOR_TYPE).  */
3409 
3410 static tree
get_array_or_vector_nelts(const constexpr_ctx * ctx,tree type,bool * non_constant_p,bool * overflow_p)3411 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
3412 			   bool *non_constant_p, bool *overflow_p)
3413 {
3414   tree nelts;
3415   if (TREE_CODE (type) == ARRAY_TYPE)
3416     {
3417       if (TYPE_DOMAIN (type))
3418 	nelts = array_type_nelts_top (type);
3419       else
3420 	nelts = size_zero_node;
3421     }
3422   else if (VECTOR_TYPE_P (type))
3423     nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
3424   else
3425     gcc_unreachable ();
3426 
3427   /* For VLAs, the number of elements won't be an integer constant.  */
3428   nelts = cxx_eval_constant_expression (ctx, nelts, false,
3429 					non_constant_p, overflow_p);
3430   return nelts;
3431 }
3432 
3433 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
3434    STRING_CST STRING.  */
3435 
3436 static tree
extract_string_elt(tree string,unsigned chars_per_elt,unsigned index)3437 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
3438 {
3439   tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
3440   tree r;
3441 
3442   if (chars_per_elt == 1)
3443     r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
3444   else
3445     {
3446       const unsigned char *ptr
3447 	= ((const unsigned char *)TREE_STRING_POINTER (string)
3448 	   + index * chars_per_elt);
3449       r = native_interpret_expr (type, ptr, chars_per_elt);
3450     }
3451   return r;
3452 }
3453 
3454 /* Subroutine of cxx_eval_array_reference.  T is an ARRAY_REF; evaluate the
3455    subscript, diagnose any problems with it, and return the result.  */
3456 
3457 static tree
eval_and_check_array_index(const constexpr_ctx * ctx,tree t,bool allow_one_past,bool * non_constant_p,bool * overflow_p)3458 eval_and_check_array_index (const constexpr_ctx *ctx,
3459 			    tree t, bool allow_one_past,
3460 			    bool *non_constant_p, bool *overflow_p)
3461 {
3462   location_t loc = cp_expr_loc_or_input_loc (t);
3463   tree ary = TREE_OPERAND (t, 0);
3464   t = TREE_OPERAND (t, 1);
3465   tree index = cxx_eval_constant_expression (ctx, t, false,
3466 					     non_constant_p, overflow_p);
3467   VERIFY_CONSTANT (index);
3468 
3469   if (!tree_fits_shwi_p (index)
3470       || tree_int_cst_sgn (index) < 0)
3471     {
3472       diag_array_subscript (loc, ctx, ary, index);
3473       *non_constant_p = true;
3474       return t;
3475     }
3476 
3477   tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
3478 					  overflow_p);
3479   VERIFY_CONSTANT (nelts);
3480   if (allow_one_past
3481       ? !tree_int_cst_le (index, nelts)
3482       : !tree_int_cst_lt (index, nelts))
3483     {
3484       diag_array_subscript (loc, ctx, ary, index);
3485       *non_constant_p = true;
3486       return t;
3487     }
3488 
3489   return index;
3490 }
3491 
3492 /* Subroutine of cxx_eval_constant_expression.
3493    Attempt to reduce a reference to an array slot.  */
3494 
3495 static tree
cxx_eval_array_reference(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)3496 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
3497 			  bool lval,
3498 			  bool *non_constant_p, bool *overflow_p)
3499 {
3500   tree oldary = TREE_OPERAND (t, 0);
3501   tree ary = cxx_eval_constant_expression (ctx, oldary,
3502 					   lval,
3503 					   non_constant_p, overflow_p);
3504   if (*non_constant_p)
3505     return t;
3506   if (!lval
3507       && TREE_CODE (ary) == VIEW_CONVERT_EXPR
3508       && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
3509       && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
3510     ary = TREE_OPERAND (ary, 0);
3511 
3512   tree oldidx = TREE_OPERAND (t, 1);
3513   tree index = eval_and_check_array_index (ctx, t, lval,
3514 					   non_constant_p, overflow_p);
3515   if (*non_constant_p)
3516     return t;
3517 
3518   if (lval && ary == oldary && index == oldidx)
3519     return t;
3520   else if (lval)
3521     return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
3522 
3523   unsigned len = 0, elem_nchars = 1;
3524   tree elem_type = TREE_TYPE (TREE_TYPE (ary));
3525   if (TREE_CODE (ary) == CONSTRUCTOR)
3526     len = CONSTRUCTOR_NELTS (ary);
3527   else if (TREE_CODE (ary) == STRING_CST)
3528     {
3529       elem_nchars = (TYPE_PRECISION (elem_type)
3530 		     / TYPE_PRECISION (char_type_node));
3531       len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
3532     }
3533   else if (TREE_CODE (ary) == VECTOR_CST)
3534     /* We don't create variable-length VECTOR_CSTs.  */
3535     len = VECTOR_CST_NELTS (ary).to_constant ();
3536   else
3537     {
3538       /* We can't do anything with other tree codes, so use
3539 	 VERIFY_CONSTANT to complain and fail.  */
3540       VERIFY_CONSTANT (ary);
3541       gcc_unreachable ();
3542     }
3543 
3544   bool found;
3545   HOST_WIDE_INT i = 0;
3546   if (TREE_CODE (ary) == CONSTRUCTOR)
3547     {
3548       HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
3549       found = (ix >= 0);
3550       if (found)
3551 	i = ix;
3552     }
3553   else
3554     {
3555       i = tree_to_shwi (index);
3556       found = (i < len);
3557     }
3558 
3559   if (found)
3560     {
3561       tree r;
3562       if (TREE_CODE (ary) == CONSTRUCTOR)
3563 	r = (*CONSTRUCTOR_ELTS (ary))[i].value;
3564       else if (TREE_CODE (ary) == VECTOR_CST)
3565 	r = VECTOR_CST_ELT (ary, i);
3566       else
3567 	r = extract_string_elt (ary, elem_nchars, i);
3568 
3569       if (r)
3570 	/* Don't VERIFY_CONSTANT here.  */
3571 	return r;
3572 
3573       /* Otherwise the element doesn't have a value yet.  */
3574     }
3575 
3576   /* Not found.  */
3577 
3578   if (TREE_CODE (ary) == CONSTRUCTOR
3579       && CONSTRUCTOR_NO_CLEARING (ary))
3580     {
3581       /* 'ary' is part of the aggregate initializer we're currently
3582 	 building; if there's no initializer for this element yet,
3583 	 that's an error.  */
3584       if (!ctx->quiet)
3585 	error ("accessing uninitialized array element");
3586       *non_constant_p = true;
3587       return t;
3588     }
3589 
3590   /* If it's within the array bounds but doesn't have an explicit
3591      initializer, it's initialized from {}.  But use build_value_init
3592      directly for non-aggregates to avoid creating a garbage CONSTRUCTOR.  */
3593   tree val;
3594   constexpr_ctx new_ctx;
3595   if (CP_AGGREGATE_TYPE_P (elem_type))
3596     {
3597       tree empty_ctor = build_constructor (init_list_type_node, NULL);
3598       val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
3599       new_ctx = *ctx;
3600       new_ctx.object = t;
3601       new_ctx.ctor = build_constructor (elem_type, NULL);
3602       ctx = &new_ctx;
3603     }
3604   else
3605     val = build_value_init (elem_type, tf_warning_or_error);
3606   t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3607 				    overflow_p);
3608   if (CP_AGGREGATE_TYPE_P (elem_type) && t != ctx->ctor)
3609     free_constructor (ctx->ctor);
3610   return t;
3611 }
3612 
3613 /* Subroutine of cxx_eval_constant_expression.
3614    Attempt to reduce a field access of a value of class type.  */
3615 
3616 static tree
cxx_eval_component_reference(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)3617 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
3618 			      bool lval,
3619 			      bool *non_constant_p, bool *overflow_p)
3620 {
3621   unsigned HOST_WIDE_INT i;
3622   tree field;
3623   tree value;
3624   tree part = TREE_OPERAND (t, 1);
3625   tree orig_whole = TREE_OPERAND (t, 0);
3626   tree whole = cxx_eval_constant_expression (ctx, orig_whole,
3627 					     lval,
3628 					     non_constant_p, overflow_p);
3629   if (INDIRECT_REF_P (whole)
3630       && integer_zerop (TREE_OPERAND (whole, 0)))
3631     {
3632       if (!ctx->quiet)
3633 	error ("dereferencing a null pointer in %qE", orig_whole);
3634       *non_constant_p = true;
3635       return t;
3636     }
3637 
3638   if (TREE_CODE (whole) == PTRMEM_CST)
3639     whole = cplus_expand_constant (whole);
3640   if (whole == orig_whole)
3641     return t;
3642   if (lval)
3643     return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
3644 			whole, part, NULL_TREE);
3645   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
3646      CONSTRUCTOR.  */
3647   if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
3648     {
3649       if (!ctx->quiet)
3650 	error ("%qE is not a constant expression", orig_whole);
3651       *non_constant_p = true;
3652     }
3653   if (DECL_MUTABLE_P (part))
3654     {
3655       if (!ctx->quiet)
3656 	error ("mutable %qD is not usable in a constant expression", part);
3657       *non_constant_p = true;
3658     }
3659   if (*non_constant_p)
3660     return t;
3661   bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
3662   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
3663     {
3664       /* Use name match for PMF fields, as a variant will have a
3665 	 different FIELD_DECL with a different type.  */
3666       if (pmf ? DECL_NAME (field) == DECL_NAME (part)
3667 	  : field == part)
3668 	{
3669 	  if (value)
3670 	    {
3671 	      STRIP_ANY_LOCATION_WRAPPER (value);
3672 	      return value;
3673 	    }
3674 	  else
3675 	    /* We're in the middle of initializing it.  */
3676 	    break;
3677 	}
3678     }
3679   if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
3680       && CONSTRUCTOR_NELTS (whole) > 0)
3681     {
3682       /* DR 1188 says we don't have to deal with this.  */
3683       if (!ctx->quiet)
3684 	{
3685 	  constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
3686 	  if (cep->value == NULL_TREE)
3687 	    error ("accessing uninitialized member %qD", part);
3688 	  else
3689 	    error ("accessing %qD member instead of initialized %qD member in "
3690 		   "constant expression", part, cep->index);
3691 	}
3692       *non_constant_p = true;
3693       return t;
3694     }
3695 
3696   /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
3697      classes never get represented; throw together a value now.  */
3698   if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
3699     return build_constructor (TREE_TYPE (t), NULL);
3700 
3701   gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
3702 
3703   if (CONSTRUCTOR_NO_CLEARING (whole))
3704     {
3705       /* 'whole' is part of the aggregate initializer we're currently
3706 	 building; if there's no initializer for this member yet, that's an
3707 	 error.  */
3708       if (!ctx->quiet)
3709 	error ("accessing uninitialized member %qD", part);
3710       *non_constant_p = true;
3711       return t;
3712     }
3713 
3714   /* If there's no explicit init for this field, it's value-initialized.  */
3715   value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
3716   return cxx_eval_constant_expression (ctx, value,
3717 				       lval,
3718 				       non_constant_p, overflow_p);
3719 }
3720 
3721 /* Subroutine of cxx_eval_constant_expression.
3722    Attempt to reduce a field access of a value of class type that is
3723    expressed as a BIT_FIELD_REF.  */
3724 
3725 static tree
cxx_eval_bit_field_ref(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)3726 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
3727 			bool lval,
3728 			bool *non_constant_p, bool *overflow_p)
3729 {
3730   tree orig_whole = TREE_OPERAND (t, 0);
3731   tree retval, fldval, utype, mask;
3732   bool fld_seen = false;
3733   HOST_WIDE_INT istart, isize;
3734   tree whole = cxx_eval_constant_expression (ctx, orig_whole,
3735 					     lval,
3736 					     non_constant_p, overflow_p);
3737   tree start, field, value;
3738   unsigned HOST_WIDE_INT i;
3739 
3740   if (whole == orig_whole)
3741     return t;
3742   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
3743      CONSTRUCTOR.  */
3744   if (!*non_constant_p
3745       && TREE_CODE (whole) != VECTOR_CST
3746       && TREE_CODE (whole) != CONSTRUCTOR)
3747     {
3748       if (!ctx->quiet)
3749 	error ("%qE is not a constant expression", orig_whole);
3750       *non_constant_p = true;
3751     }
3752   if (*non_constant_p)
3753     return t;
3754 
3755   if (TREE_CODE (whole) == VECTOR_CST)
3756     return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
3757 			 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
3758 
3759   start = TREE_OPERAND (t, 2);
3760   istart = tree_to_shwi (start);
3761   isize = tree_to_shwi (TREE_OPERAND (t, 1));
3762   utype = TREE_TYPE (t);
3763   if (!TYPE_UNSIGNED (utype))
3764     utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
3765   retval = build_int_cst (utype, 0);
3766   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
3767     {
3768       tree bitpos = bit_position (field);
3769       STRIP_ANY_LOCATION_WRAPPER (value);
3770       if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
3771 	return value;
3772       if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
3773 	  && TREE_CODE (value) == INTEGER_CST
3774 	  && tree_fits_shwi_p (bitpos)
3775 	  && tree_fits_shwi_p (DECL_SIZE (field)))
3776 	{
3777 	  HOST_WIDE_INT bit = tree_to_shwi (bitpos);
3778 	  HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
3779 	  HOST_WIDE_INT shift;
3780 	  if (bit >= istart && bit + sz <= istart + isize)
3781 	    {
3782 	      fldval = fold_convert (utype, value);
3783 	      mask = build_int_cst_type (utype, -1);
3784 	      mask = fold_build2 (LSHIFT_EXPR, utype, mask,
3785 				  size_int (TYPE_PRECISION (utype) - sz));
3786 	      mask = fold_build2 (RSHIFT_EXPR, utype, mask,
3787 				  size_int (TYPE_PRECISION (utype) - sz));
3788 	      fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
3789 	      shift = bit - istart;
3790 	      if (BYTES_BIG_ENDIAN)
3791 		shift = TYPE_PRECISION (utype) - shift - sz;
3792 	      fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
3793 				    size_int (shift));
3794 	      retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
3795 	      fld_seen = true;
3796 	    }
3797 	}
3798     }
3799   if (fld_seen)
3800     return fold_convert (TREE_TYPE (t), retval);
3801   gcc_unreachable ();
3802   return error_mark_node;
3803 }
3804 
3805 /* Subroutine of cxx_eval_constant_expression.
3806    Evaluate a short-circuited logical expression T in the context
3807    of a given constexpr CALL.  BAILOUT_VALUE is the value for
3808    early return.  CONTINUE_VALUE is used here purely for
3809    sanity check purposes.  */
3810 
3811 static tree
cxx_eval_logical_expression(const constexpr_ctx * ctx,tree t,tree bailout_value,tree continue_value,bool lval,bool * non_constant_p,bool * overflow_p)3812 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
3813                              tree bailout_value, tree continue_value,
3814 			     bool lval,
3815 			     bool *non_constant_p, bool *overflow_p)
3816 {
3817   tree r;
3818   tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3819 					   lval,
3820 					   non_constant_p, overflow_p);
3821   VERIFY_CONSTANT (lhs);
3822   if (tree_int_cst_equal (lhs, bailout_value))
3823     return lhs;
3824   gcc_assert (tree_int_cst_equal (lhs, continue_value));
3825   r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3826 				    lval, non_constant_p,
3827 				    overflow_p);
3828   VERIFY_CONSTANT (r);
3829   return r;
3830 }
3831 
3832 /* REF is a COMPONENT_REF designating a particular field.  V is a vector of
3833    CONSTRUCTOR elements to initialize (part of) an object containing that
3834    field.  Return a pointer to the constructor_elt corresponding to the
3835    initialization of the field.  */
3836 
3837 static constructor_elt *
base_field_constructor_elt(vec<constructor_elt,va_gc> * v,tree ref)3838 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
3839 {
3840   tree aggr = TREE_OPERAND (ref, 0);
3841   tree field = TREE_OPERAND (ref, 1);
3842   HOST_WIDE_INT i;
3843   constructor_elt *ce;
3844 
3845   gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
3846 
3847   if (TREE_CODE (aggr) == COMPONENT_REF)
3848     {
3849       constructor_elt *base_ce
3850 	= base_field_constructor_elt (v, aggr);
3851       v = CONSTRUCTOR_ELTS (base_ce->value);
3852     }
3853 
3854   for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
3855     if (ce->index == field)
3856       return ce;
3857 
3858   gcc_unreachable ();
3859   return NULL;
3860 }
3861 
3862 /* Some of the expressions fed to the constexpr mechanism are calls to
3863    constructors, which have type void.  In that case, return the type being
3864    initialized by the constructor.  */
3865 
3866 static tree
initialized_type(tree t)3867 initialized_type (tree t)
3868 {
3869   if (TYPE_P (t))
3870     return t;
3871   tree type = TREE_TYPE (t);
3872   if (TREE_CODE (t) == CALL_EXPR)
3873     {
3874       /* A constructor call has void type, so we need to look deeper.  */
3875       tree fn = get_function_named_in_call (t);
3876       if (fn && TREE_CODE (fn) == FUNCTION_DECL
3877 	  && DECL_CXX_CONSTRUCTOR_P (fn))
3878 	type = DECL_CONTEXT (fn);
3879     }
3880   else if (TREE_CODE (t) == COMPOUND_EXPR)
3881     return initialized_type (TREE_OPERAND (t, 1));
3882   else if (TREE_CODE (t) == AGGR_INIT_EXPR)
3883     type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
3884   return cv_unqualified (type);
3885 }
3886 
3887 /* We're about to initialize element INDEX of an array or class from VALUE.
3888    Set up NEW_CTX appropriately by adjusting .object to refer to the
3889    subobject and creating a new CONSTRUCTOR if the element is itself
3890    a class or array.  */
3891 
3892 static void
init_subob_ctx(const constexpr_ctx * ctx,constexpr_ctx & new_ctx,tree index,tree & value)3893 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
3894 	       tree index, tree &value)
3895 {
3896   new_ctx = *ctx;
3897 
3898   if (index && TREE_CODE (index) != INTEGER_CST
3899       && TREE_CODE (index) != FIELD_DECL
3900       && TREE_CODE (index) != RANGE_EXPR)
3901     /* This won't have an element in the new CONSTRUCTOR.  */
3902     return;
3903 
3904   tree type = initialized_type (value);
3905   if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
3906     /* A non-aggregate member doesn't get its own CONSTRUCTOR.  */
3907     return;
3908 
3909   /* The sub-aggregate initializer might contain a placeholder;
3910      update object to refer to the subobject and ctor to refer to
3911      the (newly created) sub-initializer.  */
3912   if (ctx->object)
3913     {
3914       if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
3915 	/* There's no well-defined subobject for this index.  */
3916 	new_ctx.object = NULL_TREE;
3917       else
3918 	new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
3919     }
3920   tree elt = build_constructor (type, NULL);
3921   CONSTRUCTOR_NO_CLEARING (elt) = true;
3922   new_ctx.ctor = elt;
3923 
3924   if (TREE_CODE (value) == TARGET_EXPR)
3925     /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR.  */
3926     value = TARGET_EXPR_INITIAL (value);
3927 }
3928 
3929 /* We're about to process an initializer for a class or array TYPE.  Make
3930    sure that CTX is set up appropriately.  */
3931 
3932 static void
verify_ctor_sanity(const constexpr_ctx * ctx,tree type)3933 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
3934 {
3935   /* We don't bother building a ctor for an empty base subobject.  */
3936   if (is_empty_class (type))
3937     return;
3938 
3939   /* We're in the middle of an initializer that might involve placeholders;
3940      our caller should have created a CONSTRUCTOR for us to put the
3941      initializer into.  We will either return that constructor or T.  */
3942   gcc_assert (ctx->ctor);
3943   gcc_assert (same_type_ignoring_top_level_qualifiers_p
3944 	      (type, TREE_TYPE (ctx->ctor)));
3945   /* We used to check that ctx->ctor was empty, but that isn't the case when
3946      the object is zero-initialized before calling the constructor.  */
3947   if (ctx->object)
3948     {
3949       tree otype = TREE_TYPE (ctx->object);
3950       gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
3951 		  /* Handle flexible array members.  */
3952 		  || (TREE_CODE (otype) == ARRAY_TYPE
3953 		      && TYPE_DOMAIN (otype) == NULL_TREE
3954 		      && TREE_CODE (type) == ARRAY_TYPE
3955 		      && (same_type_ignoring_top_level_qualifiers_p
3956 			  (TREE_TYPE (type), TREE_TYPE (otype)))));
3957     }
3958   gcc_assert (!ctx->object || !DECL_P (ctx->object)
3959 	      || *(ctx->global->values.get (ctx->object)) == ctx->ctor);
3960 }
3961 
3962 /* Subroutine of cxx_eval_constant_expression.
3963    The expression tree T denotes a C-style array or a C-style
3964    aggregate.  Reduce it to a constant expression.  */
3965 
3966 static tree
cxx_eval_bare_aggregate(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)3967 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
3968 			 bool lval,
3969 			 bool *non_constant_p, bool *overflow_p)
3970 {
3971   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
3972   bool changed = false;
3973   gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
3974   tree type = TREE_TYPE (t);
3975 
3976   constexpr_ctx new_ctx;
3977   if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
3978     {
3979       /* We don't really need the ctx->ctor business for a PMF or
3980 	 vector, but it's simpler to use the same code.  */
3981       new_ctx = *ctx;
3982       new_ctx.ctor = build_constructor (type, NULL);
3983       new_ctx.object = NULL_TREE;
3984       ctx = &new_ctx;
3985     };
3986   verify_ctor_sanity (ctx, type);
3987   vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
3988   vec_alloc (*p, vec_safe_length (v));
3989 
3990   if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
3991     CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
3992 
3993   unsigned i;
3994   tree index, value;
3995   bool constant_p = true;
3996   bool side_effects_p = false;
3997   FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
3998     {
3999       tree orig_value = value;
4000       init_subob_ctx (ctx, new_ctx, index, value);
4001       int pos_hint = -1;
4002       if (new_ctx.ctor != ctx->ctor)
4003 	{
4004 	  /* If we built a new CONSTRUCTOR, attach it now so that other
4005 	     initializers can refer to it.  */
4006 	  constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
4007 	  cep->value = new_ctx.ctor;
4008 	  pos_hint = cep - (*p)->begin();
4009 	}
4010       else if (TREE_CODE (type) == UNION_TYPE)
4011 	/* Otherwise if we're constructing a non-aggregate union member, set
4012 	   the active union member now so that we can later detect and diagnose
4013 	   if its initializer attempts to activate another member.  */
4014 	get_or_insert_ctor_field (ctx->ctor, index);
4015       tree elt = cxx_eval_constant_expression (&new_ctx, value,
4016 					       lval,
4017 					       non_constant_p, overflow_p);
4018       /* Don't VERIFY_CONSTANT here.  */
4019       if (ctx->quiet && *non_constant_p)
4020 	break;
4021       if (elt != orig_value)
4022 	changed = true;
4023 
4024       if (!TREE_CONSTANT (elt))
4025 	constant_p = false;
4026       if (TREE_SIDE_EFFECTS (elt))
4027 	side_effects_p = true;
4028       if (index && TREE_CODE (index) == COMPONENT_REF)
4029 	{
4030 	  /* This is an initialization of a vfield inside a base
4031 	     subaggregate that we already initialized; push this
4032 	     initialization into the previous initialization.  */
4033 	  constructor_elt *inner = base_field_constructor_elt (*p, index);
4034 	  inner->value = elt;
4035 	  changed = true;
4036 	}
4037       else if (index
4038 	       && (TREE_CODE (index) == NOP_EXPR
4039 		   || TREE_CODE (index) == POINTER_PLUS_EXPR))
4040 	{
4041 	  /* This is an initializer for an empty base; now that we've
4042 	     checked that it's constant, we can ignore it.  */
4043 	  gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
4044 	  changed = true;
4045 	}
4046       else
4047 	{
4048 	  if (TREE_CODE (type) == UNION_TYPE
4049 	      && (*p)->last().index != index)
4050 	    /* The initializer erroneously changed the active union member that
4051 	       we're initializing.  */
4052 	    gcc_assert (*non_constant_p);
4053 	  else
4054 	    {
4055 	      /* The initializer might have mutated the underlying CONSTRUCTOR,
4056 		 so recompute the location of the target constructer_elt.  */
4057 	      constructor_elt *cep
4058 		= get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
4059 	      cep->value = elt;
4060 	    }
4061 
4062 	  /* Adding or replacing an element might change the ctor's flags.  */
4063 	  TREE_CONSTANT (ctx->ctor) = constant_p;
4064 	  TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
4065 	}
4066     }
4067   if (*non_constant_p || !changed)
4068     return t;
4069   t = ctx->ctor;
4070   /* We're done building this CONSTRUCTOR, so now we can interpret an
4071      element without an explicit initializer as value-initialized.  */
4072   CONSTRUCTOR_NO_CLEARING (t) = false;
4073   TREE_CONSTANT (t) = constant_p;
4074   TREE_SIDE_EFFECTS (t) = side_effects_p;
4075   if (VECTOR_TYPE_P (type))
4076     t = fold (t);
4077   return t;
4078 }
4079 
4080 /* Subroutine of cxx_eval_constant_expression.
4081    The expression tree T is a VEC_INIT_EXPR which denotes the desired
4082    initialization of a non-static data member of array type.  Reduce it to a
4083    CONSTRUCTOR.
4084 
4085    Note that apart from value-initialization (when VALUE_INIT is true),
4086    this is only intended to support value-initialization and the
4087    initializations done by defaulted constructors for classes with
4088    non-static data members of array type.  In this case, VEC_INIT_EXPR_INIT
4089    will either be NULL_TREE for the default constructor, or a COMPONENT_REF
4090    for the copy/move constructor.  */
4091 
4092 static tree
cxx_eval_vec_init_1(const constexpr_ctx * ctx,tree atype,tree init,bool value_init,bool lval,bool * non_constant_p,bool * overflow_p)4093 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
4094 		     bool value_init, bool lval,
4095 		     bool *non_constant_p, bool *overflow_p)
4096 {
4097   tree elttype = TREE_TYPE (atype);
4098   verify_ctor_sanity (ctx, atype);
4099   vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
4100   bool pre_init = false;
4101   unsigned HOST_WIDE_INT i;
4102   tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
4103 
4104   if (init && TREE_CODE (init) == CONSTRUCTOR)
4105     return cxx_eval_bare_aggregate (ctx, init, lval,
4106 				    non_constant_p, overflow_p);
4107 
4108   /* For the default constructor, build up a call to the default
4109      constructor of the element type.  We only need to handle class types
4110      here, as for a constructor to be constexpr, all members must be
4111      initialized, which for a defaulted default constructor means they must
4112      be of a class type with a constexpr default constructor.  */
4113   if (TREE_CODE (elttype) == ARRAY_TYPE)
4114     /* We only do this at the lowest level.  */;
4115   else if (value_init)
4116     {
4117       init = build_value_init (elttype, complain);
4118       pre_init = true;
4119     }
4120   else if (!init)
4121     {
4122       releasing_vec argvec;
4123       init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
4124 					&argvec, elttype, LOOKUP_NORMAL,
4125 					complain);
4126       init = build_aggr_init_expr (elttype, init);
4127       pre_init = true;
4128     }
4129 
4130   bool zeroed_out = false;
4131   if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
4132     {
4133       /* We're initializing an array object that had been zero-initialized
4134 	 earlier.  Truncate ctx->ctor, and propagate its zeroed state by
4135 	 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
4136 	 initializers we append to it.  */
4137       gcc_checking_assert (initializer_zerop (ctx->ctor));
4138       zeroed_out = true;
4139       vec_safe_truncate (*p, 0);
4140     }
4141 
4142   tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
4143 					  overflow_p);
4144   unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
4145   for (i = 0; i < max; ++i)
4146     {
4147       tree idx = build_int_cst (size_type_node, i);
4148       tree eltinit;
4149       bool reuse = false;
4150       constexpr_ctx new_ctx;
4151       init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
4152       if (new_ctx.ctor != ctx->ctor)
4153 	{
4154 	  if (zeroed_out)
4155 	    CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
4156 	  CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
4157 	}
4158       if (TREE_CODE (elttype) == ARRAY_TYPE)
4159 	{
4160 	  /* A multidimensional array; recurse.  */
4161 	  if (value_init || init == NULL_TREE)
4162 	    {
4163 	      eltinit = NULL_TREE;
4164 	      reuse = i == 0;
4165 	    }
4166 	  else
4167 	    eltinit = cp_build_array_ref (input_location, init, idx, complain);
4168 	  eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
4169 					 lval,
4170 					 non_constant_p, overflow_p);
4171 	}
4172       else if (pre_init)
4173 	{
4174 	  /* Initializing an element using value or default initialization
4175 	     we just pre-built above.  */
4176 	  if (init == void_node)
4177 	    /* Trivial default-init, don't do anything to the CONSTRUCTOR.  */
4178 	    return ctx->ctor;
4179 	  eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
4180 						  non_constant_p, overflow_p);
4181 	  reuse = i == 0;
4182 	}
4183       else
4184 	{
4185 	  /* Copying an element.  */
4186 	  gcc_assert (same_type_ignoring_top_level_qualifiers_p
4187 		      (atype, TREE_TYPE (init)));
4188 	  eltinit = cp_build_array_ref (input_location, init, idx, complain);
4189 	  if (!lvalue_p (init))
4190 	    eltinit = move (eltinit);
4191 	  eltinit = force_rvalue (eltinit, complain);
4192 	  eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
4193 						  non_constant_p, overflow_p);
4194 	}
4195       if (*non_constant_p)
4196 	break;
4197       if (new_ctx.ctor != ctx->ctor)
4198 	{
4199 	  /* We appended this element above; update the value.  */
4200 	  gcc_assert ((*p)->last().index == idx);
4201 	  (*p)->last().value = eltinit;
4202 	}
4203       else
4204 	CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
4205       /* Reuse the result of cxx_eval_constant_expression call
4206 	 from the first iteration to all others if it is a constant
4207 	 initializer that doesn't require relocations.  */
4208       if (reuse
4209 	  && max > 1
4210 	  && (eltinit == NULL_TREE
4211 	      || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
4212 		  == null_pointer_node)))
4213 	{
4214 	  if (new_ctx.ctor != ctx->ctor)
4215 	    eltinit = new_ctx.ctor;
4216 	  tree range = build2 (RANGE_EXPR, size_type_node,
4217 			       build_int_cst (size_type_node, 1),
4218 			       build_int_cst (size_type_node, max - 1));
4219 	  CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
4220 	  break;
4221 	}
4222       else if (i == 0)
4223 	vec_safe_reserve (*p, max);
4224     }
4225 
4226   if (!*non_constant_p)
4227     {
4228       init = ctx->ctor;
4229       CONSTRUCTOR_NO_CLEARING (init) = false;
4230     }
4231   return init;
4232 }
4233 
4234 static tree
cxx_eval_vec_init(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)4235 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
4236 		   bool lval,
4237 		   bool *non_constant_p, bool *overflow_p)
4238 {
4239   tree atype = TREE_TYPE (t);
4240   tree init = VEC_INIT_EXPR_INIT (t);
4241   tree r = cxx_eval_vec_init_1 (ctx, atype, init,
4242 				VEC_INIT_EXPR_VALUE_INIT (t),
4243 				lval, non_constant_p, overflow_p);
4244   if (*non_constant_p)
4245     return t;
4246   else
4247     return r;
4248 }
4249 
4250 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
4251    where the desired type is an array of unknown bounds because the variable
4252    has had its bounds deduced since the wrapping expression was created.  */
4253 
4254 static bool
same_type_ignoring_tlq_and_bounds_p(tree type1,tree type2)4255 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
4256 {
4257   while (TREE_CODE (type1) == ARRAY_TYPE
4258 	 && TREE_CODE (type2) == ARRAY_TYPE
4259 	 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
4260     {
4261       type1 = TREE_TYPE (type1);
4262       type2 = TREE_TYPE (type2);
4263     }
4264   return same_type_ignoring_top_level_qualifiers_p (type1, type2);
4265 }
4266 
4267 /* Try to determine the currently active union member for an expression
4268    with UNION_TYPE.  If it can be determined, return the FIELD_DECL,
4269    otherwise return NULL_TREE.  */
4270 
4271 static tree
cxx_union_active_member(const constexpr_ctx * ctx,tree t)4272 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
4273 {
4274   constexpr_ctx new_ctx = *ctx;
4275   new_ctx.quiet = true;
4276   bool non_constant_p = false, overflow_p = false;
4277   tree ctor = cxx_eval_constant_expression (&new_ctx, t, false,
4278 					    &non_constant_p,
4279 					    &overflow_p);
4280   if (TREE_CODE (ctor) == CONSTRUCTOR
4281       && CONSTRUCTOR_NELTS (ctor) == 1
4282       && CONSTRUCTOR_ELT (ctor, 0)->index
4283       && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
4284     return CONSTRUCTOR_ELT (ctor, 0)->index;
4285   return NULL_TREE;
4286 }
4287 
4288 /* Helper function for cxx_fold_indirect_ref_1, called recursively.  */
4289 
4290 static tree
cxx_fold_indirect_ref_1(const constexpr_ctx * ctx,location_t loc,tree type,tree op,unsigned HOST_WIDE_INT off,bool * empty_base)4291 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
4292 			 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
4293 {
4294   tree optype = TREE_TYPE (op);
4295   unsigned HOST_WIDE_INT const_nunits;
4296   if (off == 0)
4297     {
4298       if (similar_type_p (optype, type))
4299 	return op;
4300       /* Also handle conversion to an empty base class, which
4301 	 is represented with a NOP_EXPR.  */
4302       /* *(foo *)&complexfoo => __real__ complexfoo */
4303       else if (TREE_CODE (optype) == COMPLEX_TYPE
4304 	       && similar_type_p (type, TREE_TYPE (optype)))
4305 	return build1_loc (loc, REALPART_EXPR, type, op);
4306     }
4307   /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
4308   else if (TREE_CODE (optype) == COMPLEX_TYPE
4309 	   && similar_type_p (type, TREE_TYPE (optype))
4310 	   && tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
4311     return build1_loc (loc, IMAGPART_EXPR, type, op);
4312   if (is_empty_class (type)
4313       && CLASS_TYPE_P (optype)
4314       && DERIVED_FROM_P (type, optype))
4315     {
4316       *empty_base = true;
4317       return op;
4318     }
4319   /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
4320   else if (VECTOR_TYPE_P (optype)
4321 	   && similar_type_p (type, TREE_TYPE (optype))
4322 	   && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
4323     {
4324       unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
4325       unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
4326       if (off < max_offset && off % part_width == 0)
4327 	{
4328 	  tree index = bitsize_int (off * BITS_PER_UNIT);
4329 	  return build3_loc (loc, BIT_FIELD_REF, type, op,
4330 			     TYPE_SIZE (type), index);
4331 	}
4332     }
4333   /* ((foo *)&fooarray)[x] => fooarray[x] */
4334   else if (TREE_CODE (optype) == ARRAY_TYPE
4335 	   && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
4336 	   && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
4337     {
4338       tree type_domain = TYPE_DOMAIN (optype);
4339       tree min_val = size_zero_node;
4340       if (type_domain && TYPE_MIN_VALUE (type_domain))
4341 	min_val = TYPE_MIN_VALUE (type_domain);
4342       unsigned HOST_WIDE_INT el_sz
4343 	= tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
4344       unsigned HOST_WIDE_INT idx = off / el_sz;
4345       unsigned HOST_WIDE_INT rem = off % el_sz;
4346       if (tree_fits_uhwi_p (min_val))
4347 	{
4348 	  tree index = size_int (idx + tree_to_uhwi (min_val));
4349 	  op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
4350 			   NULL_TREE, NULL_TREE);
4351 	  return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
4352 					  empty_base);
4353 	}
4354     }
4355   /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
4356   else if (TREE_CODE (optype) == RECORD_TYPE
4357 	   || TREE_CODE (optype) == UNION_TYPE)
4358     {
4359       if (TREE_CODE (optype) == UNION_TYPE)
4360 	/* For unions prefer the currently active member.  */
4361 	if (tree field = cxx_union_active_member (ctx, op))
4362 	  {
4363 	    unsigned HOST_WIDE_INT el_sz
4364 	      = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
4365 	    if (off < el_sz)
4366 	      {
4367 		tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
4368 				   op, field, NULL_TREE);
4369 		if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
4370 							off, empty_base))
4371 		  return ret;
4372 	      }
4373 	  }
4374       for (tree field = TYPE_FIELDS (optype);
4375 	   field; field = DECL_CHAIN (field))
4376 	if (TREE_CODE (field) == FIELD_DECL
4377 	    && TREE_TYPE (field) != error_mark_node
4378 	    && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
4379 	  {
4380 	    tree pos = byte_position (field);
4381 	    if (!tree_fits_uhwi_p (pos))
4382 	      continue;
4383 	    unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
4384 	    unsigned HOST_WIDE_INT el_sz
4385 	      = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
4386 	    if (upos <= off && off < upos + el_sz)
4387 	      {
4388 		tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
4389 				   op, field, NULL_TREE);
4390 		if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
4391 							off - upos,
4392 							empty_base))
4393 		  return ret;
4394 	      }
4395 	  }
4396     }
4397 
4398   return NULL_TREE;
4399 }
4400 
4401 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
4402    match.  We want to be less strict for simple *& folding; if we have a
4403    non-const temporary that we access through a const pointer, that should
4404    work.  We handle this here rather than change fold_indirect_ref_1
4405    because we're dealing with things like ADDR_EXPR of INTEGER_CST which
4406    don't really make sense outside of constant expression evaluation.  Also
4407    we want to allow folding to COMPONENT_REF, which could cause trouble
4408    with TBAA in fold_indirect_ref_1.  */
4409 
4410 static tree
cxx_fold_indirect_ref(const constexpr_ctx * ctx,location_t loc,tree type,tree op0,bool * empty_base)4411 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
4412 		       tree op0, bool *empty_base)
4413 {
4414   tree sub = op0;
4415   tree subtype;
4416   poly_uint64 const_op01;
4417 
4418   /* STRIP_NOPS, but stop if REINTERPRET_CAST_P.  */
4419   while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
4420 	 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
4421     {
4422       if (TREE_CODE (sub) == NOP_EXPR
4423 	  && REINTERPRET_CAST_P (sub))
4424 	return NULL_TREE;
4425       sub = TREE_OPERAND (sub, 0);
4426     }
4427 
4428   subtype = TREE_TYPE (sub);
4429   if (!INDIRECT_TYPE_P (subtype))
4430     return NULL_TREE;
4431 
4432   if (TREE_CODE (sub) == ADDR_EXPR)
4433     {
4434       tree op = TREE_OPERAND (sub, 0);
4435       tree optype = TREE_TYPE (op);
4436 
4437       /* *&CONST_DECL -> to the value of the const decl.  */
4438       if (TREE_CODE (op) == CONST_DECL)
4439 	return DECL_INITIAL (op);
4440       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
4441       if (similar_type_p (optype, type))
4442 	{
4443 	  tree fop = fold_read_from_constant_string (op);
4444 	  if (fop)
4445 	    return fop;
4446 	  else
4447 	    return op;
4448 	}
4449       else
4450 	return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
4451     }
4452   else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
4453 	   && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
4454     {
4455       tree op00 = TREE_OPERAND (sub, 0);
4456       tree op01 = TREE_OPERAND (sub, 1);
4457 
4458       STRIP_NOPS (op00);
4459       if (TREE_CODE (op00) == ADDR_EXPR)
4460 	return cxx_fold_indirect_ref_1 (ctx, loc, type, TREE_OPERAND (op00, 0),
4461 					tree_to_uhwi (op01), empty_base);
4462     }
4463   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
4464   else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
4465 	   && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
4466     {
4467       tree type_domain;
4468       tree min_val = size_zero_node;
4469       tree newsub
4470 	= cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
4471       if (newsub)
4472 	sub = newsub;
4473       else
4474 	sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
4475       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
4476       if (type_domain && TYPE_MIN_VALUE (type_domain))
4477 	min_val = TYPE_MIN_VALUE (type_domain);
4478       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
4479 			 NULL_TREE);
4480     }
4481 
4482   return NULL_TREE;
4483 }
4484 
4485 static tree
cxx_eval_indirect_ref(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)4486 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
4487 		       bool lval,
4488 		       bool *non_constant_p, bool *overflow_p)
4489 {
4490   tree orig_op0 = TREE_OPERAND (t, 0);
4491   bool empty_base = false;
4492 
4493   /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
4494      operand is an integer-zero.  Otherwise reject the MEM_REF for now.  */
4495 
4496   if (TREE_CODE (t) == MEM_REF
4497       && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
4498     {
4499       gcc_assert (ctx->quiet);
4500       *non_constant_p = true;
4501       return t;
4502     }
4503 
4504   /* First try to simplify it directly.  */
4505   tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4506 				  orig_op0, &empty_base);
4507   if (!r)
4508     {
4509       /* If that didn't work, evaluate the operand first.  */
4510       tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
4511 					       /*lval*/false, non_constant_p,
4512 					       overflow_p);
4513       /* Don't VERIFY_CONSTANT here.  */
4514       if (*non_constant_p)
4515 	return t;
4516 
4517       if (!lval && integer_zerop (op0))
4518 	{
4519 	  if (!ctx->quiet)
4520 	    error ("dereferencing a null pointer");
4521 	  *non_constant_p = true;
4522 	  return t;
4523 	}
4524 
4525       r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
4526 				 &empty_base);
4527       if (r == NULL_TREE)
4528 	{
4529 	  /* We couldn't fold to a constant value.  Make sure it's not
4530 	     something we should have been able to fold.  */
4531 	  tree sub = op0;
4532 	  STRIP_NOPS (sub);
4533 	  if (TREE_CODE (sub) == ADDR_EXPR)
4534 	    {
4535 	      gcc_assert (!similar_type_p
4536 			  (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
4537 	      /* DR 1188 says we don't have to deal with this.  */
4538 	      if (!ctx->quiet)
4539 		error_at (cp_expr_loc_or_input_loc (t),
4540 			  "accessing value of %qE through a %qT glvalue in a "
4541 			  "constant expression", build_fold_indirect_ref (sub),
4542 			  TREE_TYPE (t));
4543 	      *non_constant_p = true;
4544 	      return t;
4545 	    }
4546 
4547 	  if (lval && op0 != orig_op0)
4548 	    return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
4549 	  if (!lval)
4550 	    VERIFY_CONSTANT (t);
4551 	  return t;
4552 	}
4553     }
4554 
4555   r = cxx_eval_constant_expression (ctx, r,
4556 				    lval, non_constant_p, overflow_p);
4557   if (*non_constant_p)
4558     return t;
4559 
4560   /* If we're pulling out the value of an empty base, just return an empty
4561      CONSTRUCTOR.  */
4562   if (empty_base && !lval)
4563     {
4564       r = build_constructor (TREE_TYPE (t), NULL);
4565       TREE_CONSTANT (r) = true;
4566     }
4567 
4568   return r;
4569 }
4570 
4571 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
4572    Shared between potential_constant_expression and
4573    cxx_eval_constant_expression.  */
4574 
4575 static void
non_const_var_error(location_t loc,tree r)4576 non_const_var_error (location_t loc, tree r)
4577 {
4578   auto_diagnostic_group d;
4579   tree type = TREE_TYPE (r);
4580   if (DECL_NAME (r) == heap_uninit_identifier
4581       || DECL_NAME (r) == heap_identifier)
4582     {
4583       error_at (loc, "the content of uninitialized storage is not usable "
4584 		"in a constant expression");
4585       inform (DECL_SOURCE_LOCATION (r), "allocated here");
4586       return;
4587     }
4588   if (DECL_NAME (r) == heap_deleted_identifier)
4589     {
4590       error_at (loc, "use of allocated storage after deallocation in a "
4591 		"constant expression");
4592       inform (DECL_SOURCE_LOCATION (r), "allocated here");
4593       return;
4594     }
4595   error_at (loc, "the value of %qD is not usable in a constant "
4596 	    "expression", r);
4597   /* Avoid error cascade.  */
4598   if (DECL_INITIAL (r) == error_mark_node)
4599     return;
4600   if (DECL_DECLARED_CONSTEXPR_P (r))
4601     inform (DECL_SOURCE_LOCATION (r),
4602 	    "%qD used in its own initializer", r);
4603   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4604     {
4605       if (!CP_TYPE_CONST_P (type))
4606 	inform (DECL_SOURCE_LOCATION (r),
4607 		"%q#D is not const", r);
4608       else if (CP_TYPE_VOLATILE_P (type))
4609 	inform (DECL_SOURCE_LOCATION (r),
4610 		"%q#D is volatile", r);
4611       else if (!DECL_INITIAL (r)
4612 	       || !TREE_CONSTANT (DECL_INITIAL (r))
4613 	       || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
4614 	inform (DECL_SOURCE_LOCATION (r),
4615 		"%qD was not initialized with a constant "
4616 		"expression", r);
4617       else
4618 	gcc_unreachable ();
4619     }
4620   else if (TYPE_REF_P (type))
4621     inform (DECL_SOURCE_LOCATION (r),
4622 	    "%qD was not initialized with a constant "
4623 	    "expression", r);
4624   else
4625     {
4626       if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
4627 	inform (DECL_SOURCE_LOCATION (r),
4628 		"%qD was not declared %<constexpr%>", r);
4629       else
4630 	inform (DECL_SOURCE_LOCATION (r),
4631 		"%qD does not have integral or enumeration type",
4632 		r);
4633     }
4634 }
4635 
4636 /* Subroutine of cxx_eval_constant_expression.
4637    Like cxx_eval_unary_expression, except for trinary expressions.  */
4638 
4639 static tree
cxx_eval_trinary_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)4640 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
4641 			     bool lval,
4642 			     bool *non_constant_p, bool *overflow_p)
4643 {
4644   int i;
4645   tree args[3];
4646   tree val;
4647 
4648   for (i = 0; i < 3; i++)
4649     {
4650       args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
4651 					      lval,
4652 					      non_constant_p, overflow_p);
4653       VERIFY_CONSTANT (args[i]);
4654     }
4655 
4656   val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
4657 			  args[0], args[1], args[2]);
4658   if (val == NULL_TREE)
4659     return t;
4660   VERIFY_CONSTANT (val);
4661   return val;
4662 }
4663 
4664 /* True if T was declared in a function declared to be constexpr, and
4665    therefore potentially constant in C++14.  */
4666 
4667 bool
var_in_constexpr_fn(tree t)4668 var_in_constexpr_fn (tree t)
4669 {
4670   tree ctx = DECL_CONTEXT (t);
4671   return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
4672 	  && DECL_DECLARED_CONSTEXPR_P (ctx));
4673 }
4674 
4675 /* True if T was declared in a function that might be constexpr: either a
4676    function that was declared constexpr, or a C++17 lambda op().  */
4677 
4678 bool
var_in_maybe_constexpr_fn(tree t)4679 var_in_maybe_constexpr_fn (tree t)
4680 {
4681   if (cxx_dialect >= cxx17
4682       && DECL_FUNCTION_SCOPE_P (t)
4683       && LAMBDA_FUNCTION_P (DECL_CONTEXT (t)))
4684     return true;
4685   return var_in_constexpr_fn (t);
4686 }
4687 
4688 /* We're assigning INIT to TARGET.  In do_build_copy_constructor and
4689    build_over_call we implement trivial copy of a class with tail padding using
4690    assignment of character arrays, which is valid in normal code, but not in
4691    constexpr evaluation.  We don't need to worry about clobbering tail padding
4692    in constexpr evaluation, so strip the type punning.  */
4693 
4694 static void
maybe_simplify_trivial_copy(tree & target,tree & init)4695 maybe_simplify_trivial_copy (tree &target, tree &init)
4696 {
4697   if (TREE_CODE (target) == MEM_REF
4698       && TREE_CODE (init) == MEM_REF
4699       && TREE_TYPE (target) == TREE_TYPE (init)
4700       && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
4701       && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
4702     {
4703       target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
4704       init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
4705     }
4706 }
4707 
4708 /* Returns true if REF, which is a COMPONENT_REF, has any fields
4709    of constant type.  This does not check for 'mutable', so the
4710    caller is expected to be mindful of that.  */
4711 
4712 static bool
cref_has_const_field(tree ref)4713 cref_has_const_field (tree ref)
4714 {
4715   while (TREE_CODE (ref) == COMPONENT_REF)
4716     {
4717       if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
4718        return true;
4719       ref = TREE_OPERAND (ref, 0);
4720     }
4721   return false;
4722 }
4723 
4724 /* Return true if we are modifying something that is const during constant
4725    expression evaluation.  CODE is the code of the statement, OBJ is the
4726    object in question, MUTABLE_P is true if one of the subobjects were
4727    declared mutable.  */
4728 
4729 static bool
modifying_const_object_p(tree_code code,tree obj,bool mutable_p)4730 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
4731 {
4732   /* If this is initialization, there's no problem.  */
4733   if (code != MODIFY_EXPR)
4734     return false;
4735 
4736   /* [basic.type.qualifier] "A const object is an object of type
4737      const T or a non-mutable subobject of a const object."  */
4738   if (mutable_p)
4739     return false;
4740 
4741   if (TREE_READONLY (obj))
4742     return true;
4743 
4744   if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
4745     {
4746       /* Although a COMPONENT_REF may have a const type, we should
4747 	 only consider it modifying a const object when any of the
4748 	 field components is const.  This can happen when using
4749 	 constructs such as const_cast<const T &>(m), making something
4750 	 const even though it wasn't declared const.  */
4751       if (TREE_CODE (obj) == COMPONENT_REF)
4752 	return cref_has_const_field (obj);
4753       else
4754 	return true;
4755     }
4756 
4757   return false;
4758 }
4759 
4760 /* Evaluate an INIT_EXPR or MODIFY_EXPR.  */
4761 
4762 static tree
cxx_eval_store_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)4763 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
4764 			   bool lval,
4765 			   bool *non_constant_p, bool *overflow_p)
4766 {
4767   constexpr_ctx new_ctx = *ctx;
4768 
4769   tree init = TREE_OPERAND (t, 1);
4770   if (TREE_CLOBBER_P (init))
4771     /* Just ignore clobbers.  */
4772     return void_node;
4773 
4774   /* First we figure out where we're storing to.  */
4775   tree target = TREE_OPERAND (t, 0);
4776 
4777   maybe_simplify_trivial_copy (target, init);
4778 
4779   tree type = TREE_TYPE (target);
4780   bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
4781   if (preeval)
4782     {
4783       /* Evaluate the value to be stored without knowing what object it will be
4784 	 stored in, so that any side-effects happen first.  */
4785       if (!SCALAR_TYPE_P (type))
4786 	new_ctx.ctor = new_ctx.object = NULL_TREE;
4787       init = cxx_eval_constant_expression (&new_ctx, init, false,
4788 					   non_constant_p, overflow_p);
4789       if (*non_constant_p)
4790 	return t;
4791     }
4792 
4793   bool evaluated = false;
4794   if (lval)
4795     {
4796       /* If we want to return a reference to the target, we need to evaluate it
4797 	 as a whole; otherwise, only evaluate the innermost piece to avoid
4798 	 building up unnecessary *_REFs.  */
4799       target = cxx_eval_constant_expression (ctx, target, true,
4800 					     non_constant_p, overflow_p);
4801       evaluated = true;
4802       if (*non_constant_p)
4803 	return t;
4804     }
4805 
4806   /* Find the underlying variable.  */
4807   releasing_vec refs;
4808   tree object = NULL_TREE;
4809   /* If we're modifying a const object, save it.  */
4810   tree const_object_being_modified = NULL_TREE;
4811   bool mutable_p = false;
4812   for (tree probe = target; object == NULL_TREE; )
4813     {
4814       switch (TREE_CODE (probe))
4815 	{
4816 	case BIT_FIELD_REF:
4817 	case COMPONENT_REF:
4818 	case ARRAY_REF:
4819 	  {
4820 	    tree ob = TREE_OPERAND (probe, 0);
4821 	    tree elt = TREE_OPERAND (probe, 1);
4822 	    if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
4823 	      mutable_p = true;
4824 	    if (TREE_CODE (probe) == ARRAY_REF)
4825 	      {
4826 		elt = eval_and_check_array_index (ctx, probe, false,
4827 						  non_constant_p, overflow_p);
4828 		if (*non_constant_p)
4829 		  return t;
4830 	      }
4831 	    /* We don't check modifying_const_object_p for ARRAY_REFs.  Given
4832 	       "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
4833 	       the array isn't const.  Instead, check "a" in the next iteration;
4834 	       that will detect modifying "const int a[10]".  */
4835 	    else if (evaluated
4836 		     && modifying_const_object_p (TREE_CODE (t), probe,
4837 						  mutable_p)
4838 		     && const_object_being_modified == NULL_TREE)
4839 	      const_object_being_modified = probe;
4840 	    vec_safe_push (refs, elt);
4841 	    vec_safe_push (refs, TREE_TYPE (probe));
4842 	    probe = ob;
4843 	  }
4844 	  break;
4845 
4846 	default:
4847 	  if (evaluated)
4848 	    object = probe;
4849 	  else
4850 	    {
4851 	      probe = cxx_eval_constant_expression (ctx, probe, true,
4852 						    non_constant_p, overflow_p);
4853 	      evaluated = true;
4854 	      if (*non_constant_p)
4855 		return t;
4856 	    }
4857 	  break;
4858 	}
4859     }
4860 
4861   if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
4862       && const_object_being_modified == NULL_TREE)
4863     const_object_being_modified = object;
4864 
4865   /* And then find/build up our initializer for the path to the subobject
4866      we're initializing.  */
4867   tree *valp;
4868   if (DECL_P (object))
4869     valp = ctx->global->values.get (object);
4870   else
4871     valp = NULL;
4872   if (!valp)
4873     {
4874       /* A constant-expression cannot modify objects from outside the
4875 	 constant-expression.  */
4876       if (!ctx->quiet)
4877 	error ("modification of %qE is not a constant expression", object);
4878       *non_constant_p = true;
4879       return t;
4880     }
4881   type = TREE_TYPE (object);
4882   bool no_zero_init = true;
4883 
4884   releasing_vec ctors, indexes;
4885   auto_vec<int> index_pos_hints;
4886   bool activated_union_member_p = false;
4887   while (!refs->is_empty ())
4888     {
4889       if (*valp == NULL_TREE)
4890 	{
4891 	  *valp = build_constructor (type, NULL);
4892 	  CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
4893 	}
4894       else if (TREE_CODE (*valp) == STRING_CST)
4895 	{
4896 	  /* An array was initialized with a string constant, and now
4897 	     we're writing into one of its elements.  Explode the
4898 	     single initialization into a set of element
4899 	     initializations.  */
4900 	  gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
4901 
4902 	  tree string = *valp;
4903 	  tree elt_type = TREE_TYPE (type);
4904 	  unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
4905 				    / TYPE_PRECISION (char_type_node));
4906 	  unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
4907 	  tree ary_ctor = build_constructor (type, NULL);
4908 
4909 	  vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
4910 	  for (unsigned ix = 0; ix != num_elts; ix++)
4911 	    {
4912 	      constructor_elt elt =
4913 		{
4914 		  build_int_cst (size_type_node, ix),
4915 		  extract_string_elt (string, chars_per_elt, ix)
4916 		};
4917 	      CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
4918 	    }
4919 
4920 	  *valp = ary_ctor;
4921 	}
4922 
4923       /* If the value of object is already zero-initialized, any new ctors for
4924 	 subobjects will also be zero-initialized.  */
4925       no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
4926 
4927       enum tree_code code = TREE_CODE (type);
4928       type = refs->pop();
4929       tree index = refs->pop();
4930 
4931       if (TREE_CODE (index) == FIELD_DECL
4932 	  && !(same_type_ignoring_top_level_qualifiers_p
4933 	       (DECL_CONTEXT (index), TREE_TYPE (*valp))))
4934 	{
4935 	  /* INDEX isn't a member of *valp.  This can happen if it's a member
4936 	     of an empty base which isn't represented with a FIELD_DECL.  Stop
4937 	     trying to build a CONSTRUCTOR for the inner target; we'll notice
4938 	     this disconnect again below and just return init.  */
4939 	  gcc_assert (is_empty_class (DECL_CONTEXT (index)));
4940 	  break;
4941 	}
4942 
4943       if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
4944 	  && CONSTRUCTOR_ELT (*valp, 0)->index != index)
4945 	{
4946 	  if (cxx_dialect < cxx2a)
4947 	    {
4948 	      if (!ctx->quiet)
4949 		error_at (cp_expr_loc_or_input_loc (t),
4950 			  "change of the active member of a union "
4951 			  "from %qD to %qD",
4952 			  CONSTRUCTOR_ELT (*valp, 0)->index,
4953 			  index);
4954 	      *non_constant_p = true;
4955 	    }
4956 	  else if (TREE_CODE (t) == MODIFY_EXPR
4957 		   && CONSTRUCTOR_NO_CLEARING (*valp))
4958 	    {
4959 	      /* Diagnose changing the active union member while the union
4960 		 is in the process of being initialized.  */
4961 	      if (!ctx->quiet)
4962 		error_at (cp_expr_loc_or_input_loc (t),
4963 			  "change of the active member of a union "
4964 			  "from %qD to %qD during initialization",
4965 			  CONSTRUCTOR_ELT (*valp, 0)->index,
4966 			  index);
4967 	      *non_constant_p = true;
4968 	    }
4969 	  no_zero_init = true;
4970 	}
4971 
4972       vec_safe_push (ctors, *valp);
4973       vec_safe_push (indexes, index);
4974 
4975       constructor_elt *cep
4976 	= get_or_insert_ctor_field (*valp, index);
4977       index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
4978 
4979       if (code == UNION_TYPE)
4980 	activated_union_member_p = true;
4981 
4982       valp = &cep->value;
4983     }
4984 
4985   /* Detect modifying a constant object in constexpr evaluation.
4986      We have found a const object that is being modified.  Figure out
4987      if we need to issue an error.  Consider
4988 
4989      struct A {
4990        int n;
4991        constexpr A() : n(1) { n = 2; } // #1
4992      };
4993      struct B {
4994        const A a;
4995        constexpr B() { a.n = 3; } // #2
4996      };
4997     constexpr B b{};
4998 
4999     #1 is OK, since we're modifying an object under construction, but
5000     #2 is wrong, since "a" is const and has been fully constructed.
5001     To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
5002     which means that the object is read-only.  For the example above, the
5003     *ctors stack at the point of #2 will look like:
5004 
5005       ctors[0] = {.a={.n=2}}  TREE_READONLY = 0
5006       ctors[1] = {.n=2}       TREE_READONLY = 1
5007 
5008     and we're modifying "b.a", so we search the stack and see if the
5009     constructor for "b.a" has already run.  */
5010   if (const_object_being_modified)
5011     {
5012       bool fail = false;
5013       tree const_objtype
5014 	= strip_array_types (TREE_TYPE (const_object_being_modified));
5015       if (!CLASS_TYPE_P (const_objtype))
5016 	fail = true;
5017       else
5018 	{
5019 	  /* [class.ctor]p5 "A constructor can be invoked for a const,
5020 	     volatile, or const volatile object.  const and volatile
5021 	     semantics are not applied on an object under construction.
5022 	     They come into effect when the constructor for the most
5023 	     derived object ends."  */
5024 	  tree elt;
5025 	  unsigned int i;
5026 	  FOR_EACH_VEC_ELT (*ctors, i, elt)
5027 	    if (same_type_ignoring_top_level_qualifiers_p
5028 		(TREE_TYPE (const_object_being_modified), TREE_TYPE (elt)))
5029 	      {
5030 		fail = TREE_READONLY (elt);
5031 		break;
5032 	      }
5033 	}
5034       if (fail)
5035 	{
5036 	  if (!ctx->quiet)
5037 	    modifying_const_object_error (t, const_object_being_modified);
5038 	  *non_constant_p = true;
5039 	  return t;
5040 	}
5041     }
5042 
5043   if (!preeval)
5044     {
5045       /* Create a new CONSTRUCTOR in case evaluation of the initializer
5046 	 wants to modify it.  */
5047       if (*valp == NULL_TREE)
5048 	{
5049 	  *valp = build_constructor (type, NULL);
5050 	  CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
5051 	}
5052       new_ctx.ctor = *valp;
5053       new_ctx.object = target;
5054       /* Avoid temporary materialization when initializing from a TARGET_EXPR.
5055 	 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
5056 	 expansion of those trees uses ctx instead.  */
5057       if (TREE_CODE (init) == TARGET_EXPR)
5058 	if (tree tinit = TARGET_EXPR_INITIAL (init))
5059 	  init = tinit;
5060       init = cxx_eval_constant_expression (&new_ctx, init, false,
5061 					   non_constant_p, overflow_p);
5062       /* The hash table might have moved since the get earlier, and the
5063 	 initializer might have mutated the underlying CONSTRUCTORs, so we must
5064 	 recompute VALP. */
5065       valp = ctx->global->values.get (object);
5066       for (unsigned i = 0; i < vec_safe_length (indexes); i++)
5067 	{
5068 	  constructor_elt *cep
5069 	    = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
5070 	  valp = &cep->value;
5071 	}
5072     }
5073 
5074   /* Don't share a CONSTRUCTOR that might be changed later.  */
5075   init = unshare_constructor (init);
5076 
5077   if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
5078       && TREE_CODE (init) == CONSTRUCTOR)
5079     {
5080       /* An outer ctx->ctor might be pointing to *valp, so replace
5081 	 its contents.  */
5082       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init),
5083 						      TREE_TYPE (*valp)))
5084 	{
5085 	  /* For initialization of an empty base, the original target will be
5086 	   *(base*)this, evaluation of which resolves to the object
5087 	   argument, which has the derived type rather than the base type.  In
5088 	   this situation, just evaluate the initializer and return, since
5089 	   there's no actual data to store.  */
5090 	  gcc_assert (is_empty_class (TREE_TYPE (init)) && !lval);
5091 	  return init;
5092 	}
5093       CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
5094       TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
5095       TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
5096       CONSTRUCTOR_NO_CLEARING (*valp)
5097 	= CONSTRUCTOR_NO_CLEARING (init);
5098     }
5099   else
5100     *valp = init;
5101 
5102   /* After initialization, 'const' semantics apply to the value of the
5103      object.  Make a note of this fact by marking the CONSTRUCTOR
5104      TREE_READONLY.  */
5105   if (TREE_CODE (t) == INIT_EXPR
5106       && TREE_CODE (*valp) == CONSTRUCTOR
5107       && TYPE_READONLY (type))
5108     {
5109       if (INDIRECT_REF_P (target)
5110 	  && (is_this_parameter
5111 	      (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
5112 	/* We've just initialized '*this' (perhaps via the target
5113 	   constructor of a delegating constructor).  Leave it up to the
5114 	   caller that set 'this' to set TREE_READONLY appropriately.  */
5115 	gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
5116 			     (TREE_TYPE (target), type));
5117       else
5118 	TREE_READONLY (*valp) = true;
5119     }
5120 
5121   /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
5122      CONSTRUCTORs, if any.  */
5123   tree elt;
5124   unsigned i;
5125   bool c = TREE_CONSTANT (init);
5126   bool s = TREE_SIDE_EFFECTS (init);
5127   if (!c || s || activated_union_member_p)
5128     FOR_EACH_VEC_ELT (*ctors, i, elt)
5129       {
5130 	if (!c)
5131 	  TREE_CONSTANT (elt) = false;
5132 	if (s)
5133 	  TREE_SIDE_EFFECTS (elt) = true;
5134 	/* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
5135 	   this union.  */
5136 	if (TREE_CODE (TREE_TYPE (elt)) == UNION_TYPE)
5137 	  CONSTRUCTOR_NO_CLEARING (elt) = false;
5138       }
5139 
5140   if (*non_constant_p)
5141     return t;
5142   else if (lval)
5143     return target;
5144   else
5145     return init;
5146 }
5147 
5148 /* Evaluate a ++ or -- expression.  */
5149 
5150 static tree
cxx_eval_increment_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p)5151 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
5152 			      bool lval,
5153 			      bool *non_constant_p, bool *overflow_p)
5154 {
5155   enum tree_code code = TREE_CODE (t);
5156   tree type = TREE_TYPE (t);
5157   tree op = TREE_OPERAND (t, 0);
5158   tree offset = TREE_OPERAND (t, 1);
5159   gcc_assert (TREE_CONSTANT (offset));
5160 
5161   /* OFFSET is constant, but perhaps not constant enough.  We need to
5162      e.g. bash FLOAT_EXPRs to REAL_CSTs.  */
5163   offset = fold_simple (offset);
5164 
5165   /* The operand as an lvalue.  */
5166   op = cxx_eval_constant_expression (ctx, op, true,
5167 				     non_constant_p, overflow_p);
5168 
5169   /* The operand as an rvalue.  */
5170   tree val
5171     = cxx_eval_constant_expression (ctx, op, false,
5172 				    non_constant_p, overflow_p);
5173   /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
5174      a local array in a constexpr function.  */
5175   bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
5176   if (!ptr)
5177     VERIFY_CONSTANT (val);
5178 
5179   /* The modified value.  */
5180   bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
5181   tree mod;
5182   if (INDIRECT_TYPE_P (type))
5183     {
5184       /* The middle end requires pointers to use POINTER_PLUS_EXPR.  */
5185       offset = convert_to_ptrofftype (offset);
5186       if (!inc)
5187 	offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
5188       mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
5189     }
5190   else
5191     mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
5192   if (!ptr)
5193     VERIFY_CONSTANT (mod);
5194 
5195   /* Storing the modified value.  */
5196   tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
5197 			   MODIFY_EXPR, type, op, mod);
5198   cxx_eval_constant_expression (ctx, store,
5199 				true, non_constant_p, overflow_p);
5200   ggc_free (store);
5201 
5202   /* And the value of the expression.  */
5203   if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
5204     {
5205       /* Prefix ops are lvalues.  */
5206       if (lval)
5207 	return op;
5208       else
5209 	/* But we optimize when the caller wants an rvalue.  */
5210 	return mod;
5211     }
5212   else
5213     /* Postfix ops are rvalues.  */
5214     return val;
5215 }
5216 
5217 /* Predicates for the meaning of *jump_target.  */
5218 
5219 static bool
returns(tree * jump_target)5220 returns (tree *jump_target)
5221 {
5222   return *jump_target
5223     && (TREE_CODE (*jump_target) == RETURN_EXPR
5224 	|| (TREE_CODE (*jump_target) == LABEL_DECL
5225 	    && LABEL_DECL_CDTOR (*jump_target)));
5226 }
5227 
5228 static bool
breaks(tree * jump_target)5229 breaks (tree *jump_target)
5230 {
5231   return *jump_target
5232     && ((TREE_CODE (*jump_target) == LABEL_DECL
5233 	 && LABEL_DECL_BREAK (*jump_target))
5234 	|| TREE_CODE (*jump_target) == BREAK_STMT
5235 	|| TREE_CODE (*jump_target) == EXIT_EXPR);
5236 }
5237 
5238 static bool
continues(tree * jump_target)5239 continues (tree *jump_target)
5240 {
5241   return *jump_target
5242     && ((TREE_CODE (*jump_target) == LABEL_DECL
5243 	 && LABEL_DECL_CONTINUE (*jump_target))
5244 	|| TREE_CODE (*jump_target) == CONTINUE_STMT);
5245 
5246 }
5247 
5248 static bool
switches(tree * jump_target)5249 switches (tree *jump_target)
5250 {
5251   return *jump_target
5252     && TREE_CODE (*jump_target) == INTEGER_CST;
5253 }
5254 
5255 /* Subroutine of cxx_eval_statement_list.  Determine whether the statement
5256    STMT matches *jump_target.  If we're looking for a case label and we see
5257    the default label, note it in ctx->css_state.  */
5258 
5259 static bool
label_matches(const constexpr_ctx * ctx,tree * jump_target,tree stmt)5260 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
5261 {
5262   switch (TREE_CODE (*jump_target))
5263     {
5264     case LABEL_DECL:
5265       if (TREE_CODE (stmt) == LABEL_EXPR
5266 	  && LABEL_EXPR_LABEL (stmt) == *jump_target)
5267 	return true;
5268       break;
5269 
5270     case INTEGER_CST:
5271       if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
5272 	{
5273 	  gcc_assert (ctx->css_state != NULL);
5274 	  if (!CASE_LOW (stmt))
5275 	    {
5276 	      /* default: should appear just once in a SWITCH_EXPR
5277 		 body (excluding nested SWITCH_EXPR).  */
5278 	      gcc_assert (*ctx->css_state != css_default_seen);
5279 	      /* When evaluating SWITCH_EXPR body for the second time,
5280 		 return true for the default: label.  */
5281 	      if (*ctx->css_state == css_default_processing)
5282 		return true;
5283 	      *ctx->css_state = css_default_seen;
5284 	    }
5285 	  else if (CASE_HIGH (stmt))
5286 	    {
5287 	      if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
5288 		  && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
5289 		return true;
5290 	    }
5291 	  else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
5292 	    return true;
5293 	}
5294       break;
5295 
5296     case BREAK_STMT:
5297     case CONTINUE_STMT:
5298       /* These two are handled directly in cxx_eval_loop_expr by testing
5299 	 breaks (jump_target) or continues (jump_target).  */
5300       break;
5301 
5302     default:
5303       gcc_unreachable ();
5304     }
5305   return false;
5306 }
5307 
5308 /* Evaluate a STATEMENT_LIST for side-effects.  Handles various jump
5309    semantics, for switch, break, continue, and return.  */
5310 
5311 static tree
cxx_eval_statement_list(const constexpr_ctx * ctx,tree t,bool * non_constant_p,bool * overflow_p,tree * jump_target)5312 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
5313 			 bool *non_constant_p, bool *overflow_p,
5314 			 tree *jump_target)
5315 {
5316   tree_stmt_iterator i;
5317   tree local_target;
5318   /* In a statement-expression we want to return the last value.
5319      For empty statement expression return void_node.  */
5320   tree r = void_node;
5321   if (!jump_target)
5322     {
5323       local_target = NULL_TREE;
5324       jump_target = &local_target;
5325     }
5326   for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
5327     {
5328       tree stmt = tsi_stmt (i);
5329       /* We've found a continue, so skip everything until we reach
5330 	 the label its jumping to.  */
5331       if (continues (jump_target))
5332 	{
5333 	  if (label_matches (ctx, jump_target, stmt))
5334 	    /* Found it.  */
5335 	    *jump_target = NULL_TREE;
5336 	  else
5337 	    continue;
5338 	}
5339       if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
5340 	continue;
5341       r = cxx_eval_constant_expression (ctx, stmt, false,
5342 					non_constant_p, overflow_p,
5343 					jump_target);
5344       if (*non_constant_p)
5345 	break;
5346       if (returns (jump_target) || breaks (jump_target))
5347 	break;
5348     }
5349   if (*jump_target && jump_target == &local_target)
5350     {
5351       /* We aren't communicating the jump to our caller, so give up.  We don't
5352 	 need to support evaluation of jumps out of statement-exprs.  */
5353       if (!ctx->quiet)
5354 	error_at (cp_expr_loc_or_input_loc (r),
5355 		  "statement is not a constant expression");
5356       *non_constant_p = true;
5357     }
5358   return r;
5359 }
5360 
5361 /* Evaluate a LOOP_EXPR for side-effects.  Handles break and return
5362    semantics; continue semantics are covered by cxx_eval_statement_list.  */
5363 
5364 static tree
cxx_eval_loop_expr(const constexpr_ctx * ctx,tree t,bool * non_constant_p,bool * overflow_p,tree * jump_target)5365 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
5366 		    bool *non_constant_p, bool *overflow_p,
5367 		    tree *jump_target)
5368 {
5369   constexpr_ctx new_ctx = *ctx;
5370   tree local_target;
5371   if (!jump_target)
5372     {
5373       local_target = NULL_TREE;
5374       jump_target = &local_target;
5375     }
5376 
5377   tree body, cond = NULL_TREE, expr = NULL_TREE;
5378   int count = 0;
5379   switch (TREE_CODE (t))
5380     {
5381     case LOOP_EXPR:
5382       body = LOOP_EXPR_BODY (t);
5383       break;
5384     case DO_STMT:
5385       body = DO_BODY (t);
5386       cond = DO_COND (t);
5387       break;
5388     case WHILE_STMT:
5389       body = WHILE_BODY (t);
5390       cond = WHILE_COND (t);
5391       count = -1;
5392       break;
5393     case FOR_STMT:
5394       if (FOR_INIT_STMT (t))
5395 	cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), /*lval*/false,
5396 				      non_constant_p, overflow_p, jump_target);
5397       if (*non_constant_p)
5398 	return NULL_TREE;
5399       body = FOR_BODY (t);
5400       cond = FOR_COND (t);
5401       expr = FOR_EXPR (t);
5402       count = -1;
5403       break;
5404     default:
5405       gcc_unreachable ();
5406     }
5407   auto_vec<tree, 10> save_exprs;
5408   new_ctx.save_exprs = &save_exprs;
5409   do
5410     {
5411       if (count != -1)
5412 	{
5413 	  if (body)
5414 	    cxx_eval_constant_expression (&new_ctx, body, /*lval*/false,
5415 					  non_constant_p, overflow_p,
5416 					  jump_target);
5417 	  if (breaks (jump_target))
5418 	    {
5419 	      *jump_target = NULL_TREE;
5420 	      break;
5421 	    }
5422 
5423 	  if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
5424 	    *jump_target = NULL_TREE;
5425 
5426 	  if (expr)
5427 	    cxx_eval_constant_expression (&new_ctx, expr, /*lval*/false,
5428 					  non_constant_p, overflow_p,
5429 					  jump_target);
5430 	}
5431 
5432       if (cond)
5433 	{
5434 	  tree res
5435 	    = cxx_eval_constant_expression (&new_ctx, cond, /*lval*/false,
5436 					    non_constant_p, overflow_p,
5437 					    jump_target);
5438 	  if (res)
5439 	    {
5440 	      if (verify_constant (res, ctx->quiet, non_constant_p,
5441 				   overflow_p))
5442 		break;
5443 	      if (integer_zerop (res))
5444 		break;
5445 	    }
5446 	  else
5447 	    gcc_assert (*jump_target);
5448 	}
5449 
5450       /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs.  */
5451       unsigned int i;
5452       tree save_expr;
5453       FOR_EACH_VEC_ELT (save_exprs, i, save_expr)
5454 	ctx->global->values.remove (save_expr);
5455       save_exprs.truncate (0);
5456 
5457       if (++count >= constexpr_loop_limit)
5458 	{
5459 	  if (!ctx->quiet)
5460 	    error_at (cp_expr_loc_or_input_loc (t),
5461 		      "%<constexpr%> loop iteration count exceeds limit of %d "
5462 		      "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
5463 		      constexpr_loop_limit);
5464 	  *non_constant_p = true;
5465 	  break;
5466 	}
5467     }
5468   while (!returns (jump_target)
5469 	 && !breaks (jump_target)
5470 	 && !continues (jump_target)
5471 	 && (!switches (jump_target) || count == 0)
5472 	 && !*non_constant_p);
5473 
5474   /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs.  */
5475   unsigned int i;
5476   tree save_expr;
5477   FOR_EACH_VEC_ELT (save_exprs, i, save_expr)
5478     ctx->global->values.remove (save_expr);
5479 
5480   return NULL_TREE;
5481 }
5482 
5483 /* Evaluate a SWITCH_EXPR for side-effects.  Handles switch and break jump
5484    semantics.  */
5485 
5486 static tree
cxx_eval_switch_expr(const constexpr_ctx * ctx,tree t,bool * non_constant_p,bool * overflow_p,tree * jump_target)5487 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
5488 		      bool *non_constant_p, bool *overflow_p,
5489 		      tree *jump_target)
5490 {
5491   tree cond
5492     = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
5493   cond = cxx_eval_constant_expression (ctx, cond, false,
5494 				       non_constant_p, overflow_p);
5495   VERIFY_CONSTANT (cond);
5496   *jump_target = cond;
5497 
5498   tree body
5499     = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
5500   constexpr_ctx new_ctx = *ctx;
5501   constexpr_switch_state css = css_default_not_seen;
5502   new_ctx.css_state = &css;
5503   cxx_eval_constant_expression (&new_ctx, body, false,
5504 				non_constant_p, overflow_p, jump_target);
5505   if (switches (jump_target) && css == css_default_seen)
5506     {
5507       /* If the SWITCH_EXPR body has default: label, process it once again,
5508 	 this time instructing label_matches to return true for default:
5509 	 label on switches (jump_target).  */
5510       css = css_default_processing;
5511       cxx_eval_constant_expression (&new_ctx, body, false,
5512 				    non_constant_p, overflow_p, jump_target);
5513     }
5514   if (breaks (jump_target) || switches (jump_target))
5515     *jump_target = NULL_TREE;
5516   return NULL_TREE;
5517 }
5518 
5519 /* Find the object of TYPE under initialization in CTX.  */
5520 
5521 static tree
lookup_placeholder(const constexpr_ctx * ctx,bool lval,tree type)5522 lookup_placeholder (const constexpr_ctx *ctx, bool lval, tree type)
5523 {
5524   if (!ctx)
5525     return NULL_TREE;
5526 
5527   /* Prefer the outermost matching object, but don't cross
5528      CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors.  */
5529   if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
5530     if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
5531       return outer_ob;
5532 
5533   /* We could use ctx->object unconditionally, but using ctx->ctor when we
5534      can is a minor optimization.  */
5535   if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
5536     return ctx->ctor;
5537 
5538   if (!ctx->object)
5539     return NULL_TREE;
5540 
5541   /* Since an object cannot have a field of its own type, we can search outward
5542      from ctx->object to find the unique containing object of TYPE.  */
5543   tree ob = ctx->object;
5544   while (ob)
5545     {
5546       if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
5547 	break;
5548       if (handled_component_p (ob))
5549 	ob = TREE_OPERAND (ob, 0);
5550       else
5551 	ob = NULL_TREE;
5552     }
5553 
5554   return ob;
5555 }
5556 
5557 /* Complain about an attempt to evaluate inline assembly.  */
5558 
5559 static void
inline_asm_in_constexpr_error(location_t loc)5560 inline_asm_in_constexpr_error (location_t loc)
5561 {
5562   auto_diagnostic_group d;
5563   error_at (loc, "inline assembly is not a constant expression");
5564   inform (loc, "only unevaluated inline assembly is allowed in a "
5565 	  "%<constexpr%> function in C++2a");
5566 }
5567 
5568 /* Attempt to reduce the expression T to a constant value.
5569    On failure, issue diagnostic and return error_mark_node.  */
5570 /* FIXME unify with c_fully_fold */
5571 /* FIXME overflow_p is too global */
5572 
5573 static tree
cxx_eval_constant_expression(const constexpr_ctx * ctx,tree t,bool lval,bool * non_constant_p,bool * overflow_p,tree * jump_target)5574 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
5575 			      bool lval,
5576 			      bool *non_constant_p, bool *overflow_p,
5577 			      tree *jump_target /* = NULL */)
5578 {
5579   if (jump_target && *jump_target)
5580     {
5581       /* If we are jumping, ignore all statements/expressions except those
5582 	 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies.  */
5583       switch (TREE_CODE (t))
5584 	{
5585 	case BIND_EXPR:
5586 	case STATEMENT_LIST:
5587 	case LOOP_EXPR:
5588 	case COND_EXPR:
5589 	case IF_STMT:
5590 	case DO_STMT:
5591 	case WHILE_STMT:
5592 	case FOR_STMT:
5593 	  break;
5594 	case LABEL_EXPR:
5595 	case CASE_LABEL_EXPR:
5596 	  if (label_matches (ctx, jump_target, t))
5597 	    /* Found it.  */
5598 	    *jump_target = NULL_TREE;
5599 	  return NULL_TREE;
5600 	default:
5601 	  return NULL_TREE;
5602 	}
5603     }
5604   if (error_operand_p (t))
5605     {
5606       *non_constant_p = true;
5607       return t;
5608     }
5609 
5610   location_t loc = cp_expr_loc_or_input_loc (t);
5611 
5612   STRIP_ANY_LOCATION_WRAPPER (t);
5613 
5614   if (CONSTANT_CLASS_P (t))
5615     {
5616       if (TREE_OVERFLOW (t))
5617 	{
5618 	  if (!ctx->quiet)
5619 	    permerror (input_location, "overflow in constant expression");
5620 	  if (!flag_permissive || ctx->quiet)
5621 	    *overflow_p = true;
5622 	}
5623 
5624       if (TREE_CODE (t) == INTEGER_CST
5625 	  && TYPE_PTR_P (TREE_TYPE (t))
5626 	  && !integer_zerop (t))
5627 	{
5628 	  if (!ctx->quiet)
5629 	    error ("value %qE of type %qT is not a constant expression",
5630 		   t, TREE_TYPE (t));
5631 	  *non_constant_p = true;
5632 	}
5633 
5634       return t;
5635     }
5636 
5637   /* Avoid excessively long constexpr evaluations.  */
5638   if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
5639     {
5640       if (!ctx->quiet)
5641 	error_at (loc,
5642 		  "%<constexpr%> evaluation operation count exceeds limit of "
5643 		  "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
5644 		  constexpr_ops_limit);
5645       ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
5646       *non_constant_p = true;
5647       return t;
5648     }
5649 
5650   constexpr_ctx new_ctx;
5651   tree r = t;
5652 
5653   tree_code tcode = TREE_CODE (t);
5654   switch (tcode)
5655     {
5656     case RESULT_DECL:
5657       if (lval)
5658 	return t;
5659       /* We ask for an rvalue for the RESULT_DECL when indirecting
5660 	 through an invisible reference, or in named return value
5661 	 optimization.  */
5662       if (tree *p = ctx->global->values.get (t))
5663 	return *p;
5664       else
5665 	{
5666 	  if (!ctx->quiet)
5667 	    error ("%qE is not a constant expression", t);
5668 	  *non_constant_p = true;
5669 	}
5670       break;
5671 
5672     case VAR_DECL:
5673       if (DECL_HAS_VALUE_EXPR_P (t))
5674 	{
5675 	  if (is_normal_capture_proxy (t)
5676 	      && current_function_decl == DECL_CONTEXT (t))
5677 	    {
5678 	      /* Function parms aren't constexpr within the function
5679 		 definition, so don't try to look at the closure.  But if the
5680 		 captured variable is constant, try to evaluate it directly. */
5681 	      r = DECL_CAPTURED_VARIABLE (t);
5682 	      tree type = TREE_TYPE (t);
5683 	      if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
5684 		{
5685 		  /* Adjust r to match the reference-ness of t.  */
5686 		  if (TYPE_REF_P (type))
5687 		    r = build_address (r);
5688 		  else
5689 		    r = convert_from_reference (r);
5690 		}
5691 	    }
5692 	  else
5693 	    r = DECL_VALUE_EXPR (t);
5694 	  return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
5695 					       overflow_p);
5696 	}
5697       /* fall through */
5698     case CONST_DECL:
5699       /* We used to not check lval for CONST_DECL, but darwin.c uses
5700 	 CONST_DECL for aggregate constants.  */
5701       if (lval)
5702 	return t;
5703       else if (t == ctx->object)
5704 	return ctx->ctor;
5705       if (VAR_P (t))
5706 	if (tree *p = ctx->global->values.get (t))
5707 	  if (*p != NULL_TREE)
5708 	    {
5709 	      r = *p;
5710 	      break;
5711 	    }
5712       if (COMPLETE_TYPE_P (TREE_TYPE (t))
5713 	  && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
5714 	{
5715 	  /* If the class is empty, we aren't actually loading anything.  */
5716 	  r = build_constructor (TREE_TYPE (t), NULL);
5717 	  TREE_CONSTANT (r) = true;
5718 	}
5719       else if (ctx->strict)
5720 	r = decl_really_constant_value (t, /*unshare_p=*/false);
5721       else
5722 	r = decl_constant_value (t, /*unshare_p=*/false);
5723       if (TREE_CODE (r) == TARGET_EXPR
5724 	  && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
5725 	r = TARGET_EXPR_INITIAL (r);
5726       if (DECL_P (r))
5727 	{
5728 	  if (!ctx->quiet)
5729 	    non_const_var_error (loc, r);
5730 	  *non_constant_p = true;
5731 	}
5732       break;
5733 
5734     case DEBUG_BEGIN_STMT:
5735       /* ??? It might be nice to retain this information somehow, so
5736 	 as to be able to step into a constexpr function call.  */
5737       /* Fall through.  */
5738 
5739     case FUNCTION_DECL:
5740     case TEMPLATE_DECL:
5741     case LABEL_DECL:
5742     case LABEL_EXPR:
5743     case CASE_LABEL_EXPR:
5744     case PREDICT_EXPR:
5745       return t;
5746 
5747     case PARM_DECL:
5748       if (lval && !TYPE_REF_P (TREE_TYPE (t)))
5749 	/* glvalue use.  */;
5750       else if (tree *p = ctx->global->values.get (r))
5751 	r = *p;
5752       else if (lval)
5753 	/* Defer in case this is only used for its type.  */;
5754       else if (COMPLETE_TYPE_P (TREE_TYPE (t))
5755 	       && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
5756 	{
5757 	  /* If the class is empty, we aren't actually loading anything.  */
5758 	  r = build_constructor (TREE_TYPE (t), NULL);
5759 	  TREE_CONSTANT (r) = true;
5760 	}
5761       else
5762 	{
5763 	  if (!ctx->quiet)
5764 	    error ("%qE is not a constant expression", t);
5765 	  *non_constant_p = true;
5766 	}
5767       break;
5768 
5769     case CALL_EXPR:
5770     case AGGR_INIT_EXPR:
5771       r = cxx_eval_call_expression (ctx, t, lval,
5772 				    non_constant_p, overflow_p);
5773       break;
5774 
5775     case DECL_EXPR:
5776       {
5777 	r = DECL_EXPR_DECL (t);
5778 	if (TREE_CODE (r) == USING_DECL)
5779 	  {
5780 	    r = void_node;
5781 	    break;
5782 	  }
5783 	if (AGGREGATE_TYPE_P (TREE_TYPE (r))
5784 	    || VECTOR_TYPE_P (TREE_TYPE (r)))
5785 	  {
5786 	    new_ctx = *ctx;
5787 	    new_ctx.object = r;
5788 	    new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
5789 	    CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
5790 	    ctx->global->values.put (r, new_ctx.ctor);
5791 	    ctx = &new_ctx;
5792 	  }
5793 
5794 	if (tree init = DECL_INITIAL (r))
5795 	  {
5796 	    init = cxx_eval_constant_expression (ctx, init,
5797 						 false,
5798 						 non_constant_p, overflow_p);
5799 	    /* Don't share a CONSTRUCTOR that might be changed.  */
5800 	    init = unshare_constructor (init);
5801 	    /* Remember that a constant object's constructor has already
5802 	       run.  */
5803 	    if (CLASS_TYPE_P (TREE_TYPE (r))
5804 		&& CP_TYPE_CONST_P (TREE_TYPE (r)))
5805 	      TREE_READONLY (init) = true;
5806 	    ctx->global->values.put (r, init);
5807 	  }
5808 	else if (ctx == &new_ctx)
5809 	  /* We gave it a CONSTRUCTOR above.  */;
5810 	else
5811 	  ctx->global->values.put (r, NULL_TREE);
5812       }
5813       break;
5814 
5815     case TARGET_EXPR:
5816       {
5817 	tree type = TREE_TYPE (t);
5818 
5819 	if (!literal_type_p (type))
5820 	  {
5821 	    if (!ctx->quiet)
5822 	      {
5823 		auto_diagnostic_group d;
5824 		error ("temporary of non-literal type %qT in a "
5825 		       "constant expression", type);
5826 		explain_non_literal_class (type);
5827 	      }
5828 	    *non_constant_p = true;
5829 	    break;
5830 	  }
5831 	gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
5832 	/* Avoid evaluating a TARGET_EXPR more than once.  */
5833 	tree slot = TARGET_EXPR_SLOT (t);
5834 	if (tree *p = ctx->global->values.get (slot))
5835 	  {
5836 	    if (lval)
5837 	      return slot;
5838 	    r = *p;
5839 	    break;
5840 	  }
5841 	if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
5842 	  {
5843 	    /* We're being expanded without an explicit target, so start
5844 	       initializing a new object; expansion with an explicit target
5845 	       strips the TARGET_EXPR before we get here.  */
5846 	    new_ctx = *ctx;
5847 	    /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
5848 	       any PLACEHOLDER_EXPR within the initializer that refers to the
5849 	       former object under construction.  */
5850 	    new_ctx.parent = ctx;
5851 	    new_ctx.ctor = build_constructor (type, NULL);
5852 	    CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
5853 	    new_ctx.object = slot;
5854 	    ctx->global->values.put (new_ctx.object, new_ctx.ctor);
5855 	    ctx = &new_ctx;
5856 	  }
5857 	/* Pass false for 'lval' because this indicates
5858 	   initialization of a temporary.  */
5859 	r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
5860 					  false,
5861 					  non_constant_p, overflow_p);
5862 	if (*non_constant_p)
5863 	  break;
5864 	/* Adjust the type of the result to the type of the temporary.  */
5865 	r = adjust_temp_type (type, r);
5866 	if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
5867 	  ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
5868 	r = unshare_constructor (r);
5869 	ctx->global->values.put (slot, r);
5870 	if (ctx->save_exprs)
5871 	  ctx->save_exprs->safe_push (slot);
5872 	if (lval)
5873 	  return slot;
5874       }
5875       break;
5876 
5877     case INIT_EXPR:
5878     case MODIFY_EXPR:
5879       gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
5880       r = cxx_eval_store_expression (ctx, t, lval,
5881 				     non_constant_p, overflow_p);
5882       break;
5883 
5884     case SCOPE_REF:
5885       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
5886 					lval,
5887 					non_constant_p, overflow_p);
5888       break;
5889 
5890     case RETURN_EXPR:
5891       if (TREE_OPERAND (t, 0) != NULL_TREE)
5892 	r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
5893 					  lval,
5894 					  non_constant_p, overflow_p);
5895       /* FALLTHRU */
5896     case BREAK_STMT:
5897     case CONTINUE_STMT:
5898       if (jump_target)
5899 	*jump_target = t;
5900       else
5901 	{
5902 	  /* Can happen with ({ return true; }) && false; passed to
5903 	     maybe_constant_value.  There is nothing to jump over in this
5904 	     case, and the bug will be diagnosed later.  */
5905 	  gcc_assert (ctx->quiet);
5906 	  *non_constant_p = true;
5907 	}
5908       break;
5909 
5910     case SAVE_EXPR:
5911       /* Avoid evaluating a SAVE_EXPR more than once.  */
5912       if (tree *p = ctx->global->values.get (t))
5913 	r = *p;
5914       else
5915 	{
5916 	  r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
5917 					    non_constant_p, overflow_p);
5918 	  if (*non_constant_p)
5919 	    break;
5920 	  ctx->global->values.put (t, r);
5921 	  if (ctx->save_exprs)
5922 	    ctx->save_exprs->safe_push (t);
5923 	}
5924       break;
5925 
5926     case TRY_CATCH_EXPR:
5927       if (TREE_OPERAND (t, 0) == NULL_TREE)
5928 	{
5929 	  r = void_node;
5930 	  break;
5931 	}
5932       /* FALLTHRU */
5933     case NON_LVALUE_EXPR:
5934     case TRY_BLOCK:
5935     case MUST_NOT_THROW_EXPR:
5936     case EXPR_STMT:
5937     case EH_SPEC_BLOCK:
5938       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
5939 					lval,
5940 					non_constant_p, overflow_p,
5941 					jump_target);
5942       break;
5943 
5944     case CLEANUP_POINT_EXPR:
5945       {
5946 	auto_vec<tree, 2> cleanups;
5947 	vec<tree> *prev_cleanups = ctx->global->cleanups;
5948 	ctx->global->cleanups = &cleanups;
5949 	r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
5950 					  lval,
5951 					  non_constant_p, overflow_p,
5952 					  jump_target);
5953 	ctx->global->cleanups = prev_cleanups;
5954 	unsigned int i;
5955 	tree cleanup;
5956 	/* Evaluate the cleanups.  */
5957 	FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
5958 	  cxx_eval_constant_expression (ctx, cleanup, false,
5959 					non_constant_p, overflow_p);
5960       }
5961       break;
5962 
5963     case TRY_FINALLY_EXPR:
5964       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
5965 					non_constant_p, overflow_p,
5966 					jump_target);
5967       if (!*non_constant_p)
5968 	/* Also evaluate the cleanup.  */
5969 	cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
5970 				      non_constant_p, overflow_p);
5971       break;
5972 
5973     case CLEANUP_STMT:
5974       r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
5975 					non_constant_p, overflow_p,
5976 					jump_target);
5977       if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
5978 	{
5979 	  iloc_sentinel ils (loc);
5980 	  /* Also evaluate the cleanup.  */
5981 	  cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), true,
5982 					non_constant_p, overflow_p);
5983 	}
5984       break;
5985 
5986       /* These differ from cxx_eval_unary_expression in that this doesn't
5987 	 check for a constant operand or result; an address can be
5988 	 constant without its operand being, and vice versa.  */
5989     case MEM_REF:
5990     case INDIRECT_REF:
5991       r = cxx_eval_indirect_ref (ctx, t, lval,
5992 				 non_constant_p, overflow_p);
5993       break;
5994 
5995     case ADDR_EXPR:
5996       {
5997 	tree oldop = TREE_OPERAND (t, 0);
5998 	tree op = cxx_eval_constant_expression (ctx, oldop,
5999 						/*lval*/true,
6000 						non_constant_p, overflow_p);
6001 	/* Don't VERIFY_CONSTANT here.  */
6002 	if (*non_constant_p)
6003 	  return t;
6004 	gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
6005 	/* This function does more aggressive folding than fold itself.  */
6006 	r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
6007 	if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
6008 	  {
6009 	    ggc_free (r);
6010 	    return t;
6011 	  }
6012 	break;
6013       }
6014 
6015     case REALPART_EXPR:
6016     case IMAGPART_EXPR:
6017       if (lval)
6018 	{
6019 	  r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
6020 					    non_constant_p, overflow_p);
6021 	  if (r == error_mark_node)
6022 	    ;
6023 	  else if (r == TREE_OPERAND (t, 0))
6024 	    r = t;
6025 	  else
6026 	    r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
6027 	  break;
6028 	}
6029       /* FALLTHRU */
6030     case CONJ_EXPR:
6031     case FIX_TRUNC_EXPR:
6032     case FLOAT_EXPR:
6033     case NEGATE_EXPR:
6034     case ABS_EXPR:
6035     case ABSU_EXPR:
6036     case BIT_NOT_EXPR:
6037     case TRUTH_NOT_EXPR:
6038     case FIXED_CONVERT_EXPR:
6039       r = cxx_eval_unary_expression (ctx, t, lval,
6040 				     non_constant_p, overflow_p);
6041       break;
6042 
6043     case SIZEOF_EXPR:
6044       r = fold_sizeof_expr (t);
6045       /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
6046 	 which could lead to an infinite recursion.  */
6047       if (TREE_CODE (r) != SIZEOF_EXPR)
6048 	r = cxx_eval_constant_expression (ctx, r, lval,
6049 					  non_constant_p, overflow_p,
6050 					  jump_target);
6051       else
6052 	{
6053 	  *non_constant_p = true;
6054 	  gcc_assert (ctx->quiet);
6055 	}
6056 
6057       break;
6058 
6059     case COMPOUND_EXPR:
6060       {
6061 	/* check_return_expr sometimes wraps a TARGET_EXPR in a
6062 	   COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
6063 	   introduced by build_call_a.  */
6064 	tree op0 = TREE_OPERAND (t, 0);
6065 	tree op1 = TREE_OPERAND (t, 1);
6066 	STRIP_NOPS (op1);
6067 	if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
6068 	    || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
6069 	  r = cxx_eval_constant_expression (ctx, op0,
6070 					    lval, non_constant_p, overflow_p,
6071 					    jump_target);
6072 	else
6073 	  {
6074 	    /* Check that the LHS is constant and then discard it.  */
6075 	    cxx_eval_constant_expression (ctx, op0,
6076 					  true, non_constant_p, overflow_p,
6077 					  jump_target);
6078 	    if (*non_constant_p)
6079 	      return t;
6080 	    op1 = TREE_OPERAND (t, 1);
6081 	    r = cxx_eval_constant_expression (ctx, op1,
6082 					      lval, non_constant_p, overflow_p,
6083 					      jump_target);
6084 	  }
6085       }
6086       break;
6087 
6088     case POINTER_PLUS_EXPR:
6089     case POINTER_DIFF_EXPR:
6090     case PLUS_EXPR:
6091     case MINUS_EXPR:
6092     case MULT_EXPR:
6093     case TRUNC_DIV_EXPR:
6094     case CEIL_DIV_EXPR:
6095     case FLOOR_DIV_EXPR:
6096     case ROUND_DIV_EXPR:
6097     case TRUNC_MOD_EXPR:
6098     case CEIL_MOD_EXPR:
6099     case ROUND_MOD_EXPR:
6100     case RDIV_EXPR:
6101     case EXACT_DIV_EXPR:
6102     case MIN_EXPR:
6103     case MAX_EXPR:
6104     case LSHIFT_EXPR:
6105     case RSHIFT_EXPR:
6106     case LROTATE_EXPR:
6107     case RROTATE_EXPR:
6108     case BIT_IOR_EXPR:
6109     case BIT_XOR_EXPR:
6110     case BIT_AND_EXPR:
6111     case TRUTH_XOR_EXPR:
6112     case LT_EXPR:
6113     case LE_EXPR:
6114     case GT_EXPR:
6115     case GE_EXPR:
6116     case EQ_EXPR:
6117     case NE_EXPR:
6118     case SPACESHIP_EXPR:
6119     case UNORDERED_EXPR:
6120     case ORDERED_EXPR:
6121     case UNLT_EXPR:
6122     case UNLE_EXPR:
6123     case UNGT_EXPR:
6124     case UNGE_EXPR:
6125     case UNEQ_EXPR:
6126     case LTGT_EXPR:
6127     case RANGE_EXPR:
6128     case COMPLEX_EXPR:
6129       r = cxx_eval_binary_expression (ctx, t, lval,
6130 				      non_constant_p, overflow_p);
6131       break;
6132 
6133       /* fold can introduce non-IF versions of these; still treat them as
6134 	 short-circuiting.  */
6135     case TRUTH_AND_EXPR:
6136     case TRUTH_ANDIF_EXPR:
6137       r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
6138 				       boolean_true_node,
6139 				       lval,
6140 				       non_constant_p, overflow_p);
6141       break;
6142 
6143     case TRUTH_OR_EXPR:
6144     case TRUTH_ORIF_EXPR:
6145       r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
6146 				       boolean_false_node,
6147 				       lval,
6148 				       non_constant_p, overflow_p);
6149       break;
6150 
6151     case ARRAY_REF:
6152       r = cxx_eval_array_reference (ctx, t, lval,
6153 				    non_constant_p, overflow_p);
6154       break;
6155 
6156     case COMPONENT_REF:
6157       if (is_overloaded_fn (t))
6158 	{
6159 	  /* We can only get here in checking mode via
6160 	     build_non_dependent_expr,  because any expression that
6161 	     calls or takes the address of the function will have
6162 	     pulled a FUNCTION_DECL out of the COMPONENT_REF.  */
6163 	  gcc_checking_assert (ctx->quiet || errorcount);
6164 	  *non_constant_p = true;
6165 	  return t;
6166 	}
6167       r = cxx_eval_component_reference (ctx, t, lval,
6168 					non_constant_p, overflow_p);
6169       break;
6170 
6171     case BIT_FIELD_REF:
6172       r = cxx_eval_bit_field_ref (ctx, t, lval,
6173 				  non_constant_p, overflow_p);
6174       break;
6175 
6176     case COND_EXPR:
6177     case IF_STMT:
6178       if (jump_target && *jump_target)
6179 	{
6180 	  tree orig_jump = *jump_target;
6181 	  tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
6182 		      ? TREE_OPERAND (t, 1) : void_node);
6183 	  /* When jumping to a label, the label might be either in the
6184 	     then or else blocks, so process then block first in skipping
6185 	     mode first, and if we are still in the skipping mode at its end,
6186 	     process the else block too.  */
6187 	  r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
6188 					    overflow_p, jump_target);
6189 	  /* It's possible that we found the label in the then block.  But
6190 	     it could have been followed by another jumping statement, e.g.
6191 	     say we're looking for case 1:
6192 	      if (cond)
6193 		{
6194 		  // skipped statements
6195 		  case 1:; // clears up *jump_target
6196 		  return 1; // and sets it to a RETURN_EXPR
6197 		}
6198 	      else { ... }
6199 	     in which case we need not go looking to the else block.
6200 	     (goto is not allowed in a constexpr function.)  */
6201 	  if (*jump_target == orig_jump)
6202 	    {
6203 	      arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
6204 		     ? TREE_OPERAND (t, 2) : void_node);
6205 	      r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
6206 						overflow_p, jump_target);
6207 	    }
6208 	  break;
6209 	}
6210       r = cxx_eval_conditional_expression (ctx, t, lval,
6211 					   non_constant_p, overflow_p,
6212 					   jump_target);
6213       break;
6214     case VEC_COND_EXPR:
6215       r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
6216 						  overflow_p);
6217       break;
6218 
6219     case CONSTRUCTOR:
6220       if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
6221 	{
6222 	  /* Don't re-process a constant CONSTRUCTOR, but do fold it to
6223 	     VECTOR_CST if applicable.  */
6224 	  verify_constructor_flags (t);
6225 	  if (TREE_CONSTANT (t))
6226 	    return fold (t);
6227 	}
6228       r = cxx_eval_bare_aggregate (ctx, t, lval,
6229 				   non_constant_p, overflow_p);
6230       break;
6231 
6232     case VEC_INIT_EXPR:
6233       /* We can get this in a defaulted constructor for a class with a
6234 	 non-static data member of array type.  Either the initializer will
6235 	 be NULL, meaning default-initialization, or it will be an lvalue
6236 	 or xvalue of the same type, meaning direct-initialization from the
6237 	 corresponding member.  */
6238       r = cxx_eval_vec_init (ctx, t, lval,
6239 			     non_constant_p, overflow_p);
6240       break;
6241 
6242     case VEC_PERM_EXPR:
6243       r = cxx_eval_trinary_expression (ctx, t, lval,
6244 				       non_constant_p, overflow_p);
6245       break;
6246 
6247     case NOP_EXPR:
6248       if (REINTERPRET_CAST_P (t))
6249 	{
6250 	  if (!ctx->quiet)
6251 	    error_at (loc,
6252 		      "%<reinterpret_cast%> is not a constant expression");
6253 	  *non_constant_p = true;
6254 	  return t;
6255 	}
6256       /* FALLTHROUGH.  */
6257     case CONVERT_EXPR:
6258     case VIEW_CONVERT_EXPR:
6259     case UNARY_PLUS_EXPR:
6260       {
6261 	tree oldop = TREE_OPERAND (t, 0);
6262 
6263 	tree op = cxx_eval_constant_expression (ctx, oldop,
6264 						lval,
6265 						non_constant_p, overflow_p);
6266 	if (*non_constant_p)
6267 	  return t;
6268 	tree type = TREE_TYPE (t);
6269 
6270 	if (VOID_TYPE_P (type))
6271 	  return void_node;
6272 
6273 	if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
6274 	  op = cplus_expand_constant (op);
6275 
6276 	if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
6277 	  {
6278 	    if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
6279 		&& !can_convert_qual (type, op))
6280 	      op = cplus_expand_constant (op);
6281 	    return cp_fold_convert (type, op);
6282 	  }
6283 
6284 	if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
6285 	  {
6286 	    if (integer_zerop (op))
6287 	      {
6288 		if (TYPE_REF_P (type))
6289 		  {
6290 		    if (!ctx->quiet)
6291 		      error_at (loc,
6292 				"dereferencing a null pointer");
6293 		    *non_constant_p = true;
6294 		    return t;
6295 		  }
6296 		else if (TYPE_PTR_P (TREE_TYPE (op)))
6297 		  {
6298 		    tree from = TREE_TYPE (op);
6299 
6300 		    if (!can_convert (type, from, tf_none))
6301 		      {
6302 			if (!ctx->quiet)
6303 			  error_at (loc,
6304 				    "conversion of %qT null pointer to %qT "
6305 				    "is not a constant expression",
6306 				    from, type);
6307 			*non_constant_p = true;
6308 			return t;
6309 		      }
6310 		  }
6311 	      }
6312 	    else
6313 	      {
6314 		/* This detects for example:
6315 		     reinterpret_cast<void*>(sizeof 0)
6316 		*/
6317 		if (!ctx->quiet)
6318 		  error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
6319 			    "a constant expression",
6320 			    type, op);
6321 		*non_constant_p = true;
6322 		return t;
6323 	      }
6324 	  }
6325 
6326 	if (INDIRECT_TYPE_P (type)
6327 	    && TREE_CODE (op) == NOP_EXPR
6328 	    && TREE_TYPE (op) == ptr_type_node
6329 	    && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
6330 	    && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
6331 	    && DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
6332 					0)) == heap_uninit_identifier)
6333 	  {
6334 	    tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
6335 	    tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
6336 	    tree elt_type = TREE_TYPE (type);
6337 	    tree cookie_size = NULL_TREE;
6338 	    if (TREE_CODE (elt_type) == RECORD_TYPE
6339 		&& TYPE_NAME (elt_type) == heap_identifier)
6340 	      {
6341 		tree fld1 = TYPE_FIELDS (elt_type);
6342 		tree fld2 = DECL_CHAIN (fld1);
6343 		elt_type = TREE_TYPE (TREE_TYPE (fld2));
6344 		cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
6345 	      }
6346 	    DECL_NAME (var) = heap_identifier;
6347 	    TREE_TYPE (var)
6348 	      = build_new_constexpr_heap_type (elt_type, cookie_size,
6349 					       var_size);
6350 	    TREE_TYPE (TREE_OPERAND (op, 0))
6351 	      = build_pointer_type (TREE_TYPE (var));
6352 	  }
6353 
6354 	if (op == oldop && tcode != UNARY_PLUS_EXPR)
6355 	  /* We didn't fold at the top so we could check for ptr-int
6356 	     conversion.  */
6357 	  return fold (t);
6358 
6359 	tree sop;
6360 
6361 	/* Handle an array's bounds having been deduced after we built
6362 	   the wrapping expression.  */
6363 	if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
6364 	  r = op;
6365 	else if (sop = tree_strip_nop_conversions (op),
6366 		 sop != op && (same_type_ignoring_tlq_and_bounds_p
6367 			       (type, TREE_TYPE (sop))))
6368 	  r = sop;
6369 	else if (tcode == UNARY_PLUS_EXPR)
6370 	  r = fold_convert (TREE_TYPE (t), op);
6371 	else
6372 	  r = fold_build1 (tcode, type, op);
6373 
6374 	/* Conversion of an out-of-range value has implementation-defined
6375 	   behavior; the language considers it different from arithmetic
6376 	   overflow, which is undefined.  */
6377 	if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
6378 	  TREE_OVERFLOW (r) = false;
6379       }
6380       break;
6381 
6382     case EMPTY_CLASS_EXPR:
6383       /* This is good enough for a function argument that might not get
6384 	 used, and they can't do anything with it, so just return it.  */
6385       return t;
6386 
6387     case STATEMENT_LIST:
6388       new_ctx = *ctx;
6389       new_ctx.ctor = new_ctx.object = NULL_TREE;
6390       return cxx_eval_statement_list (&new_ctx, t,
6391 				      non_constant_p, overflow_p, jump_target);
6392 
6393     case BIND_EXPR:
6394       return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
6395 					   lval,
6396 					   non_constant_p, overflow_p,
6397 					   jump_target);
6398 
6399     case PREINCREMENT_EXPR:
6400     case POSTINCREMENT_EXPR:
6401     case PREDECREMENT_EXPR:
6402     case POSTDECREMENT_EXPR:
6403       return cxx_eval_increment_expression (ctx, t,
6404 					    lval, non_constant_p, overflow_p);
6405 
6406     case LAMBDA_EXPR:
6407     case NEW_EXPR:
6408     case VEC_NEW_EXPR:
6409     case DELETE_EXPR:
6410     case VEC_DELETE_EXPR:
6411     case THROW_EXPR:
6412     case MODOP_EXPR:
6413       /* GCC internal stuff.  */
6414     case VA_ARG_EXPR:
6415     case NON_DEPENDENT_EXPR:
6416     case BASELINK:
6417     case OFFSET_REF:
6418       if (!ctx->quiet)
6419 	error_at (loc, "expression %qE is not a constant expression", t);
6420       *non_constant_p = true;
6421       break;
6422 
6423     case OBJ_TYPE_REF:
6424       /* Virtual function lookup.  We don't need to do anything fancy.  */
6425       return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
6426 					   lval, non_constant_p, overflow_p);
6427 
6428     case PLACEHOLDER_EXPR:
6429       /* Use of the value or address of the current object.  */
6430       if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
6431 	{
6432 	  if (TREE_CODE (ctor) == CONSTRUCTOR)
6433 	    return ctor;
6434 	  else
6435 	    return cxx_eval_constant_expression (ctx, ctor, lval,
6436 						 non_constant_p, overflow_p);
6437 	}
6438       /* A placeholder without a referent.  We can get here when
6439 	 checking whether NSDMIs are noexcept, or in massage_init_elt;
6440 	 just say it's non-constant for now.  */
6441       gcc_assert (ctx->quiet);
6442       *non_constant_p = true;
6443       break;
6444 
6445     case EXIT_EXPR:
6446       {
6447 	tree cond = TREE_OPERAND (t, 0);
6448 	cond = cxx_eval_constant_expression (ctx, cond, /*lval*/false,
6449 					     non_constant_p, overflow_p);
6450 	VERIFY_CONSTANT (cond);
6451 	if (integer_nonzerop (cond))
6452 	  *jump_target = t;
6453       }
6454       break;
6455 
6456     case GOTO_EXPR:
6457       *jump_target = TREE_OPERAND (t, 0);
6458       gcc_assert (breaks (jump_target) || continues (jump_target)
6459 		  /* Allow for jumping to a cdtor_label.  */
6460 		  || returns (jump_target));
6461       break;
6462 
6463     case LOOP_EXPR:
6464     case DO_STMT:
6465     case WHILE_STMT:
6466     case FOR_STMT:
6467       cxx_eval_loop_expr (ctx, t,
6468 			  non_constant_p, overflow_p, jump_target);
6469       break;
6470 
6471     case SWITCH_EXPR:
6472     case SWITCH_STMT:
6473       cxx_eval_switch_expr (ctx, t,
6474 			    non_constant_p, overflow_p, jump_target);
6475       break;
6476 
6477     case REQUIRES_EXPR:
6478       /* It's possible to get a requires-expression in a constant
6479          expression. For example:
6480 
6481              template<typename T> concept bool C() {
6482                return requires (T t) { t; };
6483              }
6484 
6485              template<typename T> requires !C<T>() void f(T);
6486 
6487          Normalization leaves f with the associated constraint
6488          '!requires (T t) { ... }' which is not transformed into
6489          a constraint.  */
6490       if (!processing_template_decl)
6491         return satisfy_constraint_expression (t);
6492       else
6493         *non_constant_p = true;
6494       return t;
6495 
6496     case ANNOTATE_EXPR:
6497       r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6498 					lval,
6499 					non_constant_p, overflow_p,
6500 					jump_target);
6501       break;
6502 
6503     case USING_STMT:
6504       r = void_node;
6505       break;
6506 
6507     case TEMPLATE_ID_EXPR:
6508       {
6509         /* We can evaluate template-id that refers to a concept only if
6510 	   the template arguments are non-dependent.  */
6511 	tree id = unpack_concept_check (t);
6512 	tree tmpl = TREE_OPERAND (id, 0);
6513 	if (!concept_definition_p (tmpl))
6514 	  internal_error ("unexpected template-id %qE", t);
6515 
6516 	if (function_concept_p (tmpl))
6517 	  {
6518 	    if (!ctx->quiet)
6519 	      error_at (cp_expr_loc_or_input_loc (t),
6520 			"function concept must be called");
6521 	    r = error_mark_node;
6522 	    break;
6523 	  }
6524 
6525 	if (!processing_template_decl)
6526 	  r = evaluate_concept_check (t, tf_warning_or_error);
6527 	else
6528 	  *non_constant_p = true;
6529 
6530 	break;
6531       }
6532 
6533     case ASM_EXPR:
6534       if (!ctx->quiet)
6535 	inline_asm_in_constexpr_error (loc);
6536       *non_constant_p = true;
6537       return t;
6538 
6539     default:
6540       if (STATEMENT_CODE_P (TREE_CODE (t)))
6541 	{
6542 	  /* This function doesn't know how to deal with pre-genericize
6543 	     statements; this can only happen with statement-expressions,
6544 	     so for now just fail.  */
6545 	  if (!ctx->quiet)
6546 	    error_at (EXPR_LOCATION (t),
6547 		      "statement is not a constant expression");
6548 	}
6549       else
6550 	internal_error ("unexpected expression %qE of kind %s", t,
6551 			get_tree_code_name (TREE_CODE (t)));
6552       *non_constant_p = true;
6553       break;
6554     }
6555 
6556   if (r == error_mark_node)
6557     *non_constant_p = true;
6558 
6559   if (*non_constant_p)
6560     return t;
6561   else
6562     return r;
6563 }
6564 
6565 /* P0859: A function is needed for constant evaluation if it is a constexpr
6566    function that is named by an expression ([basic.def.odr]) that is
6567    potentially constant evaluated.
6568 
6569    So we need to instantiate any constexpr functions mentioned by the
6570    expression even if the definition isn't needed for evaluating the
6571    expression.  */
6572 
6573 static tree
instantiate_cx_fn_r(tree * tp,int * walk_subtrees,void *)6574 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
6575 {
6576   if (TREE_CODE (*tp) == FUNCTION_DECL
6577       && DECL_DECLARED_CONSTEXPR_P (*tp)
6578       && !DECL_INITIAL (*tp)
6579       && !trivial_fn_p (*tp)
6580       && DECL_TEMPLOID_INSTANTIATION (*tp))
6581     {
6582       ++function_depth;
6583       instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
6584       --function_depth;
6585     }
6586   else if (TREE_CODE (*tp) == CALL_EXPR
6587 	   || TREE_CODE (*tp) == AGGR_INIT_EXPR)
6588     {
6589       if (EXPR_HAS_LOCATION (*tp))
6590 	input_location = EXPR_LOCATION (*tp);
6591     }
6592 
6593   if (!EXPR_P (*tp))
6594     *walk_subtrees = 0;
6595 
6596   return NULL_TREE;
6597 }
6598 
6599 static void
instantiate_constexpr_fns(tree t)6600 instantiate_constexpr_fns (tree t)
6601 {
6602   location_t loc = input_location;
6603   cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
6604   input_location = loc;
6605 }
6606 
6607 /* Look for heap variables in the expression *TP.  */
6608 
6609 static tree
find_heap_var_refs(tree * tp,int * walk_subtrees,void *)6610 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
6611 {
6612   if (VAR_P (*tp)
6613       && (DECL_NAME (*tp) == heap_uninit_identifier
6614 	  || DECL_NAME (*tp) == heap_identifier
6615 	  || DECL_NAME (*tp) == heap_deleted_identifier))
6616     return *tp;
6617 
6618   if (TYPE_P (*tp))
6619     *walk_subtrees = 0;
6620   return NULL_TREE;
6621 }
6622 
6623 /* Find immediate function decls in *TP if any.  */
6624 
6625 static tree
find_immediate_fndecl(tree * tp,int *,void *)6626 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
6627 {
6628   if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
6629     return *tp;
6630   return NULL_TREE;
6631 }
6632 
6633 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
6634    STRICT has the same sense as for constant_value_1: true if we only allow
6635    conforming C++ constant expressions, or false if we want a constant value
6636    even if it doesn't conform.
6637    MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
6638    per P0595 even when ALLOW_NON_CONSTANT is true.
6639    CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
6640    OBJECT must be non-NULL in that case.  */
6641 
6642 static tree
6643 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
6644 				  bool strict = true,
6645 				  bool manifestly_const_eval = false,
6646 				  bool constexpr_dtor = false,
6647 				  tree object = NULL_TREE,
6648 				  bool uid_sensitive = false)
6649 {
6650   auto_timevar time (TV_CONSTEXPR);
6651 
6652   bool non_constant_p = false;
6653   bool overflow_p = false;
6654 
6655   if (BRACE_ENCLOSED_INITIALIZER_P (t))
6656     {
6657       gcc_checking_assert (allow_non_constant);
6658       return t;
6659     }
6660 
6661   constexpr_global_ctx global_ctx;
6662   constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
6663 			allow_non_constant, strict,
6664 			manifestly_const_eval || !allow_non_constant,
6665 			uid_sensitive };
6666 
6667   /* Turn off -frounding-math for manifestly constant evaluation.  */
6668   warning_sentinel rm (flag_rounding_math, ctx.manifestly_const_eval);
6669   tree type = initialized_type (t);
6670   tree r = t;
6671   bool is_consteval = false;
6672   if (VOID_TYPE_P (type))
6673     {
6674       if (constexpr_dtor)
6675 	/* Used for destructors of array elements.  */
6676 	type = TREE_TYPE (object);
6677       else
6678 	{
6679 	  if (cxx_dialect < cxx2a)
6680 	    return t;
6681 	  if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
6682 	    return t;
6683 	  /* Calls to immediate functions returning void need to be
6684 	     evaluated.  */
6685 	  tree fndecl = cp_get_callee_fndecl_nofold (t);
6686 	  if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
6687 	    return t;
6688 	  else
6689 	    is_consteval = true;
6690 	}
6691     }
6692   else if (cxx_dialect >= cxx2a
6693 	   && (TREE_CODE (t) == CALL_EXPR
6694 	       || TREE_CODE (t) == AGGR_INIT_EXPR
6695 	       || TREE_CODE (t) == TARGET_EXPR))
6696     {
6697       /* For non-concept checks, determine if it is consteval.  */
6698       if (!concept_check_p (t))
6699 	{
6700 	  tree x = t;
6701 	  if (TREE_CODE (x) == TARGET_EXPR)
6702 	    x = TARGET_EXPR_INITIAL (x);
6703 	  tree fndecl = cp_get_callee_fndecl_nofold (x);
6704 	  if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
6705 	    is_consteval = true;
6706 	}
6707     }
6708   if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
6709     {
6710       /* In C++14 an NSDMI can participate in aggregate initialization,
6711 	 and can refer to the address of the object being initialized, so
6712 	 we need to pass in the relevant VAR_DECL if we want to do the
6713 	 evaluation in a single pass.  The evaluation will dynamically
6714 	 update ctx.values for the VAR_DECL.  We use the same strategy
6715 	 for C++11 constexpr constructors that refer to the object being
6716 	 initialized.  */
6717       if (constexpr_dtor)
6718 	{
6719 	  gcc_assert (object && VAR_P (object));
6720 	  gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
6721 	  gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
6722 	  if (error_operand_p (DECL_INITIAL (object)))
6723 	    return t;
6724 	  ctx.ctor = unshare_expr (DECL_INITIAL (object));
6725 	  TREE_READONLY (ctx.ctor) = false;
6726 	  /* Temporarily force decl_really_constant_value to return false
6727 	     for it, we want to use ctx.ctor for the current value instead.  */
6728 	  DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
6729 	}
6730       else
6731 	{
6732 	  ctx.ctor = build_constructor (type, NULL);
6733 	  CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
6734 	}
6735       if (!object)
6736 	{
6737 	  if (TREE_CODE (t) == TARGET_EXPR)
6738 	    object = TARGET_EXPR_SLOT (t);
6739 	  else if (TREE_CODE (t) == AGGR_INIT_EXPR)
6740 	    object = AGGR_INIT_EXPR_SLOT (t);
6741 	}
6742       ctx.object = object;
6743       if (object)
6744 	gcc_assert (same_type_ignoring_top_level_qualifiers_p
6745 		    (type, TREE_TYPE (object)));
6746       if (object && DECL_P (object))
6747 	global_ctx.values.put (object, ctx.ctor);
6748       if (TREE_CODE (r) == TARGET_EXPR)
6749 	/* Avoid creating another CONSTRUCTOR when we expand the
6750 	   TARGET_EXPR.  */
6751 	r = TARGET_EXPR_INITIAL (r);
6752     }
6753 
6754   auto_vec<tree, 16> cleanups;
6755   global_ctx.cleanups = &cleanups;
6756 
6757   if (!uid_sensitive)
6758     instantiate_constexpr_fns (r);
6759   r = cxx_eval_constant_expression (&ctx, r,
6760 				    false, &non_constant_p, &overflow_p);
6761 
6762   if (!constexpr_dtor)
6763     verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
6764   else
6765     DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
6766 
6767   unsigned int i;
6768   tree cleanup;
6769   /* Evaluate the cleanups.  */
6770   FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
6771     cxx_eval_constant_expression (&ctx, cleanup, false,
6772 				  &non_constant_p, &overflow_p);
6773 
6774   /* Mutable logic is a bit tricky: we want to allow initialization of
6775      constexpr variables with mutable members, but we can't copy those
6776      members to another constexpr variable.  */
6777   if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
6778     {
6779       if (!allow_non_constant)
6780 	error ("%qE is not a constant expression because it refers to "
6781 	       "mutable subobjects of %qT", t, type);
6782       non_constant_p = true;
6783     }
6784 
6785   if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
6786     {
6787       if (!allow_non_constant)
6788 	error ("%qE is not a constant expression because it refers to "
6789 	       "an incompletely initialized variable", t);
6790       TREE_CONSTANT (r) = false;
6791       non_constant_p = true;
6792     }
6793 
6794   if (!global_ctx.heap_vars.is_empty ())
6795     {
6796       tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
6797 						       NULL);
6798       unsigned int i;
6799       if (heap_var)
6800 	{
6801 	  if (!allow_non_constant && !non_constant_p)
6802 	    error_at (DECL_SOURCE_LOCATION (heap_var),
6803 		      "%qE is not a constant expression because it refers to "
6804 		      "a result of %<operator new%>", t);
6805 	  r = t;
6806 	  non_constant_p = true;
6807 	}
6808       FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
6809 	{
6810 	  if (DECL_NAME (heap_var) != heap_deleted_identifier)
6811 	    {
6812 	      if (!allow_non_constant && !non_constant_p)
6813 		error_at (DECL_SOURCE_LOCATION (heap_var),
6814 			  "%qE is not a constant expression because allocated "
6815 			  "storage has not been deallocated", t);
6816 	      r = t;
6817 	      non_constant_p = true;
6818 	    }
6819 	  varpool_node::get (heap_var)->remove ();
6820 	}
6821     }
6822 
6823   /* Check that immediate invocation does not return an expression referencing
6824      any immediate function decls.  They need to be allowed while parsing
6825      immediate functions, but can't leak outside of them.  */
6826   if (is_consteval
6827       && t != r
6828       && (current_function_decl == NULL_TREE
6829 	  || !DECL_IMMEDIATE_FUNCTION_P (current_function_decl)))
6830     if (tree immediate_fndecl
6831 	= cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
6832 					   NULL))
6833     {
6834       if (!allow_non_constant && !non_constant_p)
6835 	error_at (cp_expr_loc_or_input_loc (t),
6836 		  "immediate evaluation returns address of immediate "
6837 		  "function %qD", immediate_fndecl);
6838       r = t;
6839       non_constant_p = true;
6840     }
6841 
6842   /* Technically we should check this for all subexpressions, but that
6843      runs into problems with our internal representation of pointer
6844      subtraction and the 5.19 rules are still in flux.  */
6845   if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
6846       && ARITHMETIC_TYPE_P (TREE_TYPE (r))
6847       && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
6848     {
6849       if (!allow_non_constant)
6850 	error ("conversion from pointer type %qT "
6851 	       "to arithmetic type %qT in a constant expression",
6852 	       TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
6853       non_constant_p = true;
6854     }
6855 
6856   if (!non_constant_p && overflow_p)
6857     non_constant_p = true;
6858 
6859   /* Unshare the result.  */
6860   bool should_unshare = true;
6861   if (r == t || (TREE_CODE (t) == TARGET_EXPR
6862 		 && TARGET_EXPR_INITIAL (t) == r))
6863     should_unshare = false;
6864 
6865   if (non_constant_p && !allow_non_constant)
6866     return error_mark_node;
6867   else if (constexpr_dtor)
6868     return r;
6869   else if (non_constant_p && TREE_CONSTANT (r))
6870     {
6871       /* If __builtin_is_constant_evaluated () was evaluated to true
6872 	 and the result is not a valid constant expression, we need to
6873 	 punt.  */
6874       if (manifestly_const_eval)
6875 	return cxx_eval_outermost_constant_expr (t, true, strict,
6876 						 false, false, object);
6877       /* This isn't actually constant, so unset TREE_CONSTANT.
6878 	 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
6879 	 it to be set if it is invariant address, even when it is not
6880 	 a valid C++ constant expression.  Wrap it with a NOP_EXPR
6881 	 instead.  */
6882       if (EXPR_P (r) && TREE_CODE (r) != ADDR_EXPR)
6883 	r = copy_node (r);
6884       else if (TREE_CODE (r) == CONSTRUCTOR)
6885 	r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
6886       else
6887 	r = build_nop (TREE_TYPE (r), r);
6888       TREE_CONSTANT (r) = false;
6889     }
6890   else if (non_constant_p)
6891     return t;
6892 
6893   if (should_unshare)
6894     r = unshare_expr (r);
6895 
6896   if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
6897     {
6898       r = adjust_temp_type (type, r);
6899       if (TREE_CODE (t) == TARGET_EXPR
6900 	  && TARGET_EXPR_INITIAL (t) == r)
6901 	return t;
6902       else if (TREE_CODE (t) != CONSTRUCTOR)
6903 	{
6904 	  r = get_target_expr_sfinae (r, tf_warning_or_error | tf_no_cleanup);
6905 	  TREE_CONSTANT (r) = true;
6906 	}
6907     }
6908 
6909   return r;
6910 }
6911 
6912 /* If T represents a constant expression returns its reduced value.
6913    Otherwise return error_mark_node.  If T is dependent, then
6914    return NULL.  */
6915 
6916 tree
cxx_constant_value(tree t,tree decl)6917 cxx_constant_value (tree t, tree decl)
6918 {
6919   return cxx_eval_outermost_constant_expr (t, false, true, true, false, decl);
6920 }
6921 
6922 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
6923    of constexpr variables.  The actual initializer of DECL is not modified.  */
6924 
6925 void
cxx_constant_dtor(tree t,tree decl)6926 cxx_constant_dtor (tree t, tree decl)
6927 {
6928   cxx_eval_outermost_constant_expr (t, false, true, true, true, decl);
6929 }
6930 
6931 /* Helper routine for fold_simple function.  Either return simplified
6932    expression T, otherwise NULL_TREE.
6933    In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
6934    even if we are within template-declaration.  So be careful on call, as in
6935    such case types can be undefined.  */
6936 
6937 static tree
fold_simple_1(tree t)6938 fold_simple_1 (tree t)
6939 {
6940   tree op1;
6941   enum tree_code code = TREE_CODE (t);
6942 
6943   switch (code)
6944     {
6945     case INTEGER_CST:
6946     case REAL_CST:
6947     case VECTOR_CST:
6948     case FIXED_CST:
6949     case COMPLEX_CST:
6950       return t;
6951 
6952     case SIZEOF_EXPR:
6953       return fold_sizeof_expr (t);
6954 
6955     case ABS_EXPR:
6956     case ABSU_EXPR:
6957     case CONJ_EXPR:
6958     case REALPART_EXPR:
6959     case IMAGPART_EXPR:
6960     case NEGATE_EXPR:
6961     case BIT_NOT_EXPR:
6962     case TRUTH_NOT_EXPR:
6963     case NOP_EXPR:
6964     case VIEW_CONVERT_EXPR:
6965     case CONVERT_EXPR:
6966     case FLOAT_EXPR:
6967     case FIX_TRUNC_EXPR:
6968     case FIXED_CONVERT_EXPR:
6969     case ADDR_SPACE_CONVERT_EXPR:
6970 
6971       op1 = TREE_OPERAND (t, 0);
6972 
6973       t = const_unop (code, TREE_TYPE (t), op1);
6974       if (!t)
6975 	return NULL_TREE;
6976 
6977       if (CONVERT_EXPR_CODE_P (code)
6978 	  && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
6979 	TREE_OVERFLOW (t) = false;
6980       return t;
6981 
6982     default:
6983       return NULL_TREE;
6984     }
6985 }
6986 
6987 /* If T is a simple constant expression, returns its simplified value.
6988    Otherwise returns T.  In contrast to maybe_constant_value we
6989    simplify only few operations on constant-expressions, and we don't
6990    try to simplify constexpressions.  */
6991 
6992 tree
fold_simple(tree t)6993 fold_simple (tree t)
6994 {
6995   if (processing_template_decl)
6996     return t;
6997 
6998   tree r = fold_simple_1 (t);
6999   if (r)
7000     return r;
7001 
7002   return t;
7003 }
7004 
7005 /* If T is a constant expression, returns its reduced value.
7006    Otherwise, if T does not have TREE_CONSTANT set, returns T.
7007    Otherwise, returns a version of T without TREE_CONSTANT.
7008    MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
7009    as per P0595.  UID_SENSITIVE is true if we can't do anything that
7010    would affect DECL_UID ordering.  */
7011 
7012 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
7013 
7014 tree
maybe_constant_value(tree t,tree decl,bool manifestly_const_eval,bool uid_sensitive)7015 maybe_constant_value (tree t, tree decl, bool manifestly_const_eval,
7016 		      bool uid_sensitive)
7017 {
7018   tree r;
7019 
7020   if (!is_nondependent_constant_expression (t))
7021     {
7022       if (TREE_OVERFLOW_P (t))
7023 	{
7024 	  t = build_nop (TREE_TYPE (t), t);
7025 	  TREE_CONSTANT (t) = false;
7026 	}
7027       return t;
7028     }
7029   else if (CONSTANT_CLASS_P (t))
7030     /* No caching or evaluation needed.  */
7031     return t;
7032 
7033   if (manifestly_const_eval)
7034     return cxx_eval_outermost_constant_expr (t, true, true, true, false,
7035 					     decl, uid_sensitive);
7036 
7037   if (cv_cache == NULL)
7038     cv_cache = hash_map<tree, tree>::create_ggc (101);
7039   if (tree *cached = cv_cache->get (t))
7040     {
7041       r = *cached;
7042       if (r != t)
7043 	{
7044 	  r = break_out_target_exprs (r, /*clear_loc*/true);
7045 	  protected_set_expr_location (r, EXPR_LOCATION (t));
7046 	}
7047       return r;
7048     }
7049 
7050   r = cxx_eval_outermost_constant_expr (t, true, true, false, false,
7051 					decl, uid_sensitive);
7052   gcc_checking_assert (r == t
7053 		       || CONVERT_EXPR_P (t)
7054 		       || TREE_CODE (t) == VIEW_CONVERT_EXPR
7055 		       || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
7056 		       || !cp_tree_equal (r, t));
7057   cv_cache->put (t, r);
7058   return r;
7059 }
7060 
7061 /* Dispose of the whole CV_CACHE.  */
7062 
7063 static void
clear_cv_cache(void)7064 clear_cv_cache (void)
7065 {
7066   if (cv_cache != NULL)
7067     cv_cache->empty ();
7068 }
7069 
7070 /* Dispose of the whole CV_CACHE, FOLD_CACHE, and satisfaction caches.  */
7071 
7072 void
clear_cv_and_fold_caches(bool sat)7073 clear_cv_and_fold_caches (bool sat /*= true*/)
7074 {
7075   clear_cv_cache ();
7076   clear_fold_cache ();
7077   if (sat)
7078     clear_satisfaction_cache ();
7079 }
7080 
7081 /* Internal function handling expressions in templates for
7082    fold_non_dependent_expr and fold_non_dependent_init.
7083 
7084    If we're in a template, but T isn't value dependent, simplify
7085    it.  We're supposed to treat:
7086 
7087      template <typename T> void f(T[1 + 1]);
7088      template <typename T> void f(T[2]);
7089 
7090    as two declarations of the same function, for example.  */
7091 
7092 static tree
fold_non_dependent_expr_template(tree t,tsubst_flags_t complain,bool manifestly_const_eval,tree object)7093 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
7094 				  bool manifestly_const_eval,
7095 				  tree object)
7096 {
7097   gcc_assert (processing_template_decl);
7098 
7099   if (is_nondependent_constant_expression (t))
7100     {
7101       processing_template_decl_sentinel s;
7102       t = instantiate_non_dependent_expr_internal (t, complain);
7103 
7104       if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
7105 	{
7106 	  if (TREE_OVERFLOW_P (t))
7107 	    {
7108 	      t = build_nop (TREE_TYPE (t), t);
7109 	      TREE_CONSTANT (t) = false;
7110 	    }
7111 	  return t;
7112 	}
7113 
7114       tree r = cxx_eval_outermost_constant_expr (t, true, true,
7115 						 manifestly_const_eval,
7116 						 false, object);
7117       /* cp_tree_equal looks through NOPs, so allow them.  */
7118       gcc_checking_assert (r == t
7119 			   || CONVERT_EXPR_P (t)
7120 			   || TREE_CODE (t) == VIEW_CONVERT_EXPR
7121 			   || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
7122 			   || !cp_tree_equal (r, t));
7123       return r;
7124     }
7125   else if (TREE_OVERFLOW_P (t))
7126     {
7127       t = build_nop (TREE_TYPE (t), t);
7128       TREE_CONSTANT (t) = false;
7129     }
7130 
7131   return t;
7132 }
7133 
7134 /* Like maybe_constant_value but first fully instantiate the argument.
7135 
7136    Note: this is equivalent to instantiate_non_dependent_expr_sfinae
7137    (t, complain) followed by maybe_constant_value but is more efficient,
7138    because it calls instantiation_dependent_expression_p and
7139    potential_constant_expression at most once.
7140    The manifestly_const_eval argument is passed to maybe_constant_value.
7141 
7142    Callers should generally pass their active complain, or if they are in a
7143    non-template, diagnosing context, they can use the default of
7144    tf_warning_or_error.  Callers that might be within a template context, don't
7145    have a complain parameter, and aren't going to remember the result for long
7146    (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
7147    appropriately.  */
7148 
7149 tree
fold_non_dependent_expr(tree t,tsubst_flags_t complain,bool manifestly_const_eval,tree object)7150 fold_non_dependent_expr (tree t,
7151 			 tsubst_flags_t complain /* = tf_warning_or_error */,
7152 			 bool manifestly_const_eval /* = false */,
7153 			 tree object /* = NULL_TREE */)
7154 {
7155   if (t == NULL_TREE)
7156     return NULL_TREE;
7157 
7158   if (processing_template_decl)
7159     return fold_non_dependent_expr_template (t, complain,
7160 					     manifestly_const_eval, object);
7161 
7162   return maybe_constant_value (t, object, manifestly_const_eval);
7163 }
7164 
7165 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
7166    return the original expression.  */
7167 
7168 tree
maybe_fold_non_dependent_expr(tree expr,tsubst_flags_t complain)7169 maybe_fold_non_dependent_expr (tree expr,
7170 			       tsubst_flags_t complain/*=tf_warning_or_error*/)
7171 {
7172   tree t = fold_non_dependent_expr (expr, complain);
7173   if (t && TREE_CONSTANT (t))
7174     return t;
7175 
7176   return expr;
7177 }
7178 
7179 /* Like maybe_constant_init but first fully instantiate the argument.  */
7180 
7181 tree
fold_non_dependent_init(tree t,tsubst_flags_t complain,bool manifestly_const_eval,tree object)7182 fold_non_dependent_init (tree t,
7183 			 tsubst_flags_t complain /*=tf_warning_or_error*/,
7184 			 bool manifestly_const_eval /*=false*/,
7185 			 tree object /* = NULL_TREE */)
7186 {
7187   if (t == NULL_TREE)
7188     return NULL_TREE;
7189 
7190   if (processing_template_decl)
7191     {
7192       t = fold_non_dependent_expr_template (t, complain,
7193 					    manifestly_const_eval, object);
7194       /* maybe_constant_init does this stripping, so do it here too.  */
7195       if (TREE_CODE (t) == TARGET_EXPR)
7196 	{
7197 	  tree init = TARGET_EXPR_INITIAL (t);
7198 	  if (TREE_CODE (init) == CONSTRUCTOR)
7199 	    t = init;
7200 	}
7201       return t;
7202     }
7203 
7204   return maybe_constant_init (t, object, manifestly_const_eval);
7205 }
7206 
7207 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
7208    than wrapped in a TARGET_EXPR.
7209    ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
7210    MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
7211    per P0595 even when ALLOW_NON_CONSTANT is true.  */
7212 
7213 static tree
maybe_constant_init_1(tree t,tree decl,bool allow_non_constant,bool manifestly_const_eval)7214 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
7215 		       bool manifestly_const_eval)
7216 {
7217   if (!t)
7218     return t;
7219   if (TREE_CODE (t) == EXPR_STMT)
7220     t = TREE_OPERAND (t, 0);
7221   if (TREE_CODE (t) == CONVERT_EXPR
7222       && VOID_TYPE_P (TREE_TYPE (t)))
7223     t = TREE_OPERAND (t, 0);
7224   if (TREE_CODE (t) == INIT_EXPR)
7225     t = TREE_OPERAND (t, 1);
7226   if (TREE_CODE (t) == TARGET_EXPR)
7227     t = TARGET_EXPR_INITIAL (t);
7228   if (!is_nondependent_static_init_expression (t))
7229     /* Don't try to evaluate it.  */;
7230   else if (CONSTANT_CLASS_P (t) && allow_non_constant)
7231     /* No evaluation needed.  */;
7232   else
7233     t = cxx_eval_outermost_constant_expr (t, allow_non_constant,
7234 					  /*strict*/false,
7235 					  manifestly_const_eval, false, decl);
7236   if (TREE_CODE (t) == TARGET_EXPR)
7237     {
7238       tree init = TARGET_EXPR_INITIAL (t);
7239       if (TREE_CODE (init) == CONSTRUCTOR)
7240 	t = init;
7241     }
7242   return t;
7243 }
7244 
7245 /* Wrapper for maybe_constant_init_1 which permits non constants.  */
7246 
7247 tree
maybe_constant_init(tree t,tree decl,bool manifestly_const_eval)7248 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
7249 {
7250   return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
7251 }
7252 
7253 /* Wrapper for maybe_constant_init_1 which does not permit non constants.  */
7254 
7255 tree
cxx_constant_init(tree t,tree decl)7256 cxx_constant_init (tree t, tree decl)
7257 {
7258   return maybe_constant_init_1 (t, decl, false, true);
7259 }
7260 
7261 #if 0
7262 /* FIXME see ADDR_EXPR section in potential_constant_expression_1.  */
7263 /* Return true if the object referred to by REF has automatic or thread
7264    local storage.  */
7265 
7266 enum { ck_ok, ck_bad, ck_unknown };
7267 static int
7268 check_automatic_or_tls (tree ref)
7269 {
7270   machine_mode mode;
7271   poly_int64 bitsize, bitpos;
7272   tree offset;
7273   int volatilep = 0, unsignedp = 0;
7274   tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
7275 				   &mode, &unsignedp, &volatilep, false);
7276   duration_kind dk;
7277 
7278   /* If there isn't a decl in the middle, we don't know the linkage here,
7279      and this isn't a constant expression anyway.  */
7280   if (!DECL_P (decl))
7281     return ck_unknown;
7282   dk = decl_storage_duration (decl);
7283   return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
7284 }
7285 #endif
7286 
7287 /* Data structure for passing data from potential_constant_expression_1
7288    to check_for_return_continue via cp_walk_tree.  */
7289 struct check_for_return_continue_data {
7290   hash_set<tree> *pset;
7291   tree continue_stmt;
7292   tree break_stmt;
7293 };
7294 
7295 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
7296    called through cp_walk_tree.  Return the first RETURN_EXPR found, or note
7297    the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found.  */
7298 static tree
check_for_return_continue(tree * tp,int * walk_subtrees,void * data)7299 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
7300 {
7301   tree t = *tp, s, b;
7302   check_for_return_continue_data *d = (check_for_return_continue_data *) data;
7303   switch (TREE_CODE (t))
7304     {
7305     case RETURN_EXPR:
7306       return t;
7307 
7308     case CONTINUE_STMT:
7309       if (d->continue_stmt == NULL_TREE)
7310 	d->continue_stmt = t;
7311       break;
7312 
7313     case BREAK_STMT:
7314       if (d->break_stmt == NULL_TREE)
7315 	d->break_stmt = t;
7316       break;
7317 
7318 #define RECUR(x) \
7319       if (tree r = cp_walk_tree (&x, check_for_return_continue, data,	\
7320 				 d->pset))				\
7321 	return r
7322 
7323       /* For loops, walk subtrees manually, so that continue stmts found
7324 	 inside of the bodies of the loops are ignored.  */
7325     case DO_STMT:
7326       *walk_subtrees = 0;
7327       RECUR (DO_COND (t));
7328       s = d->continue_stmt;
7329       b = d->break_stmt;
7330       RECUR (DO_BODY (t));
7331       d->continue_stmt = s;
7332       d->break_stmt = b;
7333       break;
7334 
7335     case WHILE_STMT:
7336       *walk_subtrees = 0;
7337       RECUR (WHILE_COND (t));
7338       s = d->continue_stmt;
7339       b = d->break_stmt;
7340       RECUR (WHILE_BODY (t));
7341       d->continue_stmt = s;
7342       d->break_stmt = b;
7343       break;
7344 
7345     case FOR_STMT:
7346       *walk_subtrees = 0;
7347       RECUR (FOR_INIT_STMT (t));
7348       RECUR (FOR_COND (t));
7349       RECUR (FOR_EXPR (t));
7350       s = d->continue_stmt;
7351       b = d->break_stmt;
7352       RECUR (FOR_BODY (t));
7353       d->continue_stmt = s;
7354       d->break_stmt = b;
7355       break;
7356 
7357     case RANGE_FOR_STMT:
7358       *walk_subtrees = 0;
7359       RECUR (RANGE_FOR_EXPR (t));
7360       s = d->continue_stmt;
7361       b = d->break_stmt;
7362       RECUR (RANGE_FOR_BODY (t));
7363       d->continue_stmt = s;
7364       d->break_stmt = b;
7365       break;
7366 
7367     case SWITCH_STMT:
7368       *walk_subtrees = 0;
7369       RECUR (SWITCH_STMT_COND (t));
7370       b = d->break_stmt;
7371       RECUR (SWITCH_STMT_BODY (t));
7372       d->break_stmt = b;
7373       break;
7374 #undef RECUR
7375 
7376     case STATEMENT_LIST:
7377     case CONSTRUCTOR:
7378       break;
7379 
7380     default:
7381       if (!EXPR_P (t))
7382 	*walk_subtrees = 0;
7383       break;
7384     }
7385 
7386   return NULL_TREE;
7387 }
7388 
7389 /* Return true if T denotes a potentially constant expression.  Issue
7390    diagnostic as appropriate under control of FLAGS.  If WANT_RVAL is true,
7391    an lvalue-rvalue conversion is implied.  If NOW is true, we want to
7392    consider the expression in the current context, independent of constexpr
7393    substitution.
7394 
7395    C++0x [expr.const] used to say
7396 
7397    6 An expression is a potential constant expression if it is
7398      a constant expression where all occurrences of function
7399      parameters are replaced by arbitrary constant expressions
7400      of the appropriate type.
7401 
7402    2  A conditional expression is a constant expression unless it
7403       involves one of the following as a potentially evaluated
7404       subexpression (3.2), but subexpressions of logical AND (5.14),
7405       logical OR (5.15), and conditional (5.16) operations that are
7406       not evaluated are not considered.   */
7407 
7408 static bool
potential_constant_expression_1(tree t,bool want_rval,bool strict,bool now,tsubst_flags_t flags,tree * jump_target)7409 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
7410 				 tsubst_flags_t flags, tree *jump_target)
7411 {
7412 #define RECUR(T,RV) \
7413   potential_constant_expression_1 ((T), (RV), strict, now, flags, jump_target)
7414 
7415   enum { any = false, rval = true };
7416   int i;
7417   tree tmp;
7418 
7419   if (t == error_mark_node)
7420     return false;
7421   if (t == NULL_TREE)
7422     return true;
7423   location_t loc = cp_expr_loc_or_input_loc (t);
7424 
7425   if (*jump_target)
7426     /* If we are jumping, ignore everything.  This is simpler than the
7427        cxx_eval_constant_expression handling because we only need to be
7428        conservatively correct, and we don't necessarily have a constant value
7429        available, so we don't bother with switch tracking.  */
7430     return true;
7431 
7432   if (TREE_THIS_VOLATILE (t) && want_rval)
7433     {
7434       if (flags & tf_error)
7435 	error_at (loc, "lvalue-to-rvalue conversion of a volatile lvalue "
7436 		  "%qE with type %qT", t, TREE_TYPE (t));
7437       return false;
7438     }
7439   if (CONSTANT_CLASS_P (t))
7440     return true;
7441   if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
7442       && TREE_TYPE (t) == error_mark_node)
7443     return false;
7444 
7445   switch (TREE_CODE (t))
7446     {
7447     case FUNCTION_DECL:
7448     case BASELINK:
7449     case TEMPLATE_DECL:
7450     case OVERLOAD:
7451     case TEMPLATE_ID_EXPR:
7452     case LABEL_DECL:
7453     case LABEL_EXPR:
7454     case CASE_LABEL_EXPR:
7455     case PREDICT_EXPR:
7456     case CONST_DECL:
7457     case SIZEOF_EXPR:
7458     case ALIGNOF_EXPR:
7459     case OFFSETOF_EXPR:
7460     case NOEXCEPT_EXPR:
7461     case TEMPLATE_PARM_INDEX:
7462     case TRAIT_EXPR:
7463     case IDENTIFIER_NODE:
7464     case USERDEF_LITERAL:
7465       /* We can see a FIELD_DECL in a pointer-to-member expression.  */
7466     case FIELD_DECL:
7467     case RESULT_DECL:
7468     case USING_DECL:
7469     case USING_STMT:
7470     case PLACEHOLDER_EXPR:
7471     case REQUIRES_EXPR:
7472     case STATIC_ASSERT:
7473     case DEBUG_BEGIN_STMT:
7474       return true;
7475 
7476     case RETURN_EXPR:
7477       if (!RECUR (TREE_OPERAND (t, 0), any))
7478 	return false;
7479       /* FALLTHROUGH */
7480 
7481     case BREAK_STMT:
7482     case CONTINUE_STMT:
7483       *jump_target = t;
7484       return true;
7485 
7486     case PARM_DECL:
7487       if (now && want_rval)
7488 	{
7489 	  tree type = TREE_TYPE (t);
7490 	  if (dependent_type_p (type)
7491 	      || is_really_empty_class (type, /*ignore_vptr*/false))
7492 	    /* An empty class has no data to read.  */
7493 	    return true;
7494 	  if (flags & tf_error)
7495 	    error ("%qE is not a constant expression", t);
7496 	  return false;
7497 	}
7498       return true;
7499 
7500     case AGGR_INIT_EXPR:
7501     case CALL_EXPR:
7502       /* -- an invocation of a function other than a constexpr function
7503             or a constexpr constructor.  */
7504       {
7505         tree fun = get_function_named_in_call (t);
7506         const int nargs = call_expr_nargs (t);
7507 	i = 0;
7508 
7509 	if (fun == NULL_TREE)
7510 	  {
7511 	    /* Reset to allow the function to continue past the end
7512 	       of the block below.  Otherwise return early.  */
7513 	    bool bail = true;
7514 
7515 	    if (TREE_CODE (t) == CALL_EXPR
7516 		&& CALL_EXPR_FN (t) == NULL_TREE)
7517 	      switch (CALL_EXPR_IFN (t))
7518 		{
7519 		/* These should be ignored, they are optimized away from
7520 		   constexpr functions.  */
7521 		case IFN_UBSAN_NULL:
7522 		case IFN_UBSAN_BOUNDS:
7523 		case IFN_UBSAN_VPTR:
7524 		case IFN_FALLTHROUGH:
7525 		  return true;
7526 
7527 		case IFN_ADD_OVERFLOW:
7528 		case IFN_SUB_OVERFLOW:
7529 		case IFN_MUL_OVERFLOW:
7530 		case IFN_LAUNDER:
7531 		case IFN_VEC_CONVERT:
7532 		  bail = false;
7533 		  break;
7534 
7535 		default:
7536 		  break;
7537 		}
7538 
7539 	    if (bail)
7540 	      {
7541 		/* fold_call_expr can't do anything with IFN calls.  */
7542 		if (flags & tf_error)
7543 		  error_at (loc, "call to internal function %qE", t);
7544 		return false;
7545 	      }
7546 	  }
7547 
7548 	if (fun && is_overloaded_fn (fun))
7549 	  {
7550 	    if (TREE_CODE (fun) == FUNCTION_DECL)
7551 	      {
7552 		if (builtin_valid_in_constant_expr_p (fun))
7553 		  return true;
7554 		if (!DECL_DECLARED_CONSTEXPR_P (fun)
7555 		    /* Allow any built-in function; if the expansion
7556 		       isn't constant, we'll deal with that then.  */
7557 		    && !fndecl_built_in_p (fun)
7558 		    /* In C++2a, replaceable global allocation functions
7559 		       are constant expressions.  */
7560 		    && (!cxx_replaceable_global_alloc_fn (fun)
7561 			|| TREE_CODE (t) != CALL_EXPR
7562 			|| (!CALL_FROM_NEW_OR_DELETE_P (t)
7563 			    && (current_function_decl == NULL_TREE
7564 				|| !is_std_allocator_allocate
7565 						(current_function_decl))))
7566 		    /* Allow placement new in std::construct_at.  */
7567 		    && (!cxx_placement_new_fn (fun)
7568 			|| TREE_CODE (t) != CALL_EXPR
7569 			|| current_function_decl == NULL_TREE
7570 			|| !is_std_construct_at (current_function_decl))
7571 		    && !cxx_dynamic_cast_fn_p (fun))
7572 		  {
7573 		    if (flags & tf_error)
7574 		      {
7575 			error_at (loc, "call to non-%<constexpr%> function %qD",
7576 				  fun);
7577 			explain_invalid_constexpr_fn (fun);
7578 		      }
7579 		    return false;
7580 		  }
7581 		/* A call to a non-static member function takes the address
7582 		   of the object as the first argument.  But in a constant
7583 		   expression the address will be folded away, so look
7584 		   through it now.  */
7585 		if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
7586 		    && !DECL_CONSTRUCTOR_P (fun))
7587 		  {
7588 		    tree x = get_nth_callarg (t, 0);
7589 		    if (is_this_parameter (x))
7590 		      return true;
7591 		    /* Don't require an immediately constant value, as
7592 		       constexpr substitution might not use the value.  */
7593 		    bool sub_now = false;
7594 		    if (!potential_constant_expression_1 (x, rval, strict,
7595 							  sub_now, flags,
7596 							  jump_target))
7597 		      return false;
7598 		    i = 1;
7599 		  }
7600 	      }
7601 	    else
7602 	      {
7603 		if (!RECUR (fun, true))
7604 		  return false;
7605 		fun = get_first_fn (fun);
7606 	      }
7607 	    /* Skip initial arguments to base constructors.  */
7608 	    if (DECL_BASE_CONSTRUCTOR_P (fun))
7609 	      i = num_artificial_parms_for (fun);
7610 	    fun = DECL_ORIGIN (fun);
7611 	  }
7612 	else if (fun)
7613           {
7614 	    if (RECUR (fun, rval))
7615 	      /* Might end up being a constant function pointer.  */;
7616 	    else
7617 	      return false;
7618           }
7619         for (; i < nargs; ++i)
7620           {
7621             tree x = get_nth_callarg (t, i);
7622 	    /* In a template, reference arguments haven't been converted to
7623 	       REFERENCE_TYPE and we might not even know if the parameter
7624 	       is a reference, so accept lvalue constants too.  */
7625 	    bool rv = processing_template_decl ? any : rval;
7626 	    /* Don't require an immediately constant value, as constexpr
7627 	       substitution might not use the value of the argument.  */
7628 	    bool sub_now = false;
7629 	    if (!potential_constant_expression_1 (x, rv, strict,
7630 						  sub_now, flags, jump_target))
7631 	      return false;
7632           }
7633         return true;
7634       }
7635 
7636     case NON_LVALUE_EXPR:
7637       /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
7638             -- an lvalue of integral type that refers to a non-volatile
7639                const variable or static data member initialized with
7640                constant expressions, or
7641 
7642             -- an lvalue of literal type that refers to non-volatile
7643                object defined with constexpr, or that refers to a
7644                sub-object of such an object;  */
7645       return RECUR (TREE_OPERAND (t, 0), rval);
7646 
7647     case VAR_DECL:
7648       if (DECL_HAS_VALUE_EXPR_P (t))
7649 	{
7650 	  if (now && is_normal_capture_proxy (t))
7651 	    {
7652 	      /* -- in a lambda-expression, a reference to this or to a
7653 		 variable with automatic storage duration defined outside that
7654 		 lambda-expression, where the reference would be an
7655 		 odr-use.  */
7656 
7657 	      if (want_rval)
7658 		/* Since we're doing an lvalue-rvalue conversion, this might
7659 		   not be an odr-use, so evaluate the variable directly. */
7660 		return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
7661 
7662 	      if (flags & tf_error)
7663 		{
7664 		  tree cap = DECL_CAPTURED_VARIABLE (t);
7665 		  error ("lambda capture of %qE is not a constant expression",
7666 			 cap);
7667 		  if (decl_constant_var_p (cap))
7668 		    inform (input_location, "because it is used as a glvalue");
7669 		}
7670 	      return false;
7671 	    }
7672 	  return RECUR (DECL_VALUE_EXPR (t), rval);
7673 	}
7674       if (want_rval
7675 	  && !var_in_maybe_constexpr_fn (t)
7676 	  && !type_dependent_expression_p (t)
7677 	  && !decl_maybe_constant_var_p (t)
7678 	  && (strict
7679 	      || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
7680 	      || (DECL_INITIAL (t)
7681 		  && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
7682 	  && COMPLETE_TYPE_P (TREE_TYPE (t))
7683 	  && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7684         {
7685           if (flags & tf_error)
7686 	    non_const_var_error (loc, t);
7687           return false;
7688         }
7689       return true;
7690 
7691     case NOP_EXPR:
7692       if (REINTERPRET_CAST_P (t))
7693 	{
7694 	  if (flags & tf_error)
7695 	    error_at (loc, "%<reinterpret_cast%> is not a constant expression");
7696 	  return false;
7697 	}
7698       /* FALLTHRU */
7699     case CONVERT_EXPR:
7700     case VIEW_CONVERT_EXPR:
7701       /* -- a reinterpret_cast.  FIXME not implemented, and this rule
7702 	 may change to something more specific to type-punning (DR 1312).  */
7703       {
7704         tree from = TREE_OPERAND (t, 0);
7705 	if (location_wrapper_p (t))
7706 	  return (RECUR (from, want_rval));
7707 	if (INDIRECT_TYPE_P (TREE_TYPE (t)))
7708 	  {
7709 	    STRIP_ANY_LOCATION_WRAPPER (from);
7710 	    if (TREE_CODE (from) == INTEGER_CST
7711 		&& !integer_zerop (from))
7712 	      {
7713 		if (flags & tf_error)
7714 		  error_at (loc,
7715 			    "%<reinterpret_cast%> from integer to pointer");
7716 		return false;
7717 	      }
7718 	  }
7719         return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
7720       }
7721 
7722     case ADDRESSOF_EXPR:
7723       /* This is like ADDR_EXPR, except it won't form pointer-to-member.  */
7724       t = TREE_OPERAND (t, 0);
7725       goto handle_addr_expr;
7726 
7727     case ADDR_EXPR:
7728       /* -- a unary operator & that is applied to an lvalue that
7729             designates an object with thread or automatic storage
7730             duration;  */
7731       t = TREE_OPERAND (t, 0);
7732 
7733       if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
7734 	/* A pointer-to-member constant.  */
7735 	return true;
7736 
7737     handle_addr_expr:
7738 #if 0
7739       /* FIXME adjust when issue 1197 is fully resolved.  For now don't do
7740          any checking here, as we might dereference the pointer later.  If
7741          we remove this code, also remove check_automatic_or_tls.  */
7742       i = check_automatic_or_tls (t);
7743       if (i == ck_ok)
7744 	return true;
7745       if (i == ck_bad)
7746         {
7747           if (flags & tf_error)
7748             error ("address-of an object %qE with thread local or "
7749                    "automatic storage is not a constant expression", t);
7750           return false;
7751         }
7752 #endif
7753       return RECUR (t, any);
7754 
7755     case COMPONENT_REF:
7756     case ARROW_EXPR:
7757     case OFFSET_REF:
7758       /* -- a class member access unless its postfix-expression is
7759             of literal type or of pointer to literal type.  */
7760       /* This test would be redundant, as it follows from the
7761 	 postfix-expression being a potential constant expression.  */
7762       if (type_unknown_p (t))
7763 	return true;
7764       if (is_overloaded_fn (t))
7765 	/* In a template, a COMPONENT_REF of a function expresses ob.fn(),
7766 	   which uses ob as an lvalue.  */
7767 	want_rval = false;
7768       gcc_fallthrough ();
7769 
7770     case REALPART_EXPR:
7771     case IMAGPART_EXPR:
7772     case BIT_FIELD_REF:
7773       return RECUR (TREE_OPERAND (t, 0), want_rval);
7774 
7775     case EXPR_PACK_EXPANSION:
7776       return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
7777 
7778     case INDIRECT_REF:
7779       {
7780         tree x = TREE_OPERAND (t, 0);
7781         STRIP_NOPS (x);
7782         if (is_this_parameter (x) && !is_capture_proxy (x))
7783 	  {
7784 	    if (!var_in_maybe_constexpr_fn (x))
7785 	      {
7786 		if (flags & tf_error)
7787 		  error_at (loc, "use of %<this%> in a constant expression");
7788 		return false;
7789 	      }
7790 	    return true;
7791 	  }
7792 	return RECUR (x, rval);
7793       }
7794 
7795     case STATEMENT_LIST:
7796       {
7797 	tree_stmt_iterator i;
7798 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
7799 	  {
7800 	    if (!RECUR (tsi_stmt (i), any))
7801 	      return false;
7802 	  }
7803 	return true;
7804       }
7805       break;
7806 
7807     case MODIFY_EXPR:
7808       if (cxx_dialect < cxx14)
7809 	goto fail;
7810       if (!RECUR (TREE_OPERAND (t, 0), any))
7811 	return false;
7812       /* Just ignore clobbers.  */
7813       if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
7814 	return true;
7815       if (!RECUR (TREE_OPERAND (t, 1), rval))
7816 	return false;
7817       return true;
7818 
7819     case MODOP_EXPR:
7820       if (cxx_dialect < cxx14)
7821 	goto fail;
7822       if (!RECUR (TREE_OPERAND (t, 0), rval))
7823 	return false;
7824       if (!RECUR (TREE_OPERAND (t, 2), rval))
7825 	return false;
7826       return true;
7827 
7828     case DO_STMT:
7829       if (!RECUR (DO_COND (t), rval))
7830 	return false;
7831       if (!RECUR (DO_BODY (t), any))
7832 	return false;
7833       if (breaks (jump_target) || continues (jump_target))
7834 	*jump_target = NULL_TREE;
7835       return true;
7836 
7837     case FOR_STMT:
7838       if (!RECUR (FOR_INIT_STMT (t), any))
7839 	return false;
7840       tmp = FOR_COND (t);
7841       if (!RECUR (tmp, rval))
7842 	return false;
7843       if (tmp)
7844 	{
7845 	  if (!processing_template_decl)
7846 	    tmp = cxx_eval_outermost_constant_expr (tmp, true);
7847 	  /* If we couldn't evaluate the condition, it might not ever be
7848 	     true.  */
7849 	  if (!integer_onep (tmp))
7850 	    {
7851 	      /* Before returning true, check if the for body can contain
7852 		 a return.  */
7853 	      hash_set<tree> pset;
7854 	      check_for_return_continue_data data = { &pset, NULL_TREE,
7855 						      NULL_TREE };
7856 	      if (tree ret_expr
7857 		  = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
7858 				  &data, &pset))
7859 		*jump_target = ret_expr;
7860 	      return true;
7861 	    }
7862 	}
7863       if (!RECUR (FOR_EXPR (t), any))
7864 	return false;
7865       if (!RECUR (FOR_BODY (t), any))
7866 	return false;
7867       if (breaks (jump_target) || continues (jump_target))
7868 	*jump_target = NULL_TREE;
7869       return true;
7870 
7871     case RANGE_FOR_STMT:
7872       if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
7873 	return false;
7874       if (!RECUR (RANGE_FOR_EXPR (t), any))
7875 	return false;
7876       if (!RECUR (RANGE_FOR_BODY (t), any))
7877 	return false;
7878       if (breaks (jump_target) || continues (jump_target))
7879 	*jump_target = NULL_TREE;
7880       return true;
7881 
7882     case WHILE_STMT:
7883       tmp = WHILE_COND (t);
7884       if (!RECUR (tmp, rval))
7885 	return false;
7886       if (!processing_template_decl)
7887 	tmp = cxx_eval_outermost_constant_expr (tmp, true);
7888       /* If we couldn't evaluate the condition, it might not ever be true.  */
7889       if (!integer_onep (tmp))
7890 	{
7891 	  /* Before returning true, check if the while body can contain
7892 	     a return.  */
7893 	  hash_set<tree> pset;
7894 	  check_for_return_continue_data data = { &pset, NULL_TREE,
7895 						  NULL_TREE  };
7896 	  if (tree ret_expr
7897 	      = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
7898 			      &data, &pset))
7899 	    *jump_target = ret_expr;
7900 	  return true;
7901 	}
7902       if (!RECUR (WHILE_BODY (t), any))
7903 	return false;
7904       if (breaks (jump_target) || continues (jump_target))
7905 	*jump_target = NULL_TREE;
7906       return true;
7907 
7908     case SWITCH_STMT:
7909       if (!RECUR (SWITCH_STMT_COND (t), rval))
7910 	return false;
7911       /* FIXME we don't check SWITCH_STMT_BODY currently, because even
7912 	 unreachable labels would be checked and it is enough if there is
7913 	 a single switch cond value for which it is a valid constant
7914 	 expression.  We need to check if there are any RETURN_EXPRs
7915 	 or CONTINUE_STMTs inside of the body though, as in that case
7916 	 we need to set *jump_target.  */
7917       else
7918 	{
7919 	  hash_set<tree> pset;
7920 	  check_for_return_continue_data data = { &pset, NULL_TREE,
7921 						  NULL_TREE };
7922 	  if (tree ret_expr
7923 	      = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
7924 			      &data, &pset))
7925 	    /* The switch might return.  */
7926 	    *jump_target = ret_expr;
7927 	  else if (data.continue_stmt)
7928 	    /* The switch can't return, but might continue.  */
7929 	    *jump_target = data.continue_stmt;
7930 	}
7931       return true;
7932 
7933     case STMT_EXPR:
7934       return RECUR (STMT_EXPR_STMT (t), rval);
7935 
7936     case LAMBDA_EXPR:
7937       if (cxx_dialect >= cxx17)
7938 	/* In C++17 lambdas can be constexpr, don't give up yet.  */
7939 	return true;
7940       else if (flags & tf_error)
7941 	error_at (loc, "lambda-expression is not a constant expression "
7942 		  "before C++17");
7943       return false;
7944 
7945     case DYNAMIC_CAST_EXPR:
7946     case PSEUDO_DTOR_EXPR:
7947     case NEW_EXPR:
7948     case VEC_NEW_EXPR:
7949     case DELETE_EXPR:
7950     case VEC_DELETE_EXPR:
7951     case THROW_EXPR:
7952     case OMP_PARALLEL:
7953     case OMP_TASK:
7954     case OMP_FOR:
7955     case OMP_SIMD:
7956     case OMP_DISTRIBUTE:
7957     case OMP_TASKLOOP:
7958     case OMP_LOOP:
7959     case OMP_TEAMS:
7960     case OMP_TARGET_DATA:
7961     case OMP_TARGET:
7962     case OMP_SECTIONS:
7963     case OMP_ORDERED:
7964     case OMP_CRITICAL:
7965     case OMP_SINGLE:
7966     case OMP_SECTION:
7967     case OMP_MASTER:
7968     case OMP_TASKGROUP:
7969     case OMP_TARGET_UPDATE:
7970     case OMP_TARGET_ENTER_DATA:
7971     case OMP_TARGET_EXIT_DATA:
7972     case OMP_ATOMIC:
7973     case OMP_ATOMIC_READ:
7974     case OMP_ATOMIC_CAPTURE_OLD:
7975     case OMP_ATOMIC_CAPTURE_NEW:
7976     case OMP_DEPOBJ:
7977     case OACC_PARALLEL:
7978     case OACC_KERNELS:
7979     case OACC_SERIAL:
7980     case OACC_DATA:
7981     case OACC_HOST_DATA:
7982     case OACC_LOOP:
7983     case OACC_CACHE:
7984     case OACC_DECLARE:
7985     case OACC_ENTER_DATA:
7986     case OACC_EXIT_DATA:
7987     case OACC_UPDATE:
7988       /* GCC internal stuff.  */
7989     case VA_ARG_EXPR:
7990     case TRANSACTION_EXPR:
7991     case AT_ENCODE_EXPR:
7992     fail:
7993       if (flags & tf_error)
7994 	error_at (loc, "expression %qE is not a constant expression", t);
7995       return false;
7996 
7997     case ASM_EXPR:
7998       if (flags & tf_error)
7999 	inline_asm_in_constexpr_error (loc);
8000       return false;
8001 
8002     case OBJ_TYPE_REF:
8003       if (cxx_dialect >= cxx2a)
8004 	/* In C++2a virtual calls can be constexpr, don't give up yet.  */
8005 	return true;
8006       else if (flags & tf_error)
8007 	error_at (loc,
8008 		  "virtual functions cannot be %<constexpr%> before C++2a");
8009       return false;
8010 
8011     case TYPEID_EXPR:
8012       /* In C++20, a typeid expression whose operand is of polymorphic
8013 	 class type can be constexpr.  */
8014       {
8015         tree e = TREE_OPERAND (t, 0);
8016 	if (cxx_dialect < cxx2a
8017 	    && strict
8018 	    && !TYPE_P (e)
8019 	    && !type_dependent_expression_p (e)
8020 	    && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
8021           {
8022             if (flags & tf_error)
8023 	      error_at (loc, "%<typeid%> is not a constant expression "
8024 			"because %qE is of polymorphic type", e);
8025             return false;
8026           }
8027         return true;
8028       }
8029 
8030     case POINTER_DIFF_EXPR:
8031     case MINUS_EXPR:
8032       want_rval = true;
8033       goto binary;
8034 
8035     case LT_EXPR:
8036     case LE_EXPR:
8037     case GT_EXPR:
8038     case GE_EXPR:
8039     case EQ_EXPR:
8040     case NE_EXPR:
8041     case SPACESHIP_EXPR:
8042       want_rval = true;
8043       goto binary;
8044 
8045     case PREINCREMENT_EXPR:
8046     case POSTINCREMENT_EXPR:
8047     case PREDECREMENT_EXPR:
8048     case POSTDECREMENT_EXPR:
8049       if (cxx_dialect < cxx14)
8050 	goto fail;
8051       goto unary;
8052 
8053     case BIT_NOT_EXPR:
8054       /* A destructor.  */
8055       if (TYPE_P (TREE_OPERAND (t, 0)))
8056 	return true;
8057       /* fall through.  */
8058 
8059     case CONJ_EXPR:
8060     case SAVE_EXPR:
8061     case FIX_TRUNC_EXPR:
8062     case FLOAT_EXPR:
8063     case NEGATE_EXPR:
8064     case ABS_EXPR:
8065     case ABSU_EXPR:
8066     case TRUTH_NOT_EXPR:
8067     case FIXED_CONVERT_EXPR:
8068     case UNARY_PLUS_EXPR:
8069     case UNARY_LEFT_FOLD_EXPR:
8070     case UNARY_RIGHT_FOLD_EXPR:
8071     unary:
8072       return RECUR (TREE_OPERAND (t, 0), rval);
8073 
8074     case CAST_EXPR:
8075     case CONST_CAST_EXPR:
8076     case STATIC_CAST_EXPR:
8077     case REINTERPRET_CAST_EXPR:
8078     case IMPLICIT_CONV_EXPR:
8079       if (cxx_dialect < cxx11
8080 	  && !dependent_type_p (TREE_TYPE (t))
8081 	  && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
8082 	/* In C++98, a conversion to non-integral type can't be part of a
8083 	   constant expression.  */
8084 	{
8085 	  if (flags & tf_error)
8086 	    error_at (loc,
8087 		      "cast to non-integral type %qT in a constant expression",
8088 		      TREE_TYPE (t));
8089 	  return false;
8090 	}
8091       /* This might be a conversion from a class to a (potentially) literal
8092 	 type.  Let's consider it potentially constant since the conversion
8093 	 might be a constexpr user-defined conversion.  */
8094       else if (cxx_dialect >= cxx11
8095 	       && (dependent_type_p (TREE_TYPE (t))
8096 		   || !COMPLETE_TYPE_P (TREE_TYPE (t))
8097 		   || literal_type_p (TREE_TYPE (t)))
8098 	       && TREE_OPERAND (t, 0))
8099 	{
8100 	  tree type = TREE_TYPE (TREE_OPERAND (t, 0));
8101 	  /* If this is a dependent type, it could end up being a class
8102 	     with conversions.  */
8103 	  if (type == NULL_TREE || WILDCARD_TYPE_P (type))
8104 	    return true;
8105 	  /* Or a non-dependent class which has conversions.  */
8106 	  else if (CLASS_TYPE_P (type)
8107 		   && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
8108 	    return true;
8109 	}
8110 
8111       return (RECUR (TREE_OPERAND (t, 0),
8112 		     !TYPE_REF_P (TREE_TYPE (t))));
8113 
8114     case BIND_EXPR:
8115       return RECUR (BIND_EXPR_BODY (t), want_rval);
8116 
8117     case CLEANUP_POINT_EXPR:
8118     case MUST_NOT_THROW_EXPR:
8119     case TRY_CATCH_EXPR:
8120     case TRY_BLOCK:
8121     case EH_SPEC_BLOCK:
8122     case EXPR_STMT:
8123     case PAREN_EXPR:
8124     case NON_DEPENDENT_EXPR:
8125       /* For convenience.  */
8126     case LOOP_EXPR:
8127     case EXIT_EXPR:
8128       return RECUR (TREE_OPERAND (t, 0), want_rval);
8129 
8130     case DECL_EXPR:
8131       tmp = DECL_EXPR_DECL (t);
8132       if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
8133 	{
8134 	  if (TREE_STATIC (tmp))
8135 	    {
8136 	      if (flags & tf_error)
8137 		error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
8138 			  "%<static%> in %<constexpr%> context", tmp);
8139 	      return false;
8140 	    }
8141 	  else if (CP_DECL_THREAD_LOCAL_P (tmp))
8142 	    {
8143 	      if (flags & tf_error)
8144 		error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
8145 			  "%<thread_local%> in %<constexpr%> context", tmp);
8146 	      return false;
8147 	    }
8148 	  else if (!check_for_uninitialized_const_var
8149 		   (tmp, /*constexpr_context_p=*/true, flags))
8150 	    return false;
8151 	}
8152       return RECUR (tmp, want_rval);
8153 
8154     case TRY_FINALLY_EXPR:
8155       return (RECUR (TREE_OPERAND (t, 0), want_rval)
8156 	      && RECUR (TREE_OPERAND (t, 1), any));
8157 
8158     case SCOPE_REF:
8159       return RECUR (TREE_OPERAND (t, 1), want_rval);
8160 
8161     case TARGET_EXPR:
8162       if (!TARGET_EXPR_DIRECT_INIT_P (t)
8163 	  && !literal_type_p (TREE_TYPE (t)))
8164 	{
8165 	  if (flags & tf_error)
8166 	    {
8167 	      auto_diagnostic_group d;
8168 	      error_at (loc, "temporary of non-literal type %qT in a "
8169 			"constant expression", TREE_TYPE (t));
8170 	      explain_non_literal_class (TREE_TYPE (t));
8171 	    }
8172 	  return false;
8173 	}
8174       /* FALLTHRU */
8175     case INIT_EXPR:
8176       return RECUR (TREE_OPERAND (t, 1), rval);
8177 
8178     case CONSTRUCTOR:
8179       {
8180         vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
8181         constructor_elt *ce;
8182         for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
8183 	  if (!RECUR (ce->value, want_rval))
8184 	    return false;
8185 	return true;
8186       }
8187 
8188     case TREE_LIST:
8189       {
8190 	gcc_assert (TREE_PURPOSE (t) == NULL_TREE
8191 		    || DECL_P (TREE_PURPOSE (t)));
8192 	if (!RECUR (TREE_VALUE (t), want_rval))
8193 	  return false;
8194 	if (TREE_CHAIN (t) == NULL_TREE)
8195 	  return true;
8196 	return RECUR (TREE_CHAIN (t), want_rval);
8197       }
8198 
8199     case TRUNC_DIV_EXPR:
8200     case CEIL_DIV_EXPR:
8201     case FLOOR_DIV_EXPR:
8202     case ROUND_DIV_EXPR:
8203     case TRUNC_MOD_EXPR:
8204     case CEIL_MOD_EXPR:
8205     case ROUND_MOD_EXPR:
8206       {
8207 	tree denom = TREE_OPERAND (t, 1);
8208 	if (!RECUR (denom, rval))
8209 	  return false;
8210 	/* We can't call cxx_eval_outermost_constant_expr on an expression
8211 	   that hasn't been through instantiate_non_dependent_expr yet.  */
8212 	if (!processing_template_decl)
8213 	  denom = cxx_eval_outermost_constant_expr (denom, true);
8214 	if (integer_zerop (denom))
8215 	  {
8216 	    if (flags & tf_error)
8217 	      error ("division by zero is not a constant expression");
8218 	    return false;
8219 	  }
8220 	else
8221 	  {
8222 	    want_rval = true;
8223 	    return RECUR (TREE_OPERAND (t, 0), want_rval);
8224 	  }
8225       }
8226 
8227     case COMPOUND_EXPR:
8228       {
8229 	/* check_return_expr sometimes wraps a TARGET_EXPR in a
8230 	   COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
8231 	   introduced by build_call_a.  */
8232 	tree op0 = TREE_OPERAND (t, 0);
8233 	tree op1 = TREE_OPERAND (t, 1);
8234 	STRIP_NOPS (op1);
8235 	if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
8236 	    || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
8237 	  return RECUR (op0, want_rval);
8238 	else
8239 	  goto binary;
8240       }
8241 
8242       /* If the first operand is the non-short-circuit constant, look at
8243 	 the second operand; otherwise we only care about the first one for
8244 	 potentiality.  */
8245     case TRUTH_AND_EXPR:
8246     case TRUTH_ANDIF_EXPR:
8247       tmp = boolean_true_node;
8248       goto truth;
8249     case TRUTH_OR_EXPR:
8250     case TRUTH_ORIF_EXPR:
8251       tmp = boolean_false_node;
8252     truth:
8253       {
8254 	tree op = TREE_OPERAND (t, 0);
8255 	if (!RECUR (op, rval))
8256 	  return false;
8257 	if (!processing_template_decl)
8258 	  op = cxx_eval_outermost_constant_expr (op, true);
8259 	if (tree_int_cst_equal (op, tmp))
8260 	  return RECUR (TREE_OPERAND (t, 1), rval);
8261 	else
8262 	  return true;
8263       }
8264 
8265     case PLUS_EXPR:
8266     case MULT_EXPR:
8267     case POINTER_PLUS_EXPR:
8268     case RDIV_EXPR:
8269     case EXACT_DIV_EXPR:
8270     case MIN_EXPR:
8271     case MAX_EXPR:
8272     case LSHIFT_EXPR:
8273     case RSHIFT_EXPR:
8274     case LROTATE_EXPR:
8275     case RROTATE_EXPR:
8276     case BIT_IOR_EXPR:
8277     case BIT_XOR_EXPR:
8278     case BIT_AND_EXPR:
8279     case TRUTH_XOR_EXPR:
8280     case UNORDERED_EXPR:
8281     case ORDERED_EXPR:
8282     case UNLT_EXPR:
8283     case UNLE_EXPR:
8284     case UNGT_EXPR:
8285     case UNGE_EXPR:
8286     case UNEQ_EXPR:
8287     case LTGT_EXPR:
8288     case RANGE_EXPR:
8289     case COMPLEX_EXPR:
8290       want_rval = true;
8291       /* Fall through.  */
8292     case ARRAY_REF:
8293     case ARRAY_RANGE_REF:
8294     case MEMBER_REF:
8295     case DOTSTAR_EXPR:
8296     case MEM_REF:
8297     case BINARY_LEFT_FOLD_EXPR:
8298     case BINARY_RIGHT_FOLD_EXPR:
8299     binary:
8300       for (i = 0; i < 2; ++i)
8301 	if (!RECUR (TREE_OPERAND (t, i), want_rval))
8302 	  return false;
8303       return true;
8304 
8305     case VEC_PERM_EXPR:
8306      for (i = 0; i < 3; ++i)
8307       if (!RECUR (TREE_OPERAND (t, i), true))
8308 	return false;
8309      return true;
8310 
8311     case COND_EXPR:
8312       if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx2a)
8313 	{
8314 	  if (flags & tf_error)
8315 	    error_at (loc, "%<delete[]%> is not a constant expression");
8316 	  return false;
8317 	}
8318       /* Fall through.  */
8319     case IF_STMT:
8320     case VEC_COND_EXPR:
8321       /* If the condition is a known constant, we know which of the legs we
8322 	 care about; otherwise we only require that the condition and
8323 	 either of the legs be potentially constant.  */
8324       tmp = TREE_OPERAND (t, 0);
8325       if (!RECUR (tmp, rval))
8326 	return false;
8327       if (!processing_template_decl)
8328 	tmp = cxx_eval_outermost_constant_expr (tmp, true);
8329       if (integer_zerop (tmp))
8330 	return RECUR (TREE_OPERAND (t, 2), want_rval);
8331       else if (TREE_CODE (tmp) == INTEGER_CST)
8332 	return RECUR (TREE_OPERAND (t, 1), want_rval);
8333       tmp = *jump_target;
8334       for (i = 1; i < 3; ++i)
8335 	{
8336 	  tree this_jump_target = tmp;
8337 	  if (potential_constant_expression_1 (TREE_OPERAND (t, i),
8338 					       want_rval, strict, now,
8339 					       tf_none, &this_jump_target))
8340 	    {
8341 	      if (returns (&this_jump_target))
8342 		*jump_target = this_jump_target;
8343 	      else if (!returns (jump_target))
8344 		{
8345 		  if (breaks (&this_jump_target)
8346 		      || continues (&this_jump_target))
8347 		    *jump_target = this_jump_target;
8348 		  if (i == 1)
8349 		    {
8350 		      /* If the then branch is potentially constant, but
8351 			 does not return, check if the else branch
8352 			 couldn't return, break or continue.  */
8353 		      hash_set<tree> pset;
8354 		      check_for_return_continue_data data = { &pset, NULL_TREE,
8355 							      NULL_TREE };
8356 		      if (tree ret_expr
8357 			= cp_walk_tree (&TREE_OPERAND (t, 2),
8358 					check_for_return_continue, &data,
8359 					&pset))
8360 			*jump_target = ret_expr;
8361 		      else if (*jump_target == NULL_TREE)
8362 			{
8363 			  if (data.continue_stmt)
8364 			    *jump_target = data.continue_stmt;
8365 			  else if (data.break_stmt)
8366 			    *jump_target = data.break_stmt;
8367 			}
8368 		    }
8369 		}
8370 	      return true;
8371 	    }
8372 	}
8373       if (flags & tf_error)
8374 	error_at (loc, "expression %qE is not a constant expression", t);
8375       return false;
8376 
8377     case VEC_INIT_EXPR:
8378       if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
8379 	return true;
8380       if (flags & tf_error)
8381 	{
8382 	  error_at (loc, "non-constant array initialization");
8383 	  diagnose_non_constexpr_vec_init (t);
8384 	}
8385       return false;
8386 
8387     case TYPE_DECL:
8388     case TAG_DEFN:
8389       /* We can see these in statement-expressions.  */
8390       return true;
8391 
8392     case CLEANUP_STMT:
8393       if (!RECUR (CLEANUP_BODY (t), any))
8394 	return false;
8395       if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
8396 	return false;
8397       return true;
8398 
8399     case EMPTY_CLASS_EXPR:
8400       return false;
8401 
8402     case GOTO_EXPR:
8403       {
8404 	tree *target = &TREE_OPERAND (t, 0);
8405 	/* Gotos representing break and continue are OK.  */
8406 	if (breaks (target) || continues (target))
8407 	  {
8408 	    *jump_target = *target;
8409 	    return true;
8410 	  }
8411 	if (flags & tf_error)
8412 	  error_at (loc, "%<goto%> is not a constant expression");
8413 	return false;
8414       }
8415 
8416     case ANNOTATE_EXPR:
8417       return RECUR (TREE_OPERAND (t, 0), rval);
8418 
8419     /* Coroutine await, yield and return expressions are not.  */
8420     case CO_AWAIT_EXPR:
8421     case CO_YIELD_EXPR:
8422     case CO_RETURN_EXPR:
8423       return false;
8424 
8425     default:
8426       if (objc_non_constant_expr_p (t))
8427 	return false;
8428 
8429       sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
8430       gcc_unreachable ();
8431       return false;
8432     }
8433 #undef RECUR
8434 }
8435 
8436 bool
potential_constant_expression_1(tree t,bool want_rval,bool strict,bool now,tsubst_flags_t flags)8437 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
8438 				 tsubst_flags_t flags)
8439 {
8440   tree target = NULL_TREE;
8441   return potential_constant_expression_1 (t, want_rval, strict, now,
8442 					  flags, &target);
8443 }
8444 
8445 /* The main entry point to the above.  */
8446 
8447 bool
potential_constant_expression(tree t)8448 potential_constant_expression (tree t)
8449 {
8450   return potential_constant_expression_1 (t, false, true, false, tf_none);
8451 }
8452 
8453 /* As above, but require a constant rvalue.  */
8454 
8455 bool
potential_rvalue_constant_expression(tree t)8456 potential_rvalue_constant_expression (tree t)
8457 {
8458   return potential_constant_expression_1 (t, true, true, false, tf_none);
8459 }
8460 
8461 /* Like above, but complain about non-constant expressions.  */
8462 
8463 bool
require_potential_constant_expression(tree t)8464 require_potential_constant_expression (tree t)
8465 {
8466   return potential_constant_expression_1 (t, false, true, false,
8467 					  tf_warning_or_error);
8468 }
8469 
8470 /* Cross product of the above.  */
8471 
8472 bool
require_potential_rvalue_constant_expression(tree t)8473 require_potential_rvalue_constant_expression (tree t)
8474 {
8475   return potential_constant_expression_1 (t, true, true, false,
8476 					  tf_warning_or_error);
8477 }
8478 
8479 /* Like above, but don't consider PARM_DECL a potential_constant_expression.  */
8480 
8481 bool
require_rvalue_constant_expression(tree t)8482 require_rvalue_constant_expression (tree t)
8483 {
8484   return potential_constant_expression_1 (t, true, true, true,
8485 					  tf_warning_or_error);
8486 }
8487 
8488 /* Like potential_constant_expression, but don't consider possible constexpr
8489    substitution of the current function.  That is, PARM_DECL qualifies under
8490    potential_constant_expression, but not here.
8491 
8492    This is basically what you can check when any actual constant values might
8493    be value-dependent.  */
8494 
8495 bool
is_constant_expression(tree t)8496 is_constant_expression (tree t)
8497 {
8498   return potential_constant_expression_1 (t, false, true, true, tf_none);
8499 }
8500 
8501 /* Like above, but complain about non-constant expressions.  */
8502 
8503 bool
require_constant_expression(tree t)8504 require_constant_expression (tree t)
8505 {
8506   return potential_constant_expression_1 (t, false, true, true,
8507 					  tf_warning_or_error);
8508 }
8509 
8510 /* Like is_constant_expression, but allow const variables that are not allowed
8511    under constexpr rules.  */
8512 
8513 bool
is_static_init_expression(tree t)8514 is_static_init_expression (tree t)
8515 {
8516   return potential_constant_expression_1 (t, false, false, true, tf_none);
8517 }
8518 
8519 /* Returns true if T is a potential constant expression that is not
8520    instantiation-dependent, and therefore a candidate for constant folding even
8521    in a template.  */
8522 
8523 bool
is_nondependent_constant_expression(tree t)8524 is_nondependent_constant_expression (tree t)
8525 {
8526   return (!type_unknown_p (t)
8527 	  && is_constant_expression (t)
8528 	  && !instantiation_dependent_expression_p (t));
8529 }
8530 
8531 /* Returns true if T is a potential static initializer expression that is not
8532    instantiation-dependent.  */
8533 
8534 bool
is_nondependent_static_init_expression(tree t)8535 is_nondependent_static_init_expression (tree t)
8536 {
8537   return (!type_unknown_p (t)
8538 	  && is_static_init_expression (t)
8539 	  && !instantiation_dependent_expression_p (t));
8540 }
8541 
8542 /* Finalize constexpr processing after parsing.  */
8543 
8544 void
fini_constexpr(void)8545 fini_constexpr (void)
8546 {
8547   /* The contexpr call and fundef copies tables are no longer needed.  */
8548   constexpr_call_table = NULL;
8549   fundef_copies_table = NULL;
8550 }
8551 
8552 #include "gt-cp-constexpr.h"
8553